Skip to content

perf(proxy): do not tokenize a bypassed request on the request path - #542

Merged
amiddavid merged 5 commits into
mainfrom
perf/bypass-no-request-path-tokenizing
Oct 15, 2026
Merged

amiddavid merged 5 commits into
mainfrom
perf/bypass-no-request-path-tokenizing

Conversation

@OsherElhadad

@OsherElhadad OsherElhadad commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator

What

A bypassed request (the agent's own compaction request, or one sent with x-context-guru-bypass) is forwarded untouched, but components.Pipeline.Run and apply.attemptedTokens still tokenized the whole transcript before forwarding it: about 0.35 s per MiB, so a 33 MiB compaction request spent about 12 s in the proxy before the upstream saw it.

  • Pipeline.Run and attemptedTokens skip the count for a bypassed request.
  • The count moves off the request path and off the dashboard writer: the row is inserted at once, then one separate count worker (queue of 8; it never blocks, and a full queue leaves the row uncounted, which the accounting reads as unknown) fills tokens_before/tokens_after, attempted_tokens and frozen_tokens with the same figures main stored for the same body, and flips accounting from missing to partial exactly as before. The row still reads mode bypass / reason bypassed. Until the count lands (or if it is dropped) those columns read 0. With the dashboard off nothing counts, and the request log line shows tokens_before=0 for a bypassed request.
  • cg_ms on the cg.request line (nothing parses it; the scripts read the dashboard's cg_latency_ms) was the sum of the components' own durations, which leaves out normalization and counting (it read 0.4 ms on a request that took 600 ms to reach the upstream). It is now the whole pre-forward time (the figure the dashboard's cg_latency_ms already carried); the component sum is components_ms.
  • tokens.Stats() exposes the count memo's hit, miss and encoded-bytes counters.

Not changed

The normal (non-bypassed) path still counts on the request path. That is a separate decision.

Evidence (local, no -race, one request per process)

Time from sending a bypassed 33 MiB compaction request to the upstream receiving it: about 12 s before, about 2 s after. The remaining time is body normalization and thread matching (JSON), not tokenizing; it is not addressed here.

Tests

  • TestBypassedRequestIsNotTokenizedOnTheRequestPath: a 33 MiB compaction request encodes about 0 bytes on the request path (34.6 MB when the skip is removed).
  • TestBypassedRowGetsItsTokenCountFromTheWorker: the row ends with the figures origin/main stored for the same body (hard-coded), mode bypass, reason bypassed.
  • TestBypassCountDoesNotBlockTheWriter (other rows keep being saved while a count is blocked), TestBypassCountFlipsMissingToPartialOnly, TestBypassCountQueueFullDropsTheCount.
  • TestLifecycleLoggerCGMsIsThePreForwardTime.
    go test ./apply ./components/... ./dash ./proxy ./internal/tokens passes.

ponytail: one worker, so rows of big bypassed requests lag by the queue's total counting time; a pool is the upgrade if that shows. The ~2 s that remains for a bypassed 33 MiB request is body normalization and JSON, not tokenizing.

…log cg_ms as the pre-forward time

A bypassed request (an agent compaction, or x-context-guru-bypass) is forwarded untouched, but Pipeline.Run and apply.attemptedTokens still tokenized the whole transcript first, about 0.35 s per MiB on the request path. Both now skip a bypassed request, and the dashboard writer fills tokens_before/after for the row off the request path (Event.BypassTokens). The cg.request line's cg_ms was the sum of the components' own durations, which excludes the counting; it is now the whole pre-forward time and the component sum is components_ms. tokens.Stats exposes the memo's hit/miss/encoded-bytes counters.

Signed-off-by: Osher-Elhadad <[email protected]>

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review: REQUEST CHANGES at 218ac4b. One blocker: CI is red. (Posted as a comment: GitHub does not let the author account request changes.)

Blocker: TestBypassedRowGetsItsTokenCountFromTheWriter fails in CI. build-test fails at bypasstokens_test.go:114: only 0 of 1 rows persisted. It reproduces locally with go test -race ./proxy -run TestBypassedRowGetsItsTokenCountFromTheWriter. waitForRows waits 2 s (400 × 5 ms), and under -race the writer now tokenizes the 1 MiB body (plus the wait-cause scan) before the insert, which takes longer than that. Use a smaller body, for example bypassBody(t, 64<<10) (the count is still non-zero), or give this test a longer wait. Without -race it passes.

What I checked and found correct:

  • The writer's count equals the old pipeline figure. I sent the same bypassed Anthropic request through main and through this PR: system prompt, tool declaration, tool_use / tool_result, non-ASCII text, x-context-guru-bypass. Both rows read the same tokens_before/tokens_after, mode=bypass, reason=bypassed and the same accounting. On a bypassed request body == orig (the expand repair and the stray-call answer are both under !bypassed), and NormalizeMessages is the same normalize over the same messages array that BodyOpts uses. The new test's want uses the same function as the writer, so it doesn't prove this by itself, but the cross-check does.
  • Price. On the complete path the bypass count never entered cost: Saved() is 0 when before == after, so baseline_cost_usd is unchanged. On the incomplete path, the writer's missing → partial flip reproduces what Price used to decide from TokensBefore > 0.
  • /stats. It already skips bypassed requests (RecordEligibility is under !bypassed), so nothing changes there.
  • cg_ms. No script, dashboard or doc parses cg_ms from the log line. scripts/scenarios/lib.sh and metrics_export read the DB's cg_latency_ms.
  • Request-path skip. Removing it makes TestBypassedRequestIsNotTokenizedOnTheRequestPath fail, and removing the writer fill makes the row test fail.
  • gofmt and go vet are clean, and ./internal/tokens, ./components/..., ./apply, ./dash and ./proxy pass without -race. The tokens.Stats counters are atomics. Signed off, no AI attribution.

Non-blocking:

  1. A consumer you missed: attempted_tokens on bypassed rows. In the same cross-check, main stored attempted_tokens equal to the full count on the bypassed row, and this PR stores 0 (frozen_tokens is 0 on both). The dashboard Overview sums attempted_tokens, and SavedGrossAttempted takes its population from attempted_tokens > 0. Bypassed rows used to sit in that denominator with zero saving and now don't, so the "of attempted" ratio rises and the attempted totals fall. This is arguably more correct, and it matches /stats, which never counted bypassed requests. It is still a visible change, so say so in the PR text.
  2. The missing → partial flip is untested. Disabling it passes every test. Add a bypassed request with incomplete usage.
  3. The writer goroutine now carries the counting cost (about 0.35 s per MiB without -race), so a 33 MiB compaction row holds the writer for about 12 s before its insert. With the default queue of 4096 a drop is unlikely, but dashboard rows lag during that time. Worth a ponytail: line next to BypassTokens, with the upgrade path (count on its own goroutine, or count only the bytes and estimate).

@amiddavid amiddavid 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.

Verdict: blocking: the new test fails under -race

@OsherElhadad: the change itself looks right. One test must change before merge.

Why CI is red

  • Cause: this PR's own test, TestBypassedRowGetsItsTokenCountFromTheWriter. Not a flake, not main.
  • The CI log shows bypasstokens_test.go:114: only 0 of 1 rows persisted. The failing job runs with -race.
  • I ran it on eval box 1: 3 of 3 runs fail with -race. Without -race it passes in 0.42 s.
  • Under -race, the writer goroutine counts the 1 MiB body more than 2 s. waitForRows waits only 400 x 5 ms = 2 s. The row is not yet written when the wait ends.
  • Production is not at fault. The count simply runs off the request path, as intended.

Blocking

  • Fix the test. Pick one:
    • Use a smaller body (for example 64 KiB). The test needs a non-zero count, not a large one.
    • Or wait longer for the row (for example 30 s).

What I checked, and found fine

  • Dashboard row: the writer fills tokens_before and tokens_after. The test confirms they equal the old value.
  • Money figures: Price() uses billed usage, not these fields. The missing to partial upgrade restores the old label.
  • Status line and keep-alive: nothing in proxy/ reads Run.TokensBefore. MinPrefixTokens compares against billed cache tokens. No zero reaches them.
  • Trial merge with current origin/main (6 newer commits): clean.
  • go vet on proxy dash components apply internal/tokens: clean.
  • go test -race on components apply internal/tokens metrics dash: all pass.

Mutations (no -race)

Mutation Result
Count tokens again in Pipeline.Run on bypass caught by TestBypassedRequestIsNotTokenizedOnTheRequestPath
Remove the BypassTokens hook caught by the writer test
Run attemptedTokens on bypass again caught
Remove the missing to partial upgrade in dash/capture.go survives: no test covers it

Non-blocking

  • Add a test for the missing to partial upgrade (the mutation above).

  • On a bypassed request, these now read 0 where they held the full count before:

    • the cg.request log fields tokens_before and tokens_after;
    • frozen_tokens on the dashboard row;
    • the in-memory /stats and Prometheus cg_tokens_before_total and cg_tokens_after_total.

    saved stays 0 in all cases. Mention this in the PR description so nobody reads the 0 as a bug.

…orker

The first version counted on the dashboard writer, which a 33 MiB request would hold for ~12 s while every account's rows waited, and it left attempted_tokens and frozen_tokens at 0. The row is now inserted at once and a single count worker (queue of 8, never blocking; a full queue leaves the row uncounted) fills tokens_before/after, attempted_tokens and frozen_tokens with the figures main stored, and flips accounting missing to partial as before.

Signed-off-by: Osher-Elhadad <[email protected]>

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Re-review: APPROVE at 2ab067c. (Posted as a comment: GitHub does not let the author account approve.)

The earlier blockers are fixed, and CI is green (build-test 12m8s).

  • No lost counts. enqueueCount runs only after insertBatch has committed and e.ID is set from LastInsertId, so the worker's UPDATE ... WHERE id = ? always finds the row. The row is never updated before it exists.
  • Same figures as main. The count closure is schema.MessagesTokens(chat), attemptedTokens(norm, c), the same calls main's Pipeline.Run and apply made on the same request. The proxy test pins main's stored value for the same body. frozen = before - attempted, clamped at 0.
  • Mutations. Each of these fails a test:
    • Removing the enqueue fails TestBypassedRowGetsItsTokenCountFromTheWorker.
    • Writing 0 for attempted_tokens fails the same test.
    • Disabling the missing→partial flip fails TestBypassCountFlipsMissingToPartialOnly.
    • Making the send blocking fails TestBypassCountQueueFullDropsTheCount.
  • Worker. One goroutine, started with the recorder and stopped on done. -race passes on the dash BypassCount tests (-count=3) and the proxy Bypass/CGMs tests (-count=2). That includes the end-to-end case, where the worker reads the request's parsed chat after the handler returned, with no race reported.
  • gofmt and go vet are clean, and internal/tokens, apply, dash and proxy pass in full. Signed off. The PR text now notes the attempted-tokens shift and that cg_ms is unread.

Non-blocking:

  1. Drops aren't observable. countsDropped is incremented but never exported. Add it to the recorder's stats, or log a rate-limited warning, so operators can see uncounted rows. A dropped row keeps tokens 0 and accounting missing, which reads honestly as unknown.
  2. Memory. Each queued job's closure holds the parsed request (chat, norm), so the worker queue can pin up to 8 transcripts plus the one being counted. Before enqueue, bypassed events waiting in the recorder channel also hold theirs. This is bounded and usually short-lived, but on 33 MiB compaction bodies the queue alone could hold a few hundred MB of parsed requests. A ponytail: note with the ceiling, or keeping only the raw bytes and normalizing in the worker, would cover it.

This approval covers 2ab067c.

Osher-Elhadad added 2 commits October 15, 2026 09:55
…e totals; export dropped counts

A bypassed request's log fields tokens_before/after read 0 because the count runs later, so the line now carries tokens_pending=true. A test pins that the process-wide counters match main (a bypassed request was never emitted to them) and that the per-tenant token series, summed from the rows, carry main's figures once counted. The count worker's dropped counter is exported through the recorder stats.

Signed-off-by: Osher-Elhadad <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]>
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Pushed f1fb5a9, addressing the review:

  1. CI blocker: the row test now uses a 64 KiB body and polls the row (bounded, 10 s) instead of a fixed 2 s. go test -race -count=5 on the touched tests passes.
  2. The surviving mutation (removing the missing to partial flip) is now caught by TestBypassCountFlipsMissingToPartialOnly; I re-ran the mutation and it fails.
  3. Totals: the process-wide counters (/stats, cg_tokens_*_total) never saw a bypassed request on main either (Pipeline.Run returns before emitting its report), so they match main at 0. The per-tenant series are summed from the rows and carry main's figures once the worker has counted; both are pinned in TestBypassedRowGetsItsTokenCountFromTheWorker. The log line now carries tokens_pending=true for a bypassed request.
    Also: the count now runs on a separate bounded worker (queue 8) and fills attempted_tokens and frozen_tokens with main's figures; the dropped-count is exported in the recorder stats (counts_dropped); ponytail note on the memory ceiling. go vet, ./proxy and ./dash suites pass.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Re-review: APPROVE at f1fb5a9 (a60fa28 + gofmt on top of the approved 2ab067c). Both earlier non-blocking notes are addressed:

  • counts_dropped is exported in the recorder stats.
  • The ponytail note records the queued-closure memory ceiling.

Also new: the bypassed cg.request log line carries tokens_pending=true, so a 0 there no longer reads as an empty request, and a new proxy test pins the totals against main. gofmt and go vet are clean, the dash Bypass/Count tests and the proxy Bypass tests pass under -race, CI is green, and both commits are signed off. This approval covers f1fb5a9.

…op counter to Prometheus

Each queued job pins its parsed request, so eight large transcripts could be held at once. The queue now also refuses a job that would take the queued body bytes past 64 MiB (a lone job is always accepted), and the drop counter is exported as cg_bypass_count_dropped_total.

Signed-off-by: Osher-Elhadad <[email protected]>

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Re-review: APPROVE at dd9f6db.

  • Byte bound. The count queue is now also bounded by total body bytes (countMaxBytes, 64 MiB), and a lone job is always accepted. The size is added on enqueue and subtracted both on a full-channel drop and after the worker counts. BypassBytes is the pristine body length, set for bypassed requests too, since noteWaitBody runs after applyMode either way. With the bound disabled, TestBypassCountQueueIsBoundedByBytes fails.
  • Prometheus. cg_bypass_count_dropped_total is exported, and TestBypassCountDroppedIsExportedToPrometheus covers it.
  • gofmt and go vet are clean, the dash Bypass/Count and proxy Bypass/Prom tests pass under -race, CI is green, and the commit is signed off.

This approval covers dd9f6db.

@amiddavid amiddavid 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.

Verdict: approve

Both round 1 points are fixed. I reviewed the delta 218ac4bc..dd9f6db9.

Round 1 items

  • -race timeout: fixed. The test now uses a 64 KiB body and polls for the count. On eval box 1, go test -race -count=5 ./proxy -run "TestBypass|TestLifecycleLoggerCG" passes (71 s). It failed 3 of 3 before.
  • missing to partial upgrade: now covered. TestBypassCountFlipsMissingToPartialOnly fails when I disable the SQL CASE. A complete row stays complete.

New code (count worker)

  • The count now runs on one worker goroutine after the row insert. It does not run on the writer. The queue holds at most 8 jobs and 64 MiB of body.
  • A full queue skips the count, never blocks, and increments cg_bypass_count_dropped_total.
  • attempted_tokens and frozen_tokens are now filled as well. This fixes my round 1 non-blocking note.
  • The test pins the counts to the values origin/main stored (11992) and checks the per-tenant totals.

Checks

  • go vet ./proxy ./dash ./apply: clean.
  • go test -race: ./dash/... (441 s), ./apply, ./components, ./internal/tokens, ./metrics all pass. The ./dash BypassCount tests pass at -count=3.
  • Trial merge with current origin/main: clean.
  • Mutations on the new logic, all caught:
    • Disable the accounting upgrade.
    • Drop the byte bound.
    • Set frozen = before.
    • Do not enqueue the count.

Non-blocking

  • Rows stay at tokens_before 0 until the worker finishes. A restart or a dropped count leaves them at 0. The log field tokens_pending=true and the new counter make this visible. Say this in the PR description.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants