Skip to content

Perf: Move the savings accountant off the request path - #1073

Merged
amiddavid merged 6 commits into
mainfrom
perf/1059-accountant-off-request-path
Nov 11, 2026
Merged

amiddavid merged 6 commits into
mainfrom
perf/1059-accountant-off-request-path

Conversation

@boazdavid

@boazdavid boazdavid commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Behavior change (needs a human yes before merge)

The accountant work now runs on its own goroutine. `finish` waits for it before it prices the request. So a row still has its saving when it is written. The cost moves from before the upstream call to `finish`, which runs after the response. If the work is slow, `finish` can wait for it.

Problem

`accBegin` and `accEnd` parsed and hashed the request body on the request goroutine. The request went upstream only after they finished. On a 670 KB body (24 tool results) this cost 5.7 ms idle and 26 ms mean under load. Closes #1059.

Change

  1. `accBegin` only notes the meta and the client body. It does no work.
  2. `accEnd` starts one goroutine. The goroutine opens the record and ends it. It uses a private `capture`, so it shares no field with the request goroutine.
  3. `finish` calls `accWait` before it prices the request. A record is complete before it is priced.
  4. If the job panics, the panic is recovered and logged. The row is stored with no saving.

The accountant library is not changed.

Tests

New tests are in `proxy/accountant_async_test.go`. Each failed before the change.

  • `accEnd` returns while the accountant is blocked.
  • On a 24-tool-result body, without `-race`, the request path costs under a quarter of the accountant work.
  • A panic in the job does not reach the request or the process.
  • Through the real handler, the upstream sees the request while the accountant is still working. The row still carries the saving.

Three existing tests changed because `accBegin` no longer does work: `TestAccBeginRecoversAndDrops`, `TestAccDropForgetsTheClientHash` and the ping test.

Results: `go test ./proxy/` passed. A `-race` run of the accountant, ping, savings and dashboard tests reported no data races. I did not re-measure the issue's timings on the eval box.

Data dependence

None changes. The accountant still works from hashes and counts only. Nothing new is stored.

Assisted-By: Claude (Anthropic AI) [email protected]

accBegin and accEnd parsed and hashed the request body on the request
goroutine, before the request went upstream. On a 670 KB body this cost
5.7 ms idle and 26 ms mean under load (issue #1059).

accBegin now only notes the meta and the client body. accEnd starts one
goroutine that opens the record and ends it. finish waits for that goroutine
(accWait) before it prices the request, so a record is complete before it is
priced. A panic in the job is recovered and the row is stored with no saving.

Adds a guard test on a 24-tool-result body without -race.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session fresh 1 of 2 1 of 2 50b8a42cc781 approve

Verdict: approve

Findings

None. I found no wrong behavior, no data loss, no broken fail-open path, and no missing test.

Non-blocking

  1. proxy/accountant_wire.go:46 — the comment claims an ordering the code does not enforce.

    • The comment says "a thread's next request arrives after the previous one was priced". finish runs in serve's defer, after the response bytes are flushed to the client (proxy/proxy.go:2614-2617). The client can send the next request before that defer runs, so the next request can be processed, and even priced, first.
    • With the record now opened in the job goroutine, the begin/end order of two requests of one thread rests on scheduling, not on synchronization. The window is narrow: the job must be delayed past a full client round trip. The accountant library tolerates this by design (optimistic Version replace, Result.Recomputed, R53 in internal/engine/compute.go and state.go), and concurrent same-thread requests could already interleave before this PR.
    • Fix: weaken the comment to say the order is usual, not guaranteed.
  2. proxy/proxy.go:1512 — stale comment. It says "The savings tracker begins HERE". accBegin now only notes the body; BeginRequest runs in accEnd's job. Fix the wording.

  3. proxy/dashcapture.go:940 — stale comment. It says "accBegin never opened a record". Now the reason is that accEnd never noted a request, or the job never ran. Fix the wording.

  4. proxy/accountant_async_test.go:66 — the test's premise is broader than what it measures. "What the request pays" measures accBegin + accEnd only. The request goroutine also pays accWait in finish, which waits for the whole job. That cost sits after the response is flushed, so it does not touch the first byte upstream (issue #1059's goal). The comment "what the request goroutine pays must be a small part" reads as if no other part exists. Say "what the request pays before the first byte goes upstream".

