Skip to content

Traffic between the gateway and upstreams, live request content, security log detail - #311

Merged
fylorn merged 6 commits into
mainfrom
feat/traffic-live
Oct 10, 2026
Merged

fylorn merged 6 commits into
mainfrom
feat/traffic-live

Conversation

@fylorn

@fylorn fylorn commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Integration of three tracks built against shared contracts, on top of main (which already has #310).

Traffic (protocol 44, store schema 27). Each request records sent_bytes / received_bytes — request and response bodies to and from upstreams as they crossed the network (after the gateway's own compression such as zstd for the Codex backend, before any decoding; reqwest has no decompression features and the gateway sends no Accept-Encoding), summed over failover attempts — and egress, the proxy the serving attempt used (None = direct). A new crate::traffic counter is shared by every reader of an upstream body so nothing is counted twice; WebSocket rows count frame payloads.

  • API: HistoryRow (bytes → sent_bytes, received_bytes, egress), events (RequestFinished, RequestFailed, RequestCancelled, RequestRouted, in-flight egress), AttemptView.proxy, ReplayOriginal.received_bytes; Summary, CostBucket (+ token counts and per-bucket ttft_p50_ms / ttft_p95_ms / ttft_samples), CostBucketGroup gain byte totals; CostDim::Egress; new GET /latency/client.

Live request content. GET /request/{id}/live (Events): replays and then streams head / body / end for the client side (attempt 0) and each upstream attempt; 404 control.request_not_running once ended. Redaction is the same Redaction::apply used for what goes to disk; credential headers are masked like key_masked. Subscribers pull, so a slow one never blocks forwarding; nothing extra is buffered when nobody listens. Finished requests store heads and, only when they differ from the client side, upstream_request_body / upstream_response_body (new blob kinds next to .req / .res, same retention and quota). RequestDetail.response_body now means what the client received.

Security log detail. Every security event records where each hit is and what was done, in the request log's own SQLite rows so it expires with the request: direction, locations (part, message index, role, tool, JSON path in the client's own format, up to 80 chars of masked context either side, at most 50 per event plus more_locations), rule_snapshot (the rule as it was when it matched: built-in id and name with the evaluating core version, or a custom rule's pattern and matching), and outcome_detail (recorded, replaced with the placeholders sent, cut with the tool, its masked arguments and the sentence the client got, blocked with the refusal, stripped with the number of segments). Context and matches go through the same redaction as stored bodies; no raw secret is stored. SecurityEventView also carries session and sent_model; live SecretsFound items, ContentMatched and ToolCallFlagged carry the same detail. Guard setting changes are not written to the log.

Also: an adaptation of the #310 tests to the traffic counters, and the traffic counter without fetch_update (deprecated on newer toolchains).

Checks on this tree: cargo fmt --all --check, cargo clippy --workspace --all-targets -D warnings, cargo test --workspace --no-fail-fast — 3240 passed, 0 failed.

The version bump and release notes follow in a separate PR.

🤖 Generated with Claude Code

fylorn and others added 6 commits October 10, 2026 11:12
…atency

A request's `bytes` counted the decoded answer the gateway read, which says
nothing about what went over a proxy or a metered link. Replace it with the
traffic between the gateway and its upstreams, the only leg that leaves the
machine:

- `sent_bytes`: request bodies sent upstream, summed over every attempt
  (failover hops included), as on the wire, i.e. after the zstd the Codex
  backend gets. A hop that never connected is taken back: nothing left.
- `received_bytes`: response bodies received from upstreams over every
  attempt, before content decoding. The HTTP client is built without any
  decompression feature, so what is read is what arrived; each upstream
  response body is wrapped once, right where it is received, so every
  reader (error peek, held opening, relay to the client) adds to the same
  count and replayed chunks are not counted twice. A test pins the
  no-decompression assumption.
- WebSocket rows count data-frame payloads both ways (upstream text before
  placeholders are restored, client frames after redaction); control
  frames do not count.
- Failed/cancelled requests that never reached an upstream have no traffic
  (None) rather than a pair of zeros; so do local answers.
- `egress`: the proxy the serving attempt went through (None = direct; if
  no attempt served, the last one that reached an upstream). Every attempt
  in the routing chain carries its `proxy`.

Aggregates follow: `Summary` and `CostBucketGroup` gain the two byte sums,
`CostBucket` also gains the four token kinds and first-token p50/p95/samples
(same samples as `/latency`), `CostDim::Egress` groups by exit with "" for
direct, and `GET /latency/client` gives first-token percentiles per key.
`ReplayOriginal.bytes` becomes `received_bytes`.

The request store schema goes to 27 (old store is rebuilt) and
CONTROL_API_VERSION to 44.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The tests added with the Codex endings fix read the old `bytes` field and
called `stream_body()` without its new argument; the traffic branch
renamed the field to `received_bytes` and counts what arrives through
the traffic counter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…am-side bodies

While a request is in flight the control plane now streams what goes over the
wire: `GET /request/{id}/live` replays everything held so far and then follows
live, as SSE messages `head` / `body` / `end` for the client side (attempt 0)
and each upstream attempt (its 1-based position in the attempt chain). A request
that is not running is a 404 with `control.request_not_running`.

- New `tw_gateway::content`: a per-request capture that follows the request
  (ending, client response body, each hop hold a handle; the last one dropped
  ends it). It is the single buffer for what storage already keeps: the serving
  attempt's upstream answer (moved off `Ending`'s own tap), the client request,
  the client answer only when it differs from the upstream's (format conversion,
  reply plugins), the sent request only when it is reshaped. Nothing more is held
  when nobody watches.
