Repository navigation
feat(gateway): export bounded body-free call evidence - #2506
Conversation
hidb4ai
left a comment
There was a problem hiding this comment.
Reviewed df8738e920c2d910c076832cf4d23b64d0f727d8. Two reproducible SSE evidence-loss cases are detailed inline. No approval submitted.
| .ok() | ||
| .and_then(|v| v.get("usage").cloned()) | ||
| fn extract_usage(body: &[u8], content_type: &str) -> Option<serde_json::Value> { | ||
| if !content_type.starts_with("text/event-stream") { |
There was a problem hiding this comment.
[P2] Match the SSE media type case-insensitively
This case-sensitive prefix check sends a valid Content-Type: Text/Event-Stream; charset=utf-8 response through the JSON parser, so all reported usage disappears. With the real Gateway binary and a local HTTP fixture, the same SSE body reports input/output/cache-read counts of 80/7/20 with lowercase text/event-stream, but all three become unknown with the mixed-case header; the body is still delivered unchanged and first_model_content is recorded. HTTP media types are case-insensitive. Normalize and compare the media type, as respond() already does, and cover both header spellings through the transport.
There was a problem hiding this comment.
Confirmed fixed at a1707cde, and the fix is in both places that consume the header, not only the usage path.
gateway/crates/pc-gateway-transport/src/reqwest_transport.rs::extract_usagenow normalizes:content_type.split(';').next().unwrap_or("").trim()theneq_ignore_ascii_case("text/event-stream"). Exact media-type equality, so a prefix such astext/event-stream-xno longer aliases into the SSE parser.gateway/crates/pc-gateway-app/src/ingress.rs::respondapplies the same rule before choosing the first-content offset, soText/Event-Stream; charset=utf-8also gets afirst_model_contentobservation, which the oldstarts_withcheck silently skipped.- Regression coverage:
sse_usage_matches_case_insensitive_media_types_without_prefix_aliasesingateway/crates/pc-gateway-transport/tests/usage_timing.rsdrives bothtext/event-streamandText/Event-Stream; charset=utf-8.
Verification on this head: gateway-validation / check is green (job 128313440433, cargo test --workspace on ubuntu). Locally on Windows cargo test -p pc-gateway-protocol -p pc-gateway-evidence is 30 passed / 0 failed.
| data.clear(); | ||
| segments.clear(); | ||
| event = None; | ||
| } else if let Some(value) = line.strip_prefix("data:") { |
There was a problem hiding this comment.
[P2] Handle a leading SSE BOM without losing the first event
A valid SSE stream may start with one UTF-8 BOM. Prefixing the first data: line with EF BB BF makes this check discard that line. In a spawned-Gateway probe with one nonempty Chat content delta followed by finish/usage/[DONE] events, the response bytes are delivered unchanged but first_model_content is absent; without the BOM it is present. A later content delta would instead move the observation to the wrong frame. The same prefix handling in extract_usage() loses usage when it is in the first event. Ignore the single leading BOM while preserving offsets into the original outgoing bytes, and cover these cases in the transport/body-boundary tests.
There was a problem hiding this comment.
Confirmed fixed at a1707cde.
sse_offset now strips exactly one leading U+FEFF and rebases every returned offset back into 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();so the first data: line after the BOM is dispatched and the emitted offset still points at the first encoded content byte of the untouched body, not at the stripped slice.
The regression test sse_ignores_only_one_leading_bom_and_returns_original_wire_offset (in gateway/crates/pc-gateway-protocol/tests/content_boundary.rs) covers Chat, Responses, CRLF framing with multi-line data:, keeps a BOM that appears inside content, and confirms a second BOM or a BOM after a comment line is not stripped. Locally cargo test -p pc-gateway-protocol is 30 passed / 0 failed on this head; gateway-validation / check is green on ubuntu.
hidb4ai
left a comment
There was a problem hiding this comment.
Re-reviewed 778e5e02cb3310671a796f6685b7a1f2df10c12f. Both previous SSE findings are fixed: independent spawned-Gateway probes retain 80/7/20 usage with mixed-case media types and observe the first content with a leading BOM, without changing response bytes. No new runtime defect found in the fix.
Current-master integration remains blocked. Against master at e356ba2f1955f7bf2bb2dff95590c07706114729, GitHub reports CONFLICTING / DIRTY, and git merge-tree --write-tree independently reproduces conflicts in:
gateway/crates/pc-gateway-app/src/main.rsgateway/crates/pc-gateway-core/src/executor.rsgateway/crates/pc-gateway-core/tests/executor_semantics.rsgateway/crates/pc-gateway-transport/src/reqwest_transport.rs
Please reconcile the evidence changes with the capacity-limit changes merged in #2513 and rerun the Gateway workspace and process tests on the reconciled head. The current green checks validate this branch, not the combined implementation.
hireview001
left a comment
There was a problem hiding this comment.
- Resolve merge conflicts with the target branch.
| 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); |
There was a problem hiding this comment.
[P2] Drop and write-failure counters are unreachable exactly when the stream is lost
submit() increments dropped here, and the worker increments write_failed on a failed serialize/write, but neither path leaves any out-of-band signal: JsonEvidenceSink::stats() has no production caller (main.rs constructs the sink at lines 116-140 and never reads it), and the worker thread emits no log.
The only place these counters surface is the loss field embedded in each record that is successfully written. That covers "some records survived", but not the two states an operator actually needs to tell apart from silence:
- the writer fails from the first record (stdout closed, full pipe, broken collector): every
write_all/flushfails, nothing is ever written, sowrite_failedis never exported; - sustained overflow: all submissions are dropped, so no record carries the
droppedvalue.
In both cases stdout is empty or truncated and indistinguishable from "the gateway received no traffic". The documented limitation ("process exit can lose queued records", docs/en/docs/operate/gateway-evidence.md) does not cover this, because there is no recovery record to report earlier losses.
Suggested: log the first write failure once (tracing::error! without the error value, as the sink already avoids stringifying writer errors) and emit a bounded periodic or exit-time stats() summary on stderr. That keeps the JSONL body-free and makes total loss observable.
knqiufan
left a comment
There was a problem hiding this comment.
The earlier SSE and loss-counter findings are addressed. The new incomplete-response evidence still misclassifies body-read timeouts; please address the inline finding.
| loop { | ||
| match next_chunk(&mut stream).await { | ||
| None => break, | ||
| Some(Err(_)) => { |
There was a problem hiding this comment.
[P2] Preserve timeout classification after response headers
A response-body read timeout is discarded by next_chunk and recorded here as LostAfterHandoff. With the real transport against a local service that sends headers and a partial body then stalls, a 100 ms timeout produces this lost-connection classification. The new call evidence therefore attributes a timeout to the wrong failure category. Preserve the timeout reason while keeping the existing no-retry behavior.
knqiufan
left a comment
There was a problem hiding this comment.
Re-reviewed the current head. The earlier SSE, evidence-loss diagnostics, and body-read timeout findings are addressed; I found no remaining blocking code issue. The Gateway workspace tests passed locally with loopback fixtures. The live Core cases returned early because no Core server was reachable; hosted providers and external telemetry storage were not exercised.
Which issue or RFC does this PR close?
Refs #2463 and planning discussion #2433. This is the G4 evidence delivery built on the merged G3-0 (#2499).
Rationale for this change
Production Gateway retained attempts and diagnostics in unbounded demo buffers, while extracted usage never reached a final call record. Export bounded, readable, body-free evidence with explicit transport, release and framework observation boundaries.
What changes are included in this PR?
Are there any user-facing changes?
Evidence JSONL uses stdout; operational tracing uses stderr. Configure collector retention separately, or explicitly disable evidence with
PC_GATEWAY_EVIDENCE=off. Startup diagnostics identify connection mode without exposing configured URLs or paths.JSONL adds
outcome,duration_msand thefirst_model_contentboundary. Consumers must accept null classification and variable record counts. The common fields align with #2388 vocabulary; the existing managed Server OTLP pipeline does not ingest Gateway stdout or preserve nested evidence/loss by default.Gateway HTTP 503
gate_paused.detailusesgate_unavailableormalformed_gate_responsefor the corresponding Core errors. Rust consumers adopt explicit first-byte/completion timing and must not retryIncompleteResponse. Existing lifecycle/evidence enum import names remain available through re-exports. No OpenAPI contract or database migration is required; the lockfile adds only an internal workspace dependency.How was this change tested?
On macOS arm64 with Rust 1.95.0:
cargo fmt --manifest-path gateway/Cargo.toml --all --check cargo clippy --locked --manifest-path gateway/Cargo.toml --all-targets -- -D warnings cargo test --locked --manifest-path gateway/Cargo.toml --workspace make check uv run prek run -a make docs-testValidation includes 160 exercised behavior tests; four additional live-Core cases return early because Core is unavailable. A spawned Gateway serves 1000 enabled requests with 6000 readable records, plus 100 requests with evidence disabled. Process tests cover synthetic Core URL credentials/paths, UDS/steering paths and invalid configuration text. Other tests cover real HTTP usage/timing fixtures, arbitrary body-frame splits, operational output mapping, lifecycle/evidence consistency, a 100000-submission overflow burst and blocking/failing writers.
See
gateway/EVIDENCE_VALIDATION.mdfor source commit, commands and evidence limits. Real Core, hosted providers, external telemetry storage and native agent hosts were not exercised. G3-0 cancellation/deadline handles do not automatically stop execution; actual total-deadline, disconnect/cancellation and drain owners remain with #2462. Framework polling does not prove socket writing or client receipt.AI usage statement
OpenAI Codex assisted implementation, tests and documentation.