What I checked

  • Read CLAUDE.md and docs/design.md in full. Read the full diff of all six files, and the code around each change.
  • The async handoff. accEnd builds a private capture w and copies meta, client and ops. The job goroutine writes only w's fields. accWait reads w only after done is closed, so the channel close gives the happens-before edge. The request goroutine writes c.accJob, c.accOpen, c.accMeta, c.accClient and c.accPreDefer only before accEnd or after accWait (proxy/accountant_wire.go:33-75, proxy/proxy.go:1524-1669). finish and accEnd run on the same handler goroutine. I found no shared field without an ordering edge, so no data race.
  • Shared state. savingsTracker.clients is a sync.Map; PingStore and siblingStore hold mutexes (proxy/accountant_ping.go, proxy/accountant_shared.go). The job's pings.peek and siblings.sharedWarm are safe against the keeper and other requests.
  • Body bytes. The job reads orig and the forwarded body. After accEnd the request goroutine only reads them (serve, the recorder, the prefix asker). The go statement gives the job visibility of all earlier writes. I found no in-place writer after accEnd.
  • Fail-open. A panic in the job is recovered in accRun and costs the figure only (proxy/accountant_wire.go:82-91). This is stronger than before: the request is already on its way, and the old pre-forward recover is no longer reachable from accountant work. TestAccountantPanicOffThePathCostsTheSavingOnly pins it.
  • The drop path. A panic between accBegin and accEnd still calls accDrop (proxy/proxy.go:1424), and accOpen = false makes a later accEnd a no-op (proxy/accountant_wire.go:49, proxy/dashcapture.go:925). accDrop runs only before accEnd in production, so no job is left booked for a dropped request. TestAccDropForgetsTheClientHash covers it.
  • finish ordering. accWait is the first statement of the accountant block (proxy/dashcapture.go:775), before every read of accReq, accThread, accPingWindow and accNoResult. finish runs before the --record defer sends the row, so a row still carries the priced result; TestUpstreamIsReachedBeforeTheAccountantFinishes pins both halves. The /compact finish (proxy/proxy.go:960) never pairs with accBegin, so its accWait is a no-op.
  • Figure stability. meta.At is cp.start, fixed at request start, so EndRequest, Compute and sharedWarm see the same times as before; only the wall-clock moment the library calls run moved. RequestID is still taken at accBegin, so ids stay in request order.
  • Library tolerance. Read rossoctl/[email protected] (internal/engine/state.go, compute.go). BeginRequest touches no thread state; EndRequest and Compute use optimistic Version replacement and mark Recomputed when another request of the thread intervened. The new interleaving window falls inside what the library already handles.
  • Tests. Every test that read accountant results right after accEnd now calls accWait (accountant_ping_test.go:352, accountant_state_test.go:161, accountant_wire_test.go:307). All helpers the new file uses exist (accHandlerYAML, waitForRows, manyToolResultsRequest, benchBody, accTap.all). The new tests cover the four new behaviors: no wait, bounded pre-forward cost, panic isolation, row completeness.
  • Rules. No request-path behavior changes for users; only the timing of the accounting moved. No data-dependence change: the accountant still works from hashes and counts only. No sidecar code, no library/proxy boundary change.

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session fresh 2 of 2 1 of 2 50b8a42cc781 approve

Verdict: approve

Findings

None. The change is sound. The proof paths I checked:

  • Fail-open holds. accRun keeps the recover from the old accBegin (proxy/accountant_wire.go:82-91). A panic in the job costs the saving only. The request is already on its way. TestAccountantPanicOffThePathCostsTheSavingOnly pins this.
  • No shared mutable state between the job and the request goroutine. accEnd builds a private capture w and copies savings, provider, pings, accClient, accPreDefer into it before the goroutine starts (proxy/accountant_wire.go:52-60). The job writes only w fields. accWait reads them after <-job.done, so the channel close gives the happens-before edge. The stores the job touches are mutex-guarded: PingStore (proxy/accountant_ping.go:20), siblingStore (proxy/accountant_shared.go:24), and the library's Trackers ("safe for concurrent use", engine/state.go:56). serve never mutates the body bytes in place, so the job's concurrent parse of client and forwarded races with reads only.
  • Every reader of accReq, accThread, accPingWindow, accNoResult runs after accWait. I grepped all uses. They sit in finish (proxy/dashcapture.go:775-807), which calls c.accWait() first. accBilledTTL and the ping-window drop therefore see the finished record. The /compact path (proxy/proxy.go:960) never calls accBegin, so its accWait is a no-op.
  • The drop path is correct. accDrop now also clears accOpen, so an accEnd after a drop is a no-op. The pre-forward recover (proxy/proxy.go:1417-1426) fires only before accEnd, so no job is in flight when it runs. TestAccDropForgetsTheClientHash and TestAccBeginRecoversAndDrops cover both.
  • Cross-request ordering. The next request of a thread can now begin before the previous one is priced, because finish runs in serve's defer while the client may already send the next turn. The library handles this: each request holds its own state copy, Compute detects a version change and recomputes (Result.Recomputed, engine R53). So the figure degrades to "recomputed", never to a wrong sum.
  • Ping facts. The job's peek and finish's drop keep the window check from before (proxy/accountant_ping.go:67-76), so a newer ping still survives. The read moved from the request goroutine to the job, but the order inside the work (begin, then peek) is unchanged.
  • Reversibility and the wire are untouched. The accountant is a side figure. The forwarded body, the expand loop and the store are not on any path this PR changes.

Non-blocking

  • proxy/accountant_wire.go:53-60 — a panic between c.accJob = job and go func() leaves done unclosed. finish's accWait then blocks forever, and the request loses its row and its cg.request line. The only realistic trigger is an allocation failure in the ops copy, so the probability is near zero. The old code was worse: any panic in accEnd's work reached the pre-forward recover and cost the rewrite. A cheap hardening: start the goroutine before you publish c.accJob, or let accDrop clear c.accJob.
  • proxy/dashcapture.go:773-774 — the comment is stale. It says "the client hash begin kept for end". accBegin no longer keeps a hash; the job's begin does, and the job's own paths remove it. The defer c.savings.drop(c.accReq) is now a belt-and-braces no-op in practice.
  • proxy/accountant_wire.go:46-47 — the doc comment overstates the ordering. "A thread's next request arrives after the previous one was priced" is not guaranteed: finish runs in serve's defer, and the client can send the next request after the last response byte. The library tolerates the interleaving (R53), so the claim should say "the library recomputes" rather than promise an order.
  • proxy/accountant_async_test.go:143-163 — thin timing margin. The row becomes visible about accountantDelay (2 s) after accEnd. waitForRows polls 400 x 5 ms, also about 2 s. The pass margin comes mostly from the two SQLite PRAGMA queries that Recorder.Stats() runs per poll (dash/store.go:881). A smaller accountantDelay (say 1 s) or a longer poll budget would remove the dependence on that incidental overhead.
  • PR body — no data-dependence statement. CLAUDE.md asks every PR that changes a feature to state its data dependence. This PR changes none (hashes and counts only, nothing new stored), so one line saying so is enough. The behavior change is named at the top, as the rule requires.