- Watchers pull: the gateway only appends and bumps a version, so a slow watcher
  never holds the request up; each watcher keeps a cursor, no copy. Body text is
  redacted with the very function used before writing to disk, segment by segment
  on SSE event boundaries; heads are redacted when recorded (credentials masked the
  way `key_masked` is) and stored as is.
- Stored at the end: `{id}.heads`, `{id}.up-req`, `{id}.client-res` (no SQLite
  change). `RequestDetail` gains `heads`, `upstream_request_body` and
  `upstream_response_body`; `response_body` is what the client received.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`fetch_update` is renamed to `try_update` in newer standard libraries and
CI builds with -D warnings, while older ones have no `try_update`. Take
the bytes back with a compare-exchange loop instead, as tw-watch does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…as it was, and what was done

Every security record now carries, decided at detection time and stored on the
same `security_events` row (so it expires with the request log):

- direction (request / response) and every location of the hit, capped at 50
  with `more_locations`: part (system / message / tool_result / tool_call),
  message index, role, tool, JSON path into the body the client sent (or the
  answer it received, for tool calls), and up to 80 characters of context on
  each side plus the matched text;
- a rule snapshot: built-in id and name with the core version, or the custom
  pattern exactly as written, and the content filter's matching mode;
- an outcome detail: the placeholders a value was replaced with, the cut tool
  call (masked arguments, at most 4 KiB, with a truncated flag) and the notice
  the client got instead, the refusal the client received, or how many
  segments were stripped;
- the request's session and the model actually sent to the serving upstream.

Contexts never carry a raw value: they are cut from the original text after
going through the request's `Redaction` (the same rules, ledger and shape
masking as stored bodies), window edges never split a hit or a token, and a
content or tool-call match whose edge falls inside a secret takes the whole
secret in, masked.

tw-guard gains a `locate` module (parts, paths, a raw JSON walker, literal
offset mapping), `content::places`/`places_text`/`Rule::draw`, location fields
on `tools::wall::Verdict`, `tools::rules::Rule::find_all`,
`RuleSet::custom_pattern` and `Ledger::placeholder_of`. Protocol 44 and store
SCHEMA 27 are extended in place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@fylorn fylorn changed the title Traffic between the gateway and upstreams, live request content, per-bucket first-token latency Traffic between the gateway and upstreams, live request content, security log detail Oct 10, 2026
@fylorn
fylorn merged commit c8db288 into main Oct 10, 2026
5 checks passed
@fylorn
fylorn deleted the feat/traffic-live branch October 10, 2026 05:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant