From bffc3980bbece93c86948b62f70446d90b08affb Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Fri, 6 Nov 2026 10:38:58 +0800 Subject: [PATCH 01/15] feat(gateway): export bounded call evidence --- docs/en/docs/operate/gateway-evidence.md | 130 ++++++ docs/en/docs/operate/meta.json | 1 + docs/en/docs/operate/observability.md | 3 + docs/zh/docs/operate/gateway-evidence.md | 124 +++++ docs/zh/docs/operate/meta.json | 1 + docs/zh/docs/operate/observability.md | 3 + gateway/README.md | 6 +- .../pc-gateway-app/src/evidence_body.rs | 101 +++++ gateway/crates/pc-gateway-app/src/ingress.rs | 172 ++++++- gateway/crates/pc-gateway-app/src/main.rs | 36 +- .../pc-gateway-app/tests/evidence_process.rs | 169 +++++++ .../crates/pc-gateway-core/src/evidence.rs | 173 +++++++ .../crates/pc-gateway-core/src/executor.rs | 77 +++- gateway/crates/pc-gateway-core/src/lib.rs | 2 + .../crates/pc-gateway-core/src/lifecycle.rs | 14 + .../tests/executor_semantics.rs | 427 +++++++++++++++++- gateway/crates/pc-gateway-evidence/src/lib.rs | 269 +++++++++-- .../crates/pc-gateway-evidence/src/output.rs | 142 ++++++ .../pc-gateway-evidence/tests/output.rs | 183 ++++++++ .../src/reqwest_transport.rs | 72 ++- .../crates/pc-gateway-transport/src/retry.rs | 6 +- .../crates/pc-gateway-transport/src/sender.rs | 12 +- .../tests/buffer_limit_nonstreaming.rs | 9 +- .../tests/usage_timing.rs | 95 ++++ 24 files changed, 2125 insertions(+), 102 deletions(-) create mode 100644 docs/en/docs/operate/gateway-evidence.md create mode 100644 docs/zh/docs/operate/gateway-evidence.md create mode 100644 gateway/crates/pc-gateway-app/src/evidence_body.rs create mode 100644 gateway/crates/pc-gateway-app/tests/evidence_process.rs create mode 100644 gateway/crates/pc-gateway-core/src/evidence.rs create mode 100644 gateway/crates/pc-gateway-evidence/src/output.rs create mode 100644 gateway/crates/pc-gateway-evidence/tests/output.rs create mode 100644 gateway/crates/pc-gateway-transport/tests/usage_timing.rs diff --git a/docs/en/docs/operate/gateway-evidence.md b/docs/en/docs/operate/gateway-evidence.md new file mode 100644 index 0000000000..e8e51313d5 --- /dev/null +++ b/docs/en/docs/operate/gateway-evidence.md @@ -0,0 +1,130 @@ +--- +title: Gateway call evidence +description: Read bounded, body-free Rust Gateway call, attempt, usage and HTTP-framework observations. +--- + +# Gateway call evidence + +The Rust Gateway exports `powercontext.gateway-evidence.v1` JSON lines on **stdout** by default. +Operational tracing goes to **stderr**. No external telemetry platform is required. Configure your existing +log collector's rotation and retention; redirecting stdout to a file does not bound that file's size. + +```bash +# Keep evidence separate from operational logs; use a collector with bounded retention. +./gateway/target/release/pc-gateway | your-existing-log-collector + +# Explicitly disable evidence. The startup diagnostic reports missing evidence coverage. +PC_GATEWAY_EVIDENCE=off ./gateway/target/release/pc-gateway +``` + +The application composes `JsonEvidenceSink`, not the unbounded `BufferedEvidenceSink` retained for tests/demos. +It keeps at most **1024 queued records plus one worker-owned record**. Each accepted record has bounded identifiers, +typed counts/enums and at most 4096 serialized bytes including the newline. Submission uses `try_send`: +when full, the new record is discarded. There is no request-side I/O, writer join or drain wait. +A stalled stdout can occupy the one exporter thread but cannot accumulate more threads or queue entries. +The rest of the Gateway still has its own request/response buffers and concurrency limits. + +Every readable line has `schema`, `operation=gateway.model_call`, `unit` (`call`, `attempt`, `delivery`), +`event` (the same three values), `evidence`, and `loss`. The process-local cumulative `loss.dropped`, +`loss.write_failed` and `loss.written` count discarded submissions, failed/unconfirmed record writes, and completed +write-and-flush operations respectively, sampled before that line's write. Recovered output reports earlier losses; +an embedding host can also read `JsonEvidenceSink.stats()` during congestion. No execution IDs are metric labels. +These are best-effort records: overflow can remove a call terminal or an attempt, a failed/partial write can corrupt +one line, and process exit can lose queued records. Readers should skip malformed/blank lines; after a write failure, +the exporter restores a newline boundary before the next record. Counters reset on restart. There is no replay or +billing/audit durability guarantee, and no financial reconciliation, token savings or task-success claim. +If the worker cannot start, the application reports a fixed diagnostic and uses Noop without changing business results. + +## Correlation and coverage + +`call_id` identifies one execution and joins its `call`, numbered `attempt`, and `delivery` records. +It is generated once in request control and reused through completion and response-body lifetime. +`request_id_fingerprint` is a keyed process-local fingerprint of the **bound** request ID, or null when none exists; +`target_fingerprint` fingerprints the actual transport URL, never the requested model or client-claimed target. +Redirects remain disabled. Fingerprints use a random process-local key and are not portable identities or a +cryptographic anonymization promise. They never export a raw URL, request ID, cache key, conversation ID, +Scope, provider error, model, credential, prompt or response body. Records do not establish task identity or +Source projection coverage. No task association is available unless the embedding host independently supplies it. + +Coverage starts when `Executor::run` is polled. Authentication, invalid-body, middleware rejection and other ingress +failures before execution are outside this stream. A complete model response does not imply successful release. +`attempts` counts actual transport handoffs, including a degraded send; an expired admission has zero attempts. +Retries keep one `call_id` and increment attempt numbers only after fresh admission. An uncertain attempt is never +retried. The legacy demo-only `record_not_sent(0, ...)` diagnostics for preparation/capture/degradation are not +exported and are not model-send facts. + +## Terminal and send facts + +The `call` record contains `terminal`, `sending`, `attempts`, `upstream_status`, normalized `usage`, optional +`interruption`, and timing fields. Terminal values are `release_authorized`, `blocked`, `withheld`, +`send_indeterminate`, `not_sent`, `gate_paused`, `degraded`, `admission_expired`, and `abandoned`. +`sending` independently reports `no_send`, `definitely_not_sent`, `possibly_sent`, or `response_received`. +A release refusal or expiry after a response preserves `response_received` and any reported usage. + +Pending execution future destruction emits `abandoned` and preserves sending facts. `interruption` reports +`cancellation_requested` if the shared cancellation signal was set, otherwise `deadline_elapsed` if the host deadline +has elapsed, otherwise `future_dropped`. These are observations at destruction, **not a claim about its cause**. +As in the shared G3-0 lifecycle, signaling cancellation or passing a deadline does not by itself interrupt execution; +the owner must stop/drop the future. Evidence adds no new cancellation authority or timer. +Cancellation during transport remains `possibly_sent`, with unknown usage, never `not_sent`. + +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`, +`lost_after_handoff`, `timeout_awaiting_response`, and `buffer_limit_exceeded`. A partial-response failure preserves +its observed status/first-byte timing but keeps completion and usage unknown. Once the transport reports delivery, +usage survives decoding/release failures. A dropped pending transport cannot provide its private partial observations. + +## Usage mapping + +`usage_mapping` is `open_ai_chat` or `open_ai_responses`, selected from the actual wire renderer, not the client model. An unrecognized renderer has null mapping and unknown usage. +Each of `usage.input`, `usage.output`, `usage.cache_read`, and `usage.cache_write` has `tokens` (nonnegative integer +or null) and `completeness` (`known`, `estimated`, `unknown`, `reconciled`). This implementation emits only +provider-reported `known` values or `unknown`; it performs no estimates or reconciliation. + +| Quantity | OpenAI Chat | OpenAI Responses | +| --- | --- | --- | +| Input | `usage.prompt_tokens` | `usage.input_tokens` | +| Output | `usage.completion_tokens` | `usage.output_tokens` | +| Cache read | `usage.prompt_tokens_details.cached_tokens` | `usage.input_tokens_details.cached_tokens` | +| Cache write | Unknown | Unknown | + +Input **includes** cached input: do not add cache reads to input or subtract them from the reported input field. +No Anthropic cache-creation/write fields are guessed into the OpenAI mapping. Missing, null, malformed or negative +counts remain unknown; a reported zero is known zero. `total_tokens` alone cannot establish input/output counts. +SSE uses an explicitly present usage object from a Chat usage chunk or Responses event's `response.usage`. +It retains the last such object, without summing cumulative chunks. Missing/malformed SSE usage remains unknown. +This does not expand the Core's accepted streaming protocols. + +## Timing and HTTP delivery + +All durations are monotonic milliseconds, truncated to integers. Null means unavailable. + +| Field/boundary | Meaning | +| --- | --- | +| Call `duration_ms` | Request-control creation to executor terminal/drop; includes ingress time after control creation | +| 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 | +| `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 | +| Delivery `elapsed_ms` | Request-control creation to the named framework observation | + +A `delivery` record reports `framework_handoff` when the released/degraded body is placed in the HTTP response, +`first_body_frame` when the framework first polls a nonempty data frame, `body_completed` when the wrapped body +reports completion, or `body_dropped` if dropped before observed completion. Strict release authorization precedes +framework handoff and content-frame observation. A degraded response has no release authorization timestamp. +No boundary proves a socket write, client receipt, rendering or adoption. The current host cannot observe actual +socket writes. Non-streaming Responses JSON's first byte and replayed SSE output are not provider TTFT. + +## Deployment and compatibility + +Collectors that previously consumed human tracing from stdout must move that input to stderr and parse evidence +stdout separately. No database migration, new HTTP endpoint, Python operational field or OpenAPI regeneration is +required. The JSON schema is separate from the Server's allowlisted Python log fields and existing exporters. +Custom embedding sinks must keep synchronous callbacks bounded, nonblocking and free of I/O; route blocking writers +through `JsonEvidenceSink` and keep one sink per host. Custom writers must return I/O errors without panicking. +Rust integrations consume the nested per-field `CallEvidence.usage` instead of the demo record's former flat token/completeness fields. There is no production record-store migration. They must replace `RawResponse.ttft_ms` with the explicit first-byte/completion fields and handle +`SendOutcome::IncompleteResponse` as indeterminate, preserving its progress and never retrying it. diff --git a/docs/en/docs/operate/meta.json b/docs/en/docs/operate/meta.json index 6e8650e669..9e22f64fe9 100644 --- a/docs/en/docs/operate/meta.json +++ b/docs/en/docs/operate/meta.json @@ -13,6 +13,7 @@ "context-protection", "atomic-memory-migration", "observability", + "gateway-evidence", "reference-observability-stack", "trace-with-phoenix", "trace-with-langfuse", diff --git a/docs/en/docs/operate/observability.md b/docs/en/docs/operate/observability.md index 1cd2c6244e..cc9528da11 100644 --- a/docs/en/docs/operate/observability.md +++ b/docs/en/docs/operate/observability.md @@ -580,3 +580,6 @@ Topic processing may report `invalid_topic_placeholder` for recognizable numbere identify recoverable generation rejection, not successful NOOP. Retries use the existing durable Window budget; exhaustion retains the pending frontier. Existing worker events and correlation fields carry the diagnostic code. Source text, generated bodies and provider responses must not be added to operational logs. + +Rust Gateway call/attempt/usage and HTTP-framework observations use a separate +[bounded evidence output](gateway-evidence.md); they do not add Python log fields or establish client receipt. diff --git a/docs/zh/docs/operate/gateway-evidence.md b/docs/zh/docs/operate/gateway-evidence.md new file mode 100644 index 0000000000..3de95510e9 --- /dev/null +++ b/docs/zh/docs/operate/gateway-evidence.md @@ -0,0 +1,124 @@ +--- +title: Gateway 调用证据 +description: 读取 Rust Gateway 有界、无正文的调用、尝试、usage 与 HTTP 框架观测。 +--- + +# Gateway 调用证据 + +Rust Gateway 默认向 **stdout** 输出 `powercontext.gateway-evidence.v1` JSON 行,运行日志使用 **stderr**。 +无需额外部署观测平台。沿用现有日志采集器的轮转与保留策略;仅将 stdout 重定向到文件不会限制文件大小。 + +```bash +# 将证据与运行日志分开;采集器应配置有界保留。 +./gateway/target/release/pc-gateway | your-existing-log-collector + +# 显式关闭证据。启动诊断会说明证据覆盖缺失。 +PC_GATEWAY_EVIDENCE=off ./gateway/target/release/pc-gateway +``` + +生产应用装配 `JsonEvidenceSink`,不再使用测试/演示保留的无界 `BufferedEvidenceSink`。 +最多保留 **1024 条排队记录和 1 条写出线程持有的记录**。接收的记录仅含有界标识符、数值和枚举, +序列化后每条含换行不超过 4096 字节。提交使用 `try_send`,队列满时丢弃新记录。 +请求侧不执行 I/O,也不等待写出线程退出或队列排空。stdout 卡住最多占用一个写出线程, +不会持续增加线程或队列条目。Gateway 的请求/响应缓冲与并发仍有各自的资源限制。 + +每行包含 `schema`、`operation=gateway.model_call`、`unit`(`call`、`attempt`、`delivery`)、 +`event`(同样的三个值)、`evidence` 和 `loss`。进程内累计的 `loss.dropped`、`loss.write_failed`、 +`loss.written` 分别统计被丢弃的提交、失败或无法确认的记录写出、完成写入并 flush 的记录, +采样发生在当前行写出之前。恢复后的输出会携带此前的丢失计数;嵌入宿主也能在拥塞时读取 +`JsonEvidenceSink.stats()`。执行身份不作为指标标签。 +这些记录是尽力输出:溢出可能丢掉终态或尝试记录,失败/部分写入可能损坏一行,进程退出可能丢掉队列内容。 +读取器应跳过畸形行和空行;写出失败后,exporter 会先补换行,再写下一条记录。计数随进程重启清零。 +没有重放、计费或审计持久性保证,也不建立财务对账、token 节省或任务成功结论。 +写出线程无法启动时,应用输出固定诊断并使用 Noop,不改变业务结果。 + +## 关联与覆盖范围 + +`call_id` 标识一次执行,关联它的 `call`、编号 `attempt` 和 `delivery` 记录。 +它在请求控制中生成一次,贯穿执行完成与响应体生命周期。 +`request_id_fingerprint` 是已绑定请求 ID 的进程内带密钥指纹;没有宿主关联时为 null。 +`target_fingerprint` 是实际传输 URL 的指纹,不是客户端请求的模型或自报目标。重定向仍被禁用。 +指纹密钥在进程内随机生成,不是可跨重启使用的身份,也不承诺密码学匿名化。 +不输出原始 URL、请求 ID、缓存键、会话 ID、Scope、provider 异常、模型名、凭据、prompt 或响应正文。 +记录不证明任务身份或 Source 投影覆盖;除非嵌入宿主另行提供关联,否则没有任务关联能力。 + +覆盖从 `Executor::run` 被轮询时开始。认证、非法请求体、中间件拒绝以及其他执行前入口错误不在本证据流内。 +完整模型响应不代表释放成功。`attempts` 只统计实际交给 transport 的尝试,包含降级发送; +准入过期而未发送时为零。重试沿用同一 `call_id`,只有重新准入后真实发送才增加尝试编号。 +不确定尝试不重发。演示接口 `record_not_sent(0, ...)` 的 prepare/capture/降级诊断不导出, +也不被当作模型未发送事实。 + +## 终态与发送事实 + +`call` 记录包含 `terminal`、`sending`、`attempts`、`upstream_status`、归一化 `usage`、 +可选 `interruption` 和计时字段。终态取值为 `release_authorized`、`blocked`、`withheld`、 +`send_indeterminate`、`not_sent`、`gate_paused`、`degraded`、`admission_expired`、`abandoned`。 +`sending` 独立表示 `no_send`、`definitely_not_sent`、`possibly_sent`、`response_received`。 +取得响应后发生释放拒绝或期限过期,仍保留 `response_received` 与已上报的 usage。 + +pending 执行 future 销毁时输出 `abandoned` 并保留发送事实。 +共享取消信号已设置时,`interruption` 为 `cancellation_requested`;否则宿主期限已过时为 +`deadline_elapsed`,其余情况为 `future_dropped`。这些是销毁时的观测,**不证明销毁原因**。 +沿用 G3-0 的共享生命周期语义:发出取消信号或超过期限本身不会中断执行,所有者必须停止/丢弃 future。 +证据层不新增取消权或定时器。传输中取消保持 `possibly_sent` 和未知 usage,不能记成 `not_sent`。 + +每个 `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)、 +`connect_refused`、`rejected_locally`、`lost_after_handoff`、`timeout_awaiting_response`、`buffer_limit_exceeded`。 +部分响应失败保留已观察到的状态码与首字节时间,完整响应时间和 usage 保持未知。 +transport 交付完整响应后,解码或释放失败不会丢掉 usage。直接丢弃 pending transport 时无法取得其内部的部分观测。 + +## Usage 映射 + +`usage_mapping` 为 `open_ai_chat` 或 `open_ai_responses`,由实际线格式 renderer 选择,不使用客户端模型名。 +无法识别 renderer 时 mapping 为 null、usage 保持未知。 +`usage.input`、`usage.output`、`usage.cache_read`、`usage.cache_write` 各有 `tokens`(非负整数或 null) +与 `completeness`(`known`、`estimated`、`unknown`、`reconciled`)。当前只输出 provider 明确报告的 +`known` 或 `unknown`,不执行估算或对账。 + +| 数量 | OpenAI Chat | OpenAI Responses | +| --- | --- | --- | +| 输入 | `usage.prompt_tokens` | `usage.input_tokens` | +| 输出 | `usage.completion_tokens` | `usage.output_tokens` | +| 缓存读取 | `usage.prompt_tokens_details.cached_tokens` | `usage.input_tokens_details.cached_tokens` | +| 缓存写入 | 未知 | 未知 | + +输入数量**包含**缓存输入;不能把缓存读取再加到输入上,也不能从已上报的输入字段减掉它。 +不会把 Anthropic 的缓存创建/写入字段猜测为 OpenAI 字段。缺失、null、畸形或负数保持未知;明确上报的零为已知零。 +仅有 `total_tokens` 不能确定输入/输出数量。SSE 只使用 Chat usage chunk 中明确的 usage 对象或 Responses +事件的 `response.usage`,保留最后一个对象,不累加累计 chunk。SSE usage 缺失或无法解析时保持未知。 +这不会扩展 Core 接受的流式协议范围。 + +## 计时与 HTTP 交付 + +所有时长使用单调时钟,单位为毫秒,向下取整。null 表示不可得。 + +| 字段/边界 | 含义 | +| --- | --- | +| 调用 `duration_ms` | 创建请求控制至执行终态/销毁,包含创建控制后的入口耗时 | +| 尝试 `started_ms` | 创建请求控制至交给 transport | +| 尝试 `duration_ms` | 交给 transport 至得到传输结果或 future 销毁 | +| `response_first_byte_ms` | 从等待响应头**之前**的 transport 发送起点至首个非空 HTTP 正文 chunk | +| `response_complete_ms` | 从同一 transport 起点至完整缓冲响应 | +| `upstream_ttft_ms` | 始终为 null;HTTP JSON/SSE 字节无法证明模型首 token | +| `release_decision_ms` | 创建请求控制至 before-release 检查返回,包含错误与拒绝 | +| `release_authorized_ms` | 创建请求控制至通过校验且未过期的释放批准,位于可选 capture 之后 | +| 交付 `elapsed_ms` | 创建请求控制至所标记的框架观测 | + +`delivery` 在获准/降级响应体放入 HTTP 响应时报告 `framework_handoff`,框架首次轮询取出非空 data frame +时报告 `first_body_frame`,包装的 body 报告完成时为 `body_completed`,观察到完成之前被丢弃时为 `body_dropped`。 +strict 模式的释放批准先于框架交接与内容 frame 观测。降级响应没有释放批准时间。 +这些边界都不证明 socket 写入、客户端收到、呈现或采用。当前宿主无法观察实际 socket 写出。 +非流式 Responses JSON 的首字节及重放的 SSE 输出不是 provider TTFT。 + +## 部署与兼容 + +原来从 stdout 采集人类可读 tracing 的部署,需要改为采集 stderr,并单独解析 stdout 证据。 +无需数据库迁移、新 HTTP 端点、Python operational 字段或 OpenAPI 重新生成。 +该 JSON schema 独立于 Server 的 Python 日志白名单与现有 exporter。 +自定义嵌入 sink 的同步回调必须有界、不阻塞且不执行 I/O;将阻塞 writer 接入 `JsonEvidenceSink`, +每个宿主保留一个 sink。自定义 writer 应返回 I/O 错误,不应 panic。 +Rust 集成改为读取 `CallEvidence.usage` 中逐字段的数量与完整性,不再读取演示记录原来的扁平 token/completeness 字段。 +不存在生产记录存储迁移。集成需将 `RawResponse.ttft_ms` 替换为明确的首字节/完整响应字段,并将 +`SendOutcome::IncompleteResponse` 视为不确定结果,保留其进度,禁止重试。 diff --git a/docs/zh/docs/operate/meta.json b/docs/zh/docs/operate/meta.json index a65f205006..bbd602ed09 100644 --- a/docs/zh/docs/operate/meta.json +++ b/docs/zh/docs/operate/meta.json @@ -13,6 +13,7 @@ "context-protection", "atomic-memory-migration", "observability", + "gateway-evidence", "reference-observability-stack", "trace-with-phoenix", "trace-with-langfuse", diff --git a/docs/zh/docs/operate/observability.md b/docs/zh/docs/operate/observability.md index afe290dde4..09ece13a45 100644 --- a/docs/zh/docs/operate/observability.md +++ b/docs/zh/docs/operate/observability.md @@ -510,3 +510,6 @@ Topic 处理可通过 `invalid_topic_placeholder` 标识可识别的编号占位 这些不含内容的诊断码表示可恢复的生成拒绝,不表示成功 NOOP。 重试消耗现有 Window 持久化预算;耗尽后保留待处理前沿。诊断码由现有 Worker 事件及关联字段承载。 不得将 Source 文本、生成正文或服务商响应写入运维日志。 + +Rust Gateway 的调用/尝试/usage 与 HTTP 框架观测使用独立的[有界证据输出](gateway-evidence.md), +不新增 Python 日志字段,也不证明客户端已收到内容。 diff --git a/gateway/README.md b/gateway/README.md index 010106bc13..d2b8dac154 100644 --- a/gateway/README.md +++ b/gateway/README.md @@ -28,7 +28,7 @@ An optional Rust executor for PowerContext, defined by the gateway design in #21 - **OpenAI-compatible ingress** at `/gateway/v1/chat/completions` and `/gateway/v1/responses` (same format in and out, no cross-format translation), authenticated by a gateway key that replaces provider keys. - **Responses fidelity**: on `/gateway/v1/responses`, every input item other than a plain user message (developer messages, tool calls and outputs, reasoning, client-specific items such as Codex's `additional_tools`) is forwarded unchanged, and request fields the ingress does not model (for example `reasoning`, `include`, `prompt_cache_key`) are passed through for Core's request allowlist to decide; only the client-local `client_metadata` is dropped. The upstream request is always non-streaming; a streaming client receives the released (or permitted degraded-passthrough, still marked `x-pc-degraded`) 200 response replayed as Responses SSE events: `response.created`, `response.output_item.added`/`done` per item with each message content part as `response.content_part.added`/`done` around one buffered `response.output_text.delta`/`done` (or `response.refusal.delta`/`done`), and a terminal event chosen from the response status (`response.completed`, `response.incomplete`, or `response.failed` when the status is `failed`/`cancelled` or an `error` is present). - **Middleware chain**: composable `GatewayMiddleware` trait; ships with resource limits (request-body precheck + concurrency semaphore, health probe exempt) and request-id propagation (`x-powercontext-request-id`, client-supplied or generated, echoed on responses). -- **Body-free evidence**: usage completeness (known/estimated/unknown), cache tokens, TTFT vs first-release latency, attempt counters — never request/response bodies. +- **Body-free evidence**: bounded JSONL on stdout (1024 queued records plus one in flight), correlated call/attempt terminals, per-field usage completeness and cache reads, explicit first-byte/release/framework timing; model TTFT stays unknown. Operational tracing uses stderr. See the [output and deployment contract](../docs/en/docs/operate/gateway-evidence.md) / [中文](../docs/zh/docs/operate/gateway-evidence.md). `PC_GATEWAY_EVIDENCE=off` explicitly disables coverage. ## PC call sequence over UDS @@ -71,7 +71,7 @@ Everything else (Core's 127 domain operations, MCP, dashboard) is reverse-proxie | `pc-gateway-types` | contract DTOs aligned field-by-field with #2264 | | `pc-gateway-protocol` | canonical request, chat/responses wire renderers, SSE framing | | `pc-gateway-transport` | upstream transport, bounded retry, streaming buffer with caps | -| `pc-gateway-evidence` | body-free evidence (usage completeness, cache tokens, TTFT) | +| `pc-gateway-evidence` | bounded body-free JSONL evidence (calls, attempts, usage, delivery boundaries) | | `pc-gateway-embedded` | placeholder for the in-process (FFI) executor path | ## Run @@ -103,4 +103,4 @@ Credentials live only in server-side environment variables; they are never accep ## Tests -`cargo test` — 27 tests covering the failure-semantics table (gate unavailable, withhold terminal, bounded retry, indeterminate no-resend, blocked turns never sediment), renderer fidelity (no timestamps/request ids injected), byte-range declaration, UDS connection-pool correctness over a real Unix socket, and live integration tests against a real PowerContext Server (binding validity, cross-scope rejection, deadlines) that skip gracefully when no server is reachable. +`cargo test --locked --workspace` exercises executor outcomes and pending-future destruction, actual HTTP transport fixtures, strict release/framework order, queue overflow, slow/failing writers and privacy markers. The `live_context_check` tests return early when no real Core is reachable; a green workspace run alone is not real-Core/provider/host acceptance. No hosted-model calls are required. diff --git a/gateway/crates/pc-gateway-app/src/evidence_body.rs b/gateway/crates/pc-gateway-app/src/evidence_body.rs new file mode 100644 index 0000000000..8aec0d0629 --- /dev/null +++ b/gateway/crates/pc-gateway-app/src/evidence_body.rs @@ -0,0 +1,101 @@ +// 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. + +//! HTTP-framework observations. Polling a frame does not prove a socket write or receipt. +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 std::pin::Pin; +use std::sync::Arc; +use std::task::{Context, Poll}; + +pub(crate) struct EvidenceBody { + body: Body, + observation: ExecutionObservation, + sink: Arc, + first: bool, + completed: bool, +} + +impl EvidenceBody { + pub(crate) fn wrap( + body: Body, + observation: ExecutionObservation, + sink: Arc, + ) -> Body { + let wrapper = Self { + body, + observation, + sink, + first: false, + completed: false, + }; + wrapper.record(DeliveryBoundary::FrameworkHandoff); + Body::new(wrapper) + } + + fn record(&self, boundary: DeliveryBoundary) { + self.sink.record_delivery(&DeliveryEvidence { + call_id: self.observation.call_id().to_owned(), + boundary, + elapsed_ms: self.observation.elapsed_ms(), + }); + } +} + +impl HttpBody for EvidenceBody { + type Data = Bytes; + type Error = axum::Error; + + fn poll_frame( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll, Self::Error>>> { + let result = Pin::new(&mut self.body).poll_frame(cx); + if let Poll::Ready(frame) = &result { + if !self.first + && frame + .as_ref() + .and_then(|r| r.as_ref().ok()) + .and_then(Frame::data_ref) + .is_some_and(|data| !data.is_empty()) + { + self.first = true; + self.record(DeliveryBoundary::FirstBodyFrame); + } + if !self.completed + && (frame.is_none() || (matches!(frame, Some(Ok(_))) && self.body.is_end_stream())) + { + self.completed = true; + self.record(DeliveryBoundary::BodyCompleted); + } + } + result + } + fn is_end_stream(&self) -> bool { + self.body.is_end_stream() + } + fn size_hint(&self) -> SizeHint { + self.body.size_hint() + } +} + +impl Drop for EvidenceBody { + fn drop(&mut self) { + if !self.completed { + self.record(DeliveryBoundary::BodyDropped); + } + } +} diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index c89daaab6a..d23fad4a7c 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -124,7 +124,24 @@ async fn ingress_common( ); let observation = control.observation(); let cancellation = control.cancellation(); - let mut response = ingress_model(state, headers, req, format, control).await; + let mut response = ingress_model(state.clone(), headers, req, format, control).await; + if matches!( + observation.snapshot().execution, + pc_gateway_core::ExecutionState::Finished( + pc_gateway_core::ExecutionTerminal::ReleaseAuthorized + | pc_gateway_core::ExecutionTerminal::Degraded + ) + ) { + let (parts, body) = response.into_parts(); + response = Response::from_parts( + parts, + crate::evidence_body::EvidenceBody::wrap( + body, + observation.clone(), + state.evidence.clone(), + ), + ); + } response.extensions_mut().insert(observation); response.extensions_mut().insert(cancellation); response @@ -691,6 +708,12 @@ mod tests { use super::*; async fn lifecycle_router() -> (axum::Router, tokio::task::JoinHandle<()>) { + lifecycle_router_with_evidence(Arc::new(pc_gateway_evidence::NoopEvidenceSink)).await + } + + async fn lifecycle_router_with_evidence( + evidence: Arc, + ) -> (axum::Router, tokio::task::JoinHandle<()>) { use axum::routing::post; use pc_gateway_core::{Executor, HttpGateClient}; use pc_gateway_types::{CheckPhase, ContextCheckRequest}; @@ -720,7 +743,9 @@ mod tests { ( StatusCode::CREATED, Json(serde_json::json!({ - "choices": [{"message": {"role": "assistant", "content": "checked"}}] + "choices": [{"message": {"role": "assistant", "content": "checked"}}], + "usage": {"prompt_tokens": 100, "completion_tokens": 12, "prompt_tokens_details": {"cached_tokens": 70}}, + "provider_debug": "SYNTHETIC_SENSITIVE_RESPONSE" })), ) }), @@ -729,7 +754,8 @@ mod tests { "/v1/responses", post(|| async { Json(serde_json::json!({ - "id": "resp-1", "object": "response", "status": "completed", "output": [] + "id": "resp-1", "object": "response", "status": "completed", "output": [], + "usage": {"input_tokens": 80, "output_tokens": 11, "input_tokens_details": {"cached_tokens": 30}} })) }), ); @@ -742,11 +768,11 @@ mod tests { pc_gateway_transport::ReqwestTransport::new(std::time::Duration::from_secs(120)), std::num::NonZeroU32::new(2).unwrap(), )), - evidence: Arc::new(pc_gateway_evidence::BufferedEvidenceSink::new()), + evidence, upstream_profile: "test".into(), upstream_chat: format!("{base}/v1/chat/completions"), upstream_responses: format!("{base}/v1/responses"), - upstream_chat_api_key: String::new(), + upstream_chat_api_key: "SYNTHETIC_SENSITIVE_CREDENTIAL".into(), upstream_responses_api_key: String::new(), api_key: Some("gateway-key".into()), degrade: pc_gateway_core::DegradePolicy::Pause, @@ -1511,4 +1537,140 @@ mod tests { assert!(canonical.messages[0].content_null); assert!(canonical.messages[0].tool_calls.is_none()); } + + #[derive(Clone, Default)] + struct EvidenceOutput(Arc>>); + impl std::io::Write for EvidenceOutput { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + #[tokio::test] + async fn real_ingress_exports_usage_and_distinct_framework_boundaries_without_content() { + use pc_gateway_evidence::JsonEvidenceSink; + use tower::ServiceExt; + let output = EvidenceOutput::default(); + let sink = Arc::new( + JsonEvidenceSink::new(output.clone(), std::num::NonZeroUsize::new(1024).unwrap()) + .unwrap(), + ); + let (router, server) = lifecycle_router_with_evidence(sink.clone()).await; + // Exercise both public routes and Responses replay, with the real reqwest transport. + for i in 0..200 { + let chat = i % 2 == 0; + let request = Request::builder().method("POST") + .uri(if chat { "/gateway/v1/chat/completions" } else { "/gateway/v1/responses" }) + .header(header::AUTHORIZATION, "Bearer gateway-key") + .header("x-powercontext-request-id", "SYNTHETIC_SENSITIVE_CORRELATION") + .body(axum::body::Body::from(if chat { + serde_json::json!({"model":"SYNTHETIC_SENSITIVE_MODEL", "messages":[{"role":"user", "content":"SYNTHETIC_SENSITIVE_PROMPT"}]}).to_string() + } else { + serde_json::json!({"model":"SYNTHETIC_SENSITIVE_MODEL", "input":[{"role":"user", "content":"SYNTHETIC_SENSITIVE_PROMPT"}], "store":false, "stream":true}).to_string() + })).unwrap(); + let response = router.clone().oneshot(request).await.unwrap(); + assert!(response.status().is_success()); + axum::body::to_bytes(response.into_body(), 1024 * 1024) + .await + .unwrap(); + } + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while sink.stats().written < 1000 { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert_eq!(sink.stats().dropped, 0); + let text = String::from_utf8(output.0.lock().unwrap().clone()).unwrap(); + assert!(!text.contains("SYNTHETIC_SENSITIVE")); + assert!(!text.contains("gateway-key")); + assert!(!text.contains("/v1/")); + let mut records = std::collections::BTreeMap::>::new(); + for line in text.lines() { + let value: serde_json::Value = serde_json::from_str(line).unwrap(); + records + .entry(value["evidence"]["call_id"].as_str().unwrap().to_owned()) + .or_default() + .push(value); + } + assert_eq!(records.len(), 200); + for events in records.values() { + let names: Vec<_> = events + .iter() + .map(|e| e["event"].as_str().unwrap()) + .collect(); + assert_eq!( + names, + ["attempt", "call", "delivery", "delivery", "delivery"] + ); + let call = &events[1]["evidence"]; + let attempt = &events[0]["evidence"]; + let chat = call["usage_mapping"] == "open_ai_chat"; + assert_eq!( + call["usage"]["input"]["tokens"], + if chat { 100 } else { 80 } + ); + assert_eq!( + call["usage"]["cache_read"]["tokens"], + if chat { 70 } else { 30 } + ); + assert!(call["usage"]["cache_write"]["tokens"].is_null()); + assert!(call["upstream_ttft_ms"].is_null()); + assert!(attempt["response_first_byte_ms"].is_u64()); + assert!( + attempt["response_complete_ms"].as_u64() + >= attempt["response_first_byte_ms"].as_u64() + ); + assert_eq!(events[2]["evidence"]["boundary"], "framework_handoff"); + assert_eq!(events[3]["evidence"]["boundary"], "first_body_frame"); + assert_eq!(events[4]["evidence"]["boundary"], "body_completed"); + assert!( + events[2]["evidence"]["elapsed_ms"].as_u64() + >= call["release_authorized_ms"].as_u64() + ); + } + server.abort(); + } + + #[tokio::test] + async fn unconsumed_response_reports_drop_without_claiming_content_delivery() { + use pc_gateway_evidence::{BufferedEvidenceSink, DeliveryBoundary, EvidenceEvent}; + use tower::ServiceExt; + let evidence = Arc::new(BufferedEvidenceSink::new()); + let (router, server) = lifecycle_router_with_evidence(evidence.clone()).await; + let request = Request::builder() + .method("POST") + .uri("/gateway/v1/chat/completions") + .header(header::AUTHORIZATION, "Bearer gateway-key") + .body(axum::body::Body::from( + r#"{"model":"test","messages":[{"role":"user","content":"hello"}]}"#, + )) + .unwrap(); + let response = router.oneshot(request).await.unwrap(); + drop(response); + let delivery: Vec<_> = evidence + .events() + .into_iter() + .filter_map(|e| { + if let EvidenceEvent::Delivery(d) = e { + Some(d.boundary) + } else { + None + } + }) + .collect(); + assert!(matches!( + delivery.as_slice(), + [ + DeliveryBoundary::FrameworkHandoff, + DeliveryBoundary::BodyDropped + ] + )); + server.abort(); + } } diff --git a/gateway/crates/pc-gateway-app/src/main.rs b/gateway/crates/pc-gateway-app/src/main.rs index 49244106b0..93e8fcc78e 100644 --- a/gateway/crates/pc-gateway-app/src/main.rs +++ b/gateway/crates/pc-gateway-app/src/main.rs @@ -24,6 +24,7 @@ //! PC_GATEWAY_UPSTREAM_API_KEY、PC_GATEWAY_UPSTREAM_PROFILE、 //! PC_GATEWAY_POLICY_VERSION、PC_GATEWAY_MAX_ATTEMPTS、PC_GATEWAY_DEGRADE。 +mod evidence_body; mod ingress; mod link; mod middleware; @@ -34,7 +35,7 @@ use crate::link::CoreLink; use axum::routing::{get, post}; use axum::Router; use pc_gateway_core::Executor; -use pc_gateway_evidence::BufferedEvidenceSink; +use pc_gateway_evidence::{EvidenceSink, JsonEvidenceSink, NoopEvidenceSink}; use pc_gateway_transport::ReqwestTransport; use std::net::SocketAddr; use std::num::NonZeroU32; @@ -44,7 +45,7 @@ use std::time::Duration; pub struct AppState { /// 单一执行器;线格式渲染器按请求格式传入(同格式进出)。 pub executor: Arc>, - pub evidence: Arc, + pub evidence: Arc, pub upstream_profile: String, /// chat-completions 上游(含 key;老变量 PC_GATEWAY_UPSTREAM_URL 仍作缺省)。 pub upstream_chat: String, @@ -74,6 +75,7 @@ pub struct AppState { #[tokio::main] async fn main() { tracing_subscriber::fmt() + .with_writer(std::io::stderr) .with_env_filter( tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), ) @@ -109,13 +111,37 @@ async fn main() { } }; + // stdout is reserved for body-free evidence JSONL; operational tracing uses stderr. + let evidence: Arc = + if matches!(std::env::var("PC_GATEWAY_EVIDENCE").as_deref(), Ok("off")) { + tracing::info!("gateway evidence disabled; usage and call coverage unavailable"); + Arc::new(NoopEvidenceSink) + } else { + match JsonEvidenceSink::new( + std::io::stdout(), + std::num::NonZeroUsize::new(1024).unwrap(), + ) { + Ok(sink) => { + tracing::info!( + capacity = 1024, + "gateway evidence JSONL enabled on stdout; drop newest on overflow" + ); + Arc::new(sink) + } + Err(_) => { + tracing::error!("gateway evidence worker unavailable; evidence disabled"); + Arc::new(NoopEvidenceSink) + } + } + }; + let state = Arc::new(AppState { executor: Arc::new(Executor::new( core_link.clone(), ReqwestTransport::new(Duration::from_secs(120)), NonZeroU32::new(max_attempts).expect("max_attempts > 0"), )), - evidence: Arc::new(BufferedEvidenceSink::new()), + evidence, upstream_profile: std::env::var("PC_GATEWAY_UPSTREAM_PROFILE") .unwrap_or_else(|_| "default".into()), upstream_chat: std::env::var("PC_GATEWAY_UPSTREAM_URL_CHAT") @@ -237,8 +263,8 @@ async fn resolve_degradation(link: link::CoreLink) -> bool { ); allowed } - Ok(Err(e)) => { - tracing::warn!(error = %e, "capabilities error; degradation disabled (fail-closed)"); + Ok(Err(_)) => { + tracing::warn!("capabilities error; degradation disabled (fail-closed)"); false } Err(_) => { diff --git a/gateway/crates/pc-gateway-app/tests/evidence_process.rs b/gateway/crates/pc-gateway-app/tests/evidence_process.rs new file mode 100644 index 0000000000..380af624d2 --- /dev/null +++ b/gateway/crates/pc-gateway-app/tests/evidence_process.rs @@ -0,0 +1,169 @@ +// 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. + +//! Production composition in a real spawned Gateway, with local HTTP Core/provider fixtures. +use axum::{ + routing::{get, post}, + Json, Router, +}; +use serde_json::{json, Value}; +use std::io::{BufRead, Read}; +use std::process::{Child, Command, Stdio}; +use std::sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, +}; +use std::time::Duration; + +struct Gateway(Child); +impl Drop for Gateway { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn production_jsonl_and_explicit_noop_keep_real_requests_usable() { + let fixture = Router::new() + .route("/v1/capabilities", get(|| async { Json(json!({"context_protection": { + "check_versions": ["powercontext.context-check.v1"], "payload_versions": ["powercontext.model-json-payload.v1"], "enforcing":true + }})) })) + .route("/v1/context/check", post(|Json(request): Json| async move { Json(json!({ + "schema":"powercontext.context-check.v1", "phase":request["phase"], "decision":"allow", + "reason_codes":[], "coverage":{"profile":"text-and-tools.v1", "complete":true}, + "policy_version":"fixture", "valid_until":"2999-01-01T00:00:00Z", "binding":"fixture-binding" + })) })) + .route("/v1/chat/completions", post(|| async { Json(json!({ + "choices":[{"message":{"role":"assistant", "content":"SYNTHETIC_RESPONSE_SECRET"}}], + "usage":{"prompt_tokens":101, "completion_tokens":13, "prompt_tokens_details":{"cached_tokens":61}} + })) })); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let fixture_task = tokio::spawn(async move { + axum::serve(listener, fixture).await.unwrap(); + }); + let client = reqwest::Client::new(); + for disabled in [false, true] { + let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let address = port.local_addr().unwrap(); + drop(port); + let mut command = Command::new(env!("CARGO_BIN_EXE_pc-gateway")); + for (key, _) in std::env::vars_os() { + if key.to_string_lossy().starts_with("PC_GATEWAY_") { + command.env_remove(key); + } + } + command + .env("PC_GATEWAY_CORE_BASE", &base) + .env("PC_GATEWAY_LISTEN", address.to_string()) + .env( + "PC_GATEWAY_UPSTREAM_URL", + format!("{base}/v1/chat/completions"), + ) + .env("PC_GATEWAY_API_KEY", "SYNTHETIC_GATEWAY_KEY") + .env("PC_GATEWAY_UPSTREAM_API_KEY", "SYNTHETIC_PROVIDER_KEY") + .env("PC_GATEWAY_INJECTION", "off") + .env("RUST_LOG", "info") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + if disabled { + command.env("PC_GATEWAY_EVIDENCE", "off"); + } + let mut gateway = Gateway(command.spawn().unwrap()); + let stdout = gateway.0.stdout.take().unwrap(); + let mut stderr = gateway.0.stderr.take().unwrap(); + let lines = Arc::new(AtomicUsize::new(0)); + let read_lines = lines.clone(); + let output = std::thread::spawn(move || { + std::io::BufReader::new(stdout) + .lines() + .map(|line| { + let line = line.unwrap(); + read_lines.fetch_add(1, Ordering::Relaxed); + line + }) + .collect::>() + }); + let errors = std::thread::spawn(move || { + let mut text = String::new(); + stderr.read_to_string(&mut text).unwrap(); + text + }); + let url = format!("http://{address}"); + tokio::time::timeout(Duration::from_secs(10), async { + loop { + if client.get(format!("{url}/healthz")).send().await.is_ok() { + break; + } + assert!( + gateway.0.try_wait().unwrap().is_none(), + "Gateway exited during startup" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + let count = if disabled { 100 } else { 1000 }; + for _ in 0..count { + let response = client.post(format!("{url}/gateway/v1/chat/completions")) + .bearer_auth("SYNTHETIC_GATEWAY_KEY") + .header("x-powercontext-request-id", "SYNTHETIC_REQUEST_SECRET") + .json(&json!({"model":"SYNTHETIC_MODEL", "messages":[{"role":"user", "content":"SYNTHETIC_PROMPT_SECRET"}]})) + .send().await.unwrap(); + assert_eq!(response.status(), 200); + assert_eq!( + response.json::().await.unwrap()["usage"]["prompt_tokens"], + 101 + ); + } + if !disabled { + tokio::time::timeout(Duration::from_secs(5), async { + while lines.load(Ordering::Relaxed) < count * 5 { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + } + drop(gateway); + let output = output.join().unwrap(); + let errors = errors.join().unwrap(); + assert!(!errors.contains("SYNTHETIC_")); + if disabled { + assert!(output.is_empty()); + assert!(errors.contains("evidence disabled")); + } else { + assert_eq!(output.len(), count * 5); + let mut call_ids = std::collections::BTreeSet::new(); + for line in output { + assert!(!line.contains("SYNTHETIC_")); + let record: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(record["loss"]["dropped"], 0); + if record["event"] == "call" { + let evidence = &record["evidence"]; + assert_eq!(evidence["terminal"], "release_authorized"); + assert_eq!(evidence["usage"]["input"]["tokens"], 101); + assert_eq!(evidence["usage"]["cache_read"]["tokens"], 61); + assert!(evidence["usage"]["cache_write"]["tokens"].is_null()); + assert!(evidence["upstream_ttft_ms"].is_null()); + call_ids.insert(evidence["call_id"].as_str().unwrap().to_owned()); + } + } + assert_eq!(call_ids.len(), count); + } + } + fixture_task.abort(); +} diff --git a/gateway/crates/pc-gateway-core/src/evidence.rs b/gateway/crates/pc-gateway-core/src/evidence.rs new file mode 100644 index 0000000000..38aa1054ee --- /dev/null +++ b/gateway/crates/pc-gateway-core/src/evidence.rs @@ -0,0 +1,173 @@ +// 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. + +//! Execution-owned evidence, including destruction of a pending future. +use crate::{ExecutionObservation, ManagedOutcome, RequestCancellation}; +use pc_gateway_evidence::{ + fingerprint, AttemptEvidence, AttemptOutcome, CallEvidence, EvidenceSink, Interruption, + Sending, Terminal, UsageEvidence, UsageMapping, +}; +use pc_gateway_transport::{NotSentReason, RawResponse, SendIndeterminateReason}; +use std::time::Instant; + +pub(crate) struct CallRecorder<'a> { + sink: &'a dyn EvidenceSink, + observation: ExecutionObservation, + cancellation: RequestCancellation, + call: CallEvidence, + attempt: Option<(AttemptEvidence, Instant)>, +} + +impl<'a> CallRecorder<'a> { + pub(crate) fn new( + sink: &'a dyn EvidenceSink, + observation: ExecutionObservation, + cancellation: RequestCancellation, + target: &str, + mapping: Option, + ) -> Self { + let call = CallEvidence { + call_id: observation.call_id().to_owned(), + request_id_fingerprint: observation.request_id().map(fingerprint), + target_fingerprint: fingerprint(target), + usage_mapping: mapping, + ..Default::default() + }; + Self { + sink, + observation, + cancellation, + call, + attempt: None, + } + } + + pub(crate) fn begin_attempt(&mut self) { + self.call.attempts += 1; + self.call.sending = Sending::PossiblySent; + self.attempt = Some(( + AttemptEvidence { + call_id: self.call.call_id.clone(), + attempt: self.call.attempts, + started_ms: self.observation.elapsed_ms(), + ..Default::default() + }, + Instant::now(), + )); + } + + pub(crate) fn received(&mut self, raw: &RawResponse) { + self.call.sending = Sending::ResponseReceived; + self.call.upstream_status = Some(raw.status); + self.call.usage = self + .call + .usage_mapping + .map(|mapping| UsageEvidence::openai(raw.usage.as_ref(), mapping)) + .unwrap_or_default(); + if let Some((attempt, _)) = &mut self.attempt { + attempt.outcome = if raw.status >= 400 { + AttemptOutcome::UpstreamError + } else { + AttemptOutcome::Delivered + }; + attempt.upstream_status = Some(raw.status); + attempt.response_first_byte_ms = raw.response_first_byte_ms; + attempt.response_complete_ms = raw.response_complete_ms; + attempt.usage = self.call.usage.clone(); + } + self.finish_attempt(); + } + + pub(crate) fn not_sent(&mut self, reason: &NotSentReason) { + self.call.sending = Sending::DefinitelyNotSent; + if let Some((attempt, _)) = &mut self.attempt { + attempt.outcome = match reason { + NotSentReason::ConnectRefused => AttemptOutcome::ConnectRefused, + NotSentReason::RejectedLocally => AttemptOutcome::RejectedLocally, + }; + } + self.finish_attempt(); + } + + pub(crate) fn incomplete_response( + &mut self, + reason: &SendIndeterminateReason, + status: u16, + first_byte: Option, + ) { + self.call.upstream_status = Some(status); + if let Some((attempt, _)) = &mut self.attempt { + attempt.upstream_status = Some(status); + attempt.response_first_byte_ms = first_byte; + } + self.indeterminate(reason); + } + + pub(crate) fn indeterminate(&mut self, reason: &SendIndeterminateReason) { + if let Some((attempt, _)) = &mut self.attempt { + attempt.outcome = match reason { + SendIndeterminateReason::LostAfterHandoff => AttemptOutcome::LostAfterHandoff, + SendIndeterminateReason::TimeoutAwaitingResponse => { + AttemptOutcome::TimeoutAwaitingResponse + } + SendIndeterminateReason::BufferLimitExceeded => AttemptOutcome::BufferLimitExceeded, + }; + } + self.finish_attempt(); + } + + fn finish_attempt(&mut self) { + if let Some((mut attempt, start)) = self.attempt.take() { + attempt.duration_ms = start.elapsed().as_millis() as u64; + self.sink.record_attempt_evidence(&attempt); + } + } + + pub(crate) fn release_decision(&mut self) { + self.call.release_decision_ms = Some(self.observation.elapsed_ms()); + } + pub(crate) fn authorized(&mut self) { + self.call.release_authorized_ms = Some(self.observation.elapsed_ms()); + } + + pub(crate) fn finish(&mut self, outcome: &ManagedOutcome) { + self.call.terminal = match outcome { + ManagedOutcome::Released { .. } => Terminal::ReleaseAuthorized, + ManagedOutcome::Blocked { .. } => Terminal::Blocked, + ManagedOutcome::Withheld { .. } => Terminal::Withheld, + ManagedOutcome::SendIndeterminate => Terminal::SendIndeterminate, + ManagedOutcome::NotSent { .. } => Terminal::NotSent, + ManagedOutcome::GatePaused(_) => Terminal::GatePaused, + ManagedOutcome::Degraded { .. } => Terminal::Degraded, + ManagedOutcome::AdmissionExpired => Terminal::AdmissionExpired, + }; + } +} + +impl Drop for CallRecorder<'_> { + fn drop(&mut self) { + self.finish_attempt(); + if self.call.terminal == Terminal::Abandoned { + self.call.interruption = Some(if self.cancellation.is_cancelled() { + Interruption::CancellationRequested + } else if tokio::time::Instant::now() >= self.observation.deadline() { + Interruption::DeadlineElapsed + } else { + Interruption::FutureDropped + }); + } + 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 e93fdef06e..f178db6747 100644 --- a/gateway/crates/pc-gateway-core/src/executor.rs +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -28,12 +28,14 @@ //! └── 降级时用此原始请求(不含注入)重新渲染 //! ``` +use crate::evidence::CallRecorder; use crate::lifecycle::Execution; use crate::replay_cache::{message_anchor, PreparedBlock, ReplayCache, MAX_REPLAY_MS}; use crate::transcript::turn_transcript; use crate::{GateClient, GateError}; use crate::{ModelSendState, RequestControl}; use pc_gateway_evidence::EvidenceSink; +use pc_gateway_evidence::UsageMapping; use pc_gateway_protocol::{CanonicalRequest, WireRenderer}; use pc_gateway_transport::{AdmittedSend, SendOutcome, Transport}; use pc_gateway_types::{ @@ -134,8 +136,22 @@ where renderer: &R, evidence: &dyn EvidenceSink, ) -> ManagedOutcome { + let mut recording = CallRecorder::new( + evidence, + control.observation(), + control.cancellation(), + &call.target_url, + match renderer.message_list_key() { + "input" => Some(UsageMapping::OpenAiResponses), + "messages" => Some(UsageMapping::OpenAiChat), + _ => None, + }, + ); let mut execution = control.start(); - let outcome = self.execute(call, renderer, evidence, &mut execution).await; + let outcome = self + .execute(call, renderer, evidence, &mut execution, &mut recording) + .await; + recording.finish(&outcome); execution.finish(&outcome); outcome } @@ -146,6 +162,7 @@ where renderer: &R, evidence: &dyn EvidenceSink, execution: &mut Execution, + recording: &mut CallRecorder<'_>, ) -> ManagedOutcome { let mut call = call; // P1-3:enrich 之前快照原始请求。降级路径必须用这份(不含注入内容) @@ -204,7 +221,7 @@ where prepared_contexts: Vec::new(), }; degraded_call.request.stream = call.request.stream; - self.degraded_send(°raded_call, renderer, evidence, execution) + self.degraded_send(°raded_call, renderer, evidence, execution, recording) .await } (e, _) => ManagedOutcome::GatePaused(classify_gate_error(e)), @@ -250,14 +267,28 @@ where stream: call.request.stream, }; let sent_binding = current.binding.clone(); + recording.begin_attempt(); execution.model_send(ModelSendState::PossiblySent); match self.transport.send(send).await { SendOutcome::Delivered(raw) => { + recording.received(&raw); execution.model_send(ModelSendState::ResponseReceived); break (raw, sent_binding); } - SendOutcome::Indeterminate(_) => return ManagedOutcome::SendIndeterminate, + SendOutcome::IncompleteResponse { + reason, + status, + response_first_byte_ms, + } => { + recording.incomplete_response(&reason, status, response_first_byte_ms); + return ManagedOutcome::SendIndeterminate; + } + SendOutcome::Indeterminate(reason) => { + recording.indeterminate(&reason); + return ManagedOutcome::SendIndeterminate; + } SendOutcome::NotSent(reason) => { + recording.not_sent(&reason); execution.model_send(ModelSendState::DefinitelyNotSent); evidence.record_not_sent(attempt, &reason.to_string()); if attempt >= self.max_attempts.get() { @@ -326,7 +357,9 @@ where ), completion: pc_gateway_types::CONTEXT_CHECK_COMPLETION.into(), }; - match self.gate.check(release_check).await { + let verdict = self.gate.check(release_check).await; + recording.release_decision(); + match verdict { Err(e) => ManagedOutcome::GatePaused(classify_gate_error(e)), Ok(result) => match result.decision { CheckDecision::Allow => { @@ -376,13 +409,14 @@ where Err(GateError::GateRejected(409)) => { evidence.record_not_sent(0, "sediment_duplicate") } - Err(e) => evidence.record_not_sent(0, &format!("sediment_failed:{e}")), + Err(_) => evidence.record_not_sent(0, "sediment_failed:gate_error"), } // P1-4 残留:capture 完成后复核——沉淀耗时可能跨越截止时间。 if now_ms() >= release_deadline { return ManagedOutcome::AdmissionExpired; } } + recording.authorized(); ManagedOutcome::Released { binding: result.binding, status: raw.status, @@ -479,9 +513,9 @@ where .await { Ok(p) => p, - Err(e) => { - evidence.record_not_sent(0, &format!("prepare_failed:{e}")); - tracing::warn!(error = %e, "prepare failed; injecting nothing"); + Err(_) => { + evidence.record_not_sent(0, "prepare_failed"); + tracing::warn!("prepare failed; injecting nothing"); return None; } }; @@ -576,6 +610,7 @@ where renderer: &R, evidence: &dyn EvidenceSink, execution: &mut Execution, + recording: &mut CallRecorder<'_>, ) -> ManagedOutcome { evidence.record_not_sent(0, "degraded_passthrough"); let payload = match renderer.render(&call.request, None) { @@ -593,9 +628,11 @@ where headers: call.headers.clone(), stream: call.request.stream, }; + recording.begin_attempt(); execution.model_send(ModelSendState::PossiblySent); match self.transport.send(send).await { SendOutcome::Delivered(raw) => { + recording.received(&raw); execution.model_send(ModelSendState::ResponseReceived); ManagedOutcome::Degraded { status: raw.status, @@ -603,8 +640,20 @@ where body: raw.body, } } - SendOutcome::Indeterminate(_) => ManagedOutcome::SendIndeterminate, + SendOutcome::IncompleteResponse { + reason, + status, + response_first_byte_ms, + } => { + recording.incomplete_response(&reason, status, response_first_byte_ms); + ManagedOutcome::SendIndeterminate + } + SendOutcome::Indeterminate(reason) => { + recording.indeterminate(&reason); + ManagedOutcome::SendIndeterminate + } SendOutcome::NotSent(reason) => { + recording.not_sent(&reason); execution.model_send(ModelSendState::DefinitelyNotSent); evidence.record_not_sent(1, &reason.to_string()); ManagedOutcome::NotSent { attempts: 1 } @@ -635,10 +684,9 @@ fn validate_allow( ) -> Result<(String, u64), ManagedOutcome> { // 1. schema 必须匹配 if result.schema != pc_gateway_types::CONTEXT_CHECK_SCHEMA { - return Err(ManagedOutcome::GatePaused(format!( - "malformed_verdict: schema mismatch: {}", - result.schema - ))); + return Err(ManagedOutcome::GatePaused( + "malformed_verdict: schema mismatch".into(), + )); } // 2. phase 必须与请求阶段一致 if result.phase != expected_phase { @@ -668,7 +716,8 @@ fn validate_allow( fn classify_gate_error(e: GateError) -> String { match e { - GateError::GateUnavailable(msg) | GateError::Malformed(msg) => msg, + GateError::GateUnavailable(_) => "gate_unavailable".into(), + GateError::Malformed(_) => "malformed_gate_response".into(), GateError::GateRejected(status) => format!("gate rejected: HTTP {status}"), } } diff --git a/gateway/crates/pc-gateway-core/src/lib.rs b/gateway/crates/pc-gateway-core/src/lib.rs index 9121ccc84e..66a7df4357 100644 --- a/gateway/crates/pc-gateway-core/src/lib.rs +++ b/gateway/crates/pc-gateway-core/src/lib.rs @@ -38,3 +38,5 @@ pub use gate_client::*; pub use http_gate_client::*; pub use lifecycle::*; pub use uds_gate_client::*; + +mod evidence; diff --git a/gateway/crates/pc-gateway-core/src/lifecycle.rs b/gateway/crates/pc-gateway-core/src/lifecycle.rs index aa0c25af7d..5bf891e823 100644 --- a/gateway/crates/pc-gateway-core/src/lifecycle.rs +++ b/gateway/crates/pc-gateway-core/src/lifecycle.rs @@ -47,6 +47,8 @@ pub struct ExecutionSnapshot { struct Shared { deadline: Instant, request_id: Option, + call_id: String, + started: std::time::Instant, snapshot: Mutex, } @@ -71,6 +73,8 @@ impl RequestControl { shared: Arc::new(Shared { deadline, request_id, + call_id: pc_gateway_evidence::new_call_id(), + started: std::time::Instant::now(), snapshot: Mutex::new(ExecutionSnapshot { model_send: ModelSendState::NoSend, execution: ExecutionState::NotStarted, @@ -127,6 +131,16 @@ pub struct ExecutionObservation { } impl ExecutionObservation { + /// Process-local logical call identity; contains no host-provided values. + pub fn call_id(&self) -> &str { + &self.shared.call_id + } + + /// Monotonic milliseconds since the host created request control. + pub fn elapsed_ms(&self) -> u64 { + self.shared.started.elapsed().as_millis() as u64 + } + pub fn deadline(&self) -> Instant { self.shared.deadline } diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index 14250b0bd2..c018df97dc 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -205,7 +205,8 @@ fn raw_response() -> SendOutcome { SendOutcome::Delivered(pc_gateway_transport::RawResponse { status: 200, content_type: "application/json".into(), - ttft_ms: None, + response_first_byte_ms: None, + response_complete_ms: None, body: bytes::Bytes::from_static(br#"{"choices":[{"message":{"role":"assistant","content":"ok"}}],"usage":{"total_tokens":1}}"#), usage: Some(serde_json::json!({"total_tokens": 1})), }) @@ -1356,7 +1357,8 @@ async fn non_utf8_response_is_never_released() { status: 200, body: bytes::Bytes::from_static(b"{\"text\":\"\xff\xfe\"}"), // 非法 UTF-8 content_type: "application/json".into(), - ttft_ms: None, + response_first_byte_ms: None, + response_complete_ms: None, usage: None, }); let (executor, renderer, transport, gate) = harness( @@ -2451,7 +2453,8 @@ fn delivered(body: serde_json::Value) -> SendOutcome { SendOutcome::Delivered(pc_gateway_transport::RawResponse { status: 200, content_type: "application/json".into(), - ttft_ms: None, + response_first_byte_ms: None, + response_complete_ms: None, body: bytes::Bytes::from(body.to_string()), usage: None, }) @@ -2866,3 +2869,421 @@ async fn a_hosted_tool_response_is_terminal_but_a_client_tool_call_is_not() { ); assert_eq!(transcript["assistant"], "found it"); } + +#[tokio::test] +async fn terminal_evidence_covers_zero_send_release_refusal_and_paid_possibility() { + use pc_gateway_evidence::{EvidenceEvent, Sending, Terminal}; + for (case, expected_terminal, expected_send, expected_attempts) in [ + ("block", Terminal::Blocked, Sending::NoSend, 0), + ("withhold", Terminal::Withheld, Sending::NoSend, 0), + ("expired", Terminal::AdmissionExpired, Sending::NoSend, 0), + ( + "release_block", + Terminal::Blocked, + Sending::ResponseReceived, + 1, + ), + ( + "release_withhold", + Terminal::Withheld, + Sending::ResponseReceived, + 1, + ), + ( + "release_expired", + Terminal::AdmissionExpired, + Sending::ResponseReceived, + 1, + ), + ( + "released", + Terminal::ReleaseAuthorized, + Sending::ResponseReceived, + 1, + ), + ( + "upstream_error", + Terminal::ReleaseAuthorized, + Sending::ResponseReceived, + 1, + ), + ("not_sent", Terminal::NotSent, Sending::DefinitelyNotSent, 1), + ( + "indeterminate", + Terminal::SendIndeterminate, + Sending::PossiblySent, + 1, + ), + ("gate_error", Terminal::GatePaused, Sending::NoSend, 0), + ("degraded", Terminal::Degraded, Sending::ResponseReceived, 1), + ] { + let mut admission = result( + CheckPhase::BeforeSend, + if case == "block" { + CheckDecision::Block + } else if case == "withhold" { + CheckDecision::Withhold + } else { + CheckDecision::Allow + }, + &[], + ); + let mut release = result( + CheckPhase::BeforeRelease, + if case == "release_block" { + CheckDecision::Block + } else if case == "release_withhold" { + CheckDecision::Withhold + } else { + CheckDecision::Allow + }, + &[], + ); + if case == "expired" { + admission.valid_until = "2000-01-01T00:00:00Z".into(); + } + if case == "release_expired" { + release.valid_until = "2000-01-01T00:00:00Z".into(); + } + let initial = if matches!(case, "gate_error" | "degraded") { + Err(GateError::GateUnavailable( + "SENSITIVE_PROVIDER_ERROR".into(), + )) + } else { + Ok(admission) + }; + let response = match case { + "not_sent" => SendOutcome::NotSent(pc_gateway_transport::NotSentReason::ConnectRefused), + "indeterminate" => SendOutcome::Indeterminate( + pc_gateway_transport::SendIndeterminateReason::LostAfterHandoff, + ), + "upstream_error" => { + let SendOutcome::Delivered(mut raw) = raw_response() else { + unreachable!() + }; + raw.status = 500; + SendOutcome::Delivered(raw) + } + _ => raw_response(), + }; + let (executor, renderer, _, _) = harness(vec![initial, Ok(release)], vec![response], 1); + let evidence = BufferedEvidenceSink::new(); + let control = request_control(); + let observation = control.observation(); + let outcome = executor + .run( + control, + call(if case == "degraded" { + DegradePolicy::PassthroughWithoutMemory + } else { + DegradePolicy::Pause + }), + &RendererRef(renderer), + &evidence, + ) + .await; + let calls = evidence.calls(); + assert_eq!(calls.len(), 1, "{case}"); + let record = &calls[0]; + assert_eq!(record.call_id, observation.call_id()); + assert_eq!(record.terminal, expected_terminal, "{case}"); + assert_eq!(record.sending, expected_send, "{case}"); + assert_eq!(record.attempts, expected_attempts, "{case}"); + assert!(record.upstream_ttft_ms.is_none()); + assert!( + record.usage.input.tokens.is_none(), + "total_tokens alone cannot establish input usage" + ); + let attempts: Vec<_> = evidence + .events() + .into_iter() + .filter_map(|event| { + if let EvidenceEvent::Attempt(a) = event { + Some(a) + } else { + None + } + }) + .collect(); + assert_eq!(attempts.len(), expected_attempts as usize, "{case}"); + for a in &attempts { + assert_eq!(a.call_id, record.call_id); + } + if case == "upstream_error" { + assert_eq!( + attempts[0].outcome, + pc_gateway_evidence::AttemptOutcome::UpstreamError + ); + } + if case == "gate_error" { + assert!(!format!("{outcome:?}").contains("SENSITIVE_PROVIDER_ERROR")); + } + } +} + +#[tokio::test] +async fn interrupted_model_send_keeps_paid_possibility_and_observed_stop_facts() { + use pc_gateway_evidence::{AttemptOutcome, EvidenceEvent, Interruption, Sending, Terminal}; + for (stop, expected) in [ + ("cancel", Interruption::CancellationRequested), + ("deadline", Interruption::DeadlineElapsed), + ("drop", Interruption::FutureDropped), + ] { + let (executor, renderer, transport, _) = harness( + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Allow, + &[], + ))], + vec![raw_response()], + 1, + ); + transport + .send_holds + .lock() + .unwrap() + .push_back(Some(Arc::new(tokio::sync::Notify::new()))); + let evidence = BufferedEvidenceSink::new(); + let control = RequestControl::new( + tokio::time::Instant::now() + + if stop == "deadline" { + std::time::Duration::ZERO + } else { + std::time::Duration::from_secs(30) + }, + None, + ); + let cancellation = control.cancellation(); + let renderer = RendererRef(renderer); + let mut future = + Box::pin(executor.run(control, call(DegradePolicy::Pause), &renderer, &evidence)); + assert!( + std::future::poll_fn(|cx| std::task::Poll::Ready(future.as_mut().poll(cx))) + .await + .is_pending() + ); + if stop == "cancel" { + cancellation.cancel(); + } + drop(future); + let record = &evidence.calls()[0]; + assert_eq!(record.terminal, Terminal::Abandoned); + assert_eq!(record.sending, Sending::PossiblySent); + assert_eq!(record.interruption, Some(expected)); + let EvidenceEvent::Attempt(attempt) = &evidence.events()[0] else { + panic!("missing attempt") + }; + assert_eq!(attempt.outcome, AttemptOutcome::PossiblySent); + assert_eq!(attempt.call_id, record.call_id); + assert!(record.usage.input.tokens.is_none()); + } +} + +#[tokio::test] +async fn readmission_evidence_keeps_each_real_attempt_and_release_order() { + use pc_gateway_evidence::{AttemptOutcome, EvidenceEvent}; + let (executor, renderer, _, gate) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result(CheckPhase::BeforeRelease, CheckDecision::Allow, &[])), + ], + vec![ + SendOutcome::NotSent(pc_gateway_transport::NotSentReason::RejectedLocally), + raw_response(), + ], + 2, + ); + let hold = Arc::new(tokio::sync::Notify::new()); + gate.check_holds + .lock() + .unwrap() + .extend([None, None, Some(hold.clone())]); + let evidence = BufferedEvidenceSink::new(); + let renderer = RendererRef(renderer); + let mut future = Box::pin(executor.run( + request_control(), + call(DegradePolicy::Pause), + &renderer, + &evidence, + )); + assert!( + std::future::poll_fn(|cx| std::task::Poll::Ready(future.as_mut().poll(cx))) + .await + .is_pending() + ); + assert!(evidence.calls().is_empty(), "release decision is pending"); + let attempts: Vec<_> = evidence + .events() + .into_iter() + .filter_map(|e| { + if let EvidenceEvent::Attempt(a) = e { + Some(a) + } else { + None + } + }) + .collect(); + assert_eq!( + attempts.iter().map(|a| a.outcome).collect::>(), + [AttemptOutcome::RejectedLocally, AttemptOutcome::Delivered] + ); + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + hold.notify_one(); + assert!(matches!(future.await, ManagedOutcome::Released { .. })); + let record = &evidence.calls()[0]; + assert_eq!(record.attempts, 2); + assert_eq!(record.call_id, attempts[0].call_id); + assert_eq!(record.call_id, attempts[1].call_id); + assert!(record.release_decision_ms.unwrap() >= 20); + assert!(record.release_authorized_ms.unwrap() >= record.release_decision_ms.unwrap()); + assert!(record.duration_ms >= record.release_authorized_ms.unwrap()); +} + +struct EvidenceFaultWriter { + entered: std::sync::mpsc::Sender<()>, + resume: Option>, +} +impl std::io::Write for EvidenceFaultWriter { + fn write(&mut self, _bytes: &[u8]) -> std::io::Result { + let _ = self.entered.send(()); + if let Some(resume) = self.resume.take() { + resume.recv().unwrap(); + } + Err(std::io::Error::other("SENSITIVE_WRITER_ERROR")) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +#[tokio::test] +async fn failing_or_blocked_full_evidence_output_cannot_change_release_or_cancellation() { + use pc_gateway_evidence::JsonEvidenceSink; + for blocked_writer in [false, true] { + let (entered_tx, entered_rx) = std::sync::mpsc::channel(); + let (resume_tx, resume_rx) = std::sync::mpsc::channel(); + let sink = JsonEvidenceSink::new( + EvidenceFaultWriter { + entered: entered_tx, + resume: blocked_writer.then_some(resume_rx), + }, + std::num::NonZeroUsize::new(1).unwrap(), + ) + .unwrap(); + let (executor, renderer, _, _) = harness(allow_runs(1), vec![raw_response()], 1); + let outcome = executor + .run( + request_control(), + call(DegradePolicy::Pause), + &RendererRef(renderer), + &sink, + ) + .await; + assert!(matches!(outcome, ManagedOutcome::Released { .. })); + entered_rx + .recv_timeout(std::time::Duration::from_secs(3)) + .unwrap(); + let (executor, renderer, transport, _) = harness( + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Allow, + &[], + ))], + vec![raw_response()], + 1, + ); + transport + .send_holds + .lock() + .unwrap() + .push_back(Some(Arc::new(tokio::sync::Notify::new()))); + let control = request_control(); + let observation = control.observation(); + let cancellation = control.cancellation(); + let renderer = RendererRef(renderer); + let mut future = + Box::pin(executor.run(control, call(DegradePolicy::Pause), &renderer, &sink)); + assert!( + std::future::poll_fn(|cx| std::task::Poll::Ready(future.as_mut().poll(cx))) + .await + .is_pending() + ); + cancellation.cancel(); + drop(future); + assert_eq!( + observation.snapshot().model_send, + ModelSendState::PossiblySent + ); + assert_eq!( + observation.snapshot().execution, + ExecutionState::Finished(ExecutionTerminal::Abandoned) + ); + let (executor, renderer, _, _) = harness( + vec![ + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])), + Ok(result( + CheckPhase::BeforeRelease, + CheckDecision::Withhold, + &[], + )), + ], + vec![raw_response()], + 1, + ); + assert!(matches!( + executor + .run( + request_control(), + call(DegradePolicy::Pause), + &RendererRef(renderer), + &sink + ) + .await, + ManagedOutcome::Withheld { .. } + )); + if blocked_writer { + assert!(sink.stats().dropped > 0); + resume_tx.send(()).unwrap(); + } + } +} + +#[tokio::test] +async fn partial_response_facts_survive_without_claiming_complete_delivery_or_usage() { + let (executor, renderer, _, _) = harness( + vec![Ok(result( + CheckPhase::BeforeSend, + CheckDecision::Allow, + &[], + ))], + vec![SendOutcome::IncompleteResponse { + reason: pc_gateway_transport::SendIndeterminateReason::BufferLimitExceeded, + status: 429, + response_first_byte_ms: Some(17), + }], + 2, + ); + let evidence = BufferedEvidenceSink::new(); + assert!(matches!( + executor + .run( + request_control(), + call(DegradePolicy::Pause), + &RendererRef(renderer), + &evidence + ) + .await, + ManagedOutcome::SendIndeterminate + )); + let call = &evidence.calls()[0]; + assert_eq!(call.attempts, 1); + assert_eq!(call.sending, pc_gateway_evidence::Sending::PossiblySent); + assert_eq!(call.upstream_status, Some(429)); + let pc_gateway_evidence::EvidenceEvent::Attempt(attempt) = &evidence.events()[0] else { + panic!("missing attempt") + }; + assert_eq!(attempt.response_first_byte_ms, Some(17)); + assert!(attempt.response_complete_ms.is_none()); + assert!(call.usage.input.tokens.is_none()); +} diff --git a/gateway/crates/pc-gateway-evidence/src/lib.rs b/gateway/crates/pc-gateway-evidence/src/lib.rs index 9f657d16ef..8243f4ed66 100644 --- a/gateway/crates/pc-gateway-evidence/src/lib.rs +++ b/gateway/crates/pc-gateway-evidence/src/lib.rs @@ -12,104 +12,281 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! 证据适配层。 -//! -//! RFC 约束:归一化实际目标身份、usage 完整性、供应商缓存 read/write、 -//! 失败尝试与延迟;分别报告上游首 token 与首次内容释放时间; -//! **绝不记录 query/prompt/响应正文/凭据**;执行身份不进指标标签。 -//! 已知 / 估算 / 未知 / 对账用量分开记录,不可用标 unknown 不记零。 +//! Bounded, body-free execution evidence. This is best-effort telemetry, not a ledger. +mod output; +pub use output::{EvidenceStats, JsonEvidenceSink}; use serde::{Deserialize, Serialize}; -/// usage 完整性:不把缺失当零。 -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum UsageCompleteness { Known, Estimated, + #[default] Unknown, Reconciled, } -/// 单次调用的无正文证据记录。 +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TokenUsage { + pub tokens: Option, + pub completeness: UsageCompleteness, +} + +impl TokenUsage { + fn observed(value: Option<&serde_json::Value>) -> Self { + match value.and_then(serde_json::Value::as_u64) { + Some(tokens) => Self { + tokens: Some(tokens), + completeness: UsageCompleteness::Known, + }, + None => Self::default(), + } + } +} + +/// OpenAI input counts INCLUDE cache reads. Cache counts are subsets, never added to input. +/// No inference from totals, no zero-filling, no Anthropic/other-provider guessing. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct UsageEvidence { + pub input: TokenUsage, + pub output: TokenUsage, + pub cache_read: TokenUsage, + pub cache_write: TokenUsage, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum UsageMapping { + OpenAiChat, + OpenAiResponses, +} + +impl UsageEvidence { + pub fn openai(raw: Option<&serde_json::Value>, mapping: UsageMapping) -> Self { + let Some(raw) = raw else { + return Self::default(); + }; + let (input, output, details) = match mapping { + UsageMapping::OpenAiChat => ( + "prompt_tokens", + "completion_tokens", + "prompt_tokens_details", + ), + UsageMapping::OpenAiResponses => { + ("input_tokens", "output_tokens", "input_tokens_details") + } + }; + Self { + input: TokenUsage::observed(raw.get(input)), + output: TokenUsage::observed(raw.get(output)), + cache_read: TokenUsage::observed(raw.get(details).and_then(|v| v.get("cached_tokens"))), + // These OpenAI contracts expose no cache-write token count. + cache_write: TokenUsage::default(), + } + } +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Sending { + #[default] + NoSend, + DefinitelyNotSent, + PossiblySent, + ResponseReceived, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Terminal { + ReleaseAuthorized, + Blocked, + Withheld, + SendIndeterminate, + NotSent, + GatePaused, + Degraded, + AdmissionExpired, + #[default] + Abandoned, +} + +/// Facts observed on future drop; neither intent nor elapsed deadline proves its cause. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Interruption { + CancellationRequested, + DeadlineElapsed, + FutureDropped, +} + #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct CallEvidence { - /// 实际发送目标身份(归一化后),不是客户端声称的目标。 - pub actual_target: Option, - pub completeness: Option, - pub input_tokens: Option, - pub output_tokens: Option, - pub cache_read_tokens: Option, - pub cache_write_tokens: Option, + pub call_id: String, + /// Process-local keyed fingerprint of the bound request ID; absent without host correlation. + pub request_id_fingerprint: Option, + /// Fingerprint of the actual transport URL. Never a URL, profile, model or credential. + pub target_fingerprint: String, + pub usage_mapping: Option, + pub terminal: Terminal, + pub sending: Sending, + pub interruption: Option, pub attempts: u32, - /// 上游首 token 延迟(毫秒)。 + pub usage: UsageEvidence, + pub upstream_status: Option, + /// Elapsed from call start (monotonic milliseconds). + pub duration_ms: u64, + pub release_decision_ms: Option, + pub release_authorized_ms: Option, + /// Unavailable with the current fully buffered transport, including non-streaming Responses. pub upstream_ttft_ms: Option, - /// 首次内容释放延迟(毫秒)。strict 模式下必然晚于 ttft。 - pub first_release_ms: Option, - /// 失败原因类别(无正文)。 - pub failure_reason: Option, } -/// 证据下沉抽象。实现可以是空对象(观测可选), -/// 借鉴 TensorZero 的 disabled client 模式。 +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AttemptOutcome { + #[default] + PossiblySent, + Delivered, + UpstreamError, + ConnectRefused, + RejectedLocally, + LostAfterHandoff, + TimeoutAwaitingResponse, + BufferLimitExceeded, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct AttemptEvidence { + pub call_id: String, + pub attempt: u32, + pub outcome: AttemptOutcome, + /// Call-relative send handoff time; the following durations start at that handoff. + pub started_ms: u64, + pub duration_ms: u64, + pub response_first_byte_ms: Option, + pub response_complete_ms: Option, + pub upstream_status: Option, + pub usage: UsageEvidence, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum DeliveryBoundary { + FrameworkHandoff, + FirstBodyFrame, + BodyCompleted, + BodyDropped, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct DeliveryEvidence { + pub call_id: String, + pub boundary: DeliveryBoundary, + pub elapsed_ms: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "event", content = "evidence", rename_all = "snake_case")] +pub enum EvidenceEvent { + Call(CallEvidence), + Attempt(AttemptEvidence), + Delivery(DeliveryEvidence), +} + +/// Synchronous submissions MUST be bounded, nonblocking and non-I/O. +/// Use JsonEvidenceSink to isolate arbitrary I/O on a dedicated bounded worker. pub trait EvidenceSink: Send + Sync { - fn record_attempt(&self, attempt: u32); - fn record_not_sent(&self, attempt: u32, reason: &str); + // Legacy test/demo diagnostics. Not exported by the production sink. + fn record_attempt(&self, _attempt: u32) {} + fn record_not_sent(&self, _attempt: u32, _reason: &str) {} fn record_call(&self, evidence: &CallEvidence); + fn record_attempt_evidence(&self, _evidence: &AttemptEvidence) {} + fn record_delivery(&self, _evidence: &DeliveryEvidence) {} } -/// 空对象实现:观测关闭时使用。 #[derive(Debug, Default, Clone, Copy)] pub struct NoopEvidenceSink; - impl EvidenceSink for NoopEvidenceSink { - fn record_attempt(&self, _attempt: u32) {} - fn record_not_sent(&self, _attempt: u32, _reason: &str) {} fn record_call(&self, _evidence: &CallEvidence) {} } -/// 内存缓冲实现:测试与本地演示用;不落盘、不落正文。 +/// Unbounded test/demo collector; never compose this into a production host. #[derive(Debug, Default)] pub struct BufferedEvidenceSink { attempts: std::sync::Mutex>, not_sent: std::sync::Mutex>, calls: std::sync::Mutex>, + events: std::sync::Mutex>, } - impl BufferedEvidenceSink { pub fn new() -> Self { Self::default() } - pub fn attempts(&self) -> Vec { - self.attempts.lock().expect("evidence lock").clone() + self.attempts.lock().unwrap().clone() } - pub fn not_sent(&self) -> Vec<(u32, String)> { - self.not_sent.lock().expect("evidence lock").clone() + self.not_sent.lock().unwrap().clone() } - pub fn calls(&self) -> Vec { - self.calls.lock().expect("evidence lock").clone() + self.calls.lock().unwrap().clone() + } + pub fn events(&self) -> Vec { + self.events.lock().unwrap().clone() } } - impl EvidenceSink for BufferedEvidenceSink { fn record_attempt(&self, attempt: u32) { - self.attempts.lock().expect("evidence lock").push(attempt); + self.attempts.lock().unwrap().push(attempt); } - fn record_not_sent(&self, attempt: u32, reason: &str) { self.not_sent .lock() - .expect("evidence lock") - .push((attempt, reason.to_string())); + .unwrap() + .push((attempt, reason.to_owned())); } - fn record_call(&self, evidence: &CallEvidence) { - self.calls + self.calls.lock().unwrap().push(evidence.clone()); + self.events + .lock() + .unwrap() + .push(EvidenceEvent::Call(evidence.clone())); + } + fn record_attempt_evidence(&self, evidence: &AttemptEvidence) { + self.events + .lock() + .unwrap() + .push(EvidenceEvent::Attempt(evidence.clone())); + } + fn record_delivery(&self, evidence: &DeliveryEvidence) { + self.events .lock() - .expect("evidence lock") - .push(evidence.clone()); + .unwrap() + .push(EvidenceEvent::Delivery(evidence.clone())); } } + +/// Keyed, process-local correlation avoids exporting arbitrary host strings or URLs. +/// Not a durable identity or cryptographic anonymization guarantee. +pub fn fingerprint(value: &str) -> String { + use std::hash::{BuildHasher, Hasher}; + static KEY: std::sync::OnceLock = + std::sync::OnceLock::new(); + let mut hasher = KEY.get_or_init(Default::default).build_hasher(); + hasher.write(value.as_bytes()); + format!("{:016x}", hasher.finish()) +} + +pub fn new_call_id() -> String { + use std::sync::atomic::{AtomicU64, Ordering}; + static SEQUENCE: AtomicU64 = AtomicU64::new(0); + static INSTANCE: std::sync::OnceLock = std::sync::OnceLock::new(); + let instance = INSTANCE.get_or_init(|| fingerprint("gateway-evidence-instance")); + format!( + "{instance}-{:016x}", + SEQUENCE.fetch_add(1, Ordering::Relaxed) + ) +} diff --git a/gateway/crates/pc-gateway-evidence/src/output.rs b/gateway/crates/pc-gateway-evidence/src/output.rs new file mode 100644 index 0000000000..62a0064045 --- /dev/null +++ b/gateway/crates/pc-gateway-evidence/src/output.rs @@ -0,0 +1,142 @@ +// 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. + +use crate::{AttemptEvidence, CallEvidence, DeliveryEvidence, EvidenceEvent, EvidenceSink}; +use serde::Serialize; +use std::io::Write; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{mpsc, Arc}; + +#[derive(Debug, Clone, Copy, Default, Serialize)] +pub struct EvidenceStats { + pub dropped: u64, + pub write_failed: u64, + pub written: u64, +} + +#[derive(Default)] +struct Counters { + dropped: AtomicU64, + write_failed: AtomicU64, + written: AtomicU64, +} +impl Counters { + fn snapshot(&self) -> EvidenceStats { + EvidenceStats { + dropped: self.dropped.load(Ordering::Relaxed), + write_failed: self.write_failed.load(Ordering::Relaxed), + written: self.written.load(Ordering::Relaxed), + } + } +} + +/// Fixed-capacity, drop-newest JSON-lines exporter. One worker owns all blocking writes. +/// Drop never joins a possibly blocked writer. At process exit pending records can be lost. +/// A record is at most 4096 serialized bytes; at most capacity queued records plus one in flight. +pub struct JsonEvidenceSink { + sender: mpsc::SyncSender, + counters: Arc, +} + +impl JsonEvidenceSink { + pub fn new( + writer: impl Write + Send + 'static, + capacity: std::num::NonZeroUsize, + ) -> std::io::Result { + let (sender, receiver) = mpsc::sync_channel::(capacity.get()); + let counters = Arc::new(Counters::default()); + let worker_counters = counters.clone(); + std::thread::Builder::new() + .name("gateway-evidence".into()) + .spawn(move || { + let mut writer = writer; + let mut recover_line = false; + for event in receiver { + #[derive(Serialize)] + struct Envelope<'a> { + schema: &'static str, + operation: &'static str, + unit: &'static str, + #[serde(flatten)] + event: &'a EvidenceEvent, + loss: EvidenceStats, + } + let envelope = Envelope { + schema: "powercontext.gateway-evidence.v1", + operation: "gateway.model_call", + unit: match event { + EvidenceEvent::Call(_) => "call", + EvidenceEvent::Attempt(_) => "attempt", + EvidenceEvent::Delivery(_) => "delivery", + }, + event: &event, + loss: worker_counters.snapshot(), + }; + // Never stringify writer errors. Custom writers must not panic. + // After a partial failure, restore a line boundary before the next record. + let result = serde_json::to_vec(&envelope) + .ok() + .filter(|line| line.len() < 4096) + .and_then(|mut line| { + line.push(b'\n'); + if recover_line && writer.write_all(b"\n").is_err() { + return None; + } + writer.write_all(&line).and_then(|_| writer.flush()).ok() + }); + recover_line = result.is_none(); + if result.is_some() { + worker_counters.written.fetch_add(1, Ordering::Relaxed); + } else { + worker_counters.write_failed.fetch_add(1, Ordering::Relaxed); + } + } + })?; + Ok(Self { sender, counters }) + } + + pub fn stats(&self) -> EvidenceStats { + self.counters.snapshot() + } + + fn submit(&self, event: EvidenceEvent) { + // The producer supplies only bounded typed records. Reject oversized caller strings + // before queueing; neither raw fields nor legacy diagnostics are exported. + let valid_id = + |id: &str| id.len() <= 64 && id.bytes().all(|b| b.is_ascii_hexdigit() || b == b'-'); + let valid = match &event { + EvidenceEvent::Call(e) => { + valid_id(&e.call_id) + && valid_id(&e.target_fingerprint) + && e.request_id_fingerprint.as_deref().is_none_or(valid_id) + } + EvidenceEvent::Attempt(e) => valid_id(&e.call_id), + EvidenceEvent::Delivery(e) => valid_id(&e.call_id), + }; + if !valid || self.sender.try_send(event).is_err() { + self.counters.dropped.fetch_add(1, Ordering::Relaxed); + } + } +} +impl EvidenceSink for JsonEvidenceSink { + fn record_call(&self, evidence: &CallEvidence) { + self.submit(EvidenceEvent::Call(evidence.clone())); + } + fn record_attempt_evidence(&self, evidence: &AttemptEvidence) { + self.submit(EvidenceEvent::Attempt(evidence.clone())); + } + fn record_delivery(&self, evidence: &DeliveryEvidence) { + self.submit(EvidenceEvent::Delivery(evidence.clone())); + } +} diff --git a/gateway/crates/pc-gateway-evidence/tests/output.rs b/gateway/crates/pc-gateway-evidence/tests/output.rs new file mode 100644 index 0000000000..837af60846 --- /dev/null +++ b/gateway/crates/pc-gateway-evidence/tests/output.rs @@ -0,0 +1,183 @@ +// 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. + +use pc_gateway_evidence::*; +use std::io::{self, Write}; +use std::num::NonZeroUsize; +use std::sync::{mpsc, Arc, Mutex}; +use std::time::{Duration, Instant}; + +#[derive(Clone, Default)] +struct Output(Arc>>); +impl Write for Output { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} +fn record() -> CallEvidence { + CallEvidence { + call_id: new_call_id(), + target_fingerprint: fingerprint("https://secret:credential@host/private"), + ..Default::default() + } +} +fn until(mut condition: impl FnMut() -> bool) { + let end = Instant::now() + Duration::from_secs(3); + while !condition() { + assert!(Instant::now() < end, "export did not complete"); + std::thread::sleep(Duration::from_millis(1)); + } +} + +#[test] +fn readable_output_preserves_unknown_and_separates_cache_usage() { + let output = Output::default(); + let sink = JsonEvidenceSink::new(output.clone(), NonZeroUsize::new(2).unwrap()).unwrap(); + let mut call = record(); + call.usage = UsageEvidence::openai( + Some(&serde_json::json!({ + "input_tokens": 100, "output_tokens": 7, "input_tokens_details": {"cached_tokens": 60}, + "cache_creation_input_tokens": 999, "secret": "SYNTHETIC_SENSITIVE_USAGE" + })), + UsageMapping::OpenAiResponses, + ); + call.request_id_fingerprint = Some(fingerprint("SYNTHETIC_SECRET_REQUEST_ID")); + sink.record_call(&call); + sink.record_not_sent(0, "SYNTHETIC_SECRET_PROVIDER_EXCEPTION"); + until(|| sink.stats().written == 1); + let bytes = output.0.lock().unwrap().clone(); + let text = String::from_utf8(bytes).unwrap(); + for marker in [ + "SYNTHETIC", + "credential", + "/private", + "cache_creation_input_tokens", + ] { + assert!(!text.contains(marker)); + } + let value: serde_json::Value = serde_json::from_str(text.trim()).unwrap(); + assert_eq!(value["schema"], "powercontext.gateway-evidence.v1"); + assert_eq!(value["evidence"]["usage"]["input"]["tokens"], 100); + assert_eq!(value["evidence"]["usage"]["cache_read"]["tokens"], 60); + assert_eq!( + value["evidence"]["usage"]["cache_write"]["completeness"], + "unknown" + ); + assert!(value["evidence"]["usage"]["cache_write"]["tokens"].is_null()); + assert!(value["evidence"]["upstream_ttft_ms"].is_null()); + assert_eq!( + UsageEvidence::openai(None, UsageMapping::OpenAiChat), + UsageEvidence::default() + ); +} + +struct SlowWriter { + started: mpsc::Sender<()>, + resume: mpsc::Receiver<()>, + output: Output, + first: bool, +} +impl Write for SlowWriter { + fn write(&mut self, bytes: &[u8]) -> io::Result { + if self.first { + self.first = false; + self.started.send(()).unwrap(); + self.resume.recv().unwrap(); + } + self.output.write(bytes) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[test] +fn blocked_writer_keeps_a_fixed_budget_and_reports_overflow() { + let (started_tx, started_rx) = mpsc::channel(); + let (resume_tx, resume_rx) = mpsc::channel(); + let output = Output::default(); + let sink = JsonEvidenceSink::new( + SlowWriter { + started: started_tx, + resume: resume_rx, + output: output.clone(), + first: true, + }, + NonZeroUsize::new(4).unwrap(), + ) + .unwrap(); + sink.record_call(&record()); + started_rx.recv_timeout(Duration::from_secs(3)).unwrap(); + // The writer is held for this entire burst. Only four queued records may survive. + for _ in 0..100_000 { + sink.record_call(&record()); + } + assert_eq!(sink.stats().dropped, 99_996); + assert_eq!(sink.stats().written, 0); + resume_tx.send(()).unwrap(); + until(|| sink.stats().written == 5); + let text = String::from_utf8(output.0.lock().unwrap().clone()).unwrap(); + assert_eq!(text.lines().count(), 5); + assert!(text + .lines() + .skip(1) + .any( + |line| serde_json::from_str::(line).unwrap()["loss"]["dropped"] + == 99_996 + )); +} + +struct FailingWriter { + failed: bool, + output: Output, +} +impl Write for FailingWriter { + fn write(&mut self, bytes: &[u8]) -> io::Result { + if !self.failed { + self.failed = true; + return Err(io::Error::other("SYNTHETIC_SECRET_IO_ERROR")); + } + self.output.write(bytes) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[test] +fn writer_errors_are_isolated_counted_and_never_serialized() { + let output = Output::default(); + let sink = JsonEvidenceSink::new( + FailingWriter { + failed: false, + output: output.clone(), + }, + NonZeroUsize::new(2).unwrap(), + ) + .unwrap(); + sink.record_call(&record()); + until(|| sink.stats().write_failed == 1); + sink.record_call(&record()); + until(|| sink.stats().written == 1); + let text = String::from_utf8(output.0.lock().unwrap().clone()).unwrap(); + assert!(!text.contains("SYNTHETIC_SECRET")); + assert_eq!( + serde_json::from_str::(&text).unwrap()["loss"]["write_failed"], + 1 + ); +} diff --git a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs index fb4c299778..950915e225 100644 --- a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs +++ b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs @@ -24,7 +24,7 @@ use std::time::{Duration, Instant}; /// 结果映射(对齐 RFC 失败语义): /// - 连接失败/请求构造失败 → 确定性 NotSent(可重试); /// - 发送后连接丢失、超时、解码中断 → Indeterminate(不自动重发); -/// - 流式接收:逐块读入(计量 TTFT、字节数受 `max_buffer_bytes` 上限), +/// - 流式接收:逐块读入(计量首字节延迟、字节数受 `max_buffer_bytes` 上限), /// strict 语义不变——完整缓冲后仍需过 before_release 才释放。 #[derive(Debug, Clone)] pub struct ReqwestTransport { @@ -72,6 +72,7 @@ impl Transport for ReqwestTransport { if !has_content_type { req = req.header("content-type", "application/json"); } + let start = Instant::now(); let resp = match req.body(send.payload.to_vec()).send().await { Err(e) => { // NotSent 仅限于「可证明发生在传输之前」的失败: @@ -103,39 +104,44 @@ impl Transport for ReqwestTransport { // 两种接收模式共用逐块累积 + 字节上限(review P2:非流式路径 // 此前用 resp.bytes() 一次性收集,max_buffer_bytes 完全不生效)。 - // 区别仅在计量:流式记录 TTFT。 - let start = Instant::now(); + // 首字节是 HTTP 正文的首个非空 chunk,不是模型首 token。 let mut body: Vec = Vec::with_capacity(16 * 1024); - let mut ttft: Option = None; + let mut first_byte: Option = None; let mut stream = resp.bytes_stream(); loop { match next_chunk(&mut stream).await { None => break, Some(Err(_)) => { - return SendOutcome::Indeterminate( - SendIndeterminateReason::LostAfterHandoff, - ) + return SendOutcome::IncompleteResponse { + reason: SendIndeterminateReason::LostAfterHandoff, + status, + response_first_byte_ms: first_byte, + } } Some(Ok(chunk)) => { - if send.stream && ttft.is_none() { - ttft = Some(start.elapsed().as_millis() as u64); + if !chunk.is_empty() && first_byte.is_none() { + first_byte = Some(start.elapsed().as_millis() as u64); } if body.len() + chunk.len() > self.max_buffer_bytes { // 已送达且部分计费:不重发,向上标记不确定。 - return SendOutcome::Indeterminate( - SendIndeterminateReason::BufferLimitExceeded, - ); + return SendOutcome::IncompleteResponse { + reason: SendIndeterminateReason::BufferLimitExceeded, + status, + response_first_byte_ms: first_byte, + }; } body.extend_from_slice(&chunk); } } } - let usage = extract_usage(&body); + let complete_ms = start.elapsed().as_millis() as u64; + let usage = extract_usage(&body, &content_type); SendOutcome::Delivered(RawResponse { status, body: Bytes::from(body), content_type, - ttft_ms: ttft, + response_first_byte_ms: first_byte, + response_complete_ms: Some(complete_ms), usage, }) }) @@ -148,19 +154,45 @@ impl Transport for ReqwestTransport { } } -fn extract_usage(body: &[u8]) -> Option { - serde_json::from_slice::(body) - .ok() - .and_then(|v| v.get("usage").cloned()) +fn extract_usage(body: &[u8], content_type: &str) -> Option { + if !content_type.starts_with("text/event-stream") { + return serde_json::from_slice::(body) + .ok() + .and_then(|v| v.get("usage").filter(|v| v.is_object()).cloned()); + } + // Usage-only Chat chunks and Responses terminal events. Do not infer missing usage. + // Join multi-line SSE data, reset at blank lines, and retain only the latest usage. + let text = std::str::from_utf8(body).ok()?; + let mut data = String::new(); + let mut usage = None; + for line in text.lines().chain(std::iter::once("")) { + if line.is_empty() { + if let Ok(value) = serde_json::from_str::(&data) { + let found = value + .get("usage") + .or_else(|| value.get("response")?.get("usage")); + if let Some(found) = found.filter(|v| v.is_object()) { + usage = Some(found.clone()); + } + } + data.clear(); + } else if let Some(line) = line.strip_prefix("data:") { + if !data.is_empty() { + data.push('\n'); + } + data.push_str(line.strip_prefix(' ').unwrap_or(line)); + } + } + usage } /// 不引入 futures-util 依赖的 next():用标准库 poll_fn 轮询 Stream。 -async fn next_chunk(stream: &mut S) -> Option> +async fn next_chunk(stream: &mut S) -> Option> where S: futures_core::Stream> + Unpin, { use std::pin::Pin; std::future::poll_fn(|cx| Pin::new(&mut *stream).poll_next(cx)) .await - .map(|r| r.map_err(|e| e.to_string())) + .map(|r| r.map_err(|_| ())) } diff --git a/gateway/crates/pc-gateway-transport/src/retry.rs b/gateway/crates/pc-gateway-transport/src/retry.rs index e2ddb91910..39ca5c2b67 100644 --- a/gateway/crates/pc-gateway-transport/src/retry.rs +++ b/gateway/crates/pc-gateway-transport/src/retry.rs @@ -54,9 +54,9 @@ impl BoundedRetry { evidence.record_attempt(attempt); match self.transport.send(send.clone()).await { // 可能已送达:立即上抛,不做任何自动重发。 - outcome @ SendOutcome::Indeterminate(_) | outcome @ SendOutcome::Delivered(_) => { - return RetryOutcome::Done(outcome) - } + outcome @ SendOutcome::Indeterminate(_) + | outcome @ SendOutcome::IncompleteResponse { .. } + | outcome @ SendOutcome::Delivered(_) => return RetryOutcome::Done(outcome), SendOutcome::NotSent(reason) => { if attempt >= self.max_attempts.get() { evidence.record_not_sent(attempt, &reason.to_string()); diff --git a/gateway/crates/pc-gateway-transport/src/sender.rs b/gateway/crates/pc-gateway-transport/src/sender.rs index 1b3d562092..88559dc852 100644 --- a/gateway/crates/pc-gateway-transport/src/sender.rs +++ b/gateway/crates/pc-gateway-transport/src/sender.rs @@ -37,8 +37,10 @@ pub struct RawResponse { pub body: Bytes, /// 响应的 Content-Type(SSE 为 text/event-stream),释放时原样使用。 pub content_type: String, - /// 上游首字节延迟(毫秒);流式接收时计量,非流式为 None。 - pub ttft_ms: Option, + /// Send handoff to first nonempty HTTP body chunk, including response-header wait. Not model TTFT. + pub response_first_byte_ms: Option, + /// Send handoff to complete buffered response, in monotonic milliseconds. + pub response_complete_ms: Option, /// usage 证据(不可用时为 None,标记 unknown,不记零)。 pub usage: Option, } @@ -52,6 +54,12 @@ pub enum SendOutcome { NotSent(NotSentReason), /// 可能已到达上游:返回不确定,不自动付费重发,不假设退费。 Indeterminate(SendIndeterminateReason), + /// Headers/partial body observed, but no complete response. Still never retry. + IncompleteResponse { + reason: SendIndeterminateReason, + status: u16, + response_first_byte_ms: Option, + }, } #[derive(Debug, thiserror::Error)] 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 2116a50d5d..50d104eb03 100644 --- a/gateway/crates/pc-gateway-transport/tests/buffer_limit_nonstreaming.rs +++ b/gateway/crates/pc-gateway-transport/tests/buffer_limit_nonstreaming.rs @@ -56,7 +56,14 @@ async fn nonstreaming_response_over_buffer_limit_is_rejected() { }; let outcome = transport.send(send).await; match outcome { - SendOutcome::Indeterminate(SendIndeterminateReason::BufferLimitExceeded) => {} + SendOutcome::IncompleteResponse { + reason: SendIndeterminateReason::BufferLimitExceeded, + status, + response_first_byte_ms, + } => { + assert_eq!(status, 200); + assert!(response_first_byte_ms.is_some()); + } other => panic!("expected Indeterminate(BufferLimitExceeded), got {other:?}"), } } diff --git a/gateway/crates/pc-gateway-transport/tests/usage_timing.rs b/gateway/crates/pc-gateway-transport/tests/usage_timing.rs new file mode 100644 index 0000000000..48b7839545 --- /dev/null +++ b/gateway/crates/pc-gateway-transport/tests/usage_timing.rs @@ -0,0 +1,95 @@ +// 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. + +//! Real HTTP transport fixtures; these are local providers, not hosted-model acceptance. +use pc_gateway_evidence::{UsageCompleteness, UsageEvidence, UsageMapping}; +use pc_gateway_transport::{AdmittedSend, ReqwestTransport, SendOutcome, Transport}; +use std::time::Duration; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; + +async fn response( + body: &'static str, + content_type: &'static str, +) -> pc_gateway_transport::RawResponse { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut buffer = [0; 4096]; + assert!(socket.read(&mut buffer).await.unwrap() > 0); + tokio::time::sleep(Duration::from_millis(40)).await; + socket.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()).as_bytes()).await.unwrap(); + let split = body.len() / 2; + socket.write_all(&body.as_bytes()[..split]).await.unwrap(); + tokio::time::sleep(Duration::from_millis(20)).await; + socket.write_all(&body.as_bytes()[split..]).await.unwrap(); + }); + let transport = ReqwestTransport::new(Duration::from_secs(5)); + let outcome = transport + .send(AdmittedSend { + binding: "test".into(), + payload: bytes::Bytes::from_static(b"{}"), + target_url: format!("http://{addr}/v1/responses"), + headers: vec![], + stream: content_type == "text/event-stream", + }) + .await; + server.await.unwrap(); + let SendOutcome::Delivered(raw) = outcome else { + panic!("fixture response not delivered") + }; + raw +} + +#[tokio::test] +async fn json_usage_and_first_body_byte_include_the_header_wait() { + let raw = response(r#"{"usage":{"input_tokens":100,"output_tokens":9,"input_tokens_details":{"cached_tokens":70}},"output":[]}"#, "application/json").await; + assert!( + raw.response_first_byte_ms.unwrap() >= 40, + "header wait belongs to send-to-first-byte latency" + ); + assert!(raw.response_complete_ms.unwrap() >= raw.response_first_byte_ms.unwrap() + 15); + let usage = UsageEvidence::openai(raw.usage.as_ref(), UsageMapping::OpenAiResponses); + assert_eq!(usage.input.tokens, Some(100)); + assert_eq!(usage.output.tokens, Some(9)); + assert_eq!(usage.cache_read.tokens, Some(70)); + assert_eq!(usage.cache_write.completeness, UsageCompleteness::Unknown); +} + +#[tokio::test] +async fn sse_usage_only_chunks_and_missing_usage_keep_their_distinct_meaning() { + let raw = response("data: {\"choices\":[{\"delta\":{\"content\":\"SENSITIVE\"}}]}\r\n\r\ndata: {\"usage\":{\"prompt_tokens\":80,\n\ndata: \"completion_tokens\":0,\"prompt_tokens_details\":{\"cached_tokens\":20}}}\n\ndata: [DONE]\n\n", "text/event-stream").await; + // The deliberately malformed multi-line event cannot establish usage. + assert!(raw.usage.is_none()); + let raw = response("data: {\"choices\":[]}\r\n\r\ndata: {\"usage\":{\"prompt_tokens\":80,\r\ndata: \"completion_tokens\":0,\"prompt_tokens_details\":{\"cached_tokens\":20}}}\r\n\r\ndata: [DONE]\r\n\r\n", "text/event-stream").await; + let usage = UsageEvidence::openai(raw.usage.as_ref(), UsageMapping::OpenAiChat); + assert_eq!(usage.input.tokens, Some(80)); + assert_eq!(usage.output.tokens, Some(0)); + assert_eq!(usage.output.completeness, UsageCompleteness::Known); + assert_eq!(usage.cache_read.tokens, Some(20)); + let raw = response( + "data: {\"choices\":[{\"delta\":{\"content\":\"SENSITIVE\"}}]}\n\ndata: [DONE]\n\n", + "text/event-stream", + ) + .await; + assert_eq!( + UsageEvidence::openai(raw.usage.as_ref(), UsageMapping::OpenAiChat), + UsageEvidence::default() + ); + let raw = response("event: response.completed\ndata: {\"response\":{\"usage\":{\"input_tokens\":7,\"output_tokens\":2}}}\n\n", "text/event-stream").await; + let usage = UsageEvidence::openai(raw.usage.as_ref(), UsageMapping::OpenAiResponses); + assert_eq!(usage.input.tokens, Some(7)); + assert!(usage.cache_read.tokens.is_none()); +} From cc5289e14f2bc01d4e6872fdef70123d348109d8 Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Fri, 6 Nov 2026 10:40:36 +0800 Subject: [PATCH 02/15] docs(gateway): record bounded evidence validation --- gateway/EVIDENCE_VALIDATION.md | 78 ++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 gateway/EVIDENCE_VALIDATION.md diff --git a/gateway/EVIDENCE_VALIDATION.md b/gateway/EVIDENCE_VALIDATION.md new file mode 100644 index 0000000000..1c631cfcf3 --- /dev/null +++ b/gateway/EVIDENCE_VALIDATION.md @@ -0,0 +1,78 @@ +# Gateway evidence validation / Gateway 证据验收 + +- Date / 日期: 2026-11-06. +- Implementation commit / 实现提交: `bffc3980bbece93c86948b62f70446d90b08affb`. +- Master base / master 基线: `69b2d7e2ac1aacc05f386d04d4616aa9254b3f5d`; fetched at start and rechecked before delivery. +- Platform / 平台: Darwin arm64, Rust `1.95.0 (59807616e 2026-04-14)`, Python 3.13.15. +- Scope / 范围: [#2463](https://github.com/oceanbase/powercontext/issues/2463), + [planning discussion / 规划讨论 #2433](https://github.com/oceanbase/powercontext/discussions/2433). +- G3-0 dependency / 依赖: [#2499](https://github.com/oceanbase/powercontext/pull/2499) is included in the base. + Pending execution destruction records abandonment plus cancellation/deadline observations; the owner still decides + when to stop the future. Cancellation intent and deadline passage alone do not interrupt execution. + pending 执行销毁时记录 abandoned 与取消/期限事实;仍由所有者决定何时停止 future,信号与期限本身不中断执行。 + +Related open PR snapshots checked / 已核查相关开放 PR 源码快照: + +| PR | Head | Relevant ownership / 相关职责 | +| --- | --- | --- | +| [#2470](https://github.com/oceanbase/powercontext/pull/2470) | `35ec28045b56c2e26cc5558e0edd642d0ddc45e3` | Native protocol behavior and ingress / 原生协议与入口 | +| [#2457](https://github.com/oceanbase/powercontext/pull/2457) | `a676623b8675468500181eb770cbc73a02d44415` | Protection modes and lifecycle facts / 保护模式与生命周期事实 | +| [#2435](https://github.com/oceanbase/powercontext/pull/2435) | `ce0e256f5a8367526b31ce749c5a5a20b1c2c2af` | Prefix capture and projection receipts / 前缀捕获与投影 receipt | + +These changes do not incorporate the unmerged PRs or reinterpret Source projection receipts as model usage. +本实现不包含这些未合并 PR,也不将 Source 投影 receipt 当作模型 usage。 + +## Commands and results / 命令与结果 + +Cargo was invoked through `/Users/lioky/.cargo/bin/cargo` because the shell's mise cargo shim had no selected version. +下列 Cargo 命令使用上述实际可执行文件运行,避免未选择版本的 mise shim。 + +| Command | Result / 结果 | +| --- | --- | +| `cargo fmt --manifest-path gateway/Cargo.toml --all --check` | Passed / 通过 | +| `cargo clippy --locked --manifest-path gateway/Cargo.toml --all-targets -- -D warnings` | Passed / 通过 | +| `cargo test --locked --manifest-path gateway/Cargo.toml --workspace` | 149 exercised behavior tests passed; 4 live-Core cases returned early / 149 个实际行为测试通过,4 个真实 Core 用例提前返回 | +| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-app --test evidence_process` | Real spawned Gateway, 1000 enabled + 100 disabled requests passed / 真实 Gateway 子进程,启用 1000 次与关闭 100 次请求通过 | +| `make check` | Passed, including lock/policy checks, hooks, types and 61 integration-manifest tests / 通过,包含锁文件/策略检查、hooks、类型及 61 个集成清单测试 | +| `uv run prek run -a` | Passed with all implementation files staged / 实现文件暂存后通过 | +| `make docs-test` | Passed: bilingual links and static build, 1084 public pages verified / 双语链接与静态构建通过,验证 1084 个公开页面 | +| `git diff --check` | Passed / 通过 | + +The workspace runner prints 153 passing test cases. Four `live_context_check` cases return early when the real Core +at `127.0.0.1:8000` is unavailable; readiness was unavailable here. Those four are not real-Core acceptance evidence. +workspace 输出共 153 个通过用例;其中 4 个 `live_context_check` 因真实 Core 不可达而提前返回,不能算作真实 Core 验收。 +The documentation build emitted existing CSS `::highlight` compatibility warnings and completed successfully. +文档构建出现既有 CSS `::highlight` 兼容性警告,构建成功。 + +## Observed behavior / 实际覆盖 + +| Acceptance / 验收项 | Evidence / 证据 | +| --- | --- | +| Correlated call terminals and actual attempts / 关联终态与真实尝试 | Executor tests cover success, zero-send block/withhold/expiry, retry/NotSent, Indeterminate, upstream HTTP error, release refusal/expiry, degraded execution and pending-future destruction / 覆盖成功、零发送拒绝/过期、重试/NotSent、不确定、上游 HTTP 错误、释放拒绝/过期、降级和 pending future 销毁 | +| Usage through real transport / 真实 transport usage | Local HTTP JSON/SSE fixtures verify Chat/Responses input, output, cached reads, known zero and missing/malformed usage; cache writes stay unknown / 核对两种协议的输入、输出、缓存读、已知零及缺失/畸形 usage,缓存写保持未知 | +| Bounded retention and visible loss / 有界保留与可见丢失 | A held writer with capacity 4 receives 100000 extra submissions: exactly 4 queue, 99996 drop; 1 record remains in flight, and recovered output reports loss / 容量 4 且 writer 卡住时额外提交 10 万条,4 条排队、99996 条丢弃、1 条在写,恢复输出含丢失计数 | +| Business isolation / 业务隔离 | Blocking/full and I/O-error writers preserve release/withhold decisions and pending-send cancellation/drop facts; errors are counted without their text / 慢写/队列满/I/O 错误不改变释放与 withhold 结论及发送中取消/销毁事实,错误仅计数不输出原文 | +| Timing and strict order / 计时与 strict 顺序 | Header-wait fixture is included in first-byte timing; incomplete responses retain observed status/first byte; release approval precedes framework handoff and first body frame; model TTFT is null / 首字节包含响应头等待,部分失败保留已知状态与首字节,批准先于框架交接及首 frame,模型 TTFT 为 null | +| Privacy / 隐私 | Synthetic prompt/response/model/request-ID/credential/provider-error/I/O-error markers are absent from evidence; process test also checks stderr / 合成 prompt、响应、模型名、请求 ID、凭据、provider 异常及 I/O 异常标记未出现在证据中,进程测试另检查 stderr | +| Real production composition / 真实生产装配 | Spawned binary handles 1000 requests with 5000 readable records and 1000 distinct call IDs; explicit Noop handles 100 requests with empty stdout and an evidence-disabled startup diagnostic / 真实二进制处理 1000 次请求,输出 5000 条可读记录、1000 个不同调用 ID;显式 Noop 处理 100 次请求,stdout 为空且启动诊断说明证据关闭 | +| Both ingress formats / 两种入口格式 | In-process public-router tests send 200 calls through actual reqwest to local HTTP fixtures, including Responses SSE replay, and read serialized production-sink output / 进程内公开路由用真实 reqwest 完成 200 次本地 HTTP 调用,含 Responses SSE 重放,并读取生产 sink 的序列化输出 | + +## Evidence limits / 证据边界 + +Local Core/provider HTTP fixtures and fake-Gate executor tests are distinct from a real PowerContext Core, +hosted model provider, external telemetry backend, or native agent host. Those external environments were not +executed. The spawned-process test establishes the Rust Gateway's production assembly and local HTTP behavior, +not a third-party agent's cancellation, socket-write visibility or task adoption. No paid model calls were made. + +本地 Core/provider HTTP fixture、FakeGate 执行器测试不等同于真实 PowerContext Core、真实模型供应商、外部观测后端 +或原生 agent 宿主;这些外部环境未执行。真实子进程测试证明 Rust Gateway 生产装配及本地 HTTP 行为, +不证明第三方 agent 的取消能力、实际 socket 写出或任务采用,没有调用付费模型。 + +No public HTTP contract, Python operational fields, database records or dependency lockfiles changed. +OpenAPI generation/contract regeneration and Python logging formatter tests are therefore not applicable. +The bilingual [output contract](../docs/en/docs/operate/gateway-evidence.md) / +[输出契约](../docs/zh/docs/operate/gateway-evidence.md) defines retention, unknown usage, interruption facts, +framework boundaries and deployment/Rust migration behavior. No deployment or GitHub issue closure was performed. + +未修改公开 HTTP 契约、Python operational 字段、数据库记录或依赖锁文件,无需重新生成 OpenAPI 或验证 Python formatter。 +双语契约定义保留、未知 usage、中断事实、框架边界及部署/Rust 迁移行为;未执行部署或关闭 GitHub Issue。 From 7946dec6001396b6f94a931423e9cad199eba1c8 Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Fri, 6 Nov 2026 11:00:03 +0800 Subject: [PATCH 03/15] docs(gateway): clarify first-byte timing and unknown TTFT --- gateway/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gateway/README.md b/gateway/README.md index d2b8dac154..c417791001 100644 --- a/gateway/README.md +++ b/gateway/README.md @@ -12,7 +12,7 @@ An optional Rust executor for PowerContext, defined by the gateway design in #21 - **Privacy enforcement by Core, executed by the gateway**: forbidden content is blocked before any byte leaves the gateway (zero-send on block/withhold, zero-release on refuse, upstream cancel on refusal). - **Deterministic-failure-only bounded retry**: connection-refused style failures retry a bounded number of times with a single owner; indeterminate outcomes (timeout after hand-off) are surfaced as `send_indeterminate` and never auto-retried (no paid re-sends). - **Degradation policy**: when Core is unreachable, either pause (default) or pass through without memory (`PC_GATEWAY_DEGRADE=passthrough`) — degraded responses are explicitly marked (`x-pc-degraded` header). Blocked verdicts never degrade. -- **Streaming ingestion** (`stream: true`): upstream SSE is received incrementally (TTFT measured, byte-capped); strict semantics hold — the complete raw response is buffered and must pass `before_release` before anything is released to the client. (The current public carrier in #2264 withholds streaming payloads; the pipeline is ready for when the contract allows it.) +- **Streaming ingestion** (`stream: true`): upstream SSE is received incrementally with a byte cap; first HTTP body byte latency is measured from before the response-header wait, while model TTFT remains unknown. Strict semantics hold — the complete raw response is buffered and must pass `before_release` before anything is released to the client. (The current public carrier in #2264 withholds streaming payloads; the pipeline is ready for when the contract allows it.) - **Status-code fidelity**: upstream errors pass through with their original status code (a provider 402/400 is never masked as 200), and `Content-Type` is preserved. ### Memory features (#2199 capabilities) From f644f0e0779ce72858c1b6b79414204727e085f5 Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Fri, 6 Nov 2026 11:07:44 +0800 Subject: [PATCH 04/15] docs(gateway): clarify evidence timing and compatibility --- docs/en/docs/operate/gateway-evidence.md | 11 ++++++++++- docs/zh/docs/operate/gateway-evidence.md | 11 ++++++++++- gateway/EVIDENCE_VALIDATION.md | 13 +++++++++++-- gateway/crates/pc-gateway-evidence/src/lib.rs | 7 ++++++- 4 files changed, 37 insertions(+), 5 deletions(-) diff --git a/docs/en/docs/operate/gateway-evidence.md b/docs/en/docs/operate/gateway-evidence.md index e8e51313d5..de7fcc06e3 100644 --- a/docs/en/docs/operate/gateway-evidence.md +++ b/docs/en/docs/operate/gateway-evidence.md @@ -112,10 +112,16 @@ All durations are monotonic milliseconds, truncated to integers. Null means unav | `release_authorized_ms` | Request-control creation to validated, unexpired release after optional capture | | Delivery `elapsed_ms` | Request-control creation to the named framework observation | +The executor handoff and the transport's own send start are separate origins. Their exact offset is not recorded; +`started_ms + response_first_byte_ms` or `started_ms + response_complete_ms` is not an exact call-relative timestamp. + A `delivery` record reports `framework_handoff` when the released/degraded body is placed in the HTTP response, `first_body_frame` when the framework first polls a nonempty data frame, `body_completed` when the wrapped body reports completion, or `body_dropped` if dropped before observed completion. Strict release authorization precedes -framework handoff and content-frame observation. A degraded response has no release authorization timestamp. +framework handoff and first-data-frame observation. A degraded response has no release authorization timestamp. +For SSE, the first data frame may contain a control event such as `response.created` without model content. +`first_body_frame` therefore does not measure first model-content delivery. That boundary is currently unmeasured; +G8 consumers requiring it must treat it as unknown and must not substitute `first_body_frame`. No boundary proves a socket write, client receipt, rendering or adoption. The current host cannot observe actual socket writes. Non-streaming Responses JSON's first byte and replayed SSE output are not provider TTFT. @@ -124,6 +130,9 @@ socket writes. Non-streaming Responses JSON's first byte and replayed SSE output Collectors that previously consumed human tracing from stdout must move that input to stderr and parse evidence stdout separately. No database migration, new HTTP endpoint, Python operational field or OpenAPI regeneration is required. The JSON schema is separate from the Server's allowlisted Python log fields and existing exporters. +The Gateway's client-visible HTTP 503 `gate_paused` body normalizes `detail` for Core-unavailable errors to +`gate_unavailable`, and for malformed Core-response errors to `malformed_gate_response`, instead of exposing raw +diagnostic text. Clients must not depend on the former free-form detail; use the status and `decision` for handling. Custom embedding sinks must keep synchronous callbacks bounded, nonblocking and free of I/O; route blocking writers through `JsonEvidenceSink` and keep one sink per host. Custom writers must return I/O errors without panicking. Rust integrations consume the nested per-field `CallEvidence.usage` instead of the demo record's former flat token/completeness fields. There is no production record-store migration. They must replace `RawResponse.ttft_ms` with the explicit first-byte/completion fields and handle diff --git a/docs/zh/docs/operate/gateway-evidence.md b/docs/zh/docs/operate/gateway-evidence.md index 3de95510e9..c57cbbd7cc 100644 --- a/docs/zh/docs/operate/gateway-evidence.md +++ b/docs/zh/docs/operate/gateway-evidence.md @@ -106,9 +106,15 @@ transport 交付完整响应后,解码或释放失败不会丢掉 usage。直 | `release_authorized_ms` | 创建请求控制至通过校验且未过期的释放批准,位于可选 capture 之后 | | 交付 `elapsed_ms` | 创建请求控制至所标记的框架观测 | +执行器交接与 transport 自身的发送起点不同,两者的精确偏移没有记录。 +`started_ms + response_first_byte_ms` 或 `started_ms + response_complete_ms` 不能得到精确的调用相对时间戳。 + `delivery` 在获准/降级响应体放入 HTTP 响应时报告 `framework_handoff`,框架首次轮询取出非空 data frame 时报告 `first_body_frame`,包装的 body 报告完成时为 `body_completed`,观察到完成之前被丢弃时为 `body_dropped`。 -strict 模式的释放批准先于框架交接与内容 frame 观测。降级响应没有释放批准时间。 +strict 模式的释放批准先于框架交接与首个 data frame 观测。降级响应没有释放批准时间。 +对于 SSE,首个 data frame 可能仅包含 `response.created` 等控制事件,没有模型内容。 +因此 `first_body_frame` 不表示首次模型内容交付;当前没有测量该边界。 +G8 消费方若依赖首次模型内容交付指标,必须将其视为未知,不能用 `first_body_frame` 替代。 这些边界都不证明 socket 写入、客户端收到、呈现或采用。当前宿主无法观察实际 socket 写出。 非流式 Responses JSON 的首字节及重放的 SSE 输出不是 provider TTFT。 @@ -117,6 +123,9 @@ strict 模式的释放批准先于框架交接与内容 frame 观测。降级响 原来从 stdout 采集人类可读 tracing 的部署,需要改为采集 stderr,并单独解析 stdout 证据。 无需数据库迁移、新 HTTP 端点、Python operational 字段或 OpenAPI 重新生成。 该 JSON schema 独立于 Server 的 Python 日志白名单与现有 exporter。 +Gateway 客户端可见的 HTTP 503 `gate_paused` 响应中,Core 不可用错误的 `detail` 归一化为 +`gate_unavailable`,Core 响应畸形错误的 `detail` 归一化为 `malformed_gate_response`,不再暴露原始诊断文本。 +客户端不应依赖原来的自由文本 detail,应使用状态码和 `decision` 处理结果。 自定义嵌入 sink 的同步回调必须有界、不阻塞且不执行 I/O;将阻塞 writer 接入 `JsonEvidenceSink`, 每个宿主保留一个 sink。自定义 writer 应返回 I/O 错误,不应 panic。 Rust 集成改为读取 `CallEvidence.usage` 中逐字段的数量与完整性,不再读取演示记录原来的扁平 token/completeness 字段。 diff --git a/gateway/EVIDENCE_VALIDATION.md b/gateway/EVIDENCE_VALIDATION.md index 1c631cfcf3..f631047650 100644 --- a/gateway/EVIDENCE_VALIDATION.md +++ b/gateway/EVIDENCE_VALIDATION.md @@ -63,16 +63,25 @@ Local Core/provider HTTP fixtures and fake-Gate executor tests are distinct from hosted model provider, external telemetry backend, or native agent host. Those external environments were not executed. The spawned-process test establishes the Rust Gateway's production assembly and local HTTP behavior, not a third-party agent's cancellation, socket-write visibility or task adoption. No paid model calls were made. +The first nonempty body frame can contain only SSE control events. First model-content delivery is unmeasured; +this evidence does not establish the literal first-content boundary in #2463 behavior 4. G8 must treat that metric +as unknown rather than substituting `first_body_frame`. 本地 Core/provider HTTP fixture、FakeGate 执行器测试不等同于真实 PowerContext Core、真实模型供应商、外部观测后端 或原生 agent 宿主;这些外部环境未执行。真实子进程测试证明 Rust Gateway 生产装配及本地 HTTP 行为, 不证明第三方 agent 的取消能力、实际 socket 写出或任务采用,没有调用付费模型。 +首个非空 body frame 可能仅包含 SSE 控制事件;首次模型内容交付没有测量,不能据此宣称已验收 +#2463 行为 4 中字面上的首次内容边界。G8 必须将该指标视为未知,不能使用 `first_body_frame` 替代。 -No public HTTP contract, Python operational fields, database records or dependency lockfiles changed. +No OpenAPI contract, Python operational fields, database records or dependency lockfiles changed. +The Gateway's client-visible HTTP 503 `gate_paused.detail` is normalized for Core-unavailable and malformed-response +errors; the bilingual deployment contract documents these fixed values and the client migration behavior. OpenAPI generation/contract regeneration and Python logging formatter tests are therefore not applicable. The bilingual [output contract](../docs/en/docs/operate/gateway-evidence.md) / [输出契约](../docs/zh/docs/operate/gateway-evidence.md) defines retention, unknown usage, interruption facts, framework boundaries and deployment/Rust migration behavior. No deployment or GitHub issue closure was performed. -未修改公开 HTTP 契约、Python operational 字段、数据库记录或依赖锁文件,无需重新生成 OpenAPI 或验证 Python formatter。 +未修改 OpenAPI 契约、Python operational 字段、数据库记录或依赖锁文件,无需重新生成 OpenAPI 或验证 Python formatter。 +Gateway 客户端可见的 HTTP 503 `gate_paused.detail` 对 Core 不可用及响应畸形错误进行了归一化, +双语部署契约记录了固定值与客户端迁移行为。 双语契约定义保留、未知 usage、中断事实、框架边界及部署/Rust 迁移行为;未执行部署或关闭 GitHub Issue。 diff --git a/gateway/crates/pc-gateway-evidence/src/lib.rs b/gateway/crates/pc-gateway-evidence/src/lib.rs index 8243f4ed66..cc9a9b4f6a 100644 --- a/gateway/crates/pc-gateway-evidence/src/lib.rs +++ b/gateway/crates/pc-gateway-evidence/src/lib.rs @@ -163,10 +163,14 @@ pub struct AttemptEvidence { pub call_id: String, pub attempt: u32, pub outcome: AttemptOutcome, - /// Call-relative send handoff time; the following durations start at that handoff. + /// Milliseconds from request-control creation to the executor's transport handoff. pub started_ms: u64, + /// Executor handoff to transport result or future destruction, in milliseconds. pub duration_ms: u64, + /// Transport's own send start (before awaiting headers) to first nonempty HTTP body chunk. + /// Its origin differs from `started_ms`; adding them does not give an exact call-relative timestamp. pub response_first_byte_ms: Option, + /// Same transport send-start origin as `response_first_byte_ms`, to complete buffered response. pub response_complete_ms: Option, pub upstream_status: Option, pub usage: UsageEvidence, @@ -176,6 +180,7 @@ pub struct AttemptEvidence { #[serde(rename_all = "snake_case")] pub enum DeliveryBoundary { FrameworkHandoff, + /// First nonempty HTTP data frame polled by the framework; may contain only SSE control events. FirstBodyFrame, BodyCompleted, BodyDropped, From 2a686028262f9ac10f1d9f3c95ad7c4e923aba38 Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Fri, 6 Nov 2026 11:39:30 +0800 Subject: [PATCH 05/15] feat(gateway): observe first model content at body delivery --- docs/en/docs/operate/gateway-evidence.md | 23 +- docs/zh/docs/operate/gateway-evidence.md | 22 +- gateway/README.md | 2 +- .../pc-gateway-app/src/evidence_body.rs | 146 +++++++++- gateway/crates/pc-gateway-app/src/ingress.rs | 119 ++++++-- .../pc-gateway-app/tests/evidence_process.rs | 12 +- gateway/crates/pc-gateway-evidence/src/lib.rs | 3 + gateway/crates/pc-gateway-protocol/Cargo.toml | 2 +- .../crates/pc-gateway-protocol/src/content.rs | 254 ++++++++++++++++++ gateway/crates/pc-gateway-protocol/src/lib.rs | 2 + .../tests/content_boundary.rs | 153 +++++++++++ 11 files changed, 690 insertions(+), 48 deletions(-) create mode 100644 gateway/crates/pc-gateway-protocol/src/content.rs create mode 100644 gateway/crates/pc-gateway-protocol/tests/content_boundary.rs diff --git a/docs/en/docs/operate/gateway-evidence.md b/docs/en/docs/operate/gateway-evidence.md index de7fcc06e3..62f04ab04a 100644 --- a/docs/en/docs/operate/gateway-evidence.md +++ b/docs/en/docs/operate/gateway-evidence.md @@ -116,17 +116,30 @@ The executor handoff and the transport's own send start are separate origins. Th `started_ms + response_first_byte_ms` or `started_ms + response_complete_ms` is not an exact call-relative timestamp. A `delivery` record reports `framework_handoff` when the released/degraded body is placed in the HTTP response, -`first_body_frame` when the framework first polls a nonempty data frame, `body_completed` when the wrapped 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 first-data-frame observation. A degraded response has no release authorization timestamp. -For SSE, the first data frame may contain a control event such as `response.created` without model content. -`first_body_frame` therefore does not measure first model-content delivery. That boundary is currently unmeasured; -G8 consumers requiring it must treat it as unknown and must not substitute `first_body_frame`. +framework handoff and both first-frame/content observations. 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 +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. + +Control-only, empty, malformed and unsupported output has no `first_model_content` event. Neither does a body dropped +before its content frame is polled. Absence is unavailable evidence, not a zero duration; consumers must also account +for the sink's loss counters. The first body frame may contain only `response.created` or other SSE controls, so G8 +must consume `first_model_content` separately. Both observations can share a timestamp when one frame contains both. No boundary proves a socket write, client receipt, rendering or adoption. The current host cannot observe actual socket writes. Non-streaming Responses JSON's first byte and replayed SSE output are not provider TTFT. ## Deployment and compatibility +The additive `delivery.boundary=first_model_content` value requires consumers with exhaustive enum matching to +accept the new value; consumers must not assume a fixed number of records per call. Collectors that previously consumed human tracing from stdout must move that input to stderr and parse evidence stdout separately. No database migration, new HTTP endpoint, Python operational field or OpenAPI regeneration is required. The JSON schema is separate from the Server's allowlisted Python log fields and existing exporters. diff --git a/docs/zh/docs/operate/gateway-evidence.md b/docs/zh/docs/operate/gateway-evidence.md index c57cbbd7cc..a8008074ef 100644 --- a/docs/zh/docs/operate/gateway-evidence.md +++ b/docs/zh/docs/operate/gateway-evidence.md @@ -110,16 +110,28 @@ transport 交付完整响应后,解码或释放失败不会丢掉 usage。直 `started_ms + response_first_byte_ms` 或 `started_ms + response_complete_ms` 不能得到精确的调用相对时间戳。 `delivery` 在获准/降级响应体放入 HTTP 响应时报告 `framework_handoff`,框架首次轮询取出非空 data frame -时报告 `first_body_frame`,包装的 body 报告完成时为 `body_completed`,观察到完成之前被丢弃时为 `body_dropped`。 -strict 模式的释放批准先于框架交接与首个 data frame 观测。降级响应没有释放批准时间。 -对于 SSE,首个 data frame 可能仅包含 `response.created` 等控制事件,没有模型内容。 -因此 `first_body_frame` 不表示首次模型内容交付;当前没有测量该边界。 -G8 消费方若依赖首次模型内容交付指标,必须将其视为未知,不能用 `first_body_frame` 替代。 +时报告 `first_body_frame`,取出包含首个可识别模型输出编码字节的 frame 时报告 `first_model_content`, +包装的 body 报告完成时为 `body_completed`,观察到完成之前被丢弃时为 `body_dropped`。 +strict 模式的释放批准先于框架交接、首个 data frame 与首内容观测。降级响应没有释放批准时间。 + +首内容边界识别 OpenAI Chat/Responses JSON 与所支持 SSE 输出中的非空 assistant 文本、拒绝字符串、 +函数调用名称及参数,包含 Responses 重放。仅含 role、usage、reasoning、error 及其他控制信息的事件不触发。 +item-added 事件若确实包含函数名或输出文本,也可以建立内容边界;仅凭事件名称不能建立。 +定位器检查实际发送的完整缓冲正文,只把字节偏移交给观察器。观察器累计已轮询 data 字节,支持任意 frame +切分,不保留正文,不改变响应字节。记录的是包含首个**编码**内容字节的 frame,该字节可能属于 JSON 转义, +不等待完整解码字符或完整 SSE 事件。 + +仅控制事件、空、畸形或不支持的输出没有 `first_model_content` 事件;在轮询到内容 frame 之前丢弃 body +也不产生该事件。缺失表示证据不可得,不是耗时为零;消费方还须考虑 sink 丢失计数。 +首 body frame 可能只有 `response.created` 等 SSE 控制信息,因此 G8 必须单独读取 `first_model_content`。 +同一 frame 同时包含两种边界时,两条记录可以使用相同时间戳。 这些边界都不证明 socket 写入、客户端收到、呈现或采用。当前宿主无法观察实际 socket 写出。 非流式 Responses JSON 的首字节及重放的 SSE 输出不是 provider TTFT。 ## 部署与兼容 +新增 `delivery.boundary=first_model_content` 值,穷举匹配枚举的消费方需要接受该值, +不能假定每次调用的记录数量固定。 原来从 stdout 采集人类可读 tracing 的部署,需要改为采集 stderr,并单独解析 stdout 证据。 无需数据库迁移、新 HTTP 端点、Python operational 字段或 OpenAPI 重新生成。 该 JSON schema 独立于 Server 的 Python 日志白名单与现有 exporter。 diff --git a/gateway/README.md b/gateway/README.md index c417791001..8a0bfca8a7 100644 --- a/gateway/README.md +++ b/gateway/README.md @@ -28,7 +28,7 @@ An optional Rust executor for PowerContext, defined by the gateway design in #21 - **OpenAI-compatible ingress** at `/gateway/v1/chat/completions` and `/gateway/v1/responses` (same format in and out, no cross-format translation), authenticated by a gateway key that replaces provider keys. - **Responses fidelity**: on `/gateway/v1/responses`, every input item other than a plain user message (developer messages, tool calls and outputs, reasoning, client-specific items such as Codex's `additional_tools`) is forwarded unchanged, and request fields the ingress does not model (for example `reasoning`, `include`, `prompt_cache_key`) are passed through for Core's request allowlist to decide; only the client-local `client_metadata` is dropped. The upstream request is always non-streaming; a streaming client receives the released (or permitted degraded-passthrough, still marked `x-pc-degraded`) 200 response replayed as Responses SSE events: `response.created`, `response.output_item.added`/`done` per item with each message content part as `response.content_part.added`/`done` around one buffered `response.output_text.delta`/`done` (or `response.refusal.delta`/`done`), and a terminal event chosen from the response status (`response.completed`, `response.incomplete`, or `response.failed` when the status is `failed`/`cancelled` or an `error` is present). - **Middleware chain**: composable `GatewayMiddleware` trait; ships with resource limits (request-body precheck + concurrency semaphore, health probe exempt) and request-id propagation (`x-powercontext-request-id`, client-supplied or generated, echoed on responses). -- **Body-free evidence**: bounded JSONL on stdout (1024 queued records plus one in flight), correlated call/attempt terminals, per-field usage completeness and cache reads, explicit first-byte/release/framework timing; model TTFT stays unknown. Operational tracing uses stderr. See the [output and deployment contract](../docs/en/docs/operate/gateway-evidence.md) / [中文](../docs/zh/docs/operate/gateway-evidence.md). `PC_GATEWAY_EVIDENCE=off` explicitly disables coverage. +- **Body-free evidence**: bounded JSONL on stdout (1024 queued records plus one in flight), correlated call/attempt terminals, per-field usage completeness and cache reads, explicit first-byte/release/framework timing and separate first model-content frame observation; model TTFT stays unknown. Operational tracing uses stderr. See the [output and deployment contract](../docs/en/docs/operate/gateway-evidence.md) / [中文](../docs/zh/docs/operate/gateway-evidence.md). `PC_GATEWAY_EVIDENCE=off` explicitly disables coverage. ## PC call sequence over UDS diff --git a/gateway/crates/pc-gateway-app/src/evidence_body.rs b/gateway/crates/pc-gateway-app/src/evidence_body.rs index 8aec0d0629..8cc7c6f625 100644 --- a/gateway/crates/pc-gateway-app/src/evidence_body.rs +++ b/gateway/crates/pc-gateway-app/src/evidence_body.rs @@ -21,11 +21,17 @@ use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; +/// Offset in the exact outgoing body; this metadata contains no response content. +#[derive(Clone, Copy)] +pub(crate) struct FirstContentOffset(pub(crate) Option); + pub(crate) struct EvidenceBody { body: Body, observation: ExecutionObservation, sink: Arc, first: bool, + first_content: Option, + body_bytes: usize, completed: bool, } @@ -34,12 +40,15 @@ impl EvidenceBody { body: Body, observation: ExecutionObservation, sink: Arc, + first_content: Option, ) -> Body { let wrapper = Self { body, observation, sink, first: false, + first_content, + body_bytes: 0, completed: false, }; wrapper.record(DeliveryBoundary::FrameworkHandoff); @@ -65,15 +74,23 @@ impl HttpBody for EvidenceBody { ) -> Poll, Self::Error>>> { let result = Pin::new(&mut self.body).poll_frame(cx); if let Poll::Ready(frame) = &result { - if !self.first - && frame - .as_ref() - .and_then(|r| r.as_ref().ok()) - .and_then(Frame::data_ref) - .is_some_and(|data| !data.is_empty()) + if let Some(data) = frame + .as_ref() + .and_then(|r| r.as_ref().ok()) + .and_then(Frame::data_ref) { - self.first = true; - self.record(DeliveryBoundary::FirstBodyFrame); + if !self.first && !data.is_empty() { + self.first = true; + self.record(DeliveryBoundary::FirstBodyFrame); + } + self.body_bytes = self.body_bytes.saturating_add(data.len()); + if self + .first_content + .is_some_and(|offset| offset < self.body_bytes) + { + self.first_content = None; + self.record(DeliveryBoundary::FirstModelContent); + } } if !self.completed && (frame.is_none() || (matches!(frame, Some(Ok(_))) && self.body.is_end_stream())) @@ -99,3 +116,116 @@ impl Drop for EvidenceBody { } } } + +#[cfg(test)] +mod tests { + use super::*; + 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; + + struct Frames(VecDeque); + impl HttpBody for Frames { + type Data = Bytes; + type Error = Infallible; + + fn poll_frame( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + ) -> Poll, Infallible>>> { + Poll::Ready(self.0.pop_front().map(|bytes| Ok(Frame::data(bytes)))) + } + } + + fn boundaries(sink: &BufferedEvidenceSink) -> Vec { + sink.events() + .into_iter() + .filter_map(|event| match event { + EvidenceEvent::Delivery(e) => Some( + serde_json::to_value(e.boundary) + .unwrap() + .as_str() + .unwrap() + .to_owned(), + ), + _ => None, + }) + .collect() + } + + fn wrap(bytes: Vec, offset: Option, sink: Arc) -> Body { + let control = RequestControl::new( + tokio::time::Instant::now() + std::time::Duration::from_secs(30), + None, + ); + EvidenceBody::wrap( + Body::new(Frames(bytes.into())), + control.observation(), + sink, + offset, + ) + } + + #[tokio::test] + async fn content_observation_waits_for_matching_frame_at_every_wire_split() { + for (wire, protocol, sse) in [ + ("event: response.created\ndata: {\"type\":\"response.created\"}\n\nevent: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"秘密\"}\n\n", OutputProtocol::OpenAiResponses, true), + (r#"{"choices":[{"message":{"content":"\u79d8密"}}]}"#, OutputProtocol::OpenAiChat, false), + ("data: {\"choices\":[{\"delta\":{\"role\":\"assistant\"}}]}\n\ndata: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"function\":{\"arguments\":\"{}\"}}]}}]}\n\n", OutputProtocol::OpenAiChat, true), + (r#"{"output":[{"type":"message","content":[{"type":"refusal","refusal":"no"}]}]}"#, OutputProtocol::OpenAiResponses, false), + ] { + let offset = first_model_content_offset(wire.as_bytes(), protocol, sse).unwrap(); + for split in 0..=wire.len() { + let sink = Arc::new(BufferedEvidenceSink::new()); + let mut body = wrap(vec![Bytes::copy_from_slice(&wire.as_bytes()[..split]), Bytes::copy_from_slice(&wire.as_bytes()[split..])], Some(offset), sink.clone()); + let first = body.frame().await.unwrap().unwrap().into_data().unwrap(); + assert_eq!(boundaries(&sink).iter().any(|b| b == "first_model_content"), split > offset); + let second = body.frame().await.unwrap().unwrap().into_data().unwrap(); + assert_eq!([first.as_ref(), second.as_ref()].concat(), wire.as_bytes()); + assert!(body.frame().await.is_none()); + drop(body); + assert_eq!(boundaries(&sink), ["framework_handoff", "first_body_frame", "first_model_content", "body_completed"]); + } + } + } + + #[tokio::test] + async fn dropping_after_control_frame_does_not_claim_later_content() { + let wire = "event: response.created\ndata: {\"type\":\"response.created\"}\n\nevent: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"secret\"}\n\n"; + let split = wire.find("event: response.output_text").unwrap(); + let sink = Arc::new(BufferedEvidenceSink::new()); + let mut body = wrap( + vec![ + Bytes::copy_from_slice(&wire.as_bytes()[..split]), + Bytes::copy_from_slice(&wire.as_bytes()[split..]), + ], + first_model_content_offset(wire.as_bytes(), OutputProtocol::OpenAiResponses, true), + sink.clone(), + ); + body.frame().await.unwrap().unwrap(); + drop(body); + assert_eq!( + boundaries(&sink), + ["framework_handoff", "first_body_frame", "body_dropped"] + ); + } + + #[tokio::test] + async fn control_only_output_completes_without_inventing_content() { + let wire = b"event: response.created\ndata: {\"type\":\"response.created\"}\n\n"; + let sink = Arc::new(BufferedEvidenceSink::new()); + let body = wrap( + vec![Bytes::from_static(wire)], + first_model_content_offset(wire, OutputProtocol::OpenAiResponses, true), + sink.clone(), + ); + assert_eq!(body.collect().await.unwrap().to_bytes(), wire.as_slice()); + assert_eq!( + boundaries(&sink), + ["framework_handoff", "first_body_frame", "body_completed"] + ); + } +} diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index d23fad4a7c..8bd8ed8de8 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -15,6 +15,7 @@ //! 模型入口:OpenAI 兼容 `/gateway/v1/chat/completions`。 //! 客户端只改 Base URL 与 API Key 即接入(PR #2199 产品形态)。 +use crate::evidence_body::FirstContentOffset; use crate::{proxy::SharedProxy, AppState, Injection}; use axum::body::Bytes; use axum::extract::{Request, State}; @@ -22,7 +23,10 @@ use axum::http::{header, HeaderMap, StatusCode}; use axum::response::{IntoResponse, Response}; use axum::Json; use pc_gateway_core::{ManagedCall, ManagedOutcome, RequestControl}; -use pc_gateway_protocol::{CanonicalMessage, CanonicalRequest, OutputLimits, Role}; +use pc_gateway_protocol::{ + first_model_content_offset, CanonicalMessage, CanonicalRequest, OutputLimits, OutputProtocol, + Role, +}; use serde::Deserialize; use std::sync::Arc; @@ -132,6 +136,10 @@ async fn ingress_common( | pc_gateway_core::ExecutionTerminal::Degraded ) ) { + let first_content = response + .extensions() + .get::() + .and_then(|offset| offset.0); let (parts, body) = response.into_parts(); response = Response::from_parts( parts, @@ -139,6 +147,7 @@ async fn ingress_common( body, observation.clone(), state.evidence.clone(), + first_content, ), ); } @@ -296,7 +305,13 @@ async fn ingress_model( if client_stream { return respond_responses_sse(outcome); } - respond(outcome) + respond( + outcome, + match format { + Format::Chat => OutputProtocol::OpenAiChat, + Format::Responses => OutputProtocol::OpenAiResponses, + }, + ) } /// 流式 Responses 客户端:把放行(或允许降级直通)后的完整响应重放为 Responses SSE 事件。 @@ -310,17 +325,23 @@ fn respond_responses_sse(outcome: ManagedOutcome) -> Response { ManagedOutcome::Degraded { status: 200, body, .. } => (body, true), - _ => return respond(outcome), + _ => return respond(outcome, OutputProtocol::OpenAiResponses), }; let Ok(resp) = serde_json::from_slice::(body) else { - return respond(outcome); + return respond(outcome, OutputProtocol::OpenAiResponses); }; + let body = responses_sse(&resp); + let first_content = + first_model_content_offset(body.as_bytes(), OutputProtocol::OpenAiResponses, true); let mut response = ( StatusCode::OK, [(header::CONTENT_TYPE, "text/event-stream")], - responses_sse(&resp), + body, ) .into_response(); + response + .extensions_mut() + .insert(FirstContentOffset(first_content)); if degraded { response.headers_mut().insert( "x-pc-degraded", @@ -631,8 +652,35 @@ fn to_canonical_responses(r: OpenAiResponsesRequest) -> Result Response { - match outcome { +fn respond(outcome: ManagedOutcome, protocol: OutputProtocol) -> Response { + let first_content = match &outcome { + ManagedOutcome::Released { + status, + content_type, + body, + .. + } + | ManagedOutcome::Degraded { + status, + content_type, + body, + } if (200..300).contains(status) => { + let mime = content_type.split(';').next().unwrap_or("").trim(); + if mime.eq_ignore_ascii_case("application/json") + || mime.eq_ignore_ascii_case("text/event-stream") + { + first_model_content_offset( + body, + protocol, + mime.eq_ignore_ascii_case("text/event-stream"), + ) + } else { + None + } + } + _ => None, + }; + let mut response = match outcome { ManagedOutcome::Released { status, content_type, @@ -695,7 +743,11 @@ fn respond(outcome: ManagedOutcome) -> Response { Json(serde_json::json!({ "decision": "gate_paused", "detail": msg })), ) .into_response(), - } + }; + response + .extensions_mut() + .insert(FirstContentOffset(first_content)); + response } // 抑制未使用导入警告(Bytes 用于类型别名文档场景)。 @@ -739,22 +791,31 @@ mod tests { ) .route( "/v1/chat/completions", - post(|| async { - ( - StatusCode::CREATED, - Json(serde_json::json!({ - "choices": [{"message": {"role": "assistant", "content": "checked"}}], - "usage": {"prompt_tokens": 100, "completion_tokens": 12, "prompt_tokens_details": {"cached_tokens": 70}}, - "provider_debug": "SYNTHETIC_SENSITIVE_RESPONSE" - })), - ) + post(|Json(request): Json| async move { + let usage = serde_json::json!({"prompt_tokens": 100, "completion_tokens": 12, "prompt_tokens_details": {"cached_tokens": 70}}); + if request["stream"] == true { + ( + StatusCode::CREATED, + [(header::CONTENT_TYPE, "text/event-stream")], + format!("data: {{\"choices\":[{{\"delta\":{{\"role\":\"assistant\"}}}}]}}\n\ndata: {{\"choices\":[{{\"delta\":{{\"content\":\"SYNTHETIC_SENSITIVE_RESPONSE\"}}}}]}}\n\ndata: {{\"choices\":[],\"usage\":{usage}}}\n\ndata: [DONE]\n\n"), + ).into_response() + } else { + ( + StatusCode::CREATED, + Json(serde_json::json!({ + "choices": [{"message": {"role": "assistant", "content": "checked"}}], + "usage": usage, + "provider_debug": "SYNTHETIC_SENSITIVE_RESPONSE" + })), + ).into_response() + } }), ) .route( "/v1/responses", post(|| async { Json(serde_json::json!({ - "id": "resp-1", "object": "response", "status": "completed", "output": [], + "id": "resp-1", "object": "response", "status": "completed", "output": [{"type":"message", "role":"assistant", "content":[{"type":"output_text", "text":"SYNTHETIC_SENSITIVE_RESPONSE"}]}], "usage": {"input_tokens": 80, "output_tokens": 11, "input_tokens_details": {"cached_tokens": 30}} })) }), @@ -1551,7 +1612,7 @@ mod tests { } #[tokio::test] - async fn real_ingress_exports_usage_and_distinct_framework_boundaries_without_content() { + async fn real_ingress_exports_usage_and_content_boundaries_without_sensitive_data() { use pc_gateway_evidence::JsonEvidenceSink; use tower::ServiceExt; let output = EvidenceOutput::default(); @@ -1560,17 +1621,18 @@ mod tests { .unwrap(), ); let (router, server) = lifecycle_router_with_evidence(sink.clone()).await; - // Exercise both public routes and Responses replay, with the real reqwest transport. + // Exercise JSON/SSE on both public routes with the real reqwest transport. for i in 0..200 { - let chat = i % 2 == 0; + let chat = i % 4 < 2; + let stream = i % 2 == 1; let request = Request::builder().method("POST") .uri(if chat { "/gateway/v1/chat/completions" } else { "/gateway/v1/responses" }) .header(header::AUTHORIZATION, "Bearer gateway-key") .header("x-powercontext-request-id", "SYNTHETIC_SENSITIVE_CORRELATION") .body(axum::body::Body::from(if chat { - serde_json::json!({"model":"SYNTHETIC_SENSITIVE_MODEL", "messages":[{"role":"user", "content":"SYNTHETIC_SENSITIVE_PROMPT"}]}).to_string() + serde_json::json!({"model":"SYNTHETIC_SENSITIVE_MODEL", "messages":[{"role":"user", "content":"SYNTHETIC_SENSITIVE_PROMPT"}], "stream":stream}).to_string() } else { - serde_json::json!({"model":"SYNTHETIC_SENSITIVE_MODEL", "input":[{"role":"user", "content":"SYNTHETIC_SENSITIVE_PROMPT"}], "store":false, "stream":true}).to_string() + serde_json::json!({"model":"SYNTHETIC_SENSITIVE_MODEL", "input":[{"role":"user", "content":"SYNTHETIC_SENSITIVE_PROMPT"}], "store":false, "stream":stream}).to_string() })).unwrap(); let response = router.clone().oneshot(request).await.unwrap(); assert!(response.status().is_success()); @@ -1579,7 +1641,7 @@ mod tests { .unwrap(); } tokio::time::timeout(std::time::Duration::from_secs(5), async { - while sink.stats().written < 1000 { + while sink.stats().written < 1200 { tokio::task::yield_now().await; } }) @@ -1606,7 +1668,7 @@ mod tests { .collect(); assert_eq!( names, - ["attempt", "call", "delivery", "delivery", "delivery"] + ["attempt", "call", "delivery", "delivery", "delivery", "delivery"] ); let call = &events[1]["evidence"]; let attempt = &events[0]["evidence"]; @@ -1628,7 +1690,12 @@ mod tests { ); assert_eq!(events[2]["evidence"]["boundary"], "framework_handoff"); assert_eq!(events[3]["evidence"]["boundary"], "first_body_frame"); - assert_eq!(events[4]["evidence"]["boundary"], "body_completed"); + assert_eq!(events[4]["evidence"]["boundary"], "first_model_content"); + assert_eq!(events[5]["evidence"]["boundary"], "body_completed"); + assert!( + events[4]["evidence"]["elapsed_ms"].as_u64() + >= events[3]["evidence"]["elapsed_ms"].as_u64() + ); assert!( events[2]["evidence"]["elapsed_ms"].as_u64() >= call["release_authorized_ms"].as_u64() diff --git a/gateway/crates/pc-gateway-app/tests/evidence_process.rs b/gateway/crates/pc-gateway-app/tests/evidence_process.rs index 380af624d2..15601ebcc3 100644 --- a/gateway/crates/pc-gateway-app/tests/evidence_process.rs +++ b/gateway/crates/pc-gateway-app/tests/evidence_process.rs @@ -131,7 +131,7 @@ async fn production_jsonl_and_explicit_noop_keep_real_requests_usable() { } if !disabled { tokio::time::timeout(Duration::from_secs(5), async { - while lines.load(Ordering::Relaxed) < count * 5 { + while lines.load(Ordering::Relaxed) < count * 6 { tokio::task::yield_now().await; } }) @@ -146,12 +146,19 @@ async fn production_jsonl_and_explicit_noop_keep_real_requests_usable() { assert!(output.is_empty()); assert!(errors.contains("evidence disabled")); } else { - assert_eq!(output.len(), count * 5); + assert_eq!(output.len(), count * 6); let mut call_ids = std::collections::BTreeSet::new(); + let mut content_ids = std::collections::BTreeSet::new(); for line in output { assert!(!line.contains("SYNTHETIC_")); let record: Value = serde_json::from_str(&line).unwrap(); assert_eq!(record["loss"]["dropped"], 0); + if record["event"] == "delivery" + && record["evidence"]["boundary"] == "first_model_content" + { + assert!(content_ids + .insert(record["evidence"]["call_id"].as_str().unwrap().to_owned())); + } if record["event"] == "call" { let evidence = &record["evidence"]; assert_eq!(evidence["terminal"], "release_authorized"); @@ -163,6 +170,7 @@ async fn production_jsonl_and_explicit_noop_keep_real_requests_usable() { } } assert_eq!(call_ids.len(), count); + assert_eq!(content_ids, call_ids); } } fixture_task.abort(); diff --git a/gateway/crates/pc-gateway-evidence/src/lib.rs b/gateway/crates/pc-gateway-evidence/src/lib.rs index cc9a9b4f6a..897b26370d 100644 --- a/gateway/crates/pc-gateway-evidence/src/lib.rs +++ b/gateway/crates/pc-gateway-evidence/src/lib.rs @@ -182,6 +182,9 @@ pub enum DeliveryBoundary { FrameworkHandoff, /// First nonempty HTTP data frame polled by the framework; may contain only SSE control events. FirstBodyFrame, + /// Framework polls the frame containing the first encoded byte of recognized model content. + /// This is a local body observation, not socket writing, client receipt or provider TTFT. + FirstModelContent, BodyCompleted, BodyDropped, } diff --git a/gateway/crates/pc-gateway-protocol/Cargo.toml b/gateway/crates/pc-gateway-protocol/Cargo.toml index 74ae8e4e8d..e90cdebb55 100644 --- a/gateway/crates/pc-gateway-protocol/Cargo.toml +++ b/gateway/crates/pc-gateway-protocol/Cargo.toml @@ -22,6 +22,6 @@ description = "PowerContext Gateway: canonical internal types + per-provider wir [dependencies] pc-gateway-types = { workspace = true } serde = { workspace = true } -serde_json = { workspace = true } +serde_json = { workspace = true, features = ["raw_value"] } bytes = { workspace = true } thiserror = { workspace = true } diff --git a/gateway/crates/pc-gateway-protocol/src/content.rs b/gateway/crates/pc-gateway-protocol/src/content.rs new file mode 100644 index 0000000000..0a27597a8d --- /dev/null +++ b/gateway/crates/pc-gateway-protocol/src/content.rs @@ -0,0 +1,254 @@ +// 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. + +//! Locate model output in an already buffered wire response, without retaining its content. +use serde::Deserialize; +use serde_json::value::RawValue; +use std::borrow::Cow; + +#[derive(Debug, Clone, Copy)] +pub enum OutputProtocol { + OpenAiChat, + OpenAiResponses, +} + +/// Byte offset of the first encoded byte in a nonempty supported model-output string. +/// Only the offset survives inspection; callers must observe the corresponding outgoing body frame. +/// Invalid/unsupported output and responses without recognized content return None. +pub fn first_model_content_offset( + body: &[u8], + protocol: OutputProtocol, + sse: bool, +) -> Option { + let text = std::str::from_utf8(body).ok()?; + if sse { + sse_offset(text, protocol) + } else { + json_offset(text, protocol, false) + } +} + +// Borrow raw field slices instead of allocating copies of model text or decoded JSON trees. +#[derive(Default, Deserialize)] +struct Fields<'a> { + #[serde(borrow, rename = "type")] + kind: Option>, + #[serde(borrow)] + role: Option>, + #[serde(borrow)] + choices: Option<&'a RawValue>, + #[serde(borrow)] + message: Option<&'a RawValue>, + #[serde(borrow)] + delta: Option<&'a RawValue>, + #[serde(borrow)] + content: Option<&'a RawValue>, + #[serde(borrow)] + refusal: Option<&'a RawValue>, + #[serde(borrow)] + tool_calls: Option<&'a RawValue>, + #[serde(borrow)] + function: Option<&'a RawValue>, + #[serde(borrow)] + function_call: Option<&'a RawValue>, + #[serde(borrow)] + name: Option<&'a RawValue>, + #[serde(borrow)] + arguments: Option<&'a RawValue>, + #[serde(borrow)] + output: Option<&'a RawValue>, + #[serde(borrow)] + text: Option<&'a RawValue>, + #[serde(borrow)] + item: Option<&'a RawValue>, + #[serde(borrow)] + part: Option<&'a RawValue>, + #[serde(borrow)] + response: Option<&'a RawValue>, +} + +fn fields(raw: Option<&RawValue>) -> Fields<'_> { + raw.and_then(|r| serde_json::from_str(r.get()).ok()) + .unwrap_or_default() +} + +fn array(raw: Option<&RawValue>) -> Vec<&RawValue> { + raw.and_then(|r| serde_json::from_str(r.get()).ok()) + .unwrap_or_default() +} + +fn string_offset(raw: Option<&RawValue>, text: &str) -> Option { + let value = raw?.get(); + // RawValue has already validated JSON. Only "" is an empty JSON string, including escapes. + if !value.starts_with('"') || value.len() <= 2 { + return None; + } + (value.as_ptr() as usize) + .checked_sub(text.as_ptr() as usize)? + .checked_add(1) + .filter(|offset| *offset < text.len()) +} + +fn function_offset(function: Fields<'_>, text: &str) -> Option { + [ + string_offset(function.name, text), + string_offset(function.arguments, text), + ] + .into_iter() + .flatten() + .min() +} + +fn part_offset(raw: Option<&RawValue>, text: &str) -> Option { + let part = fields(raw); + match part.kind.as_deref() { + Some("output_text" | "text") => string_offset(part.text, text), + Some("refusal") => string_offset(part.refusal, text), + _ => None, + } +} + +fn message_offset(message: Fields<'_>, text: &str) -> Option { + if message + .role + .as_deref() + .is_some_and(|role| role != "assistant") + { + return None; + } + let content = string_offset(message.content, text).into_iter().chain( + array(message.content) + .into_iter() + .filter_map(|part| part_offset(Some(part), text)), + ); + content + .chain(string_offset(message.refusal, text)) + .chain(function_offset(fields(message.function_call), text)) + .chain( + array(message.tool_calls) + .into_iter() + .filter_map(|tool| function_offset(fields(fields(Some(tool)).function), text)), + ) + .min() +} + +fn item_offset(raw: Option<&RawValue>, text: &str) -> Option { + let item = fields(raw); + match item.kind.as_deref() { + Some("message") if item.role.as_deref().is_none_or(|role| role == "assistant") => { + array(item.content) + .into_iter() + .filter_map(|part| part_offset(Some(part), text)) + .min() + } + Some("function_call") => function_offset(item, text), + _ => None, + } +} + +fn responses_offset(response: Fields<'_>, text: &str) -> Option { + array(response.output) + .into_iter() + .filter_map(|item| item_offset(Some(item), text)) + .min() +} + +fn json_offset(text: &str, protocol: OutputProtocol, streaming: bool) -> Option { + let root: Fields<'_> = serde_json::from_str(text).ok()?; + match protocol { + OutputProtocol::OpenAiChat => array(root.choices) + .into_iter() + .filter_map(|choice| { + let choice = fields(Some(choice)); + message_offset( + fields(if streaming { + choice.delta + } else { + choice.message + }), + text, + ) + }) + .min(), + OutputProtocol::OpenAiResponses => responses_offset(root, text), + } +} + +fn response_event_offset(text: &str, event: Option<&str>) -> Option { + let root: Fields<'_> = serde_json::from_str(text).ok()?; + if event + .zip(root.kind.as_deref()) + .is_some_and(|(event, kind)| event != kind) + { + return None; + } + match root.kind.as_deref().or(event)? { + "response.output_text.delta" + | "response.refusal.delta" + | "response.function_call_arguments.delta" => string_offset(root.delta, text), + "response.output_text.done" => string_offset(root.text, text), + "response.refusal.done" => string_offset(root.refusal, text), + "response.function_call_arguments.done" => string_offset(root.arguments, text), + "response.content_part.added" | "response.content_part.done" => { + part_offset(root.part, text) + } + "response.output_item.added" | "response.output_item.done" => item_offset(root.item, text), + "response.completed" | "response.incomplete" => { + responses_offset(fields(root.response), text) + } + // created, role, usage, reasoning and error/control-only events do not establish model content. + _ => None, + } +} + +fn sse_offset(text: &str, protocol: OutputProtocol) -> Option { + let mut data = String::new(); + let mut segments = Vec::new(); + let mut event = None; + let mut original = 0; + // LF and CRLF framing, matching the supported SSE wire profiles. Unfinished events are not dispatched. + for line in text.split_inclusive('\n') { + let line_start = original; + original += line.len(); + let Some(line) = line.strip_suffix('\n') else { + break; + }; + let line = line.strip_suffix('\r').unwrap_or(line); + if line.is_empty() { + let offset = match protocol { + OutputProtocol::OpenAiChat => json_offset(&data, protocol, true), + OutputProtocol::OpenAiResponses => response_event_offset(&data, event), + }; + if let Some(offset) = offset { + return segments.iter().find_map(|&(joined, start, len)| { + (offset >= joined && offset < joined + len).then(|| start + offset - joined) + }); + } + data.clear(); + segments.clear(); + event = None; + } else if let Some(value) = line.strip_prefix("data:") { + let value = value.strip_prefix(' ').unwrap_or(value); + if !segments.is_empty() { + data.push('\n'); + } + let start = line_start + line.len() - value.len(); + segments.push((data.len(), start, value.len())); + data.push_str(value); + } else if let Some(value) = line.strip_prefix("event:") { + event = Some(value.strip_prefix(' ').unwrap_or(value)); + } + } + None +} diff --git a/gateway/crates/pc-gateway-protocol/src/lib.rs b/gateway/crates/pc-gateway-protocol/src/lib.rs index 962dc96a73..b58e0fdf84 100644 --- a/gateway/crates/pc-gateway-protocol/src/lib.rs +++ b/gateway/crates/pc-gateway-protocol/src/lib.rs @@ -19,9 +19,11 @@ //! 不任意合并旧消息、不静默重映射目标。 mod canonical; +mod content; mod render; mod sse; pub use canonical::*; +pub use content::{first_model_content_offset, OutputProtocol}; pub use render::*; pub use sse::*; diff --git a/gateway/crates/pc-gateway-protocol/tests/content_boundary.rs b/gateway/crates/pc-gateway-protocol/tests/content_boundary.rs new file mode 100644 index 0000000000..0cfa0713c9 --- /dev/null +++ b/gateway/crates/pc-gateway-protocol/tests/content_boundary.rs @@ -0,0 +1,153 @@ +// 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. + +use pc_gateway_protocol::{first_model_content_offset, OutputProtocol}; + +fn assert_at(body: &str, protocol: OutputProtocol, sse: bool, content: &str) { + let offset = first_model_content_offset(body.as_bytes(), protocol, sse) + .expect("model content must be recognized"); + assert!( + body[offset..].starts_with(content), + "offset {offset} does not locate {content}" + ); +} + +#[test] +fn json_model_content_ignores_metadata_and_preserves_wire_offsets() { + assert_at( + r#"{"metadata":{"content":"DECOY"}, "choices":[{"message":{"role":"assistant","content":"你好\\nactual"}}]}"#, + OutputProtocol::OpenAiChat, + false, + "你好", + ); + assert_at( + r#"{"choices":[{"message":{"content":null,"tool_calls":[{"function":{"arguments":"{\\\"x\\\":1}","name":"tool"}}]}}]}"#, + OutputProtocol::OpenAiChat, + false, + "{", + ); + assert_at( + r#"{"choices":[{"message":{"content":"","refusal":"refused"}}]}"#, + OutputProtocol::OpenAiChat, + false, + "refused", + ); + assert_at( + r#"{"output":[{"type":"reasoning","summary":[{"text":"DECOY"}]},{"type":"message","content":[{"type":"output_text","text":"actual"}]}]}"#, + OutputProtocol::OpenAiResponses, + false, + "actual", + ); + assert_at( + r#"{"output":[{"type":"function_call","arguments":"{}","name":"tool"}]}"#, + OutputProtocol::OpenAiResponses, + false, + "{", + ); + assert_at( + r#"{"output":[{"type":"message","content":[{"type":"refusal","refusal":"refused"}]}]}"#, + OutputProtocol::OpenAiResponses, + false, + "refused", + ); + assert_at( + r#"{"output":[{"type":"message","content":[{"type":"output_text","text":"\u4f60\u597d"}]}]}"#, + OutputProtocol::OpenAiResponses, + false, + r"\u4f60", + ); +} + +#[test] +fn empty_error_and_unsupported_output_do_not_invent_a_content_boundary() { + for (protocol, body) in [ + ( + OutputProtocol::OpenAiChat, + r#"{"error":{"message":"DECOY"}}"#, + ), + ( + OutputProtocol::OpenAiChat, + r#"{"choices":[{"message":{"role":"user","content":"DECOY"}}]}"#, + ), + ( + OutputProtocol::OpenAiChat, + r#"{"choices":[{"message":{"content":"","tool_calls":[]}}],"usage":{"content":"DECOY"}}"#, + ), + ( + OutputProtocol::OpenAiResponses, + r#"{"output":[{"type":"message","content":[{"type":"image","text":"DECOY"}]}]}"#, + ), + ( + OutputProtocol::OpenAiResponses, + r#"{"output":[],"text":"DECOY"}"#, + ), + ( + OutputProtocol::OpenAiResponses, + r#"{"output":[{"type":"message","content":[{"type":"output_text","text":""}]}]}"#, + ), + ( + OutputProtocol::OpenAiResponses, + r#"{"output":[{"type":"message","role":"user","content":[{"type":"output_text","text":"DECOY"}]}]}"#, + ), + (OutputProtocol::OpenAiChat, "malformed"), + ] { + assert_eq!( + first_model_content_offset(body.as_bytes(), protocol, false), + None, + "{body}" + ); + } +} + +#[test] +fn chat_sse_skips_roles_empty_deltas_usage_and_done_before_content() { + let body = "data: {\"choices\":[{\"delta\":{\"role\":\"assistant\",\"content\":\"\"}}]}\r\n\r\ndata: {\"usage\":{\"text\":\"DECOY\"},\"choices\":[]}\r\n\r\ndata: {\"choices\":[{\"delta\":{\"content\":\"actual\"}}]}\r\n\r\ndata: [DONE]\r\n\r\n"; + assert_at(body, OutputProtocol::OpenAiChat, true, "actual"); + let tool = "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"function\":{\"arguments\":\"{\"}}]}}]}\n\n"; + assert_at(tool, OutputProtocol::OpenAiChat, true, "{"); +} + +#[test] +fn responses_sse_locates_content_after_controls_across_multiline_data() { + let body = ": comment\r\nevent: response.created\r\ndata: {\"type\":\"response.created\",\"delta\":\"DECOY\"}\r\n\r\nevent: response.output_text.delta\r\ndata: {\"type\":\"response.output_text.delta\",\r\ndata: \"delta\":\"actual\"}\r\n\r\n"; + assert_at(body, OutputProtocol::OpenAiResponses, true, "actual"); + let refusal = "event: response.refusal.delta\ndata: {\"delta\":\"refused\"}\n\n"; + assert_at(refusal, OutputProtocol::OpenAiResponses, true, "refused"); + let tool = "data: {\"type\":\"response.function_call_arguments.delta\",\"delta\":\"{\"}\n\n"; + assert_at(tool, OutputProtocol::OpenAiResponses, true, "{"); + let item = "data: {\"type\":\"response.output_item.added\",\"item\":{\"type\":\"function_call\",\"name\":\"tool\",\"arguments\":\"\"}}\n\n"; + assert_at(item, OutputProtocol::OpenAiResponses, true, "tool"); +} + +#[test] +fn control_only_conflicting_and_unterminated_sse_remain_without_content() { + for body in [ + "event: response.created\ndata: {\"type\":\"response.created\",\"delta\":\"DECOY\"}\n\n", + "event: response.created\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"DECOY\"}\n\n", + "data: {\"type\":\"response.output_text.delta\",\"delta\":\"\"}\n\n", + "data: {\"type\":\"response.output_text.delta\",\"delta\":\"DECOY\"}\n", + "data: {\"type\":\"response.failed\",\"error\":{\"message\":\"DECOY\"}}\n\n", + ] { + assert_eq!(first_model_content_offset(body.as_bytes(), OutputProtocol::OpenAiResponses, true), None, "{body}"); + } +} + +#[test] +fn large_content_needs_no_fixed_observer_buffer_or_content_copy() { + let content = "x".repeat(256 * 1024); + let body = format!(r#"{{"choices":[{{"message":{{"content":"{content}"}}}}]}}"#); + let offset = + first_model_content_offset(body.as_bytes(), OutputProtocol::OpenAiChat, false).unwrap(); + assert_eq!(&body[offset..offset + content.len()], content); +} From 14d426cbb4d35bf1e812ba9f62ac30a8f61e10ff Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Fri, 6 Nov 2026 11:41:13 +0800 Subject: [PATCH 06/15] docs(gateway): record first-content delivery validation --- gateway/EVIDENCE_VALIDATION.md | 43 +++++++++++++++++++++------------- 1 file changed, 27 insertions(+), 16 deletions(-) diff --git a/gateway/EVIDENCE_VALIDATION.md b/gateway/EVIDENCE_VALIDATION.md index f631047650..375c07ac61 100644 --- a/gateway/EVIDENCE_VALIDATION.md +++ b/gateway/EVIDENCE_VALIDATION.md @@ -1,8 +1,8 @@ # Gateway evidence validation / Gateway 证据验收 - Date / 日期: 2026-11-06. -- Implementation commit / 实现提交: `bffc3980bbece93c86948b62f70446d90b08affb`. -- Master base / master 基线: `69b2d7e2ac1aacc05f386d04d4616aa9254b3f5d`; fetched at start and rechecked before delivery. +- Implementation commit / 实现提交: `2a686028262f9ac10f1d9f3c95ad7c4e923aba38`. +- Master base / master 基线: `69b2d7e2ac1aacc05f386d04d4616aa9254b3f5d`; latest master rechecked at `24e0017e0504f2980300ed87b21412bb425b1744` (no additional Gateway changes). - Platform / 平台: Darwin arm64, Rust `1.95.0 (59807616e 2026-04-14)`, Python 3.13.15. - Scope / 范围: [#2463](https://github.com/oceanbase/powercontext/issues/2463), [planning discussion / 规划讨论 #2433](https://github.com/oceanbase/powercontext/discussions/2433). @@ -31,18 +31,16 @@ Cargo was invoked through `/Users/lioky/.cargo/bin/cargo` because the shell's mi | --- | --- | | `cargo fmt --manifest-path gateway/Cargo.toml --all --check` | Passed / 通过 | | `cargo clippy --locked --manifest-path gateway/Cargo.toml --all-targets -- -D warnings` | Passed / 通过 | -| `cargo test --locked --manifest-path gateway/Cargo.toml --workspace` | 149 exercised behavior tests passed; 4 live-Core cases returned early / 149 个实际行为测试通过,4 个真实 Core 用例提前返回 | -| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-app --test evidence_process` | Real spawned Gateway, 1000 enabled + 100 disabled requests passed / 真实 Gateway 子进程,启用 1000 次与关闭 100 次请求通过 | +| `cargo test --locked --manifest-path gateway/Cargo.toml --workspace` | 158 exercised behavior tests passed; 4 live-Core cases returned early / 158 个实际行为测试通过,4 个真实 Core 用例提前返回 | +| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-app` | Real spawned Gateway, 1000 enabled + 100 disabled requests passed / 真实 Gateway 子进程,启用 1000 次与关闭 100 次请求通过 | | `make check` | Passed, including lock/policy checks, hooks, types and 61 integration-manifest tests / 通过,包含锁文件/策略检查、hooks、类型及 61 个集成清单测试 | | `uv run prek run -a` | Passed with all implementation files staged / 实现文件暂存后通过 | | `make docs-test` | Passed: bilingual links and static build, 1084 public pages verified / 双语链接与静态构建通过,验证 1084 个公开页面 | | `git diff --check` | Passed / 通过 | -The workspace runner prints 153 passing test cases. Four `live_context_check` cases return early when the real Core +The workspace runner prints 162 passing test cases. Four `live_context_check` cases return early when the real Core at `127.0.0.1:8000` is unavailable; readiness was unavailable here. Those four are not real-Core acceptance evidence. -workspace 输出共 153 个通过用例;其中 4 个 `live_context_check` 因真实 Core 不可达而提前返回,不能算作真实 Core 验收。 -The documentation build emitted existing CSS `::highlight` compatibility warnings and completed successfully. -文档构建出现既有 CSS `::highlight` 兼容性警告,构建成功。 +workspace 输出共 162 个通过用例;其中 4 个 `live_context_check` 因真实 Core 不可达而提前返回,不能算作真实 Core 验收。 ## Observed behavior / 实际覆盖 @@ -52,10 +50,18 @@ The documentation build emitted existing CSS `::highlight` compatibility warning | Usage through real transport / 真实 transport usage | Local HTTP JSON/SSE fixtures verify Chat/Responses input, output, cached reads, known zero and missing/malformed usage; cache writes stay unknown / 核对两种协议的输入、输出、缓存读、已知零及缺失/畸形 usage,缓存写保持未知 | | Bounded retention and visible loss / 有界保留与可见丢失 | A held writer with capacity 4 receives 100000 extra submissions: exactly 4 queue, 99996 drop; 1 record remains in flight, and recovered output reports loss / 容量 4 且 writer 卡住时额外提交 10 万条,4 条排队、99996 条丢弃、1 条在写,恢复输出含丢失计数 | | Business isolation / 业务隔离 | Blocking/full and I/O-error writers preserve release/withhold decisions and pending-send cancellation/drop facts; errors are counted without their text / 慢写/队列满/I/O 错误不改变释放与 withhold 结论及发送中取消/销毁事实,错误仅计数不输出原文 | -| Timing and strict order / 计时与 strict 顺序 | Header-wait fixture is included in first-byte timing; incomplete responses retain observed status/first byte; release approval precedes framework handoff and first body frame; model TTFT is null / 首字节包含响应头等待,部分失败保留已知状态与首字节,批准先于框架交接及首 frame,模型 TTFT 为 null | +| Timing and strict order / 计时与 strict 顺序 | Header-wait fixture is included in first-byte timing; incomplete responses retain observed status/first byte; release approval precedes framework handoff, first body frame and first model-content observation; model TTFT is null / 首字节包含响应头等待,部分失败保留已知状态与首字节,批准先于框架交接、首 frame 与首次模型内容观测,模型 TTFT 为 null | | Privacy / 隐私 | Synthetic prompt/response/model/request-ID/credential/provider-error/I/O-error markers are absent from evidence; process test also checks stderr / 合成 prompt、响应、模型名、请求 ID、凭据、provider 异常及 I/O 异常标记未出现在证据中,进程测试另检查 stderr | -| Real production composition / 真实生产装配 | Spawned binary handles 1000 requests with 5000 readable records and 1000 distinct call IDs; explicit Noop handles 100 requests with empty stdout and an evidence-disabled startup diagnostic / 真实二进制处理 1000 次请求,输出 5000 条可读记录、1000 个不同调用 ID;显式 Noop 处理 100 次请求,stdout 为空且启动诊断说明证据关闭 | -| Both ingress formats / 两种入口格式 | In-process public-router tests send 200 calls through actual reqwest to local HTTP fixtures, including Responses SSE replay, and read serialized production-sink output / 进程内公开路由用真实 reqwest 完成 200 次本地 HTTP 调用,含 Responses SSE 重放,并读取生产 sink 的序列化输出 | +| Real production composition / 真实生产装配 | Spawned binary handles 1000 requests with 6000 readable records and 1000 distinct call IDs; explicit Noop handles 100 requests with empty stdout and an evidence-disabled startup diagnostic / 真实二进制处理 1000 次请求,输出 6000 条可读记录、1000 个不同调用 ID;显式 Noop 处理 100 次请求,stdout 为空且启动诊断说明证据关闭 | +| Both ingress formats / 两种入口格式 | In-process public-router tests send 200 calls through actual reqwest to local HTTP fixtures, covering Chat JSON/SSE and Responses JSON/replayed SSE, and read 1200 serialized production-sink records / 进程内公开路由用真实 reqwest 完成 200 次本地 HTTP 调用,覆盖 Chat JSON/SSE 与 Responses JSON/重放 SSE,读取生产 sink 的 1200 条序列化输出 | + +Protocol fixtures cover text, refusals and function output, metadata/control decoys, escaped/Unicode content, +LF/CRLF multiline SSE, malformed/empty output and 256 KiB content. Body-observer tests split each sample at every +byte position, verify unchanged outgoing bytes, defer first-content observation until the matching frame, and +verify that control-only or dropped-before-content output does not invent content delivery. +协议 fixture 覆盖文本、拒绝与函数输出、元数据/控制事件干扰、转义/Unicode 内容、LF/CRLF 多行 SSE、 +畸形/空输出及 256 KiB 内容。body 观察器测试在样本每个字节位置切分,验证输出字节不变、 +首次内容观测等待对应 frame,以及只有控制事件或读到内容之前丢弃时不伪造内容交付。 ## Evidence limits / 证据边界 @@ -63,15 +69,20 @@ Local Core/provider HTTP fixtures and fake-Gate executor tests are distinct from hosted model provider, external telemetry backend, or native agent host. Those external environments were not executed. The spawned-process test establishes the Rust Gateway's production assembly and local HTTP behavior, not a third-party agent's cancellation, socket-write visibility or task adoption. No paid model calls were made. -The first nonempty body frame can contain only SSE control events. First model-content delivery is unmeasured; -this evidence does not establish the literal first-content boundary in #2463 behavior 4. G8 must treat that metric -as unknown rather than substituting `first_body_frame`. +`first_model_content` observes the framework polling a frame containing the first encoded byte of supported +model output; it is separate from `first_body_frame` and does not prove socket writing or client receipt. +Unsupported/empty output and bodies dropped before content have no content event; missing records and sink loss +must remain unavailable evidence. Closing #2463 still requires integration acceptance of actual total-deadline and +cancellation interruption owned by [#2462](https://github.com/oceanbase/powercontext/issues/2462). The shared control +and future-destruction observations tested here do not establish automatic interruption. 本地 Core/provider HTTP fixture、FakeGate 执行器测试不等同于真实 PowerContext Core、真实模型供应商、外部观测后端 或原生 agent 宿主;这些外部环境未执行。真实子进程测试证明 Rust Gateway 生产装配及本地 HTTP 行为, 不证明第三方 agent 的取消能力、实际 socket 写出或任务采用,没有调用付费模型。 -首个非空 body frame 可能仅包含 SSE 控制事件;首次模型内容交付没有测量,不能据此宣称已验收 -#2463 行为 4 中字面上的首次内容边界。G8 必须将该指标视为未知,不能使用 `first_body_frame` 替代。 +`first_model_content` 记录框架轮询到包含受支持模型输出首个编码字节的 frame,与 `first_body_frame` 分开, +不证明 socket 写出或客户端收到。不支持/空输出及内容之前丢弃的 body 不产生内容事件;记录缺失与 sink 丢失 +均不能当作耗时为零。关闭 #2463 仍需验收 #2462 所拥有的实际总期限与取消中断集成; +本报告验证的共享控制与 future 销毁观测不能证明自动中断。 No OpenAPI contract, Python operational fields, database records or dependency lockfiles changed. The Gateway's client-visible HTTP 503 `gate_paused.detail` is normalized for Core-unavailable and malformed-response From eb0deda1b746fc277ea3cc109390c55d12f6c9d7 Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Fri, 6 Nov 2026 11:56:05 +0800 Subject: [PATCH 07/15] fix(gateway): align evidence lifecycle and redact startup logs --- docs/en/docs/operate/gateway-evidence.md | 44 ++++++- docs/en/docs/operate/observability.md | 4 + docs/zh/docs/operate/gateway-evidence.md | 41 +++++- docs/zh/docs/operate/observability.md | 4 + gateway/Cargo.lock | 1 + gateway/README.md | 2 +- gateway/crates/pc-gateway-app/src/link.rs | 4 +- gateway/crates/pc-gateway-app/src/main.rs | 7 +- gateway/crates/pc-gateway-app/src/proxy.rs | 2 +- .../pc-gateway-app/tests/evidence_process.rs | 38 +++++- .../crates/pc-gateway-core/src/evidence.rs | 11 +- .../crates/pc-gateway-core/src/executor.rs | 17 +++ .../crates/pc-gateway-core/src/lifecycle.rs | 53 +++----- .../tests/executor_semantics.rs | 14 ++ gateway/crates/pc-gateway-evidence/Cargo.toml | 1 + gateway/crates/pc-gateway-evidence/src/lib.rs | 26 +--- .../crates/pc-gateway-evidence/src/output.rs | 48 ++++++- .../pc-gateway-evidence/tests/output.rs | 123 ++++++++++++++++++ gateway/crates/pc-gateway-types/src/lib.rs | 6 +- .../crates/pc-gateway-types/src/lifecycle.rs | 47 +++++++ 20 files changed, 406 insertions(+), 87 deletions(-) create mode 100644 gateway/crates/pc-gateway-types/src/lifecycle.rs diff --git a/docs/en/docs/operate/gateway-evidence.md b/docs/en/docs/operate/gateway-evidence.md index 62f04ab04a..ca5e6060c4 100644 --- a/docs/en/docs/operate/gateway-evidence.md +++ b/docs/en/docs/operate/gateway-evidence.md @@ -25,7 +25,7 @@ A stalled stdout can occupy the one exporter thread but cannot accumulate more t The rest of the Gateway still has its own request/response buffers and concurrency limits. Every readable line has `schema`, `operation=gateway.model_call`, `unit` (`call`, `attempt`, `delivery`), -`event` (the same three values), `evidence`, and `loss`. The process-local cumulative `loss.dropped`, +`event` (the same three values), `outcome`, `duration_ms`, `evidence`, and `loss`. The process-local cumulative `loss.dropped`, `loss.write_failed` and `loss.written` count discarded submissions, failed/unconfirmed record writes, and completed write-and-flush operations respectively, sampled before that line's write. Recovered output reports earlier losses; an embedding host can also read `JsonEvidenceSink.stats()` during congestion. No execution IDs are metric labels. @@ -35,6 +35,41 @@ the exporter restores a newline boundary before the next record. Counters reset billing/audit durability guarantee, and no financial reconciliation, token savings or task-success claim. If the worker cannot start, the application reports a fixed diagnostic and uses Noop without changing business results. +## Operational vocabulary and exporter boundary + +The [Server operational contract](observability.md) and the managed stack from +[#2388](https://github.com/oceanbase/powercontext/pull/2388) use bounded operation/unit/outcome fields. +Gateway evidence uses the same field meanings with its own operation, `gateway.model_call`: it counts one local +managed model execution, not a Core `context_check` application operation or a worker inference generation. +`unit=call` counts logical executions, `attempt` counts real transport handoffs, and `delivery` describes local +framework observations. Do not sum the three units or count delivery events as additional calls. + +| Evidence facts | Top-level operational `outcome` | +| --- | --- | +| Call `release_authorized` or `degraded`, observed upstream status < 400 | `success` | +| Same terminals with observed upstream status >= 400 | `failure` | +| Same terminals with missing upstream status | null | +| Call `blocked`, `withheld`, `admission_expired` | `blocked` | +| Call `send_indeterminate`, `not_sent`, `gate_paused` | `failure` | +| Call `abandoned`, regardless of observed interruption intent/deadline | null | +| Attempt `delivered` | `success` | +| Attempt `possibly_sent` on future destruction | null | +| Other terminal attempt outcomes | `failure` | +| Any delivery observation | null | + +Null is unavailable classification, not `success` or `noop`. In particular, destruction-time cancellation intent +is not a confirmed cancellation cause and is not projected as `cancelled`. Keep the nested terminal, sending, +interruption and attempt outcome fields: the common outcome does not replace them. `success` here does not prove +strict release authorization for degraded output, client receipt, task adoption or task success. +Top-level `duration_ms` copies call/attempt duration; it is null for delivery, whose `elapsed_ms` has a different origin. + +The existing managed Collector receives Server OTLP logs and reduces them through the Server field allowlist. +It does **not** ingest Gateway stdout by default, and that transform would discard nested `schema/evidence/loss`. +Keep the complete JSONL in a collector with bounded retention; feeding it through the Server formatter or current +OTLP pipeline is not a supported evidence-preserving path. The common fields enable vocabulary-compatible queries; +this implementation adds no Prometheus metrics, OTLP exporter or duplicate monitoring stack. External Collector/Loki +storage and readback have not been verified for this stream. + ## Correlation and coverage `call_id` identifies one execution and joins its `call`, numbered `attempt`, and `delivery` records. @@ -58,6 +93,8 @@ exported and are not model-send facts. The `call` record contains `terminal`, `sending`, `attempts`, `upstream_status`, normalized `usage`, optional `interruption`, and timing fields. Terminal values are `release_authorized`, `blocked`, `withheld`, `send_indeterminate`, `not_sent`, `gate_paused`, `degraded`, `admission_expired`, and `abandoned`. +Lifecycle snapshots and evidence share `ExecutionTerminal` and `ModelSendState` from `pc-gateway-types`; +`ManagedOutcome` has one terminal mapping. Existing Rust import names in core and evidence remain re-exports. `sending` independently reports `no_send`, `definitely_not_sent`, `possibly_sent`, or `response_received`. A release refusal or expiry after a response preserves `response_received` and any reported usage. @@ -138,6 +175,11 @@ socket writes. Non-streaming Responses JSON's first byte and replayed SSE output ## Deployment and compatibility +Operational diagnostics identify TCP/UDS connection mode without logging the configured Core URL or socket path. +Invalid injection settings omit the supplied value; steering-file rejection uses fixed reasons without a file path. +Operators should inspect their protected configuration for endpoints and paths. +The additive top-level `outcome` and `duration_ms` fields preserve the nested domain records. Consumers must accept +null classifications, including abandoned execution and delivery observations. The additive `delivery.boundary=first_model_content` value requires consumers with exhaustive enum matching to accept the new value; consumers must not assume a fixed number of records per call. Collectors that previously consumed human tracing from stdout must move that input to stderr and parse evidence diff --git a/docs/en/docs/operate/observability.md b/docs/en/docs/operate/observability.md index cc9528da11..322f8044ea 100644 --- a/docs/en/docs/operate/observability.md +++ b/docs/en/docs/operate/observability.md @@ -10,6 +10,10 @@ These signals describe service behavior; they do not replace inspection of store For a provisioned local metrics/trace/log backend, see the [reference observability stack](reference-observability-stack.md). +Rust Gateway call evidence uses its own `gateway.model_call` operation with `call`, `attempt`, and `delivery` units. +Its common outcome projection and exporter limits are defined in the [Gateway evidence contract](gateway-evidence.md). +The managed Server OTLP pipeline does not ingest that JSONL stream by default. + ## Logs The foreground Server writes operational logs to its process output. Configure diff --git a/docs/zh/docs/operate/gateway-evidence.md b/docs/zh/docs/operate/gateway-evidence.md index a8008074ef..b49c2c1ef9 100644 --- a/docs/zh/docs/operate/gateway-evidence.md +++ b/docs/zh/docs/operate/gateway-evidence.md @@ -23,7 +23,7 @@ PC_GATEWAY_EVIDENCE=off ./gateway/target/release/pc-gateway 不会持续增加线程或队列条目。Gateway 的请求/响应缓冲与并发仍有各自的资源限制。 每行包含 `schema`、`operation=gateway.model_call`、`unit`(`call`、`attempt`、`delivery`)、 -`event`(同样的三个值)、`evidence` 和 `loss`。进程内累计的 `loss.dropped`、`loss.write_failed`、 +`event`(同样的三个值)、`outcome`、`duration_ms`、`evidence` 和 `loss`。进程内累计的 `loss.dropped`、`loss.write_failed`、 `loss.written` 分别统计被丢弃的提交、失败或无法确认的记录写出、完成写入并 flush 的记录, 采样发生在当前行写出之前。恢复后的输出会携带此前的丢失计数;嵌入宿主也能在拥塞时读取 `JsonEvidenceSink.stats()`。执行身份不作为指标标签。 @@ -32,6 +32,38 @@ PC_GATEWAY_EVIDENCE=off ./gateway/target/release/pc-gateway 没有重放、计费或审计持久性保证,也不建立财务对账、token 节省或任务成功结论。 写出线程无法启动时,应用输出固定诊断并使用 Noop,不改变业务结果。 +## 运维词汇与 exporter 边界 + +[Server 运维契约](observability.md)和 [#2388](https://github.com/oceanbase/powercontext/pull/2388) +的托管监控栈使用有界的 operation/unit/outcome 字段。Gateway 证据沿用这些字段的含义, +使用自身所属操作 `gateway.model_call`:统计一次本地托管模型执行,不是 Core 的 `context_check` +application operation,也不是 worker 的 inference generation。 +`unit=call` 统计逻辑执行,`attempt` 统计实际 transport 交接,`delivery` 描述本地框架观测。 +三种 unit 不能相加,delivery 事件也不能当作额外调用。 + +| 证据事实 | 顶层运维 `outcome` | +| --- | --- | +| 调用 `release_authorized` 或 `degraded`,已观察上游状态码 < 400 | `success` | +| 同上,已观察上游状态码 >= 400 | `failure` | +| 同上,上游状态码缺失 | null | +| 调用 `blocked`、`withheld`、`admission_expired` | `blocked` | +| 调用 `send_indeterminate`、`not_sent`、`gate_paused` | `failure` | +| 调用 `abandoned`,不论销毁时的取消意图/期限事实 | null | +| 尝试 `delivered` | `success` | +| future 销毁时的尝试 `possibly_sent` | null | +| 其他终态尝试结果 | `failure` | +| 任何 delivery 观测 | null | + +null 表示分类不可得,不是 `success` 或 `noop`。销毁时存在取消意图不能证明取消原因,因此不投影为 +`cancelled`。保留嵌套的 terminal、sending、interruption 和尝试 outcome;通用 outcome 不能替代这些事实。 +这里的 `success` 不证明降级输出获得 strict 释放批准、客户端收到、任务采用或任务成功。 +顶层 `duration_ms` 复制调用/尝试耗时;delivery 为 null,因为其 `elapsed_ms` 使用不同的起点。 + +现有托管 Collector 接收 Server OTLP 日志,并通过 Server 字段白名单精简;默认**不采集** Gateway stdout, +该 transform 也会丢弃嵌套的 `schema/evidence/loss`。完整 JSONL 应交给具有有界保留策略的采集器; +通过 Server formatter 或当前 OTLP pipeline 转发不能保全此证据流。公共字段用于词汇兼容的查询, +本实现不新增 Prometheus 指标、OTLP exporter 或重复监控栈;未验证该流在外部 Collector/Loki 中的存储与读回。 + ## 关联与覆盖范围 `call_id` 标识一次执行,关联它的 `call`、编号 `attempt` 和 `delivery` 记录。 @@ -53,6 +85,8 @@ PC_GATEWAY_EVIDENCE=off ./gateway/target/release/pc-gateway `call` 记录包含 `terminal`、`sending`、`attempts`、`upstream_status`、归一化 `usage`、 可选 `interruption` 和计时字段。终态取值为 `release_authorized`、`blocked`、`withheld`、 `send_indeterminate`、`not_sent`、`gate_paused`、`degraded`、`admission_expired`、`abandoned`。 +生命周期快照与证据共享 `pc-gateway-types` 的 `ExecutionTerminal`、`ModelSendState`; +`ManagedOutcome` 只保留一处终态映射。core 与 evidence 现有 Rust 导入名称继续通过重导出提供。 `sending` 独立表示 `no_send`、`definitely_not_sent`、`possibly_sent`、`response_received`。 取得响应后发生释放拒绝或期限过期,仍保留 `response_received` 与已上报的 usage。 @@ -130,6 +164,11 @@ item-added 事件若确实包含函数名或输出文本,也可以建立内容 ## 部署与兼容 +运维诊断只说明 TCP/UDS 连接模式,不输出配置的 Core URL 或 socket 路径。 +非法 injection 配置不输出输入值;steering 文件拒绝使用固定原因,不包含文件路径。 +运维人员应从受保护配置中检查端点和路径。 +新增顶层 `outcome`、`duration_ms` 字段,嵌套领域记录保持原有含义。消费方必须接受 null 分类, +包括 abandoned 执行与 delivery 观测。 新增 `delivery.boundary=first_model_content` 值,穷举匹配枚举的消费方需要接受该值, 不能假定每次调用的记录数量固定。 原来从 stdout 采集人类可读 tracing 的部署,需要改为采集 stderr,并单独解析 stdout 证据。 diff --git a/docs/zh/docs/operate/observability.md b/docs/zh/docs/operate/observability.md index 09ece13a45..6c6e20b6a6 100644 --- a/docs/zh/docs/operate/observability.md +++ b/docs/zh/docs/operate/observability.md @@ -11,6 +11,10 @@ description: 通过日志定位请求,并查看 Server 指标与 Trace。 需要自动配置的本地 metrics、traces 和 logs 后端时,参见[参考监控环境](reference-observability-stack.md)。 +Rust Gateway 调用证据使用独立的 `gateway.model_call` 操作及 `call`、`attempt`、`delivery` 单位。 +通用 outcome 投影与 exporter 边界见 [Gateway 证据契约](gateway-evidence.md)。 +托管 Server OTLP pipeline 默认不采集该 JSONL 流。 + ## 日志 前台 Server 将运行日志写入进程输出。可配置 `POWERCONTEXT_SERVER_LOGGING_LEVEL`(默认 `INFO`)、 diff --git a/gateway/Cargo.lock b/gateway/Cargo.lock index 50c384da31..99a1ba4b70 100644 --- a/gateway/Cargo.lock +++ b/gateway/Cargo.lock @@ -681,6 +681,7 @@ dependencies = [ name = "pc-gateway-evidence" version = "0.1.0" dependencies = [ + "pc-gateway-types", "serde", "serde_json", ] diff --git a/gateway/README.md b/gateway/README.md index 8a0bfca8a7..9e29e06d56 100644 --- a/gateway/README.md +++ b/gateway/README.md @@ -28,7 +28,7 @@ An optional Rust executor for PowerContext, defined by the gateway design in #21 - **OpenAI-compatible ingress** at `/gateway/v1/chat/completions` and `/gateway/v1/responses` (same format in and out, no cross-format translation), authenticated by a gateway key that replaces provider keys. - **Responses fidelity**: on `/gateway/v1/responses`, every input item other than a plain user message (developer messages, tool calls and outputs, reasoning, client-specific items such as Codex's `additional_tools`) is forwarded unchanged, and request fields the ingress does not model (for example `reasoning`, `include`, `prompt_cache_key`) are passed through for Core's request allowlist to decide; only the client-local `client_metadata` is dropped. The upstream request is always non-streaming; a streaming client receives the released (or permitted degraded-passthrough, still marked `x-pc-degraded`) 200 response replayed as Responses SSE events: `response.created`, `response.output_item.added`/`done` per item with each message content part as `response.content_part.added`/`done` around one buffered `response.output_text.delta`/`done` (or `response.refusal.delta`/`done`), and a terminal event chosen from the response status (`response.completed`, `response.incomplete`, or `response.failed` when the status is `failed`/`cancelled` or an `error` is present). - **Middleware chain**: composable `GatewayMiddleware` trait; ships with resource limits (request-body precheck + concurrency semaphore, health probe exempt) and request-id propagation (`x-powercontext-request-id`, client-supplied or generated, echoed on responses). -- **Body-free evidence**: bounded JSONL on stdout (1024 queued records plus one in flight), correlated call/attempt terminals, per-field usage completeness and cache reads, explicit first-byte/release/framework timing and separate first model-content frame observation; model TTFT stays unknown. Operational tracing uses stderr. See the [output and deployment contract](../docs/en/docs/operate/gateway-evidence.md) / [中文](../docs/zh/docs/operate/gateway-evidence.md). `PC_GATEWAY_EVIDENCE=off` explicitly disables coverage. +- **Body-free evidence**: bounded JSONL on stdout (1024 queued records plus one in flight), correlated call/attempt terminals, per-field usage completeness and cache reads, explicit first-byte/release/framework timing and separate first model-content frame observation; model TTFT stays unknown. Operational tracing uses stderr and omits configured Core URLs/socket paths. Common operation/unit/outcome fields align with the Server vocabulary; the managed Server OTLP pipeline does not ingest Gateway JSONL by default. See the [output and deployment contract](../docs/en/docs/operate/gateway-evidence.md) / [中文](../docs/zh/docs/operate/gateway-evidence.md). `PC_GATEWAY_EVIDENCE=off` explicitly disables coverage. ## PC call sequence over UDS diff --git a/gateway/crates/pc-gateway-app/src/link.rs b/gateway/crates/pc-gateway-app/src/link.rs index 7abe2e6197..dcf016f29f 100644 --- a/gateway/crates/pc-gateway-app/src/link.rs +++ b/gateway/crates/pc-gateway-app/src/link.rs @@ -29,12 +29,12 @@ pub enum CoreLink { impl CoreLink { pub fn from_env() -> Self { if let Ok(sock) = std::env::var("PC_GATEWAY_CORE_UDS") { - tracing::info!(%sock, "core link: UDS (combined deployment)"); + tracing::info!("core link: UDS (combined deployment)"); Self::Uds(UdsGateClient::new(sock)) } else { let base = std::env::var("PC_GATEWAY_CORE_BASE") .unwrap_or_else(|_| "http://127.0.0.1:8000".into()); - tracing::info!(%base, "core link: TCP (standalone deployment)"); + tracing::info!("core link: TCP (standalone deployment)"); Self::Http(HttpGateClient::new(base)) } } diff --git a/gateway/crates/pc-gateway-app/src/main.rs b/gateway/crates/pc-gateway-app/src/main.rs index 93e8fcc78e..2d4958fcee 100644 --- a/gateway/crates/pc-gateway-app/src/main.rs +++ b/gateway/crates/pc-gateway-app/src/main.rs @@ -297,11 +297,8 @@ fn injection_mode(setting: Option<&str>, combined: bool) -> Injection { Some("off") => Injection::Off, None if combined => Injection::ConversationsOnly, None => Injection::Off, - Some(other) => { - tracing::warn!( - value = other, - "PC_GATEWAY_INJECTION must be on or off; injection disabled" - ); + Some(_) => { + tracing::warn!("PC_GATEWAY_INJECTION must be on or off; injection disabled"); Injection::Off } } diff --git a/gateway/crates/pc-gateway-app/src/proxy.rs b/gateway/crates/pc-gateway-app/src/proxy.rs index 2758e4b47c..0d45501b3a 100644 --- a/gateway/crates/pc-gateway-app/src/proxy.rs +++ b/gateway/crates/pc-gateway-app/src/proxy.rs @@ -57,7 +57,7 @@ impl ProxyState { let client = Client::builder(TokioExecutor::new()).build(UnixConnector { socket: PathBuf::from(&sock), }); - tracing::info!(%sock, "proxy: forwarding non-gateway routes to Python UDS"); + tracing::info!("proxy: forwarding non-gateway routes to Python UDS"); Self { inner: Some(Arc::new(ProxyInner { socket: PathBuf::from(sock), diff --git a/gateway/crates/pc-gateway-app/tests/evidence_process.rs b/gateway/crates/pc-gateway-app/tests/evidence_process.rs index 15601ebcc3..1ca4a59098 100644 --- a/gateway/crates/pc-gateway-app/tests/evidence_process.rs +++ b/gateway/crates/pc-gateway-app/tests/evidence_process.rs @@ -50,7 +50,11 @@ async fn production_jsonl_and_explicit_noop_keep_real_requests_usable() { "usage":{"prompt_tokens":101, "completion_tokens":13, "prompt_tokens_details":{"cached_tokens":61}} })) })); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let base = format!("http://{}", listener.local_addr().unwrap()); + let base = format!( + "http://SYNTHETIC_CORE_USER:SYNTHETIC_CORE_PASSWORD@{}/SYNTHETIC_PRIVATE_PATH", + listener.local_addr().unwrap() + ); + let fixture = Router::new().nest("/SYNTHETIC_PRIVATE_PATH", fixture); let fixture_task = tokio::spawn(async move { axum::serve(listener, fixture).await.unwrap(); }); @@ -74,7 +78,7 @@ async fn production_jsonl_and_explicit_noop_keep_real_requests_usable() { ) .env("PC_GATEWAY_API_KEY", "SYNTHETIC_GATEWAY_KEY") .env("PC_GATEWAY_UPSTREAM_API_KEY", "SYNTHETIC_PROVIDER_KEY") - .env("PC_GATEWAY_INJECTION", "off") + .env("PC_GATEWAY_INJECTION", "SYNTHETIC_INVALID_INJECTION_VALUE") .env("RUST_LOG", "info") .stdout(Stdio::piped()) .stderr(Stdio::piped()); @@ -161,6 +165,10 @@ async fn production_jsonl_and_explicit_noop_keep_real_requests_usable() { } if record["event"] == "call" { let evidence = &record["evidence"]; + assert_eq!(record["operation"], "gateway.model_call"); + assert_eq!(record["unit"], "call"); + assert_eq!(record["outcome"], "success"); + assert_eq!(record["duration_ms"], evidence["duration_ms"]); assert_eq!(evidence["terminal"], "release_authorized"); assert_eq!(evidence["usage"]["input"]["tokens"], 101); assert_eq!(evidence["usage"]["cache_read"]["tokens"], 61); @@ -175,3 +183,29 @@ async fn production_jsonl_and_explicit_noop_keep_real_requests_usable() { } fixture_task.abort(); } + +#[test] +fn rejected_startup_does_not_expose_uds_or_steering_paths() { + let mut command = Command::new(env!("CARGO_BIN_EXE_pc-gateway")); + for (key, _) in std::env::vars_os() { + if key.to_string_lossy().starts_with("PC_GATEWAY_") { + command.env_remove(key); + } + } + let missing = std::env::temp_dir() + .join(format!("SYNTHETIC_PRIVATE_STEERING_{}", std::process::id())) + .join("missing.txt"); + let output = command + .env("PC_GATEWAY_CORE_UDS", "/SYNTHETIC_PRIVATE_SOCKET/core.sock") + .env("PC_GATEWAY_STEERING_FILE", missing) + .env("RUST_LOG", "info") + .output() + .unwrap(); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); + let errors = String::from_utf8(output.stderr).unwrap(); + assert!(errors.contains("core link: UDS")); + assert!(errors.contains("proxy: forwarding")); + assert!(errors.contains("file cannot be read")); + assert!(!errors.contains("SYNTHETIC_")); +} diff --git a/gateway/crates/pc-gateway-core/src/evidence.rs b/gateway/crates/pc-gateway-core/src/evidence.rs index 38aa1054ee..3b5ba90cbe 100644 --- a/gateway/crates/pc-gateway-core/src/evidence.rs +++ b/gateway/crates/pc-gateway-core/src/evidence.rs @@ -142,16 +142,7 @@ impl<'a> CallRecorder<'a> { } pub(crate) fn finish(&mut self, outcome: &ManagedOutcome) { - self.call.terminal = match outcome { - ManagedOutcome::Released { .. } => Terminal::ReleaseAuthorized, - ManagedOutcome::Blocked { .. } => Terminal::Blocked, - ManagedOutcome::Withheld { .. } => Terminal::Withheld, - ManagedOutcome::SendIndeterminate => Terminal::SendIndeterminate, - ManagedOutcome::NotSent { .. } => Terminal::NotSent, - ManagedOutcome::GatePaused(_) => Terminal::GatePaused, - ManagedOutcome::Degraded { .. } => Terminal::Degraded, - ManagedOutcome::AdmissionExpired => Terminal::AdmissionExpired, - }; + self.call.terminal = outcome.terminal(); } } diff --git a/gateway/crates/pc-gateway-core/src/executor.rs b/gateway/crates/pc-gateway-core/src/executor.rs index f178db6747..3f9df7040f 100644 --- a/gateway/crates/pc-gateway-core/src/executor.rs +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -99,6 +99,23 @@ pub enum ManagedOutcome { AdmissionExpired, } +impl ManagedOutcome { + /// One terminal interpretation shared by lifecycle snapshots and evidence. + pub(crate) fn terminal(&self) -> crate::ExecutionTerminal { + use crate::ExecutionTerminal; + match self { + Self::Released { .. } => ExecutionTerminal::ReleaseAuthorized, + Self::Blocked { .. } => ExecutionTerminal::Blocked, + Self::Withheld { .. } => ExecutionTerminal::Withheld, + Self::SendIndeterminate => ExecutionTerminal::SendIndeterminate, + Self::NotSent { .. } => ExecutionTerminal::NotSent, + Self::GatePaused(_) => ExecutionTerminal::GatePaused, + Self::Degraded { .. } => ExecutionTerminal::Degraded, + Self::AdmissionExpired => ExecutionTerminal::AdmissionExpired, + } + } +} + pub struct Executor { gate: G, transport: T, diff --git a/gateway/crates/pc-gateway-core/src/lifecycle.rs b/gateway/crates/pc-gateway-core/src/lifecycle.rs index 5bf891e823..f2422eca38 100644 --- a/gateway/crates/pc-gateway-core/src/lifecycle.rs +++ b/gateway/crates/pc-gateway-core/src/lifecycle.rs @@ -1,34 +1,23 @@ +// 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. + use crate::ManagedOutcome; use std::sync::{Arc, Mutex, MutexGuard}; use tokio::sync::watch; use tokio::time::Instant; -/// Sending facts for the whole call, independent of authorization and local delivery. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ModelSendState { - /// No attempt has crossed the transport boundary. - NoSend, - /// Every attempted send was confirmed unsent by the transport. - DefinitelyNotSent, - /// An attempt was handed off without evidence ruling out sending. - PossiblySent, - /// A complete upstream response was obtained, regardless of release or decoding. - ResponseReceived, -} - -/// The local execution terminal; none of these establishes client receipt. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ExecutionTerminal { - ReleaseAuthorized, - Blocked, - Withheld, - SendIndeterminate, - NotSent, - GatePaused, - Degraded, - AdmissionExpired, - Abandoned, -} +pub use pc_gateway_types::{ExecutionTerminal, ModelSendState}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ExecutionState { @@ -164,17 +153,7 @@ impl Execution { } pub(crate) fn finish(&mut self, outcome: &ManagedOutcome) { - let terminal = match outcome { - ManagedOutcome::Released { .. } => ExecutionTerminal::ReleaseAuthorized, - ManagedOutcome::Blocked { .. } => ExecutionTerminal::Blocked, - ManagedOutcome::Withheld { .. } => ExecutionTerminal::Withheld, - ManagedOutcome::SendIndeterminate => ExecutionTerminal::SendIndeterminate, - ManagedOutcome::NotSent { .. } => ExecutionTerminal::NotSent, - ManagedOutcome::GatePaused(_) => ExecutionTerminal::GatePaused, - ManagedOutcome::Degraded { .. } => ExecutionTerminal::Degraded, - ManagedOutcome::AdmissionExpired => ExecutionTerminal::AdmissionExpired, - }; - self.control.shared.snapshot().execution = ExecutionState::Finished(terminal); + self.control.shared.snapshot().execution = ExecutionState::Finished(outcome.terminal()); } } diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index c018df97dc..4f4b6d5903 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -2988,6 +2988,13 @@ async fn terminal_evidence_covers_zero_send_release_refusal_and_paid_possibility assert_eq!(record.call_id, observation.call_id()); assert_eq!(record.terminal, expected_terminal, "{case}"); assert_eq!(record.sending, expected_send, "{case}"); + let snapshot = observation.snapshot(); + assert_eq!( + snapshot.execution, + ExecutionState::Finished(record.terminal), + "{case}" + ); + assert_eq!(snapshot.model_send, record.sending, "{case}"); assert_eq!(record.attempts, expected_attempts, "{case}"); assert!(record.upstream_ttft_ms.is_none()); assert!( @@ -3054,6 +3061,7 @@ async fn interrupted_model_send_keeps_paid_possibility_and_observed_stop_facts() None, ); let cancellation = control.cancellation(); + let observation = control.observation(); let renderer = RendererRef(renderer); let mut future = Box::pin(executor.run(control, call(DegradePolicy::Pause), &renderer, &evidence)); @@ -3070,6 +3078,12 @@ async fn interrupted_model_send_keeps_paid_possibility_and_observed_stop_facts() assert_eq!(record.terminal, Terminal::Abandoned); assert_eq!(record.sending, Sending::PossiblySent); assert_eq!(record.interruption, Some(expected)); + let snapshot = observation.snapshot(); + assert_eq!( + snapshot.execution, + ExecutionState::Finished(record.terminal) + ); + assert_eq!(snapshot.model_send, record.sending); let EvidenceEvent::Attempt(attempt) = &evidence.events()[0] else { panic!("missing attempt") }; diff --git a/gateway/crates/pc-gateway-evidence/Cargo.toml b/gateway/crates/pc-gateway-evidence/Cargo.toml index 0b939df869..d0a638810c 100644 --- a/gateway/crates/pc-gateway-evidence/Cargo.toml +++ b/gateway/crates/pc-gateway-evidence/Cargo.toml @@ -20,5 +20,6 @@ license.workspace = true description = "PowerContext Gateway: evidence normalization — usage completeness, cache read/write, latency; never bodies" [dependencies] +pc-gateway-types = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/gateway/crates/pc-gateway-evidence/src/lib.rs b/gateway/crates/pc-gateway-evidence/src/lib.rs index 897b26370d..c3d56f37bf 100644 --- a/gateway/crates/pc-gateway-evidence/src/lib.rs +++ b/gateway/crates/pc-gateway-evidence/src/lib.rs @@ -88,30 +88,8 @@ impl UsageEvidence { } } -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum Sending { - #[default] - NoSend, - DefinitelyNotSent, - PossiblySent, - ResponseReceived, -} - -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum Terminal { - ReleaseAuthorized, - Blocked, - Withheld, - SendIndeterminate, - NotSent, - GatePaused, - Degraded, - AdmissionExpired, - #[default] - Abandoned, -} +// Preserve the public evidence names while sharing the authoritative lifecycle fact types. +pub use pc_gateway_types::{ExecutionTerminal as Terminal, ModelSendState as Sending}; /// Facts observed on future drop; neither intent nor elapsed deadline proves its cause. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] diff --git a/gateway/crates/pc-gateway-evidence/src/output.rs b/gateway/crates/pc-gateway-evidence/src/output.rs index 62a0064045..1f6ca6b0c1 100644 --- a/gateway/crates/pc-gateway-evidence/src/output.rs +++ b/gateway/crates/pc-gateway-evidence/src/output.rs @@ -12,12 +12,50 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{AttemptEvidence, CallEvidence, DeliveryEvidence, EvidenceEvent, EvidenceSink}; +use crate::{ + AttemptEvidence, AttemptOutcome, CallEvidence, DeliveryEvidence, EvidenceEvent, EvidenceSink, + Terminal, +}; use serde::Serialize; use std::io::Write; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{mpsc, Arc}; +// Match the Server's bounded operational vocabulary without discarding domain facts. +#[derive(Serialize)] +#[serde(rename_all = "snake_case")] +enum OperationalOutcome { + Success, + Failure, + Blocked, +} + +fn operational_outcome(event: &EvidenceEvent) -> Option { + use OperationalOutcome::*; + match event { + EvidenceEvent::Call(call) => match call.terminal { + Terminal::ReleaseAuthorized | Terminal::Degraded => call + .upstream_status + .map(|status| if status >= 400 { Failure } else { Success }), + Terminal::Blocked | Terminal::Withheld | Terminal::AdmissionExpired => Some(Blocked), + Terminal::SendIndeterminate | Terminal::NotSent | Terminal::GatePaused => Some(Failure), + // Drop-time intent/deadline facts do not establish why the owner stopped execution. + Terminal::Abandoned => None, + }, + EvidenceEvent::Attempt(attempt) => match attempt.outcome { + AttemptOutcome::Delivered => Some(Success), + AttemptOutcome::PossiblySent => None, + AttemptOutcome::UpstreamError + | AttemptOutcome::ConnectRefused + | AttemptOutcome::RejectedLocally + | AttemptOutcome::LostAfterHandoff + | AttemptOutcome::TimeoutAwaitingResponse + | AttemptOutcome::BufferLimitExceeded => Some(Failure), + }, + EvidenceEvent::Delivery(_) => None, + } +} + #[derive(Debug, Clone, Copy, Default, Serialize)] pub struct EvidenceStats { pub dropped: u64, @@ -68,6 +106,8 @@ impl JsonEvidenceSink { schema: &'static str, operation: &'static str, unit: &'static str, + outcome: Option, + duration_ms: Option, #[serde(flatten)] event: &'a EvidenceEvent, loss: EvidenceStats, @@ -80,6 +120,12 @@ impl JsonEvidenceSink { EvidenceEvent::Attempt(_) => "attempt", EvidenceEvent::Delivery(_) => "delivery", }, + outcome: operational_outcome(&event), + duration_ms: match &event { + EvidenceEvent::Call(call) => Some(call.duration_ms), + EvidenceEvent::Attempt(attempt) => Some(attempt.duration_ms), + EvidenceEvent::Delivery(_) => None, + }, event: &event, loss: worker_counters.snapshot(), }; diff --git a/gateway/crates/pc-gateway-evidence/tests/output.rs b/gateway/crates/pc-gateway-evidence/tests/output.rs index 837af60846..3ce18e6eee 100644 --- a/gateway/crates/pc-gateway-evidence/tests/output.rs +++ b/gateway/crates/pc-gateway-evidence/tests/output.rs @@ -181,3 +181,126 @@ fn writer_errors_are_isolated_counted_and_never_serialized() { 1 ); } + +#[test] +fn operational_fields_preserve_domain_facts_and_do_not_infer_interruption_causes() { + use serde_json::json; + let output = Output::default(); + let sink = JsonEvidenceSink::new(output.clone(), NonZeroUsize::new(64).unwrap()).unwrap(); + let mut expected = Vec::new(); + for (terminal, status, interruption, outcome) in [ + ( + Terminal::ReleaseAuthorized, + Some(200), + None, + json!("success"), + ), + ( + Terminal::ReleaseAuthorized, + Some(500), + None, + json!("failure"), + ), + (Terminal::ReleaseAuthorized, None, None, json!(null)), + (Terminal::Degraded, Some(200), None, json!("success")), + (Terminal::Degraded, Some(429), None, json!("failure")), + (Terminal::Blocked, None, None, json!("blocked")), + (Terminal::Withheld, Some(200), None, json!("blocked")), + ( + Terminal::AdmissionExpired, + Some(200), + None, + json!("blocked"), + ), + (Terminal::SendIndeterminate, None, None, json!("failure")), + (Terminal::NotSent, None, None, json!("failure")), + (Terminal::GatePaused, None, None, json!("failure")), + ( + Terminal::Abandoned, + None, + Some(Interruption::CancellationRequested), + json!(null), + ), + ( + Terminal::Abandoned, + None, + Some(Interruption::DeadlineElapsed), + json!(null), + ), + ( + Terminal::Abandoned, + None, + Some(Interruption::FutureDropped), + json!(null), + ), + ] { + let call = CallEvidence { + terminal, + upstream_status: status, + interruption, + duration_ms: 17, + ..record() + }; + sink.record_call(&call); + expected.push(( + "call", + outcome, + json!(17), + serde_json::to_value(call).unwrap(), + )); + } + for (outcome, operational) in [ + (AttemptOutcome::Delivered, json!("success")), + (AttemptOutcome::UpstreamError, json!("failure")), + (AttemptOutcome::ConnectRefused, json!("failure")), + (AttemptOutcome::RejectedLocally, json!("failure")), + (AttemptOutcome::LostAfterHandoff, json!("failure")), + (AttemptOutcome::TimeoutAwaitingResponse, json!("failure")), + (AttemptOutcome::BufferLimitExceeded, json!("failure")), + (AttemptOutcome::PossiblySent, json!(null)), + ] { + let attempt = AttemptEvidence { + call_id: new_call_id(), + outcome, + duration_ms: 9, + ..Default::default() + }; + sink.record_attempt_evidence(&attempt); + expected.push(( + "attempt", + operational, + json!(9), + serde_json::to_value(attempt).unwrap(), + )); + } + for boundary in [ + DeliveryBoundary::FrameworkHandoff, + DeliveryBoundary::FirstBodyFrame, + DeliveryBoundary::FirstModelContent, + DeliveryBoundary::BodyCompleted, + DeliveryBoundary::BodyDropped, + ] { + let delivery = DeliveryEvidence { + call_id: new_call_id(), + boundary, + elapsed_ms: 23, + }; + sink.record_delivery(&delivery); + expected.push(( + "delivery", + json!(null), + json!(null), + serde_json::to_value(delivery).unwrap(), + )); + } + until(|| sink.stats().written as usize == expected.len()); + let text = String::from_utf8(output.0.lock().unwrap().clone()).unwrap(); + for (line, (unit, outcome, duration, domain)) in text.lines().zip(expected) { + let value: serde_json::Value = serde_json::from_str(line).unwrap(); + assert_eq!(value["operation"], "gateway.model_call"); + assert_eq!(value["unit"], unit); + assert_eq!(value["outcome"], outcome); + assert_eq!(value["duration_ms"], duration); + assert_eq!(value["evidence"], domain); + } +} diff --git a/gateway/crates/pc-gateway-types/src/lib.rs b/gateway/crates/pc-gateway-types/src/lib.rs index aa8812617c..2a128b6233 100644 --- a/gateway/crates/pc-gateway-types/src/lib.rs +++ b/gateway/crates/pc-gateway-types/src/lib.rs @@ -12,15 +12,17 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! PR #2264 契约值类型。 +//! Core HTTP DTOs and shared managed-call facts. //! //! 网关无策略:这里的类型只承载 Core 的输入/输出, -//! 与 openapi/powercontext.yaml 对齐。 +//! HTTP DTOs 与 openapi/powercontext.yaml 对齐;进程内生命周期事实独立于 HTTP 契约。 mod check; +mod lifecycle; mod prepare; mod time; pub use check::*; +pub use lifecycle::*; pub use prepare::*; pub use time::*; diff --git a/gateway/crates/pc-gateway-types/src/lifecycle.rs b/gateway/crates/pc-gateway-types/src/lifecycle.rs new file mode 100644 index 0000000000..36a5918911 --- /dev/null +++ b/gateway/crates/pc-gateway-types/src/lifecycle.rs @@ -0,0 +1,47 @@ +// 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. + +//! Shared managed-call facts, separate from Core's HTTP check DTOs. +use serde::{Deserialize, Serialize}; + +/// Sending facts for the whole call, independent of authorization and local delivery. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ModelSendState { + /// No attempt has crossed the transport boundary. + #[default] + NoSend, + /// Every attempted send was confirmed unsent by the transport. + DefinitelyNotSent, + /// An attempt was handed off without evidence ruling out sending. + PossiblySent, + /// A complete upstream response was obtained, regardless of release or decoding. + ResponseReceived, +} + +/// The local execution terminal; none of these establishes client receipt. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ExecutionTerminal { + ReleaseAuthorized, + Blocked, + Withheld, + SendIndeterminate, + NotSent, + GatePaused, + Degraded, + AdmissionExpired, + #[default] + Abandoned, +} From df8738e920c2d910c076832cf4d23b64d0f727d8 Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Fri, 6 Nov 2026 11:57:39 +0800 Subject: [PATCH 08/15] docs(gateway): record lifecycle and privacy acceptance --- gateway/EVIDENCE_VALIDATION.md | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/gateway/EVIDENCE_VALIDATION.md b/gateway/EVIDENCE_VALIDATION.md index 375c07ac61..04adaaa2ea 100644 --- a/gateway/EVIDENCE_VALIDATION.md +++ b/gateway/EVIDENCE_VALIDATION.md @@ -1,7 +1,7 @@ # Gateway evidence validation / Gateway 证据验收 - Date / 日期: 2026-11-06. -- Implementation commit / 实现提交: `2a686028262f9ac10f1d9f3c95ad7c4e923aba38`. +- Implementation commit / 实现提交: `eb0deda1b746fc277ea3cc109390c55d12f6c9d7`. - Master base / master 基线: `69b2d7e2ac1aacc05f386d04d4616aa9254b3f5d`; latest master rechecked at `24e0017e0504f2980300ed87b21412bb425b1744` (no additional Gateway changes). - Platform / 平台: Darwin arm64, Rust `1.95.0 (59807616e 2026-04-14)`, Python 3.13.15. - Scope / 范围: [#2463](https://github.com/oceanbase/powercontext/issues/2463), @@ -10,6 +10,8 @@ Pending execution destruction records abandonment plus cancellation/deadline observations; the owner still decides when to stop the future. Cancellation intent and deadline passage alone do not interrupt execution. pending 执行销毁时记录 abandoned 与取消/期限事实;仍由所有者决定何时停止 future,信号与期限本身不中断执行。 + #2462 remains open: total-deadline/RPC integration and real disconnect/cancellation/drain are subsequent G3 stages. + #2462 仍开放;总期限/RPC 集成与真实断连/取消/drain 属于后续 G3 阶段,#2499 未交付这些生产 owner。 Related open PR snapshots checked / 已核查相关开放 PR 源码快照: @@ -31,16 +33,18 @@ Cargo was invoked through `/Users/lioky/.cargo/bin/cargo` because the shell's mi | --- | --- | | `cargo fmt --manifest-path gateway/Cargo.toml --all --check` | Passed / 通过 | | `cargo clippy --locked --manifest-path gateway/Cargo.toml --all-targets -- -D warnings` | Passed / 通过 | -| `cargo test --locked --manifest-path gateway/Cargo.toml --workspace` | 158 exercised behavior tests passed; 4 live-Core cases returned early / 158 个实际行为测试通过,4 个真实 Core 用例提前返回 | -| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-app` | Real spawned Gateway, 1000 enabled + 100 disabled requests passed / 真实 Gateway 子进程,启用 1000 次与关闭 100 次请求通过 | +| `cargo test --locked --manifest-path gateway/Cargo.toml --workspace` | 160 exercised behavior tests passed; 4 live-Core cases returned early / 160 个实际行为测试通过,4 个真实 Core 用例提前返回 | +| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-app --test evidence_process` | Spawned Gateway: 1000 enabled + 100 disabled requests, plus rejected UDS/steering startup passed / 真实 Gateway 子进程,启用 1000 次、关闭 100 次请求及 UDS/steering 启动拒绝测试通过 | +| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-evidence` | Usage/privacy/bounded-writer tests and operational outcome output passed / usage、隐私、有界 writer 与运维 outcome 输出测试通过 | +| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-core --test executor_semantics` | 66 passed, including snapshot/evidence consistency on normal terminals and pending-future destruction / 66 个通过,含正常终态及 pending future 销毁时快照/证据一致性 | | `make check` | Passed, including lock/policy checks, hooks, types and 61 integration-manifest tests / 通过,包含锁文件/策略检查、hooks、类型及 61 个集成清单测试 | | `uv run prek run -a` | Passed with all implementation files staged / 实现文件暂存后通过 | | `make docs-test` | Passed: bilingual links and static build, 1084 public pages verified / 双语链接与静态构建通过,验证 1084 个公开页面 | | `git diff --check` | Passed / 通过 | -The workspace runner prints 162 passing test cases. Four `live_context_check` cases return early when the real Core +The workspace runner prints 164 passing test cases. Four `live_context_check` cases return early when the real Core at `127.0.0.1:8000` is unavailable; readiness was unavailable here. Those four are not real-Core acceptance evidence. -workspace 输出共 162 个通过用例;其中 4 个 `live_context_check` 因真实 Core 不可达而提前返回,不能算作真实 Core 验收。 +workspace 输出共 164 个通过用例;其中 4 个 `live_context_check` 因真实 Core 不可达而提前返回,不能算作真实 Core 验收。 ## Observed behavior / 实际覆盖 @@ -52,6 +56,9 @@ workspace 输出共 162 个通过用例;其中 4 个 `live_context_check` 因 | Business isolation / 业务隔离 | Blocking/full and I/O-error writers preserve release/withhold decisions and pending-send cancellation/drop facts; errors are counted without their text / 慢写/队列满/I/O 错误不改变释放与 withhold 结论及发送中取消/销毁事实,错误仅计数不输出原文 | | Timing and strict order / 计时与 strict 顺序 | Header-wait fixture is included in first-byte timing; incomplete responses retain observed status/first byte; release approval precedes framework handoff, first body frame and first model-content observation; model TTFT is null / 首字节包含响应头等待,部分失败保留已知状态与首字节,批准先于框架交接、首 frame 与首次模型内容观测,模型 TTFT 为 null | | Privacy / 隐私 | Synthetic prompt/response/model/request-ID/credential/provider-error/I/O-error markers are absent from evidence; process test also checks stderr / 合成 prompt、响应、模型名、请求 ID、凭据、provider 异常及 I/O 异常标记未出现在证据中,进程测试另检查 stderr | +| Shared lifecycle / 共享生命周期 | Snapshot and evidence use the same terminal/send enums and one ManagedOutcome-to-terminal mapping; normal/refusal/error/degraded/drop scenarios agree / 快照与证据共享终态/发送枚举和唯一 ManagedOutcome 终态映射,正常/拒绝/错误/降级/销毁场景一致 | +| Operational vocabulary / 运维词汇 | Serialized call/attempt/delivery records verify operation, unit, common success/failure/blocked/null outcome and duration projection while preserving nested domain facts; abandoned intent/deadline facts never invent cancelled / 序列化输出验证 operation、unit、通用 outcome 与耗时投影,保留嵌套领域事实,不将 abandoned 的意图/期限推断为 cancelled | +| Startup privacy / 启动隐私 | Spawned TCP requests embed synthetic Core URL credentials/path and invalid injection text; UDS plus rejected steering startup embeds socket/file paths. Markers are absent from stdout/stderr while diagnostics remain readable / 真实 TCP 进程植入 Core URL 凭据/路径及非法 injection 文本,UDS/steering 启动拒绝植入 socket/文件路径;stdout/stderr 不含标记且保留可读诊断 | | Real production composition / 真实生产装配 | Spawned binary handles 1000 requests with 6000 readable records and 1000 distinct call IDs; explicit Noop handles 100 requests with empty stdout and an evidence-disabled startup diagnostic / 真实二进制处理 1000 次请求,输出 6000 条可读记录、1000 个不同调用 ID;显式 Noop 处理 100 次请求,stdout 为空且启动诊断说明证据关闭 | | Both ingress formats / 两种入口格式 | In-process public-router tests send 200 calls through actual reqwest to local HTTP fixtures, covering Chat JSON/SSE and Responses JSON/replayed SSE, and read 1200 serialized production-sink records / 进程内公开路由用真实 reqwest 完成 200 次本地 HTTP 调用,覆盖 Chat JSON/SSE 与 Responses JSON/重放 SSE,读取生产 sink 的 1200 条序列化输出 | @@ -74,7 +81,9 @@ model output; it is separate from `first_body_frame` and does not prove socket w Unsupported/empty output and bodies dropped before content have no content event; missing records and sink loss must remain unavailable evidence. Closing #2463 still requires integration acceptance of actual total-deadline and cancellation interruption owned by [#2462](https://github.com/oceanbase/powercontext/issues/2462). The shared control -and future-destruction observations tested here do not establish automatic interruption. +and future-destruction observations tested here do not establish automatic interruption. Common operational fields +align with #2388 vocabulary, but its current Server OTLP pipeline does not ingest this stdout stream or preserve +nested evidence/loss automatically; external backend ingestion/storage/readback was not executed. 本地 Core/provider HTTP fixture、FakeGate 执行器测试不等同于真实 PowerContext Core、真实模型供应商、外部观测后端 或原生 agent 宿主;这些外部环境未执行。真实子进程测试证明 Rust Gateway 生产装配及本地 HTTP 行为, @@ -83,8 +92,11 @@ and future-destruction observations tested here do not establish automatic inter 不证明 socket 写出或客户端收到。不支持/空输出及内容之前丢弃的 body 不产生内容事件;记录缺失与 sink 丢失 均不能当作耗时为零。关闭 #2463 仍需验收 #2462 所拥有的实际总期限与取消中断集成; 本报告验证的共享控制与 future 销毁观测不能证明自动中断。 +通用运维字段已与 #2388 词汇对齐,但其当前 Server OTLP pipeline 不会自动采集此 stdout 流, +也不会自动保全嵌套 evidence/loss;未执行外部后端采集、存储与读回。 -No OpenAPI contract, Python operational fields, database records or dependency lockfiles changed. +No OpenAPI contract, Python operational fields or database records changed. The Gateway lockfile adds only the +workspace dependency `pc-gateway-evidence` → `pc-gateway-types`; no external dependency versions changed. The Gateway's client-visible HTTP 503 `gate_paused.detail` is normalized for Core-unavailable and malformed-response errors; the bilingual deployment contract documents these fixed values and the client migration behavior. OpenAPI generation/contract regeneration and Python logging formatter tests are therefore not applicable. @@ -92,7 +104,8 @@ The bilingual [output contract](../docs/en/docs/operate/gateway-evidence.md) / [输出契约](../docs/zh/docs/operate/gateway-evidence.md) defines retention, unknown usage, interruption facts, framework boundaries and deployment/Rust migration behavior. No deployment or GitHub issue closure was performed. -未修改 OpenAPI 契约、Python operational 字段、数据库记录或依赖锁文件,无需重新生成 OpenAPI 或验证 Python formatter。 +未修改 OpenAPI 契约、Python operational 字段或数据库记录,无需重新生成 OpenAPI 或验证 Python formatter。 +Gateway 锁文件仅新增 evidence → types 的 workspace 依赖,未变更外部依赖版本。 Gateway 客户端可见的 HTTP 503 `gate_paused.detail` 对 Core 不可用及响应畸形错误进行了归一化, 双语部署契约记录了固定值与客户端迁移行为。 双语契约定义保留、未知 usage、中断事实、框架边界及部署/Rust 迁移行为;未执行部署或关闭 GitHub Issue。 From 91f576f6f0c3d8a4285a613e95a07919b79ad447 Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Fri, 6 Nov 2026 16:21:59 +0800 Subject: [PATCH 09/15] fix(gateway): preserve SSE evidence across media types and BOM --- docs/en/docs/operate/gateway-evidence.md | 3 ++ docs/zh/docs/operate/gateway-evidence.md | 2 + .../pc-gateway-app/src/evidence_body.rs | 1 + .../pc-gateway-app/tests/evidence_process.rs | 43 ++++++++++++++----- .../crates/pc-gateway-protocol/src/content.rs | 5 ++- .../tests/content_boundary.rs | 21 +++++++++ .../src/reqwest_transport.rs | 5 ++- .../tests/usage_timing.rs | 41 +++++++++++++++++- 8 files changed, 108 insertions(+), 13 deletions(-) diff --git a/docs/en/docs/operate/gateway-evidence.md b/docs/en/docs/operate/gateway-evidence.md index ca5e6060c4..3e7716e22f 100644 --- a/docs/en/docs/operate/gateway-evidence.md +++ b/docs/en/docs/operate/gateway-evidence.md @@ -131,6 +131,9 @@ No Anthropic cache-creation/write fields are guessed into the OpenAI mapping. Mi counts remain unknown; a reported zero is known zero. `total_tokens` alone cannot establish input/output counts. SSE uses an explicitly present usage object from a Chat usage chunk or Responses event's `response.usage`. It retains the last such object, without summing cumulative chunks. Missing/malformed SSE usage remains unknown. +The SSE media type is compared case-insensitively after separating parameters. Usage and first-content inspection +ignore exactly one leading UTF-8 BOM; first-content offsets still refer to the original outgoing bytes, including +that BOM. Response bytes and the original Content-Type are preserved. This does not expand the Core's accepted streaming protocols. ## Timing and HTTP delivery diff --git a/docs/zh/docs/operate/gateway-evidence.md b/docs/zh/docs/operate/gateway-evidence.md index b49c2c1ef9..6815052b9e 100644 --- a/docs/zh/docs/operate/gateway-evidence.md +++ b/docs/zh/docs/operate/gateway-evidence.md @@ -122,6 +122,8 @@ transport 交付完整响应后,解码或释放失败不会丢掉 usage。直 不会把 Anthropic 的缓存创建/写入字段猜测为 OpenAI 字段。缺失、null、畸形或负数保持未知;明确上报的零为已知零。 仅有 `total_tokens` 不能确定输入/输出数量。SSE 只使用 Chat usage chunk 中明确的 usage 对象或 Responses 事件的 `response.usage`,保留最后一个对象,不累加累计 chunk。SSE usage 缺失或无法解析时保持未知。 +SSE 媒体类型在分离参数后按大小写不敏感方式比较。usage 与首内容检查只忽略流开头的一个 UTF-8 BOM; +首内容偏移仍对应包含 BOM 的原始输出字节。响应字节与原始 Content-Type 保持不变。 这不会扩展 Core 接受的流式协议范围。 ## 计时与 HTTP 交付 diff --git a/gateway/crates/pc-gateway-app/src/evidence_body.rs b/gateway/crates/pc-gateway-app/src/evidence_body.rs index 8cc7c6f625..5216e2fa5d 100644 --- a/gateway/crates/pc-gateway-app/src/evidence_body.rs +++ b/gateway/crates/pc-gateway-app/src/evidence_body.rs @@ -172,6 +172,7 @@ mod tests { #[tokio::test] async fn content_observation_waits_for_matching_frame_at_every_wire_split() { for (wire, protocol, sse) in [ + ("\u{feff}data: {\"choices\":[{\"delta\":{\"content\":\"FIRST\"}}]}\r\n\r\ndata: {\"choices\":[{\"delta\":{\"content\":\"LATER\"}}]}\r\n\r\n", OutputProtocol::OpenAiChat, true), ("event: response.created\ndata: {\"type\":\"response.created\"}\n\nevent: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"秘密\"}\n\n", OutputProtocol::OpenAiResponses, true), (r#"{"choices":[{"message":{"content":"\u79d8密"}}]}"#, OutputProtocol::OpenAiChat, false), ("data: {\"choices\":[{\"delta\":{\"role\":\"assistant\"}}]}\n\ndata: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"function\":{\"arguments\":\"{}\"}}]}}]}\n\n", OutputProtocol::OpenAiChat, true), diff --git a/gateway/crates/pc-gateway-app/tests/evidence_process.rs b/gateway/crates/pc-gateway-app/tests/evidence_process.rs index 1ca4a59098..f2946a3027 100644 --- a/gateway/crates/pc-gateway-app/tests/evidence_process.rs +++ b/gateway/crates/pc-gateway-app/tests/evidence_process.rs @@ -14,6 +14,7 @@ //! Production composition in a real spawned Gateway, with local HTTP Core/provider fixtures. use axum::{ + response::IntoResponse, routing::{get, post}, Json, Router, }; @@ -26,6 +27,9 @@ use std::sync::{ }; use std::time::Duration; +// First-event usage and the only content delta share a leading-BOM event. +const BOM_SSE_RESPONSE: &str = "\u{feff}data: {\"choices\":[{\"delta\":{\"content\":\"SYNTHETIC_RESPONSE_SECRET\"}}],\"usage\":{\"prompt_tokens\":101,\"completion_tokens\":13,\"prompt_tokens_details\":{\"cached_tokens\":61}}}\r\n\r\ndata: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}]}\r\n\r\ndata: [DONE]\r\n\r\n"; + struct Gateway(Child); impl Drop for Gateway { fn drop(&mut self) { @@ -45,10 +49,16 @@ async fn production_jsonl_and_explicit_noop_keep_real_requests_usable() { "reason_codes":[], "coverage":{"profile":"text-and-tools.v1", "complete":true}, "policy_version":"fixture", "valid_until":"2999-01-01T00:00:00Z", "binding":"fixture-binding" })) })) - .route("/v1/chat/completions", post(|| async { Json(json!({ - "choices":[{"message":{"role":"assistant", "content":"SYNTHETIC_RESPONSE_SECRET"}}], - "usage":{"prompt_tokens":101, "completion_tokens":13, "prompt_tokens_details":{"cached_tokens":61}} - })) })); + .route("/v1/chat/completions", post(|Json(request): Json| async move { + if request["stream"] == true { + ([("content-type", "Text/Event-Stream; charset=utf-8")], BOM_SSE_RESPONSE).into_response() + } else { + Json(json!({ + "choices":[{"message":{"role":"assistant", "content":"SYNTHETIC_RESPONSE_SECRET"}}], + "usage":{"prompt_tokens":101, "completion_tokens":13, "prompt_tokens_details":{"cached_tokens":61}} + })).into_response() + } + })); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let base = format!( "http://SYNTHETIC_CORE_USER:SYNTHETIC_CORE_PASSWORD@{}/SYNTHETIC_PRIVATE_PATH", @@ -121,17 +131,29 @@ async fn production_jsonl_and_explicit_noop_keep_real_requests_usable() { .await .unwrap(); let count = if disabled { 100 } else { 1000 }; - for _ in 0..count { + for i in 0..count { + let stream = i % 2 == 1; let response = client.post(format!("{url}/gateway/v1/chat/completions")) .bearer_auth("SYNTHETIC_GATEWAY_KEY") .header("x-powercontext-request-id", "SYNTHETIC_REQUEST_SECRET") - .json(&json!({"model":"SYNTHETIC_MODEL", "messages":[{"role":"user", "content":"SYNTHETIC_PROMPT_SECRET"}]})) + .json(&json!({"model":"SYNTHETIC_MODEL", "messages":[{"role":"user", "content":"SYNTHETIC_PROMPT_SECRET"}], "stream":stream})) .send().await.unwrap(); assert_eq!(response.status(), 200); - assert_eq!( - response.json::().await.unwrap()["usage"]["prompt_tokens"], - 101 - ); + if stream { + assert_eq!( + response.headers()["content-type"], + "Text/Event-Stream; charset=utf-8" + ); + assert_eq!( + response.bytes().await.unwrap().as_ref(), + BOM_SSE_RESPONSE.as_bytes() + ); + } else { + assert_eq!( + response.json::().await.unwrap()["usage"]["prompt_tokens"], + 101 + ); + } } if !disabled { tokio::time::timeout(Duration::from_secs(5), async { @@ -171,6 +193,7 @@ async fn production_jsonl_and_explicit_noop_keep_real_requests_usable() { assert_eq!(record["duration_ms"], evidence["duration_ms"]); assert_eq!(evidence["terminal"], "release_authorized"); assert_eq!(evidence["usage"]["input"]["tokens"], 101); + assert_eq!(evidence["usage"]["output"]["tokens"], 13); assert_eq!(evidence["usage"]["cache_read"]["tokens"], 61); assert!(evidence["usage"]["cache_write"]["tokens"].is_null()); assert!(evidence["upstream_ttft_ms"].is_null()); diff --git a/gateway/crates/pc-gateway-protocol/src/content.rs b/gateway/crates/pc-gateway-protocol/src/content.rs index 0a27597a8d..155e408919 100644 --- a/gateway/crates/pc-gateway-protocol/src/content.rs +++ b/gateway/crates/pc-gateway-protocol/src/content.rs @@ -216,7 +216,10 @@ fn sse_offset(text: &str, protocol: OutputProtocol) -> Option { let mut data = String::new(); let mut segments = Vec::new(); let mut event = None; - let mut original = 0; + // Ignore exactly one leading SSE BOM, but keep offsets in the original wire body. + let wire_len = text.len(); + let text = text.strip_prefix('\u{feff}').unwrap_or(text); + let mut original = wire_len - text.len(); // LF and CRLF framing, matching the supported SSE wire profiles. Unfinished events are not dispatched. for line in text.split_inclusive('\n') { let line_start = original; diff --git a/gateway/crates/pc-gateway-protocol/tests/content_boundary.rs b/gateway/crates/pc-gateway-protocol/tests/content_boundary.rs index 0cfa0713c9..91eb0dbdc5 100644 --- a/gateway/crates/pc-gateway-protocol/tests/content_boundary.rs +++ b/gateway/crates/pc-gateway-protocol/tests/content_boundary.rs @@ -151,3 +151,24 @@ fn large_content_needs_no_fixed_observer_buffer_or_content_copy() { first_model_content_offset(body.as_bytes(), OutputProtocol::OpenAiChat, false).unwrap(); assert_eq!(&body[offset..offset + content.len()], content); } + +#[test] +fn sse_ignores_only_one_leading_bom_and_returns_original_wire_offset() { + for (wire, protocol, content) in [ + ("\u{feff}data: {\"choices\":[{\"delta\":{\"content\":\"FIRST\"}}]}\n\ndata: {\"choices\":[{\"delta\":{\"content\":\"LATER\"}}]}\n\n", OutputProtocol::OpenAiChat, "FIRST"), + ("\u{feff}event: response.output_text.delta\r\ndata: {\"delta\":\"FIRST\"}\r\n\r\n", OutputProtocol::OpenAiResponses, "FIRST"), + ("\u{feff}data: {\"type\":\"response.output_text.delta\",\r\ndata: \"delta\":\"FIRST\"}\r\n\r\n", OutputProtocol::OpenAiResponses, "FIRST"), + ("\u{feff}data: {\"choices\":[{\"delta\":{\"content\":\"\u{feff}FIRST\"}}]}\n\n", OutputProtocol::OpenAiChat, "\u{feff}FIRST"), + ] { + assert_eq!(first_model_content_offset(wire.as_bytes(), protocol, true), wire.find(content)); + } + for wire in [ + "\u{feff}\u{feff}data: {\"choices\":[{\"delta\":{\"content\":\"DECOY\"}}]}\n\n", + ": comment\n\u{feff}data: {\"choices\":[{\"delta\":{\"content\":\"DECOY\"}}]}\n\n", + ] { + assert_eq!( + first_model_content_offset(wire.as_bytes(), OutputProtocol::OpenAiChat, true), + None + ); + } +} diff --git a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs index 950915e225..26ab0e499f 100644 --- a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs +++ b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs @@ -155,7 +155,8 @@ impl Transport for ReqwestTransport { } fn extract_usage(body: &[u8], content_type: &str) -> Option { - if !content_type.starts_with("text/event-stream") { + let media_type = content_type.split(';').next().unwrap_or("").trim(); + if !media_type.eq_ignore_ascii_case("text/event-stream") { return serde_json::from_slice::(body) .ok() .and_then(|v| v.get("usage").filter(|v| v.is_object()).cloned()); @@ -163,6 +164,8 @@ fn extract_usage(body: &[u8], content_type: &str) -> Option { // Usage-only Chat chunks and Responses terminal events. Do not infer missing usage. // Join multi-line SSE data, reset at blank lines, and retain only the latest usage. let text = std::str::from_utf8(body).ok()?; + // SSE ignores one BOM at stream start; keep the original response bytes intact. + let text = text.strip_prefix('\u{feff}').unwrap_or(text); let mut data = String::new(); let mut usage = None; for line in text.lines().chain(std::iter::once("")) { diff --git a/gateway/crates/pc-gateway-transport/tests/usage_timing.rs b/gateway/crates/pc-gateway-transport/tests/usage_timing.rs index 48b7839545..f9df5a792d 100644 --- a/gateway/crates/pc-gateway-transport/tests/usage_timing.rs +++ b/gateway/crates/pc-gateway-transport/tests/usage_timing.rs @@ -43,7 +43,12 @@ async fn response( payload: bytes::Bytes::from_static(b"{}"), target_url: format!("http://{addr}/v1/responses"), headers: vec![], - stream: content_type == "text/event-stream", + stream: content_type + .split(';') + .next() + .unwrap_or("") + .trim() + .eq_ignore_ascii_case("text/event-stream"), }) .await; server.await.unwrap(); @@ -93,3 +98,37 @@ async fn sse_usage_only_chunks_and_missing_usage_keep_their_distinct_meaning() { assert_eq!(usage.input.tokens, Some(7)); assert!(usage.cache_read.tokens.is_none()); } + +#[tokio::test] +async fn sse_usage_matches_case_insensitive_media_types_without_prefix_aliases() { + let body = "data: {\"usage\":{\"prompt_tokens\":80,\"completion_tokens\":7,\"prompt_tokens_details\":{\"cached_tokens\":20}}}\n\ndata: [DONE]\n\n"; + for content_type in ["text/event-stream", "Text/Event-Stream; charset=utf-8"] { + let raw = response(body, content_type).await; + assert_eq!(raw.body.as_ref(), body.as_bytes()); + assert_eq!(raw.content_type, content_type); + let usage = UsageEvidence::openai(raw.usage.as_ref(), UsageMapping::OpenAiChat); + assert_eq!(usage.input.tokens, Some(80), "{content_type}"); + assert_eq!(usage.output.tokens, Some(7)); + assert_eq!(usage.cache_read.tokens, Some(20)); + } + let raw = response(body, "text/event-stream-invalid").await; + assert!(raw.usage.is_none()); +} + +#[tokio::test] +async fn sse_leading_bom_preserves_first_event_usage_and_original_bytes() { + for (body, mapping) in [ + ("\u{feff}data: {\"usage\":{\"prompt_tokens\":80,\"completion_tokens\":7,\"prompt_tokens_details\":{\"cached_tokens\":20}}}\r\n\r\ndata: [DONE]\r\n\r\n", UsageMapping::OpenAiChat), + ("\u{feff}data: {\"response\":{\"usage\":{\"input_tokens\":80,\"output_tokens\":7,\"input_tokens_details\":{\"cached_tokens\":20}}}}\n\n", UsageMapping::OpenAiResponses), + ] { + for content_type in ["text/event-stream", "Text/Event-Stream; charset=utf-8"] { + let raw = response(body, content_type).await; + assert_eq!(raw.body.as_ref(), body.as_bytes()); + let usage = UsageEvidence::openai(raw.usage.as_ref(), mapping); + assert_eq!(usage.input.tokens, Some(80)); + assert_eq!(usage.output.tokens, Some(7)); + assert_eq!(usage.cache_read.tokens, Some(20)); + assert_eq!(usage.cache_write.completeness, UsageCompleteness::Unknown); + } + } +} From 778e5e02cb3310671a796f6685b7a1f2df10c12f Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Fri, 6 Nov 2026 16:22:20 +0800 Subject: [PATCH 10/15] docs(gateway): record SSE evidence regression validation --- gateway/EVIDENCE_VALIDATION.md | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/gateway/EVIDENCE_VALIDATION.md b/gateway/EVIDENCE_VALIDATION.md index 04adaaa2ea..d569b59fd8 100644 --- a/gateway/EVIDENCE_VALIDATION.md +++ b/gateway/EVIDENCE_VALIDATION.md @@ -1,7 +1,7 @@ # Gateway evidence validation / Gateway 证据验收 - Date / 日期: 2026-11-06. -- Implementation commit / 实现提交: `eb0deda1b746fc277ea3cc109390c55d12f6c9d7`. +- Implementation commit / 实现提交: `91f576f6f0c3d8a4285a613e95a07919b79ad447`. - Master base / master 基线: `69b2d7e2ac1aacc05f386d04d4616aa9254b3f5d`; latest master rechecked at `24e0017e0504f2980300ed87b21412bb425b1744` (no additional Gateway changes). - Platform / 平台: Darwin arm64, Rust `1.95.0 (59807616e 2026-04-14)`, Python 3.13.15. - Scope / 范围: [#2463](https://github.com/oceanbase/powercontext/issues/2463), @@ -33,8 +33,9 @@ Cargo was invoked through `/Users/lioky/.cargo/bin/cargo` because the shell's mi | --- | --- | | `cargo fmt --manifest-path gateway/Cargo.toml --all --check` | Passed / 通过 | | `cargo clippy --locked --manifest-path gateway/Cargo.toml --all-targets -- -D warnings` | Passed / 通过 | -| `cargo test --locked --manifest-path gateway/Cargo.toml --workspace` | 160 exercised behavior tests passed; 4 live-Core cases returned early / 160 个实际行为测试通过,4 个真实 Core 用例提前返回 | +| `cargo test --locked --manifest-path gateway/Cargo.toml --workspace` | 163 exercised behavior tests passed; 4 live-Core cases returned early / 163 个实际行为测试通过,4 个真实 Core 用例提前返回 | | `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-app --test evidence_process` | Spawned Gateway: 1000 enabled + 100 disabled requests, plus rejected UDS/steering startup passed / 真实 Gateway 子进程,启用 1000 次、关闭 100 次请求及 UDS/steering 启动拒绝测试通过 | +| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-app -p pc-gateway-transport -p pc-gateway-protocol` | Passed, including mixed-case SSE media types, first-event BOM usage/content, every body split and spawned Gateway byte preservation / 通过,含 SSE 媒体类型大小写、首事件 BOM usage/内容、任意 body 切分及真实子进程字节保持 | | `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-evidence` | Usage/privacy/bounded-writer tests and operational outcome output passed / usage、隐私、有界 writer 与运维 outcome 输出测试通过 | | `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-core --test executor_semantics` | 66 passed, including snapshot/evidence consistency on normal terminals and pending-future destruction / 66 个通过,含正常终态及 pending future 销毁时快照/证据一致性 | | `make check` | Passed, including lock/policy checks, hooks, types and 61 integration-manifest tests / 通过,包含锁文件/策略检查、hooks、类型及 61 个集成清单测试 | @@ -42,9 +43,9 @@ Cargo was invoked through `/Users/lioky/.cargo/bin/cargo` because the shell's mi | `make docs-test` | Passed: bilingual links and static build, 1084 public pages verified / 双语链接与静态构建通过,验证 1084 个公开页面 | | `git diff --check` | Passed / 通过 | -The workspace runner prints 164 passing test cases. Four `live_context_check` cases return early when the real Core +The workspace runner prints 167 passing test cases. Four `live_context_check` cases return early when the real Core at `127.0.0.1:8000` is unavailable; readiness was unavailable here. Those four are not real-Core acceptance evidence. -workspace 输出共 164 个通过用例;其中 4 个 `live_context_check` 因真实 Core 不可达而提前返回,不能算作真实 Core 验收。 +workspace 输出共 167 个通过用例;其中 4 个 `live_context_check` 因真实 Core 不可达而提前返回,不能算作真实 Core 验收。 ## Observed behavior / 实际覆盖 @@ -52,6 +53,7 @@ workspace 输出共 164 个通过用例;其中 4 个 `live_context_check` 因 | --- | --- | | Correlated call terminals and actual attempts / 关联终态与真实尝试 | Executor tests cover success, zero-send block/withhold/expiry, retry/NotSent, Indeterminate, upstream HTTP error, release refusal/expiry, degraded execution and pending-future destruction / 覆盖成功、零发送拒绝/过期、重试/NotSent、不确定、上游 HTTP 错误、释放拒绝/过期、降级和 pending future 销毁 | | Usage through real transport / 真实 transport usage | Local HTTP JSON/SSE fixtures verify Chat/Responses input, output, cached reads, known zero and missing/malformed usage; cache writes stay unknown / 核对两种协议的输入、输出、缓存读、已知零及缺失/畸形 usage,缓存写保持未知 | +| SSE evidence framing / SSE 证据 framing | Real transport reads 80/7/20 input/output/cache-read from lowercase and mixed-case media types, including first-event Chat/Responses usage behind one leading UTF-8 BOM. Protocol/body tests preserve original offsets through BOM and reject stripping a second/interior BOM / 真实 transport 在小写/混合大小写媒体类型及带一个开头 UTF-8 BOM 的 Chat/Responses 首事件读出 80/7/20 input/output/cache-read;协议/body 测试保留原始偏移,不移除第二个/流中间的 BOM | | Bounded retention and visible loss / 有界保留与可见丢失 | A held writer with capacity 4 receives 100000 extra submissions: exactly 4 queue, 99996 drop; 1 record remains in flight, and recovered output reports loss / 容量 4 且 writer 卡住时额外提交 10 万条,4 条排队、99996 条丢弃、1 条在写,恢复输出含丢失计数 | | Business isolation / 业务隔离 | Blocking/full and I/O-error writers preserve release/withhold decisions and pending-send cancellation/drop facts; errors are counted without their text / 慢写/队列满/I/O 错误不改变释放与 withhold 结论及发送中取消/销毁事实,错误仅计数不输出原文 | | Timing and strict order / 计时与 strict 顺序 | Header-wait fixture is included in first-byte timing; incomplete responses retain observed status/first byte; release approval precedes framework handoff, first body frame and first model-content observation; model TTFT is null / 首字节包含响应头等待,部分失败保留已知状态与首字节,批准先于框架交接、首 frame 与首次模型内容观测,模型 TTFT 为 null | @@ -62,6 +64,14 @@ workspace 输出共 164 个通过用例;其中 4 个 `live_context_check` 因 | Real production composition / 真实生产装配 | Spawned binary handles 1000 requests with 6000 readable records and 1000 distinct call IDs; explicit Noop handles 100 requests with empty stdout and an evidence-disabled startup diagnostic / 真实二进制处理 1000 次请求,输出 6000 条可读记录、1000 个不同调用 ID;显式 Noop 处理 100 次请求,stdout 为空且启动诊断说明证据关闭 | | Both ingress formats / 两种入口格式 | In-process public-router tests send 200 calls through actual reqwest to local HTTP fixtures, covering Chat JSON/SSE and Responses JSON/replayed SSE, and read 1200 serialized production-sink records / 进程内公开路由用真实 reqwest 完成 200 次本地 HTTP 调用,覆盖 Chat JSON/SSE 与 Responses JSON/重放 SSE,读取生产 sink 的 1200 条序列化输出 | +The spawned-process workload alternates JSON and mixed-case `Text/Event-Stream; charset=utf-8` responses. +Of 1000 enabled calls, 500 SSE responses contain a leading BOM with the sole content delta and usage in the first event; +all 1000 call records preserve 101/13/61 input/output/cache-read and have exactly one first-model-content observation. +The same two response formats are exercised with evidence disabled; SSE headers and complete original bytes are preserved. +真实子进程交替处理 JSON 与混合大小写媒体类型的 SSE;启用证据的 1000 次调用中,500 次 SSE 带开头 BOM, +唯一内容 delta 与 usage 位于首事件。1000 条调用记录均保留 101/13/61 input/output/cache-read, +且每次恰有一条首模型内容观测。关闭证据时也覆盖两种格式,SSE 响应头及完整原始字节保持不变。 + Protocol fixtures cover text, refusals and function output, metadata/control decoys, escaped/Unicode content, LF/CRLF multiline SSE, malformed/empty output and 256 KiB content. Body-observer tests split each sample at every byte position, verify unchanged outgoing bytes, defer first-content observation until the matching frame, and From a1707cde76efd848ae59b26a52d04a76bd2e1abf Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Sat, 7 Nov 2026 13:21:52 +0800 Subject: [PATCH 11/15] docs(gateway): record capacity and evidence integration checks --- gateway/CAPACITY_VALIDATION.md | 29 +++++++++++++++++------------ gateway/EVIDENCE_VALIDATION.md | 30 +++++++++++++++++++----------- 2 files changed, 36 insertions(+), 23 deletions(-) diff --git a/gateway/CAPACITY_VALIDATION.md b/gateway/CAPACITY_VALIDATION.md index 9d33f431f5..6ca7ce18c5 100644 --- a/gateway/CAPACITY_VALIDATION.md +++ b/gateway/CAPACITY_VALIDATION.md @@ -3,10 +3,11 @@ Scope: G5-A of [#2464](https://github.com/oceanbase/powercontext/issues/2464), the independent capacity stop-loss stage. The implemented boundary is startup-confirmed model input, final rendered-body admission, bounded provider-response buffering, and separate model/fallback concurrency permits. The HTTP capability schema is unchanged. -G5-A acceptance is partial: possible billing is retained only in process-local lifecycle state, and readable -call-evidence integration with #2506 is still required. +Readable call-evidence integration with #2506 is validated on the combined implementation; response overflow +retains possible billing in both lifecycle state and the production JSONL stream. +See [Gateway evidence validation](EVIDENCE_VALIDATION.md) for the combined commit, platform, commands and limits. -## Source and environment +## Capacity-only source and environment - Base: upstream master `24e0017e` (includes the shared managed-call lifecycle from #2499). - Implementation: local branch `codex/issue-2464-capacity-budgets`, working tree based on that commit. @@ -14,7 +15,7 @@ call-evidence integration with #2506 is still required. - Related open work inspected: #2457 (protection modes), #2470 (native protocol behavior), #2429 (output defaults), and #2506 (bounded call evidence). Their unmerged implementation is not included in this branch. -## Executed checks +## Capacity-only checks Run from the repository root with Cargo 1.95.0 available on PATH: @@ -58,9 +59,9 @@ or cryptographic bindings. The executor regressions check prepared-context replay and the lifecycle observation on response overflow: `PossiblySent` plus `Withheld`, with one provider attempt. This preserves possible billing in process-local -state without claiming complete response receipt. It does not produce a readable `record_call` export in this branch. -The production `BufferedEvidenceSink` has no operator-facing call stream, and these tests do not satisfy the -G5-A requirement that possible billing appear in readable call evidence. +state without claiming complete response receipt. The combined implementation also checks the same facts against +readable call/attempt records, including degraded passthrough and partial-response status/first-byte timing. +Production uses the bounded `JsonEvidenceSink`; `BufferedEvidenceSink` is retained for tests/demos. The Python suites exercise the real Core runtime and ASGI authorization paths; they are not evidence of spawned Core or real-provider acceptance through the new gateway. @@ -70,11 +71,15 @@ isolate transport buffering; they do not establish that real Core accepts such r ## Remaining issue acceptance -G5-A still requires integration with the bounded call-evidence exporter in #2506. A real gateway-process -regression must read the exported record for a response-buffer overflow and assert one attempt, -`Withheld` terminal, `PossiblySent` sending facts and unknown usage, without content or credentials. -Until that integration is executed, G5-A must not be described as fully accepted. The capacity changes -can be reviewed independently, with the evidence dependency stated in the PR. +The combined implementation at `b1f03eb59cc9327e9c1e8ad3df60a2fbcf914713` includes master +`b8b189091e7a412300cf1292531208a8ead0e325`. On 2026-11-07, the Gateway workspace reported 185 passing +cases, including the capacity and evidence subprocess tests; four live-Core cases returned early, so 181 +behavior tests exercised their assertions. Fmt, clippy, repository checks and the documentation build passed. +The real Gateway process regression reads exported JSONL for fixed-length and chunked response-buffer overflow: +one `buffer_limit_exceeded` attempt, `withheld` terminal, `possibly_sent`, unknown usage, retained observed +status/first-byte timing, no content or credentials, no delivery prefix and no resend. This satisfies the +G5-A readable-evidence integration requirement with local controlled Core/provider HTTP fixtures; it does not +establish real Core, paid provider or native host acceptance. G5-B remains open: output-capacity discovery where required; global and local retained-byte accounting for request, response, replay/SSE and applicable evidence owners; accounting through final owner drop; mixed-size load/RSS diff --git a/gateway/EVIDENCE_VALIDATION.md b/gateway/EVIDENCE_VALIDATION.md index d569b59fd8..7633b4d869 100644 --- a/gateway/EVIDENCE_VALIDATION.md +++ b/gateway/EVIDENCE_VALIDATION.md @@ -1,8 +1,8 @@ # Gateway evidence validation / Gateway 证据验收 -- Date / 日期: 2026-11-06. -- Implementation commit / 实现提交: `91f576f6f0c3d8a4285a613e95a07919b79ad447`. -- Master base / master 基线: `69b2d7e2ac1aacc05f386d04d4616aa9254b3f5d`; latest master rechecked at `24e0017e0504f2980300ed87b21412bb425b1744` (no additional Gateway changes). +- Date / 日期: 2026-11-07. +- Implementation commit / 实现提交: `b1f03eb59cc9327e9c1e8ad3df60a2fbcf914713`. +- Merged master / 已合并 master: `b8b189091e7a412300cf1292531208a8ead0e325`, including #2513 capacity limits and context refresh. / 包含 #2513 容量限制与上下文刷新。 - Platform / 平台: Darwin arm64, Rust `1.95.0 (59807616e 2026-04-14)`, Python 3.13.15. - Scope / 范围: [#2463](https://github.com/oceanbase/powercontext/issues/2463), [planning discussion / 规划讨论 #2433](https://github.com/oceanbase/powercontext/discussions/2433). @@ -33,19 +33,17 @@ Cargo was invoked through `/Users/lioky/.cargo/bin/cargo` because the shell's mi | --- | --- | | `cargo fmt --manifest-path gateway/Cargo.toml --all --check` | Passed / 通过 | | `cargo clippy --locked --manifest-path gateway/Cargo.toml --all-targets -- -D warnings` | Passed / 通过 | -| `cargo test --locked --manifest-path gateway/Cargo.toml --workspace` | 163 exercised behavior tests passed; 4 live-Core cases returned early / 163 个实际行为测试通过,4 个真实 Core 用例提前返回 | -| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-app --test evidence_process` | Spawned Gateway: 1000 enabled + 100 disabled requests, plus rejected UDS/steering startup passed / 真实 Gateway 子进程,启用 1000 次、关闭 100 次请求及 UDS/steering 启动拒绝测试通过 | -| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-app -p pc-gateway-transport -p pc-gateway-protocol` | Passed, including mixed-case SSE media types, first-event BOM usage/content, every body split and spawned Gateway byte preservation / 通过,含 SSE 媒体类型大小写、首事件 BOM usage/内容、任意 body 切分及真实子进程字节保持 | -| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-evidence` | Usage/privacy/bounded-writer tests and operational outcome output passed / usage、隐私、有界 writer 与运维 outcome 输出测试通过 | -| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-core --test executor_semantics` | 66 passed, including snapshot/evidence consistency on normal terminals and pending-future destruction / 66 个通过,含正常终态及 pending future 销毁时快照/证据一致性 | +| `cargo test --locked --manifest-path gateway/Cargo.toml --workspace` | 181 exercised behavior tests passed; 4 live-Core cases returned early / 181 个实际行为测试通过,4 个真实 Core 用例提前返回 | +| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-app --test capacity_process --test evidence_process` | 13 passed: capacity/UDS scenarios, readable overflow evidence, 1000 enabled + 100 disabled calls and rejected startup / 13 个通过:容量/UDS 场景、可读超限证据、启用 1000 次与关闭 100 次调用及启动拒绝 | +| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-core --test executor_semantics` | 73 passed; workspace also verifies normal/degraded capacity terminals, partial response facts and context refresh / 73 个通过;workspace 同时验证正常/降级容量终态、部分响应事实与上下文刷新 | | `make check` | Passed, including lock/policy checks, hooks, types and 61 integration-manifest tests / 通过,包含锁文件/策略检查、hooks、类型及 61 个集成清单测试 | | `uv run prek run -a` | Passed with all implementation files staged / 实现文件暂存后通过 | -| `make docs-test` | Passed: bilingual links and static build, 1084 public pages verified / 双语链接与静态构建通过,验证 1084 个公开页面 | +| `make docs-test` | Passed: bilingual links and static build, 1097 public pages verified / 双语链接与静态构建通过,验证 1097 个公开页面 | | `git diff --check` | Passed / 通过 | -The workspace runner prints 167 passing test cases. Four `live_context_check` cases return early when the real Core +The workspace runner prints 185 passing test cases. Four `live_context_check` cases return early when the real Core at `127.0.0.1:8000` is unavailable; readiness was unavailable here. Those four are not real-Core acceptance evidence. -workspace 输出共 167 个通过用例;其中 4 个 `live_context_check` 因真实 Core 不可达而提前返回,不能算作真实 Core 验收。 +workspace 输出共 185 个通过用例;其中 4 个 `live_context_check` 因真实 Core 不可达而提前返回,不能算作真实 Core 验收。 ## Observed behavior / 实际覆盖 @@ -53,6 +51,7 @@ workspace 输出共 167 个通过用例;其中 4 个 `live_context_check` 因 | --- | --- | | Correlated call terminals and actual attempts / 关联终态与真实尝试 | Executor tests cover success, zero-send block/withhold/expiry, retry/NotSent, Indeterminate, upstream HTTP error, release refusal/expiry, degraded execution and pending-future destruction / 覆盖成功、零发送拒绝/过期、重试/NotSent、不确定、上游 HTTP 错误、释放拒绝/过期、降级和 pending future 销毁 | | Usage through real transport / 真实 transport usage | Local HTTP JSON/SSE fixtures verify Chat/Responses input, output, cached reads, known zero and missing/malformed usage; cache writes stay unknown / 核对两种协议的输入、输出、缓存读、已知零及缺失/畸形 usage,缓存写保持未知 | +| Capacity/evidence integration / 容量与证据集成 | Real fixed-length/chunked overflow returns 409 with no prefix or resend; JSONL links one `buffer_limit_exceeded` attempt to a `withheld`/`possibly_sent` call with unknown usage and observed status/first byte. Normal/degraded executor variants agree with lifecycle snapshots / 真实定长/chunked 超限返回 409,不释放前缀、不重发;JSONL 将一次超限尝试与 `withheld`/`possibly_sent` 调用关联,usage 未知且保留状态码/首字节,正常/降级 executor 与生命周期快照一致 | | SSE evidence framing / SSE 证据 framing | Real transport reads 80/7/20 input/output/cache-read from lowercase and mixed-case media types, including first-event Chat/Responses usage behind one leading UTF-8 BOM. Protocol/body tests preserve original offsets through BOM and reject stripping a second/interior BOM / 真实 transport 在小写/混合大小写媒体类型及带一个开头 UTF-8 BOM 的 Chat/Responses 首事件读出 80/7/20 input/output/cache-read;协议/body 测试保留原始偏移,不移除第二个/流中间的 BOM | | Bounded retention and visible loss / 有界保留与可见丢失 | A held writer with capacity 4 receives 100000 extra submissions: exactly 4 queue, 99996 drop; 1 record remains in flight, and recovered output reports loss / 容量 4 且 writer 卡住时额外提交 10 万条,4 条排队、99996 条丢弃、1 条在写,恢复输出含丢失计数 | | Business isolation / 业务隔离 | Blocking/full and I/O-error writers preserve release/withhold decisions and pending-send cancellation/drop facts; errors are counted without their text / 慢写/队列满/I/O 错误不改变释放与 withhold 结论及发送中取消/销毁事实,错误仅计数不输出原文 | @@ -64,6 +63,15 @@ workspace 输出共 167 个通过用例;其中 4 个 `live_context_check` 因 | Real production composition / 真实生产装配 | Spawned binary handles 1000 requests with 6000 readable records and 1000 distinct call IDs; explicit Noop handles 100 requests with empty stdout and an evidence-disabled startup diagnostic / 真实二进制处理 1000 次请求,输出 6000 条可读记录、1000 个不同调用 ID;显式 Noop 处理 100 次请求,stdout 为空且启动诊断说明证据关闭 | | Both ingress formats / 两种入口格式 | In-process public-router tests send 200 calls through actual reqwest to local HTTP fixtures, covering Chat JSON/SSE and Responses JSON/replayed SSE, and read 1200 serialized production-sink records / 进程内公开路由用真实 reqwest 完成 200 次本地 HTTP 调用,覆盖 Chat JSON/SSE 与 Responses JSON/重放 SSE,读取生产 sink 的 1200 条序列化输出 | +The combined implementation preserves startup-confirmed input intersection, rendered-body limits (including +refreshed context), the response-buffer ceiling and separate fallback capacity from #2513. Capacity and evidence +process tests run against the same compiled production binary. The compatibility-ceiling test sends oversized +Content-Length headers and reads the early 413 before upload, avoiding a client BrokenPipe race while preserving +the pre-send rejection assertion. No HTTP OpenAPI change is introduced by this reconciliation. +合并后的实现保留 #2513 的启动容量交集、最终渲染限制(含刷新上下文)、响应缓冲上限与独立 fallback 容量。 +容量与证据进程测试使用同一个生产二进制。兼容性上限测试发送超限 Content-Length 请求头后直接读取提前返回的 +413,避开客户端上传 BrokenPipe 竞态,同时保留发送前拒绝的断言。本次协调未修改 HTTP OpenAPI 契约。 + The spawned-process workload alternates JSON and mixed-case `Text/Event-Stream; charset=utf-8` responses. Of 1000 enabled calls, 500 SSE responses contain a leading BOM with the sole content delta and usage in the first event; all 1000 call records preserve 101/13/61 input/output/cache-read and have exactly one first-model-content observation. From c8eeb50166d886f6155797a4ed6d74e645f979c1 Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Sat, 7 Nov 2026 17:14:50 +0800 Subject: [PATCH 12/15] fix(gateway): report total evidence loss independently of stdout --- docs/en/docs/operate/gateway-evidence.md | 22 ++- docs/zh/docs/operate/gateway-evidence.md | 19 +- .../src/evidence_diagnostics.rs | 161 +++++++++++++++++ gateway/crates/pc-gateway-app/src/main.rs | 19 +- .../pc-gateway-app/tests/evidence_process.rs | 170 +++++++++++++++++- 5 files changed, 381 insertions(+), 10 deletions(-) create mode 100644 gateway/crates/pc-gateway-app/src/evidence_diagnostics.rs diff --git a/docs/en/docs/operate/gateway-evidence.md b/docs/en/docs/operate/gateway-evidence.md index 348ac9375a..7e988dfd07 100644 --- a/docs/en/docs/operate/gateway-evidence.md +++ b/docs/en/docs/operate/gateway-evidence.md @@ -33,7 +33,27 @@ These are best-effort records: overflow can remove a call terminal or an attempt one line, and process exit can lose queued records. Readers should skip malformed/blank lines; after a write failure, the exporter restores a newline boundary before the next record. Counters reset on restart. There is no replay or billing/audit durability guarantee, and no financial reconciliation, token savings or task-success claim. -If the worker cannot start, the application reports a fixed diagnostic and uses Noop without changing business results. +The production host also starts one independent stderr health thread. It samples `JsonEvidenceSink.stats()` once +per second: the first nonzero `write_failed` emits `gateway.evidence.write_failed` at ERROR, and the first nonzero +`dropped` emits `gateway.evidence.dropped` at WARN. Each notification occurs at most once per sink. Either first +notification includes a `gateway.evidence.health` summary; thereafter a summary is emitted every 30 seconds even +without new requests or recovered stdout output. Healthy summaries use INFO; summaries with any cumulative loss use +WARN. Normal scheduling and writable stderr are required for timely reporting; `RUST_LOG` filters still apply. + +These stderr events contain fixed messages and only three cumulative unsigned record counts: `dropped` (rejected +submissions, including invalid records/full or disconnected queue), `write_failed` (failed/unconfirmed serialization, +write or flush), and `written` (successful write-and-flush operations). They carry no execution identity, writer error, +content, URL, credential or path. Counts reset on process restart and are independent atomic snapshots, not a reconciled +ledger. The embedded JSONL `loss` fields and schema are unchanged. This host-owned tracing output does not add Python +operational fields or change its JSON/console allowlists. + +A stalled stdout writer does not stop health reporting. A stalled stderr can occupy the one health thread; that +thread releases its sink reference before I/O, has no record queue, and cannot delay evidence submissions or sink +destruction. Dropping the sink retires the reporter on its next poll; shutdown never joins either potentially blocked +thread, so there is no guaranteed final summary or drain. Keep stderr collected separately from stdout: losing or +filtering both outputs cannot establish that there was no traffic. Embedding hosts that use `JsonEvidenceSink` directly +own their health reporting; the library does not configure logging or start a stderr reporter. +If either worker cannot start, the application reports a fixed diagnostic and uses Noop without changing business results. ## Operational vocabulary and exporter boundary diff --git a/docs/zh/docs/operate/gateway-evidence.md b/docs/zh/docs/operate/gateway-evidence.md index 8e5863432a..d00e2b9f1c 100644 --- a/docs/zh/docs/operate/gateway-evidence.md +++ b/docs/zh/docs/operate/gateway-evidence.md @@ -30,7 +30,24 @@ PC_GATEWAY_EVIDENCE=off ./gateway/target/release/pc-gateway 这些记录是尽力输出:溢出可能丢掉终态或尝试记录,失败/部分写入可能损坏一行,进程退出可能丢掉队列内容。 读取器应跳过畸形行和空行;写出失败后,exporter 会先补换行,再写下一条记录。计数随进程重启清零。 没有重放、计费或审计持久性保证,也不建立财务对账、token 节省或任务成功结论。 -写出线程无法启动时,应用输出固定诊断并使用 Noop,不改变业务结果。 +生产宿主另启动一个独立的 stderr 健康线程,每秒读取一次 `JsonEvidenceSink.stats()`:首次观察到非零 +`write_failed` 时以 ERROR 输出 `gateway.evidence.write_failed`,首次观察到非零 `dropped` 时以 WARN 输出 +`gateway.evidence.dropped`,每种通知每个 sink 最多一次。任一首次通知同时输出 `gateway.evidence.health` +汇总,此后每 30 秒汇总一次,即使没有新请求、stdout 仍未恢复也继续报告。无丢失的汇总为 INFO, +存在累计丢失的汇总为 WARN。及时报告依赖正常线程调度与可写的 stderr,仍遵循 `RUST_LOG` 过滤。 + +stderr 事件使用固定消息,仅携带三个累计无符号记录计数:`dropped` 为被拒绝的提交(含非法记录、队列满或断开), +`write_failed` 为失败或无法确认的序列化/写入/flush,`written` 为成功写入并 flush 的记录。 +不携带执行身份、writer 异常原文、正文、URL、凭据或路径。计数随进程重启清零,各字段为独立原子快照, +不是对账账本。JSONL 的 `loss` 字段及 schema 保持不变。此输出由 Rust 宿主通过 tracing 管理, +不新增 Python operational 字段,也不修改其 JSON/console 白名单。 + +stdout 写出卡住不影响健康线程。stderr 卡住最多占用该健康线程;线程在 I/O 前释放 sink 引用, +不维护记录队列,不会延迟证据提交或 sink 销毁。sink 销毁后 reporter 在下一次轮询时退出; +关闭时不 join 任何可能阻塞的线程,因此不保证最终汇总或排空。应独立采集 stderr 与 stdout; +两路输出同时丢失或被过滤时,不能据此推断没有流量。直接使用 `JsonEvidenceSink` 的嵌入宿主负责自身健康报告, +库不会配置日志或自动启动 stderr reporter。 +任一线程无法启动时,应用输出固定诊断并使用 Noop,不改变业务结果。 ## 运维词汇与 exporter 边界 diff --git a/gateway/crates/pc-gateway-app/src/evidence_diagnostics.rs b/gateway/crates/pc-gateway-app/src/evidence_diagnostics.rs new file mode 100644 index 0000000000..a7de1d1726 --- /dev/null +++ b/gateway/crates/pc-gateway-app/src/evidence_diagnostics.rs @@ -0,0 +1,161 @@ +// 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. + +//! Host-owned stderr health reporting, independent of the evidence writer and requests. +use pc_gateway_evidence::{EvidenceStats, JsonEvidenceSink}; +use std::sync::{Arc, Weak}; +use std::time::{Duration, Instant}; + +/// A single detached reporter per production sink. A blocked stderr holds only this +/// thread; it never blocks submissions, the stdout writer, or shutdown. No queue or +/// request data crosses this boundary, and dropping the sink retires the reporter. +pub(crate) fn start(sink: &Arc) -> std::io::Result<()> { + let sink = Arc::downgrade(sink); + let dispatch = tracing::dispatcher::get_default(Clone::clone); + std::thread::Builder::new() + .name("gateway-evidence-health".into()) + .spawn(move || { + tracing::dispatcher::with_default(&dispatch, || report(sink)); + }) + .map(|_| ()) +} + +fn report(sink: Weak) { + let mut write_failure_reported = false; + let mut drop_reported = false; + let mut last_summary = Instant::now(); + loop { + std::thread::park_timeout(Duration::from_secs(1)); + // Release the sink before stderr I/O, so a blocked diagnostic cannot keep + // its sender or stdout writer alive after the host drops the sink. + let Some(stats) = sink.upgrade().map(|sink| sink.stats()) else { + return; + }; + let first_write_failure = stats.write_failed > 0 && !write_failure_reported; + let first_drop = stats.dropped > 0 && !drop_reported; + if first_write_failure { + write_failure_reported = true; + tracing::error!( + event = "gateway.evidence.write_failed", + "gateway evidence write failed; records unavailable" + ); + } + if first_drop { + drop_reported = true; + tracing::warn!( + event = "gateway.evidence.dropped", + "gateway evidence submissions dropped; coverage incomplete" + ); + } + if first_write_failure || first_drop || last_summary.elapsed() >= Duration::from_secs(30) { + summary(stats); + last_summary = Instant::now(); + } + } +} + +fn summary(stats: EvidenceStats) { + // Fixed vocabulary and aggregate counts only, never writer errors or identities. + if stats.dropped > 0 || stats.write_failed > 0 { + tracing::warn!( + event = "gateway.evidence.health", + dropped = stats.dropped, + write_failed = stats.write_failed, + written = stats.written, + "gateway evidence loss summary" + ); + } else { + tracing::info!( + event = "gateway.evidence.health", + dropped = stats.dropped, + write_failed = stats.write_failed, + written = stats.written, + "gateway evidence health summary" + ); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use pc_gateway_evidence::{CallEvidence, EvidenceSink}; + use std::io::Write; + use std::sync::{mpsc, Mutex}; + + struct FailedOutput; + impl Write for FailedOutput { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::Error::other("SYNTHETIC_WRITER_SECRET")) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + struct BlockedDiagnostics { + entered: mpsc::Sender<()>, + resume: Mutex>, + } + impl Write for &BlockedDiagnostics { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + let _ = self.entered.send(()); + let _ = self.resume.lock().unwrap().recv(); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for BlockedDiagnostics { + type Writer = &'a BlockedDiagnostics; + fn make_writer(&'a self) -> Self::Writer { + self + } + } + + #[test] + fn blocked_diagnostics_do_not_hold_the_sink_or_delay_submissions_and_drop() { + let (entered_tx, entered_rx) = mpsc::channel(); + let (resume_tx, resume_rx) = mpsc::channel(); + let subscriber = tracing_subscriber::fmt() + .with_ansi(false) + .with_writer(BlockedDiagnostics { + entered: entered_tx, + resume: Mutex::new(resume_rx), + }) + .finish(); + let sink = Arc::new( + JsonEvidenceSink::new(FailedOutput, std::num::NonZeroUsize::new(1).unwrap()).unwrap(), + ); + let weak = Arc::downgrade(&sink); + tracing::subscriber::with_default(subscriber, || start(&sink).unwrap()); + let record = CallEvidence::default(); + sink.record_call(&record); + entered_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + let (finished_tx, finished_rx) = mpsc::channel(); + std::thread::spawn(move || { + for _ in 0..10_000 { + sink.record_call(&record); + } + assert!(sink.stats().write_failed > 0); + drop(sink); + finished_tx.send(()).unwrap(); + }); + let finished = finished_rx.recv_timeout(Duration::from_secs(3)); + // Unblock even on failure; no test thread or writer should be stranded. + drop(resume_tx); + finished.unwrap(); + assert!(weak.upgrade().is_none()); + } +} diff --git a/gateway/crates/pc-gateway-app/src/main.rs b/gateway/crates/pc-gateway-app/src/main.rs index 5c38943af8..3e5654f0b8 100644 --- a/gateway/crates/pc-gateway-app/src/main.rs +++ b/gateway/crates/pc-gateway-app/src/main.rs @@ -25,6 +25,7 @@ //! PC_GATEWAY_POLICY_VERSION、PC_GATEWAY_MAX_ATTEMPTS、PC_GATEWAY_DEGRADE。 mod evidence_body; +mod evidence_diagnostics; mod ingress; mod link; mod middleware; @@ -124,11 +125,19 @@ async fn main() { std::num::NonZeroUsize::new(1024).unwrap(), ) { Ok(sink) => { - tracing::info!( - capacity = 1024, - "gateway evidence JSONL enabled on stdout; drop newest on overflow" - ); - Arc::new(sink) + let sink = Arc::new(sink); + if evidence_diagnostics::start(&sink).is_err() { + tracing::error!( + "gateway evidence health reporter unavailable; evidence disabled" + ); + Arc::new(NoopEvidenceSink) + } else { + tracing::info!( + capacity = 1024, + "gateway evidence JSONL enabled on stdout; drop newest on overflow" + ); + sink + } } Err(_) => { tracing::error!("gateway evidence worker unavailable; evidence disabled"); diff --git a/gateway/crates/pc-gateway-app/tests/evidence_process.rs b/gateway/crates/pc-gateway-app/tests/evidence_process.rs index 81bca630c9..fb2ad44488 100644 --- a/gateway/crates/pc-gateway-app/tests/evidence_process.rs +++ b/gateway/crates/pc-gateway-app/tests/evidence_process.rs @@ -23,7 +23,7 @@ use std::io::{BufRead, Read}; use std::process::{Child, Command, Stdio}; use std::sync::{ atomic::{AtomicUsize, Ordering}, - Arc, + Arc, Mutex, }; use std::time::Duration; @@ -38,8 +38,7 @@ impl Drop for Gateway { } } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn production_jsonl_and_explicit_noop_keep_real_requests_usable() { +async fn evidence_fixture() -> (String, tokio::task::JoinHandle<()>) { let fixture = Router::new() .route("/v1/capabilities", get(|| async { Json(json!({"context_protection": { "check_versions": ["powercontext.context-check.v1"], "payload_versions": ["powercontext.model-json-payload.v1"], "enforcing":true, @@ -71,6 +70,12 @@ async fn production_jsonl_and_explicit_noop_keep_real_requests_usable() { let fixture_task = tokio::spawn(async move { axum::serve(listener, fixture).await.unwrap(); }); + (base, fixture_task) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn production_jsonl_and_explicit_noop_keep_real_requests_usable() { + let (base, fixture_task) = evidence_fixture().await; let client = reqwest::Client::new(); for disabled in [false, true] { let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); @@ -174,6 +179,7 @@ async fn production_jsonl_and_explicit_noop_keep_real_requests_usable() { if disabled { assert!(output.is_empty()); assert!(errors.contains("evidence disabled")); + assert!(!errors.contains("gateway.evidence.")); } else { assert_eq!(output.len(), count * 6); let mut call_ids = std::collections::BTreeSet::new(); @@ -235,3 +241,161 @@ fn rejected_startup_does_not_expose_uds_or_steering_paths() { assert!(errors.contains("file cannot be read")); assert!(!errors.contains("SYNTHETIC_")); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn total_evidence_loss_is_reported_on_stderr_without_blocking_requests() { + let (base, fixture_task) = evidence_fixture().await; + let client = reqwest::Client::new(); + for closed_stdout in [true, false] { + let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let address = port.local_addr().unwrap(); + drop(port); + let mut gateway = Gateway( + Command::new(env!("CARGO_BIN_EXE_pc-gateway")) + .env_clear() + .env("PC_GATEWAY_CORE_BASE", &base) + .env("PC_GATEWAY_LISTEN", address.to_string()) + .env( + "PC_GATEWAY_UPSTREAM_URL", + format!("{base}/v1/chat/completions"), + ) + .env("PC_GATEWAY_UPSTREAM_API_KEY", "SYNTHETIC_PROVIDER_KEY") + .env("RUST_LOG", "info") + .env("NO_COLOR", "1") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(), + ); + let mut stdout = gateway.0.stdout.take(); + if closed_stdout { + drop(stdout.take()); + } + // Leave an open stdout pipe unread to force a blocked writer and queue overflow. + let stderr = gateway.0.stderr.take().unwrap(); + let errors = Arc::new(Mutex::new(String::new())); + let captured = errors.clone(); + let reader = std::thread::spawn(move || { + for line in std::io::BufReader::new(stderr).lines() { + let mut text = captured.lock().unwrap(); + text.push_str(&line.unwrap()); + text.push('\n'); + } + }); + let url = format!("http://{address}"); + tokio::time::timeout(Duration::from_secs(10), async { + loop { + if client.get(format!("{url}/healthz")).send().await.is_ok() { + break; + } + assert!(gateway.0.try_wait().unwrap().is_none()); + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + let count = if closed_stdout { 10 } else { 500 }; + for _ in 0..count { + let response = tokio::time::timeout(Duration::from_secs(3), + client.post(format!("{url}/gateway/v1/chat/completions")) + .json(&json!({"model":"SYNTHETIC_MODEL", "messages":[{"role":"user", "content":"SYNTHETIC_PROMPT_SECRET"}]})) + .send()).await.unwrap().unwrap(); + assert_eq!(response.status(), 200); + assert_eq!( + response.json::().await.unwrap()["usage"]["prompt_tokens"], + 101 + ); + } + let event = if closed_stdout { + "gateway.evidence.write_failed" + } else { + "gateway.evidence.dropped" + }; + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let text = errors.lock().unwrap().clone(); + if text.contains(event) && text.contains("gateway evidence loss summary") { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + { + let text = errors.lock().unwrap(); + assert_eq!(text.matches(event).count(), 1); + assert!(!text.contains("SYNTHETIC_")); + let summary = text + .lines() + .find(|line| line.contains("gateway evidence loss summary")) + .unwrap(); + let count = |field: &str| -> u64 { + summary + .split_once(&format!("{field}=")) + .unwrap() + .1 + .split_whitespace() + .next() + .unwrap() + .parse() + .unwrap() + }; + if closed_stdout { + assert_eq!(count("written"), 0); + assert!(count("write_failed") > 0); + } else { + assert!(count("dropped") > 0); + assert_eq!( + count("write_failed"), + 0, + "the stdout writer is blocked, not recovered" + ); + } + } + if !closed_stdout { + // No new requests and no stdout recovery: the independent summary still recurs. + let previous = errors + .lock() + .unwrap() + .matches("gateway evidence loss summary") + .count(); + tokio::time::timeout(Duration::from_secs(35), async { + loop { + if errors + .lock() + .unwrap() + .matches("gateway evidence loss summary") + .count() + > previous + { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + }) + .await + .unwrap(); + assert_eq!(errors.lock().unwrap().matches(event).count(), 1); + // Retire the unread pipe; requests remain usable after the write fails as well. + drop(stdout.take()); + let response = tokio::time::timeout( + Duration::from_secs(3), + client + .post(format!("{url}/gateway/v1/chat/completions")) + .json(&json!({"model":"test", "messages":[{"role":"user", "content":"hello"}]})) + .send(), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(response.status(), 200); + } + drop(gateway); + reader.join().unwrap(); + let text = errors.lock().unwrap(); + assert!(!text.contains("SYNTHETIC_")); + assert!(!text.contains("Broken pipe")); + } + fixture_task.abort(); +} From f489d55729cab08084052c611632c943e51030b8 Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Sat, 7 Nov 2026 17:16:17 +0800 Subject: [PATCH 13/15] docs(gateway): record total evidence loss diagnostics validation --- gateway/EVIDENCE_VALIDATION.md | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/gateway/EVIDENCE_VALIDATION.md b/gateway/EVIDENCE_VALIDATION.md index 7633b4d869..2275b4375a 100644 --- a/gateway/EVIDENCE_VALIDATION.md +++ b/gateway/EVIDENCE_VALIDATION.md @@ -1,7 +1,7 @@ # Gateway evidence validation / Gateway 证据验收 - Date / 日期: 2026-11-07. -- Implementation commit / 实现提交: `b1f03eb59cc9327e9c1e8ad3df60a2fbcf914713`. +- Implementation commit / 实现提交: `c8eeb50166d886f6155797a4ed6d74e645f979c1`. - Merged master / 已合并 master: `b8b189091e7a412300cf1292531208a8ead0e325`, including #2513 capacity limits and context refresh. / 包含 #2513 容量限制与上下文刷新。 - Platform / 平台: Darwin arm64, Rust `1.95.0 (59807616e 2026-04-14)`, Python 3.13.15. - Scope / 范围: [#2463](https://github.com/oceanbase/powercontext/issues/2463), @@ -33,17 +33,22 @@ Cargo was invoked through `/Users/lioky/.cargo/bin/cargo` because the shell's mi | --- | --- | | `cargo fmt --manifest-path gateway/Cargo.toml --all --check` | Passed / 通过 | | `cargo clippy --locked --manifest-path gateway/Cargo.toml --all-targets -- -D warnings` | Passed / 通过 | -| `cargo test --locked --manifest-path gateway/Cargo.toml --workspace` | 181 exercised behavior tests passed; 4 live-Core cases returned early / 181 个实际行为测试通过,4 个真实 Core 用例提前返回 | -| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-app --test capacity_process --test evidence_process` | 13 passed: capacity/UDS scenarios, readable overflow evidence, 1000 enabled + 100 disabled calls and rejected startup / 13 个通过:容量/UDS 场景、可读超限证据、启用 1000 次与关闭 100 次调用及启动拒绝 | -| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-core --test executor_semantics` | 73 passed; workspace also verifies normal/degraded capacity terminals, partial response facts and context refresh / 73 个通过;workspace 同时验证正常/降级容量终态、部分响应事实与上下文刷新 | +| `cargo test --locked --manifest-path gateway/Cargo.toml --workspace` | 183 exercised behavior tests passed; 4 live-Core cases returned early / 183 个实际行为测试通过,4 个真实 Core 用例提前返回 | +| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-app` | 49 passed, including independent stderr diagnostics, capacity/UDS, readable overflow evidence, 1000 enabled + 100 disabled calls, 511 calls with stdout loss and rejected startup / 49 个通过,含独立 stderr 诊断、容量/UDS、可读超限证据、启用 1000 次与关闭 100 次调用、stdout 丢失时 511 次调用及启动拒绝 | | `make check` | Passed, including lock/policy checks, hooks, types and 61 integration-manifest tests / 通过,包含锁文件/策略检查、hooks、类型及 61 个集成清单测试 | | `uv run prek run -a` | Passed with all implementation files staged / 实现文件暂存后通过 | | `make docs-test` | Passed: bilingual links and static build, 1097 public pages verified / 双语链接与静态构建通过,验证 1097 个公开页面 | | `git diff --check` | Passed / 通过 | -The workspace runner prints 185 passing test cases. Four `live_context_check` cases return early when the real Core +The workspace runner prints 187 passing test cases. Four `live_context_check` cases return early when the real Core at `127.0.0.1:8000` is unavailable; readiness was unavailable here. Those four are not real-Core acceptance evidence. -workspace 输出共 185 个通过用例;其中 4 个 `live_context_check` 因真实 Core 不可达而提前返回,不能算作真实 Core 验收。 +workspace 输出共 187 个通过用例;其中 4 个 `live_context_check` 因真实 Core 不可达而提前返回,不能算作真实 Core 验收。 + +One earlier workspace attempt failed in the existing capacity process startup check (`gateway exited during startup`) +while the documentation build was also running. That harness discarded child stderr, so the cause was not established. +A complete workspace rerun passed with all tests included and the usual parallelism; no assertion or test was removed. +一次较早的 workspace 执行在文档构建并行期间遇到既有容量子进程启动检查失败;该 harness 丢弃子进程 stderr, +因此未确认原因。完整 workspace 重跑以通常并行度通过,没有移除测试或断言。 ## Observed behavior / 实际覆盖 @@ -54,6 +59,8 @@ workspace 输出共 185 个通过用例;其中 4 个 `live_context_check` 因 | Capacity/evidence integration / 容量与证据集成 | Real fixed-length/chunked overflow returns 409 with no prefix or resend; JSONL links one `buffer_limit_exceeded` attempt to a `withheld`/`possibly_sent` call with unknown usage and observed status/first byte. Normal/degraded executor variants agree with lifecycle snapshots / 真实定长/chunked 超限返回 409,不释放前缀、不重发;JSONL 将一次超限尝试与 `withheld`/`possibly_sent` 调用关联,usage 未知且保留状态码/首字节,正常/降级 executor 与生命周期快照一致 | | SSE evidence framing / SSE 证据 framing | Real transport reads 80/7/20 input/output/cache-read from lowercase and mixed-case media types, including first-event Chat/Responses usage behind one leading UTF-8 BOM. Protocol/body tests preserve original offsets through BOM and reject stripping a second/interior BOM / 真实 transport 在小写/混合大小写媒体类型及带一个开头 UTF-8 BOM 的 Chat/Responses 首事件读出 80/7/20 input/output/cache-read;协议/body 测试保留原始偏移,不移除第二个/流中间的 BOM | | Bounded retention and visible loss / 有界保留与可见丢失 | A held writer with capacity 4 receives 100000 extra submissions: exactly 4 queue, 99996 drop; 1 record remains in flight, and recovered output reports loss / 容量 4 且 writer 卡住时额外提交 10 万条,4 条排队、99996 条丢弃、1 条在写,恢复输出含丢失计数 | +| Total stream loss / 整条输出流丢失 | Real Gateway with closed stdout reports nonzero write failures and zero writes on stderr; unread stdout reports nonzero drops, then another summary after 30 seconds without new requests or recovery. 511 requests return HTTP 200 with original usage; diagnostics exclude synthetic content/credentials and OS error text / 真实 Gateway 关闭 stdout 时 stderr 报告非零写失败与零写出;不读取 stdout 时报告非零丢弃,停止请求且不恢复后 30 秒再次汇总。511 次请求返回 200 并保留 usage,诊断不含合成正文/凭据或 OS 异常文本 | +| Diagnostic isolation / 诊断隔离 | A controlled blocked diagnostic writer cannot retain the sink or delay 10000 submissions and sink destruction / 受控诊断 writer 卡住时,不保留 sink、不延迟 10000 次提交及 sink 销毁 | | Business isolation / 业务隔离 | Blocking/full and I/O-error writers preserve release/withhold decisions and pending-send cancellation/drop facts; errors are counted without their text / 慢写/队列满/I/O 错误不改变释放与 withhold 结论及发送中取消/销毁事实,错误仅计数不输出原文 | | Timing and strict order / 计时与 strict 顺序 | Header-wait fixture is included in first-byte timing; incomplete responses retain observed status/first byte; release approval precedes framework handoff, first body frame and first model-content observation; model TTFT is null / 首字节包含响应头等待,部分失败保留已知状态与首字节,批准先于框架交接、首 frame 与首次模型内容观测,模型 TTFT 为 null | | Privacy / 隐私 | Synthetic prompt/response/model/request-ID/credential/provider-error/I/O-error markers are absent from evidence; process test also checks stderr / 合成 prompt、响应、模型名、请求 ID、凭据、provider 异常及 I/O 异常标记未出现在证据中,进程测试另检查 stderr | @@ -72,6 +79,16 @@ the pre-send rejection assertion. No HTTP OpenAPI change is introduced by this r 容量与证据进程测试使用同一个生产二进制。兼容性上限测试发送超限 Content-Length 请求头后直接读取提前返回的 413,避开客户端上传 BrokenPipe 竞态,同时保留发送前拒绝的断言。本次协调未修改 HTTP OpenAPI 契约。 +The production host reads aggregate sink stats on an independent thread every second, emits one warning/error +per first loss category and periodic 30-second summaries to stderr. These reports do not need a successful stdout +record. The reporter releases its sink reference before logging and has no record queue. Both worker startups must +succeed to enable production evidence. Shutdown does not join blocked writers or promise a final summary; logging +filters and loss of stderr remain operational limits. JSONL schema, Python allowlists and dependency versions are unchanged. +生产宿主在独立线程每秒读取聚合计数,首次各类丢失仅通知一次,之后每 30 秒通过 stderr 汇总, +不依赖 stdout 成功写出。reporter 在日志 I/O 前释放 sink 引用且没有记录队列。两个线程均成功启动后才启用生产证据。 +关闭时不 join 阻塞 writer,也不保证最终汇总;日志过滤和 stderr 丢失仍是运维边界。 +未修改 JSONL schema、Python 白名单或依赖版本。 + The spawned-process workload alternates JSON and mixed-case `Text/Event-Stream; charset=utf-8` responses. Of 1000 enabled calls, 500 SSE responses contain a leading BOM with the sole content delta and usage in the first event; all 1000 call records preserve 101/13/61 input/output/cache-read and have exactly one first-model-content observation. From 2b3a1c5a48999ccae6a78499e61ba6d9a78bfdb5 Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Sat, 7 Nov 2026 18:15:53 +0800 Subject: [PATCH 14/15] fix(gateway): preserve response body timeout evidence --- docs/en/docs/operate/gateway-evidence.md | 4 +- docs/zh/docs/operate/gateway-evidence.md | 2 + .../tests/executor_semantics.rs | 138 ++++++++++++++++++ .../src/reqwest_transport.rs | 18 ++- .../crates/pc-gateway-transport/src/sender.rs | 1 + .../tests/usage_timing.rs | 80 ++++++++++ 6 files changed, 238 insertions(+), 5 deletions(-) diff --git a/docs/en/docs/operate/gateway-evidence.md b/docs/en/docs/operate/gateway-evidence.md index 7e988dfd07..36c8e46620 100644 --- a/docs/en/docs/operate/gateway-evidence.md +++ b/docs/en/docs/operate/gateway-evidence.md @@ -129,7 +129,9 @@ Each `attempt` contains `attempt`, `outcome`, `started_ms`, `duration_ms`, `upst `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`, `lost_after_handoff`, `timeout_awaiting_response`, and `buffer_limit_exceeded`. A partial-response failure preserves -its observed status/first-byte timing but keeps completion and usage unknown. Once the transport reports delivery, +its observed status/first-byte timing but keeps completion and usage unknown. `timeout_awaiting_response` covers +both waiting for response headers and timing out while reading the body, including after a partial body; +`lost_after_handoff` covers other transport/body failures. Neither permits automatic retry. Once the transport reports delivery, 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, diff --git a/docs/zh/docs/operate/gateway-evidence.md b/docs/zh/docs/operate/gateway-evidence.md index d00e2b9f1c..79ffb9e7cf 100644 --- a/docs/zh/docs/operate/gateway-evidence.md +++ b/docs/zh/docs/operate/gateway-evidence.md @@ -118,6 +118,8 @@ pending 执行 future 销毁时输出 `abandoned` 并保留发送事实。 结果取值为 `possibly_sent`(pending 发送被中断)、`delivered`、`upstream_error`(完整 HTTP 响应且状态码 >= 400)、 `connect_refused`、`rejected_locally`、`lost_after_handoff`、`timeout_awaiting_response`、`buffer_limit_exceeded`。 部分响应失败保留已观察到的状态码与首字节时间,完整响应时间和 usage 保持未知。 +`timeout_awaiting_response` 包含等待响应头超时和读取正文超时(含已经收到部分正文); +`lost_after_handoff` 表示其他传输/正文读取失败。两者均不允许自动重试。 transport 交付完整响应后,解码或释放失败不会丢掉 usage。直接丢弃 pending transport 时无法取得其内部的部分观测。 响应缓冲区超限时,调用记录为 `withheld`、发送事实为 `possibly_sent`,仅有一次 `buffer_limit_exceeded` 尝试; usage 与完整响应时间未知,保留已观察到的状态码和首字节时间。不释放响应前缀,也不重试,降级直通同样遵循此行为。 diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index fcb18e6d5c..28fc877026 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -3574,3 +3574,141 @@ async fn response_capacity_withholds_without_retry_and_preserves_possible_billin } } } + +#[tokio::test] +async fn real_body_timeout_exports_timeout_attempt_and_unknown_usage_without_release_or_retry() { + use pc_gateway_evidence::JsonEvidenceSink; + use pc_gateway_transport::ReqwestTransport; + use std::time::Duration; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + #[derive(Clone, Default)] + struct Output(Arc>>); + impl std::io::Write for Output { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + for degrade in [ + DegradePolicy::Pause, + DegradePolicy::PassthroughWithoutMemory, + ] { + for stream in [false, true] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + let mut buffer = [0; 4096]; + loop { + let n = socket.read(&mut buffer).await.unwrap(); + assert!(n > 0); + request.extend_from_slice(&buffer[..n]); + if let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") { + let head = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase(); + let length: usize = head + .lines() + .find_map(|line| line.strip_prefix("content-length: ")) + .unwrap() + .parse() + .unwrap(); + if request.len() >= end + 4 + length { + break; + } + } + } + let (mime, partial) = if stream { + ("text/event-stream", "data: {\"usage\":{\"prompt_tokens\":80},\"secret\":\"SYNTHETIC_PARTIAL_SECRET\"}\n\n") + } else { + ("application/json", "{\"usage\":{\"prompt_tokens\":80},\"secret\":\"SYNTHETIC_PARTIAL_SECRET\"}") + }; + socket.write_all(format!("HTTP/1.1 201 Created\r\nContent-Type: {mime}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{partial}", partial.len() + 100).as_bytes()).await.unwrap(); + let _ = finish_rx.await; + }); + let verdict = if degrade == DegradePolicy::Pause { + Ok(result(CheckPhase::BeforeSend, CheckDecision::Allow, &[])) + } else { + Err(GateError::GateUnavailable("SYNTHETIC_GATE_SECRET".into())) + }; + let (_, renderer, _, gate) = harness(vec![verdict], vec![], 3); + let executor = Executor::new( + FakeGateRef(gate.clone()), + ReqwestTransport::new(Duration::from_millis(250)), + NonZeroU32::new(3).unwrap(), + ); + let mut call = call(degrade); + call.target_url = + format!("http://SYNTHETIC_USER:SYNTHETIC_PASSWORD@{address}/SYNTHETIC_PATH"); + call.request.stream = stream; + let control = request_control(); + let observation = control.observation(); + let output = Output::default(); + let sink = + JsonEvidenceSink::new(output.clone(), std::num::NonZeroUsize::new(8).unwrap()) + .unwrap(); + let outcome = executor + .run(control, call, &RendererRef(renderer), &sink) + .await; + let _ = finish_tx.send(()); + server.await.unwrap(); + assert!(matches!(outcome, ManagedOutcome::SendIndeterminate)); + assert_eq!( + gate.seen.lock().unwrap().len(), + 1, + "no release check or readmission" + ); + assert_eq!( + observation.snapshot().model_send, + ModelSendState::PossiblySent + ); + assert_eq!( + observation.snapshot().execution, + ExecutionState::Finished(ExecutionTerminal::SendIndeterminate) + ); + tokio::time::timeout(Duration::from_secs(3), async { + while sink.stats().written < 2 { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + let text = String::from_utf8(output.0.lock().unwrap().clone()).unwrap(); + assert!(!text.contains("SYNTHETIC_")); + let records: Vec = text + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + assert_eq!( + records.len(), + 2, + "one attempt and one call, without delivery" + ); + assert_eq!(records[0]["event"], "attempt"); + assert_eq!(records[1]["event"], "call"); + let attempt = &records[0]["evidence"]; + let call = &records[1]["evidence"]; + assert_eq!(attempt["call_id"], call["call_id"]); + assert_eq!(attempt["outcome"], "timeout_awaiting_response"); + assert_eq!(attempt["upstream_status"], 201); + assert!(attempt["response_first_byte_ms"].is_number()); + assert!(attempt["response_complete_ms"].is_null()); + assert_eq!(call["terminal"], "send_indeterminate"); + assert_eq!(call["sending"], "possibly_sent"); + assert_eq!(call["attempts"], 1); + assert_eq!(call["upstream_status"], 201); + assert!(call["release_decision_ms"].is_null()); + assert!(call["release_authorized_ms"].is_null()); + for evidence in [attempt, call] { + for field in ["input", "output", "cache_read", "cache_write"] { + assert_eq!(evidence["usage"][field]["completeness"], "unknown"); + assert!(evidence["usage"][field]["tokens"].is_null()); + } + } + } + } +} diff --git a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs index a2b2db5e81..f9294477f4 100644 --- a/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs +++ b/gateway/crates/pc-gateway-transport/src/reqwest_transport.rs @@ -111,9 +111,9 @@ impl Transport for ReqwestTransport { loop { match next_chunk(&mut stream).await { None => break, - Some(Err(_)) => { + Some(Err(reason)) => { return SendOutcome::IncompleteResponse { - reason: SendIndeterminateReason::LostAfterHandoff, + reason, status, response_first_byte_ms: first_byte, } @@ -190,12 +190,22 @@ fn extract_usage(body: &[u8], content_type: &str) -> Option { } /// 不引入 futures-util 依赖的 next():用标准库 poll_fn 轮询 Stream。 -async fn next_chunk(stream: &mut S) -> Option> +async fn next_chunk(stream: &mut S) -> Option> where S: futures_core::Stream> + Unpin, { use std::pin::Pin; std::future::poll_fn(|cx| Pin::new(&mut *stream).poll_next(cx)) .await - .map(|r| r.map_err(|_| ())) + .map(|r| { + r.map_err(|error| { + // Preserve the failure category after headers too, without retaining + // or exporting reqwest errors (which can contain URLs/credentials). + if error.is_timeout() { + SendIndeterminateReason::TimeoutAwaitingResponse + } else { + SendIndeterminateReason::LostAfterHandoff + } + }) + }) } diff --git a/gateway/crates/pc-gateway-transport/src/sender.rs b/gateway/crates/pc-gateway-transport/src/sender.rs index 88559dc852..9d94eb3bda 100644 --- a/gateway/crates/pc-gateway-transport/src/sender.rs +++ b/gateway/crates/pc-gateway-transport/src/sender.rs @@ -74,6 +74,7 @@ pub enum NotSentReason { pub enum SendIndeterminateReason { #[error("connection lost after request handed to transport")] LostAfterHandoff, + /// Timeout waiting for response headers or reading the response body. #[error("timeout awaiting response")] TimeoutAwaitingResponse, /// 流式接收超过缓冲上限:请求已送达且部分计费,不重发。 diff --git a/gateway/crates/pc-gateway-transport/tests/usage_timing.rs b/gateway/crates/pc-gateway-transport/tests/usage_timing.rs index f9df5a792d..f2a9ff95d0 100644 --- a/gateway/crates/pc-gateway-transport/tests/usage_timing.rs +++ b/gateway/crates/pc-gateway-transport/tests/usage_timing.rs @@ -132,3 +132,83 @@ async fn sse_leading_bom_preserves_first_event_usage_and_original_bytes() { } } } + +#[tokio::test] +async fn body_read_timeouts_and_truncations_keep_distinct_reasons_without_retry() { + use pc_gateway_evidence::BufferedEvidenceSink; + use pc_gateway_transport::{BoundedRetry, RetryOutcome, SendIndeterminateReason}; + for stream in [false, true] { + for (stall, partial) in [(true, false), (true, true), (false, true)] { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + let mut chunk = [0; 4096]; + // The fixture request has the two-byte body "{}". Read it before + // closing to isolate response truncation from an unread-request reset. + while !request.ends_with(b"\r\n\r\n{}") { + let n = socket.read(&mut chunk).await.unwrap(); + assert!(n > 0); + request.extend_from_slice(&chunk[..n]); + } + let mime = if stream { + "text/event-stream" + } else { + "application/json" + }; + socket.write_all(format!("HTTP/1.1 201 Created\r\nContent-Type: {mime}\r\nContent-Length: 4096\r\nConnection: close\r\n\r\n").as_bytes()).await.unwrap(); + if partial { + socket + .write_all(b"SYNTHETIC_PARTIAL_RESPONSE_SECRET") + .await + .unwrap(); + } + if stall { + // Keep the socket open until the transport's timeout has fired. + let _ = finish_rx.await; + } + }); + let transport = BoundedRetry::new( + ReqwestTransport::new(Duration::from_millis(100)), + std::num::NonZeroU32::new(3).unwrap(), + ); + let evidence = BufferedEvidenceSink::new(); + let outcome = transport + .send_with_retry( + &AdmittedSend { + binding: "fixture".into(), + payload: bytes::Bytes::from_static(b"{}"), + target_url: format!("http://{address}/provider"), + headers: vec![], + stream, + }, + &evidence, + ) + .await; + let _ = finish_tx.send(()); + server.await.unwrap(); + assert_eq!( + evidence.attempts(), + [1], + "an incomplete response must never retry" + ); + let RetryOutcome::Done(SendOutcome::IncompleteResponse { + reason, + status, + response_first_byte_ms, + }) = outcome + else { + panic!("expected an incomplete response, got {outcome:?}"); + }; + assert_eq!(status, 201); + assert_eq!(response_first_byte_ms.is_some(), partial); + assert!(matches!( + (stall, reason), + (true, SendIndeterminateReason::TimeoutAwaitingResponse) + | (false, SendIndeterminateReason::LostAfterHandoff) + )); + } + } +} From 196a448629541a8af161ff9dd462650c3f471f3d Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Sat, 7 Nov 2026 18:17:16 +0800 Subject: [PATCH 15/15] docs(gateway): record response body timeout regression validation --- gateway/EVIDENCE_VALIDATION.md | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/gateway/EVIDENCE_VALIDATION.md b/gateway/EVIDENCE_VALIDATION.md index 2275b4375a..50f7d4b92f 100644 --- a/gateway/EVIDENCE_VALIDATION.md +++ b/gateway/EVIDENCE_VALIDATION.md @@ -1,7 +1,7 @@ # Gateway evidence validation / Gateway 证据验收 - Date / 日期: 2026-11-07. -- Implementation commit / 实现提交: `c8eeb50166d886f6155797a4ed6d74e645f979c1`. +- Implementation commit / 实现提交: `2b3a1c5a48999ccae6a78499e61ba6d9a78bfdb5`. - Merged master / 已合并 master: `b8b189091e7a412300cf1292531208a8ead0e325`, including #2513 capacity limits and context refresh. / 包含 #2513 容量限制与上下文刷新。 - Platform / 平台: Darwin arm64, Rust `1.95.0 (59807616e 2026-04-14)`, Python 3.13.15. - Scope / 范围: [#2463](https://github.com/oceanbase/powercontext/issues/2463), @@ -33,22 +33,17 @@ Cargo was invoked through `/Users/lioky/.cargo/bin/cargo` because the shell's mi | --- | --- | | `cargo fmt --manifest-path gateway/Cargo.toml --all --check` | Passed / 通过 | | `cargo clippy --locked --manifest-path gateway/Cargo.toml --all-targets -- -D warnings` | Passed / 通过 | -| `cargo test --locked --manifest-path gateway/Cargo.toml --workspace` | 183 exercised behavior tests passed; 4 live-Core cases returned early / 183 个实际行为测试通过,4 个真实 Core 用例提前返回 | -| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-app` | 49 passed, including independent stderr diagnostics, capacity/UDS, readable overflow evidence, 1000 enabled + 100 disabled calls, 511 calls with stdout loss and rejected startup / 49 个通过,含独立 stderr 诊断、容量/UDS、可读超限证据、启用 1000 次与关闭 100 次调用、stdout 丢失时 511 次调用及启动拒绝 | +| `cargo test --locked --manifest-path gateway/Cargo.toml --workspace` | 185 exercised behavior tests passed; 4 live-Core cases returned early / 185 个实际行为测试通过,4 个真实 Core 用例提前返回 | +| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-transport --test usage_timing` | 5 passed, including actual 100 ms body-read timeouts versus premature EOF for JSON/SSE, with headers-only or partial-body observations and no retry / 5 个通过,含真实 100 ms 正文读取超时与提前 EOF 的 JSON/SSE 区分、仅响应头/部分正文事实及不重试 | +| `cargo test --locked --manifest-path gateway/Cargo.toml -p pc-gateway-core --test executor_semantics` | 74 passed; actual reqwest body timeouts through normal/degraded executor paths export readable timeout attempts, unknown usage and no release or retry / 74 个通过;真实 reqwest 正文超时经正常/降级 executor 输出可读超时尝试、未知 usage,不释放、不重试 | | `make check` | Passed, including lock/policy checks, hooks, types and 61 integration-manifest tests / 通过,包含锁文件/策略检查、hooks、类型及 61 个集成清单测试 | | `uv run prek run -a` | Passed with all implementation files staged / 实现文件暂存后通过 | | `make docs-test` | Passed: bilingual links and static build, 1097 public pages verified / 双语链接与静态构建通过,验证 1097 个公开页面 | | `git diff --check` | Passed / 通过 | -The workspace runner prints 187 passing test cases. Four `live_context_check` cases return early when the real Core +The workspace runner prints 189 passing test cases. Four `live_context_check` cases return early when the real Core at `127.0.0.1:8000` is unavailable; readiness was unavailable here. Those four are not real-Core acceptance evidence. -workspace 输出共 187 个通过用例;其中 4 个 `live_context_check` 因真实 Core 不可达而提前返回,不能算作真实 Core 验收。 - -One earlier workspace attempt failed in the existing capacity process startup check (`gateway exited during startup`) -while the documentation build was also running. That harness discarded child stderr, so the cause was not established. -A complete workspace rerun passed with all tests included and the usual parallelism; no assertion or test was removed. -一次较早的 workspace 执行在文档构建并行期间遇到既有容量子进程启动检查失败;该 harness 丢弃子进程 stderr, -因此未确认原因。完整 workspace 重跑以通常并行度通过,没有移除测试或断言。 +workspace 输出共 189 个通过用例;其中 4 个 `live_context_check` 因真实 Core 不可达而提前返回,不能算作真实 Core 验收。 ## Observed behavior / 实际覆盖 @@ -57,6 +52,7 @@ A complete workspace rerun passed with all tests included and the usual parallel | Correlated call terminals and actual attempts / 关联终态与真实尝试 | Executor tests cover success, zero-send block/withhold/expiry, retry/NotSent, Indeterminate, upstream HTTP error, release refusal/expiry, degraded execution and pending-future destruction / 覆盖成功、零发送拒绝/过期、重试/NotSent、不确定、上游 HTTP 错误、释放拒绝/过期、降级和 pending future 销毁 | | Usage through real transport / 真实 transport usage | Local HTTP JSON/SSE fixtures verify Chat/Responses input, output, cached reads, known zero and missing/malformed usage; cache writes stay unknown / 核对两种协议的输入、输出、缓存读、已知零及缺失/畸形 usage,缓存写保持未知 | | Capacity/evidence integration / 容量与证据集成 | Real fixed-length/chunked overflow returns 409 with no prefix or resend; JSONL links one `buffer_limit_exceeded` attempt to a `withheld`/`possibly_sent` call with unknown usage and observed status/first byte. Normal/degraded executor variants agree with lifecycle snapshots / 真实定长/chunked 超限返回 409,不释放前缀、不重发;JSONL 将一次超限尝试与 `withheld`/`possibly_sent` 调用关联,usage 未知且保留状态码/首字节,正常/降级 executor 与生命周期快照一致 | +| Body timeout classification / 正文超时分类 | Real local HTTP fixtures send headers with or without a partial body, then stall: timeout stays `timeout_awaiting_response`; premature EOF stays `lost_after_handoff`. Readable JSONL preserves observed status/first byte, `possibly_sent`, unknown completion/usage, one attempt and no release/retry in normal/degraded execution / 真实本地 HTTP fixture 发送头部(可含部分正文)后停住,超时保留 timeout 分类,提前 EOF 保留连接丢失分类;正常/降级执行的 JSONL 保留状态/首字节、可能送达、未知完整响应/usage、单次尝试且不释放/重试 | | SSE evidence framing / SSE 证据 framing | Real transport reads 80/7/20 input/output/cache-read from lowercase and mixed-case media types, including first-event Chat/Responses usage behind one leading UTF-8 BOM. Protocol/body tests preserve original offsets through BOM and reject stripping a second/interior BOM / 真实 transport 在小写/混合大小写媒体类型及带一个开头 UTF-8 BOM 的 Chat/Responses 首事件读出 80/7/20 input/output/cache-read;协议/body 测试保留原始偏移,不移除第二个/流中间的 BOM | | Bounded retention and visible loss / 有界保留与可见丢失 | A held writer with capacity 4 receives 100000 extra submissions: exactly 4 queue, 99996 drop; 1 record remains in flight, and recovered output reports loss / 容量 4 且 writer 卡住时额外提交 10 万条,4 条排队、99996 条丢弃、1 条在写,恢复输出含丢失计数 | | Total stream loss / 整条输出流丢失 | Real Gateway with closed stdout reports nonzero write failures and zero writes on stderr; unread stdout reports nonzero drops, then another summary after 30 seconds without new requests or recovery. 511 requests return HTTP 200 with original usage; diagnostics exclude synthetic content/credentials and OS error text / 真实 Gateway 关闭 stdout 时 stderr 报告非零写失败与零写出;不读取 stdout 时报告非零丢弃,停止请求且不恢复后 30 秒再次汇总。511 次请求返回 200 并保留 usage,诊断不含合成正文/凭据或 OS 异常文本 | @@ -70,6 +66,18 @@ A complete workspace rerun passed with all tests included and the usual parallel | Real production composition / 真实生产装配 | Spawned binary handles 1000 requests with 6000 readable records and 1000 distinct call IDs; explicit Noop handles 100 requests with empty stdout and an evidence-disabled startup diagnostic / 真实二进制处理 1000 次请求,输出 6000 条可读记录、1000 个不同调用 ID;显式 Noop 处理 100 次请求,stdout 为空且启动诊断说明证据关闭 | | Both ingress formats / 两种入口格式 | In-process public-router tests send 200 calls through actual reqwest to local HTTP fixtures, covering Chat JSON/SSE and Responses JSON/replayed SSE, and read 1200 serialized production-sink records / 进程内公开路由用真实 reqwest 完成 200 次本地 HTTP 调用,覆盖 Chat JSON/SSE 与 Responses JSON/重放 SSE,读取生产 sink 的 1200 条序列化输出 | +Body-read timeout regression tests failed before the fix: the real transport and exported attempt both reported +`lost_after_handoff`. After classification is preserved before discarding the reqwest error, the same fixtures pass. +Transport fixtures use an actual 100 ms timeout; executor/export fixtures use 250 ms and a fake Gate with the real +reqwest transport and production JSONL sink. These are local HTTP and executor acceptance, not a spawned-Gateway +short-timeout configuration, a real Core or hosted-provider claim. Raw reqwest errors are not retained or exported; +no public enum values, schema fields, timeout configuration or retry behavior changed. +正文超时回归在修复前失败:真实 transport 与导出的尝试均误记 `lost_after_handoff`; +在丢弃 reqwest 错误前保留分类后,同样 fixture 通过。transport 使用真实 100 ms 超时; +executor/export 使用 250 ms、FakeGate、真实 reqwest transport 与生产 JSONL sink。 +这些验证本地 HTTP 与执行器行为,不证明 Gateway 子进程的短超时配置、真实 Core 或真实供应商能力。 +不保留或导出原始 reqwest 错误;未修改公共枚举值、schema 字段、超时配置或重试行为。 + The combined implementation preserves startup-confirmed input intersection, rendered-body limits (including refreshed context), the response-buffer ceiling and separate fallback capacity from #2513. Capacity and evidence process tests run against the same compiled production binary. The compatibility-ceiling test sends oversized