Repository navigation
perf(proxy): do not tokenize a bypassed request on the request path - #542
Conversation
…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
left a comment
There was a problem hiding this comment.
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 sametokens_before/tokens_after,mode=bypass,reason=bypassedand the same accounting. On a bypassed requestbody == orig(the expand repair and the stray-call answer are both under!bypassed), andNormalizeMessagesis the samenormalizeover the same messages array thatBodyOptsuses. The new test'swantuses 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, sobaseline_cost_usdis unchanged. On the incomplete path, the writer's missing → partial flip reproduces whatPriceused to decide fromTokensBefore > 0. - /stats. It already skips bypassed requests (
RecordEligibilityis under!bypassed), so nothing changes there. - cg_ms. No script, dashboard or doc parses
cg_msfrom the log line.scripts/scenarios/lib.shandmetrics_exportread the DB'scg_latency_ms. - Request-path skip. Removing it makes TestBypassedRequestIsNotTokenizedOnTheRequestPath fail, and removing the writer fill makes the row test fail.
gofmtandgo vetare clean, and./internal/tokens,./components/...,./apply,./dashand./proxypass without-race. Thetokens.Statscounters are atomics. Signed off, no AI attribution.
Non-blocking:
- A consumer you missed:
attempted_tokenson bypassed rows. In the same cross-check, main storedattempted_tokensequal to the full count on the bypassed row, and this PR stores 0 (frozen_tokensis 0 on both). The dashboard Overview sumsattempted_tokens, andSavedGrossAttemptedtakes its population fromattempted_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. - The missing → partial flip is untested. Disabling it passes every test. Add a bypassed request with incomplete usage.
- 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 aponytail:line next toBypassTokens, with the upgrade path (count on its own goroutine, or count only the bytes and estimate).
amiddavid
left a comment
There was a problem hiding this comment.
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-raceit passes in 0.42 s. - Under
-race, the writer goroutine counts the 1 MiB body more than 2 s.waitForRowswaits 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_beforeandtokens_after. The test confirms they equal the old value. - Money figures:
Price()uses billed usage, not these fields. Themissingtopartialupgrade restores the old label. - Status line and keep-alive: nothing in
proxy/readsRun.TokensBefore.MinPrefixTokenscompares against billed cache tokens. No zero reaches them. - Trial merge with current
origin/main(6 newer commits): clean. go vetonproxy dash components apply internal/tokens: clean.go test -raceoncomponents 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
missingtopartialupgrade (the mutation above). -
On a bypassed request, these now read 0 where they held the full count before:
- the
cg.requestlog fieldstokens_beforeandtokens_after; frozen_tokenson the dashboard row;- the in-memory
/statsand Prometheuscg_tokens_before_totalandcg_tokens_after_total.
savedstays 0 in all cases. Mention this in the PR description so nobody reads the 0 as a bug. - the
…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
left a comment
There was a problem hiding this comment.
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.
enqueueCountruns only afterinsertBatchhas committed ande.IDis set fromLastInsertId, so the worker'sUPDATE ... 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'sPipeline.Runandapplymade 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_tokensfails 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.-racepasses 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 parsedchatafter the handler returned, with no race reported. gofmtandgo vetare clean, andinternal/tokens,apply,dashandproxypass in full. Signed off. The PR text now notes the attempted-tokens shift and thatcg_msis unread.
Non-blocking:
- Drops aren't observable.
countsDroppedis 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 accountingmissing, which reads honestly as unknown. - 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. Aponytail:note with the ceiling, or keeping only the raw bytes and normalizing in the worker, would cover it.
This approval covers 2ab067c.
…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]>
|
Pushed f1fb5a9, addressing the review:
|
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-review: APPROVE at f1fb5a9 (a60fa28 + gofmt on top of the approved 2ab067c). Both earlier non-blocking notes are addressed:
counts_droppedis 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
left a comment
There was a problem hiding this comment.
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.BypassBytesis the pristine body length, set for bypassed requests too, sincenoteWaitBodyruns afterapplyModeeither way. With the bound disabled, TestBypassCountQueueIsBoundedByBytes fails. - Prometheus.
cg_bypass_count_dropped_totalis exported, and TestBypassCountDroppedIsExportedToPrometheus covers it. gofmtandgo vetare 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
left a comment
There was a problem hiding this comment.
Verdict: approve
Both round 1 points are fixed. I reviewed the delta 218ac4bc..dd9f6db9.
Round 1 items
-racetimeout: 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.missingtopartialupgrade: now covered.TestBypassCountFlipsMissingToPartialOnlyfails when I disable the SQLCASE. Acompleterow stayscomplete.
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_tokensandfrozen_tokensare now filled as well. This fixes my round 1 non-blocking note.- The test pins the counts to the values
origin/mainstored (11992) and checks the per-tenant totals.
Checks
go vet ./proxy ./dash ./apply: clean.go test -race:./dash/...(441 s),./apply,./components,./internal/tokens,./metricsall pass. The./dashBypassCounttests 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_before0 until the worker finishes. A restart or a dropped count leaves them at 0. The log fieldtokens_pending=trueand the new counter make this visible. Say this in the PR description.
What
A bypassed request (the agent's own compaction request, or one sent with
x-context-guru-bypass) is forwarded untouched, butcomponents.Pipeline.Runandapply.attemptedTokensstill 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.RunandattemptedTokensskip the count for a bypassed request.tokens_before/tokens_after,attempted_tokensandfrozen_tokenswith the same figures main stored for the same body, and flips accounting frommissingtopartialexactly as before. The row still reads modebypass/ reasonbypassed. Until the count lands (or if it is dropped) those columns read 0. With the dashboard off nothing counts, and the request log line showstokens_before=0for a bypassed request.cg_mson thecg.requestline (nothing parses it; the scripts read the dashboard'scg_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 iscomponents_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/tokenspasses.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.