From 91ef80b6e0eb8643db8c39ef931f3e74bfb72409 Mon Sep 17 00:00:00 2001 From: Chojan Shang Date: Tue, 3 Nov 2026 11:21:20 +0800 Subject: [PATCH 01/11] feat(inference): reuse Codex and Copilot subscriptions --- docs/en/development/pydantic-ai-inference.md | 138 ++++----- docs/en/docs/operate/observability.md | 284 ++++-------------- docs/zh/development/pydantic-ai-inference.md | 129 ++++---- docs/zh/docs/operate/observability.md | 242 +++------------ e2e/bub/uv.lock | 18 +- evaluation/memory/locomo/runner.py | 4 +- evaluation/uv.lock | 41 +-- .../powercontext_pydantic_ai/capability.py | 3 + pyproject.toml | 4 +- .../builtin/artifacts/memory/jev_reranking.py | 22 +- src/powercontext/builtin/inference/minimax.py | 14 +- .../builtin/inference/protected_transport.py | 24 +- .../builtin/inference/pydantic_ai.py | 28 +- .../builtin/runtime/composition.py | 29 +- .../artifacts/memory/test_jev_reranking.py | 38 +-- .../inference/test_minimax_embedding.py | 72 ++--- tests/builtin/inference/test_privacy.py | 87 +++--- tests/builtin/inference/test_pydantic_ai.py | 36 ++- .../runtime/test_composition_embedding.py | 18 +- .../runtime/test_topic_memory_work_budget.py | 11 +- tests/e2e/rfc2086_real_acceptance.py | 10 +- ...test_atomic_memory_reconciliation_retry.py | 8 +- .../test_atomic_memory_related_embedding.py | 16 +- .../e2e/test_inference_observation_retries.py | 4 +- tests/e2e/test_jev_memory_reranking.py | 7 +- tests/e2e/test_responses_output_privacy.py | 10 +- .../e2e/test_rfc2086_transport_acceptance.py | 6 +- .../evaluation/test_jev_rerank_comparison.py | 23 +- .../openai_sdk/test_openai_sdk_example.py | 13 +- tests/pydantic_ai_adapter/test_toolset.py | 11 +- tests/test_inference_endpoints.py | 5 +- tests/test_locomo_plus_runner.py | 6 +- tests/test_server.py | 9 +- tests/test_server_tracing.py | 8 +- uv.lock | 119 +++++--- 35 files changed, 614 insertions(+), 883 deletions(-) diff --git a/docs/en/development/pydantic-ai-inference.md b/docs/en/development/pydantic-ai-inference.md index 15069f29ae..961915ace9 100644 --- a/docs/en/development/pydantic-ai-inference.md +++ b/docs/en/development/pydantic-ai-inference.md @@ -1,49 +1,43 @@ # Configure Pydantic AI inference -PowerContext uses Pydantic AI at the provider boundary while keeping Memory services framework-neutral. Generation -extracts structured Memory candidates. Embedding supplies vectors for indexes that support vector search. Either -capability can be configured independently. +PowerContext uses a generation model to extract Memory from Sources and an embedding model to generate vectors for indexes that support vector search. You can configure each capability independently. -## Install the integration +## Install dependencies -The inference integration is part of the built-in implementation: +Install the `builtin` extra to use inference in a Python project: ```bash uv add "powercontext[builtin]" ``` -The Server extra includes Builtin: +To run the Server, install the `server` extra, which includes the same dependencies: ```bash uv add "powercontext[server]" ``` +Both extras install Pydantic AI 2.64 or a newer 2.x version. + ## Configure the Server -The standard Server builds inference adapters from `ServerSettings.inference`. A generation model enables -Source-to-Memory extraction: +Set the following environment variable to choose the Server's generation model for extracting Memory from Sources: ```bash export POWERCONTEXT_SERVER_INFERENCE_GENERATION_MODEL="provider:model-name" ``` -Additional Pydantic AI model settings can be supplied as JSON. Provider-specific request fields belong under -`extra_body`; for example, a compatible OpenAI-style endpoint can disable Qwen thinking with: +Supply additional model settings as JSON. Put service-specific request fields under `extra_body`. For example, an OpenAI-compatible service can disable Qwen thinking with: ```bash export POWERCONTEXT_SERVER_INFERENCE_GENERATION_MODEL="openai-chat:" export POWERCONTEXT_SERVER_INFERENCE_GENERATION_MODEL_SETTINGS='{"extra_body":{"chat_template_kwargs":{"enable_thinking":false}}}' ``` -Topic Memory also accepts this exact `extra_body` shape for `openai-chat:`. The value must be the JSON boolean -`false`; additional keys at either level, other provider prefixes, and Embedding `extra_body` remain unsupported. -Use an endpoint that implements `chat_template_kwargs.enable_thinking`; this flag does not guarantee a timeout-free run. +For Topic Memory, only `openai-chat:` accepts the `extra_body` structure shown above. The value must be the JSON boolean `false`, and neither object may contain additional fields. Other provider prefixes and embedding models do not support this setting. The service must implement `chat_template_kwargs.enable_thinking`; requests can still time out with thinking disabled. -These settings are shared by the generation-backed pipelines, the optional LLM reranker, and the readiness probe. -PowerContext retains its own request bounds: readiness uses `max_tokens=1`, and reranking uses `temperature=0`. -Keep credentials and static headers in provider configuration rather than model settings. +Generation, optional LLM reranking, and readiness checks share these settings. Readiness checks can call the model and consume quota. Available settings depend on the selected service and model. Use the dedicated configuration fields for credentials and static headers instead of putting them in model settings. -Vector search needs the embedding model and its complete deployment profile: +To enable vector search, set the embedding model, profile ID, and vector dimension together: ```bash export POWERCONTEXT_SERVER_INFERENCE_EMBEDDING_MODEL="provider:embedding-model" @@ -51,11 +45,7 @@ export POWERCONTEXT_SERVER_INFERENCE_EMBEDDING_PROFILE_ID="project-embedding-v1" export POWERCONTEXT_SERVER_INFERENCE_EMBEDDING_DIMENSION="1536" ``` -Each workload can target a different model service. Custom base URLs use the provider interface named by the model -identifier; use `openai-chat:` for an OpenAI-compatible Chat Completions service, `openai:` for an -OpenAI-compatible Responses or embeddings service, and `anthropic:` for an Anthropic-compatible generation -service. The built-in reranker is an LLM listwise reranker, so its independent endpoint is also a Pydantic AI generation -endpoint rather than a cross-encoder `/rerank` API: +Generation, embedding, and reranking can each use a different model service. Choose the model prefix for the service's interface: `openai-chat:` for OpenAI Chat Completions, `openai:` for OpenAI Responses or embeddings, and `anthropic:` for an Anthropic-compatible interface. Built-in reranking uses a language model to rank a list of candidates, so configure a generation endpoint. Cross-encoder `/rerank` endpoints are unsupported: ```bash export POWERCONTEXT_SERVER_INFERENCE_GENERATION_MODEL="openai-chat:generator" @@ -74,37 +64,60 @@ export POWERCONTEXT_SERVER_INFERENCE_RERANK_HEADERS='{"Authorization":"Bearer re export POWERCONTEXT_SERVER_INFERENCE_RERANK_MODEL_SETTINGS='{"max_tokens":256}' ``` -The header and model-settings values are JSON objects. Header values are treated as secrets by settings models and are -installed as static headers on the workload's provider client. They are not included in Pydantic AI request settings. -Do not put `extra_headers` inside a model-settings object; use the dedicated headers variable so configuration and log -redaction remain effective. Pydantic AI passes the remaining model settings through to the selected provider. The -reranker always fixes `temperature` to zero. A custom embedding base URL currently requires the OpenAI-compatible -embeddings interface. +Header and model settings are JSON objects. Values in `*_HEADERS` are treated as secrets and sent as static headers for the corresponding task. Model settings reject `extra_headers`; use the dedicated header configuration so configuration displays and logs can redact those values. Other model settings pass through to the selected service. Reranking does not support a custom sampling temperature. Custom embedding services must provide the OpenAI-compatible embeddings interface, except for supported MiniMax-native embedding endpoints. + +A base URL can include a gateway path prefix. The service's interface path, such as `/chat/completions`, `/responses`, or `/embeddings`, is appended automatically and cannot be replaced with an arbitrary path. When configuring a custom URL or static headers, use an explicit OpenAI- or Anthropic-compatible model prefix. + +When `RERANK_MODEL` is unset, LLM reranking uses the generation model and URL. Reranker headers and model settings can extend or override the generation configuration. Header overrides apply only to reranking and leave the selected model and URL unchanged. If you set a separate reranker URL, also specify a reranker model. The reranker uses the generation timeout and request limit unless you override them. + +When using the default URL and headers, supply credentials through the environment variables supported by the selected service. See below for reusing subscription credentials. + +Set `embedding_model`, `embedding_profile_id`, and `embedding_dimension` together; the Server rejects a configuration with any of them missing. SQLite vector search uses these settings because the index dimension must match the stored vectors. For OpenAI-compatible embeddings, `embedding_dimension` is sent as the `dimensions` request field by default and overrides that field in model settings. If a model has a fixed output dimension and rejects the field, set `POWERCONTEXT_SERVER_INFERENCE_EMBEDDING_SEND_DIMENSIONS` to `false`. The local dimension remains required, and the Server still validates returned vectors against it. + +## Reuse existing subscription credentials + +Make existing Codex or GitHub Copilot credentials available to the Server and its workers. Credential file paths refer to the Server host and the user running the service. A login on the client machine is not transferred to the Server automatically. -A base URL may contain a gateway path prefix. The selected Pydantic AI provider still owns the operation suffix, such -as `/chat/completions`, `/responses`, or `/embeddings`; arbitrary operation-path rewriting is not supported. -Custom base URLs and static headers require an explicit OpenAI- or Anthropic-compatible model identifier so -PowerContext can construct the corresponding provider client. +The Codex and Copilot examples below use the default service URL and authentication. Leave `POWERCONTEXT_SERVER_INFERENCE_GENERATION_BASE_URL` and `POWERCONTEXT_SERVER_INFERENCE_GENERATION_HEADERS` unset. Replace `` with a model ID available to that subscription. -When `RERANK_MODEL` is unset, LLM reranking reuses the generation model and base URL. Reranker headers and model -settings can still extend or override the generation configuration. A header override creates a separate provider -client for the rerank workload while retaining the generation model identifier and base URL. A separate reranker base -URL requires an explicit reranker model. The reranker timeout and request limit inherit their generation counterparts -unless they are set explicitly. +### Codex CLI credentials -When no custom base URL or headers are needed, provider credentials remain in the environment variables understood by -the selected Pydantic AI provider. +If Codex CLI is signed in with a subscription account and stores its credentials in `auth.json`, use the `openai-codex:` model prefix: -The Server rejects a partial embedding profile. `embedding_model`, `embedding_profile_id`, and `embedding_dimension` -must be configured together. SQLite vector search uses that embedding configuration because the index dimension and -stored vectors must agree. `embedding_dimension` is also sent as the `dimensions` request field by default, and it -overrides a `dimensions` value in model settings. For a fixed-dimension model that rejects the field, set -`POWERCONTEXT_SERVER_INFERENCE_EMBEDDING_SEND_DIMENSIONS` to `false`. The local dimension stays required, and returned -vectors are still validated against it. +```bash +export POWERCONTEXT_SERVER_INFERENCE_GENERATION_MODEL="openai-codex:" +``` + +By default, the Server reads `~/.codex/auth.json` in the home directory of the user running the service. If the credentials are in another Codex home directory, specify that directory in the environment: + +```bash +export CODEX_HOME="/path/to/existing/codex-home" +``` -## Compose generation directly +`CODEX_HOME` names the directory containing `auth.json`. The service does not update the CLI login file. If authentication fails, update the login with the original CLI, then restart the service. See [Pydantic AI's Codex credential configuration](https://github.com/pydantic/pydantic-ai/blob/v2.64.0/docs/models/openai-codex.md). -Use direct composition when the application already owns provider model lifecycles: +### GitHub Copilot credentials + +If GitHub CLI has an OAuth login for an account with Copilot access, export its token before starting the Server: + +```bash +export GITHUB_COPILOT_API_KEY="$(gh auth token)" +export POWERCONTEXT_SERVER_INFERENCE_GENERATION_MODEL="github-copilot:" +``` + +You can also reuse an existing `GITHUB_COPILOT_API_TOKEN` or `COPILOT_GITHUB_TOKEN` environment variable; the Server reads them in that order as fallbacks. The general-purpose `GITHUB_TOKEN` and `GH_TOKEN` variables are not used for Copilot authentication. Run the example's `gh auth token` command before starting the service. The Server does not load CLI configuration or renew tokens automatically. When the token changes, update the service's environment and restart the Server. See [Pydantic AI's Copilot configuration](https://github.com/pydantic/pydantic-ai/blob/v2.64.0/docs/models/github-copilot.md). + +These configurations support generation for Memory, Experience, and Profile. Topic Memory and Dream are unavailable with Codex and Copilot. If you have explicitly enabled Topic Memory processing or its automatic schedule, remove that configuration before switching providers. Enabling built-in inference protection prevents startup with these providers. + +### Existing ChatGPT Plan Usage credentials + +You can reuse an existing ChatGPT Plan Usage authorization through the SDK. The Server does not support loading these credentials through environment variables, so configuring a model name alone does not enable the service. + +Use your application's configured Pydantic AI model in the SDK example below. The model needs a ChatGPT Plan Usage authorization; Codex CLI credentials cannot replace it. See [Pydantic AI's existing credential configuration](https://github.com/pydantic/pydantic-ai/blob/v2.64.0/docs/models/openai-chatgpt.md#persisting-credentials). + +## Use a generation model through the SDK + +If your application already has a configured Pydantic AI model, pass it to a structured generator and create a Memory extraction pipeline: ```python from powercontext.builtin.artifacts.memory import ( @@ -128,20 +141,13 @@ generator = PydanticAIStructuredGenerator( candidate_pipeline = LLMMemoryCandidatePipeline(generator) ``` -`generation_model` must be an initialized Pydantic AI `Model`, not a provider name string. The application that opens -the model also closes it. +Pass an initialized Pydantic AI `Model` object as `generation_model`; model name strings are not accepted. Your application opens and closes that object. -The generator serializes Pydantic input models and validates structured output against the declared output type. -Memory validation still runs after generation, so a schema-valid candidate is not automatically accepted for -persistence. +The generator serializes data using the declared input type and validates the result against the output type. After schema validation, the output must also satisfy Memory's write rules before it can be saved. -Pass `output_check` for a rule that relates the output to its input and cannot be expressed in the output schema. The -callable receives the input and the validated output and raises `InvalidInferenceOutputError` when the output breaks -the rule. Its detail is returned to the model as retry feedback, and the retry shares the `max_requests` budget with -schema errors. When the budget is spent, `generate()` raises that last `InvalidInferenceOutputError`. Because the -detail is sent to the provider, name the rule and never include input content in it. +Pass `output_check` to enforce a rule between input and output that the output schema cannot express. The callback receives the input and validated output and raises `InvalidInferenceOutputError` when the output breaks the rule. The error's `detail` goes to the model as retry feedback, sharing the `max_requests` budget with schema validation failures. When that budget runs out, `generate()` raises the last `InvalidInferenceOutputError`. Describe only the rule in `detail`; do not include input content. -## Compose embeddings directly +## Use an embedding model through the SDK ```python from pydantic_ai import Embedder @@ -164,18 +170,14 @@ embedding_model = PydanticAIEmbeddingModel( ) ``` -Pass this adapter to `open_builtin_contexts()` or `open_builtin_runtime()` with a `SQLiteConfig`. The bundled -sqlite-vec index is enabled automatically. The adapter verifies output count, order, dimension, and finite numeric -values, then applies the declared unit normalization before vectors reach persistence. +Pass `embedding_model` to `open_builtin_contexts()` or `open_builtin_runtime()` with a `SQLiteConfig` to enable the sqlite-vec vector index. Before saving vectors, PowerContext checks their count, order, dimension, and numeric validity, then applies unit normalization as configured. + +When supplying an HTTP client for MiniMax embeddings or Jev reranking through the SDK, use an `httpx2.AsyncClient`. -An `EmbeddingProfile` is a deployment contract, not descriptive metadata. Stored projections and query embeddings -must use the same profile. When the model, dimension, or normalization changes, rebuild Memory projections from the -authoritative revisions. +Stored vectors and query vectors must use the same `EmbeddingProfile`. If you change the model, dimension, or normalization, rebuild the vector projections from authoritative Memory revisions. ## Failure behavior -Generation and embedding failures map provider errors into PowerContext inference errors. Timeouts and temporary -provider failures do not commit partial Memory revisions. +When generation or embedding calls fail, PowerContext returns the corresponding inference error. Timeouts and temporary service failures do not commit partial Memory revisions. -For `mode="auto"` search, a temporary query embedding failure can fall back to FTS when the backend supports it. -Explicit vector or hybrid search reports the missing capability instead of silently changing modes. +With `mode="auto"` search, a temporary query embedding failure can fall back to FTS if the backend supports it. If you explicitly request vector or hybrid search, the system reports the missing capability without changing the search mode. diff --git a/docs/en/docs/operate/observability.md b/docs/en/docs/operate/observability.md index b30f4564de..e786901fe6 100644 --- a/docs/en/docs/operate/observability.md +++ b/docs/en/docs/operate/observability.md @@ -5,15 +5,11 @@ description: Locate requests in logs and inspect Server metrics and traces. # Logs, metrics, and tracing -Use logs to locate an operation, metrics to observe aggregate behavior, and traces to follow a request across stages. -These signals describe service behavior; they do not replace inspection of stored Memory or Source evidence. +Use logs to locate an operation, metrics to observe aggregate behavior, and traces to follow a request across stages. These signals describe service behavior; they do not replace inspection of stored Memory or Source evidence. ## Logs -The foreground Server writes operational logs to its process output. Configure -`POWERCONTEXT_SERVER_LOGGING_LEVEL` (default `INFO`), `POWERCONTEXT_SERVER_LOGGING_FORMAT` (`console` or `json`), -and `POWERCONTEXT_SERVER_LOGGING_ACCESS` (default `true`). For a native personal service, run -`powercontext service status` to find the journal selector or log paths. Docker users can inspect container logs. +The foreground Server writes operational logs to its process output. Configure `POWERCONTEXT_SERVER_LOGGING_LEVEL` (default `INFO`), `POWERCONTEXT_SERVER_LOGGING_FORMAT` (`console` or `json`), and `POWERCONTEXT_SERVER_LOGGING_ACCESS` (default `true`). For a native personal service, run `powercontext service status` to find the journal selector or log paths. Docker users can inspect container logs. ### File output, rotation, and compression @@ -43,17 +39,13 @@ macOS and Windows personal services enable managed file output by default. An ex An unavailable directory or an existing writer prevents file logging configuration. Once running, formatting, transport, queue, write, and compression failures use the same content-free `observability.log_failed` notification as stream failures. Completed gzip archives are published before the original file is removed. SDK Runtime use does not configure logging; embedding applications retain ownership. An embedded Server with file output can own a worker-only sink without reconfiguring the embedding application's loggers. -Use the response's `X-PowerContext-Request-ID` to correlate a failed request with diagnostics. The host guides also -explain content-free recall and capture diagnostics; a missing context result can be valid rather than an outage. +Use the response's `X-PowerContext-Request-ID` to correlate a failed request with diagnostics. The host guides also explain content-free recall and capture diagnostics; a missing context result can be valid rather than an outage. ### Operational fields and correlation -For event examples, field extension, and regression checks, see the -[developer guide](../../development/observability.md). +For event examples, field extension, and regression checks, see the [developer guide](../../development/observability.md). -JSON and console logs use the same explicit operational field allowlist. Unrecognized extras are not serialized. -Both formats retain application/transport outcomes and error diagnostics, plus worker correlation on nested events, -including code stages. Code-specific diagnostic fields are included only for `code.*` events. +JSON and console logs use the same explicit operational field allowlist. Unrecognized extras are not serialized. Both formats retain application/transport outcomes and error diagnostics, plus worker correlation on nested events, including code stages. Code-specific diagnostic fields are included only for `code.*` events. | Fields | Meaning | | --- | --- | @@ -65,88 +57,29 @@ including code stages. Code-specific diagnostic fields are included only for `co | `duration_ms`, `error_code`, `error_category` | Duration in milliseconds, diagnostic code, and bounded operational error classification | | `stage`, `processing_stage`, `failure_reason`, `input_item_count`, `estimated_input_tokens`, `token_estimator_id`, `effective_budget`, `provider_request_id`, `finish_reason`, `failure_location`, `cause_exception_type` | Processing failure stage/reason and safe accounting fields; `stage` names the emitting boundary or domain location (Worker/supervisor stage, domain block name, or `worker` fallback), `processing_stage` the bounded domain stage. See [Processing failure diagnostics](../../development/processing-failures.md) | -Server roles are `all` (API and supervisor), `api`, and `background`; child processes use `worker`. Explicit logging -configuration without a deployment role uses `server`. JSON identity fields correspond to trace resource attributes -`service.name`, `service.version`, `service.instance.id`, and `powercontext.service.role`. `service_version` is absent -when installed distribution metadata is unavailable, such as a source checkout or a frozen bundle. A new process -receives a new instance ID; a worker retry receives a new `worker_id`. None of these execution identifiers are metric -labels. - -The request ID is inherited by nested request logs unless an event provides an explicit ID. Scheduled processing does -not acquire the request ID that happened to be active when the supervisor started, including supervisor control logs. -Trace IDs still exist with recording disabled, but do not imply that a backend has stored the trace. -Child logging alone does not establish cross-process trace propagation. - -Common outcomes are `success`, `failure`, `cancelled`, and `noop`; admission blocks use `blocked` rather than success or failure. -If a worker encounters a durable processing block, `artifact_processing.worker.blocked` is emitted at `WARNING` -with outcome and error category `blocked`, preserving the block's diagnostic code and stage. -Topic block `source_after` and known `source_through` are Source journal positions. When the exact selected end is -unknown, block logs omit `source_through`; attempt/request/token counters remain available. -Worker control results can also be `cursor_conflict`, -`head_conflict`, or `leadership_lost`. A `artifact_processing.worker.returned` event describes the child's result; -`artifact_processing.worker.acknowledged` indicates that the supervisor verified durable acknowledgement. A child -return does not by itself prove business completion. Forced process termination can prevent a child terminal event; -the supervisor records interruption or failure instead. - -`error_category` is absent when not applicable. Its vocabulary is `authentication`, `authorization`, `configuration`, -`rate_limit`, `dependency`, `timeout`, `not_found`, `conflict`, `invalid_request`, `internal`, `cancelled`, and `blocked`. -Server spans use the same vocabulary in `powercontext.error.category`; each boundary classifies its own observed result. -Existing diagnostic codes remain available for more specific investigation. -Supervisor worker and wait spans preserve the child's bounded failure category across the process boundary. -Policy blocks and child cancellation use `blocked` and `cancelled` outcomes without an error span status; -inference failures retain their timeout, configuration, or dependency classification. -With streamed generation aggregation enabled (`POWERCONTEXT_SERVER_INFERENCE_GENERATION_STREAMING=auto`), -an `inference.generation.usage_missing` WARNING with `unit` `inference` reports one generation request that -completed successfully while the provider did not return usage with the stream; usage statistics for that -request will be missing. The event carries no prompt or response content and does not affect the request result. -When `auto` is set and the model provider prefix is outside `anthropic`, `openai`, `openai-chat`, and -`openai-responses`, an `inference.generation.streaming_not_applied` WARNING with `unit` `inference` reports that -the model stayed on a non-streaming request. The event carries no prompt or response content and does not change -the request result. -For child cancellation, the supervisor emits `artifact_processing.failed` at `INFO` with outcome/category `cancelled` -and diagnostic code `worker_cancelled`. Application spans classify mapped diagnostic codes even when sensitive -exception values are excluded from logs and traces. - -At `DEBUG`, `code.*` events retain `seconds` and add `duration_ms`. Their `operation` is the stage name (`code.`), -matching the span identity; an existing requested query kind moves to `code_operation`. Code diagnostics can include `selected_count`, -`hit_count`, `hit_count_is_lower_bound`, `cache_bytes`, `status`, `limitations`, and `reason`. Where supported by the OS, -`process_lifetime_max_rss_bytes` and `children_lifetime_max_rss_bytes` are process-lifetime high-water marks in bytes; -they are not per-request allocations or simultaneous process-tree totals, and must not be added together. -Failed code stages retain the diagnostic `error_code` and, for domain errors, `status_code`; logs and spans use these -values to distinguish timeouts, conflicts, and invalid requests from internal failures. - -Server-created workers use the configured log level and format. Importing or running the Runtime as an SDK does not -configure global logging; an embedding application owns its logging configuration. Logging bootstrap failure does not -fail processing. The Server handler emits at most one content-free `observability.log_failed` notification to stderr -per handler if formatting or writing fails; it does not dump the failed record. Operational logs remain best-effort, -not a durable audit or billing ledger. The identity/error fields are additive; console lines now include identity. +Server roles are `all` (API and supervisor), `api`, and `background`; child processes use `worker`. Explicit logging configuration without a deployment role uses `server`. JSON identity fields correspond to trace resource attributes `service.name`, `service.version`, `service.instance.id`, and `powercontext.service.role`. `service_version` is absent when installed distribution metadata is unavailable, such as a source checkout or a frozen bundle. A new process receives a new instance ID; a worker retry receives a new `worker_id`. None of these execution identifiers are metric labels. + +The request ID is inherited by nested request logs unless an event provides an explicit ID. Scheduled processing does not acquire the request ID that happened to be active when the supervisor started, including supervisor control logs. Trace IDs still exist with recording disabled, but do not imply that a backend has stored the trace. Child logging alone does not establish cross-process trace propagation. + +Common outcomes are `success`, `failure`, `cancelled`, and `noop`; admission blocks use `blocked` rather than success or failure. If a worker encounters a durable processing block, `artifact_processing.worker.blocked` is emitted at `WARNING` with outcome and error category `blocked`, preserving the block's diagnostic code and stage. Topic block `source_after` and known `source_through` are Source journal positions. When the exact selected end is unknown, block logs omit `source_through`; attempt/request/token counters remain available. Worker control results can also be `cursor_conflict`, `head_conflict`, or `leadership_lost`. A `artifact_processing.worker.returned` event describes the child's result; `artifact_processing.worker.acknowledged` indicates that the supervisor verified durable acknowledgement. A child return does not by itself prove business completion. Forced process termination can prevent a child terminal event; the supervisor records interruption or failure instead. + +`error_category` is absent when not applicable. Its vocabulary is `authentication`, `authorization`, `configuration`, `rate_limit`, `dependency`, `timeout`, `not_found`, `conflict`, `invalid_request`, `internal`, `cancelled`, and `blocked`. Server spans use the same vocabulary in `powercontext.error.category`; each boundary classifies its own observed result. Existing diagnostic codes remain available for more specific investigation. Supervisor worker and wait spans preserve the child's bounded failure category across the process boundary. Policy blocks and child cancellation use `blocked` and `cancelled` outcomes without an error span status; inference failures retain their timeout, configuration, or dependency classification. With streamed generation aggregation enabled (`POWERCONTEXT_SERVER_INFERENCE_GENERATION_STREAMING=auto`), an `inference.generation.usage_missing` WARNING with `unit` `inference` reports one generation request that completed successfully while the provider did not return usage with the stream; usage statistics for that request will be missing. The event carries no prompt or response content and does not affect the request result. When `auto` is set and the model provider prefix is outside `anthropic`, `openai`, `openai-chat`, and `openai-responses`, an `inference.generation.streaming_not_applied` WARNING with `unit` `inference` reports that the model stayed on a non-streaming request. The event carries no prompt or response content and does not change the request result. For child cancellation, the supervisor emits `artifact_processing.failed` at `INFO` with outcome/category `cancelled` and diagnostic code `worker_cancelled`. Application spans classify mapped diagnostic codes even when sensitive exception values are excluded from logs and traces. + +At `DEBUG`, `code.*` events retain `seconds` and add `duration_ms`. Their `operation` is the stage name (`code.`), matching the span identity; an existing requested query kind moves to `code_operation`. Code diagnostics can include `selected_count`, `hit_count`, `hit_count_is_lower_bound`, `cache_bytes`, `status`, `limitations`, and `reason`. Where supported by the OS, `process_lifetime_max_rss_bytes` and `children_lifetime_max_rss_bytes` are process-lifetime high-water marks in bytes; they are not per-request allocations or simultaneous process-tree totals, and must not be added together. Failed code stages retain the diagnostic `error_code` and, for domain errors, `status_code`; logs and spans use these values to distinguish timeouts, conflicts, and invalid requests from internal failures. + +Server-created workers use the configured log level and format. Importing or running the Runtime as an SDK does not configure global logging; an embedding application owns its logging configuration. Logging bootstrap failure does not fail processing. The Server handler emits at most one content-free `observability.log_failed` notification to stderr per handler if formatting or writing fails; it does not dump the failed record. Operational logs remain best-effort, not a durable audit or billing ledger. The identity/error fields are additive; console lines now include identity. ## Metrics and readiness -Metrics are enabled by default at `/metrics` in Prometheus format. In `enforced` mode, `/metrics` and `capabilities` -require authentication as a Principal with `server.observe`. See [Troubleshoot](troubleshoot.md). -On API hosts, `/health/live` and `/health/ready` remain public. +Metrics are enabled by default at `/metrics` in Prometheus format. In `enforced` mode, `/metrics` and `capabilities` require authentication as a Principal with `server.observe`. See [Troubleshoot](troubleshoot.md). On API hosts, `/health/live` and `/health/ready` remain public. -The `background` role exposes `/metrics` and public `/health/live` using `POWERCONTEXT_SERVER_HTTP_HOST` and -`POWERCONTEXT_SERVER_METRICS_BACKGROUND_PORT` (default `8001`). It has the same metrics authentication and authorization -as the API host, but no business APIs, MCP, Dashboard, OpenAPI, or `/health/ready`. -Give API and background processes different ports when sharing a host. -`POWERCONTEXT_SERVER_METRICS_ENABLED=false` removes `/metrics`; for `background` it also prevents opening the listener. -Scraping this listener does not run API-host model readiness probes. +The `background` role exposes `/metrics` and public `/health/live` using `POWERCONTEXT_SERVER_HTTP_HOST` and `POWERCONTEXT_SERVER_METRICS_BACKGROUND_PORT` (default `8001`). It has the same metrics authentication and authorization as the API host, but no business APIs, MCP, Dashboard, OpenAPI, or `/health/ready`. Give API and background processes different ports when sharing a host. `POWERCONTEXT_SERVER_METRICS_ENABLED=false` removes `/metrics`; for `background` it also prevents opening the listener. Scraping this listener does not run API-host model readiness probes. ### Passive observations and freshness -Metrics collection copies existing, bounded, process-local Runtime/Supervisor observations. Collection does not query -the database, scan backlog, refresh readiness, invoke a model, or wait for a worker. Endpoint authentication and -authorization may still perform bounded database reads. Background pending observation, discovery, and readiness -owners produce the observations independently of scraping. A successful scrape therefore proves neither current -dependency health nor fresh backlog data; scraping never invokes a model. +Metrics collection copies existing, bounded, process-local Runtime/Supervisor observations. Collection does not query the database, scan backlog, refresh readiness, invoke a model, or wait for a worker. Endpoint authentication and authorization may still perform bounded database reads. Background pending observation, discovery, and readiness owners produce the observations independently of scraping. A successful scrape therefore proves neither current dependency health nor fresh backlog data; scraping never invokes a model. -All metric names below start with `powercontext_server_`. Timestamps are UNIX seconds; durations and ages are seconds; -counts count the named unit. State metrics are one-hot: the matching `state` is `1`, the other supported states are `0`. -Absent observations are not healthy zeroes. Counters and histogram buckets are cumulative for the owning process or -Runtime/Supervisor instance and reset when that owner is recreated; scrapes do not reset them. Use counter-aware -`rate`/`increase` functions and preserve scrape target labels such as `instance` and deployment identity. +All metric names below start with `powercontext_server_`. Timestamps are UNIX seconds; durations and ages are seconds; counts count the named unit. State metrics are one-hot: the matching `state` is `1`, the other supported states are `0`. Absent observations are not healthy zeroes. Counters and histogram buckets are cumulative for the owning process or Runtime/Supervisor instance and reset when that owner is recreated; scrapes do not reset them. Use counter-aware `rate`/`increase` functions and preserve scrape target labels such as `instance` and deployment identity. | Metric suffix | Labels and meaning | | --- | --- | @@ -165,30 +98,13 @@ Runtime/Supervisor instance and reset when that owner is recreated; scrapes do n | `telemetry_collection_failures_total` | Failed passive collection attempts; the previous observation is retained | | `telemetry_log_records_dropped_total` | Observed records that the process-owned handler or Worker receiver failed to deliver; clean EOF/reset is not a loss, and unobserved losses are not counted | -Detailed probe observations cover `database`, `inference.generation`, `inference.rerank`, `inference.decision`, and -`inference.embedding`. The same `dependency_state` family also includes bounded aggregate checks for `runtime`, -`artifact_processing_supervisor`, registered `artifact_processing.` values, `access_provider`, and -`authentication_provider`. Detailed Runtime snapshots take precedence over aggregate state for the same dependency; -each dependency has only one one-hot state set. Probe timestamps and durations remain actual-probe observations, -not aggregate evaluation times. Disabled dependencies have no probe timestamps or samples. Probe outcomes are `ready`, -`unavailable`, `timeout`, `misconfigured`, or `cancelled`; cancellation contributes duration but does not replace the -last completed state/timestamp. A cache hit updates neither actual probe timestamps nor histogram counts. One sample is one complete probe refresh; -provider-internal retries, if any, remain inside that duration and are not counted as separate network attempts. -Built-in cached probes normally retain results for 300 seconds, or 30 seconds for `timeout`/`unavailable`; cache expiry -alone does not run a probe. The aggregate evaluation timestamp, probe timestamps, collection timestamp, and Prometheus -scrape timestamp answer different freshness questions. - -`runtime_ready=1` may coexist with `degraded`: it means operations can be admitted, not that all models are available. -Use `runtime_readiness_state` with dependency states and freshness, or request `powercontext ready` and -`powercontext capabilities` to diagnose an unavailable database versus an optional model failure. A background-only -process evaluates readiness at startup and every 30 seconds when metrics are enabled; `/metrics` itself never probes. -Before a completed evaluation, or in an embedding application that does not evaluate readiness, `unobserved` is valid. +Detailed probe observations cover `database`, `inference.generation`, `inference.rerank`, `inference.decision`, and `inference.embedding`. The same `dependency_state` family also includes bounded aggregate checks for `runtime`, `artifact_processing_supervisor`, registered `artifact_processing.` values, `access_provider`, and `authentication_provider`. Detailed Runtime snapshots take precedence over aggregate state for the same dependency; each dependency has only one one-hot state set. Probe timestamps and durations remain actual-probe observations, not aggregate evaluation times. Disabled dependencies have no probe timestamps or samples. Probe outcomes are `ready`, `unavailable`, `timeout`, `misconfigured`, or `cancelled`; cancellation contributes duration but does not replace the last completed state/timestamp. A cache hit updates neither actual probe timestamps nor histogram counts. One sample is one complete probe refresh; provider-internal retries, if any, remain inside that duration and are not counted as separate network attempts. Built-in cached probes normally retain results for 300 seconds, or 30 seconds for `timeout`/`unavailable`; cache expiry alone does not run a probe. The aggregate evaluation timestamp, probe timestamps, collection timestamp, and Prometheus scrape timestamp answer different freshness questions. + +`runtime_ready=1` may coexist with `degraded`: it means operations can be admitted, not that all models are available. Use `runtime_readiness_state` with dependency states and freshness, or request `powercontext ready` and `powercontext capabilities` to diagnose an unavailable database versus an optional model failure. A background-only process evaluates readiness at startup and every 30 seconds when metrics are enabled; `/metrics` itself never probes. Before a completed evaluation, or in an embedding application that does not evaluate readiness, `unobserved` is valid. ### Processing metrics -The following suffixes have the prefix `powercontext_server_artifact_processing_`. All per-Family series use `family`; -additional labels are listed explicitly. Only registered, validated Family names are exported. No scope, worker, -request, trace, content, provider error text, or database URL is a metric label. +The following suffixes have the prefix `powercontext_server_artifact_processing_`. All per-Family series use `family`; additional labels are listed explicitly. Only registered, validated Family names are exported. No scope, worker, request, trace, content, provider error text, or database URL is a metric label. | Metric suffix | Meaning | | --- | --- | @@ -212,106 +128,42 @@ request, trace, content, provider error text, or database URL is a metric label. | `retries_total` | Additional `reason`: `failure`, `conflict`, `blocked`; retry scheduling decisions, including block rechecks and overflow | | `admission_blocks_total` | Observed blocked admission decisions; repeated decisions may count again | -Durable pending observations run periodically, independently of worker capacity, with a default interval of 30 seconds -and a 2-second deadline per observation. A full set of occupied worker slots does not pause this observation. -Failures preserve the last successful snapshot and increment `pending_observation_failures_total`; a fresh collection -or scrape does not make that snapshot fresh. These reads run in the background, never during metrics collection. - -The pending snapshot reads the existing processing intents and counts pending Scopes for the binding. It does not -store a timestamp per request generation or require a new table or schema migration. Query work scales with the -binding's intents; the retained aggregate snapshot uses O(Families) memory. Before the first successful observation, -a zero snapshot timestamp means unobserved, even when count gauges are zero. Restart and leadership changes require -fresh observations; do not interpret retained or missing measurements as current durable backlog truth. - -`oldest_observed_pending_age_seconds` is an approximate **local lower bound**, measured from first local observation -of up to 1000 retained admitted keys. It tracks locally observed pending generations, not request creation time or -exact durable backlog age. Membership may be stale between discovery passes while the local age advances. Unseen -keys can be older; acknowledgement or eviction can remove local observations. Restart and leadership changes reset -this local history. A local age of `0` does not prove an empty durable backlog, and a large value alone never implies -a stall: processing may still be making verified acknowledgement progress. Use pending evidence, snapshot freshness, -verified acknowledgement progress, and startup grace together. - -Attempt outcomes are `success`, `hold`, `noop`, `failure`, `cancelled`, `blocked`, `cursor_conflict`, `head_conflict`, -and `leadership_lost`. Discovery outcomes are `success`, `failure`, `cancelled`, and `leadership_lost`. The duration -histograms expose `_bucket`, `_count`, and `_sum`; bucket boundaries are 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, -2.5, 5, 10, 30, 60, and `+Inf` seconds. `_count` counts attempts/passes, not unique requests or business successes. -A retry contributes another attempt. `hold` and `noop` remain distinct from business success. The legacy -`completed_total` counts verified durable acknowledgements and can include acknowledged holds/no-ops; it is not an -attempt-success or produced-artifact counter. Neither histogram nor acknowledgement counter is a billing ledger. +Durable pending observations run periodically, independently of worker capacity, with a default interval of 30 seconds and a 2-second deadline per observation. A full set of occupied worker slots does not pause this observation. Failures preserve the last successful snapshot and increment `pending_observation_failures_total`; a fresh collection or scrape does not make that snapshot fresh. These reads run in the background, never during metrics collection. + +The pending snapshot reads the existing processing intents and counts pending Scopes for the binding. It does not store a timestamp per request generation or require a new table or schema migration. Query work scales with the binding's intents; the retained aggregate snapshot uses O(Families) memory. Before the first successful observation, a zero snapshot timestamp means unobserved, even when count gauges are zero. Restart and leadership changes require fresh observations; do not interpret retained or missing measurements as current durable backlog truth. + +`oldest_observed_pending_age_seconds` is an approximate **local lower bound**, measured from first local observation of up to 1000 retained admitted keys. It tracks locally observed pending generations, not request creation time or exact durable backlog age. Membership may be stale between discovery passes while the local age advances. Unseen keys can be older; acknowledgement or eviction can remove local observations. Restart and leadership changes reset this local history. A local age of `0` does not prove an empty durable backlog, and a large value alone never implies a stall: processing may still be making verified acknowledgement progress. Use pending evidence, snapshot freshness, verified acknowledgement progress, and startup grace together. + +Attempt outcomes are `success`, `hold`, `noop`, `failure`, `cancelled`, `blocked`, `cursor_conflict`, `head_conflict`, and `leadership_lost`. Discovery outcomes are `success`, `failure`, `cancelled`, and `leadership_lost`. The duration histograms expose `_bucket`, `_count`, and `_sum`; bucket boundaries are 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, and `+Inf` seconds. `_count` counts attempts/passes, not unique requests or business successes. A retry contributes another attempt. `hold` and `noop` remain distinct from business success. The legacy `completed_total` counts verified durable acknowledgements and can include acknowledged holds/no-ops; it is not an attempt-success or produced-artifact counter. Neither histogram nor acknowledgement counter is a billing ledger. ### Dashboards and alert rules -Choose and record explicit operator thresholds for scrape failure, collection age, probe age, requested-snapshot age, -startup grace, and time without acknowledgement. These are deployment-specific alert policies, not built-in defaults. -For example, an operator may select 120 seconds for collection freshness, 600 seconds for probe freshness, and 900 -seconds without acknowledgement while pending work exists; validate those choices against scrape cadence, readiness -traffic, schedules, and expected worker duration. Do not apply a 600-second probe rule to a host that never runs probes. - -- First check Prometheus `up`, collection freshness, and collection failures. A fresh scrape can contain an old snapshot - after collection failure. Missing or zero timestamps need an explicit unobserved branch, separate from stale data -- For dependency alerts, require an observed, sufficiently fresh state. Treat `disabled`, `unobserved`, stale, degraded, - and unavailable separately; optional-provider failure should not automatically page as database failure -- Separate stopped processing from stalled processing. With a fresh collection, `supervisor_present=1` and - `supervisor_running=0`, alert on stopped processing when retained local work or a sufficiently fresh positive - `unacknowledged_requests` snapshot establishes pending work. Do not require a running Leader for this rule. If only - stale last-known pending evidence remains, report stopped processing with uncertain backlog and investigate; - a missing target is handled separately through `up` -- For a running Leader, gate possible-stall alerts on a fresh collection and pending-work evidence: current - `observed_pending_scopes>0` or `used_workers>0`, or a nonzero, sufficiently fresh - `requested_snapshot_timestamp_seconds` with `unacknowledged_requests>0` from the same target/Family. - Require sustained pending work and no verified acknowledgement progress for the chosen interval, allowing a startup - grace period after restart or leadership change. Use `last_acknowledgement_timestamp_seconds` and changes in - `completed_total` to assess verified progress; process exit or successful attempt duration is not acknowledgement. - For example, after the startup grace period, 900 seconds of sustained pending evidence without acknowledgement - can indicate a possible stall; an old locally observed key while acknowledgements advance does not. - A zero acknowledgement timestamp means never acknowledged, not a UNIX-era outage: use the grace period and a - sustained observation window instead of subtracting zero from the current time. Account for clock skew when - comparing timestamps, and do not treat missing observations as zero -- Durable pending observation continues when worker slots are full; observation failures can still leave stale data. - A stale snapshot must not suppress a possible-stall alert supported by current retained work and absent verified - progress. The durable count is a last-known background observation; local retained keys and worker slots are not - a complete durable backlog. `oldest_observed_pending_age_seconds` is only supporting context, never an independent - stall trigger or a substitute for acknowledgement progress and freshness -- Keep idle healthy instances quiet. Automatic processing disabled is configuration, standby is expected, and missing - API-only Supervisor data is not a zero-capacity outage. Stale pending snapshots without current local evidence merit a freshness diagnostic, not a - fabricated backlog conclusion. Watch blocked waits, admission blocks, retry reasons, errors, and worker utilization -- Scrape API and background targets separately. Do not add API and background backlog snapshots or leader and standby - counts for the same deployment/Family. Select the current running leader for backlog/capacity dashboards; preserve - deployment/group boundaries when combining Families. Counter rates are process-local and may need aggregation - across role transitions, but the same target must never be scraped twice into the same total -- Alert on increasing pending-observation failures, collection failures, and dropped log records. OTLP SDK queue occupancy and exporter drop counts - are unsupported here: their absence means unavailable telemetry, not zero pressure or zero loss. Inspect the - collector/backend's own diagnostics when investigating trace delivery +Choose and record explicit operator thresholds for scrape failure, collection age, probe age, requested-snapshot age, startup grace, and time without acknowledgement. These are deployment-specific alert policies, not built-in defaults. For example, an operator may select 120 seconds for collection freshness, 600 seconds for probe freshness, and 900 seconds without acknowledgement while pending work exists; validate those choices against scrape cadence, readiness traffic, schedules, and expected worker duration. Do not apply a 600-second probe rule to a host that never runs probes. + +- First check Prometheus `up`, collection freshness, and collection failures. A fresh scrape can contain an old snapshot after collection failure. Missing or zero timestamps need an explicit unobserved branch, separate from stale data +- For dependency alerts, require an observed, sufficiently fresh state. Treat `disabled`, `unobserved`, stale, degraded, and unavailable separately; optional-provider failure should not automatically page as database failure +- Separate stopped processing from stalled processing. With a fresh collection, `supervisor_present=1` and `supervisor_running=0`, alert on stopped processing when retained local work or a sufficiently fresh positive `unacknowledged_requests` snapshot establishes pending work. Do not require a running Leader for this rule. If only stale last-known pending evidence remains, report stopped processing with uncertain backlog and investigate; a missing target is handled separately through `up` +- For a running Leader, gate possible-stall alerts on a fresh collection and pending-work evidence: current `observed_pending_scopes>0` or `used_workers>0`, or a nonzero, sufficiently fresh `requested_snapshot_timestamp_seconds` with `unacknowledged_requests>0` from the same target/Family. Require sustained pending work and no verified acknowledgement progress for the chosen interval, allowing a startup grace period after restart or leadership change. Use `last_acknowledgement_timestamp_seconds` and changes in `completed_total` to assess verified progress; process exit or successful attempt duration is not acknowledgement. For example, after the startup grace period, 900 seconds of sustained pending evidence without acknowledgement can indicate a possible stall; an old locally observed key while acknowledgements advance does not. A zero acknowledgement timestamp means never acknowledged, not a UNIX-era outage: use the grace period and a sustained observation window instead of subtracting zero from the current time. Account for clock skew when comparing timestamps, and do not treat missing observations as zero +- Durable pending observation continues when worker slots are full; observation failures can still leave stale data. A stale snapshot must not suppress a possible-stall alert supported by current retained work and absent verified progress. The durable count is a last-known background observation; local retained keys and worker slots are not a complete durable backlog. `oldest_observed_pending_age_seconds` is only supporting context, never an independent stall trigger or a substitute for acknowledgement progress and freshness +- Keep idle healthy instances quiet. Automatic processing disabled is configuration, standby is expected, and missing API-only Supervisor data is not a zero-capacity outage. Stale pending snapshots without current local evidence merit a freshness diagnostic, not a fabricated backlog conclusion. Watch blocked waits, admission blocks, retry reasons, errors, and worker utilization +- Scrape API and background targets separately. Do not add API and background backlog snapshots or leader and standby counts for the same deployment/Family. Select the current running leader for backlog/capacity dashboards; preserve deployment/group boundaries when combining Families. Counter rates are process-local and may need aggregation across role transitions, but the same target must never be scraped twice into the same total +- Alert on increasing pending-observation failures, collection failures, and dropped log records. OTLP SDK queue occupancy and exporter drop counts are unsupported here: their absence means unavailable telemetry, not zero pressure or zero loss. Inspect the collector/backend's own diagnostics when investigating trace delivery See [Configuration](configuration.md) for endpoint settings and [Troubleshoot](troubleshoot.md) for recovery. ## Tracing -Install the `tracing-otlp` extra, enable `POWERCONTEXT_SERVER_TRACING_ENABLED=true`, and configure an OTLP HTTP -receiver. Follow the complete [Phoenix](trace-with-phoenix.md) or [Langfuse](trace-with-langfuse.md) procedure. -Without the extra, enabling tracing fails at startup. PowerContext traces its own transport, application, and model -calls; tracing does not capture unrelated host model calls automatically. Model spans disable automatic exception events -and status descriptions so provider error bodies cannot export Source, prompt, or response content; only a bounded -`error.type` and error status are retained. +Install the `tracing-otlp` extra before setting `POWERCONTEXT_SERVER_TRACING_ENABLED=true`, then configure an OTLP HTTP receiver. See the [Phoenix](trace-with-phoenix.md) or [Langfuse](trace-with-langfuse.md) guide for setup steps. The Server fails to start if tracing is enabled without the extra. PowerContext traces its own transport, application, and model calls. It does not automatically capture other model calls in the host application. For failed model calls, traces report `error.type` and an error status. They omit provider error messages, stack traces, and status descriptions that could contain Source, prompt, or response content. Exception events contain only `exception.type` and `exception.escaped`. -For environment-file deployments, put the tracing and OpenTelemetry variables in the explicit file passed to the -Server. See [environment configuration](../get-started/configure-server-environment.md) for precedence rules. +For environment-file deployments, put the tracing and OpenTelemetry variables in the explicit file passed to the Server. See [environment configuration](../get-started/configure-server-environment.md) for precedence rules. ### Background service and observation freshness Split API/background roles require OceanBase. SQLite and embedded seekdb retain the `all` role. -The `background` role exposes only `/health/live` and `/metrics` on `HTTP_HOST` and the separate -`POWERCONTEXT_SERVER_METRICS_BACKGROUND_PORT` (default `8001`). It does not expose business APIs, MCP, the dashboard, -or OpenAPI. API/all roles continue using their normal HTTP port. Disabling `METRICS_ENABLED` also disables the background -HTTP listener. Authentication and `server.observe` authorization use the same Server profile as the API metrics endpoint; -non-loopback binding follows the existing Server bind policy. Configure the metrics port in the background environment -file when multiple processes share a host. +The `background` role exposes only `/health/live` and `/metrics` on `HTTP_HOST` and the separate `POWERCONTEXT_SERVER_METRICS_BACKGROUND_PORT` (default `8001`). It does not expose business APIs, MCP, the dashboard, or OpenAPI. API/all roles continue using their normal HTTP port. Disabling `METRICS_ENABLED` also disables the background HTTP listener. Authentication and `server.observe` authorization use the same Server profile as the API metrics endpoint; non-loopback binding follows the existing Server bind policy. Configure the metrics port in the background environment file when multiple processes share a host. -When metrics are enabled, readiness is evaluated at startup and every 30 seconds. Scraping metrics never invokes a -model, pings the database, or refreshes readiness. Inference probes retain their existing 300-second normal and 30-second -transient caches. `readiness_evaluated_timestamp_seconds` dates the aggregate evaluation, not a fresh provider request; -this timestamp does not bypass or describe the age of an individual cached probe. +When metrics are enabled, readiness is evaluated at startup and every 30 seconds. Scraping metrics never invokes a model, pings the database, or refreshes readiness. Inference probes retain their existing 300-second normal and 30-second transient caches. `readiness_evaluated_timestamp_seconds` dates the aggregate evaluation, not a fresh provider request; this timestamp does not bypass or describe the age of an individual cached probe. | Metric (prefix `powercontext_server_`) | Interpretation | | --- | --- | @@ -329,41 +181,15 @@ this timestamp does not bypass or describe the age of an individual cached probe | `model_usage_worker_reports_total{outcome}` | Invocation attempts with `received` recorder counters or `missing` observations; missing does not mean zero losses | | `metrics_collection_failures_total` | Failed processing snapshot refreshes; an old snapshot can remain visible | -Processing timestamps use `0` for an observation that has never occurred. All counts, histograms and timestamps belong -to the current process/supervisor lifetime and reset or disappear on restart/removal. The pending timestamp is a local -lower bound on unfinished-work age, not the oldest durable Source or a complete database backlog: undiscovered work, -retry-cache eviction and restart can remove its history. Combine it with backlog counts and observation freshness. -A healthy idle worker need not have a recent success. Use pending work plus stalled progress/freshness as alert conditions; -keep policy blocks separate from outages. Invocation outcomes are `success`, `failure`, `blocked`, `cancelled`, `conflict` -and `timeout`; a slot retained for leadership cleanup is not counted again as a completed reap. - -Processing labels use registered family names and bounded outcomes, never scope/worker/request identities. Scrapes read -in-memory snapshots; local ready/retry/running observation work is bounded by scheduler limits rather than database size. -Built-in spawned workers return two cumulative loss counters after recorder shutdown, on both success and failure. -The owning supervisor adds each attempt's counters once, independently of acknowledgement and tracing configuration. -Multiple recorders opened during one child invocation contribute to the same report. Scrapes do not recount reports. -Child queue depth/capacity are not live measurements in this endpoint. A running child has not yet reported; a crash, -forced termination, or invocation that never observed a recorder produces a `missing` report rather than known zero losses. -This projection is not durable: parent restart or a lost child report can lose observations. Custom launchers must supply -their own report and observer wiring. An API-only process cannot observe another background service's children. -Scrape every deployed API/background target and keep role/instance attribution in target labels. An absent target or -missing sample must not be interpreted as zero failures. Do not sum process snapshots as if they were one durable ledger. +Processing timestamps use `0` for an observation that has never occurred. All counts, histograms and timestamps belong to the current process/supervisor lifetime and reset or disappear on restart/removal. The pending timestamp is a local lower bound on unfinished-work age, not the oldest durable Source or a complete database backlog: undiscovered work, retry-cache eviction and restart can remove its history. Combine it with backlog counts and observation freshness. A healthy idle worker need not have a recent success. Use pending work plus stalled progress/freshness as alert conditions; keep policy blocks separate from outages. Invocation outcomes are `success`, `failure`, `blocked`, `cancelled`, `conflict` and `timeout`; a slot retained for leadership cleanup is not counted again as a completed reap. + +Processing labels use registered family names and bounded outcomes, never scope/worker/request identities. Scrapes read in-memory snapshots; local ready/retry/running observation work is bounded by scheduler limits rather than database size. Built-in spawned workers return two cumulative loss counters after recorder shutdown, on both success and failure. The owning supervisor adds each attempt's counters once, independently of acknowledgement and tracing configuration. Multiple recorders opened during one child invocation contribute to the same report. Scrapes do not recount reports. Child queue depth/capacity are not live measurements in this endpoint. A running child has not yet reported; a crash, forced termination, or invocation that never observed a recorder produces a `missing` report rather than known zero losses. This projection is not durable: parent restart or a lost child report can lose observations. Custom launchers must supply their own report and observer wiring. An API-only process cannot observe another background service's children. Scrape every deployed API/background target and keep role/instance attribution in target labels. An absent target or missing sample must not be interpreted as zero failures. Do not sum process snapshots as if they were one durable ledger. ### Worker execution traces and integration coverage -With tracing enabled and `tracing-otlp` installed, Server-composed workers capture only W3C `traceparent`/`tracestate` -when launched. Each child creates its own provider/resource, joins that supervisor execution, and instruments its real -family or Topic Memory model composition. Memory processing includes the existing commit stages; Topic Memory adds -`topic_memory.prepare` and `topic_memory.commit`. Explicit Dream dispatch — including the Topic Memory dream branch — -runs under the same child span and shares the same model instrumentation, so instrumented model spans appear for both. The child `artifact_processing.worker.execute` span describes a child -result; the supervisor acknowledgement remains the evidence of verified business completion. +With tracing enabled and `tracing-otlp` installed, the tracing context passed to Server-managed workers at launch contains only W3C `traceparent`/`tracestate`. Each worker reports traces under its own resource, linked to the supervisor execution, with spans for its family and model calls. Memory traces include commit stages; Topic Memory traces include `topic_memory.prepare` and `topic_memory.commit`. Explicit Dream requests, including the Topic Memory Dream branch, appear under the same worker span with their model calls. The `artifact_processing.worker.execute` span reports the worker's result. The supervisor acknowledgement confirms that business processing completed. -A scheduled/coalesced invocation starts an independent supervisor trace. It does not inherit a capture request ID, -keep an HTTP request open, or claim a durable causal link to all contributing Sources. No incoming context is persisted -for replay. Custom launchers own their bootstrap; SDK-only composition stays unconfigured unless an embedding application -supplies the optional worker wrapper. Parent-based sampling decisions propagate to the child. Child export/shutdown is -best-effort, with at most a one-second shutdown wait; forced termination can leave incomplete spans. Missing exporters -still fail an explicitly configured Server at startup, while child telemetry setup/export failure cannot change its domain result. +A scheduled/coalesced invocation starts an independent supervisor trace. It does not inherit a capture request ID, keep an HTTP request open, or claim a durable causal link to all contributing Sources. No incoming context is persisted for replay. Custom launchers own their bootstrap; SDK-only composition stays unconfigured unless an embedding application supplies the optional worker wrapper. Parent-based sampling decisions propagate to the child. Child export/shutdown is best-effort, with at most a one-second shutdown wait; forced termination can leave incomplete spans. Missing exporters still fail an explicitly configured Server at startup, while child telemetry setup/export failure cannot change its domain result. | Integration boundary | Coverage | | --- | --- | @@ -373,14 +199,8 @@ still fail an explicitly configured Server at startup, while child telemetry set | Built-in Memory and Topic Memory spawn workers | Real entrypoints, local provider HTTP success/timeout, child spans and OTLP reception verified | | Other native host integrations | Host diagnostics remain available; automatic host trace propagation is not claimed by this coverage | -OTLP tests use an actual local protobuf HTTP receiver, not a production trace database. To validate storage and backend -queries, follow the Phoenix/Langfuse instructions or the chosen backend's deployment procedure. Metrics dashboards, -trace storage, log shipping and alert delivery are separate deployment capabilities. +OTLP tests use an actual local protobuf HTTP receiver, not a production trace database. To validate storage and backend queries, follow the Phoenix/Langfuse instructions or the chosen backend's deployment procedure. Metrics dashboards, trace storage, log shipping and alert delivery are separate deployment capabilities. ## Topic generation rejection codes -Topic processing may report `invalid_topic_placeholder` for recognizable numbered placeholder bodies or -`invalid_topic_coordination_content` for identity-coordination-only bodies. These content-free diagnostic codes -identify recoverable generation rejection, not successful NOOP. Retries use the existing durable Window budget; -exhaustion retains the pending frontier. Existing worker events and correlation fields carry the diagnostic code. -Source text, generated bodies and provider responses must not be added to operational logs. +Topic processing may report `invalid_topic_placeholder` for recognizable numbered placeholder bodies or `invalid_topic_coordination_content` for identity-coordination-only bodies. These content-free diagnostic codes identify recoverable generation rejection, not successful NOOP. Retries use the existing durable Window budget; exhaustion retains the pending frontier. Existing worker events and correlation fields carry the diagnostic code. Source text, generated bodies and provider responses must not be added to operational logs. diff --git a/docs/zh/development/pydantic-ai-inference.md b/docs/zh/development/pydantic-ai-inference.md index a98b54f8de..a6858488ec 100644 --- a/docs/zh/development/pydantic-ai-inference.md +++ b/docs/zh/development/pydantic-ai-inference.md @@ -1,48 +1,43 @@ # 配置 Pydantic AI 推理 -PowerContext 在 provider 边界使用 Pydantic AI,同时保持 Memory service 与具体框架无关。generation 用于提取结构化 -Memory candidate,embedding 为支持 vector search 的 index 提供向量。这两项能力可以独立配置。 +PowerContext 使用生成模型从 Source 提取 Memory,使用向量模型为支持向量检索的索引生成向量。这两项能力可以分别配置。 -## 安装集成 +## 安装依赖 -推理集成属于内置实现: +在 Python 项目中使用内置推理功能,安装 `builtin` extra: ```bash uv add "powercontext[builtin]" ``` -Server extra 已经包含 Builtin: +运行 Server 时,安装 `server` extra 即可,它已包含上述依赖: ```bash uv add "powercontext[server]" ``` +这两个 extra 都会安装 Pydantic AI 2.64 或更新的 2.x 版本。 + ## 配置 Server -标准 Server 根据 `ServerSettings.inference` 构造推理 adapter。配置 generation model 后会启用 -Source-to-Memory extraction: +设置以下环境变量,为 Server 指定用于从 Source 提取 Memory 的生成模型: ```bash export POWERCONTEXT_SERVER_INFERENCE_GENERATION_MODEL="provider:model-name" ``` -额外的 Pydantic AI model settings 可以通过 JSON 配置。provider-specific request field 应放在 `extra_body` -下面;例如,兼容的 OpenAI-style endpoint 可以这样关闭 Qwen thinking: +额外的模型参数使用 JSON 配置。模型服务特有的请求字段放在 `extra_body` 中。例如,兼容 OpenAI 接口的服务可以这样关闭 Qwen 的思考模式: ```bash export POWERCONTEXT_SERVER_INFERENCE_GENERATION_MODEL="openai-chat:" export POWERCONTEXT_SERVER_INFERENCE_GENERATION_MODEL_SETTINGS='{"extra_body":{"chat_template_kwargs":{"enable_thinking":false}}}' ``` -Topic Memory 也支持 `openai-chat:` 使用这一精确的 `extra_body` 结构。值必须是 JSON 布尔值 -`false`;任一层的额外字段、其他 provider 前缀以及 Embedding 的 `extra_body` 仍不支持。端点必须实现 -`chat_template_kwargs.enable_thinking`;关闭 thinking 不保证推理一定在超时前完成。 +Topic Memory 仅允许 `openai-chat:` 使用示例中的 `extra_body` 结构。值必须是 JSON 布尔值 `false`,两层对象都不能包含额外字段。其他 provider 前缀和向量模型不支持这一配置。模型服务需要实现 `chat_template_kwargs.enable_thinking`;关闭思考模式后,推理仍可能超时。 -generation-backed pipeline、可选的 LLM reranker 和 readiness probe 共用这些 settings。PowerContext 仍保留自身的 -请求边界:readiness 使用 `max_tokens=1`,rerank 使用 `temperature=0`。credential 与 static header 应放在 -provider 配置中,不要放入 model settings。 +生成流程、可选的 LLM 重排和就绪检查共用这些参数。就绪检查可能调用模型并消耗用量。可用参数取决于所选模型服务和模型。凭据与静态请求头使用各自的配置项,不要放入模型参数。 -vector search 需要 embedding model 和完整的 deployment profile: +启用向量检索时,需要同时指定向量模型、配置标识和向量维度: ```bash export POWERCONTEXT_SERVER_INFERENCE_EMBEDDING_MODEL="provider:embedding-model" @@ -50,11 +45,7 @@ export POWERCONTEXT_SERVER_INFERENCE_EMBEDDING_PROFILE_ID="project-embedding-v1" export POWERCONTEXT_SERVER_INFERENCE_EMBEDDING_DIMENSION="1536" ``` -每类 workload 可以连接不同的模型服务。自定义 base URL 使用 model identifier 指定的 provider 接口: -OpenAI-compatible Chat Completions 服务使用 `openai-chat:`,OpenAI-compatible Responses 或 embedding -服务使用 `openai:`,Anthropic-compatible generation 服务使用 `anthropic:`。内置 reranker 是 LLM -listwise reranker,因此它的独立 endpoint 也是 Pydantic AI generation endpoint,而不是 cross-encoder `/rerank` -API: +生成、向量和重排任务可以分别连接不同的模型服务。按服务接口选择模型前缀:OpenAI Chat Completions 使用 `openai-chat:`,OpenAI Responses 或 embedding 使用 `openai:`,Anthropic 兼容接口使用 `anthropic:`。内置重排使用语言模型对候选列表排序,需要配置生成模型的地址,不支持 cross-encoder 的 `/rerank` 接口: ```bash export POWERCONTEXT_SERVER_INFERENCE_GENERATION_MODEL="openai-chat:generator" @@ -73,33 +64,60 @@ export POWERCONTEXT_SERVER_INFERENCE_RERANK_HEADERS='{"Authorization":"Bearer re export POWERCONTEXT_SERVER_INFERENCE_RERANK_MODEL_SETTINGS='{"max_tokens":256}' ``` -header 和 model settings 都使用 JSON object。settings model 会将 header value 作为 secret 处理,并将它们作为 -workload provider client 的静态 header;这些值不会进入 Pydantic AI request settings。不要在 model settings 中配置 -`extra_headers`;使用独立的 headers 变量才能保留配置与日志脱敏语义。其余 model settings 由 Pydantic AI 传递给 -所选 provider。reranker 始终将 `temperature` 固定为零。自定义 embedding base URL 目前要求服务实现 -OpenAI-compatible embeddings 接口。 +请求头和模型参数都使用 JSON 对象。`*_HEADERS` 中的值按敏感信息处理,并作为相应任务的静态请求头发送。将 `extra_headers` 放入模型参数会被拒绝;请使用独立的请求头配置,以便配置展示和日志脱敏生效。其余模型参数传给所选服务。重排不支持自定义采样温度。自定义向量服务需要提供 OpenAI 兼容的 embeddings 接口,已支持的 MiniMax 原生 embedding 端点除外。 + +服务地址可以包含网关路径前缀,后面会自动追加 `/chat/completions`、`/responses` 或 `/embeddings` 等接口路径,不支持任意改写这些路径。自定义地址或静态请求头时,模型名称必须带有明确的 OpenAI 或 Anthropic 兼容接口前缀。 + +未设置 `RERANK_MODEL` 时,LLM 重排复用生成模型及其服务地址。重排的请求头和模型参数可以扩展或覆盖生成配置;请求头覆盖仅影响重排,不会改变所用模型和地址。单独设置重排地址时,也必须指定重排模型。未设置重排超时和请求次数上限时,它们沿用生成任务的配置。 + +使用默认地址和请求头时,通过所选模型服务支持的环境变量提供凭据。已有订阅凭据的复用方式见下文。 + +`embedding_model`、`embedding_profile_id` 和 `embedding_dimension` 必须一起配置,缺少任一项时 Server 会拒绝该配置。SQLite 向量检索使用这组配置,索引维度必须与存储的向量一致。对于 OpenAI 兼容的 embedding 服务,`embedding_dimension` 默认作为请求参数 `dimensions` 发送,并覆盖模型参数中的同名字段。模型输出维度固定且不接受该参数时,将 `POWERCONTEXT_SERVER_INFERENCE_EMBEDDING_SEND_DIMENSIONS` 设为 `false`。本地维度仍然必填,Server 仍会按它校验返回的向量。 + +## 复用已有订阅凭据 + +在启动 Server 的环境中提供 Codex 或 GitHub Copilot 凭据,并确保 worker 也能读取。凭据文件的路径以 Server 所在主机及其运行用户为准,客户端机器上的登录不会自动带到 Server。 -base URL 可以包含 gateway path prefix,但具体 operation suffix 仍由所选 Pydantic AI provider 决定,例如 -`/chat/completions`、`/responses` 或 `/embeddings`;不支持任意改写 operation path。 -自定义 base URL 或静态 header 时必须使用显式的 OpenAI- 或 Anthropic-compatible model identifier,PowerContext -才能创建对应的 provider client。 +下面的 Codex 和 Copilot 示例使用默认服务地址和认证方式。使用这些示例时,不要设置 `POWERCONTEXT_SERVER_INFERENCE_GENERATION_BASE_URL` 和 `POWERCONTEXT_SERVER_INFERENCE_GENERATION_HEADERS`。将 `` 替换为对应订阅可用的模型 ID。 -未设置 `RERANK_MODEL` 时,LLM rerank 复用 generation model 和 base URL;仍可通过 reranker headers 和 model -settings 扩展或覆盖 generation 配置。覆盖 header 时会为 rerank workload 创建独立 provider client,但保留 -generation model identifier 和 base URL。独立的 reranker base URL 必须同时配置显式 reranker model。reranker -timeout 和 request limit 未显式设置时继承 generation 的对应配置。 +### Codex CLI 凭据 -不需要自定义 base URL 或 header 时,provider credential 仍使用所选 Pydantic AI provider 支持的环境变量。 +Codex CLI 已使用订阅账号登录,且凭据保存在 `auth.json` 时,使用 `openai-codex:` 模型前缀: -Server 会拒绝不完整的 embedding profile。`embedding_model`、`embedding_profile_id` 和 -`embedding_dimension` 必须一起配置。SQLite vector search 使用这组配置,因为 index dimension 必须与持久化向量一致。 -`embedding_dimension` 默认也会作为请求参数 `dimensions` 发送,并覆盖 model settings 里的同名字段。固定输出维度、 -不接受该参数的模型把 `POWERCONTEXT_SERVER_INFERENCE_EMBEDDING_SEND_DIMENSIONS` 设为 `false`;本地维度仍然必填, -返回向量仍按它校验。 +```bash +export POWERCONTEXT_SERVER_INFERENCE_GENERATION_MODEL="openai-codex:" +``` + +Server 默认读取运行用户的 `~/.codex/auth.json`。凭据保存在其他 Codex home 目录时,通过环境变量指定目录: + +```bash +export CODEX_HOME="/path/to/existing/codex-home" +``` -## 直接组合 generation +`CODEX_HOME` 指向包含 `auth.json` 的目录。服务不会更新 CLI 登录文件。认证失效时,用原有 CLI 更新登录,再重启服务。详见 [Pydantic AI 的 Codex 凭据配置](https://github.com/pydantic/pydantic-ai/blob/v2.64.0/docs/models/openai-codex.md)。 -应用已经持有 provider model 生命周期时,可以直接组合: +### GitHub Copilot 凭据 + +已有 GitHub CLI OAuth 登录,且账号具有 Copilot 访问权限时,在启动 Server 前导出 token: + +```bash +export GITHUB_COPILOT_API_KEY="$(gh auth token)" +export POWERCONTEXT_SERVER_INFERENCE_GENERATION_MODEL="github-copilot:" +``` + +也可以沿用环境中已有的 `GITHUB_COPILOT_API_TOKEN` 或 `COPILOT_GITHUB_TOKEN`,它们会依次作为备用变量读取。Server 使用这些专用变量,通用的 `GITHUB_TOKEN` 和 `GH_TOKEN` 不用于 Copilot 认证。示例中的 `gh auth token` 需要在启动服务前执行,Server 不会自动读取 CLI 配置或续期 token。token 更新后,更新服务进程的环境并重启 Server。详见 [Pydantic AI 的 Copilot 配置](https://github.com/pydantic/pydantic-ai/blob/v2.64.0/docs/models/github-copilot.md)。 + +这些配置支持 Memory、Experience 和 Profile 的生成。Codex 和 Copilot 暂不支持 Topic Memory 与 Dream。如果已经显式启用 Topic Memory 处理或自动调度,切换 provider 前需要移除对应配置。已启用内置推理保护时,切换到这两个 provider 会导致启动失败。 + +### 已有 ChatGPT Plan Usage 凭据 + +已有 ChatGPT Plan Usage 授权可以通过 SDK 复用。Server 环境变量暂不支持加载这类凭据,只配置模型名称不足以启用服务。 + +将已有应用配置好的 Pydantic AI 模型用于下文的 SDK 示例。该模型需要使用 ChatGPT Plan Usage 授权,Codex CLI 凭据不能替代它。详见 [Pydantic AI 的已有凭据配置](https://github.com/pydantic/pydantic-ai/blob/v2.64.0/docs/models/openai-chatgpt.md#persisting-credentials)。 + +## 通过 SDK 使用生成模型 + +如果应用已经配置好 Pydantic AI 模型,可以将它传给结构化生成器,再创建 Memory 提取流程: ```python from powercontext.builtin.artifacts.memory import ( @@ -123,18 +141,13 @@ generator = PydanticAIStructuredGenerator( candidate_pipeline = LLMMemoryCandidatePipeline(generator) ``` -`generation_model` 必须是已经初始化的 Pydantic AI `Model`,不能是 provider name 字符串。打开 model 的应用也负责 -关闭它。 +`generation_model` 接收已初始化的 Pydantic AI `Model` 对象,不接受模型名称字符串。应用负责打开和关闭该对象。 -generator 使用 Pydantic 序列化 input model,并根据声明的 output type 校验结构化输出。generation 之后仍会执行 -Memory validation,因此 schema 有效的 candidate 不会自动获得持久化资格。 +生成器按声明的输入类型序列化数据,并按输出类型校验结果。输出通过 schema 校验后,还需要满足 Memory 的写入规则才能保存。 -如果某条规则需要结合 input 才能判断,无法写进 output schema,可以传入 `output_check`。这个 callable 接收 input 和 -已通过校验的 output,output 违反规则时抛出 `InvalidInferenceOutputError`。错误的 detail 会作为重试反馈返回给模型, -这次重试和 schema 错误共用 `max_requests` 预算。预算用完后,`generate()` 抛出最后一次的 -`InvalidInferenceOutputError`。detail 会发送给 provider,所以只写规则本身,不要包含 input 内容。 +输入和输出之间的业务约束无法写入输出 schema 时,可以传入 `output_check`。该回调接收输入和已通过校验的输出,并在输出违反规则时抛出 `InvalidInferenceOutputError`。异常的 `detail` 会作为重试反馈发给模型,与 schema 校验失败共用 `max_requests` 预算。预算耗尽后,`generate()` 抛出最后一次 `InvalidInferenceOutputError`。`detail` 只应描述规则,不要包含输入内容。 -## 直接组合 embedding +## 通过 SDK 使用向量模型 ```python from pydantic_ai import Embedder @@ -157,16 +170,14 @@ embedding_model = PydanticAIEmbeddingModel( ) ``` -将这个 adapter 与 `SQLiteConfig` 一起传给 `open_builtin_contexts()` 或 `open_builtin_runtime()` 后,会自动启用捆绑的 -sqlite-vec index。向量进入持久化之前,adapter 会校验输出数量、顺序、dimension 和数值有效性,并执行 profile 声明的单位归一化。 +将 `embedding_model` 与 `SQLiteConfig` 一起传给 `open_builtin_contexts()` 或 `open_builtin_runtime()`,即可启用 sqlite-vec 向量索引。保存向量前,PowerContext 会校验数量、顺序、维度和数值是否有效,并按配置执行单位归一化。 + +通过 SDK 为 MiniMax 向量模型或 Jev 重排提供 HTTP 客户端时,使用 `httpx2.AsyncClient`。 -`EmbeddingProfile` 是 deployment contract,不是描述性 metadata。持久化 projection 和 query embedding 必须使用 -同一个 profile。model、dimension 或 normalization 发生变化后,应从权威 Memory revision 重建 projection。 +已存储的向量和查询向量必须使用相同的 `EmbeddingProfile`。修改模型、维度或归一化方式后,需要从权威 Memory revision 重建向量投影。 ## 失败行为 -generation 和 embedding failure 会将 provider error 映射为 PowerContext inference error。timeout 和临时 provider -failure 不会提交部分 Memory revision。 +生成或向量调用失败时,PowerContext 返回相应的推理错误。超时或模型服务暂时不可用时,不会提交部分 Memory revision。 -对于 `mode="auto"` 的检索,如果 backend 支持 FTS,临时 query embedding failure 可以回退到 FTS。显式 vector -或 hybrid search 会报告能力缺失,不会静默改变模式。 +使用 `mode="auto"` 检索时,如果后端支持 FTS,查询向量生成暂时失败时可以回退到 FTS。显式指定 vector 或 hybrid 检索时,系统会报告能力缺失,不会自动切换检索模式。 diff --git a/docs/zh/docs/operate/observability.md b/docs/zh/docs/operate/observability.md index a06b56a393..2acda92c0e 100644 --- a/docs/zh/docs/operate/observability.md +++ b/docs/zh/docs/operate/observability.md @@ -5,14 +5,11 @@ description: 通过日志定位请求,并查看 Server 指标与 Trace。 # 日志、指标与 Tracing -用日志定位操作,用指标观察整体行为,用 Trace 跟踪请求经过的阶段。 -这些信号描述服务行为,不能代替对已保存 Memory 或 Source 证据的检查。 +用日志定位操作,用指标观察整体行为,用 Trace 跟踪请求经过的阶段。这些信号描述服务行为,不能代替对已保存 Memory 或 Source 证据的检查。 ## 日志 -前台 Server 将运行日志写入进程输出。可配置 `POWERCONTEXT_SERVER_LOGGING_LEVEL`(默认 `INFO`)、 -`POWERCONTEXT_SERVER_LOGGING_FORMAT`(`console` 或 `json`)和 `POWERCONTEXT_SERVER_LOGGING_ACCESS`(默认 `true`)。 -原生个人服务通过 `powercontext service status` 查看 journal 查询条件或日志路径;Docker 部署查看容器日志。 +前台 Server 将运行日志写入进程输出。可配置 `POWERCONTEXT_SERVER_LOGGING_LEVEL`(默认 `INFO`)、 `POWERCONTEXT_SERVER_LOGGING_FORMAT`(`console` 或 `json`)和 `POWERCONTEXT_SERVER_LOGGING_ACCESS`(默认 `true`)。原生个人服务通过 `powercontext service status` 查看 journal 查询条件或日志路径;Docker 部署查看容器日志。 ### 文件输出、轮替与压缩 @@ -42,16 +39,13 @@ macOS 和 Windows 个人服务默认启用托管文件输出,显式设置 `POW 目录不可用或已有写入者时,文件日志配置失败。运行期间的格式化、传输、入队、写入及压缩失败均使用不含内容的 `observability.log_failed` 通知。gzip 归档完整发布后才删除原始文件。通过 SDK 使用 Runtime 不配置日志,仍由嵌入应用管理。嵌入式 Server 启用文件输出时可以持有仅用于 Worker 的日志接收器,不重新配置嵌入应用的 logger。 -用响应中的 `X-PowerContext-Request-ID` 关联失败请求与诊断记录。宿主指南还说明不含内容的召回与采集诊断; -没有上下文结果可能是正常情况,不一定代表服务故障。 +用响应中的 `X-PowerContext-Request-ID` 关联失败请求与诊断记录。宿主指南还说明不含内容的召回与采集诊断;没有上下文结果可能是正常情况,不一定代表服务故障。 ### Operational fields 与关联 Event 示例、字段扩展和 regression checks 见[开发规范](../../development/observability.md)。 -JSON 和 console logs 使用相同的 operational field allowlist,未登记的 extras 不会输出。 -两种格式都保留 application/transport 的结果与错误诊断,以及嵌套事件(包括 code stage)的 worker 关联字段。 -Code 专用诊断字段仅在 `code.*` events 中输出。 +JSON 和 console logs 使用相同的 operational field allowlist,未登记的 extras 不会输出。两种格式都保留 application/transport 的结果与错误诊断,以及嵌套事件(包括 code stage)的 worker 关联字段。 Code 专用诊断字段仅在 `code.*` events 中输出。 | 字段 | 含义 | | --- | --- | @@ -63,81 +57,29 @@ Code 专用诊断字段仅在 `code.*` events 中输出。 | `duration_ms`、`error_code`、`error_category` | 毫秒耗时、诊断 code 和有限取值的 operational error category | | `stage`、`processing_stage`、`failure_reason`、`input_item_count`、`estimated_input_tokens`、`token_estimator_id`、`effective_budget`、`provider_request_id`、`finish_reason`、`failure_location`、`cause_exception_type` | 处理失败 stage/reason 与安全计数字段;`stage` 表示发出失败的位置或领域位置(Worker/supervisor stage、领域 block 名称或 `worker` 兜底),`processing_stage` 表示有界的领域阶段。详见 [处理失败诊断](../../development/processing-failures.md) | -Server role 为 `all`(API 与 supervisor)、`api` 或 `background`,child process 使用 `worker`。 -显式配置 logging 但没有指定 deployment role 时使用 `server`。JSON identity 字段对应 trace resource attributes: -`service.name`、`service.version`、`service.instance.id` 和 `powercontext.service.role`。 -未安装 distribution metadata(例如源码 checkout 或 frozen bundle)时省略 `service_version`。 -新进程获得新的 instance ID,worker retry 获得新的 `worker_id`。这些 execution identifiers 不作为 metric labels。 - -嵌套 request logs 自动继承 request ID,event 显式提供 ID 时保留该值。Scheduled processing 不继承 supervisor -启动时偶然存在的 request ID,包括 supervisor control logs。关闭 recording 后仍可能有 trace ID, -但它不能证明 backend 保存了 trace。 -配置 child logging 本身也不等于完成了跨进程 trace propagation。 - -常用 outcome 为 `success`、`failure`、`cancelled` 和 `noop`。Admission block 使用 `blocked`,不记为 success 或 failure。 -Worker 遇到持久处理阻塞时,以 `WARNING` 级别输出 `artifact_processing.worker.blocked`, -outcome 和 error_category 均为 `blocked`,并保留阻塞的诊断代码和 stage。 -Topic 阻塞的 `source_after` 和已知的 `source_through` 表示 Source journal 位置。准确选择终点未知时,阻塞日志 -省略 `source_through`,仍保留尝试、请求和 token 计数。 -Worker control result 还可以是 `cursor_conflict`、 -`head_conflict` 或 `leadership_lost`。`artifact_processing.worker.returned` 表示 child 返回了结果; -`artifact_processing.worker.acknowledged` 表示 supervisor 验证了 durable acknowledgement。 -Child 返回结果不能单独证明业务完成。强制终止进程可能来不及输出 child terminal event, -此时通过 supervisor 的 interruption 或 failure 诊断。 - -不适用时省略 `error_category`。其取值为 `authentication`、`authorization`、`configuration`、`rate_limit`、 -`dependency`、`timeout`、`not_found`、`conflict`、`invalid_request`、`internal`、`cancelled` 和 `blocked`。 -Server spans 在 `powercontext.error.category` 中使用相同词汇,各 boundary 根据实际观察的结果分类。 -已有诊断 code 继续保留,供进一步排查。 -Supervisor 的 worker 和 wait spans 在跨进程后保留 child 的有限错误分类。 -策略阻塞与 child 取消分别使用 `blocked` 和 `cancelled` outcome,不设置 error span status; -模型失败保留 timeout、configuration 或 dependency 分类。 -启用流式聚合(`POWERCONTEXT_SERVER_INFERENCE_GENERATION_STREAMING=auto`)时,`unit` 为 `inference` 的 -`inference.generation.usage_missing` WARNING 表示一次 generation 请求成功完成、但 provider 未随流返回 usage, -该请求的用量统计会缺失。该事件不携带 prompt 或响应内容,也不影响本次请求的结果。 -`auto` 已设置且模型名前缀不属于 `anthropic`、`openai`、`openai-chat`、`openai-responses` 时,`unit` 为 -`inference` 的 `inference.generation.streaming_not_applied` WARNING 表示该模型仍走非流式请求。该事件不携带 -prompt 或响应内容,也不改变本次请求的结果。 -Child 取消时,supervisor 以 `INFO` 级别输出 `artifact_processing.failed`,outcome/category 为 `cancelled`, -诊断代码为 `worker_cancelled`。Application spans 根据已映射的诊断代码分类, -即使敏感 exception values 已从 logs 和 traces 中排除,也保留正确分类。 - -`DEBUG` 级别的 `code.*` events 保留 `seconds`,并增加 `duration_ms`。其 `operation` 为 stage name(`code.`), -与 span identity 一致;已有的 requested query kind 改放在 `code_operation`。Code diagnostics 可以包含 `selected_count`、 -`hit_count`、`hit_count_is_lower_bound`、`cache_bytes`、`status`、`limitations` 和 `reason`。 -操作系统支持时,`process_lifetime_max_rss_bytes` 与 `children_lifetime_max_rss_bytes` 表示 process lifetime -的 RSS high-water mark,单位为 bytes。它们不是单次 request allocation,也不是同一时刻的 process-tree 总量,不能相加。 -失败的 code stage 保留诊断 `error_code`;领域错误还保留 `status_code`。日志与 span 使用这些值区分超时、冲突、 -无效请求和内部故障。 - -Server 创建的 workers 使用配置的 log level 和 format。通过 SDK 导入或运行 Runtime 时不配置 global logging, -由 embedding application 管理 logging。Logging bootstrap 失败不会使 processing 失败。 -Formatting 或写入失败时,Server handler 向 stderr 输出无内容的 `observability.log_failed` 通知,每个 handler -最多输出一次,不会转储失败 record。Operational logs 保持 best-effort,不作为 durable audit 或 billing ledger。 -Identity 和 error 字段为新增字段;console 行现在包含 identity。 +Server role 为 `all`(API 与 supervisor)、`api` 或 `background`,child process 使用 `worker`。显式配置 logging 但没有指定 deployment role 时使用 `server`。JSON identity 字段对应 trace resource attributes: `service.name`、`service.version`、`service.instance.id` 和 `powercontext.service.role`。未安装 distribution metadata(例如源码 checkout 或 frozen bundle)时省略 `service_version`。新进程获得新的 instance ID,worker retry 获得新的 `worker_id`。这些 execution identifiers 不作为 metric labels。 + +嵌套 request logs 自动继承 request ID,event 显式提供 ID 时保留该值。Scheduled processing 不继承 supervisor 启动时偶然存在的 request ID,包括 supervisor control logs。关闭 recording 后仍可能有 trace ID,但它不能证明 backend 保存了 trace。配置 child logging 本身也不等于完成了跨进程 trace propagation。 + +常用 outcome 为 `success`、`failure`、`cancelled` 和 `noop`。Admission block 使用 `blocked`,不记为 success 或 failure。 Worker 遇到持久处理阻塞时,以 `WARNING` 级别输出 `artifact_processing.worker.blocked`, outcome 和 error_category 均为 `blocked`,并保留阻塞的诊断代码和 stage。 Topic 阻塞的 `source_after` 和已知的 `source_through` 表示 Source journal 位置。准确选择终点未知时,阻塞日志省略 `source_through`,仍保留尝试、请求和 token 计数。 Worker control result 还可以是 `cursor_conflict`、 `head_conflict` 或 `leadership_lost`。`artifact_processing.worker.returned` 表示 child 返回了结果; `artifact_processing.worker.acknowledged` 表示 supervisor 验证了 durable acknowledgement。 Child 返回结果不能单独证明业务完成。强制终止进程可能来不及输出 child terminal event,此时通过 supervisor 的 interruption 或 failure 诊断。 + +不适用时省略 `error_category`。其取值为 `authentication`、`authorization`、`configuration`、`rate_limit`、 `dependency`、`timeout`、`not_found`、`conflict`、`invalid_request`、`internal`、`cancelled` 和 `blocked`。 Server spans 在 `powercontext.error.category` 中使用相同词汇,各 boundary 根据实际观察的结果分类。已有诊断 code 继续保留,供进一步排查。 Supervisor 的 worker 和 wait spans 在跨进程后保留 child 的有限错误分类。策略阻塞与 child 取消分别使用 `blocked` 和 `cancelled` outcome,不设置 error span status;模型失败保留 timeout、configuration 或 dependency 分类。启用流式聚合(`POWERCONTEXT_SERVER_INFERENCE_GENERATION_STREAMING=auto`)时,`unit` 为 `inference` 的 `inference.generation.usage_missing` WARNING 表示一次 generation 请求成功完成、但 provider 未随流返回 usage,该请求的用量统计会缺失。该事件不携带 prompt 或响应内容,也不影响本次请求的结果。 `auto` 已设置且模型名前缀不属于 `anthropic`、`openai`、`openai-chat`、`openai-responses` 时,`unit` 为 `inference` 的 `inference.generation.streaming_not_applied` WARNING 表示该模型仍走非流式请求。该事件不携带 prompt 或响应内容,也不改变本次请求的结果。 Child 取消时,supervisor 以 `INFO` 级别输出 `artifact_processing.failed`,outcome/category 为 `cancelled`,诊断代码为 `worker_cancelled`。Application spans 根据已映射的诊断代码分类,即使敏感 exception values 已从 logs 和 traces 中排除,也保留正确分类。 + +`DEBUG` 级别的 `code.*` events 保留 `seconds`,并增加 `duration_ms`。其 `operation` 为 stage name(`code.`),与 span identity 一致;已有的 requested query kind 改放在 `code_operation`。Code diagnostics 可以包含 `selected_count`、 `hit_count`、`hit_count_is_lower_bound`、`cache_bytes`、`status`、`limitations` 和 `reason`。操作系统支持时,`process_lifetime_max_rss_bytes` 与 `children_lifetime_max_rss_bytes` 表示 process lifetime 的 RSS high-water mark,单位为 bytes。它们不是单次 request allocation,也不是同一时刻的 process-tree 总量,不能相加。失败的 code stage 保留诊断 `error_code`;领域错误还保留 `status_code`。日志与 span 使用这些值区分超时、冲突、 无效请求和内部故障。 + +Server 创建的 workers 使用配置的 log level 和 format。通过 SDK 导入或运行 Runtime 时不配置 global logging,由 embedding application 管理 logging。Logging bootstrap 失败不会使 processing 失败。 Formatting 或写入失败时,Server handler 向 stderr 输出无内容的 `observability.log_failed` 通知,每个 handler 最多输出一次,不会转储失败 record。Operational logs 保持 best-effort,不作为 durable audit 或 billing ledger。 Identity 和 error 字段为新增字段;console 行现在包含 identity。 ## 指标与就绪状态 -默认通过 `/metrics` 输出 Prometheus 格式指标。在 `enforced` 模式下,`/metrics` 与 `capabilities` 需要 -具备 `server.observe` 权限的 Principal 认证,参见[诊断与恢复](troubleshoot.md)。API 宿主的 -`/health/live` 与 `/health/ready` 保持公开。 +默认通过 `/metrics` 输出 Prometheus 格式指标。在 `enforced` 模式下,`/metrics` 与 `capabilities` 需要具备 `server.observe` 权限的 Principal 认证,参见[诊断与恢复](troubleshoot.md)。API 宿主的 `/health/live` 与 `/health/ready` 保持公开。 -`background` 角色使用 `POWERCONTEXT_SERVER_HTTP_HOST` 和 `POWERCONTEXT_SERVER_METRICS_BACKGROUND_PORT` -(默认 `8001`)提供 `/metrics` 和公开的 `/health/live`。指标认证与授权规则和 API 宿主一致, -不提供业务 API、MCP、Dashboard、OpenAPI 或 `/health/ready`。 -API 与后台进程同机部署时应使用不同端口。设置 `POWERCONTEXT_SERVER_METRICS_ENABLED=false` 会移除 `/metrics`; -对 `background` 还会阻止启动 listener。抓取后台指标不会执行 API 宿主的模型就绪探测。 +`background` 角色使用 `POWERCONTEXT_SERVER_HTTP_HOST` 和 `POWERCONTEXT_SERVER_METRICS_BACKGROUND_PORT` (默认 `8001`)提供 `/metrics` 和公开的 `/health/live`。指标认证与授权规则和 API 宿主一致,不提供业务 API、MCP、Dashboard、OpenAPI 或 `/health/ready`。 API 与后台进程同机部署时应使用不同端口。设置 `POWERCONTEXT_SERVER_METRICS_ENABLED=false` 会移除 `/metrics`;对 `background` 还会阻止启动 listener。抓取后台指标不会执行 API 宿主的模型就绪探测。 ### 被动观察与新鲜度 -指标采集只复制 Runtime/Supervisor 已有的、有界的进程内观察。采集不查询数据库、不扫描积压、不刷新就绪状态、 -不调用模型,也不等待 Worker;端点的认证与授权仍可能执行有界的数据库读取。后台 pending 观察、发现和就绪检查 -独立于抓取产生观察。因此,抓取成功既不能证明依赖当前健康,也不能证明积压数据足够新;抓取不会调用模型。 +指标采集只复制 Runtime/Supervisor 已有的、有界的进程内观察。采集不查询数据库、不扫描积压、不刷新就绪状态、 不调用模型,也不等待 Worker;端点的认证与授权仍可能执行有界的数据库读取。后台 pending 观察、发现和就绪检查独立于抓取产生观察。因此,抓取成功既不能证明依赖当前健康,也不能证明积压数据足够新;抓取不会调用模型。 -下表指标名均以 `powercontext_server_` 开头。时间戳单位为 UNIX 秒,耗时和年龄单位为秒;计数单位见各行。 -状态指标采用 one-hot 表示:当前 `state` 为 `1`,其他支持的状态为 `0`。缺少观察不等于健康的零值。 -计数器与直方图桶在所属进程或 Runtime/Supervisor 实例生命周期内累计,实例重建时重置,抓取不会重置。 -应使用能处理重置的 `rate`/`increase`,并保留 `instance` 和部署身份等抓取目标标签。 +下表指标名均以 `powercontext_server_` 开头。时间戳单位为 UNIX 秒,耗时和年龄单位为秒;计数单位见各行。状态指标采用 one-hot 表示:当前 `state` 为 `1`,其他支持的状态为 `0`。缺少观察不等于健康的零值。计数器与直方图桶在所属进程或 Runtime/Supervisor 实例生命周期内累计,实例重建时重置,抓取不会重置。应使用能处理重置的 `rate`/`increase`,并保留 `instance` 和部署身份等抓取目标标签。 | 指标后缀 | 标签与含义 | | --- | --- | @@ -156,28 +98,13 @@ API 与后台进程同机部署时应使用不同端口。设置 `POWERCONTEXT_S | `telemetry_collection_failures_total` | 被动采集失败次数;失败保留先前观察 | | `telemetry_log_records_dropped_total` | 进程自有 handler 或 Worker 接收端确认未能交付的记录数;干净的 EOF/reset 不计入丢失,未观测到的丢失不计数 | -详细探测观察覆盖 `database`、`inference.generation`、`inference.rerank`、`inference.decision` 和 -`inference.embedding`。同一 `dependency_state` 指标还包含有界总体检查:`runtime`、 -`artifact_processing_supervisor`、已注册的 `artifact_processing.`、`access_provider` 和 -`authentication_provider`。同名依赖优先采用详细 Runtime 快照,每个依赖只输出一组 one-hot 状态。 -探测时间戳和耗时仍表示实际探测,不是总体评估时间。禁用依赖没有探测时间戳或样本。 -探测结果为 `ready`、`unavailable`、`timeout`、 -`misconfigured` 或 `cancelled`;取消只增加耗时观察,不替换最近完成的状态与时间戳。 -缓存命中既不更新实际探测时间戳,也不增加直方图计数。每个样本代表一次完整的探测刷新;提供方内部重试 -(若有)包含在这次耗时中,不计为独立网络尝试。内置缓存通常保留结果 300 秒,`timeout`/`unavailable` -保留 30 秒;仅缓存到期不会自动执行探测。总体评估时间、实际探测时间、快照采集时间和 Prometheus 抓取时间 -分别回答不同的新鲜度问题。 - -`runtime_ready=1` 可以与 `degraded` 并存,只表示可以接收操作。结合 `runtime_readiness_state`、依赖状态及 -新鲜度判断,也可通过 `powercontext ready` 和 `powercontext capabilities` 区分数据库不可用与可选模型故障。 -后台进程在启用指标时于启动阶段及每 30 秒评估就绪状态;`/metrics` 本身不触发探测。 -首次评估完成前,或不执行就绪评估的嵌入式应用中,`unobserved` 是有效状态。 +详细探测观察覆盖 `database`、`inference.generation`、`inference.rerank`、`inference.decision` 和 `inference.embedding`。同一 `dependency_state` 指标还包含有界总体检查:`runtime`、 `artifact_processing_supervisor`、已注册的 `artifact_processing.`、`access_provider` 和 `authentication_provider`。同名依赖优先采用详细 Runtime 快照,每个依赖只输出一组 one-hot 状态。探测时间戳和耗时仍表示实际探测,不是总体评估时间。禁用依赖没有探测时间戳或样本。探测结果为 `ready`、`unavailable`、`timeout`、 `misconfigured` 或 `cancelled`;取消只增加耗时观察,不替换最近完成的状态与时间戳。缓存命中既不更新实际探测时间戳,也不增加直方图计数。每个样本代表一次完整的探测刷新;提供方内部重试(若有)包含在这次耗时中,不计为独立网络尝试。内置缓存通常保留结果 300 秒,`timeout`/`unavailable` 保留 30 秒;仅缓存到期不会自动执行探测。总体评估时间、实际探测时间、快照采集时间和 Prometheus 抓取时间分别回答不同的新鲜度问题。 + +`runtime_ready=1` 可以与 `degraded` 并存,只表示可以接收操作。结合 `runtime_readiness_state`、依赖状态及新鲜度判断,也可通过 `powercontext ready` 和 `powercontext capabilities` 区分数据库不可用与可选模型故障。后台进程在启用指标时于启动阶段及每 30 秒评估就绪状态;`/metrics` 本身不触发探测。首次评估完成前,或不执行就绪评估的嵌入式应用中,`unobserved` 是有效状态。 ### 后台处理指标 -下表后缀均以 `powercontext_server_artifact_processing_` 开头。逐 Family 指标使用 `family` 标签,额外标签 -在表中注明。只导出已注册且名称合法的 Family。Scope、Worker、请求、Trace、内容、Provider 错误文本或 -数据库 URL 均不作为指标标签。 +下表后缀均以 `powercontext_server_artifact_processing_` 开头。逐 Family 指标使用 `family` 标签,额外标签在表中注明。只导出已注册且名称合法的 Family。Scope、Worker、请求、Trace、内容、Provider 错误文本或数据库 URL 均不作为指标标签。 | 指标后缀 | 含义 | | --- | --- | @@ -201,88 +128,42 @@ API 与后台进程同机部署时应使用不同端口。设置 `POWERCONTEXT_S | `retries_total` | 额外 `reason`:`failure`、`conflict`、`blocked`;重试调度决策数,包含阻塞复查与溢出 | | `admission_blocks_total` | 观察到的准入阻塞决策数;重复决策可再次计数 | -持久 pending 观察周期性运行,独立于 Worker 容量,默认间隔 30 秒,每次观察的截止时限为 2 秒。 -即使所有 Worker 槽位占满也不会暂停这项观察。失败保留最近成功的快照,并增加 `pending_observation_failures_total`; -新的采集或抓取不能让旧快照变新。这些读取在后台执行,不在指标采集时执行。 +持久 pending 观察周期性运行,独立于 Worker 容量,默认间隔 30 秒,每次观察的截止时限为 2 秒。即使所有 Worker 槽位占满也不会暂停这项观察。失败保留最近成功的快照,并增加 `pending_observation_failures_total`;新的采集或抓取不能让旧快照变新。这些读取在后台执行,不在指标采集时执行。 -pending 快照读取已有的 processing intents,统计该 binding 的 pending Scope 数。不为每个请求 generation -保存时间戳,也不需要新表或 schema 迁移。查询工作量随该 binding 的 intents 数增长;保留的聚合快照占用 -O(Families) 内存。首次成功观察前,快照时间戳为零表示未观察,即使计数指标也为零。 -重启或 Leader 切换后需要新的观察;不能把保留或缺失的测量值当作当前持久积压的事实。 +pending 快照读取已有的 processing intents,统计该 binding 的 pending Scope 数。不为每个请求 generation 保存时间戳,也不需要新表或 schema 迁移。查询工作量随该 binding 的 intents 数增长;保留的聚合快照占用 O(Families) 内存。首次成功观察前,快照时间戳为零表示未观察,即使计数指标也为零。重启或 Leader 切换后需要新的观察;不能把保留或缺失的测量值当作当前持久积压的事实。 -`oldest_observed_pending_age_seconds` 是近似的**本地下界**,从首次本地观察最多 1000 个保留的已准入 key 起计算。 -它跟踪本地观察到的 pending generation,不是请求创建时间或精确的持久积压年龄。 -两次发现之间 pending 集合可能陈旧,而本地年龄仍在增长。未观察的 key 可能更老;确认或淘汰可能移除本地观察。 -重启与 Leader 切换会重置这段本地历史。本地年龄为 `0` 不能证明持久积压为空,较大的值也不能单独说明停滞: -处理过程可能仍在取得已验证的确认进展。应结合 pending 证据、快照新鲜度、已验证的确认进展和启动宽限期判断。 +`oldest_observed_pending_age_seconds` 是近似的**本地下界**,从首次本地观察最多 1000 个保留的已准入 key 起计算。它跟踪本地观察到的 pending generation,不是请求创建时间或精确的持久积压年龄。两次发现之间 pending 集合可能陈旧,而本地年龄仍在增长。未观察的 key 可能更老;确认或淘汰可能移除本地观察。重启与 Leader 切换会重置这段本地历史。本地年龄为 `0` 不能证明持久积压为空,较大的值也不能单独说明停滞:处理过程可能仍在取得已验证的确认进展。应结合 pending 证据、快照新鲜度、已验证的确认进展和启动宽限期判断。 -Attempt outcome 为 `success`、`hold`、`noop`、`failure`、`cancelled`、`blocked`、`cursor_conflict`、 -`head_conflict`、`leadership_lost`。Discovery outcome 为 `success`、`failure`、`cancelled`、`leadership_lost`。 -耗时直方图输出 `_bucket`、`_count`、`_sum`;桶边界为 0.005、0.01、0.025、0.05、0.1、0.25、0.5、1、2.5、5、 -10、30、60 和 `+Inf` 秒。`_count` 统计 attempt/发现次数,不统计唯一请求或业务成功数;一次重试增加一次 attempt。 -`hold` 和 `noop` 与业务成功分开。原有 `completed_total` 统计已验证持久确认的调用,可能包含已确认的 hold/noop, -不是 attempt-success 或产出 Artifact 的计数器。直方图与确认计数器都不是计费账本。 +Attempt outcome 为 `success`、`hold`、`noop`、`failure`、`cancelled`、`blocked`、`cursor_conflict`、 `head_conflict`、`leadership_lost`。Discovery outcome 为 `success`、`failure`、`cancelled`、`leadership_lost`。耗时直方图输出 `_bucket`、`_count`、`_sum`;桶边界为 0.005、0.01、0.025、0.05、0.1、0.25、0.5、1、2.5、5、 10、30、60 和 `+Inf` 秒。`_count` 统计 attempt/发现次数,不统计唯一请求或业务成功数;一次重试增加一次 attempt。 `hold` 和 `noop` 与业务成功分开。原有 `completed_total` 统计已验证持久确认的调用,可能包含已确认的 hold/noop,不是 attempt-success 或产出 Artifact 的计数器。直方图与确认计数器都不是计费账本。 ### Dashboard 与告警规则 -运维方应明确选择并记录抓取失败、快照采集年龄、探测年龄、请求快照年龄、启动宽限期和未确认时长的阈值。 -这些是部署专用的告警策略,不是内置默认值。例如可选择采集新鲜度 120 秒、探测新鲜度 600 秒、存在 pending work -时超过 900 秒未确认;必须根据抓取频率、就绪检查流量、调度间隔和 Worker 预期耗时验证这些选择。 -不执行探测的宿主不应直接套用 600 秒探测规则。 - -- 先检查 Prometheus `up`、采集新鲜度和采集失败。采集失败后,即使抓取很新,返回的仍可能是旧快照。 - 缺失或为零的时间戳需要单独的未观察分支,不能与陈旧数据混为一谈 -- 依赖告警应以已观察且足够新的状态为前提。分别处理 `disabled`、`unobserved`、陈旧、降级和不可用; - 可选模型故障不应自动触发数据库故障级别的告警 -- 将停止处理与运行停滞分开。在采集足够新、`supervisor_present=1` 且 `supervisor_running=0` 时, - 若本地保留工作或足够新的 `unacknowledged_requests>0` 快照证明存在 pending work,应触发停止处理告警, - 不能要求此规则满足运行中 Leader 条件。若只有陈旧的最后已知 pending 证据,应报告处理已停止但积压未知并排查; - 抓取目标失联则通过 `up` 单独处理 -- 对运行中的 Leader,疑似停滞告警要求足够新的采集,以及 pending work 证据:当前 - `observed_pending_scopes>0`、`used_workers>0`,或同一目标/Family 的 - `requested_snapshot_timestamp_seconds` 非零且足够新,同时 `unacknowledged_requests>0`。 - 要求在所选时间窗口内持续存在 pending work 且没有已验证的确认进展,并在重启或 Leader 切换后留出启动宽限期。 - 使用 `last_acknowledgement_timestamp_seconds` 和 `completed_total` 的变化判断已验证进展;进程退出或成功 attempt - 的耗时不代表确认。例如,启动宽限期后持续 900 秒存在 pending 证据且没有确认,可提示疑似停滞; - 确认仍在推进时,本地观察到的旧 key 不能说明停滞。 - 确认时间为零表示从未确认,不是从 UNIX 纪元起故障;应使用宽限期与持续观察窗口,不能用当前时间减零。 - 比较时间戳时应考虑时钟偏差,不能把缺失的观察当作零 -- Worker 槽位占满时持久 pending 观察仍会继续,但观察失败可能使数据陈旧。陈旧快照不能压制由当前本地工作证据 - 和缺少已验证进展共同支持的疑似停滞告警。持久计数是最后已知的后台观察;本地保留 key 与 Worker 槽位不是全量持久积压。 - `oldest_observed_pending_age_seconds` 仅提供辅助上下文,不能独立触发停滞告警,也不能替代确认进展和新鲜度判断 -- 健康空闲实例不应告警。禁用自动处理是配置,Standby 是预期角色,纯 API 缺失 Supervisor 数据不是零容量故障。 - 没有当前本地证据的陈旧 pending 快照应触发新鲜度诊断,不能据此编造积压结论。结合阻塞等待、准入阻塞、重试原因、错误与 Worker 利用率排查 -- 分别抓取 API 与后台目标。同一部署/Family 的 API 与后台积压快照、Leader 与 Standby 计数不能相加。 - 积压与容量面板选取当前运行的 Leader;跨 Family 汇总仍保留部署/group 边界。计数器速率属于各进程, - 角色切换时可能需要汇总,但不能将同一目标重复抓取后计入同一总量 -- 监控 pending 观察失败、采集失败与日志丢弃计数的增长。此处不支持 OTLP SDK 队列占用和 exporter 丢弃计数;缺失表示不可用的遥测, - 不是零压力或零丢失。排查 Trace 交付时应查看 Collector/backend 自身诊断 +运维方应明确选择并记录抓取失败、快照采集年龄、探测年龄、请求快照年龄、启动宽限期和未确认时长的阈值。这些是部署专用的告警策略,不是内置默认值。例如可选择采集新鲜度 120 秒、探测新鲜度 600 秒、存在 pending work 时超过 900 秒未确认;必须根据抓取频率、就绪检查流量、调度间隔和 Worker 预期耗时验证这些选择。不执行探测的宿主不应直接套用 600 秒探测规则。 + +- 先检查 Prometheus `up`、采集新鲜度和采集失败。采集失败后,即使抓取很新,返回的仍可能是旧快照。 缺失或为零的时间戳需要单独的未观察分支,不能与陈旧数据混为一谈 +- 依赖告警应以已观察且足够新的状态为前提。分别处理 `disabled`、`unobserved`、陈旧、降级和不可用; 可选模型故障不应自动触发数据库故障级别的告警 +- 将停止处理与运行停滞分开。在采集足够新、`supervisor_present=1` 且 `supervisor_running=0` 时, 若本地保留工作或足够新的 `unacknowledged_requests>0` 快照证明存在 pending work,应触发停止处理告警, 不能要求此规则满足运行中 Leader 条件。若只有陈旧的最后已知 pending 证据,应报告处理已停止但积压未知并排查; 抓取目标失联则通过 `up` 单独处理 +- 对运行中的 Leader,疑似停滞告警要求足够新的采集,以及 pending work 证据:当前 `observed_pending_scopes>0`、`used_workers>0`,或同一目标/Family 的 `requested_snapshot_timestamp_seconds` 非零且足够新,同时 `unacknowledged_requests>0`。 要求在所选时间窗口内持续存在 pending work 且没有已验证的确认进展,并在重启或 Leader 切换后留出启动宽限期。 使用 `last_acknowledgement_timestamp_seconds` 和 `completed_total` 的变化判断已验证进展;进程退出或成功 attempt 的耗时不代表确认。例如,启动宽限期后持续 900 秒存在 pending 证据且没有确认,可提示疑似停滞; 确认仍在推进时,本地观察到的旧 key 不能说明停滞。 确认时间为零表示从未确认,不是从 UNIX 纪元起故障;应使用宽限期与持续观察窗口,不能用当前时间减零。 比较时间戳时应考虑时钟偏差,不能把缺失的观察当作零 +- Worker 槽位占满时持久 pending 观察仍会继续,但观察失败可能使数据陈旧。陈旧快照不能压制由当前本地工作证据 和缺少已验证进展共同支持的疑似停滞告警。持久计数是最后已知的后台观察;本地保留 key 与 Worker 槽位不是全量持久积压。 `oldest_observed_pending_age_seconds` 仅提供辅助上下文,不能独立触发停滞告警,也不能替代确认进展和新鲜度判断 +- 健康空闲实例不应告警。禁用自动处理是配置,Standby 是预期角色,纯 API 缺失 Supervisor 数据不是零容量故障。 没有当前本地证据的陈旧 pending 快照应触发新鲜度诊断,不能据此编造积压结论。结合阻塞等待、准入阻塞、重试原因、错误与 Worker 利用率排查 +- 分别抓取 API 与后台目标。同一部署/Family 的 API 与后台积压快照、Leader 与 Standby 计数不能相加。 积压与容量面板选取当前运行的 Leader;跨 Family 汇总仍保留部署/group 边界。计数器速率属于各进程, 角色切换时可能需要汇总,但不能将同一目标重复抓取后计入同一总量 +- 监控 pending 观察失败、采集失败与日志丢弃计数的增长。此处不支持 OTLP SDK 队列占用和 exporter 丢弃计数;缺失表示不可用的遥测, 不是零压力或零丢失。排查 Trace 交付时应查看 Collector/backend 自身诊断 端点配置参见[配置选项](configuration.md),恢复步骤参见[诊断与恢复](troubleshoot.md)。 ## Tracing -安装 `tracing-otlp` extra,启用 `POWERCONTEXT_SERVER_TRACING_ENABLED=true`,并配置 OTLP HTTP 接收端。 -完整步骤见 [Phoenix](trace-with-phoenix.md) 或 [Langfuse](trace-with-langfuse.md)。 -缺少 extra 时启用 Tracing 会导致启动失败。PowerContext 跟踪自身的传输、应用和模型调用, -不会自动采集宿主中无关的模型调用。Model span 关闭自动 exception event 和 status description, -避免 provider error body 导出 Source、prompt 或 response 内容;仅保留有界的 `error.type` 和 error status。 +先安装 `tracing-otlp` extra,再设置 `POWERCONTEXT_SERVER_TRACING_ENABLED=true` 并配置 OTLP HTTP 接收端。具体步骤见 [Phoenix](trace-with-phoenix.md) 或 [Langfuse](trace-with-langfuse.md)。缺少该依赖时启用追踪,Server 会启动失败。PowerContext 追踪自身的传输、应用和模型调用,不会自动采集宿主应用中的其他模型调用。模型调用失败时,Trace 记录 `error.type` 和错误状态,不记录可能携带 Source、prompt 或 response 内容的模型服务错误正文、堆栈或状态描述。异常事件仅包含 `exception.type` 和 `exception.escaped`。 -使用环境文件部署时,将 Tracing 与 OpenTelemetry 变量写入传给 Server 的显式文件。 -优先级规则见[环境配置](../get-started/configure-server-environment.md)。 +使用环境文件部署时,将 Tracing 与 OpenTelemetry 变量写入传给 Server 的显式文件。优先级规则见[环境配置](../get-started/configure-server-environment.md)。 ### Background service 与 observation freshness 拆分 API/background roles 需要 OceanBase。SQLite 和 embedded seekdb 继续使用 `all` role。 -`background` role 在 `HTTP_HOST` 和独立的 `POWERCONTEXT_SERVER_METRICS_BACKGROUND_PORT`(默认 `8001`)上 -只提供 `/health/live`、`/metrics`,不提供 business API、MCP、dashboard 或 OpenAPI。API/all roles 继续使用原 HTTP -端口。关闭 `METRICS_ENABLED` 也会关闭 background HTTP listener。认证和 `server.observe` 授权复用 API metrics 的 -Server profile;非 loopback bind 遵循现有 Server 策略。同一 host 部署多个进程时,请在 background 环境文件中配置独立端口。 +`background` role 在 `HTTP_HOST` 和独立的 `POWERCONTEXT_SERVER_METRICS_BACKGROUND_PORT`(默认 `8001`)上只提供 `/health/live`、`/metrics`,不提供 business API、MCP、dashboard 或 OpenAPI。API/all roles 继续使用原 HTTP 端口。关闭 `METRICS_ENABLED` 也会关闭 background HTTP listener。认证和 `server.observe` 授权复用 API metrics 的 Server profile;非 loopback bind 遵循现有 Server 策略。同一 host 部署多个进程时,请在 background 环境文件中配置独立端口。 -启用 metrics 后,readiness 在启动时及每 30 秒评估一次。Scrape 不调用模型、不 ping 数据库,也不刷新 readiness。 -Inference probe 保留原有正常结果 300 秒、临时失败 30 秒的缓存。`readiness_evaluated_timestamp_seconds` 表示 aggregate -评估时间,不能解释为每个 provider 都刚完成了一次真实请求,也不表示单个 cached probe 的数据年龄。 +启用 metrics 后,readiness 在启动时及每 30 秒评估一次。Scrape 不调用模型、不 ping 数据库,也不刷新 readiness。 Inference probe 保留原有正常结果 300 秒、临时失败 30 秒的缓存。`readiness_evaluated_timestamp_seconds` 表示 aggregate 评估时间,不能解释为每个 provider 都刚完成了一次真实请求,也不表示单个 cached probe 的数据年龄。 | Metric(前缀 `powercontext_server_`) | 含义 | | --- | --- | @@ -300,37 +181,15 @@ Inference probe 保留原有正常结果 300 秒、临时失败 30 秒的缓存 | `model_usage_worker_reports_total{outcome}` | 收到 recorder 计数的 `received` attempt,以及缺少观察的 `missing` attempt;missing 不表示零丢失 | | `metrics_collection_failures_total` | Processing snapshot 刷新失败次数;失败时可能保留上一次 snapshot | -Processing timestamp 为 `0` 表示尚未发生该观察。计数、histogram 和 timestamp 属于当前 process/supervisor 生命周期, -重启或移除后会 reset 或消失。Pending timestamp 只提供本地已观察工作的 age lower bound,不代表最早的持久化 Source -或全库 backlog;尚未发现的工作、retry-cache eviction 和重启都可能让历史不可见。应结合 backlog 和 observation freshness -解释。健康的 idle worker 不要求近期有 success;progress alert 应同时检查存在 pending work,policy block 要单独处理。 -Invocation outcomes 为 `success`、`failure`、`blocked`、`cancelled`、`conflict`、`timeout`;等待 leadership cleanup 的保留 slot -不会被重复统计为已完成 reap。 - -Processing labels 仅使用已注册 family 和有界 outcome,不包含 scope/worker/request identity。Scrape 只读取内存 snapshot; -ready/retry/running 观察工作量受 scheduler limits 限制,不随数据库总记录数增长。内置 spawn worker 在 recorder 关闭后, -通过成功或失败结果回传两个累计丢失计数。所属 supervisor 每个 attempt 只累计一次,不依赖 acknowledgement 或 tracing。 -一个 child invocation 内创建的多个 recorder 会合并为同一份 report;scrape 不会重复计数。 -Endpoint 不提供 child queue depth/capacity 的实时值。运行中的 child 尚未上报;崩溃、强制终止,或从未观察到 recorder 的 -invocation 记录为 `missing`,不能当作零丢失。该投影不持久化,父进程重启或 child report 丢失会造成观察缺口。 -Custom launcher 需自行连接 report 与 observer;API-only 进程无法观察另一个 background service 的 children。 -应采集各 API/background targets,并通过 target labels 区分 -role/instance。Target 或 sample 缺失不等于零故障;不要把各进程 snapshot 相加当作持久化总账。 +Processing timestamp 为 `0` 表示尚未发生该观察。计数、histogram 和 timestamp 属于当前 process/supervisor 生命周期,重启或移除后会 reset 或消失。Pending timestamp 只提供本地已观察工作的 age lower bound,不代表最早的持久化 Source 或全库 backlog;尚未发现的工作、retry-cache eviction 和重启都可能让历史不可见。应结合 backlog 和 observation freshness 解释。健康的 idle worker 不要求近期有 success;progress alert 应同时检查存在 pending work,policy block 要单独处理。 Invocation outcomes 为 `success`、`failure`、`blocked`、`cancelled`、`conflict`、`timeout`;等待 leadership cleanup 的保留 slot 不会被重复统计为已完成 reap。 + +Processing labels 仅使用已注册 family 和有界 outcome,不包含 scope/worker/request identity。Scrape 只读取内存 snapshot; ready/retry/running 观察工作量受 scheduler limits 限制,不随数据库总记录数增长。内置 spawn worker 在 recorder 关闭后,通过成功或失败结果回传两个累计丢失计数。所属 supervisor 每个 attempt 只累计一次,不依赖 acknowledgement 或 tracing。一个 child invocation 内创建的多个 recorder 会合并为同一份 report;scrape 不会重复计数。 Endpoint 不提供 child queue depth/capacity 的实时值。运行中的 child 尚未上报;崩溃、强制终止,或从未观察到 recorder 的 invocation 记录为 `missing`,不能当作零丢失。该投影不持久化,父进程重启或 child report 丢失会造成观察缺口。 Custom launcher 需自行连接 report 与 observer;API-only 进程无法观察另一个 background service 的 children。应采集各 API/background targets,并通过 target labels 区分 role/instance。Target 或 sample 缺失不等于零故障;不要把各进程 snapshot 相加当作持久化总账。 ### Worker execution traces 与 integration coverage -安装 `tracing-otlp` 并启用 tracing 后,Server 自动组合的 worker 在启动时仅捕获 W3C `traceparent`/`tracestate`。 -每个 child 创建自己的 provider/resource,加入对应 supervisor execution,并为真实 family、Topic Memory model composition -启用 instrumentation。Memory 使用已有 commit stages;Topic Memory 增加 `topic_memory.prepare` 和 `topic_memory.commit`。 -显式 Dream 派发——包括 Topic Memory 的 Dream 分支——复用同一个 child span,并共享同一套 model instrumentation, -因此两者的 instrumented model span 都会出现。 -Child 的 `artifact_processing.worker.execute` span 描述 child result;业务完成仍由 supervisor 验证 acknowledgement。 +安装 `tracing-otlp` 并启用追踪后,传给 Server 所管理 worker 的追踪上下文仅包含 W3C `traceparent`/`tracestate`。每个 worker 使用各自的 resource 上报追踪数据,与所属 supervisor 执行关联,并记录相应 Family 和模型调用的 span。Memory 追踪包含提交阶段,Topic Memory 追踪包含 `topic_memory.prepare` 和 `topic_memory.commit`。显式 Dream 请求(包括 Topic Memory 的 Dream 分支)及其模型调用出现在同一个 worker span 下。`artifact_processing.worker.execute` span 报告 worker 的执行结果,业务处理完成则以 supervisor 的确认记录为准。 -Scheduled/coalesced invocation 使用独立 supervisor trace,不继承 capture request ID,不让 HTTP request 一直保持打开, -也不声称它与所有 Source 已有持久化的因果关联。Replay 不会恢复入站 trace context。Custom launcher 自己负责 bootstrap; -SDK 默认不配置 tracing,除非 embedding application 提供可选 worker wrapper。Parent-based sampling 决策会传到 child。 -Child export/shutdown 是 best-effort,shutdown 最多等待 1 秒;强制终止可能留下不完整 spans。显式启用 Server tracing 时 -缺少 exporter 仍会导致启动失败;child telemetry setup/export failure 不改变 domain result。 +Scheduled/coalesced invocation 使用独立 supervisor trace,不继承 capture request ID,不让 HTTP request 一直保持打开,也不声称它与所有 Source 已有持久化的因果关联。Replay 不会恢复入站 trace context。Custom launcher 自己负责 bootstrap; SDK 默认不配置 tracing,除非 embedding application 提供可选 worker wrapper。Parent-based sampling 决策会传到 child。 Child export/shutdown 是 best-effort,shutdown 最多等待 1 秒;强制终止可能留下不完整 spans。显式启用 Server tracing 时缺少 exporter 仍会导致启动失败;child telemetry setup/export failure 不改变 domain result。 | Integration boundary | Coverage | | --- | --- | @@ -340,13 +199,8 @@ Child export/shutdown 是 best-effort,shutdown 最多等待 1 秒;强制终 | Built-in Memory、Topic Memory spawn workers | 验证真实 entrypoints、本地 provider HTTP success/timeout、child spans 和 OTLP reception | | 其他 native host integrations | 保留 host diagnostics;本覆盖不声称已验证自动 host trace propagation | -OTLP 测试使用真实本地 protobuf HTTP receiver,不提供 production trace database。存储和 backend query 验证请按 -Phoenix/Langfuse 或所选 backend 的部署文档执行。Metrics dashboard、trace storage、log shipping 和 alert delivery 属于独立部署能力。 +OTLP 测试使用真实本地 protobuf HTTP receiver,不提供 production trace database。存储和 backend query 验证请按 Phoenix/Langfuse 或所选 backend 的部署文档执行。Metrics dashboard、trace storage、log shipping 和 alert delivery 属于独立部署能力。 ## Topic 生成拒绝码 -Topic 处理可通过 `invalid_topic_placeholder` 标识可识别的编号占位正文, -或通过 `invalid_topic_coordination_content` 标识纯身份协调正文。 -这些不含内容的诊断码表示可恢复的生成拒绝,不表示成功 NOOP。 -重试消耗现有 Window 持久化预算;耗尽后保留待处理前沿。诊断码由现有 Worker 事件及关联字段承载。 -不得将 Source 文本、生成正文或服务商响应写入运维日志。 +Topic 处理可通过 `invalid_topic_placeholder` 标识可识别的编号占位正文,或通过 `invalid_topic_coordination_content` 标识纯身份协调正文。这些不含内容的诊断码表示可恢复的生成拒绝,不表示成功 NOOP。重试消耗现有 Window 持久化预算;耗尽后保留待处理前沿。诊断码由现有 Worker 事件及关联字段承载。不得将 Source 文本、生成正文或服务商响应写入运维日志。 diff --git a/e2e/bub/uv.lock b/e2e/bub/uv.lock index 356d5b0e7a..2cee21e35c 100644 --- a/e2e/bub/uv.lock +++ b/e2e/bub/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 5 +revision = 3 requires-python = ">=3.12, <4.0" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", @@ -1697,6 +1697,11 @@ requires-dist = [ { name = "httpx", marker = "extra == 'server'", specifier = ">=0.28,<1" }, { name = "httpx", extras = ["socks"], marker = "extra == 'cli'", specifier = ">=0.28,<1" }, { name = "httpx", extras = ["socks"], marker = "extra == 'client'", specifier = ">=0.28,<1" }, + { name = "httpx2", marker = "extra == 'builtin'", specifier = ">=2.7,<3" }, + { name = "httpx2", marker = "extra == 'cli'", specifier = ">=2.7,<3" }, + { name = "httpx2", marker = "extra == 'ops'", specifier = ">=2.7,<3" }, + { name = "httpx2", marker = "extra == 'seekdb'", specifier = ">=2.7,<3" }, + { name = "httpx2", marker = "extra == 'server'", specifier = ">=2.7,<3" }, { name = "inquirerpy", marker = "extra == 'cli'", specifier = ">=0.3,<1" }, { name = "jieba", marker = "extra == 'builtin'", specifier = "==0.42.1" }, { name = "jieba", marker = "extra == 'cli'", specifier = "==0.42.1" }, @@ -1734,11 +1739,11 @@ requires-dist = [ { name = "pycasbin", marker = "extra == 'seekdb'", specifier = ">=2.8,<3" }, { name = "pycasbin", marker = "extra == 'server'", specifier = ">=2.8,<3" }, { name = "pydantic", specifier = ">=2.10,<3" }, - { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'builtin'", specifier = ">=2.27.1,<3" }, - { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'cli'", specifier = ">=2.27.1,<3" }, - { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'ops'", specifier = ">=2.27.1,<3" }, - { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'seekdb'", specifier = ">=2.27.1,<3" }, - { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'server'", specifier = ">=2.27.1,<3" }, + { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'builtin'", specifier = ">=2.64.0,<3" }, + { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'cli'", specifier = ">=2.64.0,<3" }, + { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'ops'", specifier = ">=2.64.0,<3" }, + { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'seekdb'", specifier = ">=2.64.0,<3" }, + { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'server'", specifier = ">=2.64.0,<3" }, { name = "pydantic-settings", marker = "extra == 'builtin'", specifier = ">=2.7,<3" }, { name = "pydantic-settings", marker = "extra == 'cli'", specifier = ">=2.7,<3" }, { name = "pydantic-settings", marker = "extra == 'client'", specifier = ">=2.7,<3" }, @@ -1834,6 +1839,7 @@ resource-build = [ { name = "click", specifier = ">=8.1,<9" }, { name = "filelock", specifier = ">=3.16,<4" }, { name = "httpx", specifier = ">=0.28,<1" }, + { name = "httpx2", specifier = ">=2.7,<3" }, { name = "jsonschema", specifier = ">=4.23,<5" }, { name = "opentelemetry-api", specifier = ">=1.30,<2" }, { name = "opentelemetry-sdk", specifier = ">=1.30,<2" }, diff --git a/evaluation/memory/locomo/runner.py b/evaluation/memory/locomo/runner.py index ce62ccd3eb..140bc4584e 100644 --- a/evaluation/memory/locomo/runner.py +++ b/evaluation/memory/locomo/runner.py @@ -28,7 +28,7 @@ from time import perf_counter from typing import Any, Literal, TypeVar, cast -import httpx +import httpx2 from dotenv import load_dotenv from pydantic import AnyHttpUrl, BaseModel, ConfigDict, Field, SecretStr from pydantic_ai.messages import ModelMessage, ModelResponse @@ -614,7 +614,7 @@ async def evaluate_dataset( # noqa: C901 async with AsyncExitStack() as resources: reranker: MemoryReranker | None = None if rerank_mode == "jev": - jev_client = await resources.enter_async_context(httpx.AsyncClient()) + jev_client = await resources.enter_async_context(httpx2.AsyncClient()) reranker = JevMemoryReranker(_jev_config(), jev_client) elif rerank_mode == MemoryRerankMode.LLM and answer_max_bytes is not None: inference = settings.inference diff --git a/evaluation/uv.lock b/evaluation/uv.lock index 4a2f29505d..2bb4af03ed 100644 --- a/evaluation/uv.lock +++ b/evaluation/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 5 +revision = 3 requires-python = ">=3.11, <4.0" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", @@ -839,8 +839,8 @@ name = "httpcore2" version = "2.14.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "h11" }, - { name = "truststore" }, + { name = "h11", marker = "python_full_version < '3.12' or python_full_version >= '3.14' or sys_platform != 'emscripten'" }, + { name = "truststore", marker = "python_full_version < '3.12' or python_full_version >= '3.14' or sys_platform != 'emscripten'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/30/ff/b53af1b49bb2cb5fa97c92215614b173ca5c1a99ded80e2d52f15a94fa6d/httpcore2-2.14.0.tar.gz", hash = "sha256:4f57a1a8249fe6af589d935cfd456f1d13bbdcb0f0fc72af9142368fc94811d7", size = 69096, upload-time = "2026-10-18T16:29:21.898Z" } wheels = [ @@ -911,7 +911,7 @@ name = "importlib-metadata" version = "9.0.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "zipp" }, + { name = "zipp", marker = "python_full_version < '3.12'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/6f/7e/1e7e8dc30634b93ebb3d58a3dea569ad146e656218d3960ab04f62047b29/importlib_metadata-9.0.1.tar.gz", hash = "sha256:ab830580bc0ef3db61ce8fae716389e5462b67e033018bab6d8f80ef17172f99", size = 59124, upload-time = "2026-08-28T15:30:34.646Z" } wheels = [ @@ -1675,6 +1675,7 @@ server = [ { name = "fastmcp" }, { name = "filelock" }, { name = "httpx" }, + { name = "httpx2" }, { name = "jieba" }, { name = "jinja2" }, { name = "markdown-it-py" }, @@ -1735,6 +1736,11 @@ requires-dist = [ { name = "httpx", marker = "extra == 'server'", specifier = ">=0.28,<1" }, { name = "httpx", extras = ["socks"], marker = "extra == 'cli'", specifier = ">=0.28,<1" }, { name = "httpx", extras = ["socks"], marker = "extra == 'client'", specifier = ">=0.28,<1" }, + { name = "httpx2", marker = "extra == 'builtin'", specifier = ">=2.7,<3" }, + { name = "httpx2", marker = "extra == 'cli'", specifier = ">=2.7,<3" }, + { name = "httpx2", marker = "extra == 'ops'", specifier = ">=2.7,<3" }, + { name = "httpx2", marker = "extra == 'seekdb'", specifier = ">=2.7,<3" }, + { name = "httpx2", marker = "extra == 'server'", specifier = ">=2.7,<3" }, { name = "inquirerpy", marker = "extra == 'cli'", specifier = ">=0.3,<1" }, { name = "jieba", marker = "extra == 'builtin'", specifier = "==0.42.1" }, { name = "jieba", marker = "extra == 'cli'", specifier = "==0.42.1" }, @@ -1772,11 +1778,11 @@ requires-dist = [ { name = "pycasbin", marker = "extra == 'seekdb'", specifier = ">=2.8,<3" }, { name = "pycasbin", marker = "extra == 'server'", specifier = ">=2.8,<3" }, { name = "pydantic", specifier = ">=2.10,<3" }, - { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'builtin'", specifier = ">=2.27.1,<3" }, - { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'cli'", specifier = ">=2.27.1,<3" }, - { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'ops'", specifier = ">=2.27.1,<3" }, - { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'seekdb'", specifier = ">=2.27.1,<3" }, - { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'server'", specifier = ">=2.27.1,<3" }, + { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'builtin'", specifier = ">=2.64.0,<3" }, + { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'cli'", specifier = ">=2.64.0,<3" }, + { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'ops'", specifier = ">=2.64.0,<3" }, + { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'seekdb'", specifier = ">=2.64.0,<3" }, + { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'server'", specifier = ">=2.64.0,<3" }, { name = "pydantic-settings", marker = "extra == 'builtin'", specifier = ">=2.7,<3" }, { name = "pydantic-settings", marker = "extra == 'cli'", specifier = ">=2.7,<3" }, { name = "pydantic-settings", marker = "extra == 'client'", specifier = ">=2.7,<3" }, @@ -1872,6 +1878,7 @@ resource-build = [ { name = "click", specifier = ">=8.1,<9" }, { name = "filelock", specifier = ">=3.16,<4" }, { name = "httpx", specifier = ">=0.28,<1" }, + { name = "httpx2", specifier = ">=2.7,<3" }, { name = "jsonschema", specifier = ">=4.23,<5" }, { name = "opentelemetry-api", specifier = ">=1.30,<2" }, { name = "opentelemetry-sdk", specifier = ">=1.30,<2" }, @@ -2012,7 +2019,7 @@ email = [ [[package]] name = "pydantic-ai-slim" -version = "2.57.0" +version = "2.64.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio" }, @@ -2024,9 +2031,9 @@ dependencies = [ { name = "pydantic-graph" }, { name = "typing-inspection" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/dd/f92904e5719bb7de25eaa9eb9f0fb9746a8b43b02775249d2516b9583f5b/pydantic_ai_slim-2.57.0.tar.gz", hash = "sha256:2c5c150bcd097e6a1e267ea13e7f279a0b504d46b346a4e00b61e1996ad05372", size = 1907558, upload-time = "2026-10-16T03:51:13.084Z" } +sdist = { url = "https://files.pythonhosted.org/packages/9b/57/38e6a723a69a72bc3ff9ffe806f4e6ef43a7660c11c598d9c77a3076d760/pydantic_ai_slim-2.64.0.tar.gz", hash = "sha256:bf7019bd8083a8a44b6ab891923cf3ec95c4713c04437d5f1d21206d485b2ace", size = 2390076, upload-time = "2026-10-31T00:22:39.12Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/cc/4f/ee187f80f9f9232fc6915da47d84305dfa62d4f879efbb1e6ff262172437/pydantic_ai_slim-2.57.0-py3-none-any.whl", hash = "sha256:a07d732e09df8d51f22bd3be2ad45ab644721a904809a2481146bf5d7bb47c67", size = 2229864, upload-time = "2026-10-16T03:50:59.882Z" }, + { url = "https://files.pythonhosted.org/packages/28/50/cee5e955a4d6126372b56eed56150d40b11dac393a26ca4a4826324c96f0/pydantic_ai_slim-2.64.0-py3-none-any.whl", hash = "sha256:63ccfe3f66beefb0a2fb3843d471f9d5b74a432f4436ed5ceb7e0d6bb06cb1e4", size = 2754541, upload-time = "2026-10-31T00:22:25.127Z" }, ] [package.optional-dependencies] @@ -2142,7 +2149,7 @@ wheels = [ [[package]] name = "pydantic-graph" -version = "2.57.0" +version = "2.64.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio" }, @@ -2150,9 +2157,9 @@ dependencies = [ { name = "pydantic" }, { name = "typing-inspection" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/b5/09/f02d836a27cf943b30c0bd3a3d2a3818e98ca5d554acc35be414e694984d/pydantic_graph-2.57.0.tar.gz", hash = "sha256:f848857baab4030c44b30de0c3ba650749d60f2295a0723645fb325f92191cf1", size = 45831, upload-time = "2026-10-16T03:51:16.98Z" } +sdist = { url = "https://files.pythonhosted.org/packages/ed/ea/70b61336d6648afafc9721377272c39a933f1ba426572c5c02d06bea31e9/pydantic_graph-2.64.0.tar.gz", hash = "sha256:823bc45c953e2c58b9bb89dbd8b79e9a31f90e55264078d492fe2de19269592a", size = 46464, upload-time = "2026-10-31T00:22:43.948Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/00/d9/55a8f09b6180e10a19d1d41b2f1b157b23d8a998d442cf28465c5a86bea2/pydantic_graph-2.57.0-py3-none-any.whl", hash = "sha256:4c65193a1d8b58e3c6f29a15cbe7b96e1e255a1670a5bcb9a323b8600fc1686a", size = 53274, upload-time = "2026-10-16T03:51:06.285Z" }, + { url = "https://files.pythonhosted.org/packages/5d/23/44f62c9eb71253998c5633b13d9ff44c20a4ed731fea99cc76f68dabbc3a/pydantic_graph-2.64.0-py3-none-any.whl", hash = "sha256:5034949fd78899001b31b819e3fd9357019766d48245f788712bb3a91ccf75a2", size = 53650, upload-time = "2026-10-31T00:22:31.083Z" }, ] [[package]] @@ -2712,8 +2719,8 @@ name = "secretstorage" version = "3.5.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cryptography" }, - { name = "jeepney" }, + { name = "cryptography", marker = "(python_full_version < '3.12' and sys_platform == 'emscripten') or (python_full_version >= '3.14' and sys_platform == 'emscripten') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, + { name = "jeepney", marker = "(python_full_version < '3.12' and sys_platform == 'emscripten') or (python_full_version >= '3.14' and sys_platform == 'emscripten') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/1c/03/e834bcd866f2f8a49a85eaff47340affa3bfa391ee9912a952a1faa68c7b/secretstorage-3.5.0.tar.gz", hash = "sha256:f04b8e4689cbce351744d5537bf6b1329c6fc68f91fa666f60a380edddcd11be", size = 19884, upload-time = "2025-11-23T19:02:53.191Z" } wheels = [ diff --git a/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py b/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py index f871bbac9c..3254839748 100644 --- a/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py +++ b/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py @@ -133,6 +133,8 @@ async def before_model_request( request_context, messages=_without_powercontext_context(request_context.messages), ) + # Request-only replacements no longer update the history used by later tool steps. + ctx.messages[:] = _without_powercontext_context(ctx.messages) if not query: return request_context @@ -146,6 +148,7 @@ async def before_model_request( run_id=ctx.run_id, conversation_id=ctx.conversation_id, ) + ctx.messages.insert(0, context_request) return replace(request_context, messages=[context_request, *request_context.messages]) @override diff --git a/pyproject.toml b/pyproject.toml index 07b1e39176..b0e058bee0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -54,9 +54,10 @@ builtin = [ "cryptography>=46,<51", "filelock>=3.16,<4", "httpx>=0.28,<1", + "httpx2>=2.7,<3", "jieba==0.42.1", "packaging>=24,<27", - "pydantic-ai-slim[anthropic,openai]>=2.27.1,<3", + "pydantic-ai-slim[anthropic,openai]>=2.64.0,<3", "pydantic-settings>=2.7,<3", "pyyaml>=6,<7", "pycasbin>=2.8,<3", @@ -142,6 +143,7 @@ resource-build = [ "click>=8.1,<9", "filelock>=3.16,<4", "httpx>=0.28,<1", + "httpx2>=2.7,<3", "jsonschema>=4.23,<5", "opentelemetry-api>=1.30,<2", "opentelemetry-sdk>=1.30,<2", diff --git a/src/powercontext/builtin/artifacts/memory/jev_reranking.py b/src/powercontext/builtin/artifacts/memory/jev_reranking.py index 8851d67f77..dd662ab061 100644 --- a/src/powercontext/builtin/artifacts/memory/jev_reranking.py +++ b/src/powercontext/builtin/artifacts/memory/jev_reranking.py @@ -22,7 +22,7 @@ from collections.abc import Coroutine, Iterable from typing import Literal, Self -import httpx +import httpx2 from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator from powercontext.builtin.artifacts.memory.reranking import ( @@ -72,7 +72,7 @@ class JevRerankConfig(BaseModel): @model_validator(mode="after") def validate_endpoint_and_model(self) -> Self: - url = httpx.URL(self.endpoint) + url = httpx2.URL(self.endpoint) if ( url.scheme not in {"http", "https"} or not url.host @@ -112,7 +112,7 @@ class _JevResponse(BaseModel): usage: _JevUsage -def _http_failure(error: httpx.HTTPStatusError, timeout_seconds: float) -> InferenceError: +def _http_failure(error: httpx2.HTTPStatusError, timeout_seconds: float) -> InferenceError: status = error.response.status_code if status in {408, 504}: return InferenceTimeoutError("memory.rerank", timeout_seconds) @@ -188,7 +188,7 @@ class JevMemoryReranker: def __init__( self, config: JevRerankConfig, - client: httpx.AsyncClient | None = None, + client: httpx2.AsyncClient | None = None, *, protection: InferenceProtectionConfig | None = None, ) -> None: @@ -199,13 +199,13 @@ def __init__( if client is not None: raise InferenceConfigurationError("protected Jev reranking requires an owned HTTP transport") # noqa: TRY003 - self._client = httpx.AsyncClient( + self._client = httpx2.AsyncClient( transport=ProtectedAsyncTransport(protection), follow_redirects=False, headers={"Accept-Encoding": "identity"}, ) else: - self._client = client if client is not None else httpx.AsyncClient(follow_redirects=False) + self._client = client if client is not None else httpx2.AsyncClient(follow_redirects=False) self._semaphore = asyncio.Semaphore(config.max_concurrency) self.policy_id = f"{JEV_MEMORY_RERANK_POLICY}:{config.model}" @@ -233,7 +233,7 @@ async def score(candidate: MemoryRerankText) -> float: if len(content) > self._config.max_request_bytes: raise InferenceConfigurationError("Jev rerank request exceeds max_request_bytes") # noqa: TRY003 async with self._semaphore: - request = httpx.Request( + request = httpx2.Request( "POST", self._config.endpoint, content=content, @@ -241,7 +241,7 @@ async def score(candidate: MemoryRerankText) -> float: "Content-Type": "application/json", "Authorization": f"Bearer {self._config.api_key.get_secret_value()}", }, - extensions={"timeout": httpx.Timeout(self._config.timeout_seconds).as_dict()}, + extensions={"timeout": httpx2.Timeout(self._config.timeout_seconds).as_dict()}, ) response = await self._client.send(request, auth=None, follow_redirects=False) response.raise_for_status() @@ -256,11 +256,11 @@ async def score(candidate: MemoryRerankText) -> float: (score(candidate) for candidate in candidates), usages, self._config.timeout_seconds ) ranks = tuple(sorted(range(1, len(candidates) + 1), key=lambda rank: (-scores[rank - 1], rank))[:limit]) - except (TimeoutError, httpx.TimeoutException) as error: + except (TimeoutError, httpx2.TimeoutException) as error: raise InferenceTimeoutError("memory.rerank", self._config.timeout_seconds) from error - except httpx.HTTPStatusError as error: + except httpx2.HTTPStatusError as error: raise _http_failure(error, self._config.timeout_seconds) from error - except (httpx.RequestError, OSError) as error: + except (httpx2.RequestError, OSError) as error: raise InferenceUnavailableError("memory.rerank") from error except (ValueError, KeyError, TypeError) as error: raise InvalidInferenceOutputError("memory.rerank", "Jev did not return a valid result") from error diff --git a/src/powercontext/builtin/inference/minimax.py b/src/powercontext/builtin/inference/minimax.py index 89533f8b8b..6220f5c868 100644 --- a/src/powercontext/builtin/inference/minimax.py +++ b/src/powercontext/builtin/inference/minimax.py @@ -30,7 +30,7 @@ from collections.abc import Mapping, Sequence from urllib.parse import urlparse -import httpx +import httpx2 from powercontext.builtin.artifacts.memory.canonical import canonical_embedding from powercontext.builtin.artifacts.memory.models import EmbeddingProfile @@ -66,7 +66,7 @@ def __init__( profile: EmbeddingProfile, batch_size: int = 10, timeout_seconds: float = 30.0, - http_client: httpx.AsyncClient | None = None, + http_client: httpx2.AsyncClient | None = None, protection: InferenceProtectionConfig | None = None, ) -> None: if not model or not model.strip(): @@ -91,14 +91,14 @@ def __init__( if http_client is not None: raise InferenceConfigurationError("protected MiniMax embedding requires an owned HTTP transport") # noqa: TRY003 - self._client = httpx.AsyncClient( + self._client = httpx2.AsyncClient( timeout=timeout_seconds, transport=ProtectedAsyncTransport(protection), follow_redirects=False, headers={"Accept-Encoding": "identity"}, ) else: - self._client = http_client or httpx.AsyncClient(timeout=timeout_seconds) + self._client = http_client or httpx2.AsyncClient(timeout=timeout_seconds) async def aclose(self) -> None: """Close the underlying HTTP client (registered with the runtime stack).""" @@ -140,7 +140,7 @@ async def _embed( # noqa: C901 - bounded transport and HTTP status mapping cause_exception_type=type(error).__name__, ), ) from error - except httpx.TimeoutException as error: + except httpx2.TimeoutException as error: raise attach_diagnostics( InferenceTimeoutError("embed", self._timeout), ProcessingDiagnostics( @@ -149,7 +149,7 @@ async def _embed( # noqa: C901 - bounded transport and HTTP status mapping cause_exception_type=type(error).__name__, ), ) from error - except httpx.HTTPStatusError as error: + except httpx2.HTTPStatusError as error: status = error.response.status_code if status == 429: reason = ProcessingFailureReason.RATE_LIMIT @@ -169,7 +169,7 @@ async def _embed( # noqa: C901 - bounded transport and HTTP status mapping cause_exception_type=type(error).__name__, ), ) from error - except httpx.HTTPError as error: + except httpx2.HTTPError as error: raise attach_diagnostics( InferenceUnavailableError("embed"), ProcessingDiagnostics( diff --git a/src/powercontext/builtin/inference/protected_transport.py b/src/powercontext/builtin/inference/protected_transport.py index 7b9a8aaf34..0f766ead9b 100644 --- a/src/powercontext/builtin/inference/protected_transport.py +++ b/src/powercontext/builtin/inference/protected_transport.py @@ -20,7 +20,7 @@ from collections.abc import Callable from contextlib import suppress -import httpx +import httpx2 from typing_extensions import override from powercontext.builtin.inference.carrier_checks import inspect_sse @@ -35,13 +35,13 @@ from powercontext.builtin.inference.usage import record_approved_usage -def _relevant_headers(headers: httpx.Headers) -> dict[str, str]: +def _relevant_headers(headers: httpx2.Headers) -> dict[str, str]: return { key: value for key, value in headers.items() if key in {"content-type", "anthropic-version", "anthropic-beta"} } -class ProtectedAsyncTransport(httpx.AsyncBaseTransport): +class ProtectedAsyncTransport(httpx2.AsyncBaseTransport): """Check the actual HTTP request and buffer raw output before SDK access. An enforcing client must disable SDK retries. Observation modes preserve the @@ -54,11 +54,11 @@ def __init__( self, config: InferenceProtectionConfig, *, - transport: httpx.AsyncBaseTransport | None = None, + transport: httpx2.AsyncBaseTransport | None = None, observer: Callable[[PrivacyDecision], None] | None = None, ) -> None: self.policy = PrivacyPolicy(config) - self._transport = transport if transport is not None else httpx.AsyncHTTPTransport(retries=0) + self._transport = transport if transport is not None else httpx2.AsyncHTTPTransport(retries=0) self._slots = asyncio.Semaphore(config.max_concurrent_responses) self._observer = observer @@ -70,14 +70,14 @@ def _assess(self, decision: PrivacyDecision, *, usage: InferenceUsage | None = N if self.policy.enforcing and decision.decision != "allow": raise InferencePrivacyError(decision.phase, decision.decision, decision.reason_codes, usage=usage) - async def _request_body(self, request: httpx.Request) -> bytes | None: + async def _request_body(self, request: httpx2.Request) -> bytes | None: try: return request.content - except httpx.RequestNotRead: + except httpx2.RequestNotRead: if not self.policy.enforcing: self._assess(self.policy.decision("before_send", "withhold", "request_stream_uninspected")) return None - if not isinstance(request.stream, httpx.AsyncByteStream): + if not isinstance(request.stream, httpx2.AsyncByteStream): self._assess(self.policy.decision("before_send", "withhold", "request_stream_unsupported")) return None chunks: list[bytes] = [] @@ -91,11 +91,11 @@ async def _request_body(self, request: httpx.Request) -> bytes | None: finally: await request.stream.aclose() body = b"".join(chunks) - request.stream = httpx.ByteStream(body) + request.stream = httpx2.ByteStream(body) return body @override - async def handle_async_request(self, request: httpx.Request) -> httpx.Response: # noqa: C901 - send and release have distinct failure semantics + async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response: # noqa: C901 - send and release have distinct failure semantics if self.policy.config.mode == "disabled": return await self._transport.handle_async_request(request) body = await self._request_body(request) @@ -151,7 +151,7 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response: raise except InferencePrivacyError: raise - except (TimeoutError, httpx.TransportError) as error: + except (TimeoutError, httpx2.TransportError) as error: raise InferencePrivacyError( "before_release", "withhold", @@ -181,7 +181,7 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response: headers = response.headers.copy() for name in ("content-encoding", "content-length", "transfer-encoding"): headers.pop(name, None) - return httpx.Response( + return httpx2.Response( response.status_code, headers=headers, content=raw, diff --git a/src/powercontext/builtin/inference/pydantic_ai.py b/src/powercontext/builtin/inference/pydantic_ai.py index b9ecace9ca..d2f9ebcd70 100644 --- a/src/powercontext/builtin/inference/pydantic_ai.py +++ b/src/powercontext/builtin/inference/pydantic_ai.py @@ -90,7 +90,9 @@ def __init__(self, code: str, detail: object | None = None) -> None: from pydantic_ai.exceptions import ( ConcurrencyLimitExceeded, ModelAPIError, + ModelContextWindowExceededError, ModelHTTPError, + ModelRequestRejectedError, UnexpectedModelBehavior, UsageLimitExceeded, UserError, @@ -653,13 +655,16 @@ def _map_error( # noqa: C901 - bounded mapping across status codes and provider cause_exception_type=cause_type, ), ) + if isinstance(error, (ModelHTTPError, ModelRequestRejectedError)): reason = ( ProcessingFailureReason.CONTEXT_OVERFLOW - if _looks_like_context_overflow(error) + if isinstance(error, ModelContextWindowExceededError) else ProcessingFailureReason.CONFIGURATION ) return attach_diagnostics( - PydanticAIConfigurationError("provider-rejected", detail=f"HTTP {error.status_code}"), + PydanticAIConfigurationError( + "provider-rejected", detail=f"HTTP {error.status_code}" if isinstance(error, ModelHTTPError) else None + ), ProcessingDiagnostics( stage=stage, reason=reason, @@ -711,25 +716,6 @@ def _map_error( # noqa: C901 - bounded mapping across status codes and provider return None -def _looks_like_context_overflow(error: ModelHTTPError) -> bool: - """Classify only when the provider's own response names a context limit.""" - - body = getattr(error, "body", None) - text = str(body if isinstance(body, (str, bytes)) else body or "").lower() - return any( - term in text - for term in ( - "context length", - "context window", - "maximum context", - "too many tokens", - "prompt is too long", - "input is too long", - "token limit", - ) - ) - - __all__ = [ "InferenceLimits", "PydanticAIConfigurationError", diff --git a/src/powercontext/builtin/runtime/composition.py b/src/powercontext/builtin/runtime/composition.py index d2396db363..9ee7024b63 100644 --- a/src/powercontext/builtin/runtime/composition.py +++ b/src/powercontext/builtin/runtime/composition.py @@ -2121,14 +2121,14 @@ def _protected_provider_factory( ) -> Callable[[str], Provider[Any]]: """Own the final transport, including SDK defaults and auxiliary models.""" - import httpx + import httpx2 from powercontext.builtin.inference.protected_transport import ProtectedAsyncTransport def create(provider_name: str) -> Provider[Any]: # Explicit client injection avoids SDK cached clients, redirect behavior, # hidden transport retries and provider-side request inspection bypasses. - client = httpx.AsyncClient( + client = httpx2.AsyncClient( transport=ProtectedAsyncTransport(protection), follow_redirects=False, headers={"Accept-Encoding": "identity"}, @@ -2177,6 +2177,7 @@ def _unbounded_provider_factory( workload: Literal["generation", "embedding"], resources: AsyncExitStack, ) -> Callable[[str], Provider[Any]]: + import httpx2 from pydantic_ai.providers import infer_provider if base_url is None and not headers: @@ -2189,7 +2190,7 @@ def create_provider(provider_name: str) -> Provider[Any]: if headers: from openai import AsyncOpenAI - http_client = _endpoint_http_client(follow_redirects=False) if base_url is not None else None + http_client = httpx2.AsyncClient(follow_redirects=False) if base_url is not None else None client = AsyncOpenAI( base_url=None if base_url is None else str(base_url), api_key=os.getenv("OPENAI_API_KEY") or "api-key-not-set", @@ -2199,15 +2200,9 @@ def create_provider(provider_name: str) -> Provider[Any]: resources.push_async_callback(client.close) return OpenAIProvider(openai_client=client) if base_url is not None and _is_loopback_endpoint(base_url): - from openai import AsyncOpenAI - - client = AsyncOpenAI( - base_url=str(base_url), - api_key=os.getenv("OPENAI_API_KEY") or "api-key-not-set", - http_client=_endpoint_http_client(follow_redirects=False), - ) - resources.push_async_callback(client.close) - return OpenAIProvider(openai_client=client) + http_client = httpx2.AsyncClient(follow_redirects=False) + resources.push_async_callback(http_client.aclose) + return OpenAIProvider(base_url=str(base_url), http_client=http_client) return OpenAIProvider(base_url=str(base_url)) if provider_name == "anthropic" and workload == "generation": from anthropic import AsyncAnthropic @@ -2222,7 +2217,7 @@ def create_provider(provider_name: str) -> Provider[Any]: # A configured Authorization header is the credential; gateways may reject any X-Api-Key. api_key=api_key or (None if has_authorization else "api-key-not-set"), default_headers=default_headers, - http_client=_endpoint_http_client(follow_redirects=False) if base_url is not None else None, + http_client=httpx2.AsyncClient(follow_redirects=False) if base_url is not None else None, ) resources.push_async_callback(client.close) return AnthropicProvider(anthropic_client=client) @@ -2235,14 +2230,6 @@ def create_provider(provider_name: str) -> Provider[Any]: return create_provider -def _endpoint_http_client(*, follow_redirects: bool): - """Create the SDK transport with an explicit redirect policy for custom endpoints.""" - - import httpx - - return httpx.AsyncClient(follow_redirects=follow_redirects) - - def _is_loopback_endpoint(endpoint: AnyHttpUrl | str | None) -> bool: """Allow only explicit local names and addresses for raw decision content.""" diff --git a/tests/builtin/artifacts/memory/test_jev_reranking.py b/tests/builtin/artifacts/memory/test_jev_reranking.py index c66328202c..28a3d74485 100644 --- a/tests/builtin/artifacts/memory/test_jev_reranking.py +++ b/tests/builtin/artifacts/memory/test_jev_reranking.py @@ -20,7 +20,7 @@ import json from dataclasses import dataclass -import httpx +import httpx2 import pytest from pydantic import SecretStr, ValidationError @@ -49,8 +49,8 @@ def _config(**overrides) -> JevRerankConfig: }) -def _response(score=0.8, **overrides) -> httpx.Response: - return httpx.Response( +def _response(score=0.8, **overrides) -> httpx2.Response: + return httpx2.Response( 200, json={ "model": "jev-1.13.0", @@ -71,7 +71,7 @@ def respond(request): return _response({"first": 0.2, "second": 0.9, "third": 0.9}[body["state"]["candidate"]]) async def scenario(): - async with httpx.AsyncClient(transport=httpx.MockTransport(respond), auth=("other", "credential")) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond), auth=("other", "credential")) as client: result = await JevMemoryReranker(_config(), client).rerank( "query", tuple(_Text(text) for text in ("first", "second", "third")), 2 ) @@ -89,7 +89,7 @@ async def scenario(): @pytest.mark.parametrize( ("response", "error"), [ - (httpx.Response(429), InferenceUnavailableError), + (httpx2.Response(429), InferenceUnavailableError), (_response(1.1), InvalidInferenceOutputError), (_response(model="jev-1.14.0"), InvalidInferenceOutputError), (_response(usage={}), InvalidInferenceOutputError), @@ -97,7 +97,7 @@ async def scenario(): ) def test_unavailable_or_unusable_results_expose_provider_failure(response, error): async def scenario(): - async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: response)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(lambda _: response)) as client: with pytest.raises(error): await JevMemoryReranker(_config(), client).rerank("query", (_Text("one"), _Text("two")), 2) @@ -106,10 +106,10 @@ async def scenario(): def test_partial_failure_does_not_return_a_successful_decision(): async def scenario(): - async with httpx.AsyncClient( - transport=httpx.MockTransport( + async with httpx2.AsyncClient( + transport=httpx2.MockTransport( lambda request: ( - _response() if json.loads(request.content)["state"]["candidate"] == "one" else httpx.Response(429) + _response() if json.loads(request.content)["state"]["candidate"] == "one" else httpx2.Response(429) ) ) ) as client: @@ -134,7 +134,7 @@ def respond(request): }[candidate] raise InferencePrivacyError("before_release", "block", ("forbidden_content",), usage=usage) - async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as client: with pytest.raises(InferencePrivacyError) as caught: await JevMemoryReranker(_config(), client).rerank("query", tuple(_Text(text) for text in order), 2) assert caught.value.phase == "before_release" @@ -153,7 +153,7 @@ async def scenario(): def respond(request): candidate = json.loads(request.content)["state"]["candidate"] if candidate == "unavailable": - return httpx.Response(429) + return httpx2.Response(429) if candidate == "success": return _response() raise InferencePrivacyError( @@ -163,7 +163,7 @@ def respond(request): usage=InferenceUsage(requests=1, input_tokens=11, output_tokens=2), ) - async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as client: with pytest.raises(InferencePrivacyError) as caught: await JevMemoryReranker(_config(), client).rerank("query", tuple(_Text(text) for text in order), 2) assert caught.value.phase == "before_release" @@ -191,7 +191,7 @@ async def respond(request): finally: finished.set() - async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as client: task = asyncio.create_task( JevMemoryReranker(_config(), client).rerank("query", (_Text("pending"), _Text("refusal")), 1) ) @@ -220,7 +220,7 @@ async def respond(_request): active -= 1 return _response() - async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as client: reranker = JevMemoryReranker(_config(timeout_seconds=0.03, max_concurrency=1), client) results = await asyncio.gather( *(reranker.rerank("query", (_Text("one"), _Text("two")), 1) for _ in range(2)), @@ -245,7 +245,7 @@ async def respond(_request): finished.set() return _response() - async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as client: task = asyncio.create_task(JevMemoryReranker(_config(), client).rerank("query", (_Text("one"),), 1)) await asyncio.wait_for(started.wait(), 1) task.cancel() @@ -258,8 +258,8 @@ async def respond(_request): def test_oversized_utf8_request_fails_without_sending_content(): async def scenario(): - async with httpx.AsyncClient( - transport=httpx.MockTransport(lambda _: pytest.fail("unexpected request")) + async with httpx2.AsyncClient( + transport=httpx2.MockTransport(lambda _: pytest.fail("unexpected request")) ) as client: with pytest.raises(InferenceConfigurationError, match="exceeds max_request_bytes"): await JevMemoryReranker(_config(max_request_bytes=1), client).rerank("query", (_Text("evidence"),), 1) @@ -272,10 +272,10 @@ def test_redirect_does_not_send_credentials_or_evidence_to_another_host(): def respond(request): requests.append(str(request.url)) - return httpx.Response(307, headers={"Location": "https://other.example/systemone"}) + return httpx2.Response(307, headers={"Location": "https://other.example/systemone"}) async def scenario(): - async with httpx.AsyncClient(transport=httpx.MockTransport(respond), follow_redirects=True) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond), follow_redirects=True) as client: with pytest.raises(InferenceConfigurationError): await JevMemoryReranker(_config(), client).rerank("query", (_Text("one"),), 1) assert requests == ["https://api.typesafe.ai/v1/systemone"] diff --git a/tests/builtin/inference/test_minimax_embedding.py b/tests/builtin/inference/test_minimax_embedding.py index ea518c5d57..38898d4be3 100644 --- a/tests/builtin/inference/test_minimax_embedding.py +++ b/tests/builtin/inference/test_minimax_embedding.py @@ -20,7 +20,7 @@ import json from typing import Any -import httpx +import httpx2 import pytest from powercontext.builtin.artifacts.memory.models import EmbeddingProfile @@ -68,8 +68,8 @@ def _model( ) -def _ok_response(vectors: list[list[float]], status_code: int = 0) -> httpx.Response: - return httpx.Response( +def _ok_response(vectors: list[list[float]], status_code: int = 0) -> httpx2.Response: + return httpx2.Response( 200, json={ "vectors": vectors, @@ -82,12 +82,12 @@ def _ok_response(vectors: list[list[float]], status_code: int = 0) -> httpx.Resp def test_embed_returns_validated_vectors_and_sends_native_shape() -> None: captured: list[dict[str, Any]] = [] - def handler(request: httpx.Request) -> httpx.Response: + def handler(request: httpx2.Request) -> httpx2.Response: captured.append(json.loads(request.content)) return _ok_response([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]) async def scenario() -> None: - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(handler)) as client: model = _model(http_client=client) result = await model.embed(("alpha", "beta")) assert result.vectors == ((0.1, 0.2, 0.3), (0.4, 0.5, 0.6)) @@ -101,12 +101,12 @@ async def scenario() -> None: def test_embed_query_sends_query_type() -> None: captured: list[dict[str, Any]] = [] - def handler(request: httpx.Request) -> httpx.Response: + def handler(request: httpx2.Request) -> httpx2.Response: captured.append(json.loads(request.content)) return _ok_response([[0.1, 0.2, 0.3]]) async def scenario() -> None: - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(handler)) as client: model = _model(http_client=client) result = await model.embed_query(("alpha",)) assert result.vectors == ((0.1, 0.2, 0.3),) @@ -118,13 +118,13 @@ async def scenario() -> None: def test_embed_batches_requests_without_split_size_mismatch() -> None: calls: list[dict[str, Any]] = [] - def handler(request: httpx.Request) -> httpx.Response: + def handler(request: httpx2.Request) -> httpx2.Response: body = json.loads(request.content) calls.append(body) return _ok_response([[0.1, 0.2, 0.3] for _ in body["texts"]]) async def scenario() -> None: - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(handler)) as client: model = _model(batch_size=2, http_client=client) result = await model.embed(("a", "b", "c", "d", "e")) assert result.usage.requests == 3 @@ -134,14 +134,14 @@ async def scenario() -> None: def test_embed_raises_unavailable_on_business_error() -> None: - def handler(request: httpx.Request) -> httpx.Response: + def handler(request: httpx2.Request) -> httpx2.Response: # MiniMax answers HTTP 200 with a non-zero base_resp.status_code. - return httpx.Response( + return httpx2.Response( 200, json={"vectors": None, "base_resp": {"status_code": 2013, "status_msg": "missing texts"}} ) async def scenario() -> None: - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(handler)) as client: model = _model(http_client=client) with pytest.raises(InferenceUnavailableError) as error: await model.embed(("alpha",)) @@ -152,11 +152,11 @@ async def scenario() -> None: def test_embed_raises_unavailable_on_http_error() -> None: - def handler(request: httpx.Request) -> httpx.Response: - return httpx.Response(401, json={"base_resp": {"status_code": 1001}}) + def handler(request: httpx2.Request) -> httpx2.Response: + return httpx2.Response(401, json={"base_resp": {"status_code": 1001}}) async def scenario() -> None: - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(handler)) as client: model = _model(http_client=client) with pytest.raises(InferenceUnavailableError): await model.embed(("alpha",)) @@ -165,11 +165,11 @@ async def scenario() -> None: def test_embed_classifies_rate_limited_http_status() -> None: - def handler(request: httpx.Request) -> httpx.Response: - return httpx.Response(429, json={"base_resp": {"status_code": 1002}}) + def handler(request: httpx2.Request) -> httpx2.Response: + return httpx2.Response(429, json={"base_resp": {"status_code": 1002}}) async def scenario() -> None: - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(handler)) as client: model = _model(http_client=client) with pytest.raises(InferenceUnavailableError) as error: await model.embed(("alpha",)) @@ -184,11 +184,11 @@ async def scenario() -> None: def test_embed_maps_http_timeout_to_inference_timeout() -> None: - def handler(request: httpx.Request) -> httpx.Response: - raise httpx.ReadTimeout("provider did not respond", request=request) # noqa: TRY003 + def handler(request: httpx2.Request) -> httpx2.Response: + raise httpx2.ReadTimeout("provider did not respond", request=request) # noqa: TRY003 async def scenario() -> None: - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(handler)) as client: model = _model(http_client=client) with pytest.raises(InferenceTimeoutError): await model.embed(("alpha",)) @@ -208,11 +208,11 @@ async def scenario() -> None: def test_embed_raises_invalid_output_on_wrong_vector_count() -> None: - def handler(request: httpx.Request) -> httpx.Response: + def handler(request: httpx2.Request) -> httpx2.Response: return _ok_response([[0.1, 0.2, 0.3]]) async def scenario() -> None: - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(handler)) as client: model = _model(http_client=client) with pytest.raises(InvalidInferenceOutputError): await model.embed(("alpha", "beta")) @@ -221,11 +221,11 @@ async def scenario() -> None: def test_embed_raises_invalid_output_on_malformed_json() -> None: - def handler(request: httpx.Request) -> httpx.Response: - return httpx.Response(200, content=b"not-json") + def handler(request: httpx2.Request) -> httpx2.Response: + return httpx2.Response(200, content=b"not-json") async def scenario() -> None: - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(handler)) as client: model = _model(http_client=client) with pytest.raises(InvalidInferenceOutputError): await model.embed(("alpha",)) @@ -250,11 +250,11 @@ async def scenario() -> None: def test_embed_raises_invalid_output_on_dimension_mismatch() -> None: - def handler(request: httpx.Request) -> httpx.Response: + def handler(request: httpx2.Request) -> httpx2.Response: return _ok_response([[0.1, 0.2, 0.3, 0.4]]) async def scenario() -> None: - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(handler)) as client: model = _model(http_client=client) with pytest.raises(InvalidInferenceOutputError): await model.embed(("alpha",)) @@ -263,14 +263,14 @@ async def scenario() -> None: def test_embed_empty_returns_no_vectors() -> None: - captured: list[httpx.Request] = [] + captured: list[httpx2.Request] = [] - def handler(request: httpx.Request) -> httpx.Response: + def handler(request: httpx2.Request) -> httpx2.Response: captured.append(request) return _ok_response([]) async def scenario() -> None: - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(handler)) as client: model = _model(http_client=client) result = await model.embed(()) assert result.vectors == () @@ -282,12 +282,12 @@ async def scenario() -> None: def test_embed_sends_configured_headers() -> None: captured: list[dict[str, Any]] = [] - def handler(request: httpx.Request) -> httpx.Response: + def handler(request: httpx2.Request) -> httpx2.Response: captured.append(dict(request.headers)) return _ok_response([[0.1, 0.2, 0.3]]) async def scenario() -> None: - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(handler)) as client: model = _model(headers={"Authorization": "Bearer secret-key"}, http_client=client) await model.embed(("alpha",)) @@ -333,11 +333,11 @@ def test_embedding_model_name_strips_provider_prefix() -> None: ], ) def test_embed_classifies_http_status_reason(status_code, reason) -> None: - def handler(request: httpx.Request) -> httpx.Response: - return httpx.Response(status_code, json={"base_resp": {"status_code": 1000}}) + def handler(request: httpx2.Request) -> httpx2.Response: + return httpx2.Response(status_code, json={"base_resp": {"status_code": 1000}}) async def scenario() -> None: - async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(handler)) as client: model = _model(http_client=client) with pytest.raises(InferenceUnavailableError) as error: await model.embed(("alpha",)) diff --git a/tests/builtin/inference/test_privacy.py b/tests/builtin/inference/test_privacy.py index 778f1f8822..b15ae5b69d 100644 --- a/tests/builtin/inference/test_privacy.py +++ b/tests/builtin/inference/test_privacy.py @@ -22,11 +22,11 @@ from threading import Thread from typing import Any -import httpx +import httpx2 import pytest from anthropic import APIConnectionError as AnthropicConnectionError from anthropic import AsyncAnthropic -from openai import APIConnectionError, AsyncOpenAI +from openai import AsyncOpenAI from pydantic import BaseModel, SecretStr from pydantic_ai.models.openai import OpenAIChatModel from pydantic_ai.providers.openai import OpenAIProvider @@ -349,7 +349,7 @@ async def run(endpoint: str) -> None: update={"targets": {"test": protection.targets["test"].model_copy(update={"protocol": "openai-responses"})}} ) async with ( - httpx.AsyncClient(transport=ProtectedAsyncTransport(protection)) as http, + httpx2.AsyncClient(transport=ProtectedAsyncTransport(protection)) as http, AsyncOpenAI( base_url=endpoint.removesuffix("/responses"), api_key="test", max_retries=0, http_client=http ) as sdk, @@ -364,7 +364,7 @@ async def run(endpoint: str) -> None: ({"input": [{"id": "msg_prior_private", "type": None}], "store": False}, "content_unsupported"), ) for extra, reason in cases: - with pytest.raises(APIConnectionError) as caught: + with pytest.raises(InferencePrivacyError) as caught: await sdk.responses.create(model="test-model", max_output_tokens=10, **extra) refusal = find_privacy_error(caught.value) assert refusal is not None and refusal.phase == "before_send" @@ -389,7 +389,7 @@ async def run(endpoint: str) -> None: } ) async with ( - httpx.AsyncClient(transport=ProtectedAsyncTransport(protection)) as http, + httpx2.AsyncClient(transport=ProtectedAsyncTransport(protection)) as http, AsyncAnthropic( base_url=endpoint.removesuffix("/v1/messages"), api_key="test", max_retries=0, http_client=http ) as sdk, @@ -450,7 +450,7 @@ async def generate( usages: list[InferenceUsage] | None = None, ) -> Value: async with ( - httpx.AsyncClient(transport=ProtectedAsyncTransport(configuration or config(endpoint))) as http, + httpx2.AsyncClient(transport=ProtectedAsyncTransport(configuration or config(endpoint))) as http, AsyncOpenAI( base_url=endpoint.removesuffix("/chat/completions"), api_key="test", max_retries=0, http_client=http ) as sdk, @@ -507,7 +507,7 @@ def test_shadow_reports_input_rejection_without_blocking_real_request() -> None: async def run(endpoint: str) -> None: observed = [] shadow = config(endpoint).model_copy(update={"mode": "shadow"}) - async with httpx.AsyncClient(transport=ProtectedAsyncTransport(shadow, observer=observed.append)) as client: + async with httpx2.AsyncClient(transport=ProtectedAsyncTransport(shadow, observer=observed.append)) as client: received = await client.post(endpoint, content=body(SECRET), headers={"content-type": "application/json"}) assert received.status_code == 200 assert observed[0].decision == "block" @@ -520,7 +520,7 @@ async def run(endpoint: str) -> None: def test_strict_response_buffer_limit_releases_no_raw_content() -> None: async def run(endpoint: str) -> None: bounded = config(endpoint).model_copy(update={"max_response_bytes": 256}) - async with httpx.AsyncClient(transport=ProtectedAsyncTransport(bounded)) as client: + async with httpx2.AsyncClient(transport=ProtectedAsyncTransport(bounded)) as client: with pytest.raises(InferencePrivacyError, match="before_release") as caught: await client.post(endpoint, content=body("clean"), headers={"content-type": "application/json"}) assert caught.value.reason_codes == ("payload_too_large",) @@ -596,7 +596,7 @@ def test_sse_strict_transport_releases_no_content_before_joined_inspection( async def run(endpoint: str) -> None: released: list[bytes] = [] - async with httpx.AsyncClient( + async with httpx2.AsyncClient( transport=ProtectedAsyncTransport(config(endpoint, allow_streaming=True)) ) as client: with pytest.raises(InferencePrivacyError) as caught: @@ -634,7 +634,7 @@ async def run(endpoint: str) -> None: targets={"embed": UpstreamProfile(endpoint=endpoint, model="test-model", protocol="openai-embeddings")}, ) async with ( - httpx.AsyncClient(transport=ProtectedAsyncTransport(configuration)) as http, + httpx2.AsyncClient(transport=ProtectedAsyncTransport(configuration)) as http, AsyncOpenAI( base_url=endpoint.removesuffix("/embeddings"), api_key="test", max_retries=0, http_client=http ) as sdk, @@ -735,15 +735,15 @@ async def chunks(): reads += 1 yield b"x" * 128 - async def upstream(_request: httpx.Request) -> httpx.Response: + async def upstream(_request: httpx2.Request) -> httpx2.Response: nonlocal sent sent = True - return httpx.Response(200, json={}) + return httpx2.Response(200, json={}) async def run() -> None: protection = config().model_copy(update={"max_payload_bytes": 256}) - async with httpx.AsyncClient( - transport=ProtectedAsyncTransport(protection, transport=httpx.MockTransport(upstream)) + async with httpx2.AsyncClient( + transport=ProtectedAsyncTransport(protection, transport=httpx2.MockTransport(upstream)) ) as client: with pytest.raises(InferencePrivacyError) as caught: await client.post(ENDPOINT, content=chunks()) @@ -769,7 +769,7 @@ def test_failed_schema_validation_keeps_the_provider_reported_bill() -> None: def test_rejected_sse_preserves_its_cumulative_provider_usage() -> None: async def run(endpoint: str) -> None: - async with httpx.AsyncClient( + async with httpx2.AsyncClient( transport=ProtectedAsyncTransport(config(endpoint, allow_streaming=True)) ) as client: with pytest.raises(InferencePrivacyError) as caught: @@ -796,17 +796,17 @@ async def chunks(): yield b"first" yield b"second" - async def upstream(request: httpx.Request) -> httpx.Response: + async def upstream(request: httpx2.Request) -> httpx2.Response: assert await request.aread() == b"firstsecond" - return httpx.Response(200, content=b"unchanged") + return httpx2.Response(200, content=b"unchanged") async def run() -> None: transport = ProtectedAsyncTransport( config().model_copy(update={"mode": "shadow"}), - transport=httpx.MockTransport(upstream), + transport=httpx2.MockTransport(upstream), observer=observations.append, ) - async with httpx.AsyncClient(transport=transport) as client: + async with httpx2.AsyncClient(transport=transport) as client: result = await client.post(ENDPOINT, content=chunks()) assert result.content == b"unchanged" @@ -853,12 +853,12 @@ def test_native_stream_withholds_ambiguous_tool_indices(index: str) -> None: async def run(endpoint: str) -> None: async with ( - httpx.AsyncClient(transport=ProtectedAsyncTransport(config(endpoint, allow_streaming=True))) as http, + httpx2.AsyncClient(transport=ProtectedAsyncTransport(config(endpoint, allow_streaming=True))) as http, AsyncOpenAI( base_url=endpoint.removesuffix("/chat/completions"), api_key="test", max_retries=0, http_client=http ) as sdk, ): - with pytest.raises(APIConnectionError) as caught: + with pytest.raises(InferencePrivacyError) as caught: async with sdk.chat.completions.stream( model="test-model", messages=[{"role": "user", "content": "clean"}], @@ -885,7 +885,7 @@ async def run(endpoint: str) -> None: update={"targets": {"test": protection.targets["test"].model_copy(update={"protocol": "openai-responses"})}} ) async with ( - httpx.AsyncClient(transport=ProtectedAsyncTransport(protection)) as http, + httpx2.AsyncClient(transport=ProtectedAsyncTransport(protection)) as http, AsyncOpenAI( base_url=endpoint.removesuffix("/responses"), api_key="test", max_retries=0, http_client=http ) as sdk, @@ -895,12 +895,12 @@ async def run(endpoint: str) -> None: {"input": [item]}, ) for extra in cases: - with pytest.raises(APIConnectionError) as caught: + with pytest.raises(InferencePrivacyError) as caught: await sdk.responses.create(model="test-model", max_output_tokens=10, store=False, **extra) refusal = find_privacy_error(caught.value) assert refusal is not None and refusal.phase == "before_send" assert refusal.reason_codes == ("content_unsupported",) - with pytest.raises(APIConnectionError) as caught: + with pytest.raises(InferencePrivacyError) as caught: await sdk.responses.create(model="test-model", input="clean", max_output_tokens=10, store=False) refusal = find_privacy_error(caught.value) assert refusal is not None and refusal.phase == "before_release" @@ -990,12 +990,12 @@ async def scenario(endpoint: str) -> None: released = [] async with ( - httpx.AsyncClient(transport=ProtectedAsyncTransport(config(endpoint, allow_streaming=True))) as http, + httpx2.AsyncClient(transport=ProtectedAsyncTransport(config(endpoint, allow_streaming=True))) as http, AsyncOpenAI( base_url=endpoint.removesuffix("/chat/completions"), api_key="test", max_retries=0, http_client=http ) as sdk, ): - with pytest.raises(APIConnectionError) as caught: + with pytest.raises(InferencePrivacyError) as caught: async with sdk.chat.completions.stream( model="test-model", messages=[{"role": "user", "content": "clean"}], max_tokens=10 ) as stream: @@ -1053,7 +1053,7 @@ def test_native_stream_allows_tool_updates_in_different_order(initialization: st async def scenario(endpoint: str) -> None: async with ( - httpx.AsyncClient(transport=ProtectedAsyncTransport(config(endpoint, allow_streaming=True))) as http, + httpx2.AsyncClient(transport=ProtectedAsyncTransport(config(endpoint, allow_streaming=True))) as http, AsyncOpenAI( base_url=endpoint.removesuffix("/chat/completions"), api_key="test", max_retries=0, http_client=http ) as sdk, @@ -1104,7 +1104,7 @@ async def scenario(endpoint: str) -> None: released = [] async with ( - httpx.AsyncClient( + httpx2.AsyncClient( transport=ProtectedAsyncTransport( config(endpoint, allow_streaming=True, response_models=("approved-alias",)) ) @@ -1113,7 +1113,7 @@ async def scenario(endpoint: str) -> None: base_url=endpoint.removesuffix("/chat/completions"), api_key="test", max_retries=0, http_client=http ) as sdk, ): - with pytest.raises(APIConnectionError) as caught: + with pytest.raises(InferencePrivacyError) as caught: async with sdk.chat.completions.stream( model="test-model", messages=[{"role": "user", "content": "clean"}], max_tokens=10 ) as stream: @@ -1145,7 +1145,7 @@ async def scenario(endpoint: str) -> None: @pytest.mark.parametrize("carrier", ["reordered_name", "duplicate_name", "id"]) @pytest.mark.parametrize("preamble", [False, True]) -def test_native_stream_rejects_tool_text_assembled_by_sdk(carrier: str, preamble: bool) -> None: +def test_native_stream_withholds_ambiguous_or_forbidden_tool_identity(carrier: str, preamble: bool) -> None: first_call = { "index": 1 if carrier == "reordered_name" else 0, "id": "synthetic-forbidden-" if carrier == "id" else "call_first", @@ -1186,25 +1186,28 @@ def test_native_stream_rejects_tool_text_assembled_by_sdk(carrier: str, preamble payload = ("".join(f"data: {json.dumps(event)}\n\n" for event in events) + "data: [DONE]\n\n").encode() async def scenario(endpoint: str) -> None: - async with ( - AsyncOpenAI(base_url=endpoint.removesuffix("/chat/completions"), api_key="test", max_retries=0) as sdk, - sdk.chat.completions.stream( - model="test-model", messages=[{"role": "user", "content": "clean"}], max_tokens=10 - ) as stream, - ): - completion = await stream.get_final_completion() - calls = completion.choices[0].message.tool_calls - assert calls is not None and calls[0].type == "function" - assert (calls[0].id if carrier == "id" else calls[0].function.name) == SECRET + # Ambiguous indices must be withheld even when the SDK rejects or reinterprets them. + # Only the valid identity fragments have a portable SDK assembly result. + if carrier == "id": + async with ( + AsyncOpenAI(base_url=endpoint.removesuffix("/chat/completions"), api_key="test", max_retries=0) as sdk, + sdk.chat.completions.stream( + model="test-model", messages=[{"role": "user", "content": "clean"}], max_tokens=10 + ) as stream, + ): + completion = await stream.get_final_completion() + calls = completion.choices[0].message.tool_calls + assert calls is not None and calls[0].type == "function" + assert calls[0].id == SECRET released = [] async with ( - httpx.AsyncClient(transport=ProtectedAsyncTransport(config(endpoint, allow_streaming=True))) as http, + httpx2.AsyncClient(transport=ProtectedAsyncTransport(config(endpoint, allow_streaming=True))) as http, AsyncOpenAI( base_url=endpoint.removesuffix("/chat/completions"), api_key="test", max_retries=0, http_client=http ) as sdk, ): - with pytest.raises(APIConnectionError) as caught: + with pytest.raises(InferencePrivacyError) as caught: async with sdk.chat.completions.stream( model="test-model", messages=[{"role": "user", "content": "clean"}], max_tokens=10 ) as stream: diff --git a/tests/builtin/inference/test_pydantic_ai.py b/tests/builtin/inference/test_pydantic_ai.py index d54f1105c4..5437eb8f94 100644 --- a/tests/builtin/inference/test_pydantic_ai.py +++ b/tests/builtin/inference/test_pydantic_ai.py @@ -23,7 +23,7 @@ from datetime import UTC, datetime from typing import cast -import httpx +import httpx2 import pytest from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import SimpleSpanProcessor @@ -41,13 +41,12 @@ TestEmbeddingModel, ) from pydantic_ai.embeddings.result import EmbedInputType -from pydantic_ai.exceptions import ModelHTTPError, UsageLimitExceeded +from pydantic_ai.exceptions import ModelContextWindowExceededError, ModelHTTPError, UsageLimitExceeded from pydantic_ai.messages import ( FinishReason, ModelMessage, ModelRequest, ModelResponse, - RetryPromptPart, TextPart, ToolCallPart, UserPromptPart, @@ -252,9 +251,9 @@ def test_structured_generator_receipt_uses_reasoning_provider_settings( ) -> None: requests: list[dict[str, object]] = [] - def respond(request: httpx.Request) -> httpx.Response: + def respond(request: httpx2.Request) -> httpx2.Response: requests.append(json.loads(request.content)) - return httpx.Response( + return httpx2.Response( 200, json={ "id": "receipt-settings", @@ -273,7 +272,7 @@ def respond(request: httpx.Request) -> httpx.Response: ) async def scenario() -> None: - async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as client: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as client: settings: OpenAIChatModelSettings = {"temperature": 0.0, "top_p": 0.2, "max_tokens": 512} settings.update(overrides) generator = PydanticAIStructuredGenerator( @@ -336,9 +335,12 @@ async def respond(messages: list[ModelMessage], info: AgentInfo) -> ModelRespons nonlocal calls calls += 1 observed_max_tokens.append(None if info.model_settings is None else info.model_settings.get("max_tokens")) - retry_feedback.extend( - part.model_response() for message in messages for part in message.parts if isinstance(part, RetryPromptPart) - ) + if calls > 1: + retry_feedback.extend( + part.content + for part in messages[-1].parts + if isinstance(part, UserPromptPart) and isinstance(part.content, str) + ) text = ( '{"candidates":[{"text":"candidate"}]}' if calls == 1 @@ -955,12 +957,18 @@ async def scenario() -> None: asyncio.run(scenario()) -def test_embedding_adapter_classifies_a_provider_context_limit_without_leaking_the_body() -> None: +@pytest.mark.parametrize("http_error", [False, True]) +def test_embedding_adapter_classifies_a_provider_context_limit_without_leaking_the_body(http_error: bool) -> None: async def scenario() -> None: - provider_error = ModelHTTPError( - 400, - "result-model", - {"error": {"message": "maximum context length is 8192 tokens, body secret-provider-body"}}, + provider_error = ( + ModelHTTPError.for_category( + ModelContextWindowExceededError, + status_code=400, + model_name="result-model", + body={"error": {"message": "secret-provider-body"}}, + ) + if http_error + else ModelContextWindowExceededError("result-model", "secret-provider-body") ) adapter = PydanticAIEmbeddingModel( embedder=Embedder(ResultEmbeddingModel((), error=provider_error)), diff --git a/tests/builtin/runtime/test_composition_embedding.py b/tests/builtin/runtime/test_composition_embedding.py index 33cc02e906..38248e52b7 100644 --- a/tests/builtin/runtime/test_composition_embedding.py +++ b/tests/builtin/runtime/test_composition_embedding.py @@ -232,16 +232,16 @@ async def scenario() -> None: def test_embedding_models_use_minimax_adapter_for_minimax_host(monkeypatch) -> None: import json - import httpx + import httpx2 from pydantic import AnyHttpUrl, SecretStr from powercontext.builtin.inference.minimax import MiniMaxEmbeddingModel captured: list[dict[str, Any]] = [] - def handler(request: httpx.Request) -> httpx.Response: + def handler(request: httpx2.Request) -> httpx2.Response: captured.append(json.loads(request.content)) - return httpx.Response( + return httpx2.Response( 200, json={ "vectors": [[0.1] * 1536], @@ -250,13 +250,13 @@ def handler(request: httpx.Request) -> httpx.Response: }, ) - original_async_client = httpx.AsyncClient + original_async_client = httpx2.AsyncClient - def make_client(*args, **kwargs) -> httpx.AsyncClient: - return original_async_client(transport=httpx.MockTransport(handler)) + def make_client(*args, **kwargs) -> httpx2.AsyncClient: + return original_async_client(transport=httpx2.MockTransport(handler)) - # MiniMaxEmbeddingModel builds its own httpx.AsyncClient; route it to the mock. - monkeypatch.setattr(httpx, "AsyncClient", make_client) + # MiniMaxEmbeddingModel builds its own httpx2.AsyncClient; route it to the mock. + monkeypatch.setattr(httpx2, "AsyncClient", make_client) async def scenario() -> None: config = InferenceConfig( @@ -270,7 +270,7 @@ async def scenario() -> None: operational, _readiness = await _embedding_models(config, resources, None) assert operational is not None assert isinstance(operational, MiniMaxEmbeddingModel) - # The embedding adapter owns an httpx client registered with the runtime + # The embedding adapter owns an httpx2 client registered with the runtime # stack, so it must be exercised before the stack closes it. result = await operational.embed(("hello",)) assert len(result.vectors) == 1 diff --git a/tests/builtin/runtime/test_topic_memory_work_budget.py b/tests/builtin/runtime/test_topic_memory_work_budget.py index 193a256b8f..b405352ebf 100644 --- a/tests/builtin/runtime/test_topic_memory_work_budget.py +++ b/tests/builtin/runtime/test_topic_memory_work_budget.py @@ -24,7 +24,7 @@ from types import SimpleNamespace from typing import Any, cast -import httpx +import httpx2 import pytest from pydantic import SecretStr from sqlalchemy import select @@ -355,7 +355,7 @@ async def scenario(): async def fail(request): calls.append(request) - return httpx.Response( + return httpx2.Response( 429, headers={"retry-after": "0"}, json={"error": {"message": "busy", "type": "rate_limit_error"}} ) @@ -374,7 +374,7 @@ async def fail(request): client = provider.client assert client.max_retries == 0 # Preserve the SDK's real request/retry implementation; substitute transport only. - transport = await resources.enter_async_context(httpx.AsyncClient(transport=httpx.MockTransport(fail))) + transport = await resources.enter_async_context(httpx2.AsyncClient(transport=httpx2.MockTransport(fail))) client._client = transport with pytest.raises(Exception, match="busy"): if provider_name == "openai": @@ -551,10 +551,11 @@ async def respond(_messages, _info): asyncio.run(scenario()) -def test_unsupported_worker_provider_fails_when_binding_is_assembled(): +@pytest.mark.parametrize("provider", ["google", "openai-codex"]) +def test_unsupported_worker_provider_fails_when_binding_is_assembled(provider): config = BuiltinConfig( database=SQLiteConfig(url="sqlite+aiosqlite:///not-opened.sqlite3"), - inference=InferenceConfig(generation_model="google:test"), + inference=InferenceConfig(generation_model=f"{provider}:test"), runtime=RuntimeConfig(topic_memory_schedule_seconds=60, artifact_processing_families=("topic-memory",)), ) with pytest.raises(BuiltinConfigurationError, match="bounded stateless"): diff --git a/tests/e2e/rfc2086_real_acceptance.py b/tests/e2e/rfc2086_real_acceptance.py index 8a7f6deee3..cbff0b5ad1 100644 --- a/tests/e2e/rfc2086_real_acceptance.py +++ b/tests/e2e/rfc2086_real_acceptance.py @@ -37,7 +37,7 @@ from pathlib import Path from typing import Any -import httpx +import httpx2 from pydantic import BaseModel, ConfigDict from powercontext.builtin.inference.pydantic_ai import InferenceLimits, PydanticAIStructuredGenerator @@ -99,7 +99,7 @@ def __init__(self, directory: Path, report: dict[str, Any]) -> None: self.attempts: list[dict[str, Any]] = [] report["http_attempts"] = self.attempts - async def on_request(self, request: httpx.Request) -> None: + async def on_request(self, request: httpx2.Request) -> None: body = await request.aread() self.attempts.append({ "ordinal": len(self.attempts) + 1, @@ -112,7 +112,7 @@ async def on_request(self, request: httpx.Request) -> None: }) write_report(self.directory, self.report) - async def on_response(self, response: httpx.Response) -> None: + async def on_response(self, response: httpx2.Response) -> None: raw = await response.aread() attempt = self.attempts[-1] attempt["state"] = "response_received" @@ -200,7 +200,7 @@ async def probe_model( report["protocol"] = "openai-chat" recorder = RequestEvidence(directory, report) async with ( - httpx.AsyncClient( + httpx2.AsyncClient( timeout=45, follow_redirects=False, event_hooks={"request": [recorder.on_request], "response": [recorder.on_response]}, @@ -273,7 +273,7 @@ def main() -> int: "status": "RUNNING", "mode": args.mode, "started_at": datetime.now(UTC).isoformat(), - "versions": {package: version(package) for package in ("pydantic-ai-slim", "openai", "httpx", "sqlalchemy")}, + "versions": {package: version(package) for package in ("pydantic-ai-slim", "openai", "httpx2", "sqlalchemy")}, "synthetic_inputs_only": True, "provider_calls_authorized": True, "database_writes_authorized": "unique-run-scope-only", diff --git a/tests/e2e/test_atomic_memory_reconciliation_retry.py b/tests/e2e/test_atomic_memory_reconciliation_retry.py index a2f50c6341..a11d7be8a1 100644 --- a/tests/e2e/test_atomic_memory_reconciliation_retry.py +++ b/tests/e2e/test_atomic_memory_reconciliation_retry.py @@ -19,7 +19,7 @@ import asyncio import json -from pydantic_ai.messages import ModelMessage, ModelRequest, ModelResponse, RetryPromptPart, TextPart, UserPromptPart +from pydantic_ai.messages import ModelMessage, ModelRequest, ModelResponse, TextPart, UserPromptPart from pydantic_ai.models.function import AgentInfo, FunctionModel from powercontext.builtin.inference import InvalidInferenceOutputError @@ -42,9 +42,11 @@ def __init__(self, *, corrects: bool) -> None: async def respond(self, messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse: request = messages[-1] assert isinstance(request, ModelRequest) - retries = [part for part in request.parts if isinstance(part, RetryPromptPart)] + retries = [ + part for part in request.parts if isinstance(part, UserPromptPart) and REVISE_RULE in str(part.content) + ] self.retry_feedback.extend(str(part.content) for part in retries) - (prompt,) = ( + prompt = next( part.content for message in messages if isinstance(message, ModelRequest) diff --git a/tests/e2e/test_atomic_memory_related_embedding.py b/tests/e2e/test_atomic_memory_related_embedding.py index 9cc433a71f..a5090b1ec3 100644 --- a/tests/e2e/test_atomic_memory_related_embedding.py +++ b/tests/e2e/test_atomic_memory_related_embedding.py @@ -21,7 +21,7 @@ from dataclasses import replace from datetime import UTC, datetime, timedelta -import httpx +import httpx2 import pytest from powercontext.artifacts.search import ArtifactSearchExecutionContext @@ -537,13 +537,13 @@ def respond(request): [1.0, 0.0, 0.0] if body["type"] == "query" or ORIGINAL in text else [0.0, 1.0, 0.0] for text in body["texts"] ] - return httpx.Response( + return httpx2.Response( 200, json={"vectors": vectors, "total_tokens": len(vectors), "base_resp": {"status_code": 0}} ) async def scenario(): async with ( - httpx.AsyncClient(transport=httpx.MockTransport(respond)) as client, + httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as client, open_builtin_contexts( _config(tmp_path), embedding_model=_minimax(client), candidate_pipeline=_pipeline() ) as contexts, @@ -592,11 +592,11 @@ def respond(self, request): self.document_requests.append(body) failure = self.query_failure if body["type"] == "query" else self.document_failure if failure == "timeout": - raise httpx.ReadTimeout("Embedding deadline expired", request=request) # noqa: TRY003 + raise httpx2.ReadTimeout("Embedding deadline expired", request=request) # noqa: TRY003 if failure == "unavailable": - return httpx.Response(503, json={"error": "temporarily unavailable"}) + return httpx2.Response(503, json={"error": "temporarily unavailable"}) vectors = [[1.0, 0.0, 0.0] for _ in body["texts"]] - return httpx.Response( + return httpx2.Response( 200, json={"vectors": vectors, "total_tokens": len(vectors), "base_resp": {"status_code": 0}} ) @@ -609,7 +609,7 @@ def test_related_query_failure_uses_fts_only_when_opted_in(tmp_path, failure, fa async def scenario(): async with ( - httpx.AsyncClient(transport=httpx.MockTransport(endpoint.respond)) as client, + httpx2.AsyncClient(transport=httpx2.MockTransport(endpoint.respond)) as client, open_builtin_contexts( _config(tmp_path, fallback=fallback), embedding_model=_minimax(client), candidate_pipeline=_pipeline() ) as contexts, @@ -645,7 +645,7 @@ def test_related_fts_fallback_does_not_hide_document_embedding_failure(tmp_path, async def scenario(): async with ( - httpx.AsyncClient(transport=httpx.MockTransport(endpoint.respond)) as client, + httpx2.AsyncClient(transport=httpx2.MockTransport(endpoint.respond)) as client, open_builtin_contexts( _config(tmp_path, fallback=True), embedding_model=_minimax(client), diff --git a/tests/e2e/test_inference_observation_retries.py b/tests/e2e/test_inference_observation_retries.py index ecb3137294..bca4a014ca 100644 --- a/tests/e2e/test_inference_observation_retries.py +++ b/tests/e2e/test_inference_observation_retries.py @@ -21,7 +21,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from threading import Thread -import httpx +import httpx2 import pytest from anthropic import AsyncAnthropic from openai import AsyncOpenAI @@ -178,7 +178,7 @@ async def scenario(): base_url = f"http://127.0.0.1:{upstream.server_port}" + ("" if provider == "anthropic" else "/v1") observations = [] transport = ProtectedAsyncTransport(_protection(base_url, provider, mode), observer=observations.append) - async with httpx.AsyncClient(transport=transport) as http: + async with httpx2.AsyncClient(transport=transport) as http: if provider == "anthropic": async with AsyncAnthropic(base_url=base_url, api_key="synthetic-retry-key", http_client=http) as sdk: await sdk.messages.create( diff --git a/tests/e2e/test_jev_memory_reranking.py b/tests/e2e/test_jev_memory_reranking.py index bf0b3b7a47..f5527ba53e 100644 --- a/tests/e2e/test_jev_memory_reranking.py +++ b/tests/e2e/test_jev_memory_reranking.py @@ -22,6 +22,7 @@ from uuid import uuid4 import httpx +import httpx2 import pytest from pydantic import SecretStr from starlette.middleware import Middleware @@ -49,8 +50,8 @@ async def respond(request): if failure == "timeout": await asyncio.Event().wait() if failure == "unavailable": - return httpx.Response(429) - return httpx.Response( + return httpx2.Response(429) + return httpx2.Response( 200, json={ "model": "jev-1.13.0", @@ -63,7 +64,7 @@ async def record_effort(effort): efforts.append(effort) async def scenario(): - async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as provider: + async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as provider: reranker = JevMemoryReranker( JevRerankConfig( endpoint="https://api.typesafe.ai/v1/systemone", diff --git a/tests/e2e/test_responses_output_privacy.py b/tests/e2e/test_responses_output_privacy.py index 2863a98b94..84e7301aa7 100644 --- a/tests/e2e/test_responses_output_privacy.py +++ b/tests/e2e/test_responses_output_privacy.py @@ -19,13 +19,13 @@ import asyncio import json -import httpx +import httpx2 import pytest -from openai import APIConnectionError, AsyncOpenAI +from openai import AsyncOpenAI from openai.types.responses.response_create_params import ResponseCreateParamsNonStreaming from pydantic import SecretStr -from powercontext.builtin.inference.errors import find_privacy_error +from powercontext.builtin.inference.errors import InferencePrivacyError, find_privacy_error from powercontext.builtin.inference.privacy import InferenceProtectionConfig, UpstreamProfile from powercontext.builtin.inference.protected_transport import ProtectedAsyncTransport from tests.e2e.test_rfc2086_transport_acceptance import RecordingServer, upstream @@ -110,10 +110,10 @@ async def scenario(server: RecordingServer): api_key="synthetic", base_url=base_url, max_retries=0, - http_client=httpx.AsyncClient(transport=transport), + http_client=httpx2.AsyncClient(transport=transport), ) as protected: if blocked: - with pytest.raises(APIConnectionError) as rejected: + with pytest.raises(InferencePrivacyError) as rejected: await protected.responses.create(**request) privacy = find_privacy_error(rejected.value) assert privacy is not None and privacy.phase == "before_release" diff --git a/tests/e2e/test_rfc2086_transport_acceptance.py b/tests/e2e/test_rfc2086_transport_acceptance.py index 63d53a312e..a8cc0cb84e 100644 --- a/tests/e2e/test_rfc2086_transport_acceptance.py +++ b/tests/e2e/test_rfc2086_transport_acceptance.py @@ -28,7 +28,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from typing import Any, cast -import httpx +import httpx2 import pytest from pydantic import SecretStr @@ -88,7 +88,7 @@ def completion(content: str = "safe") -> bytes: }).encode() -def protected_client(server: RecordingServer) -> httpx.AsyncClient: +def protected_client(server: RecordingServer) -> httpx2.AsyncClient: target = f"http://127.0.0.1:{server.server_port}/v1/chat/completions" config = InferenceProtectionConfig( mode="enforcing", @@ -105,7 +105,7 @@ def protected_client(server: RecordingServer) -> httpx.AsyncClient: ) }, ) - return httpx.AsyncClient( + return httpx2.AsyncClient( transport=ProtectedAsyncTransport(config), base_url=f"http://127.0.0.1:{server.server_port}", timeout=5 ) diff --git a/tests/evaluation/test_jev_rerank_comparison.py b/tests/evaluation/test_jev_rerank_comparison.py index c36f1f6729..fecc82a77b 100644 --- a/tests/evaluation/test_jev_rerank_comparison.py +++ b/tests/evaluation/test_jev_rerank_comparison.py @@ -497,7 +497,7 @@ def test_comparison_billing_through_persisted_candidates( # noqa: C901 ): from contextlib import asynccontextmanager - import httpx + import httpx2 from pydantic_ai.messages import ModelResponse, TextPart, UserPromptPart from pydantic_ai.models.function import FunctionModel @@ -521,7 +521,7 @@ async def runtime_with_embedding(config, **kwargs): async with open_builtin_runtime(config, embedding_model=Embedding(), **kwargs) as runtime: yield runtime - original_client = httpx.AsyncClient + original_client = httpx2.AsyncClient def respond_model(messages, _info): value = next( @@ -538,14 +538,14 @@ def respond_model(messages, _info): def respond_native(request): model_requests.append(request) if provider_failure == "timeout" and len(model_requests) == 1: - raise httpx.ReadTimeout("response lost", request=request) # noqa: TRY003 + raise httpx2.ReadTimeout("response lost", request=request) # noqa: TRY003 body = json.loads(request.content) prompt = json.dumps(body["messages"][-1]["content"]) is_judge = "gold_answer" in prompt is_rerank = "max_results" in prompt output = {"label": "CORRECT"} if is_judge else {"selected_ranks": [1]} if is_rerank else {"answer": "OceanBase"} if provider == "anthropic": - return httpx.Response( + return httpx2.Response( 200, json={ "id": "msg-test", @@ -566,7 +566,7 @@ def respond_native(request): ), }, ) - return httpx.Response( + return httpx2.Response( 200, json={ "id": "chatcmpl-test", @@ -605,17 +605,20 @@ def respond_native(request): else: monkeypatch.setenv("OPENAI_API_KEY" if provider == "openai-chat" else "ANTHROPIC_API_KEY", "test-key") monkeypatch.setattr( - f"pydantic_ai.providers.{'openai' if provider == 'openai-chat' else 'anthropic'}.create_async_http_client", - lambda: original_client(transport=httpx.MockTransport(respond_native)), + f"pydantic_ai.providers.{'_openai_compatible' if provider == 'openai-chat' else 'anthropic'}.create_async_httpx2_client", + lambda: original_client(transport=httpx2.MockTransport(respond_native)), ) + # The billing fixture returns JSON, independent of provider output defaults. + benchmark_settings = runner._benchmark_model_settings + monkeypatch.setattr(runner, "_benchmark_model_settings", lambda: benchmark_settings() | {"max_tokens": 256}) monkeypatch.setattr(runner, "open_builtin_runtime", runtime_with_embedding) monkeypatch.setattr( runner, - "httpx", + "httpx2", SimpleNamespace( AsyncClient=lambda: original_client( - transport=httpx.MockTransport( - lambda _: httpx.Response( + transport=httpx2.MockTransport( + lambda _: httpx2.Response( 200, json={ "model": "jev-1.13.0", diff --git a/tests/examples/openai_sdk/test_openai_sdk_example.py b/tests/examples/openai_sdk/test_openai_sdk_example.py index 6771a8fbb8..15152f8a3c 100644 --- a/tests/examples/openai_sdk/test_openai_sdk_example.py +++ b/tests/examples/openai_sdk/test_openai_sdk_example.py @@ -18,6 +18,7 @@ import json import httpx +import httpx2 import pytest pytest.importorskip("openai") @@ -56,22 +57,22 @@ def _completion(text: str) -> dict[str, object]: } -def _run(prepared: dict[str, object]) -> tuple[list[httpx.Request], list[httpx.Request], str, str]: +def _run(prepared: dict[str, object]) -> tuple[list[httpx.Request], list[httpx2.Request], str, str]: powercontext_requests: list[httpx.Request] = [] - model_requests: list[httpx.Request] = [] + model_requests: list[httpx2.Request] = [] def powercontext_handler(request: httpx.Request) -> httpx.Response: powercontext_requests.append(request) return httpx.Response(200, json=prepared) - def model_handler(request: httpx.Request) -> httpx.Response: + def model_handler(request: httpx2.Request) -> httpx2.Response: model_requests.append(request) - return httpx.Response(200, json=_completion("Check eligibility first.")) + return httpx2.Response(200, json=_completion("Check eligibility first.")) async def scenario() -> tuple[str, str]: async with ( httpx.AsyncClient(transport=httpx.MockTransport(powercontext_handler)) as powercontext_http, - httpx.AsyncClient(transport=httpx.MockTransport(model_handler)) as model_http, + httpx2.AsyncClient(transport=httpx2.MockTransport(model_handler)) as model_http, ): powercontext = PowerContextClient( "http://127.0.0.1:8000", token=POWERCONTEXT_TOKEN, http_client=powercontext_http @@ -86,7 +87,7 @@ async def scenario() -> tuple[str, str]: return powercontext_requests, model_requests, status, reply -def _messages(request: httpx.Request) -> list[dict[str, str]]: +def _messages(request: httpx2.Request) -> list[dict[str, str]]: return json.loads(request.content)["messages"] diff --git a/tests/pydantic_ai_adapter/test_toolset.py b/tests/pydantic_ai_adapter/test_toolset.py index f41c9a5896..0a9ee2068f 100644 --- a/tests/pydantic_ai_adapter/test_toolset.py +++ b/tests/pydantic_ai_adapter/test_toolset.py @@ -21,7 +21,7 @@ import pytest from powercontext_pydantic_ai import PowerContextToolset from pydantic_ai import Agent -from pydantic_ai.messages import ModelResponse, RetryPromptPart, TextPart, ToolCallPart, ToolReturnPart +from pydantic_ai.messages import ModelResponse, TextPart, ToolCallPart, ToolReturnPart from pydantic_ai.models.function import FunctionModel from powercontext.client import TransportError @@ -121,10 +121,15 @@ def test_toolset_converts_client_failure_to_model_retry(monkeypatch: pytest.Monk RecordingClient.reset() RecordingClient.search_result = TransportError("/v1/memory/search") monkeypatch.setattr(toolset_module, "PowerContextClient", RecordingClient) - retry_parts: list[RetryPromptPart] = [] + retry_parts: list[ToolReturnPart] = [] async def respond(messages, _info): - retry_parts.extend(part for message in messages for part in message.parts if isinstance(part, RetryPromptPart)) + retry_parts.extend( + part + for message in messages + for part in message.parts + if isinstance(part, ToolReturnPart) and part.outcome == "retried" + ) if retry_parts: return ModelResponse(parts=[TextPart("recovered from retry")]) return ModelResponse(parts=[ToolCallPart("powercontext_search", {"query": "missing"}, "search-failure")]) diff --git a/tests/test_inference_endpoints.py b/tests/test_inference_endpoints.py index 5b4cfc4bc8..e8b06cdc64 100644 --- a/tests/test_inference_endpoints.py +++ b/tests/test_inference_endpoints.py @@ -219,7 +219,7 @@ async def scenario() -> None: assert readiness.checks["inference.generation"] == "ready" assert server.requests assert server.requests[0]["path"] == "/v1/messages" - assert server.requests[0]["headers"]["x-api-key"] == "anthropic-standard-key" + assert server.requests[0]["headers"]["authorization"] == "Bearer anthropic-standard-key" asyncio.run(scenario()) @@ -263,7 +263,7 @@ async def scenario() -> None: asyncio.run(scenario()) -def test_anthropic_custom_endpoint_with_bearer_header_keeps_environment_api_key( +def test_anthropic_custom_endpoint_with_bearer_header_overrides_environment_authentication( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, ) -> None: @@ -287,7 +287,6 @@ async def scenario() -> None: assert server.requests request = server.requests[0] assert request["path"] == "/v1/messages" - assert request["headers"]["x-api-key"] == "anthropic-standard-key" assert request["headers"]["authorization"] == "Bearer gateway-token" asyncio.run(scenario()) diff --git a/tests/test_locomo_plus_runner.py b/tests/test_locomo_plus_runner.py index abeb7c9f60..2a9c21c6b6 100644 --- a/tests/test_locomo_plus_runner.py +++ b/tests/test_locomo_plus_runner.py @@ -26,7 +26,7 @@ import pytest from pydantic import SecretStr -from pydantic_ai.messages import ModelResponse, RetryPromptPart, TextPart, UserPromptPart +from pydantic_ai.messages import ModelResponse, TextPart, UserPromptPart from pydantic_ai.models.function import FunctionModel from sqlalchemy.engine import make_url @@ -1506,7 +1506,9 @@ def test_extraction_corrects_invalid_json_within_the_configured_request_budget( async def extract(messages, info): nonlocal requests requests += 1 - correcting = any(isinstance(part, RetryPromptPart) for message in messages for part in message.parts) + correcting = any( + isinstance(part, TextPart) and part.content == malformed for message in messages for part in message.parts + ) request = next( AtomicMemoryExtractionInput.model_validate_json(part.content) for message in messages diff --git a/tests/test_server.py b/tests/test_server.py index 8fe93f95c7..44b184346c 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -21,6 +21,7 @@ from pathlib import Path import httpx +import httpx2 import pytest from fastapi.testclient import TestClient from pydantic import SecretStr, ValidationError @@ -1047,11 +1048,11 @@ async def scenario() -> None: def test_server_factory_reports_missing_embedding_api_prefix_as_degraded(caplog, monkeypatch, tmp_path) -> None: now = [0.0] monkeypatch.setattr("powercontext.builtin.runtime.readiness.monotonic", lambda: now[0]) - requests: list[httpx.Request] = [] + requests: list[httpx2.Request] = [] - def reject(request: httpx.Request) -> httpx.Response: + def reject(request: httpx2.Request) -> httpx2.Response: requests.append(request) - return httpx.Response( + return httpx2.Response( 404, json={ "error": { @@ -1065,7 +1066,7 @@ def reject(request: httpx.Request) -> httpx.Response: provider = OpenAIProvider( base_url="https://provider.example", api_key="secret-api-key", - http_client=httpx.AsyncClient(transport=httpx.MockTransport(reject)), + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(reject)), ) monkeypatch.setattr("pydantic_ai.providers.infer_provider", lambda _name: provider) app = create_server_app( diff --git a/tests/test_server_tracing.py b/tests/test_server_tracing.py index 9c1063dcda..b2f9a0d517 100644 --- a/tests/test_server_tracing.py +++ b/tests/test_server_tracing.py @@ -183,7 +183,13 @@ async def scenario() -> None: span = next(span for span in exporter.get_finished_spans() if span.name.startswith("chat ")) assert span.status.status_code is StatusCode.ERROR assert span.status.description in (None, "") - assert span.events == () + assert len(span.events) == 1 + event = span.events[0] + assert event.name == "exception" + assert dict(event.attributes or {}) == { + "exception.type": "pydantic_ai.exceptions.ModelHTTPError", + "exception.escaped": "False", + } attributes = span.attributes or {} assert attributes["error.type"] == "ModelHTTPError" rendered = repr(dict(attributes)) + repr(span.events) + str(span.status.description) diff --git a/uv.lock b/uv.lock index 8d44135ab7..0e1595a2e3 100644 --- a/uv.lock +++ b/uv.lock @@ -2,7 +2,8 @@ version = 1 revision = 3 requires-python = ">=3.11, <4.0" resolution-markers = [ - "python_full_version >= '3.14'", + "python_full_version >= '3.15'", + "python_full_version == '3.14.*'", "python_full_version >= '3.12' and python_full_version < '3.14'", "python_full_version < '3.12'", ] @@ -74,21 +75,21 @@ wheels = [ [[package]] name = "anthropic" -version = "0.117.0" +version = "2.3.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio" }, - { name = "distro" }, { name = "docstring-parser" }, - { name = "httpx" }, + { name = "httpx2" }, { name = "jiter" }, + { name = "opentelemetry-api" }, { name = "pydantic" }, { name = "sniffio" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/41/0d/8f71d535edb0d438f023bd825fb65f67c14fa88a2bd6b75f292a58a63de4/anthropic-0.117.0.tar.gz", hash = "sha256:98107f2b76439641e0ae2a1754087534b8f178dbab99d6eb1bc4b7bc8c744496", size = 989933, upload-time = "2026-07-16T19:36:13.07Z" } +sdist = { url = "https://files.pythonhosted.org/packages/3e/ba/4c91947e0d0062d66d371db371597287153f7685fbed512d3294d0cde3c7/anthropic-2.3.0.tar.gz", hash = "sha256:edfdea1e3fa7b3ce25df1511953408b2f03bfa61eb6f6268f766101a9e18ad53", size = 1869656, upload-time = "2026-10-23T23:18:47.649Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b7/4c/917d21d6619a4475cdafc6d13a69fdb3b901ddac57e76caca5a25c117b6d/anthropic-0.117.0-py3-none-any.whl", hash = "sha256:451a0a6905f11dff7663d13e4ee5dbf909eb8942b1d049803c7b937a13ac47ec", size = 998327, upload-time = "2026-07-16T19:36:11.225Z" }, + { url = "https://files.pythonhosted.org/packages/3f/29/eb3558ab6bf252a07ac41c76ac5b0ea24a0aa0c23f87a40aaf31a5f8dba4/anthropic-2.3.0-py3-none-any.whl", hash = "sha256:aa6a3984f9276f307933d42dc6f58b6efc821a5ecafbc8d1bb5993a066767622", size = 2216980, upload-time = "2026-10-23T23:18:45.779Z" }, ] [[package]] @@ -1003,15 +1004,36 @@ wheels = [ [[package]] name = "genai-prices" -version = "0.1.2" +version = "0.1.13" source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.15'", +] dependencies = [ - { name = "httpx2" }, - { name = "pydantic" }, + { name = "httpx2", marker = "python_full_version >= '3.15'" }, + { name = "pydantic", marker = "python_full_version >= '3.15'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ad/de/119c7ba00b9ddbf629de34cf390ab472da6d7bc5df0c51cdbec900280a74/genai_prices-0.1.13.tar.gz", hash = "sha256:76c9e2dd3917fdacdf3bc562297c4591384142ea2283c477e1512fafa4e3a384", size = 134622, upload-time = "2026-10-15T09:47:04.739Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/41/5a/b6b7d55148d367d07bcd3efdf24e3086ad199ea5109d0c335a872dfaac95/genai_prices-0.1.13-py3-none-any.whl", hash = "sha256:6d2b40760a2f7f5e207bac9b98de0af80e60c58ead497872a5331a7cee610477", size = 142541, upload-time = "2026-10-15T09:47:03.424Z" }, +] + +[[package]] +name = "genai-prices" +version = "0.2.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version == '3.14.*'", + "python_full_version >= '3.12' and python_full_version < '3.14'", + "python_full_version < '3.12'", +] +dependencies = [ + { name = "httpx2", marker = "python_full_version < '3.15'" }, + { name = "pydantic", marker = "python_full_version < '3.15'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/b1/e1/203175825018a5dcdc5fde62afae57c0aa844ff1584d6c8d148107623f59/genai_prices-0.1.2.tar.gz", hash = "sha256:930ffd34e3b65e32d24818073a2fb65f0174c4de7f6afbebfee1efdf8b003877", size = 92403, upload-time = "2026-08-12T17:20:33.468Z" } +sdist = { url = "https://files.pythonhosted.org/packages/48/1f/f5748da2ef5ce0a3d7735cbfc499cc76d8333876fd4d5942bf72e03e01f7/genai_prices-0.2.1.tar.gz", hash = "sha256:d3c19682e63ae3827e7d166fc92c0f69943f446aa58725f38090301ca1cae36d", size = 159033, upload-time = "2026-10-30T19:03:16.883Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a8/aa/54f2e6ed2699889fb5b062b1a6a58afa46f9fd0d095dc183e2173bd0b415/genai_prices-0.1.2-py3-none-any.whl", hash = "sha256:bdcdb9b358de01d9c3d4337a86b8dbfbf4e8044c2c064e6e3c4a6fef2f640382", size = 96579, upload-time = "2026-08-12T17:20:32.159Z" }, + { url = "https://files.pythonhosted.org/packages/6c/0d/5af9dc89b77ae76eaeacde63bb6cbb2d0be9562f82fd2fa476909f431e16/genai_prices-0.2.1-py3-none-any.whl", hash = "sha256:b438753161537f2e2a5c937887721467dd5a24297a52ae77f946f541ce22c3a0", size = 168200, upload-time = "2026-10-30T19:03:15.339Z" }, ] [[package]] @@ -1225,7 +1247,7 @@ name = "importlib-metadata" version = "9.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "zipp" }, + { name = "zipp", marker = "python_full_version < '3.12'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/a9/01/15bb152d77b21318514a96f43af312635eb2500c96b55398d020c93d86ea/importlib_metadata-9.0.0.tar.gz", hash = "sha256:a4f57ab599e6a2e3016d7595cfd72eb4661a5106e787a95bcc90c7105b831efc", size = 56405, upload-time = "2026-03-20T06:42:56.999Z" } wheels = [ @@ -2298,7 +2320,8 @@ name = "numpy" version = "2.5.1" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version >= '3.14'", + "python_full_version >= '3.15'", + "python_full_version == '3.14.*'", "python_full_version >= '3.12' and python_full_version < '3.14'", ] sdist = { url = "https://files.pythonhosted.org/packages/22/fd/89965aa4ac08c74998539fcbf24fa3540f3e15237fbeb6bcf9c908f4aade/numpy-2.5.1.tar.gz", hash = "sha256:a48a113e6afea91f5608793bafa7ef2ad481fefbda87ec5069f483de61cb9fa3", size = 20755553, upload-time = "2026-07-04T17:08:00.933Z" } @@ -2350,21 +2373,19 @@ wheels = [ [[package]] name = "openai" -version = "2.46.0" +version = "3.42.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio" }, - { name = "distro" }, - { name = "httpx" }, + { name = "httpx2" }, { name = "jiter" }, { name = "pydantic" }, { name = "sniffio" }, - { name = "tqdm" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/af/ac/f725c4efbda8657d02be684607e5a2e5ce362e4790fdbcbdfb7c15018647/openai-2.46.0.tar.gz", hash = "sha256:0421e0735ac41451cad894af4cddf0435bfbf8cbc538ac0e15b3c062f2ddc06a", size = 1114628, upload-time = "2026-07-17T02:48:06.05Z" } +sdist = { url = "https://files.pythonhosted.org/packages/9f/7b/e01d5288d13e3bae3714ed39df402f99f88f422dcd978c5ce94848037200/openai-3.42.1.tar.gz", hash = "sha256:4222d919374648ff572753626e942f26eb1ece8a5e0e9a2708c9be4d560f070f", size = 2356422, upload-time = "2026-11-01T20:57:02.607Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ea/7b/206238ebcb50b235942b1c66dba4974776f2057402a8d91c399be587d66a/openai-2.46.0-py3-none-any.whl", hash = "sha256:672381db55efb3a1e2610f29304c130cccdd0b319bace4d492b2443cb64c1e7c", size = 1637556, upload-time = "2026-07-17T02:48:03.695Z" }, + { url = "https://files.pythonhosted.org/packages/fd/11/37b847d8a057000193974eeea1bcc681355ae50d35865f2eb2b323de6153/openai-3.42.1-py3-none-any.whl", hash = "sha256:c1959518a8e26f81a3564357082cb684540be639a21fece35ac5619415a3eadc", size = 2397433, upload-time = "2026-11-01T20:57:00.622Z" }, ] [[package]] @@ -2410,8 +2431,8 @@ name = "opendalfs" version = "0.1.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "fsspec" }, - { name = "opendal" }, + { name = "fsspec", marker = "python_full_version >= '3.12'" }, + { name = "opendal", marker = "python_full_version >= '3.12'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/0d/23/fdb4d34f08ac68a27b2d553256e13b15ce139916d36bab33f9a0e71e8770/opendalfs-0.1.0.tar.gz", hash = "sha256:5ceaeccc0852ef10c8ef2ce20e5927dbc18083909c06550ad36f81bcacb5774d", size = 75112, upload-time = "2026-08-26T05:30:33.497Z" } wheels = [ @@ -2825,6 +2846,7 @@ builtin = [ { name = "cryptography" }, { name = "filelock" }, { name = "httpx" }, + { name = "httpx2" }, { name = "jieba" }, { name = "packaging" }, { name = "pycasbin" }, @@ -2845,6 +2867,7 @@ cli = [ { name = "cryptography" }, { name = "filelock" }, { name = "httpx", extra = ["socks"] }, + { name = "httpx2" }, { name = "inquirerpy" }, { name = "jieba" }, { name = "opentelemetry-api" }, @@ -2885,6 +2908,7 @@ ops = [ { name = "fastmcp" }, { name = "filelock" }, { name = "httpx" }, + { name = "httpx2" }, { name = "jieba" }, { name = "jinja2" }, { name = "markdown-it-py" }, @@ -2912,6 +2936,7 @@ seekdb = [ { name = "cryptography" }, { name = "filelock" }, { name = "httpx" }, + { name = "httpx2" }, { name = "jieba" }, { name = "packaging" }, { name = "pycasbin" }, @@ -2934,6 +2959,7 @@ server = [ { name = "fastmcp" }, { name = "filelock" }, { name = "httpx" }, + { name = "httpx2" }, { name = "jieba" }, { name = "jinja2" }, { name = "markdown-it-py" }, @@ -3001,6 +3027,7 @@ resource-build = [ { name = "click" }, { name = "filelock" }, { name = "httpx" }, + { name = "httpx2" }, { name = "jsonschema" }, { name = "opentelemetry-api" }, { name = "opentelemetry-sdk" }, @@ -3058,6 +3085,11 @@ requires-dist = [ { name = "httpx", marker = "extra == 'server'", specifier = ">=0.28,<1" }, { name = "httpx", extras = ["socks"], marker = "extra == 'cli'", specifier = ">=0.28,<1" }, { name = "httpx", extras = ["socks"], marker = "extra == 'client'", specifier = ">=0.28,<1" }, + { name = "httpx2", marker = "extra == 'builtin'", specifier = ">=2.7,<3" }, + { name = "httpx2", marker = "extra == 'cli'", specifier = ">=2.7,<3" }, + { name = "httpx2", marker = "extra == 'ops'", specifier = ">=2.7,<3" }, + { name = "httpx2", marker = "extra == 'seekdb'", specifier = ">=2.7,<3" }, + { name = "httpx2", marker = "extra == 'server'", specifier = ">=2.7,<3" }, { name = "inquirerpy", marker = "extra == 'cli'", specifier = ">=0.3,<1" }, { name = "jieba", marker = "extra == 'builtin'", specifier = "==0.42.1" }, { name = "jieba", marker = "extra == 'cli'", specifier = "==0.42.1" }, @@ -3095,11 +3127,11 @@ requires-dist = [ { name = "pycasbin", marker = "extra == 'seekdb'", specifier = ">=2.8,<3" }, { name = "pycasbin", marker = "extra == 'server'", specifier = ">=2.8,<3" }, { name = "pydantic", specifier = ">=2.10,<3" }, - { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'builtin'", specifier = ">=2.27.1,<3" }, - { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'cli'", specifier = ">=2.27.1,<3" }, - { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'ops'", specifier = ">=2.27.1,<3" }, - { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'seekdb'", specifier = ">=2.27.1,<3" }, - { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'server'", specifier = ">=2.27.1,<3" }, + { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'builtin'", specifier = ">=2.64.0,<3" }, + { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'cli'", specifier = ">=2.64.0,<3" }, + { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'ops'", specifier = ">=2.64.0,<3" }, + { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'seekdb'", specifier = ">=2.64.0,<3" }, + { name = "pydantic-ai-slim", extras = ["anthropic", "openai"], marker = "extra == 'server'", specifier = ">=2.64.0,<3" }, { name = "pydantic-settings", marker = "extra == 'builtin'", specifier = ">=2.7,<3" }, { name = "pydantic-settings", marker = "extra == 'cli'", specifier = ">=2.7,<3" }, { name = "pydantic-settings", marker = "extra == 'client'", specifier = ">=2.7,<3" }, @@ -3195,6 +3227,7 @@ resource-build = [ { name = "click", specifier = ">=8.1,<9" }, { name = "filelock", specifier = ">=3.16,<4" }, { name = "httpx", specifier = ">=0.28,<1" }, + { name = "httpx2", specifier = ">=2.7,<3" }, { name = "jsonschema", specifier = ">=4.23,<5" }, { name = "opentelemetry-api", specifier = ">=1.30,<2" }, { name = "opentelemetry-sdk", specifier = ">=1.30,<2" }, @@ -3218,8 +3251,8 @@ name = "powercontext-connector-opendal" version = "0.0.1" source = { editable = "integrations/opendal" } dependencies = [ - { name = "opendalfs" }, - { name = "powercontext", extra = ["client"] }, + { name = "opendalfs", marker = "python_full_version >= '3.12'" }, + { name = "powercontext", extra = ["client"], marker = "python_full_version >= '3.12'" }, ] [package.metadata] @@ -3441,21 +3474,22 @@ email = [ [[package]] name = "pydantic-ai-slim" -version = "2.29.0" +version = "2.64.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio" }, - { name = "genai-prices" }, + { name = "genai-prices", version = "0.1.13", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.15'" }, + { name = "genai-prices", version = "0.2.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.15'" }, { name = "griffelib" }, - { name = "httpx" }, + { name = "httpx2" }, { name = "opentelemetry-api" }, { name = "pydantic" }, { name = "pydantic-graph" }, { name = "typing-inspection" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/6d/47/9ea38824b27efae7d19a34e2288697e0a84aa5cdd8c119ac85d030395ea3/pydantic_ai_slim-2.29.0.tar.gz", hash = "sha256:a5de25ebf8cf50187fe71be101e318e18e8ed469e5d8d1551d92b81ded1e3e99", size = 1197221, upload-time = "2026-08-13T04:16:29.027Z" } +sdist = { url = "https://files.pythonhosted.org/packages/9b/57/38e6a723a69a72bc3ff9ffe806f4e6ef43a7660c11c598d9c77a3076d760/pydantic_ai_slim-2.64.0.tar.gz", hash = "sha256:bf7019bd8083a8a44b6ab891923cf3ec95c4713c04437d5f1d21206d485b2ace", size = 2390076, upload-time = "2026-10-31T00:22:39.12Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a1/42/fda259cd11f88eb0ce7e54ee6a29011c0dd6a0af474403a2bb32d5dddb79/pydantic_ai_slim-2.29.0-py3-none-any.whl", hash = "sha256:cb5f5b7a941715b7f8894baae48ac178a603bdcf729726535964eaec25b07eb1", size = 1414034, upload-time = "2026-08-13T04:16:22.19Z" }, + { url = "https://files.pythonhosted.org/packages/28/50/cee5e955a4d6126372b56eed56150d40b11dac393a26ca4a4826324c96f0/pydantic_ai_slim-2.64.0-py3-none-any.whl", hash = "sha256:63ccfe3f66beefb0a2fb3843d471f9d5b74a432f4436ed5ceb7e0d6bb06cb1e4", size = 2754541, upload-time = "2026-10-31T00:22:25.127Z" }, ] [package.optional-dependencies] @@ -3571,18 +3605,17 @@ wheels = [ [[package]] name = "pydantic-graph" -version = "2.29.0" +version = "2.64.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio" }, - { name = "httpx" }, { name = "logfire-api" }, { name = "pydantic" }, { name = "typing-inspection" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/99/a4/364964ff4ca90fac651ffc969e04d75941389a39009fa2e950379bbcec93/pydantic_graph-2.29.0.tar.gz", hash = "sha256:078d2d7ab53ffb695e1a66c2a741880c88fef36611004736bf7313f8a5ec4465", size = 45180, upload-time = "2026-08-13T04:16:30.94Z" } +sdist = { url = "https://files.pythonhosted.org/packages/ed/ea/70b61336d6648afafc9721377272c39a933f1ba426572c5c02d06bea31e9/pydantic_graph-2.64.0.tar.gz", hash = "sha256:823bc45c953e2c58b9bb89dbd8b79e9a31f90e55264078d492fe2de19269592a", size = 46464, upload-time = "2026-10-31T00:22:43.948Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/6f/d5/9a7e31a4895904c5d81989069630c47b7ef28d07256ae7ce1b8cda9964d1/pydantic_graph-2.29.0-py3-none-any.whl", hash = "sha256:afc81688c9abca9e93c4f7b81dd1112e8a7a8d4d41514413bd8d2c674bd2dfa1", size = 52661, upload-time = "2026-08-13T04:16:24.994Z" }, + { url = "https://files.pythonhosted.org/packages/5d/23/44f62c9eb71253998c5633b13d9ff44c20a4ed731fea99cc76f68dabbc3a/pydantic_graph-2.64.0-py3-none-any.whl", hash = "sha256:5034949fd78899001b31b819e3fd9357019766d48245f788712bb3a91ccf75a2", size = 53650, upload-time = "2026-10-31T00:22:31.083Z" }, ] [[package]] @@ -4837,18 +4870,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/5f/53/4a33dc81da39db7b31e5622333df361e8fe055b7ec636bd5fea762c9182d/tox_uv_bare-1.35.2-py3-none-any.whl", hash = "sha256:c0d590a41d1054a1ad0874e9e5943ff52402786e3d4599d8f8d37a65b566ef53", size = 22307, upload-time = "2026-05-05T01:34:17.681Z" }, ] -[[package]] -name = "tqdm" -version = "4.69.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/8c/69/40407dfc835517f058b603dbf37a6df094d8582b015a51eddc988febbcb7/tqdm-4.69.0.tar.gz", hash = "sha256:700c5e85dcd5f009dd6222588a29180a193a748247a5d855b4d67db93d79a53b", size = 792569, upload-time = "2026-07-17T18:09:06.2Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/fe/21/99a0cdaf54eb35e77623c41b5a2c9472ee4404bba687052791fe2aba6773/tqdm-4.69.0-py3-none-any.whl", hash = "sha256:9979978912be667a6ef21fd5d8abf54e324e63d82f7f43c360792ebc2bc4e622", size = 676680, upload-time = "2026-07-17T18:09:04.172Z" }, -] - [[package]] name = "traitlets" version = "5.16.1" From 9afea59f4b8034defe03795c6fe413ee79e801c8 Mon Sep 17 00:00:00 2001 From: Chojan Shang Date: Tue, 3 Nov 2026 11:22:58 +0800 Subject: [PATCH 02/11] docs(inference): clarify Copilot model selection --- docs/en/development/pydantic-ai-inference.md | 2 ++ docs/zh/development/pydantic-ai-inference.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/docs/en/development/pydantic-ai-inference.md b/docs/en/development/pydantic-ai-inference.md index 961915ace9..3b69cfbc2a 100644 --- a/docs/en/development/pydantic-ai-inference.md +++ b/docs/en/development/pydantic-ai-inference.md @@ -105,6 +105,8 @@ export GITHUB_COPILOT_API_KEY="$(gh auth token)" export POWERCONTEXT_SERVER_INFERENCE_GENERATION_MODEL="github-copilot:" ``` +Choose a Copilot model that supports Chat Completions. Models available only through the Responses API cannot use the `github-copilot:` prefix. + You can also reuse an existing `GITHUB_COPILOT_API_TOKEN` or `COPILOT_GITHUB_TOKEN` environment variable; the Server reads them in that order as fallbacks. The general-purpose `GITHUB_TOKEN` and `GH_TOKEN` variables are not used for Copilot authentication. Run the example's `gh auth token` command before starting the service. The Server does not load CLI configuration or renew tokens automatically. When the token changes, update the service's environment and restart the Server. See [Pydantic AI's Copilot configuration](https://github.com/pydantic/pydantic-ai/blob/v2.64.0/docs/models/github-copilot.md). These configurations support generation for Memory, Experience, and Profile. Topic Memory and Dream are unavailable with Codex and Copilot. If you have explicitly enabled Topic Memory processing or its automatic schedule, remove that configuration before switching providers. Enabling built-in inference protection prevents startup with these providers. diff --git a/docs/zh/development/pydantic-ai-inference.md b/docs/zh/development/pydantic-ai-inference.md index a6858488ec..344a1aac46 100644 --- a/docs/zh/development/pydantic-ai-inference.md +++ b/docs/zh/development/pydantic-ai-inference.md @@ -105,6 +105,8 @@ export GITHUB_COPILOT_API_KEY="$(gh auth token)" export POWERCONTEXT_SERVER_INFERENCE_GENERATION_MODEL="github-copilot:" ``` +请选择支持 Chat Completions 的 Copilot 模型。仅支持 Responses API 的模型不能使用 `github-copilot:` 前缀。 + 也可以沿用环境中已有的 `GITHUB_COPILOT_API_TOKEN` 或 `COPILOT_GITHUB_TOKEN`,它们会依次作为备用变量读取。Server 使用这些专用变量,通用的 `GITHUB_TOKEN` 和 `GH_TOKEN` 不用于 Copilot 认证。示例中的 `gh auth token` 需要在启动服务前执行,Server 不会自动读取 CLI 配置或续期 token。token 更新后,更新服务进程的环境并重启 Server。详见 [Pydantic AI 的 Copilot 配置](https://github.com/pydantic/pydantic-ai/blob/v2.64.0/docs/models/github-copilot.md)。 这些配置支持 Memory、Experience 和 Profile 的生成。Codex 和 Copilot 暂不支持 Topic Memory 与 Dream。如果已经显式启用 Topic Memory 处理或自动调度,切换 provider 前需要移除对应配置。已启用内置推理保护时,切换到这两个 provider 会导致启动失败。 From b5e64e2b766a53809fcef27cf22183ab06f464a6 Mon Sep 17 00:00:00 2001 From: Chojan Shang Date: Thu, 5 Nov 2026 00:58:25 +0800 Subject: [PATCH 03/11] fix(inference): preserve custom Anthropic API key headers --- .../builtin/runtime/composition.py | 47 ++++++++++++------- tests/test_inference_endpoints.py | 23 +++++++-- 2 files changed, 50 insertions(+), 20 deletions(-) diff --git a/src/powercontext/builtin/runtime/composition.py b/src/powercontext/builtin/runtime/composition.py index 9ee7024b63..fba619d6a4 100644 --- a/src/powercontext/builtin/runtime/composition.py +++ b/src/powercontext/builtin/runtime/composition.py @@ -229,6 +229,7 @@ from powercontext.sources import Source, SourceDefinitionRegistry, SourceProjectionKey if TYPE_CHECKING: + import httpx2 from pydantic_ai.models import Model from pydantic_ai.models.instrumented import InstrumentationSettings from pydantic_ai.providers import Provider @@ -2153,8 +2154,11 @@ def create(provider_name: str) -> Provider[Any]: from pydantic_ai.providers.anthropic import AnthropicProvider resolved = _resolve_headers(headers) - api_key = _pop_header(resolved, "x-api-key") or os.getenv("ANTHROPIC_API_KEY") + header_api_key = _pop_header(resolved, "x-api-key") + api_key = header_api_key or os.getenv("ANTHROPIC_API_KEY") has_authorization = any(name.casefold() == "authorization" for name in resolved) + if api_key and not has_authorization and (base_url is not None or header_api_key is not None): + client.auth = partial(_anthropic_api_key_header, api_key=api_key) sdk = AsyncAnthropic( base_url=None if base_url is None else str(base_url), api_key=api_key or (None if has_authorization else "api-key-not-set"), @@ -2208,28 +2212,37 @@ def create_provider(provider_name: str) -> Provider[Any]: from anthropic import AsyncAnthropic from pydantic_ai.providers.anthropic import AnthropicProvider - if headers: - default_headers = _resolve_headers(headers) - api_key = _pop_header(default_headers, "x-api-key") or os.getenv("ANTHROPIC_API_KEY") - has_authorization = any(name.casefold() == "authorization" for name in default_headers) - client = AsyncAnthropic( - base_url=None if base_url is None else str(base_url), - # A configured Authorization header is the credential; gateways may reject any X-Api-Key. - api_key=api_key or (None if has_authorization else "api-key-not-set"), - default_headers=default_headers, - http_client=httpx2.AsyncClient(follow_redirects=False) if base_url is not None else None, - ) - resources.push_async_callback(client.close) - return AnthropicProvider(anthropic_client=client) - return AnthropicProvider( - base_url=str(base_url), - api_key=os.getenv("ANTHROPIC_API_KEY") or "api-key-not-set", + default_headers = _resolve_headers(headers) + header_api_key = _pop_header(default_headers, "x-api-key") + api_key = header_api_key or os.getenv("ANTHROPIC_API_KEY") + has_authorization = any(name.casefold() == "authorization" for name in default_headers) + http_client = httpx2.AsyncClient(follow_redirects=False) if base_url is not None else None + if api_key and not has_authorization and (base_url is not None or header_api_key is not None): + http_client = http_client or httpx2.AsyncClient() + http_client.auth = partial(_anthropic_api_key_header, api_key=api_key) + client = AsyncAnthropic( + base_url=None if base_url is None else str(base_url), + # A configured Authorization header is the credential; gateways may reject any X-Api-Key. + api_key=api_key or (None if has_authorization else "api-key-not-set"), + default_headers=default_headers, + http_client=http_client, ) + resources.push_async_callback(client.close) + return AnthropicProvider(anthropic_client=client) raise BuiltinConfigurationError("inference-endpoint-provider") return create_provider +def _anthropic_api_key_header(request: httpx2.Request, *, api_key: str) -> httpx2.Request: + """Keep custom endpoints compatible with the pre-v2 Anthropic authentication header.""" + + if request.headers.get("Authorization") == f"Bearer {api_key}": + del request.headers["Authorization"] + request.headers["X-Api-Key"] = api_key + return request + + def _is_loopback_endpoint(endpoint: AnyHttpUrl | str | None) -> bool: """Allow only explicit local names and addresses for raw decision content.""" diff --git a/tests/test_inference_endpoints.py b/tests/test_inference_endpoints.py index e8b06cdc64..823bb9376d 100644 --- a/tests/test_inference_endpoints.py +++ b/tests/test_inference_endpoints.py @@ -28,6 +28,7 @@ from pydantic import AnyHttpUrl, SecretStr, ValidationError from powercontext.builtin.artifacts.atomic_memory import AtomicMemoryContent +from powercontext.builtin.inference.privacy import InferenceProtectionConfig from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.runtime import ( BuiltinConfig, @@ -41,6 +42,7 @@ class _RecordingModelServer(ThreadingHTTPServer): requests: list[dict[str, Any]] + required_api_key: str | None = None def __init__(self) -> None: super().__init__(("127.0.0.1", 0), _ModelHandler) @@ -59,6 +61,9 @@ def do_POST(self) -> None: "headers": {name.lower(): value for name, value in self.headers.items()}, "body": body, }) + if self.server.required_api_key is not None and self.headers.get("x-api-key") != self.server.required_api_key: + self.send_error(401) + return if path == "/v1/embeddings": response = { "object": "list", @@ -197,19 +202,27 @@ def test_inference_settings_reject_invalid_http_field_names(header_name: str) -> ) -def test_anthropic_custom_endpoint_uses_standard_environment_api_key( +@pytest.mark.parametrize("protection_mode", ["disabled", "shadow"]) +@pytest.mark.parametrize("credential_source", ["environment", "header"]) +def test_anthropic_custom_endpoint_preserves_api_key_authentication( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, + credential_source: str, + protection_mode: str, ) -> None: - monkeypatch.setenv("ANTHROPIC_API_KEY", "anthropic-standard-key") + monkeypatch.setenv("ANTHROPIC_API_KEY", "environment-key") + api_key = "explicit-key" if credential_source == "header" else "environment-key" async def scenario() -> None: with _model_server() as (server, base_url): + server.required_api_key = api_key config = BuiltinConfig( database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'runtime.db'}"), inference=InferenceConfig( generation_model="anthropic:tiny-generator", generation_base_url=AnyHttpUrl(base_url.removesuffix("/v1")), + generation_headers={"X-Api-Key": SecretStr(api_key)} if credential_source == "header" else {}, + protection=InferenceProtectionConfig.model_validate({"mode": protection_mode}), ), ) @@ -219,7 +232,8 @@ async def scenario() -> None: assert readiness.checks["inference.generation"] == "ready" assert server.requests assert server.requests[0]["path"] == "/v1/messages" - assert server.requests[0]["headers"]["authorization"] == "Bearer anthropic-standard-key" + assert server.requests[0]["headers"]["x-api-key"] == api_key + assert "authorization" not in server.requests[0]["headers"] asyncio.run(scenario()) @@ -263,9 +277,11 @@ async def scenario() -> None: asyncio.run(scenario()) +@pytest.mark.parametrize("protection_mode", ["disabled", "shadow"]) def test_anthropic_custom_endpoint_with_bearer_header_overrides_environment_authentication( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, + protection_mode: str, ) -> None: monkeypatch.setenv("ANTHROPIC_API_KEY", "anthropic-standard-key") @@ -277,6 +293,7 @@ async def scenario() -> None: generation_model="anthropic:tiny-generator", generation_base_url=AnyHttpUrl(base_url.removesuffix("/v1")), generation_headers={"Authorization": SecretStr("Bearer gateway-token")}, + protection=InferenceProtectionConfig.model_validate({"mode": protection_mode}), ), ) From 4740176cf9df3df5b2a6096d21e35575104f5cca Mon Sep 17 00:00:00 2001 From: Chojan Shang Date: Thu, 5 Nov 2026 15:42:07 +0800 Subject: [PATCH 04/11] fix(inference): preserve Anthropic gateway and upstream credentials --- docs/en/development/pydantic-ai-inference.md | 2 + docs/zh/development/pydantic-ai-inference.md | 2 + .../builtin/runtime/composition.py | 5 +- tests/test_inference_endpoints.py | 56 ++++++++++++++++++- 4 files changed, 62 insertions(+), 3 deletions(-) diff --git a/docs/en/development/pydantic-ai-inference.md b/docs/en/development/pydantic-ai-inference.md index c21a4d907b..ea8b4dde70 100644 --- a/docs/en/development/pydantic-ai-inference.md +++ b/docs/en/development/pydantic-ai-inference.md @@ -73,6 +73,8 @@ Header and model settings are JSON objects. Values in `*_HEADERS` are treated as A base URL can include a gateway path prefix. The service's interface path, such as `/chat/completions`, `/responses`, or `/embeddings`, is appended automatically and cannot be replaced with an arbitrary path. When configuring a custom URL or static headers, use an explicit OpenAI- or Anthropic-compatible model prefix. +For an Anthropic-compatible gateway that requires separate gateway and upstream credentials, configure its `Authorization` header and supply the upstream key through `ANTHROPIC_API_KEY` or an explicit `X-Api-Key` header. PowerContext sends both headers to the gateway; an explicit `X-Api-Key` takes precedence over the environment key. The gateway must remove its own `Authorization` before forwarding to Anthropic, which expects one credential per request. For a gateway that requires only `Authorization`, leave `ANTHROPIC_API_KEY` and `X-Api-Key` unset. See [Anthropic's gateway authentication guidance](https://platform.claude.com/docs/en/api/migration-2026-10-21#a-client-holds-one-credential). + When `RERANK_MODEL` is unset, LLM reranking uses the generation model and URL. Reranker headers and model settings can extend or override the generation configuration. Header overrides apply only to reranking and leave the selected model and URL unchanged. If you set a separate reranker URL, also specify a reranker model. The reranker uses the generation timeout and request limit unless you override them. When using the default URL and headers, supply credentials through the environment variables supported by the selected service. See below for reusing subscription credentials. diff --git a/docs/zh/development/pydantic-ai-inference.md b/docs/zh/development/pydantic-ai-inference.md index aff2ac7d07..3d4a4784f3 100644 --- a/docs/zh/development/pydantic-ai-inference.md +++ b/docs/zh/development/pydantic-ai-inference.md @@ -73,6 +73,8 @@ export POWERCONTEXT_SERVER_INFERENCE_RERANK_MODEL_SETTINGS='{"max_tokens":256}' 服务地址可以包含网关路径前缀,后面会自动追加 `/chat/completions`、`/responses` 或 `/embeddings` 等接口路径,不支持任意改写这些路径。自定义地址或静态请求头时,模型名称必须带有明确的 OpenAI 或 Anthropic 兼容接口前缀。 +Anthropic 兼容网关需要分别认证网关和上游时,配置网关的 `Authorization` 请求头,并通过 `ANTHROPIC_API_KEY` 或显式 `X-Api-Key` 请求头提供上游密钥。PowerContext 会将两个请求头都发给网关;显式 `X-Api-Key` 优先于环境变量中的密钥。网关转发给 Anthropic 前必须移除自己的 `Authorization`,因为官方 API 每次请求只接受一份凭据。网关仅要求 `Authorization` 时,不要设置 `ANTHROPIC_API_KEY` 和 `X-Api-Key`。详见 [Anthropic 的网关认证说明](https://platform.claude.com/docs/en/api/migration-2026-10-21#a-client-holds-one-credential)。 + 未设置 `RERANK_MODEL` 时,LLM 重排复用生成模型及其服务地址。重排的请求头和模型参数可以扩展或覆盖生成配置;请求头覆盖仅影响重排,不会改变所用模型和地址。单独设置重排地址时,也必须指定重排模型。未设置重排超时和请求次数上限时,它们沿用生成任务的配置。 使用默认地址和请求头时,通过所选模型服务支持的环境变量提供凭据。已有订阅凭据的复用方式见下文。 diff --git a/src/powercontext/builtin/runtime/composition.py b/src/powercontext/builtin/runtime/composition.py index d08d8f2ece..f2b3222e62 100644 --- a/src/powercontext/builtin/runtime/composition.py +++ b/src/powercontext/builtin/runtime/composition.py @@ -2177,6 +2177,8 @@ def create(provider_name: str) -> Provider[Any]: header_api_key = _pop_header(resolved, "x-api-key") api_key = header_api_key or os.getenv("ANTHROPIC_API_KEY") has_authorization = any(name.casefold() == "authorization" for name in resolved) + if api_key and has_authorization: + resolved["X-Api-Key"] = api_key if api_key and not has_authorization and (base_url is not None or header_api_key is not None): client.auth = partial(_anthropic_api_key_header, api_key=api_key) sdk = AsyncAnthropic( @@ -2236,13 +2238,14 @@ def create_provider(provider_name: str) -> Provider[Any]: header_api_key = _pop_header(default_headers, "x-api-key") api_key = header_api_key or os.getenv("ANTHROPIC_API_KEY") has_authorization = any(name.casefold() == "authorization" for name in default_headers) + if api_key and has_authorization: + default_headers["X-Api-Key"] = api_key http_client = httpx2.AsyncClient(follow_redirects=False) if base_url is not None else None if api_key and not has_authorization and (base_url is not None or header_api_key is not None): http_client = http_client or httpx2.AsyncClient() http_client.auth = partial(_anthropic_api_key_header, api_key=api_key) client = AsyncAnthropic( base_url=None if base_url is None else str(base_url), - # A configured Authorization header is the credential; gateways may reject any X-Api-Key. api_key=api_key or (None if has_authorization else "api-key-not-set"), default_headers=default_headers, http_client=http_client, diff --git a/tests/test_inference_endpoints.py b/tests/test_inference_endpoints.py index 823bb9376d..8fabbf981f 100644 --- a/tests/test_inference_endpoints.py +++ b/tests/test_inference_endpoints.py @@ -43,6 +43,7 @@ class _RecordingModelServer(ThreadingHTTPServer): requests: list[dict[str, Any]] required_api_key: str | None = None + required_authorization: str | None = None def __init__(self) -> None: super().__init__(("127.0.0.1", 0), _ModelHandler) @@ -64,6 +65,12 @@ def do_POST(self) -> None: if self.server.required_api_key is not None and self.headers.get("x-api-key") != self.server.required_api_key: self.send_error(401) return + if ( + self.server.required_authorization is not None + and self.headers.get("Authorization") != self.server.required_authorization + ): + self.send_error(401) + return if path == "/v1/embeddings": response = { "object": "list", @@ -242,15 +249,18 @@ async def scenario() -> None: "authorization", ["Bearer gateway-token", "Basic Z2F0ZXdheTpnd2F5LXRva2Vu"], ) +@pytest.mark.parametrize("protection_mode", ["disabled", "shadow"]) def test_anthropic_custom_endpoint_with_authorization_header_omits_api_key_header( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, authorization: str, + protection_mode: str, ) -> None: monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False) async def scenario() -> None: with _model_server() as (server, base_url): + server.required_authorization = authorization config = BuiltinConfig( database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'runtime.db'}"), inference=InferenceConfig( @@ -260,6 +270,7 @@ async def scenario() -> None: "Authorization": SecretStr(authorization), "hll-appid": SecretStr("ios-lma-svc"), }, + protection=InferenceProtectionConfig.model_validate({"mode": protection_mode}), ), ) @@ -278,21 +289,29 @@ async def scenario() -> None: @pytest.mark.parametrize("protection_mode", ["disabled", "shadow"]) -def test_anthropic_custom_endpoint_with_bearer_header_overrides_environment_authentication( +@pytest.mark.parametrize("credential_source", ["environment", "header"]) +def test_anthropic_custom_endpoint_preserves_gateway_and_upstream_credentials( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, protection_mode: str, + credential_source: str, ) -> None: monkeypatch.setenv("ANTHROPIC_API_KEY", "anthropic-standard-key") + api_key = "explicit-key" if credential_source == "header" else "anthropic-standard-key" + headers = {"Authorization": SecretStr("Bearer gateway-token")} + if credential_source == "header": + headers["x-api-key"] = SecretStr(api_key) async def scenario() -> None: with _model_server() as (server, base_url): + server.required_api_key = api_key + server.required_authorization = "Bearer gateway-token" config = BuiltinConfig( database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'runtime.db'}"), inference=InferenceConfig( generation_model="anthropic:tiny-generator", generation_base_url=AnyHttpUrl(base_url.removesuffix("/v1")), - generation_headers={"Authorization": SecretStr("Bearer gateway-token")}, + generation_headers=headers, protection=InferenceProtectionConfig.model_validate({"mode": protection_mode}), ), ) @@ -305,6 +324,39 @@ async def scenario() -> None: request = server.requests[0] assert request["path"] == "/v1/messages" assert request["headers"]["authorization"] == "Bearer gateway-token" + assert request["headers"]["x-api-key"] == api_key + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("protection_mode", ["disabled", "shadow"]) +def test_anthropic_provider_environment_uses_upstream_bearer_authentication( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + protection_mode: str, +) -> None: + monkeypatch.setenv("ANTHROPIC_API_KEY", "anthropic-standard-key") + + async def scenario() -> None: + with _model_server() as (server, base_url): + monkeypatch.setenv("ANTHROPIC_BASE_URL", base_url.removesuffix("/v1")) + server.required_authorization = "Bearer anthropic-standard-key" + config = BuiltinConfig( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'runtime.db'}"), + inference=InferenceConfig( + generation_model="anthropic:tiny-generator", + protection=InferenceProtectionConfig.model_validate({"mode": protection_mode}), + ), + ) + + async with open_builtin_runtime(config) as runtime: + readiness = await runtime.readiness() + + assert readiness.checks["inference.generation"] == "ready" + assert server.requests + request = server.requests[0] + assert request["headers"]["authorization"] == "Bearer anthropic-standard-key" + assert "x-api-key" not in request["headers"] asyncio.run(scenario()) From 21b002fda5918b39ecb6783830d1acd98bccdb15 Mon Sep 17 00:00:00 2001 From: Chojan Shang Date: Sat, 7 Nov 2026 00:48:59 +0800 Subject: [PATCH 05/11] fix(pydantic-ai): keep recalled context within the current run's new-message boundary --- .../powercontext_pydantic_ai/capability.py | 32 ++++++++++---- tests/pydantic_ai_adapter/test_capability.py | 43 +++++++++++++++++-- 2 files changed, 64 insertions(+), 11 deletions(-) diff --git a/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py b/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py index 3254839748..7e696ac5ca 100644 --- a/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py +++ b/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py @@ -129,18 +129,15 @@ async def before_model_request( state.context_injected = True return request_context - request_context = replace( - request_context, - messages=_without_powercontext_context(request_context.messages), - ) + messages = _without_powercontext_context(request_context.messages) # Request-only replacements no longer update the history used by later tool steps. ctx.messages[:] = _without_powercontext_context(ctx.messages) if not query: - return request_context + return replace(request_context, messages=list(messages)) prepared_content = await self._prepare_context(query) if not prepared_content: - return request_context + return replace(request_context, messages=list(messages)) state.context_injected = True context_request = ModelRequest( @@ -148,8 +145,9 @@ async def before_model_request( run_id=ctx.run_id, conversation_id=ctx.conversation_id, ) - ctx.messages.insert(0, context_request) - return replace(request_context, messages=[context_request, *request_context.messages]) + messages = _insert_context(messages, context_request) + ctx.messages[:] = messages + return replace(request_context, messages=list(messages)) @override async def after_model_request( @@ -370,6 +368,24 @@ def _content_text(content: Any) -> str: return "" +def _insert_context(messages: Sequence[Any], context_request: ModelRequest) -> list[Any]: + """Place recalled context ahead of the current run's first message, after the caller's earlier turns. + + `new_messages()` slices history from the first message stamped with this run's `run_id`, so recalled context + has to be inserted at that boundary. Prepending it to position 0 instead moves the boundary and makes the + caller's earlier turns look new, which duplicates them when the result is appended to the conversation. + """ + boundary = len(messages) + for index, message in enumerate(messages): + if message.run_id == context_request.run_id: + boundary = index + break + if boundary == len(messages) and messages and isinstance(messages[-1], ModelRequest): + # The prompt request is stamped only after this hook returns, so anchor to it directly. + boundary = len(messages) - 1 + return [*messages[:boundary], context_request, *messages[boundary:]] + + def _has_current_run_context(messages: Sequence[Any], run_id: str | None) -> bool: if run_id is None: return False diff --git a/tests/pydantic_ai_adapter/test_capability.py b/tests/pydantic_ai_adapter/test_capability.py index e9cb6e31d6..86b8779738 100644 --- a/tests/pydantic_ai_adapter/test_capability.py +++ b/tests/pydantic_ai_adapter/test_capability.py @@ -24,7 +24,7 @@ from powercontext_pydantic_ai.capability import CONTEXT_MARKER from pydantic import SecretStr from pydantic_ai import Agent, RunContext -from pydantic_ai.messages import ModelResponse, SystemPromptPart, TextPart, ToolCallPart, ToolReturnPart +from pydantic_ai.messages import ModelResponse, SystemPromptPart, TextPart, ToolCallPart, ToolReturnPart, UserPromptPart from pydantic_ai.models.function import FunctionModel from powercontext.client import ServerResponseError, TransportError @@ -40,11 +40,13 @@ def test_context_is_replaced_once_per_run_when_reusing_old_history( model_contexts: list[list[str]] = [] async def respond(messages, _info): + # Recalled context arrives as a system prompt of the current request; mid-conversation system + # prompts are re-rendered as ``-tagged user text, so match either part type. model_contexts.append([ - part.content + str(part_content) for message in messages for part in message.parts - if isinstance(part, SystemPromptPart) and CONTEXT_MARKER in part.content + if CONTEXT_MARKER in str(part_content := getattr(part, "content", "")) ]) if isinstance(messages[-1].parts[-1], ToolReturnPart): return ModelResponse(parts=[TextPart("complete")]) @@ -67,6 +69,41 @@ async def scenario() -> None: assert all(expected in contexts[0] for contexts, expected in zip(model_contexts, expected_contexts, strict=True)) +def test_recalled_context_preserves_new_messages_boundary_across_turns( + monkeypatch: pytest.MonkeyPatch, +) -> None: + RecordingClient.reset() + RecordingClient.prepare_result = prepared_response("boundary-one") + monkeypatch.setattr(toolset_module, "PowerContextClient", RecordingClient) + + async def respond(_messages, _info): + return ModelResponse(parts=[TextPart("ok")]) + + async def scenario() -> tuple[list[Any], list[Any]]: + agent = Agent(FunctionModel(respond), capabilities=[PowerContext(scope_id="project:boundary")]) + first = await agent.run("first prompt") + RecordingClient.prepare_result = prepared_response("boundary-two") + second = await agent.run("second prompt", message_history=first.all_messages()) + return first.new_messages(), second.new_messages() + + first_new, second_new = asyncio.run(scenario()) + + def prompts(messages: list[Any]) -> list[str]: + return [ + str(part.content) + for message in messages + for part in message.parts + if isinstance(part, (UserPromptPart, SystemPromptPart)) and isinstance(part.content, str) + ] + + # Only this run's prompt and its recalled context belong to the second run's new messages. + assert prompts(second_new)[-1] == "second prompt" + assert "first prompt" not in "\n".join(prompts(second_new)) + assert any("boundary-two" in text for text in prompts(second_new)) + assert not any("boundary-one" in text for text in prompts(second_new)) + assert "first prompt" in "\n".join(prompts(first_new)) + + def test_empty_context_is_not_injected(monkeypatch: pytest.MonkeyPatch) -> None: RecordingClient.reset() RecordingClient.prepare_result = prepared_response(None) From 4a6cd606d691bc638bef1c8d0a45a8ec1ac03301 Mon Sep 17 00:00:00 2001 From: Chojan Shang Date: Sat, 7 Nov 2026 00:54:20 +0800 Subject: [PATCH 06/11] fix(inference): keep body-based context-overflow fallback for uncategorized HTTP errors --- .../powercontext_pydantic_ai/capability.py | 12 ++-- .../builtin/inference/pydantic_ai.py | 41 +++++++++++ tests/builtin/inference/test_pydantic_ai.py | 17 +++++ tests/pydantic_ai_adapter/test_capability.py | 72 ++++++++++++++----- 4 files changed, 119 insertions(+), 23 deletions(-) diff --git a/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py b/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py index 7e696ac5ca..43f4076db6 100644 --- a/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py +++ b/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py @@ -374,15 +374,15 @@ def _insert_context(messages: Sequence[Any], context_request: ModelRequest) -> l `new_messages()` slices history from the first message stamped with this run's `run_id`, so recalled context has to be inserted at that boundary. Prepending it to position 0 instead moves the boundary and makes the caller's earlier turns look new, which duplicates them when the result is appended to the conversation. + + The prompt request being prepared is stamped with this run's `run_id` only after this hook returns, so a + history with no current-run message yet anchors to the trailing request instead. That covers both a fresh + prompt and a history-only continuation, where the trailing request still carries the previous run's id. """ - boundary = len(messages) for index, message in enumerate(messages): if message.run_id == context_request.run_id: - boundary = index - break - if boundary == len(messages) and messages and isinstance(messages[-1], ModelRequest): - # The prompt request is stamped only after this hook returns, so anchor to it directly. - boundary = len(messages) - 1 + return [*messages[:index], context_request, *messages[index:]] + boundary = len(messages) - 1 if messages and isinstance(messages[-1], ModelRequest) else len(messages) return [*messages[:boundary], context_request, *messages[boundary:]] diff --git a/src/powercontext/builtin/inference/pydantic_ai.py b/src/powercontext/builtin/inference/pydantic_ai.py index d2f9ebcd70..6fe791c50d 100644 --- a/src/powercontext/builtin/inference/pydantic_ai.py +++ b/src/powercontext/builtin/inference/pydantic_ai.py @@ -605,6 +605,25 @@ def _checked_rule(error: BaseException) -> InvalidInferenceOutputError | None: return None +def _looks_like_context_overflow(error: ModelHTTPError) -> bool: + """Classify only when the provider's own response names a context limit.""" + + body = getattr(error, "body", None) + text = str(body if isinstance(body, (str, bytes)) else body or "").lower() + return any( + term in text + for term in ( + "context length", + "context window", + "maximum context", + "too many tokens", + "prompt is too long", + "input is too long", + "token limit", + ) + ) + + def _map_error( # noqa: C901 - bounded mapping across status codes and provider exception classes error: Exception, *, @@ -656,9 +675,12 @@ def _map_error( # noqa: C901 - bounded mapping across status codes and provider ), ) if isinstance(error, (ModelHTTPError, ModelRequestRejectedError)): + # Typed errors are authoritative; an uncategorized HTTP error still carries the provider's own + # words, so the body-based check keeps classifying a limit Pydantic AI did not tag as one. reason = ( ProcessingFailureReason.CONTEXT_OVERFLOW if isinstance(error, ModelContextWindowExceededError) + or (isinstance(error, ModelHTTPError) and _looks_like_context_overflow(error)) else ProcessingFailureReason.CONFIGURATION ) return attach_diagnostics( @@ -716,6 +738,25 @@ def _map_error( # noqa: C901 - bounded mapping across status codes and provider return None +def _looks_like_context_overflow(error: ModelHTTPError) -> bool: + """Classify only when the provider's own response names a context limit.""" + + body = getattr(error, "body", None) + text = str(body if isinstance(body, (str, bytes)) else body or "").lower() + return any( + term in text + for term in ( + "context length", + "context window", + "maximum context", + "too many tokens", + "prompt is too long", + "input is too long", + "token limit", + ) + ) + + __all__ = [ "InferenceLimits", "PydanticAIConfigurationError", diff --git a/tests/builtin/inference/test_pydantic_ai.py b/tests/builtin/inference/test_pydantic_ai.py index 5437eb8f94..12f81efa66 100644 --- a/tests/builtin/inference/test_pydantic_ai.py +++ b/tests/builtin/inference/test_pydantic_ai.py @@ -1125,6 +1125,23 @@ async def scenario() -> None: asyncio.run(scenario()) +def test_an_uncategorized_http_400_naming_a_context_limit_is_context_overflow() -> None: + """A provider that words its limit without a typed error still maps to the same reason.""" + + mapped = _map_error( + ModelHTTPError(400, "test-model", {"error": {"message": "Input is too long for this model"}}), + operation="generate", + timeout_seconds=1.0, + ) + + assert mapped is not None + diagnostics = classify_processing_error(mapped) + + assert diagnostics is not None + assert diagnostics.reason is ProcessingFailureReason.CONTEXT_OVERFLOW + assert diagnostics.stage is ProcessingStage.GENERATION + + def test_a_413_without_context_evidence_is_not_context_overflow() -> None: mapped = _map_error( ModelHTTPError(413, "test-model", {"error": "upload too large"}), diff --git a/tests/pydantic_ai_adapter/test_capability.py b/tests/pydantic_ai_adapter/test_capability.py index 86b8779738..3f792e3ecb 100644 --- a/tests/pydantic_ai_adapter/test_capability.py +++ b/tests/pydantic_ai_adapter/test_capability.py @@ -38,10 +38,12 @@ def test_context_is_replaced_once_per_run_when_reusing_old_history( RecordingClient.prepare_result = prepared_response("context-one") monkeypatch.setattr(toolset_module, "PowerContextClient", RecordingClient) model_contexts: list[list[str]] = [] + stored_contexts: list[list[str]] = [] async def respond(messages, _info): - # Recalled context arrives as a system prompt of the current request; mid-conversation system - # prompts are re-rendered as ``-tagged user text, so match either part type. + # What the model call carries. `FunctionModel` keeps the default profile, whose + # `supports_inline_system_prompts` is false, so a mid-conversation `SystemPromptPart` reaches + # the model as ``-tagged user text (see `Model.prepare_messages`). model_contexts.append([ str(part_content) for message in messages @@ -60,6 +62,13 @@ async def scenario() -> None: RecordingClient.prepare_result = prepared_response("context-three") third = await agent.run("third prompt", message_history=second.all_messages()) assert third.output == "complete" + for result in (first, second, third): + stored_contexts.append([ + part.content + for message in result.all_messages() + for part in message.parts + if isinstance(part, SystemPromptPart) and CONTEXT_MARKER in part.content + ]) asyncio.run(scenario()) @@ -67,6 +76,14 @@ async def scenario() -> None: expected_contexts = ["context-one", "context-one", "context-two", "context-two", "context-three", "context-three"] assert all(len(contexts) == 1 for contexts in model_contexts) assert all(expected in contexts[0] for contexts, expected in zip(model_contexts, expected_contexts, strict=True)) + # Persisted history stores recalled context as a `SystemPromptPart`, not as user text. + assert len(stored_contexts) == 3 + assert all(len(contexts) == 1 for contexts in stored_contexts) + assert [contexts[0].split("\n\n", 1)[1].split('"')[0] for contexts in stored_contexts] == [ + "context-one", + "context-two", + "context-three", + ] def test_recalled_context_preserves_new_messages_boundary_across_turns( @@ -76,32 +93,53 @@ def test_recalled_context_preserves_new_messages_boundary_across_turns( RecordingClient.prepare_result = prepared_response("boundary-one") monkeypatch.setattr(toolset_module, "PowerContextClient", RecordingClient) - async def respond(_messages, _info): - return ModelResponse(parts=[TextPart("ok")]) + async def respond(messages, _info): + if any(isinstance(part, ToolReturnPart) for part in messages[-1].parts): + return ModelResponse(parts=[TextPart("turn complete")]) + return ModelResponse(parts=[ToolCallPart("powercontext_search", {"query": "q"}, "search-1")]) - async def scenario() -> tuple[list[Any], list[Any]]: + async def scenario() -> tuple[list[Any], list[Any], list[Any], list[Any]]: agent = Agent(FunctionModel(respond), capabilities=[PowerContext(scope_id="project:boundary")]) first = await agent.run("first prompt") RecordingClient.prepare_result = prepared_response("boundary-two") second = await agent.run("second prompt", message_history=first.all_messages()) - return first.new_messages(), second.new_messages() + history_before_resume = second.all_messages() + RecordingClient.prepare_result = prepared_response("boundary-three") + third = await agent.run(message_history=history_before_resume) + return first.all_messages(), second.new_messages(), third.new_messages(), history_before_resume - first_new, second_new = asyncio.run(scenario()) + first_all, second_new, third_new, history_before_resume = asyncio.run(scenario()) - def prompts(messages: list[Any]) -> list[str]: - return [ + def text(messages: list[Any]) -> str: + return "\n".join( str(part.content) for message in messages for part in message.parts if isinstance(part, (UserPromptPart, SystemPromptPart)) and isinstance(part.content, str) - ] - - # Only this run's prompt and its recalled context belong to the second run's new messages. - assert prompts(second_new)[-1] == "second prompt" - assert "first prompt" not in "\n".join(prompts(second_new)) - assert any("boundary-two" in text for text in prompts(second_new)) - assert not any("boundary-one" in text for text in prompts(second_new)) - assert "first prompt" in "\n".join(prompts(first_new)) + ) + + # A new prompt with prior history: only this run's prompt and its own recalled context are new, so appending + # `new_messages()` to the caller's history reproduces the run's own history instead of duplicating a turn. + assert "second prompt" in text(second_new) + assert "first prompt" not in text(second_new) + assert "boundary-two" in text(second_new) + assert "boundary-one" not in text(second_new) + # The multi-step tool turn stayed inside the same boundary: one prompt, one tool call/return pair. + assert sum(isinstance(part, ToolCallPart) for message in second_new for part in message.parts) == 1 + assert [part.tool_call_id for message in second_new for part in message.parts if isinstance(part, ToolCallPart)] == [ + part.tool_call_id for message in second_new for part in message.parts if isinstance(part, ToolReturnPart) + ] + assert [message.run_id for message in second_new] == [history_before_resume[-1].run_id] * len(second_new) + + # A history-only continuation has no new prompt, so nothing from the caller's turns may be reported as new. + assert "second prompt" not in text(third_new) + assert "first prompt" not in text(third_new) + assert "boundary-three" in text(third_new) + assert "boundary-two" not in text(third_new) + + # The caller's history stays exactly what it was; the run builds its own list. + assert "boundary-one" not in text(history_before_resume[-1:]) + assert len(first_all) == 5 def test_empty_context_is_not_injected(monkeypatch: pytest.MonkeyPatch) -> None: From 3503365b4eab73dde6367210f31a23cd70dad1bd Mon Sep 17 00:00:00 2001 From: Chojan Shang Date: Sat, 7 Nov 2026 01:10:40 +0800 Subject: [PATCH 07/11] fix(pydantic-ai): keep recalled context as a leading system prompt on every step The new-message boundary fix moved recalled context to the current-run boundary in persisted history, which also demoted it from a leading SystemPromptPart to a mid-conversation -tagged user turn for providers without inline system prompts. Pydantic AI keeps the outgoing request list and the persisted history separate after the before-hook chain detaches, so persist the context at the boundary for new_messages() and lead the model-facing request with it. Later tool steps rebuild their request from persisted history, so reorder there too, restoring the system-role contract on every step. The regression now covers a new prompt, the multi-step tool turn, and a history-only resume whose input ends in a ModelRequest, and snapshots the caller's history instead of asserting message counts. --- .../powercontext_pydantic_ai/capability.py | 43 ++++++++- tests/pydantic_ai_adapter/test_capability.py | 95 +++++++++++++------ 2 files changed, 102 insertions(+), 36 deletions(-) diff --git a/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py b/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py index 43f4076db6..f8245ec8b7 100644 --- a/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py +++ b/integrations/pydantic-ai/src/powercontext_pydantic_ai/capability.py @@ -127,16 +127,20 @@ async def before_model_request( if state.context_injected or _has_current_run_context(request_context.messages, ctx.run_id): state.context_injected = True - return request_context + # Later tool steps rebuild the request from persisted history, where recalled context sits at the + # new-message boundary. Lead with it for the model so it keeps its system role on every step. + return _leading_context(request_context, ctx.run_id) messages = _without_powercontext_context(request_context.messages) # Request-only replacements no longer update the history used by later tool steps. - ctx.messages[:] = _without_powercontext_context(ctx.messages) + history = _without_powercontext_context(ctx.messages) if not query: + ctx.messages[:] = history return replace(request_context, messages=list(messages)) prepared_content = await self._prepare_context(query) if not prepared_content: + ctx.messages[:] = history return replace(request_context, messages=list(messages)) state.context_injected = True @@ -145,9 +149,10 @@ async def before_model_request( run_id=ctx.run_id, conversation_id=ctx.conversation_id, ) - messages = _insert_context(messages, context_request) - ctx.messages[:] = messages - return replace(request_context, messages=list(messages)) + # Persisted history keeps recalled context at the current-run boundary so `new_messages()` stays exact, + # while the request sent to the model leads with it as a real system prompt. + ctx.messages[:] = _insert_context(history, context_request) + return replace(request_context, messages=[context_request, *messages]) @override async def after_model_request( @@ -386,6 +391,34 @@ def _insert_context(messages: Sequence[Any], context_request: ModelRequest) -> l return [*messages[:boundary], context_request, *messages[boundary:]] +def _leading_context(request_context: ModelRequestContext, run_id: str | None) -> ModelRequestContext: + """Put this run's recalled context first for the model, keeping every other message in order. + + Persisted history stores recalled context at the new-message boundary so `new_messages()` excludes earlier + turns. The model-facing request is a separate list, so it can lead with that context as a system prompt without + changing what is persisted. + """ + messages = request_context.messages + if not messages: + return request_context + first = messages[0] + if isinstance(first, ModelRequest) and _is_context_request(first, run_id): + return request_context + for index, message in enumerate(messages): + if isinstance(message, ModelRequest) and _is_context_request(message, run_id): + return replace(request_context, messages=[message, *messages[:index], *messages[index + 1 :]]) + return request_context + + +def _is_context_request(message: ModelRequest, run_id: str | None) -> bool: + """Whether `message` carries this run's recalled context and nothing else.""" + if run_id is not None and message.run_id != run_id: + return False + return bool(message.parts) and all( + isinstance(part, SystemPromptPart) and CONTEXT_MARKER in part.content for part in message.parts + ) + + def _has_current_run_context(messages: Sequence[Any], run_id: str | None) -> bool: if run_id is None: return False diff --git a/tests/pydantic_ai_adapter/test_capability.py b/tests/pydantic_ai_adapter/test_capability.py index 85a0d0cf59..53ad3962b9 100644 --- a/tests/pydantic_ai_adapter/test_capability.py +++ b/tests/pydantic_ai_adapter/test_capability.py @@ -24,7 +24,15 @@ from powercontext_pydantic_ai.capability import CONTEXT_MARKER from pydantic import SecretStr from pydantic_ai import Agent, RunContext -from pydantic_ai.messages import ModelResponse, SystemPromptPart, TextPart, ToolCallPart, ToolReturnPart, UserPromptPart +from pydantic_ai.messages import ( + ModelRequest, + ModelResponse, + SystemPromptPart, + TextPart, + ToolCallPart, + ToolReturnPart, + UserPromptPart, +) from pydantic_ai.models.function import FunctionModel from powercontext.client import ServerResponseError, TransportError @@ -41,15 +49,15 @@ def test_context_is_replaced_once_per_run_when_reusing_old_history( stored_contexts: list[list[str]] = [] async def respond(messages, _info): - # What the model call carries. `FunctionModel` keeps the default profile, whose - # `supports_inline_system_prompts` is false, so a mid-conversation `SystemPromptPart` reaches - # the model as ``-tagged user text (see `Model.prepare_messages`). + # Recalled context reaches the model as a leading `SystemPromptPart` on every step, including the + # tool step whose request is rebuilt from persisted history. model_contexts.append([ - str(part_content) + part.content for message in messages for part in message.parts - if CONTEXT_MARKER in str(part_content := getattr(part, "content", "")) + if isinstance(part, SystemPromptPart) and CONTEXT_MARKER in part.content ]) + assert isinstance(messages[0].parts[0], SystemPromptPart) if isinstance(messages[-1].parts[-1], ToolReturnPart): return ModelResponse(parts=[TextPart("complete")]) return ModelResponse(parts=[ToolCallPart("powercontext_search", {"query": "context"}, "search-1")]) @@ -93,53 +101,78 @@ def test_recalled_context_preserves_new_messages_boundary_across_turns( RecordingClient.prepare_result = prepared_response("boundary-one") monkeypatch.setattr(toolset_module, "PowerContextClient", RecordingClient) + turns: list[int] = [] + async def respond(messages, _info): - if any(isinstance(part, ToolReturnPart) for part in messages[-1].parts): - return ModelResponse(parts=[TextPart("turn complete")]) + if not turns or any(isinstance(part, ToolReturnPart) for part in messages[-1].parts): + turns.append(len(turns) + 1) + return ModelResponse(parts=[TextPart(f"answer {turns[-1]}")]) return ModelResponse(parts=[ToolCallPart("powercontext_search", {"query": "q"}, "search-1")]) + def prompts_and_calls(messages: list[Any]) -> list[tuple[str, str]]: + return [ + (type(part).__name__, str(getattr(part, "content", getattr(part, "tool_name", "")))) + for message in messages + for part in message.parts + if isinstance(part, (UserPromptPart, SystemPromptPart, ToolCallPart, ToolReturnPart, TextPart)) + ] + async def scenario() -> tuple[list[Any], list[Any], list[Any], list[Any]]: agent = Agent(FunctionModel(respond), capabilities=[PowerContext(scope_id="project:boundary")]) first = await agent.run("first prompt") RecordingClient.prepare_result = prepared_response("boundary-two") second = await agent.run("second prompt", message_history=first.all_messages()) - history_before_resume = second.all_messages() + # Resume from an explicit history that ends in a `ModelRequest`, not a completed response. + history_before_resume = [*second.all_messages(), ModelRequest(parts=[UserPromptPart("unanswered prompt")])] RecordingClient.prepare_result = prepared_response("boundary-three") + snapshot = list(history_before_resume) third = await agent.run(message_history=history_before_resume) - return first.all_messages(), second.new_messages(), third.new_messages(), history_before_resume + # The caller's objects are never rewritten in place; only the documented context replacement happens + # inside the result's own copy. + assert prompts_and_calls(history_before_resume) == prompts_and_calls(snapshot) + return second.new_messages(), third.new_messages(), third.all_messages() - first_all, second_new, third_new, history_before_resume = asyncio.run(scenario()) + second_new, third_new, third_all = asyncio.run(scenario()) def text(messages: list[Any]) -> str: - return "\n".join( - str(part.content) - for message in messages - for part in message.parts - if isinstance(part, (UserPromptPart, SystemPromptPart)) and isinstance(part.content, str) - ) + return "\n".join(value for _, value in prompts_and_calls(messages)) - # A new prompt with prior history: only this run's prompt and its own recalled context are new, so appending - # `new_messages()` to the caller's history reproduces the run's own history instead of duplicating a turn. + # A new prompt with prior history: only this run's prompt and its own recalled context are new. assert "second prompt" in text(second_new) assert "first prompt" not in text(second_new) assert "boundary-two" in text(second_new) assert "boundary-one" not in text(second_new) - # The multi-step tool turn stayed inside the same boundary: one prompt, one tool call/return pair. - assert sum(isinstance(part, ToolCallPart) for message in second_new for part in message.parts) == 1 + # A multi-step tool turn stays inside the boundary with exactly one call/return pair, and appending + # `new_messages()` to the caller's history reproduces the run's history instead of duplicating a turn. + assert [value for name, value in prompts_and_calls(second_new) if name == "ToolCallPart"] == ["powercontext_search"] assert [ - part.tool_call_id for message in second_new for part in message.parts if isinstance(part, ToolCallPart) - ] == [part.tool_call_id for message in second_new for part in message.parts if isinstance(part, ToolReturnPart)] - assert [message.run_id for message in second_new] == [history_before_resume[-1].run_id] * len(second_new) - - # A history-only continuation has no new prompt, so nothing from the caller's turns may be reported as new. + part.tool_call_id + for message in second_new + for part in message.parts + if isinstance(part, (ToolCallPart, ToolReturnPart)) + ] == ["search-1", "search-1"] + second_run_ids = {message.run_id for message in second_new} + assert len(second_run_ids) == 1 and None not in second_run_ids + assert text(second_new).count("second prompt") == 1 + assert text(second_new).count("answer 2") == 1 + + # A history-only continuation resumes the trailing `ModelRequest`, which the framework treats as prior + # context, so no earlier prompt, answer, or tool return is reported as new either. assert "second prompt" not in text(third_new) assert "first prompt" not in text(third_new) - assert "boundary-three" in text(third_new) + assert "unanswered prompt" not in text(third_new) + assert "answer 1" not in text(third_new) + assert "answer 2" not in text(third_new) assert "boundary-two" not in text(third_new) - - # The caller's history stays exactly what it was; the run builds its own list. - assert "boundary-one" not in text(history_before_resume[-1:]) - assert len(first_all) == 5 + assert [value for name, value in prompts_and_calls(third_new) if name == "ToolCallPart"] == ["powercontext_search"] + + # The prior turns and the reviewed prompt survive exactly once in the result: none duplicated, none dropped. + assert text(third_all).count("first prompt") == 1 + assert text(third_all).count("second prompt") == 1 + assert text(third_all).count("unanswered prompt") == 1 + # Recalled context is stored once for this run, replacing the prior run's context instead of accumulating it. + assert text(third_all).count("boundary-three") == 1 + assert "boundary-one" not in text(third_all) def test_empty_context_is_not_injected(monkeypatch: pytest.MonkeyPatch) -> None: From d7a2900045095f10db700eb5a522d209526dfdea Mon Sep 17 00:00:00 2001 From: Chojan Shang Date: Sat, 7 Nov 2026 01:12:17 +0800 Subject: [PATCH 08/11] test(pydantic-ai): capture the caller history projection before the next run A shallow list copy is vacuous once parts are mutated in place, so snapshot the content, tool arguments, results, and ids beforehand and compare afterwards, excluding framework-stamped metadata. --- tests/pydantic_ai_adapter/test_capability.py | 31 ++++++++++++++++---- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/tests/pydantic_ai_adapter/test_capability.py b/tests/pydantic_ai_adapter/test_capability.py index 53ad3962b9..3d94a41a54 100644 --- a/tests/pydantic_ai_adapter/test_capability.py +++ b/tests/pydantic_ai_adapter/test_capability.py @@ -16,6 +16,7 @@ import asyncio import logging +from copy import deepcopy from typing import Any import powercontext_pydantic_ai.toolset as toolset_module @@ -117,7 +118,27 @@ def prompts_and_calls(messages: list[Any]) -> list[tuple[str, str]]: if isinstance(part, (UserPromptPart, SystemPromptPart, ToolCallPart, ToolReturnPart, TextPart)) ] - async def scenario() -> tuple[list[Any], list[Any], list[Any], list[Any]]: + def part_projection(messages: list[Any]) -> list[tuple[Any, ...]]: + """An immutable view of the caller's message content, captured before the next run. + + Message metadata such as `run_id` and `timestamp` is excluded: the framework may stamp it on the + caller's history for its own bookkeeping, so only content, tool arguments, results, and ids are + claimed unchanged. + """ + return [ + ( + type(part).__name__, + getattr(part, "content", None), + getattr(part, "tool_name", None), + getattr(part, "tool_call_id", None), + repr(getattr(part, "args", None)), + repr(getattr(part, "tool_return", None)), + ) + for message in messages + for part in message.parts + ] + + async def scenario() -> tuple[list[Any], list[Any], list[Any]]: agent = Agent(FunctionModel(respond), capabilities=[PowerContext(scope_id="project:boundary")]) first = await agent.run("first prompt") RecordingClient.prepare_result = prepared_response("boundary-two") @@ -125,11 +146,11 @@ async def scenario() -> tuple[list[Any], list[Any], list[Any], list[Any]]: # Resume from an explicit history that ends in a `ModelRequest`, not a completed response. history_before_resume = [*second.all_messages(), ModelRequest(parts=[UserPromptPart("unanswered prompt")])] RecordingClient.prepare_result = prepared_response("boundary-three") - snapshot = list(history_before_resume) + before_run = deepcopy(part_projection(history_before_resume)) third = await agent.run(message_history=history_before_resume) - # The caller's objects are never rewritten in place; only the documented context replacement happens - # inside the result's own copy. - assert prompts_and_calls(history_before_resume) == prompts_and_calls(snapshot) + # Compare against the projection captured before the run, so an in-place part mutation cannot hide by + # shifting the snapshot too. Only the documented context replacement happens inside the result's copy. + assert part_projection(history_before_resume) == before_run return second.new_messages(), third.new_messages(), third.all_messages() second_new, third_new, third_all = asyncio.run(scenario()) From 687620dbeaf87c40b63a1176d2750d7f812e27ac Mon Sep 17 00:00:00 2001 From: Chojan Shang Date: Sat, 7 Nov 2026 01:03:42 +0800 Subject: [PATCH 09/11] ci(preflight): install license-eye to a writable prefix The pinned skywalking-eyes header action installs with `make install`, whose Makefile targets /usr/local/bin and ignores the unprivileged copy failure, so its next step cannot resolve license-eye. Pass the supported INSTALL_DIR override pointing at runner.temp and publish that directory on GITHUB_PATH. The license check and its inputs are unchanged. --- .github/workflows/master.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.github/workflows/master.yml b/.github/workflows/master.yml index 5fdf5e0d97..1f8fc3201b 100644 --- a/.github/workflows/master.yml +++ b/.github/workflows/master.yml @@ -200,11 +200,21 @@ jobs: GH_TOKEN: ${{ github.token }} run: python3 scripts/ci_changes.py + - name: Prepare a writable license-eye prefix + # Install license-eye via the action's supported INSTALL_DIR override, + # using a user-writable path that the action resolves from PATH. + env: + LICENSE_EYE_BIN: ${{ runner.temp }}/license-eye-bin + run: | + mkdir -p "$LICENSE_EYE_BIN" + echo "$LICENSE_EYE_BIN" >> "$GITHUB_PATH" + - name: Check License Header timeout-minutes: 10 uses: apache/skywalking-eyes/header@a196742f472feaffafea537ce5a2a4c3c53a8de4 # v0.9.0 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + INSTALL_DIR: ${{ runner.temp }}/license-eye-bin with: config: .licenserc.yaml mode: check From 198e4238614458822c62224b236344ddc056ea0b Mon Sep 17 00:00:00 2001 From: Chojan Shang Date: Sat, 7 Nov 2026 01:56:33 +0800 Subject: [PATCH 10/11] fix(website): cap Next build workers for memory-constrained runners Next derives its default build worker count from the visible CPU count, so page-data collection peak memory scaled with host CPUs and the check-website job was OOM-killed (exit 137) on the internal runner. Cap it at 2 so the build fits the runner's memory limit. Every page is still rendered. --- website/next.config.mjs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/website/next.config.mjs b/website/next.config.mjs index 43747cdad3..31a2fbce2e 100644 --- a/website/next.config.mjs +++ b/website/next.config.mjs @@ -21,6 +21,10 @@ const withMDX = createMDX(); /** @type {import('next').NextConfig} */ const config = { basePath: process.env.NEXT_PUBLIC_BASE_PATH?.replace(/\/$/, '') || '', + // Next defaults to (visible CPUs - 1) build workers, so peak memory grows with the + // host's CPU count. Cap it: memory-constrained build runners were OOM-killed (exit 137) + // while collecting page data. Every page is still rendered. + experimental: { cpus: 2 }, images: { unoptimized: true }, output: 'export', reactStrictMode: true, From 3736c1f287197dd8167255e0e9ca7c66307fd78a Mon Sep 17 00:00:00 2001 From: Chojan Shang Date: Sat, 7 Nov 2026 02:05:53 +0800 Subject: [PATCH 11/11] test(integrations): isolate hook characterization from inherited default ACLs The case directory is a temporary directory, and on a runner whose temp root carries a default POSIX ACL that entry is inherited by every hook-created subdirectory and file. A default ACL overrides the umask, so the hooks' own `$HOME/.local`, `$HOME/.local/state/powercontext`, and diagnostics file were recorded as 775/664 instead of the characterized 755/644 even though each hook process already starts with umask 0o022. Remove the inherited default entry at the case root before any hook runs; it is created before the first step, so modes below it then follow the umask alone. Only the root needs handling, and private 0600/0700 expectations are unchanged. The attribute is Linux-specific, so other hosts are left alone, and an unexpected removal error still fails the case. Every other fixture field was identical in the failing CI run. --- tests/test_hook_characterization.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tests/test_hook_characterization.py b/tests/test_hook_characterization.py index f396fc9c9f..ca79109154 100644 --- a/tests/test_hook_characterization.py +++ b/tests/test_hook_characterization.py @@ -31,6 +31,7 @@ from __future__ import annotations +import errno import hashlib import json import os @@ -212,6 +213,7 @@ def _run_case( """Run the steps of one case in one isolated host home; return the observations and unscripted routes.""" root = directory.resolve() + _detach_inherited_default_acl(root) home, state, config, workspace = (root / name for name in ("home", "state", "config", "workspace")) layout = case.get("workspace", {}) cwd = workspace / layout.get("cwd", "") @@ -299,6 +301,27 @@ def _run_case( return observed, unscripted +def _detach_inherited_default_acl(directory: Path) -> None: + """Leave the case with the process umask as the only source of new file modes. + + A temporary directory can carry a default POSIX ACL inherited from its parent. Such an entry + overrides the umask for everything created below it, so the hooks' own files and directories + would be recorded as 775/664 rather than the 755/644 the fixtures characterize. Only the case + root needs handling: it is created before any hook runs, and modes below it then follow the + umask that each hook process is started with. + """ + + # `system.posix_acl_default` is a Linux attribute; other hosts have their own ACL models, and + # this suite does not claim them. An unexpected failure is a real environment problem. + if not sys.platform.startswith("linux"): + return + try: + os.removexattr(directory, "system.posix_acl_default") + except OSError as error: + if error.errno not in {errno.ENODATA, errno.ENOTSUP, errno.EOPNOTSUPP}: + raise + + def _installed_plugin(host: str, target: Path, server_url: str) -> Path: shutil.copytree(PLUGINS[host], target, ignore=shutil.ignore_patterns("__pycache__", ".venv")) if host == "codex":