What I checked

  • The full diff of all six files, line by line, plus the surrounding code: proxy/accountant_wire.go, proxy/dashcapture.go (capture struct, finish, accDrop), proxy/proxy.go (the pre-forward closure at 1417-1670, both finish call sites, serve's defer), proxy/accountant_savings.go, proxy/accountant_ping.go, proxy/accountant_shared.go.
  • The accountant library at the pinned version (v0.1.1-0.20261108152158-5181d50c1f98): Trackers.BeginRequest, EndRequest, Compute, the R53 optimistic lock, Snapshot locking.
  • Every use of accBegin, accEnd, accWait, accDrop, accJob, accOpen, accMeta, accClient, accPreDefer, accThread, accPingWindow, accReq, accNoResult in non-test and test code.
  • The test helpers the new tests use (accHandlerYAML, waitForRows, manyToolResultsRequest, accTap), and the timing margins of the two wall-clock tests.
  • The PR description (author's, not other reviews): the behavior change is named at the top; the owner's yes is still pending, which the PR itself states.
  • No builds or tests were run; live tests are not approved for this review.

- Say the order of two requests of one thread is usual, not guaranteed.
- Update comments that still described the old accBegin.
- Publish the accountant job last in accEnd.
- Give the handler test more time to see its row.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
@boazdavid

Copy link
Copy Markdown
Collaborator Author

Round 1 answers. Fixed in the new commit:

  1. The ordering comment now says the order of two requests of one thread is usual, not guaranteed. The library recomputes.
  2. Stale comments in proxy/proxy.go and proxy/dashcapture.go now describe the new accBegin and accEnd.
  3. accEnd now publishes c.accJob last, right before the go statement.
  4. TestUpstreamIsReachedBeforeTheAccountantFinishes now polls for up to 10 s for its row.
  5. The ratio test comment now says "before the first byte goes upstream".
  6. The PR body now has a data-dependence line.

Assisted-By: Claude (Anthropic AI) [email protected]

@amiddavid

Copy link
Copy Markdown
Collaborator

Integrator note. The owner approved the behavior change on 2026-11-11 ("1073 yes"), and called this the most critical PR of v0.7.3. It is next in line once these are fixed:

  1. Merge conflict with main. GitHub reports it does not merge cleanly. Please merge origin/main in (main now has feat(agent): an extension point for client agents #1029, feat(dash): on a subscription the Cache strategy tables show tokens (#1048) #1065, Fix: A keep-alive ping that re-wrote the cache restarts the refresh clock #1066).
  2. CI fails at e29be51 in build-test, purego and record. From the purego log:
    • accountant_async_test.go:161: "the upstream saw the request 1.209123895s after it was sent: it waited for the accountant (2s)". Either the request still waits for the accountant on that path, or the limit is too tight on a CI runner.
    • accountant_inject_test.go:62: "the savings record never ended".
  3. A new review round. The 2 GLM approvals are at 50b8a42, and the head moved after them. Please run offload-review again on the final head.

Then message the integrator session with the head.

The savings record now ends in a background job, so the inject test must
wait for it. The async test compares the upstream time with the moment the
accountant ended, not with a fixed limit.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session resumed 2 of 2 2 of 2 5bb6aaa68ed9 approve

Verdict: approve

Findings

None. The fixes are correct, and the new commits add no defect.

Earlier findings

All round-1 findings were non-blocking. None was rejected. Status:

  • Ordering comment (reviewer 1, #1; mine, #3): fixed. accEnd's doc now says the order of two requests of one thread is "usual, not guaranteed", and names the library's Result.Recomputed (proxy/accountant_wire.go:46-49). This matches what the library does.
  • Stale comments (reviewer 1, #2 and #3): fixed. proxy/proxy.go:1531-1533 now says accBegin only notes the body and accEnd opens the record on another goroutine. proxy/dashcapture.go:941 now says "accEnd never noted a request, or the job opened none".
  • Ratio test comment (reviewer 1, #4): fixed. It now says "before the first byte goes upstream" (proxy/accountant_async_test.go:57-58).
  • accJob publish order (mine, #1): fixed. c.accJob = job moved to the line before the go statement (proxy/accountant_wire.go:59-61). The ops copy and both allocations now run before the publish. Nothing that can fail sits between the publish and the go, so done cannot be left unclosed by an enqueue panic.
  • finish comment (mine, #2): fixed. proxy/dashcapture.go:773-775 now says the job is joined first and describes the job's begin as the hash holder.
  • Thin test timing margin (mine, #4): fixed twice over. The row poll now runs up to 10 s (proxy/accountant_async_test.go:170-172), and 5bb6aaa removed the fixed limit entirely. See below.
  • PR data-dependence statement (mine, #5): fixed. The PR body has a "Data dependence" section: "None changes. The accountant still works from hashes and counts only."

The new commits

e29be51 — review fixes. Comment fixes and the accJob publish move, verified above. No behavior change.

31a5f00 — merge of origin/main. The integrator asked for this merge. I checked it against an automatic merge: git merge-tree --write-tree e29be518 8b311f10 produces a tree identical to the merge commit's tree. So the merge has no hand resolution. The three main commits it brings (#1029, #1065, #1066) each carry their own approvals, named in their commit messages. The PR diff at the new base contains only the accountant change: proxy/proxy.go contributes 6 comment lines and nothing else. The interaction points are clean: #1029's agent usage reading feeds the same usage value finish prices, and #1066's refresh-clock changes sit outside the accountant block.

5bb6aaa — test speed independence. This answers the integrator's two CI failures at e29be51:

  1. accountant_async_test.go:161 failed with "the upstream saw the request 1.209 s after it was sent". The old check compared the upstream time with sent under a fixed 1 s limit, so a slow pre-forward path on CI failed it without any waiting on the accountant. The new check compares reached with accountantDone, the moment the accountant's work ended (proxy/accountant_async_test.go:163-168). Runner speed delays both sides equally, so it cancels out. I traced both directions: with the async design, reached sits one forward-hop after accEnd while done sits accountantDelay (2 s) after it, so the check passes with a wide margin however slow the runner is. With the old synchronous accEnd, the work (and the 2 s sleep) completes before the forward, so reached >= done and the test still fails. The regression guard is intact.
  2. accountant_inject_test.go:62 failed with "the savings record never ended". The record now ends in the background job, so the test polls up to 5 s for it before it reads the record (proxy/accountant_inject_test.go:61-68). Correct fix; the assertions after the poll are unchanged.

Non-blocking

  • proxy/accountant_async_test.go:176 and proxy/accountant_inject_test.go:82 — tap.all()[0] can race the Tap. The recorder increments Written before it calls Tap (dash/capture.go:549-559), both on the writer goroutine. A poll that observes Written >= 1 in the sub-microsecond window between the two can see an empty tap.all() and panic on [0]. The window is tiny and the pattern predates this PR (waitForRows then tap.all()[0]), so I do not hold the PR for it. A len check before indexing, or Tap before the counter, would close it.
  • CI at the new head is still pending. At review time, trivy and DCO pass; build-test, purego, record and analyze are pending. I could not run the tests myself (live tests are not approved for this review). Both failures the integrator named are fixed by code reading, but green CI is the integrator's final check before merge.

What I checked

  • Last review: round 1, 50b8a42, 2026-11-11T08:00:05Z.
  • New commits read: 6 — e29be518 fix(proxy): Address review of the async accountant; 31a5f003 merge of origin/main; 8b311f10 feat(dash) #1065 (from main); 62289d9a fix(keepalive) #1066 (from main); d865b250 feat(agent) #1029 (from main); 5bb6aaa6 test(proxy): Stop two accountant tests depending on runner speed.
  • Read in full: 2 reviews, 2 comments, 0 inline comments (from the three files .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt).
  • New items since my last review, and what I did about them:
    • The author's round-1 answers (08:08:32Z): checked each of the six items against the code. All fixed as stated.
    • The integrator note (09:02:58Z): merge conflict — verified the merge exists and is automatic (merge-tree comparison, identical trees). CI failures at e29be51 — read both failing tests and the fixes in 5bb6aaa, traced the pass and fail directions of the new check. New review round — this review. The owner's approval of the behavior change is recorded in that note ("1073 yes").
    • Commits e29be51, 31a5f00, 5bb6aaa: read the full diffs and the changed files around them (proxy/accountant_wire.go, proxy/accountant_async_test.go, proxy/accountant_inject_test.go, proxy/dashcapture.go, proxy/proxy.go).
    • The PR diff at the new base 8b311f10..HEAD: 8 files, +274/−23. It contains only the accountant change; the agent refactor and the other main work stay in the base.
    • The recorder's write path (dash/capture.go:515-563) for the Tap-versus-Written ordering.
    • The PR body's Data dependence section.
    • CI status at the head via gh pr checks: pending, noted above.
  • No builds or tests were run; live tests are not approved for this review.

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session resumed 1 of 2 2 of 2 5bb6aaa68ed9 approve

Verdict: approve

Findings

None. Both new commits are correct. Every round-1 finding is fixed.

Earlier findings

Mine, round 1:

  1. Ordering comment (accountant_wire.go:46) — fixed. The comment now says the order is usual, not guaranteed, and names Result.Recomputed. This matches what I proved in round 1 from the library's R53.
  2. Stale comment proxy.go:1512 — fixed. It now says accBegin only notes, accEnd opens the record on another goroutine.
  3. Stale comment dashcapture.go:940 — fixed. "accEnd never noted a request, or the job opened none".
  4. Test premise wording — fixed. The comment now says "before the first byte goes upstream (accBegin and accEnd; finish waits for the job later, after the response)".

Reviewer 2, round 1 (I checked each myself):

  1. A panic between c.accJob = job and go leaves done unclosed — fixed. accEnd now publishes c.accJob immediately before the go statement, with nothing between (proxy/accountant_wire.go:58-63). The goroutine's first statement is defer close(job.done), so done closes even if accRun panics. I agree with the fix.
  2. Stale finish comment — fixed (dashcapture.go:773-775). Same as my item 3.
  3. Ordering comment — fixed. Same as my item 1.
  4. Thin timing margin in the handler test — fixed twice. e29be518 extended the poll to 10 s; 5bb6aaa6 went further and replaced the fixed limit with a comparison against the moment the accountant ended. CI at e29be518 confirmed the margin was real ("the upstream saw the request 1.209 s after it was sent").
  5. PR body data-dependence line — fixed. The body now has a "Data dependence" section: "None changes. The accountant still works from hashes and counts only."

The integrator's note (a person's request):

  1. Merge main — done. 31a5f003 merges origin/main (d865b250 #1029, 62289d9a #1066, 8b311f10 #1065). I verified the merge: git diff e29be518..31a5f003 on all seven PR files is empty, so the merge changed none of this PR's code; git diff 8b311f10..HEAD -- proxy/proxy.go is the comment fix only. GitHub reports the PR mergeable. The three main commits carry their own two-review approvals, named in their commit messages.
  2. CI failures at e29be518 — fixed in code, CI pending. Both failures came from tests that assumed the record ends before the response returns:
    • accountant_inject_test.go:61-64 now polls got for up to 5 s before it reads the record. Correct: the record ends in the job, after the response.
    • TestUpstreamIsReachedBeforeTheAccountantFinishes now fails only when the upstream was reached at or after the accountant finished (reached >= done, accountant_async_test.go:165-168). A slow runner delays reached and done together, so the assertion no longer depends on runner speed. I traced both the healthy path and a synchronous regression: a synchronous accEnd still fails the test, so the guard stays meaningful.
    • CI at the head 5bb6aaa6 is pending (build-test, purego, record). I could not run tests; live tests are not approved. The fixes are correct by reading.
  3. New review round — this review.

Non-blocking

  1. proxy/accountant_async_test.go:170-176 — Written >= 1 does not yet prove the tap holds the event. The writer goroutine runs r.written.Add before r.opts.Tap(e) (dash/capture.go:549-558). If the writer is preempted in that window, the test sees Written >= 1 and tap.all()[0] panics on an empty slice. The window is a few statements wide, so the risk is near zero. The same shape exists in waitForRows (proxy/dash_test.go:166-176), so this is a pre-existing pattern, not a regression. Fix if desired: poll len(tap.all()) > 0 instead of Stats().Written.
  2. proxy/accountant_async_test.go:165 — the new comparison still has a runner-speed edge. A healthy runner whose pre-forward work takes more than accountantDelay (2 s) reaches the upstream after the accountant ended and fails the test. The budget doubled against the old 1 s limit and CI passed at 1.2 s before, so the residual risk is small. A larger accountantDelay would remove it.

What I checked

  • Last review: round 1, 50b8a42, 2026-11-11T07:59:57Z.
  • New commits read: 6 — e29be518 fix(proxy): Address review of the async accountant; d865b250 feat(agent) #1029 (from main, via the merge); 62289d9a fix(keepalive) #1066 (from main); 8b311f10 feat(dash) #1065 (from main, the new base); 31a5f003 merge of origin/main; 5bb6aaa6 test(proxy): Stop two accountant tests depending on runner speed.
  • Read in full: 2 reviews, 2 comments, 0 inline comments (from the three files .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt).
  • New items since my last review: reviewer 2's round-1 review (approve, 5 non-blocking; I verified each fix above); the author's round-1 answers (6 items, all verified in the diff); the integrator note (3 items, all handled above); commits e29be518, 31a5f003, 5bb6aaa6.
  • Read the full diff 50b8a42c..HEAD on the PR's own files, and the base..head diff 8b311f10..HEAD: accountant_wire.go, dashcapture.go, proxy.go, and the five test files. The PR-own proxy.go change is the comment fix only.
  • Verified the merge left every PR file untouched and that base..head contains only this PR's changes, so the merge adds no unreviewed code of this PR's authorship.
  • Re-read the changed regions at head: accEnd (publish-last), finish (accWait first), both changed tests. Checked dash.Recorder.Stats().Written exists (dash/capture.go:424,467) and the tap wiring (dash.Options.Tap, called after the insert, dash/capture.go:557).
  • The PR body states the behavior change at the top, the owner's approval (integrator note), and the data dependence.
  • No builds or tests were run; live tests are not approved. CI at head is pending; the two test fixes are correct by reading.

@amiddavid

Copy link
Copy Markdown
Collaborator

Integrator note: #1054 is now on main (43802c5). It adds the nil-by-default timing hooks timed and timedSpan to proxy/accountant_wire.go (3 lines) and proxy/dashcapture.go, plus the latency guard in proxy/dash_test.go. When you merge main, please keep the hooks around the work that is still on the request goroutine. If the accountant work moves to its own goroutine, the guard's parent map in dash_test.go must follow the new span nesting. The guard should then show the gain from this PR.

@amiddavid

Copy link
Copy Markdown
Collaborator

Integrator recheck at 5bb6aaa: round-2 approvals are at this head, thank you. Two things are left:

  1. It conflicts with main again. test(proxy): measure the dashboard's own cost, not request time #1054 merged after your merge of main. It adds timing hooks in proxy/accountant_wire.go and proxy/dashcapture.go, see my comment above. Please merge origin/main once more and keep the hooks.
  2. Sign-off: the merge commit 31a5f00 has no Signed-off-by. The DCO check passes, so this is not a blocker, but please use git merge --signoff next time.

If the merge needs a hand resolution in code, it needs one more GLM round on the new head. The owner pre-approved extra rounds.

The conflict was in proxy/accountant_wire.go. Main (#1054) times accEnd on
the request goroutine. accEnd is now the launcher, so it keeps that timing.
accEndNow runs off the request path and is not timed.

The two accountant tests now also wait for the tap, because the recorder
counts a row just before it calls the tap.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session resumed 1 of 2 3 of 3 ad1e7b8a4d8b approve

Verdict: approve

Findings

None. The merge's hand resolution is correct, and it follows the integrator's instruction.

The new commits

27c0c40 (#1067) and 43802c5 (#1054) — from main. Both sit in the new base. Each carries its own two-review approvals, named in its commit messages. Neither changes this PR's files in the PR diff: git diff 43802c5a..HEAD holds only the eight accountant files. I read #1054 where it meets this PR, in full at head: the timing hooks in proxy/accountant_wire.go and proxy/dashcapture.go, and the spend guard in proxy/dash_test.go. #1067 touches apply/ and dash/ only.

ad1e7b8 — the merge, with the hand resolution. git merge-tree --write-tree 5bb6aaa6 43802c5a confirms only proxy/accountant_wire.go conflicted; every other file auto-merged. The resolution:

  1. accBegin keeps main's defer c.timed("accBegin")() and now measures the no-op note. accEnd keeps defer c.timed("accEnd")() and now measures the launch only: the private capture, the ops copy, and the goroutine start (proxy/accountant_wire.go:30,51).
  2. accEndNow, the work on the job goroutine, carries no span. Correct: it is off the request path. No timed call exists on the job's private capture — I grepped every timed( in the package; the job's path (accRun → accEndNow → accBilled/envelopeOpsFor/entryFacts/savings.end) has none, so no span from the job can pollute the guard's figures.
  3. accWait sits inside finish's span (defer c.timed("finish")() at proxy/dashcapture.go:591 wraps all of finish, c.accWait() inside it). Correct: the join is real work on the request goroutine, and the guard should see it. This is what the integrator asked for: "keep the hooks around the work that is still on the request goroutine."
  4. The guard's parent map (accBilledTTL → accCompute → finish, proxy/dash_test.go:560) still matches reality: no span was added, removed, or renamed. The merge kept main's dash_test.go byte-identical (git diff 43802c5a..HEAD -- proxy/dash_test.go is empty), which is right, because the span set kept its shape.
  5. Nil-safety holds: timed returns noopSpan for a nil capture (proxy/dashcapture.go:56-60), so the hook before the nil check in accBegin and accEnd is safe, the same pattern main used.

The merge also carries two test fixes, named in its message:

  • TestUpstreamIsReachedBeforeTheAccountantFinishes now polls len(tap.all()) directly, not rec.Stats().Written (proxy/accountant_async_test.go:170-175).
  • TestSavingsRecordEndsWithTheInjectedForwardedBody adds a tap-wait loop after waitForRows (proxy/accountant_inject_test.go:82-85).

Both close the race from my round-2 note 1 and reviewer 2's: the recorder counts a row before it calls the tap (dash/capture.go:549-558), so Written >= 1 did not prove the tap held the event. The fix is correct.

Earlier findings

  • All round-1 and round-2 items, mine and reviewer 2's: fixed and still fixed. The merge kept every comment fix (the "usual, not guaranteed" ordering comment, both stale-comment fixes, the test-premise wording, the publish-last accJob, the PR body's data-dependence line).
  • My round-2 note 1 (tap race): fixed by the merge, above.
  • My round-2 note 2 (the accountantDone comparison fails on a runner slower than 2 s pre-forward): still open, minor. CI has passed on both heads since; the risk is small. A larger accountantDelay would remove it.

The integrator's sign-off request: the merge commit ad1e7b8a carries Signed-off-by. The DCO check passes.

Non-blocking

  1. proxy/dash_test.go:637-643 — the capture check "leaves the accountant out" only partly now. The check skips accBegin, accEnd, accBilledTTL and accCompute, but the accountant's join remainder now sits inside finish's span, which it does not skip. Counting it is semantically right: accWait is real request-goroutine work. But the 25 ms budget (dash_test.go:640) now absorbs an amount that varies with the job's remaining work at finish time. The record job passed ./proxy/... under -race at this head (ok proxy 444.440s), so the budget held. A passing run does not print its t.Logf median, so the margin is unknown to me. If this check flakes later, give accWait its own span and add it to the skip list, or raise the budget with a fresh measurement.

What I checked

  • Last review: round 2, 5bb6aaa, 2026-11-11T09:16:23Z.
  • New commits read: 3 — 27c0c406 fix(dash): count the fixed_restore copy in the saved figure (#1067, from main); 43802c5a test(proxy): time the dashboard's own work on the request goroutine (#1054, from main); ad1e7b8a merge of origin/main with the hand resolution.
  • Read in full: 4 reviews, 4 comments, 0 inline comments (from the three files .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt).
  • New items since my last review, and what I did about them: reviewer 2's round-2 review (approve; I read it and agree with its verification, including its merge-tree check); the integrator comment at 09:16:35Z (#1054 is on main; keep the hooks on request-goroutine work; the guard's parent map must follow the span nesting — all three followed, see above); the integrator comment at 09:32:59Z (merge main again, sign the merge, one more round for a hand resolution — all three done); the three commits.
  • The hand resolution: read the full git diff 43802c5a..HEAD on proxy/accountant_wire.go, proxy/dashcapture.go, proxy/limitheaders.go, and the three test files; read timed/timedSpan/spendHook (dashcapture.go:37-61), finish's span (line 591) with accWait inside it, the whole spend guard (dash_test.go:496-648) including dashboardSpends, the parent map, both budgets, and the helpers fakeUpstreamUsage and dashHandler; grepped every timed( call in the package to confirm the job goroutine has none.
  • The merge mechanics: git merge-tree --write-tree 5bb6aaa6 43802c5a (one conflict, proxy/accountant_wire.go); git diff 43802c5a..HEAD --stat (the eight PR files only); git diff 43802c5a..HEAD -- proxy/dash_test.go (empty).
  • CI at the head, read only: purego pass; record (go test -race -tags cg_record ./proxy/...) pass, ok proxy 444.440s, downloaded and read its job log; build-test (make cover, also -race) still pending at review time. The record job already runs the same proxy tests under -race, so the resolution is exercised. No tests were run by me; live tests are not approved.

finish joins the accountant's job (accWait). That wait is the accountant's
cost, which the max-content latency test leaves out. Its work ran inside
accEnd before, and accEnd was left out. It now runs in accWait, so
accWait is left out too, and its time is taken out of finish.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session fresh 2 of 2 4 of 4 dc8a9407b799 approve

Verdict: approve

Findings

None. The new commit is correct, and the merge resolution follows the integrator's instruction.

The new commits

ad1e7b8 — merge of origin/main, with a hand resolution. I ran git merge-tree --write-tree 5bb6aaa6 43802c5a myself. It reports one conflict, in proxy/accountant_wire.go, the file the integrator named. I read the resolved file in full at HEAD:

  1. accBegin keeps main's defer c.timed("accBegin")() and measures the no-op note only (proxy/accountant_wire.go:30). accEnd keeps defer c.timed("accEnd")() and measures the launch only: the private capture, the ops copy, the goroutine start (line 51). This is what the integrator asked: hooks stay on the work that is still on the request goroutine.
  2. The job goroutine's path (accRun → accEndNow → accBilled → envelopeOpsFor → entryFacts → savings.end) carries no timed call. I grepped every timed( and timedSpan( in the package. No span from the job can pollute the guard's figures.
  3. accBilledTTL is called from one place only, proxy/dashcapture.go:842, inside the accCompute span that finish opens at line 827 and closes at line 852. The guard's parent map (accBilledTTL → accCompute → finish) matches reality.
  4. The merge commit carries Signed-off-by, as the integrator asked. DCO passes at HEAD.

The merge also brings the two tap-race fixes both reviewers raised in round 2: accountant_async_test.go now polls len(tap.all()), and accountant_inject_test.go waits for the tap after waitForRows. Both are correct: the recorder counts a row before it calls the tap, so polling the tap closes the window.

27c0c40 (#1067) and 43802c5 (#1054) — from main. Both sit in the new base. Each carries its own two-review approvals, named in its commit messages. I read their full diffs as they entered this branch. The PR diff at the new base holds only the accountant change: 9 files, and git diff 43802c5a..HEAD -- proxy/dash_test.go is the 4-line delta of dc8a940 and nothing else.

dc8a940 — accWait as its own span. This answers reviewer 1's round-3 note. I verified each part:

  1. accWait now opens defer c.timed("accWait")() before its nil check (proxy/accountant_wire.go:70). timed returns noopSpan for a nil capture, so the hook before the nil check is safe, the same pattern as accBegin and accEnd.
  2. The guard's parent map gains "accWait": "finish" (proxy/dash_test.go:560). The nesting is real: accWait is called only from finish (proxy/dashcapture.go:824), inside finish's span, so the join's time is taken out of finish and counted once, under its own name.
  3. The max-content check adds accWait to its skip list (proxy/dash_test.go:643). So that check now leaves out the whole accountant: accBegin, accEnd, accWait, accBilledTTL, accCompute. The main check skips none of them, so it still counts all dashboard work, the join included. This matches the two checks' documented split: the join is the accountant's cost (#1059), not capture work.
  4. The commit message's claim checks out: before this PR, the accountant's work ran inside accEnd on the request goroutine, and accEnd was already on the skip list. The work now runs in the job, and the join runs in accWait. Skipping accWait keeps the same coverage.

Earlier findings

  • My round-1 and round-2 items: all fixed before, all still fixed at HEAD. I re-read the resolved proxy/accountant_wire.go: the "usual, not guaranteed" ordering comment (lines 47-49), the publish-last accJob (lines 59-61), and the accEnd/accWait structure are intact. The PR body still opens with the behavior-change section and carries the Data dependence section.
  • My round-2 note on the tap race: fixed by the merge's test fixes, above.
  • Reviewer 1's round-3 note 1 (accWait inside finish's span, not skipped by the capture check): fixed by dc8a940, above. I checked it myself; the fix is the right one.
  • Reviewer 1's round-3 round-2 note 2 (the accountantDone comparison fails on a runner slower than 2 s pre-forward): still open, minor, unchanged by the new commits. CI passed at the two heads before this one, so the risk stays small.

Non-blocking

  1. proxy/dash_test.go:496 — the doc comment's list of timed calls is now short. It names "the accountant's accBegin and accEnd, finish". accBilledTTL, accCompute and now accWait are also timed, and the comment does not name them (the nesting note at line 500 covers only accBilledTTL and accCompute). The maintenance rule below the comment is the load-bearing one, so this cannot mislead a careful reader. Adding accWait to the nesting note would close it.
  2. CI at HEAD is pending. CodeQL, analyze, DCO and trivy pass; build-test, purego and record are pending at review time. The two new commits touch only test accounting and a one-line span, and the merge's resolution is exercised by the proxy suite, so I expect green. Green CI stays the integrator's final check before merge.

What I checked

  • Last review: round 2, 5bb6aaa, 2026-11-11T09:16:16Z.
  • New commits read: 4 — 27c0c406 fix(dash): count the fixed_restore copy in the saved figure (#1067, from main via the merge); 43802c5a test(proxy): time the dashboard's own work on the request goroutine (#1054, from main via the merge); ad1e7b8a merge of origin/main with the hand resolution; dc8a9407 fix(proxy): Time the wait for the accountant as its own span.
  • Read in full: 5 reviews, 4 comments, 0 inline comments (from the three files .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt).
  • New items since my last review, and what I did about them:
    • Reviewer 1's round-2 review (09:16:23Z): read; its round-1 fix checks agree with mine.
    • Integrator comment 09:16:35Z (keep the hooks on request-goroutine work; the parent map must follow the span nesting): verified both in the merge resolution and in dc8a940, above.
    • Integrator comment 09:32:59Z (merge main again; sign the merge; one more round for a hand resolution): merge done at ad1e7b8, Signed-off-by present, DCO pass; this review is the round it asked for.
    • Reviewer 1's round-3 review (10:02:40Z): read in full; re-ran its merge-tree check myself and confirmed its span-nesting claims by reading the code.
    • Commits 27c0c40, 43802c5, ad1e7b8, dc8a940: read the full git diff 5bb6aaa6..HEAD (all files) and git show dc8a9407; read proxy/accountant_wire.go and proxy/dashcapture.go in full around every change.
  • The span set at HEAD: grepped every timed(, timedSpan( and spendHook use in the package; confirmed accWait and accBilledTTL each have exactly one production call site, both inside finish's span, matching the guard's parent map.
  • The PR diff at the base: git diff 43802c5a..HEAD --stat (9 accountant files); git diff 43802c5a..HEAD -- proxy/dash_test.go (the dc8a940 delta only).
  • The PR body: behavior-change section at the top and a Data dependence section, both still present.
  • CI at HEAD via gh pr checks: 4 pass, 3 pending, noted above.
  • No builds or tests were run; live tests are not approved for this review.

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session resumed 1 of 2 4 of 4 dc8a9407b799 approve

Verdict: approve

Findings

None. The commit is correct, and it fixes my round-3 note as proposed.

The new commit

dc8a940 — fix(proxy): Time the wait for the accountant as its own span. Three lines: accWait gains defer c.timed("accWait")() (proxy/accountant_wire.go:70), the guard's parent map gains "accWait": "finish" (proxy/dash_test.go:560), and the capture check's skip list gains "accWait" (proxy/dash_test.go:643). What I verified:

  1. The span reaches the guard. timed goes through timedSpan, which loads spendHook (proxy/dashcapture.go:46-61). The hook in dashboardSpends therefore sees an accWait call.
  2. The nesting is always true. The only non-test call site of accWait is proxy/dashcapture.go:824, inside finish, whose span starts at line 591. So "accWait": "finish" never misparents. A second accWait call, and the /compact path, find accJob nil and measure about zero (proxy/accountant_wire.go:71-76).
  3. Nil-safety. The hook sits before the nil check, the same pattern as accBegin and accEnd. A nil capture returns noopSpan (proxy/dashcapture.go:56-61).
  4. The main check keeps its figure. The hook counts accWait's duration in the sum and subtracts the same amount from finish. So TestDashboardAddsNoRequestLatencyWithContentCapture, which skips nothing, totals the same as before this commit. A runaway join on a small body still fails it.
  5. The exclusion is right for the capture check. The join is the accountant's cost: the same work the check has always left out, first inside accEnd, now inside accWait's join. It runs in serve's defer, after the response is flushed, so it adds no client-visible latency. The accountant's growth with body size stays tracked by TestRequestPathCostDoesNotGrowWithBodySize. The commit message states this rationale, and I agree with it.
  6. No production cost. spendHook is nil in production, so the span costs one atomic load (proxy/dashcapture.go:37-41). No user behavior change.
  7. Hygiene. The commit carries Signed-off-by and the Assisted-By: line. DCO passes.

Earlier findings

  • My round-3 non-blocking note 1 (the capture check's 25 ms budget absorbs the accWait join, with an unknown margin): fixed, exactly as the note proposed — a span of its own, plus the skip list and the parent map entry.
  • My round-2 note 2 (the accountantDone comparison fails on a runner slower than 2 s pre-forward): still open, minor. Unchanged by this commit. CI has passed on every head since.
  • All round-1 and round-2 items, mine and reviewer 2's: fixed and still fixed. Nothing in this commit touches them.

Non-blocking

  1. proxy/dash_test.go:516 — the comment is now stale. It says the capture check "leaves the accountant out (accBegin, accEnd, accBilledTTL and accCompute)". The check now also leaves out accWait, and the comment does not name it. Fix: add accWait to the list. The example at line 520 ("accBilledTTL in accCompute in finish") could also name accWait in finish, but that is optional.

What I checked

  • Last review: round 3, ad1e7b8, 2026-11-11T10:02:40Z.
  • New commits read: 1 — dc8a9407 fix(proxy): Time the wait for the accountant as its own span.
  • Read in full: 5 reviews, 4 comments, 0 inline comments (from the three files .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt).
  • New items since my last review, and what I did about them: the commit dc8a9407 only. No new comments exist — the last comment stays at 09:32:59Z, before my round-3 review. Reviewer 2 has posted no round-3 review. The round-3 reviews now in the file are mine (already known) and nothing else new.
  • The commit: read the full git diff ad1e7b8a..HEAD; read accWait at head (proxy/accountant_wire.go:68-81), timed/timedSpan/spendHook (proxy/dashcapture.go:37-61), finish's span at line 591 with the accWait call at line 824, and the whole guard in proxy/dash_test.go (the comment block, dashboardSpends, both budgets, both checks). Grepped every non-test accWait and timed("finish") call site to confirm the nesting claim.
  • The PR scope at the new head: git diff 43802c5a..HEAD --stat — 9 files, +282/−26. The only change past the round-3 head is the 3 lines of this commit, in proxy/accountant_wire.go and proxy/dash_test.go.
  • CI at the head, read only: purego pass (3m25s), CodeQL, analyze, trivy and DCO pass; build-test and record pending at review time. The prior head ad1e7b8a passed the same proxy tests under -race (record: ok proxy 444.440s), and this commit's delta is one timed call and one skip-list entry, which purego already compiled and ran green. No tests were run by me; live tests are not approved.

@amiddavid
amiddavid merged commit e86d897 into main Nov 11, 2026
7 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 11, 2026
amiddavid pushed a commit that referenced this pull request Nov 12, 2026
…ts (#1112)

The agentmodel tests (from #1074) now wait for the detached summary
call before they count the upstream's calls, with a time limit. Since
#1073 the summary call runs off the request path, so a fixed check
raced it and failed now and then in CI
(TestOpenAISummaryCallTargetIsUnchanged,
TestMalformedAgentModelTargetKeepsTheHostDefault). Test only.

Behavior change: none. Data dependence: none.

Fixes #1110.

Reviews: 2 offload review rounds (Claude backend). Round 2: both
approve at 0b3a6a0, which is the PR head.

Signed-off-by: Vitaly Zabershinsky <[email protected]>
Assisted-By: Claude Opus 5.5 <[email protected]>
amiddavid added a commit that referenced this pull request Nov 12, 2026
…tests (#1132)

The agentmodel tests wait for the detached summary calls before they
count them. Since #1073 the summary call runs off the request path, and
#1112's drain waits only for summaries already in flight, so "none
started yet" passed as "none in flight". Each test that counts summary
calls now waits through testutil.WaitForState (#1122) for the wanted
call, with a 30 s bound, after first waiting for any summary an earlier
test left running. The want-0 tests keep one read after the drain.

The failures were not reproduced locally (0 in 7,000 runs before and
after), so the race is inferred from the code. CI failed on these tests
3 times on 2026-11-12, on PRs that did not touch them.

Behavior change: none (one test file). Data dependence: none.

Fixes #1110.

Reviews: 2 offload review rounds (GLM). Round 2: both approve at
3ad22bd, which is the PR head.

Signed-off-by: DAVID AMID <[email protected]>
Assisted-By: Claude Opus 5.5 <[email protected]>
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.

perf: the savings accountant adds a body-size cost to every request before it goes upstream

2 participants