Skip to content

feat(gateway): export bounded body-free call evidence - #2506

Merged
hidb4ai merged 16 commits into
oceanbase:masterfrom
beatenevo:gateway-bound-evidence
Nov 7, 2026
Merged

hidb4ai merged 16 commits into
oceanbase:masterfrom
beatenevo:gateway-bound-evidence

Conversation

@beatenevo

@beatenevo beatenevo commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

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?

  • Export JSONL through a dedicated writer with 1024 queued records, drop-newest overflow and loss/write-failure counters. Slow/failing writers do not change business decisions.
  • Correlate call terminals, actual attempts and delivery observations. Preserve possible billing exposure, reported usage and unknown values through errors and release refusals.
  • Normalize OpenAI Chat/Responses input/output/cache usage without adding cache reads to input or inferring cache writes. Keep model TTFT unknown.
  • Separate release authorization, framework handoff, first body frame and first recognized model-content frame. Control-only SSE and bodies dropped before content do not invent content observations; outgoing bytes are preserved.
  • Share lifecycle terminal/send fact types with G3 and use one ManagedOutcome-to-terminal mapping. Add common operation/unit/outcome/duration fields, preserving domain facts and unavailable classifications.
  • Remove configured Core URLs, UDS paths and invalid injection values from startup diagnostics. Document timing, coverage, retention and migration behavior in English and Chinese.

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_ms and the first_model_content boundary. 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.detail uses gate_unavailable or malformed_gate_response for the corresponding Core errors. Rust consumers adopt explicit first-byte/completion timing and must not retry IncompleteResponse. 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-test

Validation 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.md for 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.

@AlexStocks AlexStocks added the 1.5.1 v1.5.1 release tracking label Nov 6, 2026

@hidb4ai hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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") {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_usage now normalizes: content_type.split(';').next().unwrap_or("").trim() then eq_ignore_ascii_case("text/event-stream"). Exact media-type equality, so a prefix such as text/event-stream-x no longer aliases into the SSE parser.
  • gateway/crates/pc-gateway-app/src/ingress.rs::respond applies the same rule before choosing the first-content offset, so Text/Event-Stream; charset=utf-8 also gets a first_model_content observation, which the old starts_with check silently skipped.
  • Regression coverage: sse_usage_matches_case_insensitive_media_types_without_prefix_aliases in gateway/crates/pc-gateway-transport/tests/usage_timing.rs drives both text/event-stream and Text/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:") {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.rs
  • gateway/crates/pc-gateway-core/src/executor.rs
  • gateway/crates/pc-gateway-core/tests/executor_semantics.rs
  • gateway/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 hireview001 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • 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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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/flush fails, nothing is ever written, so write_failed is never exported;
  • sustained overflow: all submissions are dropped, so no record carries the dropped value.

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 knqiufan left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(_)) => {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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 knqiufan left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@hidb4ai hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@hidb4ai
hidb4ai merged commit 7461789 into oceanbase:master Nov 7, 2026
39 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

1.5.1 v1.5.1 release tracking

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants