Skip to content

feat(link): measure the bytes each Remote Link carries and record request body size on log rows - #8584

Merged
lidge-jun merged 17 commits into
devfrom
feat/link-traffic-counters
Nov 12, 2026
Merged

lidge-jun merged 17 commits into
devfrom
feat/link-traffic-counters

Conversation

@lidge-jun

@lidge-jun lidge-jun commented Nov 12, 2026 •

Copy link
Copy Markdown
Owner

Summary

Nothing reports how many bytes a Remote Link carries, and the request log does not say how large a request body was or whether it was compressed. Bytes each way per link and body size per request are the numbers needed to decide whether to compress request bodies Child to Home (goat-si/goat#3023). This PR adds those numbers and changes no existing behaviour.

Per-link traffic (GET /api/link/status?traffic=1)

Each link row gains a traffic block:

  • requests and incomplete (requests that ended before their response body did, or on a Child before their request-body upload finished);
  • toHomeBytes, fromHomeBytes, toHomeSource (relayed on a Child, content-length on a Home) and toHomeUncounted;
  • since, epoch and generation, which say when and in which counting window the numbers started;
  • untrackedRequests, a book-level count repeated on every row.

The block appears only with the query. Older ocx link status validates rows key by key, so the plain document stays byte for byte the same; a test asserts its literal bytes. ocx link status now sends traffic=1 and validates the block exactly; it accepts a runtime that does not send it.

How the counters are kept (src/link/traffic.ts):

  • Counting is in memory: one integer addition per body chunk, with no lock, log line, timer or disk write, and no request scans the book.
  • A book holds at most 256 links and never more. A new link takes the place of the link idle longest, found in O(1). When every tracked link has a request in flight there is no place: that request is not measured and counts only in untrackedRequests. Telemetry never refuses or slows a request.
  • Every time a link's counters start from zero (its first request, or its first after the book forgot it), it takes a new generation from one monotonic counter per book. Each book also has a random epoch, new after every restart. A consumer subtracts two readings only when both epoch and generation match. since is wall-clock time for people; it can repeat or go backward with the clock, so it is never the comparison key.

Where the bytes are counted:

  • Child: the connection-bound transport (fetchBoundLinkRelay) counts, so relayed requests and the Child's own reads of the Home count alike.
    • A request counts from the moment its data request starts on the authenticated socket. A refused challenge or connection counts nothing.
    • A request body (each streamed chunk, or a buffered body) counts once its socket write completed.
    • Response chunks count as they are read off the socket, before any adapter queue or decoding.
    • A request ends only after both its response and its upload settled, and is complete only when both finished.
  • Home: the hub-link listener counts response bytes as it streams them. On the request side it records each request's declared Content-Length, because wrapping Bun's native request would lose the identity requestIP and timeout need. Requests without a Content-Length go to toHomeUncounted. Only verified relay sessions count.
  • Neither side counts headers, relay-auth challenges, SSH or TCP framing, or anything a relay between the machines adds.

What a consumer can conclude: on a Child, while incomplete is 0 every request body was counted in full. When incomplete > 0, toHomeBytes is a lower bound: a write still pending when a request ended is not counted, even if part of it reached the Home. Response bytes are counted as they arrive and need no such caveat. On a Home, toHomeBytes is what callers declared, so a verified peer can misstate it.

On a connected Child:

  • Status is served by the machine listener to its dashboard session only. With ?traffic=1 it adds the Child's own link as a row.
  • An unreadable sidecar, a sidecar for another link, or a lost sidecar under the Child-initiated marker makes that row failed with alias unknown.
  • A Home-initiated row shows the Home's recorded name, or unknown, never the loopback URL.
  • ocx link status on a Child reads only local files, so it cannot show these counters.

Request body on log rows

  • Request-log and usage.jsonl rows gain requestBody: {wireBytes, encoding, decodedBytes}, where encoding is identity, zstd, gzip or deflate.
  • The shared JSON body reader records it once a body was read and decoded in full. The admitted-turn wrapper binds it to the turn's log row, so every admitted JSON data route carries it, and /api/logs and ocx logs --json show it.
  • Readers rebuild rows from the fields they know, so an older reader drops the key and keeps the row. The test shows this tolerance with today's reader and a future field; it does not execute an older build's reader.
  • src/server/request-log.ts sits at the line cap, so its edits are folded into existing lines and the logic lives in src/server/request-body-facts.ts and src/usage/request-body.ts.

Consumers. GOAT's LinkStatus decoder (effect 4.0.5 Schema.Struct) ignores extra fields. This was checked by running its exact schema on a document with the new row fields.

Taking the measurement. On a Home, for each link take its apiKeyId from links.json, then sum requestBody.wireBytes and usage.inputTokens over that key's rows in ocx logs --json. Numerator and denominator come from the same rows. traffic deltas between two readings with the same epoch and generation, on the Home or on the Child's dashboard read, cross-check it.

Left out

The kind of SSH route a link uses (relay, jump host or direct) is not reported. Knowing it needs either running ssh (ssh -G evaluates Match exec, so a status read would start processes) or matching OpenSSH's config reader exactly (tokens, environment variables, Include and Match semantics), and neither belongs in a status read. An earlier revision tried both and each drew real review findings. A consumer can tell a relayed link from the alias it already has.

Verification

Tests that failed first, against the code before each fix:

  • tests/clients/link-traffic.test.ts: real hub-link sessions and the real bound transport. Covers:
    • a streamed request and SSE response, and an aborted response;
    • a body without Content-Length;
    • a refused request, and a refused challenge and connection;
    • a gzip response counted at wire length;
    • a Child's own Home read;
    • a Home request aborted before its headers;
    • identity bytes read before a cancel;
    • eviction with a request in flight, and more links in flight than the bound (the book stays at 256 and the rest count as untracked);
    • a new generation under a clock that repeats and one that moves backward, and two books under one repeating clock never sharing epoch and generation;
    • a 48 MiB buffered body the Home never reads counting 0 bytes;
    • a Home that reads a 1 MiB prefix before the request is cancelled, and one that reads a prefix and then answers in full: both are incomplete with toHomeBytes below what crossed (the code before the fix reported the second as complete);
    • an ordinary request whose upload and response both finish stays complete.
  • tests/clients/link-traffic-child-status.test.ts: the Child's machine listener, including valid, unreadable, mismatched and lost sidecars, and a Home-initiated row that never shows the loopback URL.
  • tests/server/link-traffic-status.test.ts: the plain document's literal bytes, the opt-in block, and CLI validation (including epoch, and refusing any path block).
  • tests/usage/request-body-log.test.ts: identity, zstd and gzip bodies through the real data plane on Responses, Chat Completions and Messages; persistence and hydration; a reader dropping unknown fields. On the base, rows carried no requestBody.

Commands at this head, with exit codes:

  • bun run typecheck: exit 0 (0.85 s; peak 1-minute load 0.41)
  • bun run privacy:scan: exit 0
  • bun run structure:check: exit 0
  • bun run lint:gui:if-changed: exit 0 (no GUI changes)
  • bun scripts/test.ts --parallel=2 over the gate tests (file-size ratchet, structure-ssot, repo-hygiene, skill-ocx, test-layout, test-layout-tooling, core-lab-boundary): exit 0, 145 pass
  • bun scripts/test.ts --parallel=2 over 20 link, relay, listener, CLI, control-socket and request-log test files: exit 0, 291 pass, 1 skip
  • bun scripts/test.ts --parallel=2 over 10 status-projection, link-route, Child status, machine-listener, listener-lifecycle, link-diagnostics, core-link-boundary, request-log, decompress and log-metrics test files: exit 0, 245 pass

The control-socket tests need a short temporary directory (a Unix socket path has a length limit), so these runs set TMPDIR to a short path.

CI on an earlier head (e83d9a3) passed all 32 checks; one test in an untouched file (codex-cli-update-apply) failed once and passed on re-run.

NOT RUN:

  • the full suite at this head (repo-wide runs are not allowed on the VM this was built on; CI runs it);
  • macOS and Windows lanes;
  • the Rust ocx-child conformance tests.

Checklist

  • Scope stays focused and avoids unrelated cleanup.
  • Docs or release notes were updated when needed: structure/remote-link.md, structure/usage-client-attribution.md, docs-site/.../guides/remote-link.md.
  • Security-sensitive changes were reviewed for secrets, auth, and unsafe defaults:
    • Initial review: an independent review ran four rounds before the first push.
    • Final reviews: two fresh final reviews returned nine P2s and two P3s between them. All were accepted and fixed test-first, the second set partly by removing the SSH path kind.
    • Fix review: five further rounds on those fixes ended with no P0–P2 left.
    • Defaults: nothing new is on by default; every new field is additive or behind ?traffic=1.

Coordinator re-run on the hub (macOS, bun 1.4.4), head 31c2159

  • bun run typecheck, bun run privacy:scan, bun run structure:check: exit 0 each
  • bun scripts/test.ts --parallel=4 over the seven test files this PR touches plus tests/providers/claude-cli-client-http.test.ts: exit 0, 88 pass, 0 fail
  • git merge-tree origin/dev (a159cdd): merges cleanly

NOT RUN on the hub: the full suite (left to CI), Windows and Linux lanes, Rust ocx-child conformance.

Built by claude-opus-5-5 through Codex in GOAT on a cloud VM; received as a git bundle and pushed by the coordinator.

…its SSH path

ocx link status --json now asks for ?traffic=1 and shows, per link, the
request and response body bytes since this process started counting, how
many requests ended early, and whether the link's SSH alias goes through a
ProxyCommand, a ProxyJump host or directly. Without the query the status
document is unchanged, so older CLIs keep validating it.

A Child counts in its relay, exactly. A Home counts response bytes exactly
in its hub-link listener and request bytes by declared Content-Length,
because it must keep Bun's native request. Refs goat-si/goat#3023.
Request-log and usage.jsonl rows gain requestBody {wireBytes, encoding,
decodedBytes}, filled by the shared JSON body reader for every admitted
data route, so ocx logs --json shows what a client actually sent. Older
readers rebuild rows from known fields and drop it. Refs goat-si/goat#3023.
…solution

Review round 1 for the traffic counters:
- count in fetchBoundLinkRelay from the data-request boundary, so a refused
  challenge or connection counts nothing, response bytes are counted before
  decoding, and the Child's own hub-state, usage and management reads count;
- a connected Child's machine listener answers ?traffic=1 with its own link
  row, counters and SSH path;
- a Home request aborted before its headers stays incomplete;
- at most four ssh -G run at once and at most 32 aliases wait.
… mark a bad sidecar row failed

Review round 2: response bytes are counted by a pass-through on the socket's
stream, so bytes read before a cancel count, and the Child's traffic row reads
failed with an unknown alias when its sidecar is unreadable or names another
link, instead of passing as an idle Home-initiated link.
…failed row

Review round 3: when the sidecar is missing but the durable marker names this
link (or cannot be read), the Child's traffic row is failed with reason
sidecar_missing and an unknown alias, instead of a Home-initiated idle link.
@coderabbitai

coderabbitai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Caution

Review failed

The pull request is closed.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@github-actions

github-actions Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

✅ Deterministic PR hygiene checks passed.

@github-actions github-actions Bot added the enhancement New feature or request label Nov 12, 2026
Final review: a status read ran ssh -G, which evaluates Match exec, could
leave processes behind and could slow ocx link status. The path kind is now
read from the user's and the system ssh_config with OpenSSH's first-value-wins
rule, Host patterns and Includes; anything only ssh could settle reads
unknown. A status read starts no process.
…link its own since

Final review: evicting the oldest entry could drop a link whose request was
still counting while its since claimed continuity. Eviction now skips links
with requests in flight, a link counted after an eviction reports since its
entry began, and an absent link reads zero since the last eviction.
Final review: a string or byte body was counted before its write completed,
unlike streamed chunks.
…d trim the traffic book

Review round 5:
- ProxyJump none blocks only a later ProxyJump, so a later ProxyCommand
  still decides, as ssh -G shows;
- a config file over the limit is refused by its size without being read,
  an Include glob stops listing past the file budget, and one status read
  reads each file once and at most 1 MiB in all;
- as requests end, the traffic book trims its oldest idle links back to the
  bound after a burst of links in flight took it past.
…ig without blocking

Review round 6: a Host pattern full of wildcards could stall the event loop
in a backtracking regex, an Include glob could walk a large tree, and a named
pipe in place of a config file blocked the open. Patterns now match in
linear-by-length time, an Include wildcard lists only one directory and at
most 1,024 entries, and only regular files are opened, without blocking.
Two independent reviews found real defects in each way of resolving it:
running ssh -G (Match exec can run commands, stall and leave processes) and
re-reading ssh_config (it must match OpenSSH's reader exactly, including
token expansion, or it reports a wrong kind). The measurement this change
exists for, bytes per link and body size per request, does not need it, and
the link's alias already names a relay route. Removes src/link/ssh-route.ts,
the path block, its CLI validation, tests and documentation.
… and state the lower bound

Second final review:
- the book never holds more than 256 links; a new link takes the place of
  the link idle longest (O(1), no scan), and a request with no place is not
  measured but counted in the book-level untrackedRequests;
- every reset of a link's counters takes a new generation from one monotonic
  counter, so a consumer can tell a reset even when the clock repeats or goes
  backward; since stays for people;
- a pending write is not counted, so toHomeBytes on a Child is a lower bound
  while incomplete > 0; the word exact is gone where it was not true;
- the plain status document is asserted byte for byte.
…ad as incomplete

Generations restarted at 1 in every process, so two reads across a restart could compare equal. Each book now reports a random epoch beside generation, and consumers compare reads only when both match. A Child request now ends only once its response and its upload both settled, so a Home that answered in full before reading the whole body leaves the request incomplete, which is the signal that toHomeBytes is a lower bound.
@lidge-jun
lidge-jun marked this pull request as ready for review November 12, 2026 19:59
@lidge-jun
lidge-jun requested a review from Ingwannu as a code owner November 12, 2026 19:59
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T20:02:29.050832Z 31c2159 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@lidge-jun
lidge-jun merged commit 05d34b9 into dev Nov 12, 2026
61 of 67 checks passed
@lidge-jun
lidge-jun deleted the feat/link-traffic-counters branch November 12, 2026 20:02
lidge-jun added a commit that referenced this pull request Nov 12, 2026
…zstd

The branch already held #8584's commits, so the tree is the branch merged with dev 9fec48a; the diff against dev is the zstd change alone.
lidge-jun added a commit that referenced this pull request Nov 12, 2026
…et-home

Conflicts resolved by keeping both features:
- link status rows carry both ws (?transport=1) and traffic (?traffic=1); ocx link status asks for
  both and validates both blocks;
- the hub-link listener owns both the traffic book and the activity holds, and the relay session
  begins a traffic flow and the body observation on the same verified request (an abort or a throw
  before headers ends both);
- the optional-listener facade and the management route state forward linkTraffic beside the
  WebSocket hooks; request-log rows carry requestBody beside link;
- the structure page keeps the traffic section, then the Responses WebSocket section.

The traffic book does not count the link WebSocket: a verified upgrade goes to the WebSocket gate
before a traffic flow begins, so the #8584 numbers cover relayed HTTP only and are unchanged. The
structure page says so, and a real-Home test checks that a WebSocket turn leaves the traffic at zero
while a relayed HTTP request on the same link is counted. Three tests that assert the status query
string now expect transport=1&traffic=1.
lidge-jun added a commit that referenced this pull request Nov 12, 2026
Dev's request-body facts (#8584) added a line to src/server/request-log.ts,
taking the union to 2000 lines. Fold this branch's untypedSse parameter onto
its parameter line to keep the file at 1999.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants