Skip to content

feat(accountant): Price a sent-back thinking block at its own token count - #1190

Merged
amiddavid merged 4 commits into
mainfrom
feat/1187-thinking-counts
Nov 17, 2026
Merged

amiddavid merged 4 commits into
mainfrom
feat/1187-thinking-counts

Conversation

@boazdavid

@boazdavid boazdavid commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Behavior change, needs a human developer's yes before merge.

  • Who: every user whose responses carry thinking blocks, when a component drops or shortens one. That includes models that strip thinking (Sonnet 4.5 and older). Those models bill 0 for a sent-back block, but the proxy passes the count, so a drop there books the count as saved. This is out of scope by the owner's decision.
  • Old: the saving of a dropped thinking block was its signature at 1 token for 250 bytes, about 12 tokens for a 3,000-byte signature.
  • New: the saving is the block's own thinking_tokens, about 1,000 tokens for that block. The text ratio of every request with thinking blocks gets more exact too: up to about 5% lower.
  • How to turn it off: no switch. Revert this PR. Pinning the accountant back to v0.1.2 also turns off the two changes below.

Two more behavior changes come with accountant v0.2.0. No tag holds accountant#81 alone, because these merged before it. Both change the figures for a thread whose model changes.

  • accountant#79, a model change that no operation reports. Who: users who switch models in a thread (the client switches, no plugin reports it). Old: row 1 booked the cache break as a charged break with no ChangeID, which the dashboard shows as an "ended change". One Sonnet-to-Opus switch on a host showed −$0.205 (42,716 tokens written). New: rows 1 and 3 book that break in the baseline (Cause = model_changed), so the charge is gone. A model change that a plugin reports is charged to that plugin's ChangeID.
  • accountant#82, a router's model setting. Who: users with a router that sets the model. Old: the router's model setting stayed active after the request that ended it, so a later switch by the client could be counted as a charged break. New: the setting ends on that request, and a later client switch goes to the baseline.
  • How to turn them off: pin the accountant back to v0.1.2. That turns off the thinking change too.

The human developer who says yes confirms all three changes.

Data dependence: metadata only. No change in level. A new table holds a 64-bit hash of each thinking signature and a token count. It holds no signature and no text. It is saved in the existing accountant state file. docs/data-dependence.md (Accountant savings row) is updated.

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_tokens plus 0 to 4 tokens. The old fixed price was 19 to 87 times too low. Closes #1187.

What changed

  • New library package thinkcount. It is not part of the proxy, so Cortex can use it too.
    • Table: a bounded map from accountant.OpaqueKey to 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 the thinking.signature and redacted_thinking.data of each block, and usage.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.
    • A count of 0, or more than 64 blocks in one response, is not recorded.
  • Proxy.
    • accParse builds both bodies with accountant.NewBodyCounted(..., table.Lookup).
    • On the chat route, streamRecOn feeds a Collector for 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_tokens collect nothing. The buffered paths use FromBody.
    • Usage.Thinking carries the result to finish. finish records it for a 2xx response that has usage.
    • The accountant state file gets an optional thinking field. 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.
  • Dependency. github.com/rossoctl/accountant moves 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. The package map in docs/design.md, and the data-dependence row (regenerated with make datadep).

How it was tested

  • thinkcount unit tests:
    • a stream fed in chunks of 1, 7 and 100 bytes, and whole;
    • spaced gateway JSON;
    • redacted_thinking;
    • a usage with no thinking_tokens;
    • the limits;
    • the table's lookup, eviction and JSON round trip;
    • NewBodyCounted with the table.
  • New proxy tests:
    • A drop of a thinking block saves its count. With no count it saves 12 tokens or fewer. With a recorded count of 1,000 it saves 1,000 plus the few tokens of the block's JSON wrapper.
    • The counts survive a save and restore of the state file.
    • The stream path reads a 300 KB signature from the middle of a stream, and the client gets the same bytes. With no accountant, nothing is collected.
    • Through the handler: a served JSON response and a served stream put the block in the table, and a 400 with the same body puts nothing. The JSON case fails without the round-1 fix.
    • The counts restore from a file past the snapshot's hour, and from a file whose snapshot is refused.
  • agentusage_test's every-field guard now sets Usage.Thinking. readAgentUsage keeps the field.
  • gofmt is clean, and go mod tidy -diff is clean. go vet and go test pass 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/modelinfo TestRateFillTableAndPrice (a float golden) fails on main too. I checked it on a clean checkout.
    • The bob-plugin Python suites, and context-guru-plugin (installer tests and a 10-minute timeout), are packages that this change does not touch. I did not check them on main.

