From 65de47bf7c391b4495e305548b22a81fac1d5a7b Mon Sep 17 00:00:00 2001 From: jasper-yl Date: Thu, 3 Dec 2026 20:45:26 -0800 Subject: [PATCH 1/4] feat(context-check): let a send admission permit early release while protection is disabled An allowed before_send returns early_release: true when the protection mode is disabled. That mode inspects no response, so an executor may forward the response of that request to its caller while it arrives. before_release with the complete response is still required and correlates it with the request binding. The other modes do not return the field. Co-Authored-By: Claude --- .../src-tauri/src/transport/operations.json | 2 +- desktop/ui/src/generated/api.d.ts | 2 + desktop/ui/src/generated/operations.ts | 2 +- docs/en/docs/operate/context-protection.md | 7 ++++ docs/zh/docs/operate/context-protection.md | 5 +++ openapi/powercontext.yaml | 6 +++ .../builtin/runtime/context_check.py | 3 ++ src/powercontext/http/_generated/models.py | 6 +++ src/powercontext/http/_generated/schema.py | 41 +++++++++++++++++++ tests/builtin/runtime/test_context_check.py | 15 +++++++ 10 files changed, 87 insertions(+), 2 deletions(-) diff --git a/desktop/src-tauri/src/transport/operations.json b/desktop/src-tauri/src/transport/operations.json index caed5b799f..308b4e1ede 100644 --- a/desktop/src-tauri/src/transport/operations.json +++ b/desktop/src-tauri/src/transport/operations.json @@ -1,5 +1,5 @@ { - "contractSha256": "72650c82272bf04fed94885723f6b5076801d09d2c74ce86636b61110b5666e1", + "contractSha256": "8b3411dec4247dc8d7f971fc242a32991fa1600085a06c28395fcb9edb2a289e", "operations": { "get_liveness": { "method": "GET", diff --git a/desktop/ui/src/generated/api.d.ts b/desktop/ui/src/generated/api.d.ts index c31eca32c8..9baa754816 100644 --- a/desktop/ui/src/generated/api.d.ts +++ b/desktop/ui/src/generated/api.d.ts @@ -4793,6 +4793,8 @@ export interface components { correlate_until?: string; /** @description Present only for allow, bound to this phase, identity, target, policy, and exact payload. */ binding?: string; + /** @description Present and true only on a before_send allow issued while protection is disabled. The executor may forward the response of this request to its caller while it arrives. The completed response still requires before_release with this request's binding. */ + early_release?: boolean; /** @description Exact Core-configured endpoint, present only on an allow for before_send when X-PowerContext-Resolve-Target was authorized for a service principal. */ target_endpoint?: string; /** diff --git a/desktop/ui/src/generated/operations.ts b/desktop/ui/src/generated/operations.ts index ff7ad5e52c..41b155e660 100644 --- a/desktop/ui/src/generated/operations.ts +++ b/desktop/ui/src/generated/operations.ts @@ -15,7 +15,7 @@ */ // Generated from openapi/powercontext.yaml. Do not edit. -export const contractSha256 = "72650c82272bf04fed94885723f6b5076801d09d2c74ce86636b61110b5666e1"; +export const contractSha256 = "8b3411dec4247dc8d7f971fc242a32991fa1600085a06c28395fcb9edb2a289e"; export const operations = { "get_liveness": { "method": "GET", diff --git a/docs/en/docs/operate/context-protection.md b/docs/en/docs/operate/context-protection.md index fe44db6011..c3b9e72c3a 100644 --- a/docs/en/docs/operate/context-protection.md +++ b/docs/en/docs/operate/context-protection.md @@ -134,6 +134,13 @@ is separate from its five-minute response-correlation deadline. Pass it as `requ Current policy, identity, and retained context dependencies are checked again. A release permit cannot authorize a new request, and correlation never extends the send deadline. These permits do not provide exactly-once execution. +While protection is `disabled`, an allowed `before_send` also returns `early_release: true`. It permits the executor +to forward the response of that request to its caller while it arrives, because this mode inspects no response. The +permission belongs to that one request and is settled before any byte is forwarded; Core does not interrupt a response +that is already being forwarded. The executor still calls `before_release` with the complete response, which +correlates it with the request binding. In `shadow`, `advisory`, and `enforcing` modes the field is absent and the +executor releases nothing before `before_release` allows it. + The public carrier currently supports complete JSON. With explicit `allow_streaming=true`, the local protected transport also supports OpenAI Chat SSE with a single choice and Responses SSE ending in a successful `response.completed` event. Other streaming profiles are withheld. It buffers and checks the complete stream before diff --git a/docs/zh/docs/operate/context-protection.md b/docs/zh/docs/operate/context-protection.md index 642f5d4825..7a904d3b37 100644 --- a/docs/zh/docs/operate/context-protection.md +++ b/docs/zh/docs/operate/context-protection.md @@ -123,6 +123,11 @@ Gateway 只有在可信的 Core 能力发现明确返回 `enforcing=false` 时 `completion: "complete"`,再次验证当前策略、身份和准备依赖。 交付批准不能用于发送新请求,关联期限也不能延长发送期限;绑定不提供恰好一次执行保证。 +保护模式为 `disabled` 时,准许的 `before_send` 还会返回 `early_release: true`:这个模式不检查任何响应,执行器可以在 +这次请求的响应到达时就把它转发给调用方。这项许可只属于这一次请求,在转发任何字节之前就已确定;Core 不会中断已经在 +转发的响应。执行器仍要在收齐响应后调用 `before_release`,把完整响应与请求绑定关联起来。`shadow`、`advisory` 和 +`enforcing` 模式下不返回这个字段,执行器在 `before_release` 准许之前不交付任何内容。 + 公开 carrier 当前支持完整 JSON。显式设置 `allow_streaming=true` 后,本地 protected transport 另外支持 单 choice 的 OpenAI Chat SSE,以及以成功的 `response.completed` 事件结束的 Responses SSE。 其他流式 profile 暂缓交付。按字节、时间、并发上限缓冲并检查完整流后,才交付原始字节; diff --git a/openapi/powercontext.yaml b/openapi/powercontext.yaml index b9865c09d0..93c800a699 100644 --- a/openapi/powercontext.yaml +++ b/openapi/powercontext.yaml @@ -10889,6 +10889,12 @@ components: minLength: 1 maxLength: 65536 description: Present only for allow, bound to this phase, identity, target, policy, and exact payload. + early_release: + type: boolean + description: >- + Present and true only on a before_send allow issued while protection is disabled. The + executor may forward the response of this request to its caller while it arrives. The + completed response still requires before_release with this request's binding. target_endpoint: type: string maxLength: 2048 diff --git a/src/powercontext/builtin/runtime/context_check.py b/src/powercontext/builtin/runtime/context_check.py index 2f9b91c896..e894f51a17 100644 --- a/src/powercontext/builtin/runtime/context_check.py +++ b/src/powercontext/builtin/runtime/context_check.py @@ -139,6 +139,7 @@ class ContextCheckResult(_CheckModel): valid_until: datetime correlate_until: datetime | None = None binding: str | None = None + early_release: bool | None = None target_endpoint: str | None = None target_protocol: str | None = None @@ -489,6 +490,8 @@ async def check_context( valid_until=deadline, correlate_until=correlate_until, binding=binding, + # Only the mode that inspects no response may let the executor forward one before it is complete. + early_release=True if request.phase == "before_send" and config.mode == "disabled" else None, target_endpoint=target.endpoint if resolve_target and target is not None else None, target_protocol=target.protocol if resolve_target and target is not None else None, ) diff --git a/src/powercontext/http/_generated/models.py b/src/powercontext/http/_generated/models.py index 73ec07ec85..fc1539b9e3 100644 --- a/src/powercontext/http/_generated/models.py +++ b/src/powercontext/http/_generated/models.py @@ -2227,6 +2227,12 @@ class ContextCheckResult(BaseModel): min_length=1, ), ] = None + early_release: Annotated[ + StrictBool | None, + Field( + description="Present and true only on a before_send allow issued while protection is disabled. The executor may forward the response of this request to its caller while it arrives. The completed response still requires before_release with this request's binding." + ), + ] = None target_endpoint: Annotated[ StrictStr | None, Field( diff --git a/src/powercontext/http/_generated/schema.py b/src/powercontext/http/_generated/schema.py index cede1de65e..995b9019de 100644 --- a/src/powercontext/http/_generated/schema.py +++ b/src/powercontext/http/_generated/schema.py @@ -12164,6 +12164,47 @@ "exact " "payload.", }, + "early_release": { + "type": "boolean", + "description": "Present " + "and " + "true " + "only " + "on " + "a " + "before_send " + "allow " + "issued " + "while " + "protection " + "is " + "disabled. " + "The " + "executor " + "may " + "forward " + "the " + "response " + "of " + "this " + "request " + "to " + "its " + "caller " + "while " + "it " + "arrives. " + "The " + "completed " + "response " + "still " + "requires " + "before_release " + "with " + "this " + "request's " + "binding.", + }, "target_endpoint": { "type": "string", "maxLength": 2048, diff --git a/tests/builtin/runtime/test_context_check.py b/tests/builtin/runtime/test_context_check.py index 558ee22449..f2738883cd 100644 --- a/tests/builtin/runtime/test_context_check.py +++ b/tests/builtin/runtime/test_context_check.py @@ -214,6 +214,21 @@ async def test_send_and_release_honor_privacy_mode(mode): assert "synthetic-forbidden-value" not in send.model_dump_json() + release.model_dump_json() +@pytest.mark.anyio +@pytest.mark.parametrize("mode", ["disabled", "shadow", "advisory", "enforcing"]) +async def test_only_a_disabled_send_admission_permits_early_release(mode): + codec = BindingCodec() + config = _config(mode=mode) + send = await _check(_send(), codec, config=config) + assert send.decision == "allow" + assert send.early_release is (True if mode == "disabled" else None) + assert ("early_release" in send.model_dump(exclude_none=True)) is (mode == "disabled") + release = await _check(_release(send.binding), codec, config=config) + assert release.decision == "allow" and release.early_release is None + unknown = await _check(_send().model_copy(update={"target_profile": "missing"}), codec, config=config) + assert unknown.decision == "withhold" and unknown.early_release is None + + @pytest.mark.anyio @pytest.mark.parametrize("mode", ["disabled", "shadow", "advisory"]) async def test_non_enforcing_modes_allow_uninspected_content(mode): From 16e1cb206c45b4236136014b4f67e55415baa9e2 Mon Sep 17 00:00:00 2001 From: jasper-yl Date: Thu, 3 Dec 2026 20:45:26 -0800 Subject: [PATCH 2/4] feat(gateway): forward a streamed Chat reply while it arrives when Core permits it With the early release permission from before_send, a streamed Chat Completions reply from an API-key upstream reaches the client as the provider writes it. The gateway keeps buffering the reply, and the release check and capture run after the client has it. The connection driver owns such an execution. The response body ends with the upstream body; a client that disconnects before that cancels the call, and a client that closes once it has the end of the stream does not: the remaining work finishes within a grace period while the model permit stays held. An upstream that stops mid-reply ends the client connection abnormally. Co-Authored-By: Claude --- docs/en/docs/operate/deploy-server.md | 14 +- docs/en/docs/operate/gateway-evidence.md | 20 +- docs/zh/docs/operate/deploy-server.md | 14 +- docs/zh/docs/operate/gateway-evidence.md | 17 +- .../crates/pc-gateway-app/src/connection.rs | 104 +++- .../pc-gateway-app/src/evidence_body.rs | 39 +- .../crates/pc-gateway-app/src/grok_tests.rs | 2 + gateway/crates/pc-gateway-app/src/ingress.rs | 157 +++++- .../pc-gateway-app/tests/live_streaming.rs | 503 ++++++++++++++++++ .../crates/pc-gateway-core/src/evidence.rs | 9 +- .../crates/pc-gateway-core/src/executor.rs | 23 + .../tests/executor_network_lifecycle.rs | 1 + .../tests/executor_semantics.rs | 13 + .../tests/real_core_rpc_recovery.rs | 1 + gateway/crates/pc-gateway-evidence/src/lib.rs | 4 + gateway/crates/pc-gateway-protocol/src/sse.rs | 3 +- .../src/reqwest_transport.rs | 55 +- .../crates/pc-gateway-transport/src/sender.rs | 97 ++++ .../tests/buffer_limit_nonstreaming.rs | 2 + .../pc-gateway-transport/tests/claude_cli.rs | 2 +- .../pc-gateway-transport/tests/codeassist.rs | 1 + .../pc-gateway-transport/tests/live_output.rs | 122 +++++ .../tests/no_duplicate_send.rs | 1 + .../tests/no_redirect_resend.rs | 1 + .../tests/subscription_response.rs | 1 + .../tests/usage_timing.rs | 2 + gateway/crates/pc-gateway-types/src/check.rs | 4 + 27 files changed, 1172 insertions(+), 40 deletions(-) create mode 100644 gateway/crates/pc-gateway-app/tests/live_streaming.rs create mode 100644 gateway/crates/pc-gateway-transport/tests/live_output.rs diff --git a/docs/en/docs/operate/deploy-server.md b/docs/en/docs/operate/deploy-server.md index 3c0b2d2c88..98bfc55f0d 100644 --- a/docs/en/docs/operate/deploy-server.md +++ b/docs/en/docs/operate/deploy-server.md @@ -220,6 +220,16 @@ The gateway adds a built-in cost-guidance instruction (S) to every request on th On Responses, the text becomes the first content block of the developer message that follows the client's first developer message, which is where Codex places its own `developer_instructions`. Without such a message, the gateway inserts a new developer message after the client's first developer message, or before the first user message when the request has no developer message. On Chat, the gateway appends the guidance to the first system message, or inserts a system message before the first user message. The text is identical on every request, so it stays part of the cached prefix. Core checks it as part of the final request like any other request text. It is independent of context injection, capture, and replay. +### Streamed replies + +By default the gateway releases a reply only after it is complete and `before_release` has allowed it, so a streaming client receives the whole stream at once when the model has finished. + +While Core's protection mode is `disabled`, an allowed `before_send` carries `early_release: true`, and the gateway forwards a streamed Chat Completions reply to the client while it arrives. This applies to a request with `stream: true` on `/gateway/v1/chat/completions` whose provider answers HTTP 200 with `text/event-stream`, on an API-key upstream. The client receives the provider's bytes unchanged. The gateway still buffers the reply, calls `before_release` with the complete body, and captures the turn; these steps run after the client has the reply and no longer delay it. In `shadow`, `advisory` and `enforcing` modes, on a gateway that discovered an enforcing Core at startup, on the Responses route, with an OAuth subscription, and for provider errors or non-streamed replies, the reply is released only when complete. A gateway started against an enforcing Core ignores the permission until it is restarted. + +The response body ends when the provider's body ends. A client that disconnects before the provider has finished cancels the call with `request_cancelled`: the provider request is dropped and the turn is not captured. Once the client has been handed the end of the stream (`data: [DONE]`) or the whole provider body, its disconnect no longer cancels the call. The release record and capture then get up to 20 seconds after the connection ends, within the original 180-second deadline and the shutdown drain limit; the model permit stays held until they finish or are stopped. If the provider stops in the middle of a forwarded reply, the gateway ends the client connection abnormally instead of completing the stream, so a partial reply is not mistaken for a complete one. + +A forwarded reply that exceeds the response buffer limit is forwarded to its end, but it is not captured and gets no release record; the call record is `withheld` with a `buffer_limit_exceeded` attempt. A release check that fails or a Core that becomes unavailable after the reply was forwarded cannot recall it: the call record shows that outcome together with `early_release`, and the turn is not captured. + ### Gateway byte capacity The Rust gateway discovers `context_protection` once at startup through `/v1/capabilities`. Model routes require the complete `ContextProtectionCapabilities` DTO defined by OpenAPI: `check_versions`, `payload_versions`, `reuse_versions`, `reuse_families`, `enforcing`, and `limits` with `payload_bytes`, `binding_bytes`, `prepared_contexts`, `dependencies`, `send_seconds`, and `correlate_seconds`. Missing or mistyped required fields pause admission even when the input capacity is present. The check/payload versions must include v1, and `limits.payload_bytes` must be a positive integer. A failed query, incompatible version, incomplete DTO, or invalid capacity pauses both model routes with HTTP 503; `/healthz` and configured Core/MCP forwarding remain available. Restore the Core contract and restart this gateway to rediscover capacity. Every model send and response release still requires its own Core check. If Core lowers a limit before the gateway restarts, that check can reject the call; increasing a Core limit does not enlarge this gateway's startup allowance until restart. Startup diagnostics distinguish transport failure, query rejection, malformed/incomplete responses, unsupported versions, and invalid capacity using fixed messages without Core error values. @@ -228,9 +238,9 @@ The Rust gateway discovers `context_protection` once at startup through `/v1/cap Provider response buffering defaults to at most 1 MiB for both fixed-length and chunked/SSE responses. The transport's explicit buffer limit can reduce this ceiling. Input `payload_bytes` does **not** declare an output allowance. Core's response configuration, content checks and the JSON/RPC envelope impose their own limits, so even a body below 1 MiB may be refused. The UDS client's 8 MiB RPC-response parser ceiling is a separate direction and is not model-body capacity. -A response buffer overflow discards the response and returns HTTP 400 with `response_buffer_limit_exceeded`. No provider content is released and the call is not retried. The execution observation retains `PossiblySent` and a `Withheld` terminal: the provider may already have charged for the call. This is not proof of a complete response or of zero cost. This observation is process-local; this stage does not export a readable call record with attempts and terminal/sending facts. The G5-A requirement to expose possible billing in call evidence remains pending integration and an exported-record regression with [#2506](https://github.com/oceanbase/powercontext/pull/2506). Smaller, completely received responses still pass `before_release` before release. +A response buffer overflow discards the response and returns HTTP 400 with `response_buffer_limit_exceeded`. No provider content is released and the call is not retried; a reply that is already being forwarded under [early release](#streamed-replies) is the exception. The execution observation retains `PossiblySent` and a `Withheld` terminal: the provider may already have charged for the call. This is not proof of a complete response or of zero cost. This observation is process-local; this stage does not export a readable call record with attempts and terminal/sending facts. The G5-A requirement to expose possible billing in call evidence remains pending integration and an exported-record regression with [#2506](https://github.com/oceanbase/powercontext/pull/2506). Smaller, completely received responses still pass `before_release` before release. -Transparent Core/MCP forwarding retains the deployment body limit rather than consuming the model input allowance. `PC_GATEWAY_MAX_CONCURRENT` (default 64) applies independently to model calls and fallback calls, so an active fallback SSE connection cannot exhaust the model semaphore. The combined ceiling is therefore up to twice the configured value, excluding exempt health probes; this setting is not a process-wide concurrency ceiling. Model permits stay with the actual HTTP/1 connection owner through local response delivery and the end of related request work, including writes still buffered after body EOF/drop. Model responses declare `Connection: close`; normal connection completion establishes local completion, without proving client receipt. The original 180-second monotonic deadline covers intake, execution, and local delivery. Expiration ends the connection without an extra delivery/cleanup window; a response may be truncated and error JSON is best effort. Framework-observed disconnects stop local work with `request_cancelled`; unobserved network loss is bounded by the deadline. A delivery interruption preserves completed execution and model-send facts, including `ReleaseAuthorized` and `ResponseReceived`. Cancellation does not prove provider rollback or safe resend. The process-local `ExecutionSnapshot::local_delivery` reports model content delivery as `NotStarted`, `InProgress`, `Completed`, or `Interrupted(reason)`; rejection and lifecycle-error responses do not start model content delivery. It is independent of the execution terminal and does not retain response bytes or permits. Fallback permits remain attached to their response body until drop. Fallback retains authentication, keep-alive and streaming behavior without the model deadline or forced connection closure. Provider sends and HTTP Core RPCs use fresh HTTP/1 connections with idle pooling disabled; the UDS Core client retains its bounded idle pool. Gateway shutdown allows up to 25 seconds to drain and bounds process exit to 30 seconds from the first shutdown signal. `/healthz` is exempt from both semaphores. A fallback request with a known oversized Content-Length returns 413 before forwarding. Unknown-length overflow produces a body error: a prefix may already have reached Core, and the proxy returns 502 if forwarding fails. It is not successful truncation, and the gateway does not buffer an entire MCP stream to force a uniform error status. +Transparent Core/MCP forwarding retains the deployment body limit rather than consuming the model input allowance. `PC_GATEWAY_MAX_CONCURRENT` (default 64) applies independently to model calls and fallback calls, so an active fallback SSE connection cannot exhaust the model semaphore. The combined ceiling is therefore up to twice the configured value, excluding exempt health probes; this setting is not a process-wide concurrency ceiling. Model permits stay with the actual HTTP/1 connection owner through local response delivery and the end of related request work, including writes still buffered after body EOF/drop. Model responses declare `Connection: close`; normal connection completion establishes local completion, without proving client receipt. The original 180-second monotonic deadline covers intake, execution, and local delivery. Expiration ends the connection without an extra delivery/cleanup window; a response may be truncated and error JSON is best effort. Framework-observed disconnects stop local work with `request_cancelled`, except after a forwarded reply is complete (see [Streamed replies](#streamed-replies)); unobserved network loss is bounded by the deadline. A delivery interruption preserves completed execution and model-send facts, including `ReleaseAuthorized` and `ResponseReceived`. Cancellation does not prove provider rollback or safe resend. The process-local `ExecutionSnapshot::local_delivery` reports model content delivery as `NotStarted`, `InProgress`, `Completed`, or `Interrupted(reason)`; rejection and lifecycle-error responses do not start model content delivery. It is independent of the execution terminal and does not retain response bytes or permits. Fallback permits remain attached to their response body until drop. Fallback retains authentication, keep-alive and streaming behavior without the model deadline or forced connection closure. Provider sends and HTTP Core RPCs use fresh HTTP/1 connections with idle pooling disabled; the UDS Core client retains its bounded idle pool. Gateway shutdown allows up to 25 seconds to drain and bounds process exit to 30 seconds from the first shutdown signal. `/healthz` is exempt from both semaphores. A fallback request with a known oversized Content-Length returns 413 before forwarding. Unknown-length overflow produces a body error: a prefix may already have reached Core, and the proxy returns 502 if forwarding fails. It is not successful truncation, and the gateway does not buffer an entire MCP stream to force a uniform error status. These are per-body and per-class concurrency limits. They do not measure retained bytes or establish a process RSS ceiling. Process-wide retained-byte accounting and output-capacity discovery belong to the remaining [G5-B work in #2464](https://github.com/oceanbase/powercontext/issues/2464). diff --git a/docs/en/docs/operate/gateway-evidence.md b/docs/en/docs/operate/gateway-evidence.md index a2d6c1b876..ac9a7e94f2 100644 --- a/docs/en/docs/operate/gateway-evidence.md +++ b/docs/en/docs/operate/gateway-evidence.md @@ -140,7 +140,7 @@ and `RUST_LOG` filtering applies. ## Terminal and send facts The `call` record contains `terminal`, `sending`, `attempts`, `upstream_status`, normalized `usage`, optional -`interruption`, `internal`, and timing fields. `internal` is true when the host marked the request with +`interruption`, `internal`, `early_release`, and timing fields. `internal` is true when the host marked the request with `X-PowerContext-Turn: internal`; the request is still checked and forwarded, but it is never prepared, injected, replayed or captured as a turn. Terminal values are `release_authorized`, `blocked`, `withheld`, `send_indeterminate`, `not_sent`, `gate_paused`, `degraded`, `admission_expired`, and `abandoned`. @@ -159,6 +159,13 @@ observations at destruction; the shared execution terminal identifies a confirme cancellation authority or timer. Cancellation during transport remains `possibly_sent`, with unknown usage, never `not_sent`. +`early_release` is true when the gateway, with Core's permission, forwarded the reply to the client while it arrived +(see [Streamed replies](deploy-server.md#streamed-replies)). For such a call, `terminal`, `release_decision_ms` and +`release_authorized_ms` describe the release record and capture made after the client had the reply, not a gate +before delivery: a terminal other than `release_authorized` means the turn was not captured, not that the reply was +withheld from the client. `delivery` records show what was handed to the framework. The field is false for every +call that was released only when complete. + Each `attempt` contains `attempt`, `outcome`, `started_ms`, `duration_ms`, `upstream_status`, normalized `usage`, `response_first_byte_ms`, and `response_complete_ms`. Outcomes are `possibly_sent` (interrupted pending send), `delivered`, `upstream_error` (complete HTTP response with status >= 400), `connect_refused`, `rejected_locally`, @@ -169,7 +176,8 @@ both waiting for response headers and timing out while reading the body, includi usage survives decoding/release failures. A dropped pending transport cannot provide its private partial observations. A response-buffer overflow produces a `withheld` call with `possibly_sent`, one `buffer_limit_exceeded` attempt, unknown usage/completion, and any observed status/first-byte timing. It releases no response prefix and does not retry, -including degraded passthrough. This preserves the capacity-limit decision separately from possible billing. +including degraded passthrough; with `early_release`, the reply was forwarded to its end and only the capture and +release record are missing. This preserves the capacity-limit decision separately from possible billing. ## Usage mapping @@ -205,7 +213,7 @@ All durations are monotonic milliseconds, truncated to integers. Null means unav | Attempt `started_ms` | Request-control creation to transport handoff | | Attempt `duration_ms` | Handoff to transport result or future destruction | | `response_first_byte_ms` | Transport send start, **before** awaiting headers, to first nonempty HTTP body chunk | -| `response_complete_ms` | Same transport origin to complete buffered response | +| `response_complete_ms` | Same transport origin to complete buffered response; a forwarded reply is buffered too | | `upstream_ttft_ms` | Always null: HTTP JSON/SSE bytes do not establish a model's first token | | `release_decision_ms` | Request-control creation to before-release check result, including error/refusal | | `release_authorized_ms` | Request-control creation to validated, unexpired release after optional capture | @@ -218,13 +226,15 @@ A `delivery` record reports `framework_handoff` when the released/degraded body `first_body_frame` when the framework first polls a nonempty data frame, `first_model_content` when it polls the frame containing the first encoded byte of recognized model output, `body_completed` when the wrapped body reports completion, or `body_dropped` if dropped before observed completion. Strict release authorization precedes -framework handoff and both first-frame/content observations. A degraded response has no release authorization timestamp. +framework handoff and both first-frame/content observations; with `early_release` it follows them. A degraded response has no release authorization timestamp. The content boundary recognizes nonempty assistant text, refusal strings, and function-call names/arguments in OpenAI Chat/Responses JSON and their supported SSE output, including Responses replay. It skips role-only, usage, reasoning, error and other control events. An item-added event containing an actual function name or output text can establish content; the event name alone cannot. The locator inspects the exact buffered outgoing body and passes -only a byte offset to the observer. The observer counts polled data bytes across arbitrary frame splits; it neither +only a byte offset to the observer. A reply forwarded under `early_release` has no complete body at handoff: the +observer keeps the frames polled so far, up to 256 KiB, until a complete SSE event establishes content, reports the +boundary with that frame, and then drops them. The observer counts polled data bytes across arbitrary frame splits; it neither retains content nor changes response bytes. This measures the frame containing the first **encoded** content byte, which can be a JSON escape, rather than waiting for a complete decoded character or SSE event. diff --git a/docs/zh/docs/operate/deploy-server.md b/docs/zh/docs/operate/deploy-server.md index 49f01e4f19..50761b5dae 100644 --- a/docs/zh/docs/operate/deploy-server.md +++ b/docs/zh/docs/operate/deploy-server.md @@ -222,6 +222,16 @@ Gemini 关闭 Gateway 上下文注入。Claude CLI 只接受新的单轮文本 在 Responses 入口,指令文本成为客户端第一条 developer 消息之后那条 developer 消息的第一个内容块,也就是 Codex 放置自身 `developer_instructions` 的位置。没有这样的消息时,网关在客户端第一条 developer 消息之后插入一条新的 developer 消息;请求中没有 developer 消息时,插在第一条用户消息之前。在 Chat 入口,网关将指令追加到第一条 system 消息,或在第一条用户消息之前插入一条 system 消息。每个请求中的文本都相同,因此它始终是缓存前缀的一部分。Core 把它作为最终请求的一部分,像其他请求文本一样检查。它与上下文注入、沉淀和重放相互独立。 +### 流式回复 + +默认情况下,Gateway 在回复完整、`before_release` 准许之后才交付,所以流式客户端要等模型全部生成完,才一次收到整段流。 + +Core 的保护模式为 `disabled` 时,准许的 `before_send` 带有 `early_release: true`,Gateway 会把流式的 Chat Completions 回复在到达时就转发给客户端。条件是:请求发到 `/gateway/v1/chat/completions` 且 `stream: true`,上游使用 API key,并以 HTTP 200 和 `text/event-stream` 应答。客户端收到的就是上游的原始字节。Gateway 仍会缓冲整段回复,用完整正文调用 `before_release`,并沉淀这个回合;这些步骤在客户端拿到回复之后进行,不再推迟回复。`shadow`、`advisory`、`enforcing` 模式,启动时发现 Core 为 enforcing 的 Gateway,Responses 路由,OAuth 订阅,以及上游返回错误或非流式回复时,回复仍然在完整之后才交付。针对 enforcing Core 启动的 Gateway 在重启之前不采用这项许可。 + +响应正文在上游正文结束时结束。客户端在上游结束之前断开,调用以 `request_cancelled` 取消:对上游的请求被丢弃,回合不沉淀。客户端已经拿到流的结束标记(`data: [DONE]`)或上游的全部正文之后,它断开连接不再取消调用;放行记录与沉淀在连接结束后最多还有 20 秒,同时受原有的 180 秒期限和停机排空期限约束,模型并发许可保持到它们完成或被停止。上游在转发途中停止时,Gateway 异常结束客户端连接,而不是正常结束这段流,残缺的回复不会被当成完整回复。 + +转发中的回复超过响应缓冲上限时,仍然转发到结束,但不沉淀,也没有放行记录;调用记录为 `withheld`,并有一次 `buffer_limit_exceeded` 尝试。回复转发之后放行检查失败或 Core 不可用,已交付的内容无法收回:调用记录保留这一结果和 `early_release`,回合不沉淀。 + ### Gateway 字节容量 Rust Gateway 在启动时通过 `/v1/capabilities` 查询一次 `context_protection`。模型入口要求 OpenAPI 定义的完整 `ContextProtectionCapabilities` DTO: `check_versions`、`payload_versions`、`reuse_versions`、`reuse_families`、`enforcing`,以及包含 `payload_bytes`、`binding_bytes`、`prepared_contexts`、`dependencies`、`send_seconds` 和 `correlate_seconds` 的 `limits`。即使存在输入容量,任何必需字段缺失或类型错误也会暂停准入。 check/payload 版本必须包含 v1,且 `limits.payload_bytes` 必须是正整数。查询失败、版本不兼容、DTO 不完整或容量无效时,两个模型入口返回 HTTP 503 暂停服务; `/healthz` 和已配置的 Core/MCP 转发仍可访问。恢复 Core 契约后,重启 Gateway 以重新发现容量。每次模型发送和响应释放仍须分别通过 Core 检查。若 Core 在 Gateway 重启前收紧限制,这次检查可以拒绝调用;增大 Core 限制不会在重启前放大 Gateway 启动时确认的额度。启动诊断通过固定消息区分传输失败、查询被拒、响应畸形/不完整、版本不兼容和容量无效,不输出 Core 错误值。 @@ -230,9 +240,9 @@ Rust Gateway 在启动时通过 `/v1/capabilities` 查询一次 `context_protect 固定长度和 chunked/SSE provider 响应的默认缓冲上限均为 1 MiB。传输器显式设置的缓冲上限可以进一步收紧该值。输入 `payload_bytes` **不声明**输出额度。 Core 的响应配置、内容检查以及 JSON/RPC 包装仍有各自的限制,因此低于 1 MiB 的正文也可能被拒绝。 UDS 客户端的 8 MiB RPC 响应解析上限属于另一个传输方向,不是模型正文容量。 -响应缓冲超限时丢弃响应,返回 HTTP 400 和 `response_buffer_limit_exceeded`。不会释放 provider 正文,也不会自动重发。执行观察保留 `PossiblySent` 与 `Withheld` 终态: provider 可能已经计费。这不代表收到了完整响应,也不承诺零费用。该观察仅在进程内可见;本阶段尚未导出含尝试次数、执行终态与发送状态的可读取调用记录。 G5-A 的“可能已计费进入调用证据”仍待接入 [#2506](https://github.com/oceanbase/powercontext/pull/2506),并通过导出记录的回归测试后才能验收。更小的完整响应仍须通过 `before_release` 才能释放。 +响应缓冲超限时丢弃响应,返回 HTTP 400 和 `response_buffer_limit_exceeded`。不会释放 provider 正文,也不会自动重发;已经按[提前交付](#流式回复)在转发的回复除外。执行观察保留 `PossiblySent` 与 `Withheld` 终态: provider 可能已经计费。这不代表收到了完整响应,也不承诺零费用。该观察仅在进程内可见;本阶段尚未导出含尝试次数、执行终态与发送状态的可读取调用记录。 G5-A 的“可能已计费进入调用证据”仍待接入 [#2506](https://github.com/oceanbase/powercontext/pull/2506),并通过导出记录的回归测试后才能验收。更小的完整响应仍须通过 `before_release` 才能释放。 -透明 Core/MCP 转发继续使用部署正文上限,不消耗模型输入额度。 `PC_GATEWAY_MAX_CONCURRENT`(默认 64)分别限制模型调用与 fallback 调用, 活跃的 fallback SSE 连接不会耗尽模型并发许可。两类合计最多可持有配置值两倍的许可, 不含豁免的健康探测;该设置不是进程全局并发上限。 模型许可由实际 HTTP/1 连接 owner 持有,覆盖本地响应交付及相关请求工作结束, 包括 body EOF/drop 后仍由框架缓冲的待写数据。模型响应声明 `Connection: close`; 连接正常完成表示本地完成,不证明客户端已经读取或接受响应。 原始 180 秒单调期限覆盖入口、执行和本地交付;到期直接结束连接,不另加交付或清理窗口, 部分响应可能截断,错误 JSON 仅尽力返回。框架实际观察到断连时以 `request_cancelled` 停止本地工作; 没有观察到断连的网络失联由原期限收束。交付中断保留已完成的执行终态和模型发送事实, 包括 `ReleaseAuthorized` 与 `ResponseReceived`;取消不证明 provider 回滚,也不代表可以安全重发。 进程内 `ExecutionSnapshot::local_delivery` 用 `NotStarted`、`InProgress`、`Completed` 与 `Interrupted(reason)` 表示模型内容的交付状态;拒绝和生命周期错误响应不启动模型内容交付。 它独立于执行终态,不持有响应字节或并发许可。 fallback 许可仍随响应 body 持有,直到 body drop;fallback 保留认证、keep-alive 与流式行为, 不继承模型期限或强制关闭连接策略。provider 发送与 HTTP Core RPC 使用全新 HTTP/1 连接,不复用空闲连接; UDS Core 客户端保留有界空闲连接池。Gateway 从首个停机信号起最多排空 25 秒,并将进程退出限制在 30 秒内。 `/healthz` 豁免两类并发限制。已知 Content-Length 的 fallback 超限请求在转发前返回 413。 未知长度超限会产生 body error:前缀可能已经到达 Core,转发失败时代理返回 502。 这不是成功截断,Gateway 不会通过完整缓冲 MCP 流来强制统一错误状态码。 +透明 Core/MCP 转发继续使用部署正文上限,不消耗模型输入额度。 `PC_GATEWAY_MAX_CONCURRENT`(默认 64)分别限制模型调用与 fallback 调用, 活跃的 fallback SSE 连接不会耗尽模型并发许可。两类合计最多可持有配置值两倍的许可, 不含豁免的健康探测;该设置不是进程全局并发上限。 模型许可由实际 HTTP/1 连接 owner 持有,覆盖本地响应交付及相关请求工作结束, 包括 body EOF/drop 后仍由框架缓冲的待写数据。模型响应声明 `Connection: close`; 连接正常完成表示本地完成,不证明客户端已经读取或接受响应。 原始 180 秒单调期限覆盖入口、执行和本地交付;到期直接结束连接,不另加交付或清理窗口, 部分响应可能截断,错误 JSON 仅尽力返回。框架实际观察到断连时以 `request_cancelled` 停止本地工作,转发中的回复已经完整之后除外(见[流式回复](#流式回复)); 没有观察到断连的网络失联由原期限收束。交付中断保留已完成的执行终态和模型发送事实, 包括 `ReleaseAuthorized` 与 `ResponseReceived`;取消不证明 provider 回滚,也不代表可以安全重发。 进程内 `ExecutionSnapshot::local_delivery` 用 `NotStarted`、`InProgress`、`Completed` 与 `Interrupted(reason)` 表示模型内容的交付状态;拒绝和生命周期错误响应不启动模型内容交付。 它独立于执行终态,不持有响应字节或并发许可。 fallback 许可仍随响应 body 持有,直到 body drop;fallback 保留认证、keep-alive 与流式行为, 不继承模型期限或强制关闭连接策略。provider 发送与 HTTP Core RPC 使用全新 HTTP/1 连接,不复用空闲连接; UDS Core 客户端保留有界空闲连接池。Gateway 从首个停机信号起最多排空 25 秒,并将进程退出限制在 30 秒内。 `/healthz` 豁免两类并发限制。已知 Content-Length 的 fallback 超限请求在转发前返回 413。 未知长度超限会产生 body error:前缀可能已经到达 Core,转发失败时代理返回 502。 这不是成功截断,Gateway 不会通过完整缓冲 MCP 流来强制统一错误状态码。 这些是逐正文和分类并发限制,不是驻留字节测量,也不构成进程 RSS 上限。全局驻留字节记账与输出容量发现属于 [#2464 的 G5-B 后续工作](https://github.com/oceanbase/powercontext/issues/2464)。 diff --git a/docs/zh/docs/operate/gateway-evidence.md b/docs/zh/docs/operate/gateway-evidence.md index f912c2052b..19605d4219 100644 --- a/docs/zh/docs/operate/gateway-evidence.md +++ b/docs/zh/docs/operate/gateway-evidence.md @@ -123,7 +123,7 @@ reasoning 一类条目以及服务商已在响应内执行完毕的工具为 ass ## 终态与发送事实 -`call` 记录包含 `terminal`、`sending`、`attempts`、`upstream_status`、归一化 `usage`、`internal`、 +`call` 记录包含 `terminal`、`sending`、`attempts`、`upstream_status`、归一化 `usage`、`internal`、`early_release`、 可选 `interruption` 和计时字段。`internal` 为 true 表示宿主用 `X-PowerContext-Turn: internal` 标记了该请求;网关仍会执行检查并转发,但不准备、不注入、不重放,也不把它捕获为回合。终态取值为 `release_authorized`、`blocked`、`withheld`、 `send_indeterminate`、`not_sent`、`gate_paused`、`degraded`、`admission_expired`、`abandoned`。 已知生命周期停止编码为 `{"stopped":"deadline_exceeded"}`、`{"stopped":"gateway_shutdown"}` @@ -139,6 +139,11 @@ reasoning 一类条目以及服务商已在响应内执行完毕的工具为 ass 该字段描述销毁时的观测,共享执行终态标识已确认的停止原因。证据层不新增取消权或定时器。 传输中取消保持 `possibly_sent` 和未知 usage,不能记成 `not_sent`。 +Gateway 经 Core 许可、在回复到达时就把它转发给了客户端时,`early_release` 为 true(见 +[流式回复](deploy-server.md#流式回复))。这样的调用里,`terminal`、`release_decision_ms` 和 `release_authorized_ms` +描述的是客户端拿到回复之后完成的放行记录与沉淀,不是交付之前的关卡:`release_authorized` 以外的终态表示回合没有 +沉淀,不表示回复没有交给客户端。交给框架的内容以 `delivery` 记录为准。回复完整之后才交付的调用,这个字段都是 false。 + 每个 `attempt` 包含 `attempt`、`outcome`、`started_ms`、`duration_ms`、`upstream_status`、归一化 `usage`、`response_first_byte_ms`、`response_complete_ms`。 结果取值为 `possibly_sent`(pending 发送被中断)、`delivered`、`upstream_error`(完整 HTTP 响应且状态码 >= 400)、 @@ -148,7 +153,8 @@ reasoning 一类条目以及服务商已在响应内执行完毕的工具为 ass `lost_after_handoff` 表示其他传输/正文读取失败。两者均不允许自动重试。 transport 交付完整响应后,解码或释放失败不会丢掉 usage。直接丢弃 pending transport 时无法取得其内部的部分观测。 响应缓冲区超限时,调用记录为 `withheld`、发送事实为 `possibly_sent`,仅有一次 `buffer_limit_exceeded` 尝试; -usage 与完整响应时间未知,保留已观察到的状态码和首字节时间。不释放响应前缀,也不重试,降级直通同样遵循此行为。 +usage 与完整响应时间未知,保留已观察到的状态码和首字节时间。不释放响应前缀,也不重试,降级直通同样遵循此行为; +`early_release` 的调用里,回复已经转发到结束,缺少的只是沉淀和放行记录。 容量限制的拒绝结论与可能计费事实分别保留。 ## Usage 映射 @@ -184,7 +190,7 @@ SSE 媒体类型在分离参数后按大小写不敏感方式比较。usage 与 | 尝试 `started_ms` | 创建请求控制至交给 transport | | 尝试 `duration_ms` | 交给 transport 至得到传输结果或 future 销毁 | | `response_first_byte_ms` | 从等待响应头**之前**的 transport 发送起点至首个非空 HTTP 正文 chunk | -| `response_complete_ms` | 从同一 transport 起点至完整缓冲响应 | +| `response_complete_ms` | 从同一 transport 起点至完整缓冲响应;转发中的回复同样会缓冲 | | `upstream_ttft_ms` | 始终为 null;HTTP JSON/SSE 字节无法证明模型首 token | | `release_decision_ms` | 创建请求控制至 before-release 检查返回,包含错误与拒绝 | | `release_authorized_ms` | 创建请求控制至通过校验且未过期的释放批准,位于可选 capture 之后 | @@ -196,12 +202,13 @@ SSE 媒体类型在分离参数后按大小写不敏感方式比较。usage 与 `delivery` 在获准/降级响应体放入 HTTP 响应时报告 `framework_handoff`,框架首次轮询取出非空 data frame 时报告 `first_body_frame`,取出包含首个可识别模型输出编码字节的 frame 时报告 `first_model_content`, 包装的 body 报告完成时为 `body_completed`,观察到完成之前被丢弃时为 `body_dropped`。 -strict 模式的释放批准先于框架交接、首个 data frame 与首内容观测。降级响应没有释放批准时间。 +strict 模式的释放批准先于框架交接、首个 data frame 与首内容观测;`early_release` 的调用里它在这些观测之后。降级响应没有释放批准时间。 首内容边界识别 OpenAI Chat/Responses JSON 与所支持 SSE 输出中的非空 assistant 文本、拒绝字符串、 函数调用名称及参数,包含 Responses 重放。仅含 role、usage、reasoning、error 及其他控制信息的事件不触发。 item-added 事件若确实包含函数名或输出文本,也可以建立内容边界;仅凭事件名称不能建立。 -定位器检查实际发送的完整缓冲正文,只把字节偏移交给观察器。观察器累计已轮询 data 字节,支持任意 frame +定位器检查实际发送的完整缓冲正文,只把字节偏移交给观察器。按 `early_release` 转发的回复在交接时还没有完整 +正文:观察器保留已轮询的 frame(最多 256 KiB),直到一个完整的 SSE 事件建立内容边界,随该 frame 报告边界后丢弃。观察器累计已轮询 data 字节,支持任意 frame 切分,不保留正文,不改变响应字节。记录的是包含首个**编码**内容字节的 frame,该字节可能属于 JSON 转义, 不等待完整解码字符或完整 SSE 事件。 diff --git a/gateway/crates/pc-gateway-app/src/connection.rs b/gateway/crates/pc-gateway-app/src/connection.rs index 5b68a07d95..5ad32b05e9 100644 --- a/gateway/crates/pc-gateway-app/src/connection.rs +++ b/gateway/crates/pc-gateway-app/src/connection.rs @@ -25,7 +25,7 @@ use std::{ future::Future, pin::Pin, sync::{Arc, Mutex}, - task::{Context, Poll}, + task::{Context, Poll, Waker}, }; use tokio::{ io::{AsyncRead, AsyncWrite}, @@ -48,8 +48,17 @@ fn has_model_deadline(path: &str) -> bool { is_model_route(path) || path == "/gateway/v1/extract" } +/// After a live reply is complete and its connection has ended, the release record and capture +/// may still run for this long: room for the two Core requests, each bounded by its own timeout. +/// The model permit stays held until they finish or are stopped. +const COMPLETION_GRACE: std::time::Duration = std::time::Duration::from_secs(20); + +// Field order is drop order: the owned execution is destroyed before its permit is released. #[derive(Default)] struct ModelState { + work: Option + Send>>>, + work_waker: Option, + reply_complete: bool, control: Option, lifecycle: Option, permit: Option, @@ -84,6 +93,54 @@ impl ModelConnection { self.state.lock().unwrap().permit = Some(permit); } + /// Hand an execution that forwards its reply while it arrives to the connection driver. The + /// driver polls it beside Hyper, so it can outlive the response body without a detached task. + pub(crate) fn own(&self, work: impl Future + Send + 'static) { + let waker = { + let mut state = self.state.lock().unwrap(); + state.work = Some(Box::pin(work)); + state.work_waker.take() + }; + if let Some(waker) = waker { + waker.wake(); + } + } + + /// The client has been handed the reply's protocol end, or the whole upstream body. + pub(crate) fn reply_complete(&self) { + self.state.lock().unwrap().reply_complete = true; + } + + /// Owned execution that is still running after its complete reply was handed over. + fn completing(&self) -> bool { + let state = self.state.lock().unwrap(); + state.work.is_some() && state.reply_complete + } + + /// Advance the owned execution. Resolves once when it finishes; pending while there is none. + async fn work(&self) { + std::future::poll_fn(|cx| { + let work = { + let mut state = self.state.lock().unwrap(); + let work = state.work.take(); + if work.is_none() { + state.work_waker = Some(cx.waker().clone()); + } + work + }; + // Polled outside the lock: the execution reads this connection's lifecycle. + let Some(mut work) = work else { + return Poll::Pending; + }; + if work.as_mut().poll(cx).is_ready() { + return Poll::Ready(()); + } + self.state.lock().unwrap().work = Some(work); + Poll::Pending + }) + .await + } + fn lifecycle(&self) -> Option { self.state.lock().unwrap().lifecycle.clone() } @@ -233,6 +290,8 @@ where .serve_connection(hyper_util::rt::TokioIo::new(io), service), ); let mut draining = None; + // A live reply reached its end, but the client closed before Hyper finished the connection. + let mut closed_at_end = false; loop { let requested = shutdown.borrow_and_update().clone(); if draining.is_none() { @@ -268,11 +327,17 @@ where owner.interrupt(LifecycleStopReason::GatewayShutdown); break; } + _ = owner.work() => {} result = &mut connection => { - if result.is_err() { + if result.is_ok() { + if let Some(lifecycle) = owner.lifecycle() { + lifecycle.complete_local_delivery(); + } + } else if owner.completing() { + // Interrupting now would stop the execution; record the delivery after it. + closed_at_end = true; + } else { owner.interrupt(LifecycleStopReason::RequestCancelled); - } else if let Some(lifecycle) = owner.lifecycle() { - lifecycle.complete_local_delivery(); } break; } @@ -281,6 +346,37 @@ where // Destruction is synchronous: includes the service future, body and write // buffers. Only afterwards may the final owner release the model permit. drop(connection); + if owner.completing() { + let grace = tokio::time::Instant::now() + COMPLETION_GRACE; + loop { + if draining.is_none() { + draining = shutdown.borrow_and_update().clone(); + } + tokio::select! { + biased; + reason = owner.stopped() => { + owner.interrupt(reason); + break; + } + _ = shutdown.changed(), if draining.is_none() => {} + _ = async { + if let Some(deadlines) = &draining { deadlines.drain_expired().await; } + else { std::future::pending::<()>().await; } + } => { + owner.interrupt(LifecycleStopReason::GatewayShutdown); + break; + } + _ = tokio::time::sleep_until(grace) => { + owner.interrupt(LifecycleStopReason::RequestCancelled); + break; + } + _ = owner.work() => break, + } + } + } + if closed_at_end { + owner.interrupt(LifecycleStopReason::RequestCancelled); + } drop(resources); drop(owner); } diff --git a/gateway/crates/pc-gateway-app/src/evidence_body.rs b/gateway/crates/pc-gateway-app/src/evidence_body.rs index 5216e2fa5d..5252c342bb 100644 --- a/gateway/crates/pc-gateway-app/src/evidence_body.rs +++ b/gateway/crates/pc-gateway-app/src/evidence_body.rs @@ -17,6 +17,7 @@ use axum::body::{Body, Bytes}; use http_body::{Body as HttpBody, Frame, SizeHint}; use pc_gateway_core::ExecutionObservation; use pc_gateway_evidence::{DeliveryBoundary, DeliveryEvidence, EvidenceSink}; +use pc_gateway_protocol::{first_model_content_offset, OutputProtocol}; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; @@ -25,12 +26,25 @@ use std::task::{Context, Poll}; #[derive(Clone, Copy)] pub(crate) struct FirstContentOffset(pub(crate) Option); +/// Where the first model content of the outgoing body is. +pub(crate) enum FirstContent { + /// Located in the complete body before handoff. + At(Option), + /// The body is forwarded while it arrives; locate it in the SSE frames as they pass. + Arriving(OutputProtocol), +} + +/// A forwarded body is searched for its first model content only this far. +const LOCATE_LIMIT: usize = 256 * 1024; + pub(crate) struct EvidenceBody { body: Body, observation: ExecutionObservation, sink: Arc, first: bool, first_content: Option, + /// Frames seen so far of a body whose first model content is not located yet. + arriving: Option<(OutputProtocol, Vec)>, body_bytes: usize, completed: bool, } @@ -40,14 +54,19 @@ impl EvidenceBody { body: Body, observation: ExecutionObservation, sink: Arc, - first_content: Option, + first_content: FirstContent, ) -> Body { + let (first_content, arriving) = match first_content { + FirstContent::At(offset) => (offset, None), + FirstContent::Arriving(protocol) => (None, Some((protocol, Vec::new()))), + }; let wrapper = Self { body, observation, sink, first: false, first_content, + arriving, body_bytes: 0, completed: false, }; @@ -84,6 +103,21 @@ impl HttpBody for EvidenceBody { self.record(DeliveryBoundary::FirstBodyFrame); } self.body_bytes = self.body_bytes.saturating_add(data.len()); + let located = self.arriving.as_mut().map(|(protocol, seen)| { + seen.extend_from_slice(data); + // Only complete events count, so the content found lies within the frames already polled. + first_model_content_offset(seen, *protocol, true).is_some() + || seen.len() > LOCATE_LIMIT + }); + if located == Some(true) { + let within = self + .arriving + .take() + .is_some_and(|(_, seen)| seen.len() <= LOCATE_LIMIT); + if within { + self.record(DeliveryBoundary::FirstModelContent); + } + } if self .first_content .is_some_and(|offset| offset < self.body_bytes) @@ -123,7 +157,6 @@ mod tests { use http_body_util::BodyExt; use pc_gateway_core::RequestControl; use pc_gateway_evidence::{BufferedEvidenceSink, EvidenceEvent}; - use pc_gateway_protocol::{first_model_content_offset, OutputProtocol}; use std::collections::VecDeque; use std::convert::Infallible; @@ -165,7 +198,7 @@ mod tests { Body::new(Frames(bytes.into())), control.observation(), sink, - offset, + FirstContent::At(offset), ) } diff --git a/gateway/crates/pc-gateway-app/src/grok_tests.rs b/gateway/crates/pc-gateway-app/src/grok_tests.rs index ad3e7a659a..9621f8283f 100644 --- a/gateway/crates/pc-gateway-app/src/grok_tests.rs +++ b/gateway/crates/pc-gateway-app/src/grok_tests.rs @@ -104,6 +104,7 @@ async fn magpie_tool_selection_and_identity_survive_checks_and_client_json_or_ss let canonical = to_canonical_responses(serde_json::from_value(request).unwrap()).unwrap(); let call = ManagedCall { + live: None, scope_id: "test".into(), target_profile: "test".into(), request: canonical, @@ -251,6 +252,7 @@ async fn magpie_tool_selection_and_identity_survive_checks_and_client_json_or_ss block_original.then(|| Bytes::copy_from_slice(reply)); let request = fixture["cases"][0]["request"].clone(); let call = ManagedCall { + live: None, scope_id: "test".into(), target_profile: "test".into(), request: to_canonical_responses(serde_json::from_value(request).unwrap()).unwrap(), diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index 5c33a907d3..e59649ef20 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -267,6 +267,7 @@ pub async fn extract( return subscription_auth_failed(); }; let call = ManagedCall { + live: None, scope_id: scope_id.to_owned(), target_profile: state.upstream_profile.clone(), request: canonical, @@ -454,7 +455,11 @@ async fn ingress_common( req: Request, format: Format, ) -> Response { - let control = match req.extensions().get::() { + let owner = req + .extensions() + .get::() + .cloned(); + let control = match &owner { Some(owner) => owner.take_control(), None => RequestControl::new( tokio::time::Instant::now() + std::time::Duration::from_secs(180), @@ -469,7 +474,14 @@ async fn ingress_common( let observation = control.observation(); let cancellation = control.cancellation(); let mut response = match lifecycle - .run(ingress_model(state.clone(), headers, req, format, control)) + .run(ingress_model( + state.clone(), + headers, + req, + format, + control, + owner, + )) .await { Ok(response) => response, @@ -482,10 +494,16 @@ async fn ingress_common( ), }; if response.extensions().get::().is_some() { - let first_content = response - .extensions() - .get::() - .and_then(|offset| offset.0); + let first_content = if response.extensions().get::().is_some() { + crate::evidence_body::FirstContent::Arriving(protocol) + } else { + crate::evidence_body::FirstContent::At( + response + .extensions() + .get::() + .and_then(|offset| offset.0), + ) + }; let (parts, body) = response.into_parts(); response = Response::from_parts( parts, @@ -513,6 +531,7 @@ async fn ingress_model( req: Request, format: Format, control: RequestControl, + owner: Option, ) -> Response { if let Some(rejected) = unauthorized(&state, &headers) { return rejected; @@ -737,7 +756,8 @@ async fn ingress_model( if injection_enabled && !inject_context { tracing::warn!("context injection skipped: no conversation identity"); } - let call = ManagedCall { + let mut call = ManagedCall { + live: None, scope_id: scope_id.to_owned(), target_profile: state.upstream_profile.clone(), request: canonical, @@ -773,6 +793,47 @@ async fn ingress_model( }, ); } + // A streamed Chat reply that reaches the client unchanged can be forwarded while it arrives, when + // Core permits it for this request. The connection driver owns that execution: it ends the response + // with the upstream body and completes the release record and capture afterwards. + if let Some(owner) = owner.filter(|_| { + call.request.stream && matches!(format, Format::Chat) && subscription_kind.is_none() + }) { + let (output, mut reply) = pc_gateway_transport::LiveOutput::channel(); + call.live = Some(output); + let (finished, outcome) = tokio::sync::oneshot::channel(); + let execution = state.clone(); + owner.own(async move { + let outcome = execution + .executor + .run_with_replay_identity( + control, + call, + &renderer, + execution.evidence.as_ref(), + history_id.as_deref(), + ) + .await; + let _ = finished.send(outcome); + }); + return match reply.next().await { + Some(first) => live_response(owner, reply, first), + // Nothing was forwarded: the complete outcome decides the response, as on every other call. + None => match outcome.await { + Ok(outcome) => respond(outcome, OutputProtocol::OpenAiChat), + Err(_) => respond( + ManagedOutcome::Stopped { + reason: lifecycle + .checkpoint() + .err() + .unwrap_or(pc_gateway_core::LifecycleStopReason::RequestCancelled), + model_send: lifecycle.observation().snapshot().model_send, + }, + OutputProtocol::OpenAiChat, + ), + }, + }; + } let outcome = state .executor .run_with_replay_identity( @@ -795,6 +856,88 @@ async fn ingress_model( ) } +/// 边到达边交付的 Chat SSE 响应。正文在上游正文结束时结束;上游中途停止时以错误结束,连接随之中断, +/// 客户端不会把残缺的流当成完整回复。 +fn live_response( + owner: crate::connection::ModelConnection, + reply: pc_gateway_transport::LiveResponse, + first: bytes::Bytes, +) -> Response { + let content_type = header::HeaderValue::from_str(reply.content_type().unwrap_or_default()) + .unwrap_or(header::HeaderValue::from_static("text/event-stream")); + let mut response = ( + StatusCode::OK, + [(header::CONTENT_TYPE, content_type)], + axum::body::Body::new(LiveBody { + first: Some(first), + reply, + framer: Default::default(), + owner, + ended: false, + }), + ) + .into_response(); + response.extensions_mut().insert(ModelContent); + response.extensions_mut().insert(LiveContent); + response +} + +/// Marks a response whose body is forwarded while it arrives, so its first model content is located +/// in the frames as they pass. +#[derive(Clone, Copy)] +pub(crate) struct LiveContent; + +struct LiveBody { + first: Option, + reply: pc_gateway_transport::LiveResponse, + framer: pc_gateway_protocol::SseFramer, + owner: crate::connection::ModelConnection, + ended: bool, +} + +impl http_body::Body for LiveBody { + type Data = bytes::Bytes; + type Error = std::io::Error; + + fn poll_frame( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll, Self::Error>>> { + use std::task::Poll; + if self.ended { + return Poll::Ready(None); + } + let chunk = match self.first.take() { + Some(first) => Some(first), + None => match self.reply.poll_next(cx) { + Poll::Ready(chunk) => chunk, + Poll::Pending => return Poll::Pending, + }, + }; + let Some(chunk) = chunk else { + self.ended = true; + if !self.reply.complete() { + return Poll::Ready(Some(Err(std::io::Error::other( + "upstream response ended before completion", + )))); + } + self.owner.reply_complete(); + return Poll::Ready(None); + }; + // A client may close as soon as it reads the protocol end; from here on that is not a cancellation. + self.framer.push(&chunk); + if self + .framer + .take_events() + .iter() + .any(|event| event.data.as_ref() == b"[DONE]") + { + self.owner.reply_complete(); + } + Poll::Ready(Some(Ok(http_body::Frame::data(chunk)))) + } +} + /// 流式 Responses 客户端:把放行(或允许降级直通)后的完整响应重放为 Responses SSE 事件。 /// 非 200 或无法解析的结果按普通 JSON 返回,错误状态码不被包装成流; /// 降级直通的流保留 `x-pc-degraded` 头。 diff --git a/gateway/crates/pc-gateway-app/tests/live_streaming.rs b/gateway/crates/pc-gateway-app/tests/live_streaming.rs new file mode 100644 index 0000000000..6c54f478e4 --- /dev/null +++ b/gateway/crates/pc-gateway-app/tests/live_streaming.rs @@ -0,0 +1,503 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Forwarding a streamed Chat reply while it arrives, through the actual binary, a loopback Core +//! and a provider whose response body the test writes step by step. + +use axum::{extract::State, routing::post, Json, Router}; +use serde_json::{json, Value}; +use std::{ + process::{Child, Command, Stdio}, + sync::{Arc, Mutex}, + time::Duration, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + sync::mpsc, +}; + +#[path = "support/gateway_process.rs"] +mod gateway_process; +use gateway_process::GatewayFiles; + +const ROLE: &str = "data: {\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\"}}]}\n\n"; +const TEXT: &str = "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"forwarded\"}}]}\n\n"; +const STOP: &str = + "data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n"; +const DONE: &str = "data: [DONE]\n\n"; + +/// What the provider does next with the one response it is writing. +enum Step { + Head(u16, &'static str), + Chunk(&'static str), + End, + Abort, +} + +struct Core { + early_release: bool, + capture_delay: Duration, + checks: Mutex>, + captures: Mutex>, +} + +async fn check(State(core): State>, Json(request): Json) -> Json { + let phase = request["phase"].as_str().unwrap().to_owned(); + core.checks.lock().unwrap().push(request); + let mut verdict = json!({ + "schema": "powercontext.context-check.v1", "phase": phase, "decision": "allow", + "reason_codes": [], "coverage": {"profile": "text-and-tools.v1", "complete": true}, + "policy_version": "test", "valid_until": "2999-01-01T00:00:00Z", + "binding": format!("test-{phase}") + }); + if core.early_release && phase == "before_send" { + verdict["early_release"] = json!(true); + } + Json(verdict) +} + +async fn capture(State(core): State>, Json(request): Json) -> Json { + tokio::time::sleep(core.capture_delay).await; + core.captures.lock().unwrap().push(request); + Json(json!({})) +} + +struct Gateway { + child: Child, + servers: Vec>, + core: Arc, + provider: mpsc::UnboundedSender, + client: reqwest::Client, + base: String, + files: GatewayFiles, +} + +impl Drop for Gateway { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + for server in &self.servers { + server.abort(); + } + } +} + +impl Gateway { + async fn start(early_release: bool, enforcing: bool, capture_delay: Duration) -> Self { + let core = Arc::new(Core { + early_release, + capture_delay, + checks: Mutex::default(), + captures: Mutex::default(), + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let core_base = format!("http://{}", listener.local_addr().unwrap()); + let router = Router::new() + .route("/v1/context/check", post(check)) + .route("/v1/sources/content/batch", post(capture)) + .route( + "/v1/capabilities", + axum::routing::get(move || async move { + Json(json!({"context_protection": { + "check_versions": ["powercontext.context-check.v1"], + "payload_versions": ["powercontext.model-json-payload.v1"], + "reuse_versions": [], "reuse_families": [], "enforcing": enforcing, + "limits": {"payload_bytes": 1_048_576, "binding_bytes": 8192, + "prepared_contexts": 16, "dependencies": 256, + "send_seconds": 60, "correlate_seconds": 300, "capture_batch_sources": 128} + }})) + }), + ) + .with_state(core.clone()); + let core_server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); + + // The provider answers one request, writing exactly the steps the test sends, when it sends them. + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let provider_base = format!("http://{}", listener.local_addr().unwrap()); + let (provider, mut steps) = mpsc::unbounded_channel(); + let provider_server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + let mut buffer = [0; 8192]; + loop { + let read = socket.read(&mut buffer).await.unwrap(); + request.extend_from_slice(&buffer[..read]); + let text = String::from_utf8_lossy(&request); + let Some(head) = text.find("\r\n\r\n") else { + continue; + }; + let length: usize = text[..head] + .lines() + .find_map(|line| { + line.to_ascii_lowercase() + .strip_prefix("content-length:")? + .trim() + .parse() + .ok() + }) + .unwrap(); + if request.len() >= head + 4 + length { + break; + } + } + while let Some(step) = steps.recv().await { + let written = match step { + Step::Head(status, content_type) => socket + .write_all( + format!( + "HTTP/1.1 {status} OK\r\nContent-Type: {content_type}\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n" + ) + .as_bytes(), + ) + .await, + Step::Chunk(text) => socket + .write_all(format!("{:x}\r\n{text}\r\n", text.len()).as_bytes()) + .await, + Step::End => socket.write_all(b"0\r\n\r\n").await, + Step::Abort => return, + }; + // A gateway that stopped the call has closed this connection. + if written.is_err() { + return; + } + } + }); + + let client = reqwest::Client::builder() + .no_proxy() + .timeout(Duration::from_secs(10)) + .build() + .unwrap(); + let files = GatewayFiles::new(); + let mut command = Command::new(env!("CARGO_BIN_EXE_pc-gateway")); + command + .env_clear() + .env("PC_GATEWAY_CORE_BASE", &core_base) + .env( + "PC_GATEWAY_UPSTREAM_URL_CHAT", + format!("{provider_base}/v1/chat/completions"), + ) + .env("PC_GATEWAY_UPSTREAM_API_KEY", "provider-test-key") + .env("PC_GATEWAY_API_KEY", "gateway-test-key") + .env("PC_GATEWAY_INJECTION", "off") + .env("PC_GATEWAY_STEERING", "off") + .env("PC_GATEWAY_PREFIX_EXTRACTION", "off") + .env("PC_GATEWAY_SEDIMENT", "on"); + files.configure(&mut command); + command.stdout(Stdio::from( + std::fs::File::create(files.path().join("stdout.jsonl")).unwrap(), + )); + let mut gateway = Self { + child: command.spawn().unwrap(), + servers: vec![core_server, provider_server], + core, + provider, + client, + base: String::new(), + files, + }; + let address = tokio::time::timeout(Duration::from_secs(10), async { + loop { + if let Some(address) = gateway.files.bound_address(&mut gateway.child) { + let probe = gateway + .client + .get(format!("http://{address}/healthz")) + .timeout(Duration::from_millis(250)) + .send() + .await; + if probe.is_ok_and(|response| response.status().is_success()) { + break address; + } + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .unwrap_or_else(|_| panic!("Gateway startup timed out:\n{}", gateway.files.read_log())); + gateway.base = format!("http://{address}/gateway/v1"); + gateway + } + + fn provide(&self, steps: impl IntoIterator) { + for step in steps { + self.provider.send(step).unwrap(); + } + } + + /// Send one streamed Chat turn; resolves when the gateway answers with response headers. + fn turn(&self) -> tokio::task::JoinHandle { + let request = self + .client + .post(format!("{}/chat/completions", self.base)) + .bearer_auth("gateway-test-key") + .header("X-PowerContext-Conversation-ID", "live-streaming-test") + .json(&json!({ + "model": "test-model", "stream": true, + "messages": [{"role": "user", "content": "say something"}] + })); + tokio::spawn(async move { request.send().await.unwrap() }) + } + + fn captures(&self) -> usize { + self.core.captures.lock().unwrap().len() + } + + fn release_checks(&self) -> usize { + let checks = self.core.checks.lock().unwrap(); + checks + .iter() + .filter(|check| check["phase"] == "before_release") + .count() + } + + /// The exported record of the only call this gateway served. + async fn call(&self) -> Value { + self.call_within(Duration::from_secs(5)).await + } + + async fn call_within(&self, limit: Duration) -> Value { + within(limit, "the call record is exported", || { + let log = std::fs::read_to_string(self.files.path().join("stdout.jsonl")).unwrap(); + log.lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .find(|record| record["event"] == "call") + .map(|record| record["evidence"].clone()) + }) + .await + } +} + +async fn eventually(what: &str, probe: impl FnMut() -> Option) -> T { + within(Duration::from_secs(5), what, probe).await +} + +async fn within(limit: Duration, what: &str, mut probe: impl FnMut() -> Option) -> T { + let deadline = std::time::Instant::now() + limit; + loop { + if let Some(found) = probe() { + return found; + } + assert!(std::time::Instant::now() < deadline, "timed out: {what}"); + tokio::time::sleep(Duration::from_millis(20)).await; + } +} + +/// Read body chunks until the text received so far ends with `end`. +async fn read_through(response: &mut reqwest::Response, received: &mut String, end: &str) { + while !received.ends_with(end) { + let chunk = tokio::time::timeout(Duration::from_secs(5), response.chunk()) + .await + .unwrap_or_else(|_| panic!("no further body after {received:?}")) + .unwrap() + .unwrap_or_else(|| panic!("body ended after {received:?}")); + received.push_str(std::str::from_utf8(&chunk).unwrap()); + } +} + +#[tokio::test] +async fn a_permitted_reply_reaches_the_client_while_the_provider_is_still_writing_it() { + let gateway = Gateway::start(true, false, Duration::ZERO).await; + let turn = gateway.turn(); + gateway.provide([ + Step::Head(200, "text/event-stream; charset=utf-8"), + Step::Chunk(ROLE), + Step::Chunk(TEXT), + ]); + let mut response = turn.await.unwrap(); + assert_eq!(response.status(), 200); + assert_eq!( + response.headers()["content-type"], + "text/event-stream; charset=utf-8" + ); + let mut received = String::new(); + read_through(&mut response, &mut received, TEXT).await; + // The provider has not finished: nothing can have been checked for release or captured yet. + assert_eq!(gateway.release_checks(), 0); + assert_eq!(gateway.captures(), 0); + + gateway.provide([Step::Chunk(STOP), Step::Chunk(DONE), Step::End]); + read_through(&mut response, &mut received, DONE).await; + assert!(response.chunk().await.unwrap().is_none()); + assert_eq!(received, [ROLE, TEXT, STOP, DONE].concat()); + + eventually("the turn is captured", || { + (gateway.captures() == 1).then_some(()) + }) + .await; + assert_eq!(gateway.release_checks(), 1); + let captured = gateway.core.captures.lock().unwrap()[0].to_string(); + assert!(captured.contains("say something") && captured.contains("forwarded")); + let call = gateway.call().await; + assert_eq!(call["early_release"], true); + assert_eq!(call["terminal"], "release_authorized"); +} + +#[tokio::test] +async fn nothing_is_released_early_without_the_permission_or_when_the_gateway_enforces_checks() { + for (early_release, enforcing) in [(false, false), (true, true)] { + let gateway = Gateway::start(early_release, enforcing, Duration::ZERO).await; + let mut turn = gateway.turn(); + gateway.provide([ + Step::Head(200, "text/event-stream"), + Step::Chunk(ROLE), + Step::Chunk(TEXT), + ]); + assert!( + tokio::time::timeout(Duration::from_millis(400), &mut turn) + .await + .is_err(), + "response started before the reply was complete ({early_release}, {enforcing})" + ); + gateway.provide([Step::Chunk(STOP), Step::Chunk(DONE), Step::End]); + let response = turn.await.unwrap(); + assert_eq!(response.status(), 200); + assert_eq!( + response.text().await.unwrap(), + [ROLE, TEXT, STOP, DONE].concat() + ); + assert_eq!(gateway.captures(), 1); + assert_eq!(gateway.call().await["early_release"], false); + } +} + +#[tokio::test] +async fn a_client_that_closes_at_the_end_of_the_reply_still_has_its_turn_captured() { + // Capture is slow enough that the client is certainly gone while it runs. + let gateway = Gateway::start(true, false, Duration::from_millis(300)).await; + let turn = gateway.turn(); + // The provider keeps its response open after the protocol end, as providers do for a moment. + gateway.provide([ + Step::Head(200, "text/event-stream"), + Step::Chunk(ROLE), + Step::Chunk(TEXT), + Step::Chunk(STOP), + Step::Chunk(DONE), + ]); + let mut response = turn.await.unwrap(); + let mut received = String::new(); + read_through(&mut response, &mut received, DONE).await; + drop(response); + tokio::time::sleep(Duration::from_millis(100)).await; + assert_eq!(gateway.captures(), 0); + + gateway.provide([Step::End]); + eventually("the turn is captured", || { + (gateway.captures() == 1).then_some(()) + }) + .await; + let call = gateway.call().await; + assert_eq!(call["terminal"], "release_authorized"); + assert!(call["interruption"].is_null()); +} + +#[tokio::test] +async fn a_capture_that_hangs_delays_neither_the_reply_nor_the_end_of_the_call() { + // Core never finishes storing the turn. + let gateway = Gateway::start(true, false, Duration::from_secs(120)).await; + let turn = gateway.turn(); + gateway.provide([ + Step::Head(200, "text/event-stream"), + Step::Chunk(ROLE), + Step::Chunk(TEXT), + Step::Chunk(STOP), + Step::Chunk(DONE), + Step::End, + ]); + let sent = std::time::Instant::now(); + let response = turn.await.unwrap(); + assert_eq!( + response.text().await.unwrap(), + [ROLE, TEXT, STOP, DONE].concat() + ); + assert!(sent.elapsed() < Duration::from_secs(3)); + // The work left after the reply is bounded: the call ends although the capture never returned. + let call = gateway.call_within(Duration::from_secs(20)).await; + assert_eq!(call["sending"], "response_received"); + assert_eq!(call["early_release"], true); + assert_eq!(gateway.captures(), 0); +} + +#[tokio::test] +async fn a_client_that_leaves_during_the_reply_cancels_the_call() { + let gateway = Gateway::start(true, false, Duration::ZERO).await; + let turn = gateway.turn(); + gateway.provide([ + Step::Head(200, "text/event-stream"), + Step::Chunk(ROLE), + Step::Chunk(TEXT), + ]); + let mut response = turn.await.unwrap(); + let mut received = String::new(); + read_through(&mut response, &mut received, TEXT).await; + drop(response); + + let call = gateway.call().await; + assert_eq!(call["terminal"], json!({"stopped": "request_cancelled"})); + assert_eq!(call["early_release"], true); + gateway.provide([Step::Chunk(STOP), Step::Chunk(DONE), Step::End]); + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!(gateway.release_checks(), 0); + assert_eq!(gateway.captures(), 0); +} + +#[tokio::test] +async fn a_provider_that_stops_during_the_reply_fails_the_client_stream() { + let gateway = Gateway::start(true, false, Duration::ZERO).await; + let turn = gateway.turn(); + gateway.provide([ + Step::Head(200, "text/event-stream"), + Step::Chunk(ROLE), + Step::Chunk(TEXT), + ]); + let mut response = turn.await.unwrap(); + let mut received = String::new(); + read_through(&mut response, &mut received, TEXT).await; + + gateway.provide([Step::Abort]); + // The stream must not end cleanly: a client would take the partial reply for the whole one. + let rest = tokio::time::timeout(Duration::from_secs(5), async { + loop { + match response.chunk().await { + Ok(Some(_)) => continue, + other => break other, + } + } + }) + .await + .unwrap(); + assert!(rest.is_err(), "partial reply ended as a complete body"); + let call = gateway.call().await; + assert_ne!(call["terminal"], "release_authorized"); + assert_eq!(gateway.captures(), 0); +} + +#[tokio::test] +async fn a_provider_error_is_returned_whole_even_when_early_release_is_permitted() { + let gateway = Gateway::start(true, false, Duration::ZERO).await; + let turn = gateway.turn(); + gateway.provide([ + Step::Head(429, "application/json"), + Step::Chunk("{\"error\":{\"message\":\"slow down\"}}"), + Step::End, + ]); + let response = turn.await.unwrap(); + assert_eq!(response.status(), 429); + assert_eq!( + response.text().await.unwrap(), + "{\"error\":{\"message\":\"slow down\"}}" + ); + assert_eq!(gateway.release_checks(), 1); + assert_eq!(gateway.captures(), 0); + assert_eq!(gateway.call().await["early_release"], false); +} diff --git a/gateway/crates/pc-gateway-core/src/evidence.rs b/gateway/crates/pc-gateway-core/src/evidence.rs index 3798a264a6..9d5c22b4f9 100644 --- a/gateway/crates/pc-gateway-core/src/evidence.rs +++ b/gateway/crates/pc-gateway-core/src/evidence.rs @@ -18,7 +18,7 @@ use pc_gateway_evidence::{ fingerprint, AttemptEvidence, AttemptOutcome, CallEvidence, EvidenceSink, Interruption, Sending, Terminal, UsageEvidence, UsageMapping, }; -use pc_gateway_transport::{NotSentReason, RawResponse, SendIndeterminateReason}; +use pc_gateway_transport::{LiveProgress, NotSentReason, RawResponse, SendIndeterminateReason}; use std::time::Instant; pub(crate) struct CallRecorder<'a> { @@ -27,6 +27,7 @@ pub(crate) struct CallRecorder<'a> { cancellation: RequestCancellation, call: CallEvidence, attempt: Option<(AttemptEvidence, Instant)>, + live: Option, } impl<'a> CallRecorder<'a> { @@ -52,6 +53,7 @@ impl<'a> CallRecorder<'a> { cancellation, call, attempt: None, + live: None, } } @@ -149,6 +151,10 @@ impl<'a> CallRecorder<'a> { pub(crate) fn prepare_failed(&mut self) { self.sink.record_not_sent(0, "prepare_failed"); } + /// 这次调用的响应出口;销毁时据此记录是否提前交付过内容,执行中途被丢弃时也一样。 + pub(crate) fn live(&mut self, progress: LiveProgress) { + self.live = Some(progress); + } pub(crate) fn authorized(&mut self) { self.call.release_authorized_ms = Some(self.observation.elapsed_ms()); } @@ -177,6 +183,7 @@ impl Drop for CallRecorder<'_> { Interruption::FutureDropped }); } + self.call.early_release = self.live.as_ref().is_some_and(LiveProgress::forwarded); self.call.duration_ms = self.observation.elapsed_ms(); self.sink.record_call(&self.call); } diff --git a/gateway/crates/pc-gateway-core/src/executor.rs b/gateway/crates/pc-gateway-core/src/executor.rs index 64439719cf..c3bec017a3 100644 --- a/gateway/crates/pc-gateway-core/src/executor.rs +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -86,6 +86,9 @@ pub struct ManagedCall { /// The host marked this request as a non-turn (`X-PowerContext-Turn: internal`). pub internal: bool, pub prepared_contexts: Vec, + /// 调用方能在响应到达时接收它的出口。只有 Core 对这次请求许可提前交付时才会用到;用到时,返回的 + /// [`ManagedOutcome`] 说明放行记录与沉淀的结果,响应正文已经从这个出口交付。 + pub live: Option, } /// 执行结果。 @@ -210,6 +213,8 @@ struct Admission { /// 截止时间(Unix 毫秒)。解析失败 = 0 = 立即过期(fail-closed, /// 不能因无法解析就当作没有截止时间照常发送)。 valid_until_ms: u64, + /// Core 许可在响应到达时就把它交给调用方。 + early_release: bool, } impl Executor @@ -321,6 +326,11 @@ where self } + /// Core 的许可只在本进程确认 Core 不强制检查响应时生效:强制模式下任何内容都要先过 before_release。 + fn early_release(&self, result: &ContextCheckResult) -> bool { + result.early_release && !self.require_privacy_coverage + } + /// 进程内累计的回合类型判定与跳过准备次数。 pub fn turn_counters(&self) -> TurnCounterSnapshot { self.turn_counters.snapshot() @@ -486,6 +496,7 @@ where ) => { // P1-3:降级时丢弃已注入的载荷,用 pristine 请求重新渲染。 let mut degraded_call = ManagedCall { + live: None, scope_id: call.scope_id.clone(), target_profile: call.target_profile.clone(), request: pristine_request.clone(), @@ -522,6 +533,7 @@ where Ok((binding, deadline)) => Admission { binding, valid_until_ms: deadline, + early_release: self.early_release(&result), }, Err(outcome) => return outcome, }, @@ -558,6 +570,11 @@ where }; // P1-4:发送阶段。每次尝试前验有效期;确定性失败后重新走 check 拿新准入。 + // 响应出口只活到发送阶段结束:它销毁后调用方的响应随即结束,放行记录与沉淀在那之后完成。 + let live = call.live.take().filter(|_| call.request.stream); + if let Some(live) = &live { + recording.live(live.progress()); + } let raw = { let mut current = admission; let mut attempt: u32 = 0; @@ -571,7 +588,9 @@ where if now_ms() >= current.valid_until_ms { return ManagedOutcome::AdmissionExpired; } + // 提前交付的许可属于这一次准入;重试拿到的新准入各自决定。 let send = AdmittedSend { + live: live.clone().filter(|_| current.early_release), binding: current.binding.clone(), payload: payload.bytes.clone(), target_url: call.target_url.clone(), @@ -636,6 +655,7 @@ where current = Admission { binding, valid_until_ms: deadline, + early_release: self.early_release(&r), }; } Err(outcome) => return outcome, @@ -654,6 +674,7 @@ where } }; + drop(live); // 释放阶段。 if let Err(stop) = execution.checkpoint() { return stop; @@ -860,6 +881,7 @@ where CheckDecision::Block => { self.transport .cancel(&AdmittedSend { + live: None, binding: String::new(), payload: bytes::Bytes::new(), target_url: call.target_url.clone(), @@ -1173,6 +1195,7 @@ where }; } let send = AdmittedSend { + live: None, binding: "degraded-passthrough".into(), payload: payload.bytes, target_url: call.target_url.clone(), diff --git a/gateway/crates/pc-gateway-core/tests/executor_network_lifecycle.rs b/gateway/crates/pc-gateway-core/tests/executor_network_lifecycle.rs index a8d6e8fc1a..d54174002f 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_network_lifecycle.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_network_lifecycle.rs @@ -56,6 +56,7 @@ async fn check(State(state): State>, Json(request): Json) - fn call(base: &str) -> ManagedCall { ManagedCall { + live: None, scope_id: "test".into(), target_profile: "test".into(), request: CanonicalRequest { diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index c1fcb3701f..e11b65f99a 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -245,6 +245,7 @@ fn raw_response() -> SendOutcome { fn result(phase: CheckPhase, decision: CheckDecision, reasons: &[&str]) -> ContextCheckResult { ContextCheckResult { + early_release: false, schema: pc_gateway_types::CONTEXT_CHECK_SCHEMA.into(), phase, decision, @@ -262,6 +263,7 @@ fn result(phase: CheckPhase, decision: CheckDecision, reasons: &[&str]) -> Conte fn call(degrade: DegradePolicy) -> ManagedCall { ManagedCall { + live: None, scope_id: "project:test".into(), target_profile: "openai:test".into(), request: CanonicalRequest { @@ -1800,6 +1802,7 @@ async fn expired_send_verdict_never_sends() { // reviewer 探针:valid_until 已过期 → 不发送(P1-4)。 let (executor, renderer, transport, _gate) = harness( vec![Ok(ContextCheckResult { + early_release: false, valid_until: "2000-01-01T00:00:00Z".into(), // 已过期 ..result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]) })], @@ -1868,6 +1871,7 @@ async fn release_expired_after_capture_withholds() { vec![ Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), Ok(ContextCheckResult { + early_release: false, valid_until: "2000-01-01T00:00:00Z".into(), // release 过期 ..result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[]) }), @@ -1899,6 +1903,7 @@ async fn empty_valid_until_never_sends() { // parse_rfc3339_ms("") → None → unwrap_or(0) → now >= 0 → AdmissionExpired。 let (executor, renderer, transport, _gate) = harness( vec![Ok(ContextCheckResult { + early_release: false, valid_until: "".into(), // 空字符串 = Core 侧字段缺失或被中间层改写 ..result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]) })], @@ -1926,6 +1931,7 @@ async fn malformed_valid_until_never_sends() { for bad in ["2026-10-28 09:55:06+00:00", "not-a-date", "@@@"] { let (executor, renderer, transport, _gate) = harness( vec![Ok(ContextCheckResult { + early_release: false, valid_until: bad.into(), ..result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]) })], @@ -1965,6 +1971,7 @@ async fn capture_duration_expires_deadline_withholds_release() { // 我们模拟:valid_until = now(恰好等于 now,check 时 now >= deadline 为 false, // capture 后 now >= deadline 为 true——由于时间流逝)。 Ok(ContextCheckResult { + early_release: false, valid_until: chrono_now_rfc3339_plus_ms(0), // 立即过期 ..result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[]) }), @@ -2156,6 +2163,7 @@ async fn allow_with_incomplete_coverage_pauses() { // Without an explicit non-enforcing configuration, incomplete coverage pauses. let (executor, renderer, transport, _gate) = harness( vec![Ok(ContextCheckResult { + early_release: false, coverage: pc_gateway_types::ContextCheckCoverage { profile: "text-and-tools.v1".into(), complete: false, // ← 不完整覆盖 @@ -2185,6 +2193,7 @@ async fn allow_without_binding_pauses() { // allow 但 binding 为空 → 畸形 → 必须暂停(不得用 missing-binding 替代)。 let (executor, renderer, transport, _gate) = harness( vec![Ok(ContextCheckResult { + early_release: false, binding: None, // ← 缺失许可凭证 ..result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]) })], @@ -2238,6 +2247,7 @@ async fn allow_with_wrong_schema_pauses() { // schema 不是 powercontext.context-check.v1 → 畸形对端。 let (executor, renderer, transport, _gate) = harness( vec![Ok(ContextCheckResult { + early_release: false, schema: "evil-schema-v99".into(), ..result(CheckPhase::BeforeSend, CheckDecision::Allow, &[]) })], @@ -2266,6 +2276,7 @@ async fn release_allow_with_incomplete_coverage_pauses() { vec![ Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), Ok(ContextCheckResult { + early_release: false, coverage: pc_gateway_types::ContextCheckCoverage { profile: "text-and-tools.v1".into(), complete: false, @@ -3489,6 +3500,7 @@ fn allow_runs_with_fresh_release_bindings(n: usize) -> Vec { @@ -143,6 +147,16 @@ impl Transport for ReqwestTransport { let mut body: Vec = Vec::with_capacity(16 * 1024); let mut first_byte: Option = None; let mut stream = resp.bytes_stream(); + // 调用方拿到的必须就是上游的字节:非 200、非 SSE 或要转换的响应不提前交付。 + let live = live.filter(|_| { + status == 200 + && !converts_response + && content_type + .split(';') + .next() + .is_some_and(|mime| mime.trim().eq_ignore_ascii_case("text/event-stream")) + }); + let mut overflowed = false; loop { match next_chunk(&mut stream).await { None => break, @@ -157,18 +171,41 @@ impl Transport for ReqwestTransport { if !chunk.is_empty() && first_byte.is_none() { first_byte = Some(start.elapsed().as_millis() as u64); } - if chunk.len() > self.max_buffer_bytes.saturating_sub(body.len()) { - // 已送达且部分计费:不重发,向上标记不确定。 - return SendOutcome::IncompleteResponse { - reason: SendIndeterminateReason::BufferLimitExceeded, - status, - response_first_byte_ms: first_byte, - }; + if !overflowed + && chunk.len() > self.max_buffer_bytes.saturating_sub(body.len()) + { + if live.is_none() { + // 已送达且部分计费:不重发,向上标记不确定。 + return SendOutcome::IncompleteResponse { + reason: SendIndeterminateReason::BufferLimitExceeded, + status, + response_first_byte_ms: first_byte, + }; + } + // 调用方已经收到前面的内容:继续交付到上游结束,只是不再缓冲,这次发送仍按超限返回。 + overflowed = true; + body = Vec::new(); + } + if !overflowed { + body.extend_from_slice(&chunk); + } + if let Some(live) = &live { + live.forward(&content_type, chunk).await; } - body.extend_from_slice(&chunk); } } } + // 上游正文到此完整结束,接收端据此结束对调用方的响应。 + if let Some(live) = live { + live.complete(); + } + if overflowed { + return SendOutcome::IncompleteResponse { + reason: SendIndeterminateReason::BufferLimitExceeded, + status, + response_first_byte_ms: first_byte, + }; + } let complete_ms = start.elapsed().as_millis() as u64; let upstream_body = Bytes::from(body); let mut upstream_type = content_type.clone(); diff --git a/gateway/crates/pc-gateway-transport/src/sender.rs b/gateway/crates/pc-gateway-transport/src/sender.rs index 0587a7fcbe..4f0bc76c87 100644 --- a/gateway/crates/pc-gateway-transport/src/sender.rs +++ b/gateway/crates/pc-gateway-transport/src/sender.rs @@ -14,6 +14,101 @@ use bytes::Bytes; use std::future::Future; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, OnceLock}; +use std::task::{Context, Poll}; +use tokio::sync::mpsc; + +/// 一次发送里最多有这么多块响应正文在等调用方取走;取走之前传输器不再读上游。 +const LIVE_CHUNKS: usize = 16; + +/// 把响应正文在到达时交给调用方的出口。只有 Core 在 before_send 许可提前交付时,执行器才把它放进 +/// [`AdmittedSend`]。传输器只转发原样交付的 200 SSE 响应;其他响应仍然只随 [`SendOutcome`] 整体返回。 +#[derive(Debug, Clone)] +pub struct LiveOutput { + chunks: mpsc::Sender, + shared: Arc, +} + +/// [`LiveOutput`] 的接收端。所有出口都销毁后,取完剩余的块即结束;[`LiveResponse::complete`] 区分上游正文 +/// 完整结束与中途停止。 +#[derive(Debug)] +pub struct LiveResponse { + chunks: mpsc::Receiver, + shared: Arc, +} + +#[derive(Debug, Default)] +struct LiveShared { + content_type: OnceLock, + complete: AtomicBool, +} + +impl LiveOutput { + pub fn channel() -> (Self, LiveResponse) { + let (sender, receiver) = mpsc::channel(LIVE_CHUNKS); + let shared = Arc::new(LiveShared::default()); + ( + Self { + chunks: sender, + shared: shared.clone(), + }, + LiveResponse { + chunks: receiver, + shared, + }, + ) + } + + /// 不占用出口的观察句柄:出口都销毁后仍能回答是否交出过内容。 + pub fn progress(&self) -> LiveProgress { + LiveProgress(self.shared.clone()) + } + + /// 上游正文已经完整读完,交出的块就是全部响应。 + pub fn complete(self) { + self.shared.complete.store(true, Ordering::Release); + } + + /// 交出一块响应正文,等到调用方有位置接收。调用方已经不再接收时直接返回,不算传输失败。 + pub async fn forward(&self, content_type: &str, chunk: Bytes) { + self.shared + .content_type + .get_or_init(|| content_type.to_owned()); + let _ = self.chunks.send(chunk).await; + } +} + +/// 一个 [`LiveOutput`] 的交付进度。 +#[derive(Debug, Clone)] +pub struct LiveProgress(Arc); + +impl LiveProgress { + /// 已经有响应正文从出口交给调用方。 + pub fn forwarded(&self) -> bool { + self.0.content_type.get().is_some() + } +} + +impl LiveResponse { + pub async fn next(&mut self) -> Option { + self.chunks.recv().await + } + + pub fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll> { + self.chunks.poll_recv(cx) + } + + /// 上游响应的 Content-Type;第一块到达之前为 `None`。 + pub fn content_type(&self) -> Option<&str> { + self.shared.content_type.get().map(String::as_str) + } + + /// 接收结束后调用:`false` 表示上游正文没有读完,已经取到的块不是完整响应。 + pub fn complete(&self) -> bool { + self.shared.complete.load(Ordering::Acquire) + } +} /// 一次已获准的发送。 #[derive(Debug, Clone)] @@ -28,6 +123,8 @@ pub struct AdmittedSend { pub headers: Vec<(String, String)>, /// 上游流式(SSE)接收:逐块读入并计量,strict 语义不变。 pub stream: bool, + /// Core 许可提前交付时的响应出口;`None` 时响应只整体返回。 + pub live: Option, } /// 原始响应 + 传输结果,交给 output/check 后才允许释放。 diff --git a/gateway/crates/pc-gateway-transport/tests/buffer_limit_nonstreaming.rs b/gateway/crates/pc-gateway-transport/tests/buffer_limit_nonstreaming.rs index 50d104eb03..d1310f34ff 100644 --- a/gateway/crates/pc-gateway-transport/tests/buffer_limit_nonstreaming.rs +++ b/gateway/crates/pc-gateway-transport/tests/buffer_limit_nonstreaming.rs @@ -48,6 +48,7 @@ async fn nonstreaming_response_over_buffer_limit_is_rejected() { let transport = ReqwestTransport::new(Duration::from_secs(10)).with_buffer_limit(16); let send = AdmittedSend { + live: None, binding: "b".into(), payload: bytes::Bytes::from_static(b"{}"), target_url: format!("http://127.0.0.1:{port}/v1/chat/completions"), @@ -91,6 +92,7 @@ async fn nonstreaming_response_within_limit_still_delivers() { let transport = ReqwestTransport::new(Duration::from_secs(10)).with_buffer_limit(1024); let send = AdmittedSend { + live: None, binding: "b".into(), payload: bytes::Bytes::from_static(b"{}"), target_url: format!("http://127.0.0.1:{port}/v1/chat/completions"), diff --git a/gateway/crates/pc-gateway-transport/tests/claude_cli.rs b/gateway/crates/pc-gateway-transport/tests/claude_cli.rs index 6f38ed27a9..fae04ae1c3 100644 --- a/gateway/crates/pc-gateway-transport/tests/claude_cli.rs +++ b/gateway/crates/pc-gateway-transport/tests/claude_cli.rs @@ -31,7 +31,7 @@ fn script(directory: &Path, body: &str) -> std::path::PathBuf { } fn admitted() -> AdmittedSend { - AdmittedSend {binding:"approved-prompt".into(),payload:serde_json::to_vec(&json!({ + AdmittedSend {live:None,binding:"approved-prompt".into(),payload:serde_json::to_vec(&json!({ "model":"sonnet","messages":[{"role":"user","content":"ordinary request"}],"stream":false })).unwrap().into(),target_url:"claude-cli://execute".into(),headers:vec![],stream:false} } diff --git a/gateway/crates/pc-gateway-transport/tests/codeassist.rs b/gateway/crates/pc-gateway-transport/tests/codeassist.rs index f5dd7dbe78..a60206f47b 100644 --- a/gateway/crates/pc-gateway-transport/tests/codeassist.rs +++ b/gateway/crates/pc-gateway-transport/tests/codeassist.rs @@ -39,6 +39,7 @@ async fn exchange(request: &Value, response: &Value, limit: usize) -> SendOutcom .with_codeassist_chat(true) .with_buffer_limit(limit) .send(AdmittedSend { + live: None, binding: "approved-final-codeassist-envelope".into(), payload: payload.into(), target_url: format!("http://{address}/v1internal:generateContent"), diff --git a/gateway/crates/pc-gateway-transport/tests/live_output.rs b/gateway/crates/pc-gateway-transport/tests/live_output.rs new file mode 100644 index 0000000000..4cc50254fa --- /dev/null +++ b/gateway/crates/pc-gateway-transport/tests/live_output.rs @@ -0,0 +1,122 @@ +// Copyright (c) 2026 OceanBase. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! A send that carries a live output hands over a streamed reply while buffering it as usual. + +use pc_gateway_transport::{ + AdmittedSend, LiveOutput, LiveResponse, ReqwestTransport, SendIndeterminateReason, SendOutcome, + Transport, +}; +use std::time::Duration; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; + +const REPLY: &str = + "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"one\"}}]}\n\ndata: [DONE]\n\n"; + +/// Send to a provider that answers with `status`, `content_type` and `body`, under a buffer limit. +async fn send( + status: u16, + content_type: &'static str, + body: &'static str, + limit: usize, +) -> (SendOutcome, LiveResponse) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut buffer = [0; 4096]; + assert!(socket.read(&mut buffer).await.unwrap() > 0); + let head = format!( + "HTTP/1.1 {status} OK\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + socket.write_all(head.as_bytes()).await.unwrap(); + for part in body.as_bytes().chunks(24) { + socket.write_all(part).await.unwrap(); + tokio::time::sleep(Duration::from_millis(5)).await; + } + }); + let (live, reply) = LiveOutput::channel(); + let outcome = ReqwestTransport::new(Duration::from_secs(5)) + .with_buffer_limit(limit) + .send(AdmittedSend { + binding: "test".into(), + payload: bytes::Bytes::from_static(b"{}"), + target_url: format!("http://{addr}/v1/chat/completions"), + headers: vec![], + stream: true, + live: Some(live), + }) + .await; + (outcome, reply) +} + +async fn forwarded(mut reply: LiveResponse) -> String { + let mut text = String::new(); + while let Some(chunk) = reply.next().await { + text.push_str(std::str::from_utf8(&chunk).unwrap()); + } + text +} + +#[tokio::test] +async fn a_streamed_reply_is_handed_over_and_still_returned_whole() { + let (outcome, reply) = send(200, "text/event-stream; charset=utf-8", REPLY, 4096).await; + let SendOutcome::Delivered(raw) = outcome else { + panic!("reply not delivered: {outcome:?}") + }; + assert_eq!(raw.body.as_ref(), REPLY.as_bytes()); + assert_eq!( + reply.content_type(), + Some("text/event-stream; charset=utf-8") + ); + assert!(reply.complete()); + assert_eq!(forwarded(reply).await, REPLY); +} + +#[tokio::test] +async fn a_reply_over_the_buffer_limit_is_handed_over_to_its_end_and_reported_over_limit() { + let (outcome, reply) = send(200, "text/event-stream", REPLY, 32).await; + assert!( + matches!( + outcome, + SendOutcome::IncompleteResponse { + reason: SendIndeterminateReason::BufferLimitExceeded, + status: 200, + .. + } + ), + "{outcome:?}" + ); + assert!(reply.complete()); + assert_eq!(forwarded(reply).await, REPLY); +} + +#[tokio::test] +async fn errors_and_replies_that_are_not_event_streams_are_only_returned_whole() { + for (status, content_type) in [ + (200, "application/json"), + (429, "text/event-stream"), + (201, "text/event-stream"), + ] { + let (outcome, reply) = send(status, content_type, REPLY, 4096).await; + let SendOutcome::Delivered(raw) = outcome else { + panic!("reply not delivered: {outcome:?}") + }; + assert_eq!((raw.status, raw.body.as_ref()), (status, REPLY.as_bytes())); + assert!(!reply.complete()); + assert_eq!(forwarded(reply).await, ""); + } +} diff --git a/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs b/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs index 48ed9a8465..d33c3e3456 100644 --- a/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs +++ b/gateway/crates/pc-gateway-transport/tests/no_duplicate_send.rs @@ -74,6 +74,7 @@ async fn upstream_closing_after_full_body_is_indeterminate_and_not_resent() { let transport = ReqwestTransport::default(); let send = AdmittedSend { + live: None, binding: "b".into(), payload: bytes::Bytes::from_static(br#"{"model":"m","messages":[]}"#), target_url: format!("http://127.0.0.1:{port}/v1/chat/completions"), diff --git a/gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs b/gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs index 5baf3229dd..8303aaf88a 100644 --- a/gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs +++ b/gateway/crates/pc-gateway-transport/tests/no_redirect_resend.rs @@ -82,6 +82,7 @@ async fn redirect_target_receives_nothing_and_307_surfaces() { let transport = ReqwestTransport::default(); let send = AdmittedSend { + live: None, binding: "b".into(), payload: bytes::Bytes::from_static(br#"{"model":"m","messages":[]}"#), target_url: format!("http://127.0.0.1:{approved_port}/v1/chat/completions"), diff --git a/gateway/crates/pc-gateway-transport/tests/subscription_response.rs b/gateway/crates/pc-gateway-transport/tests/subscription_response.rs index fe95eedb34..16e55f7725 100644 --- a/gateway/crates/pc-gateway-transport/tests/subscription_response.rs +++ b/gateway/crates/pc-gateway-transport/tests/subscription_response.rs @@ -55,6 +55,7 @@ async fn send(body: String, content_type: Option<&str>) -> SendOutcome { let result = ReqwestTransport::default() .with_subscription_responses_sse(true) .send(AdmittedSend { + live: None, binding: "admission".into(), payload: bytes::Bytes::from_static(b"{}"), target_url: format!("http://{address}/responses"), diff --git a/gateway/crates/pc-gateway-transport/tests/usage_timing.rs b/gateway/crates/pc-gateway-transport/tests/usage_timing.rs index dc0eb6a1e6..f62e54706c 100644 --- a/gateway/crates/pc-gateway-transport/tests/usage_timing.rs +++ b/gateway/crates/pc-gateway-transport/tests/usage_timing.rs @@ -39,6 +39,7 @@ async fn response( let transport = ReqwestTransport::new(Duration::from_secs(5)); let outcome = transport .send(AdmittedSend { + live: None, binding: "test".into(), payload: bytes::Bytes::from_static(b"{}"), target_url: format!("http://{addr}/v1/responses"), @@ -172,6 +173,7 @@ async fn body_read_timeouts_and_truncations_keep_distinct_reasons() { let transport = ReqwestTransport::new(Duration::from_millis(100)); let outcome = transport .send(AdmittedSend { + live: None, binding: "fixture".into(), payload: bytes::Bytes::from_static(b"{}"), target_url: format!("http://{address}/provider"), diff --git a/gateway/crates/pc-gateway-types/src/check.rs b/gateway/crates/pc-gateway-types/src/check.rs index 8975cf6e61..75a55e567b 100644 --- a/gateway/crates/pc-gateway-types/src/check.rs +++ b/gateway/crates/pc-gateway-types/src/check.rs @@ -133,6 +133,10 @@ pub struct ContextCheckResult { /// 仅 allow 有:不透明绑定字符串。 #[serde(default, skip_serializing_if = "Option::is_none")] pub binding: Option, + /// 仅保护模式为 disabled 时的 before_send allow 为 true:许可执行器在这次请求的响应到达时就把它转发给 + /// 调用方。完整响应仍要用这次请求的 binding 过 before_release。 + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub early_release: bool, } #[derive(Debug, Clone, Serialize, Deserialize)] From 084c7f8fc4c09c30b1279716bd130ca03cee26d1 Mon Sep 17 00:00:00 2001 From: jasper-yl Date: Thu, 3 Dec 2026 20:51:08 -0800 Subject: [PATCH 3/4] test(desktop): qualify the early release contract The native probe selected sqlite-early-release-16e1cb20-v1 against the SQLite Server wheel built from 16e1cb206 and passed the anonymous loopback, static Bearer, HTTPS with base path, and Provider modes. Co-Authored-By: Claude --- .../src/connections/compatibility.json | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index 9b62df722a..24434bf859 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -2043,5 +2043,26 @@ "remember_memory", "search_memory" ] + }, + { + "id": "sqlite-early-release-16e1cb20-v1", + "serverCommit": "16e1cb206c45b4236136014b4f67e55415baa9e2", + "contractSha256": "8b3411dec4247dc8d7f971fc242a32991fa1600085a06c28395fcb9edb2a289e", + "artifactSha256": "c5abe9842e9539758ddf8abfe66fb6f0c0cc9e885a7a47149197baddb27e7dbe", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ] } ] From 96738a436d3695395cdd0d2314fe5b3d747ff6e1 Mon Sep 17 00:00:00 2001 From: jasper-yl Date: Fri, 4 Dec 2026 09:40:38 -0800 Subject: [PATCH 4/4] fix(gateway): find the end of a forwarded reply without retaining its events The live response body used the SSE framer to notice `data: [DONE]`. The framer keeps every byte until an event ends, and a forwarded reply is not limited by the response buffer, so one large or unterminated event grew that buffer with the reply. The body now scans lines with a fixed-size state. Co-Authored-By: Claude --- gateway/crates/pc-gateway-app/src/ingress.rs | 83 +++++++++++++++++-- .../pc-gateway-app/tests/live_streaming.rs | 34 ++++++++ 2 files changed, 108 insertions(+), 9 deletions(-) diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index e59649ef20..4e98ab4a47 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -871,7 +871,7 @@ fn live_response( axum::body::Body::new(LiveBody { first: Some(first), reply, - framer: Default::default(), + end: Default::default(), owner, ended: false, }), @@ -890,11 +890,58 @@ pub(crate) struct LiveContent; struct LiveBody { first: Option, reply: pc_gateway_transport::LiveResponse, - framer: pc_gateway_protocol::SseFramer, + end: ChatStreamEnd, owner: crate::connection::ModelConnection, ended: bool, } +/// Finds the `[DONE]` event of a Chat Completions stream in the bytes as they pass. It keeps the +/// start of the current line only, so an event of any size costs it nothing. +#[derive(Default)] +struct ChatStreamEnd { + line: Vec, + long_line: bool, + done: bool, + other_data: bool, +} + +impl ChatStreamEnd { + /// Longer than `data: [DONE]` with a carriage return; a longer line is not the marker. + const LINE: usize = 16; + + /// True once a complete event whose data is exactly `[DONE]` has passed. + fn passed(&mut self, chunk: &[u8]) -> bool { + let mut passed = false; + for &byte in chunk { + if byte != b'\n' { + if self.line.len() < Self::LINE { + self.line.push(byte); + } else { + self.long_line = true; + } + continue; + } + let line = self.line.strip_suffix(b"\r").unwrap_or(&self.line); + if self.long_line { + self.other_data = true; + } else if line.is_empty() { + passed |= self.done && !self.other_data; + self.done = false; + self.other_data = false; + } else if let Some(data) = line.strip_prefix(b"data:") { + if data.strip_prefix(b" ").unwrap_or(data) == b"[DONE]" { + self.done = true; + } else { + self.other_data = true; + } + } + self.line.clear(); + self.long_line = false; + } + passed + } +} + impl http_body::Body for LiveBody { type Data = bytes::Bytes; type Error = std::io::Error; @@ -925,13 +972,7 @@ impl http_body::Body for LiveBody { return Poll::Ready(None); }; // A client may close as soon as it reads the protocol end; from here on that is not a cancellation. - self.framer.push(&chunk); - if self - .framer - .take_events() - .iter() - .any(|event| event.data.as_ref() == b"[DONE]") - { + if self.end.passed(&chunk) { self.owner.reply_complete(); } Poll::Ready(Some(Ok(http_body::Frame::data(chunk)))) @@ -1859,6 +1900,30 @@ pub(crate) mod tests { pub release: tokio::sync::Notify, } + #[test] + fn the_end_of_a_chat_stream_is_its_done_event_however_the_bytes_are_split() { + let passes = |chunks: &[&[u8]]| { + let mut end = ChatStreamEnd::default(); + chunks.iter().filter(|chunk| end.passed(chunk)).count() > 0 + }; + assert!(passes(&[b"data: {\"a\":1}\n\ndata: [DONE]\n\n"])); + assert!(passes(&[ + b"data: {\"a\":1}\r\n\r\nda", + b"ta:[DO", + b"NE]\r\n", + b"\r\n" + ])); + let long = [b"data: ".as_slice(), &vec![b'x'; 4096], b"\n\n"].concat(); + assert!(passes(&[&long, b"data: [DONE]\n\n"])); + // The event is not over until its blank line, and `[DONE]` inside other data is content. + assert!(!passes(&[b"data: [DONE]\n"])); + assert!(!passes(&[ + b"data: {\"content\":\"\\n\\ndata: [DONE]\\n\\n\"}\n\n" + ])); + assert!(!passes(&[b"data: [DONE]\ndata: more\n\n"])); + assert!(!passes(&[&long[..long.len() - 2], b"\ndata: [DONE]\n\n"])); + } + #[tokio::test] async fn deterministic_withholds_are_bad_requests_and_preserve_reasons() { for reasons in [ diff --git a/gateway/crates/pc-gateway-app/tests/live_streaming.rs b/gateway/crates/pc-gateway-app/tests/live_streaming.rs index 6c54f478e4..584bd5a26e 100644 --- a/gateway/crates/pc-gateway-app/tests/live_streaming.rs +++ b/gateway/crates/pc-gateway-app/tests/live_streaming.rs @@ -401,6 +401,40 @@ async fn a_client_that_closes_at_the_end_of_the_reply_still_has_its_turn_capture assert!(call["interruption"].is_null()); } +#[tokio::test] +async fn a_reply_too_large_to_capture_still_ends_at_its_protocol_end() { + let gateway = Gateway::start(true, false, Duration::ZERO).await; + let turn = gateway.turn(); + // One event larger than the gateway's response buffer. + let large: &'static str = Box::leak( + format!( + "data: {{\"choices\":[{{\"index\":0,\"delta\":{{\"content\":\"{}\"}}}}]}}\n\n", + "x".repeat(2 * 1024 * 1024) + ) + .into_boxed_str(), + ); + gateway.provide([ + Step::Head(200, "text/event-stream"), + Step::Chunk(ROLE), + Step::Chunk(large), + Step::Chunk(STOP), + Step::Chunk(DONE), + ]); + let mut response = turn.await.unwrap(); + let mut received = String::new(); + read_through(&mut response, &mut received, DONE).await; + assert_eq!(received, [ROLE, large, STOP, DONE].concat()); + drop(response); + tokio::time::sleep(Duration::from_millis(100)).await; + + // The client left after the protocol end, so the call ends as an uncaptured reply, not a cancellation. + gateway.provide([Step::End]); + let call = gateway.call().await; + assert_eq!(call["terminal"], "withheld"); + assert!(call["interruption"].is_null()); + assert_eq!(gateway.captures(), 0); +} + #[tokio::test] async fn a_capture_that_hangs_delays_neither_the_reply_nor_the_end_of_the_call() { // Core never finishes storing the turn.