Repository navigation
feat(accountant): Price a sent-back thinking block at its own token count - #1190
Conversation
…ount The proxy now records the thinking_tokens of each response against the signature of each thinking block it made. When the client sends a block back, the accountant prices it at that count, not at the fixed price of 1 token for 250 bytes. - New package thinkcount: a bounded table by signature hash, and a reader for JSON responses and for streams as the bytes go by. - accParse builds bodies with accountant.NewBodyCounted. - The stream path reads signatures outside the sniffer window. - The table is saved in the accountant state file. - Pins accountant to the commit of rossoctl/accountant#81. Closes #1187. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
boazdavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (claude, user of @boazdavid) | Claude Code 2.1.241, aws/claude-opus-5-5[1m] | offload-review skill, @boazdavid's session | fresh | 1 of 2 | 1 of 2 | 6762ae4d6447 |
blocking |
Verdict: blocking
Findings
-
proxy/proxy.go:2832-2836 — a non-stream JSON response on the main pass-through path records no thinking count
- What fails: a client sends
stream: falsewith thinking on. The proxy does not advertise expand, so the response goes throughstreamRecOn(proxy.go:2306).streamRecOnmakes aCollectoronly when the content type isevent-stream. Sou.Thinkingstays empty for every JSON response on this path. When the client sends the block back, the accountant gives it the old fixed price (about 12 tokens, not about 1,000). The data-dependence row says "From each response it reads the signature of each thinking block", and the PR says only the buffered paths useFromBody. This unbuffered JSON path is not covered. - Proof: proxy.go:2294
if !advertised {→ 2306h.streamRecOn(w, resp, tee, ag)for any content type. proxy.go:2835if h.savings != nil && strings.Contains(resp.Header.Get("Content-Type"), "event-stream"). The comment at 2833 "Only an event stream can hold them on this path" is not correct: a JSON body on this path holdscontent[].signaturetoo. Only the advertiseddefault:case (proxy.go:2419) reads JSON withFromBody. - Fix: after the loop, when
think == nil && h.savings != nil && !sn.spliced(), setu.Thinking = thinkcount.FromJSON(win). The sniffer window is the whole body up to 64 KiB (sniffMax), which holds a normal response. Or give the collector a bounded JSON mode. Add a test that sends a JSON body throughstreamRecand readsu.Thinking. Fix the comment.
- What fails: a client sends
-
go.mod:10 — the accountant pin is a PR-branch pseudo-version, not a release
- What fails:
v0.1.3-0.20261117064714-a4f71add7e85is the head of rossoctl/accountant#81. #81 merged at 2026-11-17T07:15:59Z as squash commit7791ac73d931. Soa4f71addis not on accountantmain. Nov0.1.3tag exists yet (latest tag isv0.1.2). If the PR branch is deleted, a fresh module fetch outside the Go proxy cache can fail. The PR body itself says this must move to the release tag before merge. - Proof:
gh api repos/rossoctl/accountant/pulls/81→merged: true,merge_commit_sha: 7791ac73…, heada4f71add….gh api repos/rossoctl/accountant/tags→v0.1.2, v0.1.1, v0.1.0. - Fix: tag the accountant release that holds #81, pin it here, run
go mod tidy, and run the./dash/shared cases again on the tagged version.
- What fails:
-
proxy/dashcapture.go:876-881 — no test covers the record step in
finish- What fails: the new gate
usageOK && !c.rejected()decides which responses enter the table. No test runs a request throughserve/finishand then checks the table.TestSavings_DroppedThinkingBlockSavesItsCountcallsrecordThinkingdirectly.TestStreamReadsThinkingSignaturesstops atu.Thinking. A later change that dropsusage.Thinkingon the way tofinish(for example a newusage = …assignment in an expand round, proxy.go:2312 or 2442), or that inverts the gate, passes every test. - Proof:
grep -rn recordThinking proxy/*_test.gofinds only the direct calls inaccountant_thinking_test.go. No test sets a non-2xx status with a thinking response. - Fix: add one handler-level test: an upstream that returns a thinking response (JSON and SSE), then a second request that sends the block back, and assert the table holds the key (or that the drop saves about the count). Add a 4xx case that records nothing.
- What fails: the new gate
Non-blocking
- Behavior change: the PR names it at the top (who, old, new, how to turn off). It still needs a human developer's yes before merge, as CLAUDE.md says. I do not decide it.
- Hosted mode: one table serves all tenants. A tenant with its own upstream can send responses with up to 4,096 made-up signatures each, and evict the other tenants' 20,000 entries. That only returns their blocks to the fixed price on the dashboard, so the damage is small. A per-tenant table, or a per-response cap below 4,096, would close it.
- The state file is ignored after one hour (
accStateMaxAge). The thinking counts go with it, so after a long stop a returned block gets the fixed price. This is acceptable, but the row text could say it. Usage.Thinkingholds full signature strings (up to 16 MiB per response) untilfinish. Nothing serializes or logsUsage(I checkedproxy/*.go), so no text leaks. It is only memory.
What I checked
- The full diff of all 16 files, one commit (
6762ae4d). serve: every response path (spliced Anthropic SSE, buffered Responses SSE, other SSE,!advertisedpass-through, buffered JSON) and whereusageis set for each.streamRecOnand the sniffer (sniffMax,spliced,bytes).readAgentUsagekeepsThinking(it copiesbase), and the every-field test now sets it.Collector: line split across chunks,\r, the final line with no newline, escaped"signature_delta"inside text (no match, because the quote is escaped), limits,redacted_thinking,message_startusage.Table: ring eviction, update in place, int32 clamp, JSON round trip, malformed entry leaves the table unchanged, nil safety, the mutex on every method.- State file: optional
thinkingfield, restore is fail-open for a bad table, the snapshot still restores, no version bump needed. - The accountant source at the pinned version:
OpaqueKey,SplitOpaqueTokens,NewBodyCounted, andwalkOpaquedecode the request signature as a JSON string, which matches gjson.String()on the response side. - Data dependence: the row file and the generated page hold the same text. Kind stays
metadata, no level changes. docs/design.mdpackage map entry.thinkcountimports noproxypackage.- I did not run Go builds or tests (not approved, and Go is not installed).
boazdavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (claude, user of @boazdavid) | Claude Code 2.1.241, aws/claude-opus-5-5[1m] | offload-review skill, @boazdavid's session | fresh | 2 of 2 | 1 of 2 | 6762ae4d6447 |
blocking |
Verdict: blocking
Findings
-
thinkcount/thinkcount.go:69 and proxy/dashcapture.go:880 — the proxy passes counts for models that strip thinking, against the accountant's host rule.
- What fails: A Sonnet 4.5 (or older) response reports
thinking_tokens.finishrecords it. On the next request the block comes back. The provider bills 0 tokens for it, but the body prices it at its count.- If a component drops the block, the accountant books the full count (for example 1,000 tokens) as saved. The real saving is about 0.
- Every request that carries such blocks also gets a wrong text ratio, because the body holds tokens that the bill does not hold.
- Proof:
- accountant
docs/design.mdD16 (pinned version a4f71add): "Sonnet 4.5 strips thinking: a sent-back block adds 0 (8 of 8 comparisons)." - The same entry: "The guard does not catch every case. Counts that are small next to the bill still fit ... So a host does not pass counts for a model it knows strips thinking."
Table.RecordandrecordThinkinghave no model check.accParseCountedalways passess.thinking.Lookup. The capture knows the model (c.model, used at dashcapture.go:829).- The PR names this under "Open questions" as out of scope. But the behavior-change header says "Who: every user whose model keeps thinking blocks (Opus 4.5+, Sonnet 4.6+)". Users of stripping models are affected too, and the header does not say so.
- accountant
- Fix: Record no count (or do no lookup) for a model that strips thinking. A small model list in the proxy, or in
modelinfo, is enough. If the owner prefers to keep it out of scope, change the "Who" line so the human who says yes sees that Sonnet 4.5 and older figures change as well.
- What fails: A Sonnet 4.5 (or older) response reports
-
go.mod:10 — the accountant is pinned to an untagged pseudo-version.
- What fails: The PR's own text says: "Before merge, #81 must merge and this must move to its release tag." accountant#81 merged at 2026-11-17 07:15 UTC. The commit
a4f71addis on accountantmain(main is 9 ahead, 0 behind). The repo has nov0.1.3tag yet (tags:v0.1.2,v0.1.1,v0.1.0). The commit before this PR (f3f108c) pinned the accountant to a tag on purpose. - Proof:
gh pr view 81 --repo rossoctl/accountantshowsMERGED.gh api repos/rossoctl/accountant/tagsshows nov0.1.3. - Fix: Tag the accountant release, then pin
go.modandgo.sumto it.
- What fails: The PR's own text says: "Before merge, #81 must merge and this must move to its release tag." accountant#81 merged at 2026-11-17 07:15 UTC. The commit
-
proxy/proxy.go:2434 and proxy/dashcapture.go:879 — no test covers the new wiring from a served response to the table.
- What fails: These new rules have no test:
- The buffered path reads
thinkcount.FromBodyonly whenh.savings != nil. finishrecords only whenusageOK && !c.rejected().- The Thinking field must survive the
usage, usageOK = uhand-offs inserve.
If someone moves the record above theusageOKcheck, or dropsu.Thinkingin a branch, no test fails.
- The buffered path reads
- Proof:
grep -rn "recordThinking\|savings.thinking" proxy/*_test.gofinds onlyaccountant_thinking_test.go. That test callsrecordThinkingandstreamRecdirectly. It never runsserveorfinish. No test sends a 4xx response that has thinking blocks. - Fix: Add a test through
Handler.ServeHTTPwith a dashboard. Use one JSON 2xx response with a thinking block andthinking_tokens, and asserth.savings.thinking.Lookupfinds it. Add one 4xx response with the same body, and assert that nothing is recorded. A stream case throughserveis good too.
- What fails: These new rules have no test:
Non-blocking
- thinkcount/read.go:154 and thinkcount.go:69 — a count of 0 is recorded. If the usage says
thinking_tokens: 0and the response has a signature,SplitOpaqueTokensgives 0 to each block. The accountant treats 0 as a count ("A count of 0 is a count"), so the block is then priced at 0 tokens. The Collector also keeps amessage_startfigure when nomessage_deltagives one. A block with a signature always cost more than 0 tokens. I suggest: treatTokens == 0as no count inCountable. - proxy/accountant_state.go:116 — the table follows the snapshot's 1-hour age rule. After a restart of more than 1 hour, all counts are lost. A block can come back later than 1 hour (a cold cache still bills it as fresh input). The counts are keyed by a hash, not by time, so they could be restored on their own. Also, a failed
Trackers.Restoredrops a good table. - Race at the end of a stream. The client gets
message_stopbeforefinishruns (in the defer). If the next request starts itsbeginbeforefinishrecords, that request prices the block at the fixed price in the client body. Itsendmay then price the same block at its count in the forwarded body. The hashes match, so the effect is probably small. I did not prove a wrong figure. - Data-dependence row. It says the proxy reads "the signature of each thinking block". The code also reads and hashes the
dataof eachredacted_thinkingblock. Name it in the row so the reader sees all inputs. - Hosted mode. One table for all tenants. A tenant cannot read other tenants' counts, as the PR says. But one busy tenant can push other tenants' entries out of the 20,000-entry table. This is only a lower accuracy, not a leak.
- Behavior change. The PR names it at the top, as
CLAUDE.mdrequires. A human developer must still say yes before merge.
What I checked
- Read
CLAUDE.md, thedocs/design.mdpackage table, and the full diff (16 files, one commit6762ae4d). - Read the code around each change:
serveresponse paths (proxy.go:2280-2470),streamRecOn,readAgentUsage(keepsThinking),capture.finish(dashcapture.go:820-900),restoreandsaveof the state file, andNew(savings exist only with a dashboard). - Read the pinned accountant source in the Go module cache:
NewBodyCounted,OpaqueKey,SplitOpaqueTokens, persist ofOpaqueCounted/OpaqueTokens, and design D16. - Collector: traced line splitting over chunk edges, the
\rtrim, the limits, and the event matches. Atext_deltathat holds the text"signature_delta"cannot match, because JSON escapes its quotes. Even then, the index lookup finds no thinking block. - Table: the ring eviction, the same-key update,
MarshalJSONorder (oldest first fromhead), andUnmarshalJSON(all-or-nothing parse, newest kept in a smaller table). The output is stable, solastSavedstill skips unchanged writes. - Fail-open:
FromBodyand the Collector use only gjson and byte searches. I found no panic path. The client stream bytes do not change (the stream test also checks this). - Data dependence: the row file and the generated page change by the same sentence. Kind stays
metadata. No level changes. The table holds a 64-bit hash and a count, no text. - Checked accountant#81 state and tags with
gh. - I ran no Go build or test, as this review requires.
Review of #1190, round 1. - The pass-through path read thinking counts only from a stream. A JSON response there recorded nothing. The collector now buffers a JSON body, up to 8 MiB, and reads it at the end. - A handler test serves a JSON, a stream and a rejected response and checks the table. - A count of 0, or more than 64 blocks in one response, is not recorded. - The counts restore from a state file up to 24 hours old, and when the snapshot is refused. - Pin accountant v0.2.0, the release with accountant#81. - The data-dependence row names the redacted_thinking input, the caps, the shared table and the 24-hour restore. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Replies to round 1 (both reviewers)Fixed in Reviewer 1, finding 1: a JSON response on the pass-through path recorded no count. Fixed.
Both reviewers, finding 2: the accountant pin was not a tag. Fixed.
Both reviewers, finding 3: no test from a served response to the table. Fixed.
Reviewer 2, finding 1: counts for models that strip thinking. Not changed. The owner, @boazdavid, put this out of scope for this PR. As you suggested, the PR's "Who" line now says that Sonnet 4.5 and older figures change too, so the person who says yes sees it. Non-blocking points.
Assisted-By: Claude (Anthropic AI) [email protected] |
boazdavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (claude, user of @boazdavid) | Claude Code 2.1.241, aws/claude-opus-5-5[1m] | offload-review skill, @boazdavid's session | resumed | 2 of 2 | 2 of 2 | 59aa418fbec4 |
blocking |
Verdict: blocking
Status of round-1 findings
| Finding | Status | Note |
|---|---|---|
| R1 F1: a JSON response on the pass-through path records no count | Fixed | streamRecOn now makes thinkcount.NewCollector for every content type. JSON mode buffers up to 8 MiB and runs FromJSON at the end. TestServedResponseRecordsThinkingCounts/json covers it. accPost sends a request with no marker, so expand is not advertised and the response takes the !advertised → streamRecOn path. |
| R1 F2 / R2 F2: the accountant pin is not a tag | Fixed | go.mod:10 pins v0.2.0. The tag exists on rossoctl/accountant, and it holds #81 (7791ac73). But see new finding 1. |
| R1 F3 / R2 F3: no test from a served response to the table | Fixed | The new test runs Handler.Mux() with a dashboard: JSON 2xx, stream 2xx, and a 400. The 400 case tests the !c.rejected() gate, because finish gets usageOK true from a 4xx body that has usage (dashcapture.go:851 says so). The test reads the table after waitForRows, and finish records before the row is written. |
| R2 F1: counts are passed for models that strip thinking | Rejected by the owner, accepted | The owner put it out of scope. The "Who" line now says that Sonnet 4.5 and older are affected, and that a drop there books the count as saved. The human who says yes can see it now, and that was what I asked for. |
Non-blocking points from round 1:
- A count of 0: fixed (
CountablerefusesTokens == 0, with a test). - The 1-hour age, and a refused snapshot that dropped the counts: fixed (
accThinkingMaxAgeis 24 h, withTestThinkingCountsRestoreOnTheirOwn). I tracedrestore. A version mismatch or a bad file still restores nothing. A file from 1 to 24 hours old restores only the counts and returns false. The only caller (proxy.go:459) does not use the result. redacted_thinkingin the data-dependence row: fixed.- The race at the end of a stream: not changed. I accept the reason. The gap can only lower the saving of one request, and closing it would change the stream path.
- Hosted eviction: partly fixed. A response with more than 64 blocks records nothing. But 313 responses of 64 blocks still fill the 20,000-entry table. This only lowers accuracy, and the row now says that one table serves all tenants. No new finding.
Findings
- go.mod:10 —
v0.2.0brings two accountant behavior changes that are not about thinking, and the PR header does not name them.- What fails: The round-1 pin (
a4f71add) did not contain accountant #79 or #82.v0.2.0contains both. They change the figures the dashboard shows when a model changes:- #79: If no operation reports a model switch, rows 1 and 3 now put the cache break in the baseline (
Cause = model_changed). Before, row 1 charged the break as an "ended change". The #79 text says that one Sonnet-to-Opus switch on the host showed −$0.205 (42,716 tokens written) before. After the change, that charge is gone. A model change that a plugin made is now charged to that plugin'sChangeIDin rows 1 and 3. - #82: A router's
modelsetting now leavesActiveon the request that ends it. So a later client switch is not counted as a break.
CLAUDE.mdsays a change in what the proxy shows needs a human's yes, "even when the change looks like a side effect". It must be named at the top of the PR. The header names only the thinking change. Its "How to turn it off" line ("pin the accountant back to v0.1.2") would also revert #79 and #82, and the header does not say so.
- #79: If no operation reports a model switch, rows 1 and 3 now put the cache break in the baseline (
- Proof:
gh api repos/rossoctl/accountant/compare/a4f71add…v0.2.0lists9bc4a7dd Merge pull request #79and4c0a73a4 Merge pull request #82, plus their 6 commits.gh pr view 79andgh pr view 82 --repo rossoctl/accountantgive the old and new behavior quoted above. The PR comment says "It also holds #82". It does not name #79, and no text names the change in figures. - Fix: Add #79 and #82 to the behavior-change header: who (users whose model changes in a thread, by the client or by a router), the old and new figures, and how to turn it off. Then have the human who says yes confirm all three changes. Or pin a version that holds #81 only, if one exists. A tag on
7791ac73would still hold #79 and #82, because they merged before it.
- What fails: The round-1 pin (
Non-blocking
- proxy/proxy.go:2838 — JSON mode copies every JSON pass-through body, up to 8 MiB. This includes OpenAI, Responses and Bob replies, which
FromJSONcan never read (they have no top-levelcontentof Anthropic blocks). It is one extra copy for each concurrent request, on top of the sniffer's 64 KiB. You could make the collector only for the Anthropic provider, or stop when the first 64 KiB holds no"thinking". It is memory only, and it is bounded. - Data-dependence row. The text still says the file "is ignored ... when it is more than one hour old", and later says the counts are "restored from a file up to 24 hours old". A reader can understand both together. A short "except the thinking counts" after the first sentence would make it clear.
- Behavior change. The thinking change, the strip-model effect, and finding 1 all wait for a human developer's yes.
What I checked
- Last review: round 1,
6762ae4d6447b947893c689bcc257fb4be38c1a1, 2026-11-17T07:23:46Z - New commits read: 1 (
59aa418ffix(accountant): Record thinking counts on every response path) - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files)
- New items since my last review:
- Commit
59aa418f: I read the full diff (10 files) and the code around it. - The author's reply comment (2026-11-17T08:01:21Z): I checked each reply against the code. See the status table above.
- The PR body: the updated "Who" line. I checked it against my round-1 finding 1, and I accept it.
- Reviewer 1's round-1 review (07:23:35Z), which I read for the first time this round. I checked the status of its 3 findings and its non-blocking points.
- Commit
restore(accountant_state.go:110-155): every branch (missing file, older than 24 h, from 1 to 24 h, bad JSON, version mismatch, refused snapshot, good file), and the one caller.CollectorJSON mode: the 8 MiB cap clears the buffer and makesResultempty. The stream mode does not change. TheCountablecaps are applied inTable.Record.- The test helpers
accHandler,accPostandwaitForRows: the request goes to/anthropic/v1/messageswith a dashboard, and the 400 case parses usage. - The data-dependence row file and the generated page change by the same text. Kind stays
metadata. No level changes. - The accountant
v0.2.0tag, and the commits fromv0.1.2and froma4f71addtov0.2.0. I read the bodies of accountant #79 and #82. - I ran no Go build or test, as this review requires.
boazdavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (claude, user of @boazdavid) | Claude Code 2.1.241, aws/claude-opus-5-5[1m] | offload-review skill, @boazdavid's session | resumed | 1 of 2 | 2 of 2 | 59aa418fbec4 |
blocking |
Verdict: blocking
Earlier findings
- Reviewer 1, finding 1 (JSON on the pass-through path): fixed.
streamRecOnnow makes aCollectorfor every response, andTestServedResponseRecordsThinkingCounts/jsoncovers it. See new finding 2 for a side effect. - Reviewer 1, finding 2 and reviewer 2, finding 2 (pin is not a tag): fixed.
v0.2.0is an annotated tag on7791ac73, the merge of accountant#81 (compare 7791ac73...v0.2.0→identical). See new finding 1 for what else the tag brings. - Reviewer 1, finding 3 and reviewer 2, finding 3 (no test from a served response to the table): fixed. The new test runs
Handler.Mux()with a dashboard.finishcallsrecordThinkingbeforec.rec.Record(e)(dashcapture.go:879 and 941), sowaitForRowsmakes the table read safe. The 400 case covers therejected()gate. - Reviewer 2, finding 1 (models that strip thinking): rejected by the author. The owner put it out of scope, and the "Who" line now names Sonnet 4.5 and older. I accept this. The human who says yes now sees the case.
- Non-blocking points: count of 0, 64-block cap, 24-hour restore,
redacted_thinkingin the row: fixed, and I checked each one. The two "not changed" replies (signatures inUsage, the end-of-stream race) have correct reasons. I accept them.
Findings
-
go.mod:10 — v0.2.0 also brings two accountant changes to model-switch pricing, and the PR header does not name them
- What fails: from
v0.1.2tov0.2.0the accountant gains #79 and #82, not only #81.- #79: when a client switches models and no operation reports it, rows 1 and 3 now book the cache break in the baseline (
Cause = model_changed). Before, row 1 booked it as a charged break with noChangeID, which the dashboard shows as an "ended change". The #79 text gives one example host row: −$0.205 (42,716 tokens written) for one Sonnet-to-Opus switch. That row goes away. A plugin's model change is now charged to that operation'sChangeID. - #82: a router's
modelsetting now leavesActiveon the request that ends it. A later client switch then goes to the baseline, and is not counted as an ended change.
These change the savings figures for every user who switches models or uses a model router. CLAUDE.md says the PR must name such a change at the top, and a human developer must say yes. The header names only the thinking-block change. The reply comment says "It also holds #82", but the header does not, and it does not name #79 at all. (#79 was already in the round-1 pin. I missed it in round 1.)
- #79: when a client switches models and no operation reports it, rows 1 and 3 now book the cache break in the baseline (
- Proof:
gh api repos/rossoctl/accountant/compare/v0.1.2...v0.2.0lists98d7dc87,09963366,7f6afc99,2fec3a8b, merge9bc4a7dd(#79),6b4a882b,71b74378, merge4c0a73a4(#82), and the #81 commits. The PR body's "How to turn it off" says "pin the accountant back to v0.1.2", which would also undo #79 and #82. - Fix: add #79 and #82 to the behavior-change header, with who, old, new and how to turn off. Or pin a tag that holds only #81, and move #79 and #82 to their own PR.
- What fails: from
-
proxy/proxy.go:2838 — the catch-all route and
/count_tokensnow buffer each JSON response up to 8 MiB, and the result is never used- What fails:
stream()(proxy.go:2897) callsstreamRec→streamRecOn. The catch-all pass-through (proxy.go:739) and/count_tokens(counttokens.go:109) usestream(). When a dashboard is on,h.savings != nil, sostreamRecOnnow makesthinkcount.NewCollector(...)for these routes too. Any non-event-streamcontent type, or a missing one, picks JSON mode. JSON mode appends every byte toc.bodyup tomaxJSON(8 MiB). ThenResult()runsFromJSON, which parses the whole body with gjson when it holds the bytesthinking. These routes never callfinish, so the result is dropped. Before this commit the extra memory on these routes was the sniffer's 2 × 64 KiB. Now it is up to 8 MiB for each in-flight response. For example, a batch-results download or a file fetch through the catch-all holds 8 MiB until the response ends. On a hosted proxy this happens for each tenant's concurrent requests. - Proof: proxy.go:2837-2839
if h.savings != nil { think = thinkcount.NewCollector(resp.Header.Get("Content-Type")) }. read.go:281json: !strings.Contains(contentType, eventStream). read.go:286-292 append up tomaxJSON. proxy.go:2897func (h *Handler) stream(...) { return h.streamRec(w, resp, nil) }. - Fix: make the collector only on the chat routes. For example, pass a flag from the two
servecalls (proxy.go:2306 and 2405) and not fromstream(). Or, for JSON, readthinkcount.FromJSON(win)when!sn.spliced(), which costs no extra memory. Add a test that the catch-all route makes no collector.
- What fails:
Non-blocking
- accountant_state.go:131-133: a file with another proxy version still drops the thinking counts. The row says the counts restore "also when the rest of the state is too old or is refused". A version mismatch is a refusal too. The behavior is reasonable, but the row text could say "refused by the accountant library".
- The 64-block cap stops one response from flushing the table. A tenant can still flush it with many responses (20,000 / 64 ≈ 313 responses). The damage is the same as before: other tenants' blocks go back to the fixed price. The row names the shared table now, so the reader sees it.
restorenow returns false when it restores only the counts. The one caller (proxy.go:459) ignores the result, so nothing breaks.
What I checked
- Last review: round 1, 6762ae4, 2026-11-17T07:23:35Z
- New commits read: 1 (
59aa418ffix(accountant): Record thinking counts on every response path) - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files)
- New items since my last review:
- Reviewer 2's round-1 review (07:23:46Z): I checked each of its findings and non-blocking points above.
- The author's reply comment (08:01:21Z): I checked each reply against the code and the accountant repo. One reply ("It also holds #82") led to new finding 1.
- Commit
59aa418f: read all 10 files in full diff, with the code around each change.
restoreflow at each age and error: missing file, older than 24 h, unreadable, not JSON, other proxy version, 1–24 h old, refused snapshot, bad thinking table.CollectorJSON mode: chunked append, the 8 MiB limit setsbrokenand frees the buffer,ResultwithFromJSON.Countablewith 0 and with 65 blocks.- Every caller of
streamRecOn(serveat 2306 and 2405,streamRec,stream) and every caller ofstream(proxy.go:739, counttokens.go:109). finishorder:recordThinking(879) beforec.rec.Record(e)(941).- The accountant tag
v0.2.0(object, target commit) andcompare v0.1.2...v0.2.0, plus the bodies of accountant#79 and #82. - PR body header after the edit ("Who" line now names models that strip thinking).
- Data dependence: the row file and the generated page change by the same text. Kind stays
metadata. No level changes. - I did not run Go builds or tests (not approved, and Go is not installed).
…outes Review of #1190, round 2. Since round 1, streamRecOn made a collector for every response, so the catch-all route and /count_tokens buffered JSON bodies up to 8 MiB for nothing. Now only the chat route passes a collector, and only for an Anthropic response. The data-dependence row says which file rules apply to the counts. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Replies to round 2 (both reviewers)Both reviewers, finding 1: v0.2.0 also brings accountant#79 and #82. Fixed in the PR header.
Reviewer 2, finding 2: JSON mode buffered bodies on routes that never use them. Fixed in
Non-blocking points.
Assisted-By: Claude (Anthropic AI) [email protected] |
boazdavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (claude, user of @boazdavid) | Claude Code 2.1.241, aws/claude-opus-5-5[1m] | offload-review skill, @boazdavid's session | resumed | 1 of 2 | 3 of 3 | b2e3828e804a |
approve |
Verdict: approve
Earlier findings
- Reviewer 1 round 2, finding 1 and reviewer 2 round 2, finding 1 (v0.2.0 also brings accountant#79 and #82): fixed. The PR header now names both, with who, old, new and how to turn them off. It says the human who says yes confirms all three changes. The author says no tag can hold #81 alone, because #79 and #82 merged before it. That matches
compare v0.1.2...v0.2.0: merges9bc4a7dd(#79) and4c0a73a4(#82) come before7791ac73(#81). I accept it. - Reviewer 1 round 2, finding 2 and reviewer 2 round 2, non-blocking (JSON mode buffers bodies on routes that never use them): fixed.
streamRecOnnow takes the collector as a parameter. Only the!advertisedchat call (proxy.go:2306) passesh.thinkCollector(provider, resp). That gives a collector only whenh.savings != nilandprovider == bschemas.Anthropic.streamRec,stream()(catch-all at proxy.go:739,/count_tokensat counttokens.go:109) and the non-Anthropic SSE path (proxy.go:2405) passnil. The test checksstream()collects nothing, andthinkCollectorgives nil with no accountant or for OpenAI. - Round-2 non-blocking points: the row now says "except for the thinking counts below", "the accountant library refuses it", and "A file with another proxy version gives back nothing". These match
restore. Eviction by many responses and therestorereturn value are not changed, and I accept both reasons. - All round-1 findings stay fixed. I checked that the new commit does not undo them: the JSON and stream cases of
TestServedResponseRecordsThinkingCountsstill go through proxy.go:2306, which now passes the collector.
Findings
None.
Non-blocking
- proxy.go:2821-2826: the two old doc lines of
streamRecOn("streamRecOn is streamRec for a chat route. ag is ...") now sit at the top of thethinkCollectordoc comment. So godoc shows them as part ofthinkCollector. Move them down to thestreamRecOncomment at proxy.go:2834. - The PR body's "What changed" still says "
streamRecOnfeeds aCollectorfor every response". Afterb2e3828ethat is only Anthropic responses on the chat route. Update that line. - The provider check excludes Anthropic models served through another provider value (for example Bedrock or Vertex, if a route uses one). Those blocks keep the fixed price. The row says "from Anthropic responses", so this is named.
- Behavior change: the thinking change, the strip-model effect, and accountant#79 and #82 all wait for a human developer's yes, as CLAUDE.md says. My approve covers the code only.
What I checked
- Last review: round 2, 59aa418, 2026-11-17T08:03:57Z
- New commits read: 1 (
b2e3828efix(accountant): Collect thinking counts only on the Anthropic chat routes) - Read in full: 4 reviews, 2 comments, 0 inline comments (from the three files)
- New items since my last review:
- Reviewer 2's round-2 review (08:03:54Z): its finding 1 is the same as my round-2 finding 1, and the author fixed it in the header. I checked its JSON-mode non-blocking point, which
b2e3828efixes. - The author's round-2 reply (08:09:31Z): I checked each reply against the code, the row and the accountant commit order.
- The PR body header: I read the new #79 and #82 sections and the changed "How to turn it off" line.
- Commit
b2e3828e: I read all 4 files in full diff, with the code around each change.
- Reviewer 2's round-2 review (08:03:54Z): its finding 1 is the same as my round-2 finding 1, and the author fixed it in the header. I checked its JSON-mode non-blocking point, which
- Every caller of
streamRecOn(proxy.go:2306, 2405,streamRecat 2818) and every caller ofstream()(proxy.go:739, counttokens.go:109). thinkCollector(proxy.go:2827-2832), and the bufferedFromBodypath (proxy.go:2433), which still reads only bodies it has already buffered.- Data dependence: the row file text is in the generated page once, the same text. Kind stays
metadata. No level changes. - I did not run Go builds or tests (not approved, and Go is not installed).
boazdavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (claude, user of @boazdavid) | Claude Code 2.1.241, aws/claude-opus-5-5[1m] | offload-review skill, @boazdavid's session | resumed | 2 of 2 | 3 of 3 | b2e3828e804a |
approve |
Verdict: approve
Status of round-2 findings
| Finding | Status | Note |
|---|---|---|
R2 F1 and R1 F1: v0.2.0 also brings accountant #79 and #82, and the header does not name them |
Fixed | The PR header now has a section for each change, with who, old, new, and how to turn it off. It says that pinning v0.1.2 turns off all three changes, and that the human who says yes confirms all three. I accept the author's reason why no tag holds #81 alone: #79 (9bc4a7d) and #82 (4c0a73a) merged before #81 (7791ac7). My round-2 compare shows the same order. |
R1 F2 (and my round-2 non-blocking point): the catch-all route and /count_tokens buffer JSON up to 8 MiB for nothing |
Fixed | streamRecOn now takes the collector as a parameter. Only the chat pass-through call (proxy.go:2306) passes h.thinkCollector(provider, resp). The non-Anthropic stream path (proxy.go:2405) and streamRec pass nil, so stream() (proxy.go:739 and counttokens.go:109) collects nothing. thinkCollector returns nil when there is no accountant or when the provider is not Anthropic. Only POST /anthropic/v1/messages (proxy.go:597) serves with bschemas.Anthropic, so OpenAI, Responses and Bob (proxy.go:574, 579, 659) replies are no longer buffered. |
Non-blocking points from round 2:
- The 1-hour sentence in the data-dependence row: fixed ("except for the thinking counts below").
- Reviewer 1's version-mismatch point: fixed in the row ("the accountant library refuses it", and "A file with another proxy version gives back nothing"). This matches
restore: a version mismatch setserr, so the counts are not read. - Eviction by many responses, and
restorereturning false for counts only: not changed. Both reviewers accepted these, and I still accept them.
Earlier findings that are still settled: R2 round-1 F1 (models that strip thinking) stays out of scope by the owner's decision, and the header names it. All round-1 fixes stay in place in this commit.
Findings
None.
Non-blocking
- proxy/proxy.go:2821-2826 — a doc comment was left in the wrong place. The old lines "streamRecOn is streamRec for a chat route. ag is the agent that owns the route ..." now sit at the top of the
thinkCollectordoc comment. Sogo docshows athinkCollectorcomment that starts with "streamRecOn is ...". The newstreamRecOncomment no longer says whatagis. Move the two lines down tostreamRecOn. - Behavior change. The thinking change, the strip-model effect, and accountant #79 and #82 all wait for a human developer's yes, as the header says. My approve covers the code only, not that decision.
What I checked
- Last review: round 2,
59aa418fbec4ff55c7d1f6aea62b3ef4b7c420d7, 2026-11-17T08:03:54Z - New commits read: 1 (
b2e3828efix(accountant): Collect thinking counts only on the Anthropic chat routes) - Read in full: 4 reviews, 2 comments, 0 inline comments (from the three files)
- New items since my last review:
- Commit
b2e3828e: I read the full diff (4 files) and the code around it inproxy/proxy.go(the twoservecalls,streamRec,thinkCollector,streamRecOn,stream). - The author's reply to round 2 (2026-11-17T08:09:31Z): I checked each point against the code, the PR header and the accountant merge order. See the tables above.
- Reviewer 1's round-2 review (08:03:57Z): I checked its finding 1 (the same as my finding 1, now fixed), its finding 2 (the catch-all buffering, now fixed), and its 3 non-blocking points.
- The PR body: I read the new behavior-change sections for accountant #79 and #82, and the new "How to turn it off" lines.
- Commit
- Every caller of
streamRecOnandstream, and everyh.chat(...)route with its provider (proxy.go:574, 579, 597, 659). - The test changes:
TestStreamReadsThinkingSignaturesnow callsstreamRecOnwith an Anthropic collector, checks thatstream()collects nothing, and checks thatthinkCollectorgivesnilwith no accountant or for OpenAI.TestServedResponseRecordsThinkingCountsdoes not change and still goes through the Anthropic route. - The buffered path (proxy.go:2434) still uses
FromBodywhenh.savings != nil. That body is already in memory, so it costs no new buffer. - Data dependence: the row file and the generated page change by the same text. Kind stays
metadata. No level changes. - I ran no Go build or test, as this review requires.
Review of #1190, round 3 (non-blocking, both reviewers). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Round 3: both approve. Comment fix after the approval
Output of The code is approved. Merge waits for a human developer's yes on the three behavior changes in the header: the thinking count (including models that strip thinking), accountant#79 and accountant#82. Assisted-By: Claude (Anthropic AI) [email protected] |
Summary
The accountant now prices a thinking block that comes back at the thinking tokens of the response that made it. Measured on Opus 5.5 (accountant#77), a sent-back block bills its
thinking_tokensplus 0 to 4 tokens. The old fixed price was 19 to 87 times too low. Closes #1187.What changed
thinkcount. It is not part of the proxy, so Cortex can use it too.Table: a bounded map fromaccountant.OpaqueKeyto a count. It keeps at most 20,000 blocks and drops the oldest first. It is safe across goroutines, and it is saved as JSON.FromBody: reads thethinking.signatureandredacted_thinking.dataof each block, andusage.output_tokens_details.thinking_tokens, from a JSON response or a whole SSE stream.Collector: reads an SSE stream as the bytes go by. It parses only the data lines of 4 event types and has limits (4 MiB a line, 16 MiB of signatures, 4,096 blocks). In JSON mode it buffers the body, up to 8 MiB, and reads it at the end. Past a limit the response gives no count.accParsebuilds both bodies withaccountant.NewBodyCounted(..., table.Lookup).streamRecOnfeeds aCollectorfor an Anthropic response (thinkCollector). On a stream, signatures sit in the middle, outside the sniffer's head and tail window. The catch-all route and/count_tokenscollect nothing. The buffered paths useFromBody.Usage.Thinkingcarries the result tofinish.finishrecords it for a 2xx response that has usage.thinkingfield. A file without it restores with an empty table. The counts restore from a file up to 24 hours old, and also when the snapshot is too old or is refused.github.com/rossoctl/accountantmoves from v0.1.2 to v0.2.0, the release that holds feat: Price each thinking block at its own token count from the host accountant#81 (and feat(extract_llm): cold-cache sweep, tunable prompt, size triggering, and per-call observability #82).docs/design.md, and the data-dependence row (regenerated withmake datadep).How it was tested
thinkcountunit tests:redacted_thinking;thinking_tokens;NewBodyCountedwith the table.agentusage_test's every-field guard now setsUsage.Thinking.readAgentUsagekeeps the field.gofmtis clean, andgo mod tidy -diffis clean.go vetandgo testpass for./proxy/,./thinkcount/,./dash/(which plays the accountant's shared cases, the 6 new ones included),./internal/datadep/and./components/all/.go test ./...has failures outside this change:internal/modelinfoTestRateFillTableAndPrice(a float golden) fails onmaintoo. I checked it on a clean checkout.bob-pluginPython suites, andcontext-guru-plugin(installer tests and a 10-minute timeout), are packages that this change does not touch. I did not check them onmain.Open questions
usagealready follows.opaque_tokens. Small counts next to a big bill still fit. This was left out of scope on purpose.Technical notes
data:prefix and other event types cost one prefix test and a few byte searches.Table.Recordsplits one response's count between its blocks withaccountant.SplitOpaqueTokens, by signature length.Assisted-By: Claude (Anthropic AI) [email protected]