Open questions

  • Expand rounds. A request with several upstream rounds records only the last round's blocks. Blocks from an earlier round fall back to the fixed price. That is rare, and it is the same rule that usage already follows.
  • Hosted mode. The table is one per proxy, not one per tenant. A key is the hash of a signature that only the tenant who received it holds, so a tenant can read no other tenant's count. Confirm that this is acceptable.
  • Models that strip thinking (Sonnet 4.5 and older). The proxy passes counts for them too. The accountant's guard drops counts that do not fit the bill, and fails opaque_tokens. Small counts next to a big bill still fit. This was left out of scope on purpose.

Technical notes

  • Cost on the stream path: one copy of each line into the collector's buffer. Lines with no data: prefix and other event types cost one prefix test and a few byte searches.
  • Table.Record splits one response's count between its blocks with accountant.SplitOpaqueTokens, by signature length.

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

…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 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 (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

  1. 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: false with thinking on. The proxy does not advertise expand, so the response goes through streamRecOn (proxy.go:2306). streamRecOn makes a Collector only when the content type is event-stream. So u.Thinking stays 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 use FromBody. This unbuffered JSON path is not covered.
    • Proof: proxy.go:2294 if !advertised { → 2306 h.streamRecOn(w, resp, tee, ag) for any content type. proxy.go:2835 if 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 holds content[].signature too. Only the advertised default: case (proxy.go:2419) reads JSON with FromBody.
    • Fix: after the loop, when think == nil && h.savings != nil && !sn.spliced(), set u.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 through streamRec and reads u.Thinking. Fix the comment.
  2. go.mod:10 — the accountant pin is a PR-branch pseudo-version, not a release

    • What fails: v0.1.3-0.20261117064714-a4f71add7e85 is the head of rossoctl/accountant#81. #81 merged at 2026-11-17T07:15:59Z as squash commit 7791ac73d931. So a4f71add is not on accountant main. No v0.1.3 tag exists yet (latest tag is v0.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…, head a4f71add…. 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.
  3. 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 through serve/finish and then checks the table. TestSavings_DroppedThinkingBlockSavesItsCount calls recordThinking directly. TestStreamReadsThinkingSignatures stops at u.Thinking. A later change that drops usage.Thinking on the way to finish (for example a new usage = … assignment in an expand round, proxy.go:2312 or 2442), or that inverts the gate, passes every test.
    • Proof: grep -rn recordThinking proxy/*_test.go finds only the direct calls in accountant_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.

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.Thinking holds full signature strings (up to 16 MiB per response) until finish. Nothing serializes or logs Usage (I checked proxy/*.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, !advertised pass-through, buffered JSON) and where usage is set for each.
  • streamRecOn and the sniffer (sniffMax, spliced, bytes).
  • readAgentUsage keeps Thinking (it copies base), 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_start usage.
  • 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 thinking field, 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, and walkOpaque decode 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.md package map entry. thinkcount imports no proxy package.
  • I did not run Go builds or tests (not approved, and Go is not installed).

@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 (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

  1. 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. finish records 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.md D16 (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.Record and recordThinking have no model check. accParseCounted always passes s.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.
    • 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.
  2. 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 a4f71add is on accountant main (main is 9 ahead, 0 behind). The repo has no v0.1.3 tag 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/accountant shows MERGED. gh api repos/rossoctl/accountant/tags shows no v0.1.3.
    • Fix: Tag the accountant release, then pin go.mod and go.sum to it.
  3. 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.FromBody only when h.savings != nil.
      • finish records only when usageOK && !c.rejected().
      • The Thinking field must survive the usage, usageOK = u hand-offs in serve.
        If someone moves the record above the usageOK check, or drops u.Thinking in a branch, no test fails.
    • Proof: grep -rn "recordThinking\|savings.thinking" proxy/*_test.go finds only accountant_thinking_test.go. That test calls recordThinking and streamRec directly. It never runs serve or finish. No test sends a 4xx response that has thinking blocks.
    • Fix: Add a test through Handler.ServeHTTP with a dashboard. Use one JSON 2xx response with a thinking block and thinking_tokens, and assert h.savings.thinking.Lookup finds it. Add one 4xx response with the same body, and assert that nothing is recorded. A stream case through serve is good too.

Non-blocking

  • thinkcount/read.go:154 and thinkcount.go:69 — a count of 0 is recorded. If the usage says thinking_tokens: 0 and the response has a signature, SplitOpaqueTokens gives 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 a message_start figure when no message_delta gives one. A block with a signature always cost more than 0 tokens. I suggest: treat Tokens == 0 as no count in Countable.
  • 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.Restore drops a good table.
  • Race at the end of a stream. The client gets message_stop before finish runs (in the defer). If the next request starts its begin before finish records, that request prices the block at the fixed price in the client body. Its end may 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 data of each redacted_thinking block. 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.md requires. A human developer must still say yes before merge.

What I checked

  • Read CLAUDE.md, the docs/design.md package table, and the full diff (16 files, one commit 6762ae4d).
  • Read the code around each change: serve response paths (proxy.go:2280-2470), streamRecOn, readAgentUsage (keeps Thinking), capture.finish (dashcapture.go:820-900), restore and save of the state file, and New (savings exist only with a dashboard).
  • Read the pinned accountant source in the Go module cache: NewBodyCounted, OpaqueKey, SplitOpaqueTokens, persist of OpaqueCounted/OpaqueTokens, and design D16.
  • Collector: traced line splitting over chunk edges, the \r trim, the limits, and the event matches. A text_delta that 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, MarshalJSON order (oldest first from head), and UnmarshalJSON (all-or-nothing parse, newest kept in a smaller table). The output is stable, so lastSaved still skips unchanged writes.
  • Fail-open: FromBody and 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]>
@boazdavid

Copy link
Copy Markdown
Collaborator Author

Replies to round 1 (both reviewers)

Fixed in 59aa418f, except the points marked "not changed".

Reviewer 1, finding 1: a JSON response on the pass-through path recorded no count. Fixed.

  • streamRecOn now makes a Collector for every response. In JSON mode it buffers the body, up to 8 MiB, and reads it at the end.
  • The comment "only an event stream can hold them" is gone.
  • Test: TestServedResponseRecordsThinkingCounts/json. With the old stream-only condition put back, that case fails (table has 0 false for the block). With the fix it passes.

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.

  • TestServedResponseRecordsThinkingCounts runs through Handler.Mux() with a dashboard, in three cases:
    • json: a 2xx JSON response puts the block in the table at 80.
    • stream: a 2xx stream puts the block in the table at 80.
    • rejected: a 400 with the same JSON body puts nothing.
  • The test reads h.savings.thinking after waitForRows, so it covers the gate in finish and the usage hand-offs in serve.

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.

  • A count of 0 (reviewer 2): fixed. Countable now refuses Tokens == 0.
  • Hosted eviction (both reviewers): fixed. A response with more than 64 blocks records nothing. The data-dependence row now says that one table serves all tenants.
  • 1-hour age and a failed restore (reviewer 2): fixed. The counts now restore from a file up to 24 hours old, and also when the snapshot is too old or is refused. Test: TestThinkingCountsRestoreOnTheirOwn.
  • redacted_thinking in the docs row (reviewer 2): fixed.
  • 1-hour row text (reviewer 1): covered by the 24-hour change above, and now in the row.
  • Signatures held in Usage until finish (reviewer 1): not changed. It is memory only, bounded by the 16 MiB cap, and it is released at the end of the request.
  • Race at the end of a stream (reviewer 2): not changed. The client reads message_stop before finish records. A request that starts in that gap prices the block at the fixed price in its client body, and at the count in its forwarded body only if finish has run by its end. A client sends its next turn after it has read the whole reply, and finish follows within milliseconds. The gap gives a lower saving for one request, never a higher one. Closing it would need recording before the last bytes are written, which changes the stream path.
  • Behavior change (both reviewers): named at the top of the PR. It waits for a human developer's yes.

Assisted-By: Claude (Anthropic AI) [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 (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 (Countable refuses Tokens == 0, with a test).
  • The 1-hour age, and a refused snapshot that dropped the counts: fixed (accThinkingMaxAge is 24 h, with TestThinkingCountsRestoreOnTheirOwn). I traced restore. 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_thinking in 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

  1. go.mod:10 — v0.2.0 brings 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.0 contains 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's ChangeID in rows 1 and 3.
      • #82: A router's model setting now leaves Active on the request that ends it. So a later client switch is not counted as a break.
        CLAUDE.md says 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.
    • Proof: gh api repos/rossoctl/accountant/compare/a4f71add…v0.2.0 lists 9bc4a7dd Merge pull request #79 and 4c0a73a4 Merge pull request #82, plus their 6 commits. gh pr view 79 and gh pr view 82 --repo rossoctl/accountant give 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 7791ac73 would still hold #79 and #82, because they merged before it.

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 FromJSON can never read (they have no top-level content of 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 (59aa418f fix(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.
  • 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.
  • Collector JSON mode: the 8 MiB cap clears the buffer and makes Result empty. The stream mode does not change. The Countable caps are applied in Table.Record.
  • The test helpers accHandler, accPost and waitForRows: the request goes to /anthropic/v1/messages with 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.0 tag, and the commits from v0.1.2 and from a4f71add to v0.2.0. I read the bodies of accountant #79 and #82.
  • I ran no Go build or test, as this review requires.

@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 (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. streamRecOn now makes a Collector for every response, and TestServedResponseRecordsThinkingCounts/json covers 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.0 is an annotated tag on 7791ac73, 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. finish calls recordThinking before c.rec.Record(e) (dashcapture.go:879 and 941), so waitForRows makes the table read safe. The 400 case covers the rejected() 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_thinking in the row: fixed, and I checked each one. The two "not changed" replies (signatures in Usage, the end-of-stream race) have correct reasons. I accept them.

Findings

  1. 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.2 to v0.2.0 the 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 no ChangeID, 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's ChangeID.
      • #82: a router's model setting now leaves Active on 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.)
    • Proof: gh api repos/rossoctl/accountant/compare/v0.1.2...v0.2.0 lists 98d7dc87, 09963366, 7f6afc99, 2fec3a8b, merge 9bc4a7dd (#79), 6b4a882b, 71b74378, merge 4c0a73a4 (#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.
  2. proxy/proxy.go:2838 — the catch-all route and /count_tokens now buffer each JSON response up to 8 MiB, and the result is never used

    • What fails: stream() (proxy.go:2897) calls streamRec → streamRecOn. The catch-all pass-through (proxy.go:739) and /count_tokens (counttokens.go:109) use stream(). When a dashboard is on, h.savings != nil, so streamRecOn now makes thinkcount.NewCollector(...) for these routes too. Any non-event-stream content type, or a missing one, picks JSON mode. JSON mode appends every byte to c.body up to maxJSON (8 MiB). Then Result() runs FromJSON, which parses the whole body with gjson when it holds the bytes thinking. These routes never call finish, 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:281 json: !strings.Contains(contentType, eventStream). read.go:286-292 append up to maxJSON. proxy.go:2897 func (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 serve calls (proxy.go:2306 and 2405) and not from stream(). Or, for JSON, read thinkcount.FromJSON(win) when !sn.spliced(), which costs no extra memory. Add a test that the catch-all route makes no collector.

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.
  • restore now 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 (59aa418f fix(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.
  • restore flow 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.
  • Collector JSON mode: chunked append, the 8 MiB limit sets broken and frees the buffer, Result with FromJSON. Countable with 0 and with 65 blocks.
  • Every caller of streamRecOn (serve at 2306 and 2405, streamRec, stream) and every caller of stream (proxy.go:739, counttokens.go:109).
  • finish order: recordThinking (879) before c.rec.Record(e) (941).
  • The accountant tag v0.2.0 (object, target commit) and compare 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]>
@boazdavid

Copy link
Copy Markdown
Collaborator Author

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 b2e3828e.

  • streamRecOn takes the collector as a parameter now. Only the chat route's pass-through call passes one, through thinkCollector, and only for an Anthropic response with an accountant.
  • stream() (the catch-all route and /count_tokens), streamRec and the non-Anthropic stream path pass nil.
  • This also fixes reviewer 1's non-blocking point: OpenAI, Responses and Bob replies are no longer buffered.
  • Test: TestStreamReadsThinkingSignatures now checks that stream() collects nothing, and that thinkCollector gives no collector with no accountant or for OpenAI. TestServedResponseRecordsThinkingCounts still passes for JSON, stream and rejected.

Non-blocking points.

  • The 1-hour sentence in the data-dependence row (reviewer 1): fixed. It now says "except for the thinking counts below".
  • A proxy version mismatch (reviewer 2): fixed in the row. It now says "the accountant library refuses it", and that a file with another proxy version gives back nothing.
  • Eviction by many responses (both reviewers): not changed. Both of you accept it, and the row names the shared table.
  • restore returns false for counts only (reviewer 2): not changed. Its one caller ignores the result, as you checked.

Assisted-By: Claude (Anthropic AI) [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 (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: merges 9bc4a7dd (#79) and 4c0a73a4 (#82) come before 7791ac73 (#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. streamRecOn now takes the collector as a parameter. Only the !advertised chat call (proxy.go:2306) passes h.thinkCollector(provider, resp). That gives a collector only when h.savings != nil and provider == bschemas.Anthropic. streamRec, stream() (catch-all at proxy.go:739, /count_tokens at counttokens.go:109) and the non-Anthropic SSE path (proxy.go:2405) pass nil. The test checks stream() collects nothing, and thinkCollector gives 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 the restore return 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 TestServedResponseRecordsThinkingCounts still 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 the thinkCollector doc comment. So godoc shows them as part of thinkCollector. Move them down to the streamRecOn comment at proxy.go:2834.
  • The PR body's "What changed" still says "streamRecOn feeds a Collector for every response". After b2e3828e that 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 (b2e3828e fix(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 b2e3828e fixes.
    • 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.
  • Every caller of streamRecOn (proxy.go:2306, 2405, streamRec at 2818) and every caller of stream() (proxy.go:739, counttokens.go:109).
  • thinkCollector (proxy.go:2827-2832), and the buffered FromBody path (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 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 (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 sets err, so the counts are not read.
  • Eviction by many responses, and restore returning 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 thinkCollector doc comment. So go doc shows a thinkCollector comment that starts with "streamRecOn is ...". The new streamRecOn comment no longer says what ag is. Move the two lines down to streamRecOn.
  • 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 (b2e3828e fix(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 in proxy/proxy.go (the two serve calls, 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.
  • Every caller of streamRecOn and stream, and every h.chat(...) route with its provider (proxy.go:574, 579, 597, 659).
  • The test changes: TestStreamReadsThinkingSignatures now calls streamRecOn with an Anthropic collector, checks that stream() collects nothing, and checks that thinkCollector gives nil with no accountant or for OpenAI. TestServedResponseRecordsThinkingCounts does not change and still goes through the Anthropic route.
  • The buffered path (proxy.go:2434) still uses FromBody when h.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]>
@boazdavid

Copy link
Copy Markdown
Collaborator Author

Round 3: both approve. Comment fix after the approval

be15cd51 moves the streamRecOn doc comment back onto streamRecOn (non-blocking note from both reviewers). The PR body's streamRecOn line is updated too (reviewer 1).

Output of scripts/release/approval-still-valid.sh 1190 b2e3828e:

approved: b2e3828e (base f3f108cd6bf9) patch-id bc68f92f20a1
head:     be15cd5171e7 (base f3f108cd6bf9) patch-id a45848b67daa
COMMENTS ONLY: b2e3828e..be15cd5171e7 changes only comment lines in .go and .sh files. The approval of b2e3828e still counts.

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]

@amiddavid

Copy link
Copy Markdown
Collaborator

Behavior change approved. The owner (David Amid) approved all 3 behavior changes of this PR (thinking-block price, accountant#79, accountant#82) in the integrator session on 2026-11-17: "1190 yes". The approval of b2e3828 still counts: be15cd5 changes only comment lines.

@amiddavid
amiddavid merged commit 230c8ea into main Nov 17, 2026
9 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 17, 2026
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.

Pass each thinking block's token count to the accountant

2 participants