Skip to content

Fix: Wrong savings in the accountant integration (review of #768) - #893

Closed
boazdavid wants to merge 25 commits into
mainfrom
fix/accountant-integration
Closed

boazdavid wants to merge 25 commits into
mainfrom
fix/accountant-integration

Conversation

@boazdavid

@boazdavid boazdavid commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

This PR fixes the wrong savings that a review of #768 found in the integration. It fixes 8 of the 9 blocking items (B1 to B8), and it deals with B9 and 2 of the 5 major items. Two items are not fixed. They are listed below.

go.mod pins accountant to d3b2135, the merge of PR 25 on accountant main. It holds the merged fixes for issues 9, 14, 20 and 21 (PR 22 and PR 23). Accountant main also checks usage now (0.05 to 2.0 tokens per byte, accountant#28) and prices a request with no client cache mark at the read tier (accountant#24). Six proxy test fixtures broke on that, and the last commit fits them. No production code changed for it.

Figures change. Savings, the keep-alive net and the Components verdict move for every user. Please confirm before merge.

What changed

Each item is one commit. Each has a test that fails without it.

Item Problem Fix
B1 The body hash included cache_control. Claude Code moves the mark each turn, so the library lost the cache boundary. The saving grew each turn: 2.0x, 2.9x, 3.7x. The hash leaves out the mark. The size keeps it.
B2 The declaration credit counted a removal the accountant already priced. Total saved was doubled. Both queries skip a request that has a toolfilter row priced by the accountant.
B3 A manual ping got its own credit, and the next request got a rescue for the same write. A manual ping stores no facts. It is still priced.
B4 The keep-alive gate dropped the rescue when the ping re-created an expired entry. Net was 12x too negative. For a row the accountant priced, a ping that wrote counts too.
B5 The replay cap removed negative rows. A loss was taken out, and the net went up. Only positive credit past the cap is removed.
B6 The Components first-removal verdict left out the costs. A losing component read as a gain. The verdict includes the costs. The tooltip says so.
B7 OpenAI Responses books no saving. The reason read acted_without_figure. A guard: the reason is now unsupported_wire. This is not support for the wire.
B8 A component whose requests all fell back showed a confident $0. It counts as unpriced and reads n/a. The unpriced text no longer blames the price list.
B9 The cachesplit credit was the whole cached read: $350.93 on $29.96 of cost. The cause was B1 and accountant#20. Both are fixed. A test covers it.
Major 1 Compute had no recover. computeSafe recovers. The request is recorded with no saving.

Also fixed since the first push

Item Fix
Major 2, state lost on restart The proxy saves the accountant thread state to <dashboard-db>.accountant-state.json every minute and at shutdown, and restores it at start. It fails open. Mode 0600. Accountant#13 made it possible.
OpenReadOnly + Request(id) fails The shim view exposes rowid.
ReplayMultiple ignores costs The numerator is the decomposed total, clamped at 0, as the replay cap computes it.
Dated or Bedrock model ids find no price The lookup strips the vendor prefix, the version suffix and the date and retries the exact name.
LastPing is the completion time The ping's At is TS minus the duration.
Accountant main Pinned to d31126b. Main now refuses usage outside 0.05 to 2.0 tokens per byte and prices a request with no cache mark at the read tier. Six test fixtures broke on that and were fitted. No production code changed for it.

Not fixed

  • Overview fallback_requests count (part of B8). It needs a new column on the full and the lean Overview path, each with a wide Scan that tests pin. It adds visibility, not correctness. The per-component column and the acc_fallback log line already show the fallback.
  • Major 4, saved tokens on a rejected request. I did not change it. saved_gross counts tokens the proxy removed and feeds many views (Overview, compaction episodes). The stored fact is true, and the dollar side already treats the row as unpriced. Zeroing it is a product decision.
  • Major 3, prices above 100k and 200k tokens. It is a pricing feature, and main has the same fault. Accountant#17 covers price tiers.
  • Major 5, a first request on a warm cache books nothing. It needs a trace that I do not have.
  • B7, the OpenAI Responses wire. A guard only. Every saving there is $0.
  • Gap measured from request start. Not a defect. The library measures both gaps from the start, as the provider measures the TTL (design section 5.2).
  • savingsTracker.onEnd. It is a test seam that five test files use. It costs one nil check.
  • Latency (10 ms on a 617 KB body) and the Components tab (2.4x on 100k requests). Not examined.

Things to check

  • B7 is a guard. Every saving on the Responses wire is still $0. The claim "every saving comes from the accountant" is still not true for it. docs/dashboard.md now says so.
  • B3 keeps the user's estimate as the one credit for a manual ping. The other fix would make it a measured figure. It needs to know at ping time whether the next request will read the entry, and it cannot.
  • B4 widens a gate. I measured it on 104,000 rows: 1.64 s before, 1.92 s after, for three Sessions calls. The old comment warns of a 197x slowdown from a wrong order. This is not that.
  • B6 leaves the summarize override alone. I could not show that SavedUSDCosts is the right number there.
  • The B9 test guards the combination of the two causes. With only the old hash, or only the old library, it passes. The test comment says so.
  • The review also suspected creditTurn and creditOpening in compactepisode.go. I ran both with a negative saving. They keep the cost. No change there.

How it was tested

  • dash, proxy, apply, keepalive and components pass. gofmt, go vet ./... and go mod tidy -diff are clean.
  • Three packages fail, and they fail the same way on the base commit 0f0d2d84: cmd/context-guru-proxy (2 preflight tests), internal/modelinfo (TestRateFillTableAndPrice, a float-format difference) and context-guru-plugin (installer and golden tests; it also hit the 10-minute test limit). I did not run the plugin package on the base.
  • I did not replay real Claude Code sessions. The review's replay harness is not in this repo. The tests use small fixtures of the same shape.

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

accBodies hashed each message's raw JSON with its cache_control. The
client moves its marks: Claude Code puts one on the newest block every
turn. The previous message then had new bytes on each request, the
library found no common prefix after the system block, and every token
it had saved earlier was priced at the write rate although the provider
read it. The booked saving grew each turn: 2.0x, 2.9x and 3.7x the real
value on turns 2 to 4 in the review of #768 (B1).

The hash now leaves out the mark, on the element and on its content
blocks. The size keeps it: the library checks the operations' bytes
against the bytes that went upstream.

Two tests cover the hash. A third drives three turns with a moving mark
through the tracker. Without the fix it prices the replay at the write
tier (54,185 tokens). With it, at the read tier.

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

The proxy reports each toolfilter removal to the accountant library, so
on a request it priced the removal is in baseline_cost_usd and in the net
saving. The measured declaration credit added it again: one 1,000-token
removal gave a row of $0.0001 and a total of $0.0002 (review of #768, B2).

Both declaration-filter queries now leave out a request that has a
toolfilter row with priced_by = 'accountant'. A request the library could
not price (priced_by = 'none') and a row from before the switch have
nothing in the baseline, so they keep the credit.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
A manual ping avoided a cache write, and that write is booked on its own
row as ManualSavedUSD. PingSavings also stored the ping's facts, so the
next real request credited the same write again as a library rescue. The
total counted it twice: $0.0200 booked, about $0.0096 true (review of
#768, B3).

A manual ping is still priced, so its cost stays on its row. Only the
facts are not stored.

This keeps the user's estimate as the one credit for a manual ping. The
other fix, to zero ManualSavedUSD and keep the library rescue, would make
that credit a measured figure. It needs to know at ping time whether the
next request will read the entry, and it cannot.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
The reachability gate asked for cache_read > 0 on the ping. A ping that
found the entry expired re-creates it: it writes, it does not read. The
accountant library credits the next request a rescue in that case,
because that request reads the entry the ping wrote. The gate zeroed the
credit and kept the ping's cost: the session read -$0.01146 where the
hand value is -$0.00094, 12x too negative (review of #768, B4).

For a row the library priced (a request_components row with
priced_by = 'accountant'), the test is now cache_read > 0 OR
cache_write > 0. The strict test stays for every other row. The legacy
write path credited a row on keepalive_pings alone, and a ping that only
re-created the entry earned it a credit it did not deserve. The old doc
comment explains why, and it is still true of those rows.

The credited-row guard stays first. Measured on 104,000 rows: 1.64 s
before, 1.92 s after, for three Sessions calls. The comment warns of a
197x slowdown from a wrong order, and this is not that.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
DeltaUSD removed every row past the cap. Since the accountant library
prices breaks and TTL premiums, a stored saving can be negative, and a
negative row past the cap is money that was spent. Removing it raised the
net: rows +1, +1, -2 gave a correction of +1.00 (review of #768, B5).

A negative row now counts, whether the cap is open or not. Only positive
credit past the cap is removed, which is what the cap is for.

The review also asked to check creditTurn and creditOpening in
compactepisode.go for the same sign problem. They do not have it: for a
SavedUSD of -3 both book the cost in FirstRemovalCreditUSD and keep it in
the net. It is labelled "first removal credit", which is a poor name for
a cost, but the number is right. No change there.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
NetUSDFirstRemoval is documented as what the proxy's /stats reports.
/stats reports saved_usd, which nets the costs a component caused: added
tokens and the breaks it left behind. The verdict was first removal minus
the component's own LLM spend, with no costs term, so a component that
loses money read as a gain: saved_usd -$0.0302 beside +$0.0113 (review of
#768, B6).

The same function already added the costs to SavedUSDDecomposed, so the
two totals disagreed. Both the general path and the replay-cap override
now include them, and the Components tooltip says so.

The summarize override is left as it is. It sets the split from its own
ledger and has no costs term; I could not show that SavedUSDCosts is the
right number there.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
The OpenAI Responses API keeps its conversation in input. accBodies hashes
messages and apply reports no operations on that wire, so the accountant
priced nothing there: the conservation check failed and every component
read priced_by = none with acted_without_figure. A reviewer found that all
Responses savings dropped to $0 and the PR text did not say so (review of
#768, B7).

This is a guard, not support. A request on the wire opens no record, the
event is marked, and PriceMode books no saving with the reason
unsupported_wire. Chat Completions and Messages are unchanged.

Support itself means hashing input, instructions and tools, reporting
operations from the Responses write path, and an OpenAI profile in the
library (accountant#10 and #17). That is a feature, not a fix, and it
cannot be checked here against a real stream.

docs/dashboard.md now says that every saving on this wire is $0, which the
claim "every saving comes from the accountant" had left out.

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

A request the accountant could not price books no saving. Its components
carry priced_by = 'none' and a stored saved_usd of 0, and they were
counted nowhere: saved_usd_unpriced_rows stayed 0, so the Components tab
printed a confident $0 for a component that had removed 5,000 tokens
(review of #768, B8).

A row of priced_by 'none' that removed content now counts as unpriced, so
the column reads n/a. A row that removed nothing does not, and a row the
library priced at $0 is still a measured $0.

The unpriced text blamed the operator's price list every time. For a
fallback that advice is wrong: the model may be priced, and setting
MODEL_PRICES changes nothing. The three messages now give both causes and
point at acc_fallback in the proxy log.

Not done: the review also asked for a fallback_requests count on
Overview. It needs another query on both the full and the lean path,
which TestLeanStatsMatchFullForTheSameWindow and the 20,000-request budget
test pin, and it adds visibility, not correctness. The per-component
column and the acc_fallback log line already say it.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
Takes accountant 38a32264 (PR 23's branch) for four fixes the review of
#768 needed in the library: the rescue no longer depends on what the
request wrote (#9), the ping extent ignores the ping's fresh input
(#14), a split is credited only when the system section changed (#20),
and B* follows the usage when the provider read the whole previous
extent (#21).

THIS COMMIT IS NOT ON accountant main. PR 22 (the cases) is still open,
and PR 23 merged into 22's branch, not into main. The pseudo-version
resolves because Go reads the commit from the repository, but it names a
commit that a squash or a force-push would drop. Re-pin to the merge
commit on main before this branch merges.

All dash, proxy, apply, keepalive and components tests pass on it,
including dash/accountant_play_test.go, which plays the library's shared
cases through this repo's pricing.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
The review of #768 (B9) found $350.93 of cachesplit_saved_usd on $29.96 of
cost in a replay of four Claude Code sessions, where the system snapshot
never changed and the true saving was $0. Two faults made it: the body hash
included the moving cache mark (B1), and the library credited a split with
no check that the system section changed (accountant#20).

Both are fixed on this branch. The test drives the replay's shape through
the tracker: a split every turn, an unchanged system block, a mark that
moves. It books a split effect in the state #768 merged in (103 tokens on
turn 3) and none on this branch.

I checked each fault alone: with only the old hash, or only the old
library, the test passes. Either fix is enough to keep the credit out of
this scenario, so the test guards the combination. The comment says so.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
The library asks the host to wrap Compute, and this repo's rule is to fail
open. The call ran in finish, outside the function the pre-forward
recover covers, so a panic would have lost the request's cg.request log
line and its dashboard row (review of #768, major 1). The reviewer could
not make the library panic, so this is a missing guard, not a fix for a
seen failure.

computeSafe wraps it. On a panic the request is recorded with no result
and PriceMode falls back with no_result. The panic is logged at error
level. Tests keep calling compute, so a panic still fails them.

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

Replaces the pin on the unmerged fix branch (38a3226) with main at d3b2135.
This is the pin the PR needed before it could merge.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
Accountant main now refuses usage outside 0.05 to 2.0 tokens per byte
(ratio_range, accountant#28) and prices a request with no client cache
mark at the read tier (accountant#24). Fixtures with a few hundred bytes
and thousands of tokens failed, and the absurd-usage cases now fall back
as "unpriced" with a failed ratio_range check, not "implausible_size".

- Scale the token counts of the savings, envelope and injection fixtures to their body sizes.
- Count the read tier when a test asks whether a change was priced.
- Re-derive the realistic-usage figure at the read rate (2e-7).
- The moving-cache-mark test now asserts that no break is reported.
  Without the B1 fix the library no longer prices the replay at the
  write rate, it reports a false break. Checked: fails without the fix.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
Takes accountant#30: Size gains optional Tokens and MediaBytes, and check 9
judges the media-adjusted ratio. The integration sets neither, so no
behavior changes. Proxy and dash tests pass.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
The library keeps each thread's active changes in memory, so every restart
dropped the replay saving of every live session until the next full
request (review of #768, major 2). Accountant#13 added Snapshot and Restore.

The handler restores from <dashboard-db>.accountant-state.json at New,
saves it every minute and at Close, and fails open: a missing, stale
(over 1h), corrupt or unwritable file starts the proxy empty. The file is
written through a temp file and a rename, mode 0600.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
OpenReadOnly shims the columns an older database lacks with a TEMP VIEW.
A view has no rowid, so Request(id) failed on such a file with "no such
column: rowid", and cg-cache-campaign opens databases this way (review of
#768, minor).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
ReplayMultiple was (first + replay) / first and ignored the costs the
accountant nets into saved_usd, so a component that loses money printed
"1.5x". The replay cap already divides the decomposed total. Use the same
numerator here and clamp it at 0 (review of #768, minor).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
The price lookup matched a map key against the whole id, so
claude-sonnet-5-20260101 and us.anthropic.claude-sonnet-5-v1:0 found no
price and no saving was booked. After the exact tiers, strip the vendor
prefix, the version suffix and the release date and look the bare name up
exactly. A different model (claude-sonnet-5-5) is not reached (review of
#768, minor).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
The keeper's report carries TS, the time the ping was recorded after its
response. The library measures the entry gap from the start of a ping, as
the provider measures the TTL. Map At to TS minus the duration (review of
#768, minor).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
An estimated request is one the accountant priced without knowing whether
a component broke the cache: a thread's first request, or the first after
a restart that lost the state. Its net can be too high, and only the
request detail said so (review of #768, minor).

Add estimated_requests to the full and the lean Overview, one SUM over the
stored price_estimated column in the aggregate that already runs, and a
line on the Preset card when it is above zero. The three stats goldens
gain the key.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
begin hashes the client body and end hashed the forwarded body again, even
when no component and no injection had changed a byte. On a 600 KB body
that is about 4 ms of the 8 ms the accountant costs on the request path
(review of #768, minor). Keep the client hash from begin to end and reuse
it when the bytes are equal. A request that was rewritten hashes both, as
before. The entry is dropped at end.

BenchmarkBeginEndUnchanged: 8.1 ms and 10.1 MB per request before, 4.0 ms
and 5.1 MB after. The rest is the library's NewBody walking each position
for media, which needs a fix in accountant.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
The price lookup reads the base rates only, so a model that charges more
above 100k or 200k prompt tokens is under-priced on those requests. Of the
bare Claude ids in LiteLLM's map, two carry such a tier. Applying it means
choosing the tier from each request's prompt size at 29 pricing call sites,
which moves every cost figure; that is left as a decision (review of #768,
major 3).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
no_result stands for four unrelated causes: no record was opened, the
response carried no usage, an expand loop ran several upstream rounds, or
Compute panicked. The acc_fallback line gives the reason only. Add a "why"
attribute for no_result, so the first request of a session that reads a
warm cache and books nothing (review of #768, major 5) names its cause the
next time it happens. I could not reproduce that case without the trace.

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

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: blocking

Findings

  1. proxy/accountant_savings.go:39 — the client-body cache leaks when the pre-forward recover fires after begin

    • What fails: a panic between accBegin (proxy/proxy.go:1449) and accEnd (proxy/proxy.go:1584) — for example in expand.Inject, adjudicate.Inject or applyToolDefer — is caught by the recover at proxy/proxy.go:1343. That recover calls cp.accDrop() (proxy/dashcapture.go:855), which sets c.accReq = nil but never deletes the s.clients entry. The entry holds the full client body in clientHash.raw (up to 32 MiB, 128 MiB for a compaction request). Nothing else removes it: end is the only caller of LoadAndDelete. Each such panic leaks one body for the life of the proxy, with no bound.
    • Proof: grep -rn "s.clients" proxy/*.go gives only Store at accountant_savings.go:39 and LoadAndDelete at :53. accDrop (dashcapture.go:854-859) touches only c.accReq. The recover comment at proxy.go:1346-1349 says the original goes upstream on this path, so end is never reached for this record.
    • Fix: give savingsTracker a drop(req) that does s.clients.Delete(req) and call it from accDrop (or from the recover) when c.accReq != nil.
  2. proxy/accountant_savings_body.go:43 — overwriting Pos[i].Bytes after NewBody leaves the library's cumulative byte table inconsistent

    • What fails: accountant.NewBody builds b.cum (its cumulative byte offsets) from the byte slices it is given — here the marks-stripped hashes. The code then sets b.Pos[i].Bytes to the wire size, so cum[i+1] - cum[i] no longer equals Pos[i].Bytes. The library's cumBytes uses cum when the body was built by NewBody, but sums Pos[j].Bytes for a body decoded from a snapshot (fromWireBody, persist.go:63). Three consumers read the broken number: the request's bytes-to-tokens ratio (engine/body.go:133), the span media split (engine/compute.go:278), and sawOriginal (engine/compute.go:481), which compares an operation's wire SizeBefore.Bytes against a cumBytes span that now excludes the cache marks. A splice whose removed range holds a marked message can therefore fail the sum check, and a request that should be priced books no saving. A restart also switches the same thread's ratio denominator from stripped bytes to wire bytes, because the restored body sums Pos.Bytes.
    • Proof: engine/fingerprint.go:64-70 sets Bytes: int32(len(p)) and builds cum from the same p in one pass; body.go:47-52 returns cum for a NewBody body and sums Pos[j].Bytes otherwise. apply/ops.go:173 builds every operation's sizes from wire message lengths, marks included. The marks are ~35 bytes each, so the ratio skew is small; the sawOriginal mismatch is exact (wire span minus stripped span).
    • Fix: rebuild cum from the wire sizes, or ask the library for an API that takes the hash bytes and the wire sizes together, so the two stay one unit.
  3. docs/data-dependence.md — not updated for the new accountant state file

    • What fails: the PR persists the accountant's thread state to <dashboard-db>.accountant-state.json, written every minute and at shutdown. The "Accountant savings" row (docs/data-dependence.md:229) still says the hashes "are held in memory only". CLAUDE.md makes the update mandatory for every PR that changes a feature's data dependence, with the reason in plain words and the behavior at each storage level (off, metadata only, everything). The PR states the dependence in docs/dashboard.md but not in the file the rule names.
    • Proof: git diff 0f0d2d84..HEAD -- docs/data-dependence.md is empty; the diff touches docs/dashboard.md only.
    • Fix: update the row: dashboard off = no file; dashboard on = the file holds hashes, sizes and ids (metadata), mode 0600, written beside the database; no level stores text.

Non-blocking

  • internal/modelinfo/litellm/litellm.go:328-340: decoBedrock and decoDate strip their suffix from every id, not only from a vendor-prefixed one. A model whose real name ends in -v1:0 or -YYYYMMDD could take another model's price. The exact-key lookup and the negative tests keep the risk small.
  • proxy/accountant_state.go: two proxies that share one dashboard database would write the same accountant-state.json and the last writer would win. Probably not a supported deployment; worth one sentence in the doc.
  • dash/overview.go:670 sums price_estimated over every row while the lean path gates on agent. The two agree only because a ping row never carries the flag.

What I checked

  • The full diff (25 commits, 43 files) and the code around each change: accBodies/withoutCacheMarks, the clients reuse in end, computeSafe, the state save/restore/keepSaved loop and Close, pingStart, the manual-ping facts change, the Responses-wire gate in chat and finish, noResultWhy, logFallback, accOverride ordering, the keep-alive reachability gate, the replay-cap cost rule and applyReplayLedgerToRow, the NetUSDFirstRemoval and ReplayMultiple formulas, the fallback/unpriced grouping in componentGroups/estimateFromGroups, estimated_requests on both overview paths, the read-only shim view, undecorate, declFilterNotPriced, the UI text, and the docs.
  • The accountant library at the pinned revision d31126bbb49b from the module cache: NewBody's hash/cum construction, cumBytes, sawOriginal, Trackers locking, and the snapshot wire format, to confirm findings 1 and 2 and that Snapshot/Restore are safe to call concurrently.
  • That PriceMode books no saving on the unsupported wire, that the replay-cap tests match the new arithmetic, and that the golden stats.json files only add a field (append-only contract kept).
  • No builds or tests were run, per the review rules.

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: blocking

Findings

  1. proxy/accountant_savings_body.go:43 — accBodies breaks the library's Body invariant: Pos[i].Bytes holds wire sizes, the internal cumulative byte table stays mark-free

    • What fails: a request where a message splice (collapse) removes a message that carries a cache_control mark, with at least one earlier operation, books no saving. The library's order guess for the splice is wrong, so its sum check fails, and PriceMode falls back with check_sum. Before this PR the same request priced normally.
    • Proof:
      • add (proxy/accountant_savings_body.go:30-33) hashes withoutCacheMarks(v.Raw) but records sizes = append(sizes, len(v.Raw)), the wire size with marks.
      • accountant.NewBody builds Pos[i].Bytes and the internal cum table from the mark-free bytes it is given. Its contract: cum[i+1] is the bytes of positions 0..i.
      • Lines 42-44 then overwrite b.Pos[i].Bytes = int32(sizes[i]) with the wire sizes. cum is not rebuilt, and it cannot be from outside the library.
      • Body.cumBytes prefers cum, so it returns mark-free totals. sectionBytes and Pos[i].Bytes are wire. The two disagree for every body that carries a cache mark.
      • sawOriginal (library internal/engine/compute.go:481) tests it.op.SizeBefore.Bytes == c.client.cumBytes(t)-c.client.cumBytes(f-1). The splice op's SizeBefore comes from apply/ops.go wireSizes, which counts wire bytes with marks. When the removed range holds a mark, the two sides differ by the mark bytes, so the test is always false. The library's own comment on that test says a wrong guess fails the sum check.
      • Before this PR, accBodies passed the raw wire bytes to NewBody, so cum and Pos.Bytes agreed. The change to a mark-free hash made the overwrite of Bytes correct for the sum check (which uses sectionBytes) and wrong for every cumBytes path.
      • No test covers it. The moving-mark tests (proxy/accountant_savings_test.go:227, 280) use rewrite ops only, no splice. The envelope tests' sectionDelta helper sums p.Bytes directly, so no test reads cumBytes.
    • Fix: keep the hash mark-free and the sizes wire, but build them consistently. Give the library a constructor that takes the hash input and the wire sizes together, or let NewBody exclude the marks itself. A rebuild of cum after the overwrite is not possible from this repo, because cum is unexported.
  2. proxy/accountant_savings.go:39 — a dropped request leaks its full client body in the tracker's map

    • What fails: a panic in the pipeline between accBegin and accEnd makes the proxy fail open and send the original body. The tracker keeps that request's client body in memory forever. Each such panic adds one entry. Nothing else removes it.
    • Proof:
      • begin stores the body: s.clients.Store(req, clientHash{raw: client, body: body, bps: bps}) (proxy/accountant_savings.go:39).
      • Only end removes it: s.clients.LoadAndDelete(req) (proxy/accountant_savings.go:53).
      • The panic path calls cp.accDrop() (proxy/proxy.go:1349) from the recover at proxy/proxy.go:1344. accDrop sets only c.accReq = nil (proxy/dashcapture.go:855-859). It does not touch s.clients.
      • accBegin runs at proxy/proxy.go:1449 and accEnd at proxy/proxy.go:1584. Both are inside the closure that the recover guards. A panic anywhere between them skips end.
      • raw is the full client body JSON. A large request holds hundreds of kilobytes. The library's trackers bound their own memory (the comment at proxy/accountant_savings.go:36 says so), but s.clients is host memory with no bound.
    • Fix: add a drop(req) method to savingsTracker that does s.clients.Delete(req), and call it from accDrop.
  3. docs/data-dependence.md:229 — the accountant row is now false: the state is also held on disk

    • What fails: the row says the hashes are "held in memory only". This PR adds proxy/accountant_state.go, which writes the tracker state to <dash-db>.accountant-state.json every minute and at shutdown, and restores it at startup. CLAUDE.md requires a PR that changes a feature's data dependence to update this doc in plain words and to have the row's decider confirm the change. The PR does neither.
    • Proof: save, restore and keepSaved in proxy/accountant_state.go; accountantStatePath in cmd/context-guru-proxy/main.go builds the file path; docs/data-dependence.md:229 still says "held in memory only". The diff does not touch docs/data-dependence.md.
    • Fix: update the row: what is written, where it lives, how long it lives, and what each storage level does. Get the decider's confirmation before merge.

Non-blocking

  • dash/keepalive.go: the libraryPriced probe needs a request_components row with priced_by = 'accountant'. A library-priced request with no component rows (empty pipeline, for example preset off) gets no match, so a cache_write rescue credit is zeroed. The saving is understated, not overstated.
  • internal/modelinfo/litellm/litellm.go: undecorate strips a -v\d+(:\d+)? suffix from any model id. A distinct model whose own name ends in that shape would be priced as the bare name. No test covers that shape.
  • dash/replaycap.go: applyReplayLedgerToRow recomputes ReplayMultiple without the math.Max(..., 0) clamp that decomposeFromGroups uses (dash/readvalue.go). A component whose costs exceed its credit can show a negative multiple.
  • proxy/accountant_state.go: Snapshot holds the trackers mutex while it marshals every thread, once per minute. On a busy proxy this briefly blocks request threads.
  • proxy/accountant_savings_body.go: withoutCacheMarks removes the element's own mark and the marks on its direct content blocks. A mark nested deeper, for example inside a tool_result's inner blocks, stays in the hash.
  • A request on the Responses wire whose model has no price logs acc_fallback reason "unpriced", not "unsupported_wire", because the price gate runs before accOverride. The dashboard flag is right; only the log reason is coarse.

What I checked

  • Read CLAUDE.md and docs/design.md in full.
  • Read the full diff 0f0d2d8..f95f439: 2115 lines, 43 files, 26 commits. Read the code around each change.
  • Traced the request path: proxy/proxy.go (chat closure, both recovers, accBegin/accEnd, the Responses-wire branch), proxy/dashcapture.go (finish, accDrop, noResultWhy, logFallback), proxy/accountant_savings.go, proxy/accountant_savings_body.go, proxy/accountant_wire.go, proxy/accountant_state.go, proxy/accountant_ping.go.
  • Read the accountant library at the pinned version v0.1.1-0.20261104153022-d31126bbb49b from the module cache: internal/engine/fingerprint.go, body.go, compute.go, persist.go. Verified which paths use Pos.Bytes (wire) and which use cumBytes (mark-free).
  • Read the dash changes: store.go read-only shim, schema.go additiveColumns, keepalive.go kaSavedGate, readvalue.go, replaycap.go, accountant_price.go, overview lean and full, toolsuggest.go.
  • Read internal/modelinfo/litellm undecorate and its tests; the state file path in cmd/context-guru-proxy/main.go; the new and changed tests and their helpers.
  • No Go build or tests were run. Live tests are not approved, and Go is not installed on this machine.

)

Both reviewers found the same three blocking problems.

- accBodies kept the library's cumulative byte table, built from the
  mark-free input, while Pos.Bytes held the wire size. A splice that removed
  a message with a cache mark failed the sum check (sawOriginal compares the
  operation's wire SizeBefore with that table), so the request booked no
  saving. The Body is now built again from its exported fields, which drops
  the table; every byte count the library reads is the wire size, as the
  operations' sizes are. The test passes with wire bytes hashed, fails with
  the old Body, and passes now.
- The client hash begin keeps for end leaked on the recovered panic before
  the forward. accDrop and finish now drop it.
- docs/data-dependence.md said the hashes are held in memory only; they are
  also saved to the state file. The row says so.

Also: the replay cap path clamps the replay multiple at 0 as the read path
does; undecorate strips a version suffix only from a vendor-prefixed id; the
long-context tier note names the models; two proxies must not share a
dashboard database.

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

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: approve

Findings

None.

Earlier findings, round 1

Both reviewers found the same three blocking items. All three are fixed in a311def. I checked each fix against the code and the library at the pinned revision.

  1. Client-body leak on the recovered panic — fixed. savingsTracker.drop (proxy/accountant_savings.go:31-35) deletes the map entry and is nil-safe. It runs from accDrop (proxy/dashcapture.go:860) and from a defer in finish (proxy/dashcapture.go:728), so a path that reaches neither end nor accDrop is covered too. The defer reads c.accReq before anything in finish can change it, and finish is nil-guarded above it. /compact's early finish (proxy/proxy.go:888) never opens a record, so drop(nil) is the no-op it is built to be. Test added (TestAccDropForgetsTheClientHash).
  2. Broken cum invariant in accBodies — fixed. The body is rebuilt from the exported fields (accountant.Body{Start: built.Start, Pos: built.Pos}, proxy/accountant_savings_body.go:47), which drops the unexported cum table. cumBytes then sums Pos[j].Bytes, the wire sizes, so it agrees with the operations' wire sizes and with a body restored from a snapshot (fromWireBody sets no cum either). I checked the library's Body struct: Start and Pos are the only exported fields, so nothing else is lost in the rebuild, and the empty-body edge (len(cum) == 0) still takes the summing branch. Test added (TestSavings_ASpliceOverAMarkedMessageKeepsTheSumCheck).
  3. docs/data-dependence.md not updated — fixed. The Accountant savings row now says the hashes are also saved to <dashboard-db>.accountant-state.json, what the file holds, how often it is written, that it is owner-readable only, ignored past one hour, and not written without the dashboard. Plain words, per the rule.

Non-blocking items from round 1, and their status:

  • undecorate stripping a version suffix from any id — fixed: the suffix is stripped only when a vendor prefix was present, and claude-sonnet-5-v2 is now a negative test (internal/modelinfo/litellm/chain_test.go:294).
  • Two proxies sharing one dashboard database — fixed in the doc (docs/dashboard.md:155).
  • applyReplayLedgerToRow missing the math.Max(..., 0) clamp — fixed, with a test (reviewer 2's item; I checked dash/replaycap.go:499 against decomposeFromGroups).
  • Reviewer 2's remaining non-blocking items are not addressed: the libraryPriced probe misses a request with no component rows (understates a rescue), Snapshot holds the trackers mutex once a minute, withoutCacheMarks leaves deeply nested marks in the hash, and a Responses request with no price logs unpriced instead of unsupported_wire. All four fail toward a missing or coarse figure, not a wrong one. I agree they can wait.

Non-blocking

  • The PR body states the new state file under "Also fixed since the first push", not at the top as CLAUDE.md asks for a data-dependence change. The data class does not change (metadata before and after) and the doc row is now accurate, so I do not block on the placement.
  • decoDate still strips a trailing 8-digit date from every id, vendor-prefixed or not. That is the intended dated-id form, and the exact-key lookup keeps the risk small.

What I checked

  • Last review: round 1, f95f439, 2026-11-04T16:55:33Z.
  • New commits read: 1 — a311def "fix(proxy): Review fixes for the accountant integration (round 1 of #893)".
  • Read in full: 2 reviews, 0 comments, 0 inline comments (from the three saved files; the comments and inline files are empty), and the PR body (66 lines).
  • New items since my last review: the fix commit (diff read in full, every changed file read around the change); reviewer 2's round-1 review, posted at 17:05:35Z — its three findings match mine, and I re-checked its non-blocking list as above.
  • The fix commit's own changes, as a first review: drop and both call sites (nil-safety, defer-time argument evaluation, the /compact early finish), the Body rebuild (library struct fields, cumBytes fallback branch, restored-body agreement), the undecorate vendor gate and its new negative test, the replay-cap clamp and its test, the two doc changes, and the three new tests.
  • No builds or tests were run, per the review rules.

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: approve

Round-1 findings

Both reviewers found the same three blocking problems in round 1. All three are fixed.

  1. Client-body leak on a dropped request — fixed.

    • savingsTracker.drop (proxy/accountant_savings.go) now deletes the map entry.
    • accDrop (proxy/dashcapture.go) calls it inside its nil guard, then clears c.accReq.
    • finish adds defer c.savings.drop(c.accReq) after its own nil guard. The defer reads the field at defer time, and nothing clears it before finish ends. accEnd runs before finish on every path, so the defer is a backstop, not the main path.
    • New test TestAccDropForgetsTheClientHash: one hash after accBegin, zero after accDrop, and a nil capture is safe.
  2. Body byte-table mismatch (Pos.Bytes wire, cum mark-free) — fixed.

    • accBodies (proxy/accountant_savings_body.go) now returns accountant.Body{Start: built.Start, Pos: built.Pos}. The cum table is dropped. I checked the library: Body has exactly Start, Pos and cum, and cumBytes sums Pos[j].Bytes when cum is absent. Every byte count is now the wire size, one unit everywhere.
    • This also matches the snapshot path. The library's fromWireBody restores only Pos. The number no longer changes across a restart.
    • New test TestSavings_ASpliceOverAMarkedMessageKeepsTheSumCheck covers it. I traced the library to confirm the test reaches the fault: the splice is a reported item, so sawOriginal does not take the active-item early return, and its size test compares the splice's wire SizeBefore against a cumBytes span. With the old body the two sides differ by the mark bytes. The order guess is then wrong and the sum check fails. The test asserts no failed checks.
  3. docs/data-dependence.md not updated — fixed.

    • The accountant row now states the state file in plain words: <dashboard-db>.accountant-state.json, readable by its owner only (mode 0600), written every minute and at stop, holds hashes, sizes, positions, ids and names, no message text, ignored when more than one hour old, and not written without a dashboard. Each statement matches the code.
    • The storage level is unchanged: metadata only at every level. The row names no "Decided by" person, so no decider confirmation is required by the table.

Non-blocking items from round 1

  • My undecorate suffix risk: fixed. The version suffix is now stripped only from an id that carried a vendor prefix. Price uses the undecorated name for an exact lookup only, and the last-resort CONTAINS scan uses the original tail. New negative test claude-sonnet-5-v2.
  • My two-proxy state file note: addressed. docs/dashboard.md now says two proxies must not share one dashboard database.
  • Reviewer 2's ReplayMultiple clamp: fixed. applyReplayLedgerToRow (dash/replaycap.go:499) clamps the numerator at 0 with math.Max, as decomposeFromGroups does. New test covers a loss.
  • My overview price_estimated gating note: not addressed. It was informational, and the two paths agree today.

Reviewer 2's remaining non-blocking items were not addressed. I checked each one. All remain non-blocking:

  • The keepalive libraryPriced probe needs a request_components row. A library-priced request with no component rows gets no rescue credit. The saving is understated, not overstated.
  • Snapshot holds the trackers mutex while it marshals, once per minute.
  • withoutCacheMarks misses a mark nested deeper than the direct content blocks.
  • A Responses-wire request with an unpriced model logs "unpriced", not "unsupported_wire".

The fix commit

  • I read the full diff and the code around each change, as a first review. I found no new defect.
  • The new tests were checked against the library source, not only read.
  • The PR body states at the top that the figures change and asks for confirmation. That meets the behavior-change rule in CLAUDE.md.

What I checked

  • Last review: round 1, sha f95f439e246c6e729634829fb0ea850b9b9e563b, submitted 2026-11-04T16:55:33Z.
  • New commits read: 1. a311defabcbd6d69d6d7c8541fd2be9f37465ad4 "fix(proxy): Review fixes for the accountant integration (round 1 of #893)".
  • Read in full: 2 reviews, 0 issue comments, 0 inline comments.
  • New items, and what I did with each:
    • The fix commit. Read the full diff and the code around each change. Read the library source again for the Body rebuild, the drop path, and the reach of the new tests.
    • Reviewer 2's round-1 review. Checked each finding and each non-blocking item against the code myself.
    • The PR body. Checked its claims against the code in this repo.
  • The accountant library at the pinned revision d31126bbb49b from the module cache: the Body struct, cumBytes, sawOriginal and its callers, and sectionBytes, to confirm fixes 1 and 2 and that the new tests fail on the old code.
  • No builds or tests were run, per the review rules.

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: approve

Findings

None.

Non-blocking

  • The comment on the new test TestSavings_ASpliceOverAMarkedMessageKeepsTheSumCheck (proxy/accountant_savings_test.go:364-368) names sawOriginal and the sum check as the path that fails. By my trace, sawOriginal returns false with both the old and the new Body in this scenario, because the mask makes the splice's SizeBefore differ from the client span in both. The check that actually fires with the old Body is conservation (library internal/engine/compute.go:1181): its want reads the client body's cumBytes, which the old Body understates by the mark bytes. The test still fails with the old Body and passes with the fix, so it guards the fix. Only the comment names the wrong check.
  • CLAUDE.md asks the person in the data-dependence row's "Decided by" to confirm the change before merge. The PR conversation shows no such confirmation yet.
  • Still open from round 1, not addressed, all understating or cosmetic: the kaSavedGate libraryPriced probe misses library-priced requests with no component rows; Snapshot holds the trackers mutex while it marshals; withoutCacheMarks does not reach marks nested in a tool_result's inner blocks; the acc_fallback log reason for an unpriced Responses request says "unpriced" rather than "unsupported_wire".

What I checked

  • Last review: round 1, f95f439, 2026-11-04T17:05:35Z.
  • New commits read: 1 — a311def "fix(proxy): Review fixes for the accountant integration (round 1 of #893)".
  • Read in full: 2 reviews, 0 comments, 0 inline comments (from the three files; the comment and inline files are empty).
  • New items since my last review: the commit a311def (pushed 19:13:05Z, after my review). No reviews, comments or inline comments arrived after my last review. I read the full new diff (237 lines, 11 files) and the code around each change.
  • Round-1 findings, mine and reviewer 1's (the same three):
    • Finding 1, the Body invariant (Pos.Bytes wire against a mark-free cum): fixed. accBodies now returns accountant.Body{Start: built.Start, Pos: built.Pos} (proxy/accountant_savings_body.go:48). The library's own comment on cum (internal/engine/fingerprint.go:32-34) says a Body made another way has none and cumBytes sums Pos[j].Bytes instead (internal/engine/body.go:47-56), so every byte count is now the wire size, as the operations' sizes are. A Body decoded from a snapshot has no table either, so a restart changes nothing.
    • The new test guards the fix. I traced it end to end. With the old Body, the conservation check fires: want := c.ratio.upTo(c.client, ...) - billed (compute.go:1196) reads the client body's cumBytes, short by the mark bytes (37 of about 3700, about 14 tokens at the test's ratio) against a tolerance of 3. With the rebuild it matches. See the non-blocking note about the test's comment.
    • Finding 2, the client-hash leak: fixed. drop (proxy/accountant_savings.go:31-37) deletes the entry and is nil-safe on both the tracker and the request. accDrop calls it (proxy/dashcapture.go:860), and finish defers it (proxy/dashcapture.go:728) for any path that reached neither end nor accDrop. end stays the normal remover; Delete is idempotent; the defer runs after computeSafe, which is the last reader. The new test TestAccDropForgetsTheClientHash counts the map entries before and after.
    • Finding 3, the data-dependence row: fixed. The row now says what the file holds (hashes, sizes, positions, ids and names), that it holds no text, that it is readable by its owner only, ignored when more than one hour old, and not written without a dashboard. Each claim matches the code in proxy/accountant_state.go.
  • The other changes in the commit: the replay-cap clamp now matches the read path, with a test that builds a loss and asserts a non-negative multiple; undecorate strips a -vN(:M) suffix only from an id that carried a vendor prefix, with a new negative case claude-sonnet-5-v2; docs/dashboard.md adds the two-proxies warning and names the tiered models — I checked those claims against the vendored LiteLLM data (claude-haiku-5-5 100k tier, input at 5x; claude-sonnet-4-5 200k at 2x; claude-sonnet-5, claude-opus-5, claude-fable-5 carry no prompt-size tier).
  • No Go build or tests were run. Live tests are not approved, and Go is not installed on this machine.

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: approve

Findings

None new. Both reviewers found the same three blocking problems in round 1. All three are fixed.

  1. Round 1, finding 1 (Body invariant: Pos.Bytes wire, cumulative table mark-free) — fixed.

    • accBodies now returns accountant.Body{Start: built.Start, Pos: built.Pos} (proxy/accountant_savings_body.go:48). The literal copies the two exported fields and drops the unexported cum table. Body.cumBytes then sums Pos[i].Bytes, the wire sizes, as the library does for a body decoded from a snapshot (engine/body.go:47-55, persist.go fromWireBody). Every byte count now agrees with the operations' wire sizes, before and after a restart. Body has no other exported field, so nothing is lost. Media travels inside Pos and stays.
    • The new test (proxy/accountant_savings_test.go, TestSavings_ASpliceOverAMarkedMessageKeepsTheSumCheck) covers a splice over a marked message. I checked by hand that it fails at the round-1 head: with the stale table, the conservation check compares a client token total built from mark-free bytes against operation deltas in wire bytes. The mark is about 37 bytes; at the test's ratio (30 tokens over 76 forwarded bytes) that is about 15 tokens, over a tolerance of 3. With the fixed body the two sides match exactly. The test guards the fix.
    • One wording note, non-blocking: the test's comment says "the sum check fails". In this fixture the check that fires is conservation. The sawOriginal comparison returns the same answer under both bodies here, because the mask's size change (about 3591 bytes) is much larger than the mark.
  2. Round 1, finding 2 (client hash leaked on the recovered panic) — fixed.

    • savingsTracker.drop deletes the map entry and is nil-safe on both the tracker and the request (proxy/accountant_savings.go:30-37). accDrop calls it (proxy/dashcapture.go:860). finish also defers it, so any path that reached neither end nor accDrop is covered (proxy/dashcapture.go:728). On the normal path end already removed the entry, and Delete on a missing key is a no-op. The deferred call reads c.accReq at statement time; nothing sets it later in finish. The new test TestAccDropForgetsTheClientHash counts the map entries before and after.
  3. Round 1, finding 3 (data-dependence row said "in memory only") — fixed.

    • The row now says, in plain words: the file's name and place, owner-only permissions, written every minute and at stop, loaded at start, what it holds (hashes, sizes, positions, ids and names, no message text), the one-hour age limit, and that no dashboard means no file. Each claim matches proxy/accountant_state.go and accountantStatePath in cmd/context-guru-proxy/main.go.
  4. Non-blocking items the author took — fixed.

    • applyReplayLedgerToRow now clamps ReplayMultiple at 0, with a test (dash/replaycap.go:499, dash/replaycap_test.go).
    • undecorate strips the Bedrock version suffix only from an id that carried a vendor prefix, with the claude-sonnet-5-v2 negative test (internal/modelinfo/litellm/litellm.go:343-350).
    • docs/dashboard.md says two proxies must not share one dashboard database.

Non-blocking

  • Carried from round 1, still open: the kaSavedGate libraryPriced probe needs a request_components row, so a library-priced request with no component rows (empty pipeline, preset off) loses a cache_write rescue credit. Understates, never overstates.
  • Carried from round 1, still open: Snapshot holds the trackers mutex while it marshals every thread, once per minute.
  • Carried from round 1, still open: withoutCacheMarks does not reach a mark nested inside a tool_result's inner blocks.
  • Carried from round 1, still open: a request on the Responses wire whose model has no price logs acc_fallback reason "unpriced", not "unsupported_wire".
  • New, small: decoVendor lists the regions us|eu|apac|global only. LiteLLM's own data carries au. and jp. keys (the test fixture has au.anthropic.claude-sonnet-4-6). An au. or jp. Bedrock id with a version suffix is not undecorated and stays unpriced. Fail-open direction.
  • New, cosmetic: docs/dashboard.md names claude-sonnet-4 and claude-sonnet-4-5 as 200k-tier models. In the bundled test fixture claude-sonnet-4-5 carries no above-100k or above-200k field. The live data may differ; the note is a caveat only.

What I checked

  • Last review: round 1, f95f439, 2026-11-04T17:05:35Z.
  • New commits read: 1 — a311defa fix(proxy): Review fixes for the accountant integration (round 1 of #893).
  • Read in full: 2 reviews, 0 comments, 0 inline comments (from the three files; the comments and inline files are empty).
  • New items since my last review: the commit a311defa, pushed after my review. I read its full diff (237 lines, 11 files) and each changed file around the change. Reviewer 1's round-1 review (2026-11-04T16:55:33Z, before my last review) I read in full this round; we found the same three blocking findings, and I checked each fix myself rather than taking them on trust.
  • Verified the Body fix against the library at the pinned version v0.1.1-0.20261104153022-d31126bbb49b: the Body struct's exported fields, cumBytes's fallback sum, fromWireBody, opSpans, sawOriginal, apply/undo, forwardPositions, and the checks/conservation code, to confirm the fix and to trace the new test by hand.
  • Verified the leak fix: drop, accDrop, the finish defer, and the nil-safety of each.
  • Verified the doc row against proxy/accountant_state.go and accountantStatePath.
  • Checked undecorate's new gating and its tests, the replay-cap clamp and its test, and the two docs changes. Checked the region-prefix gap against the test fixture's own keys.
  • No Go build or tests were run. Live tests are not approved, and Go is not installed on this machine.

- undecorate also strips the au., jp. and us-gov. region prefixes of a
  Bedrock id, which LiteLLM's own keys carry.
- The long-context note says where Sonnet 4 and 4.5 carry a tier: on the
  Bedrock, Vertex and Azure listings, not on the Anthropic API ids.
- The comment of the splice test names the check that fires (conservation).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
This was referenced Nov 4, 2026
@boazdavid

Copy link
Copy Markdown
Collaborator Author

Extended review of #893 (end to end, A/B, feature and library checks)

This is on top of the two-reviewer rounds (both approve at a311defa). Five reviewers worked in parallel: library, code, feature runs, A/B on identical traffic, and a check of each fix. Reproduction details are in the issues linked below, each assigned to @boazdavid.

What holds up

What does not

Filed as issues in rossoctl/context-guru:

Issue Finding Status
#906 Default tail breakpoint: every request falls back (check_sum) and books no saving. Reproduced by me: dashboard 0 against a true 0.0736; tail off gives 0.0821
#907 Plausibility gate drops the whole result when removed tool declarations exceed message tokens. Reproduced by an agent
#908 Tool defer fails check_sum and conservation on every request. Reproduced by an agent
#909 In-session cachesplit credit is $0 on the live path (pre-#768 credited it). Reproduced by an agent; line not found
#910 Summarize books its model cost but no saving (ops_dropped). Reproduced by an agent; documented
#911 B2 fix also drops measured tool-filter requests and tokens; items no longer sum to the total. From the code, not run
#912 B4 gate needs a component row, so a keep-alive-only setup still loses the rescue. Existing test fails without the row
#913 B3: next request after a manual ping may be classified cold. From the code, not measured
#914 Major 4: saved tokens booked on a rejected request. Reproduced by an agent
#915 Major 5: first request on an unseen warm cache books a baseline about 2x too high. Reproduced by an agent
#916 /api/stats cache key rounds the window to 30 s. Reproduced by an agent
#917 State file has no proxy-side version; save not durable; nested cache_control moves the hash. From the code
#918 No recover around keep-alive ping pricing. From a grep; no panic triggered
#919 Two models of keepalive_saved_usd (library and SQL gate). Argued from the code
#920 First request of a session books cost $0, so total cost under-counts the bill. Agent, synthetic trace; may be an artifact

Filed in rossoctl/accountant: #40 (mixed 1h/5m TTL), #41 (phase uses the current request's TTL), #42 (images skew the ratio; undetected media shapes), #43 (extent is O(n^2) with no breakpoints), #44 (validation gaps).

Already tracked, not refiled: #899 (Responses wire), #901 and #892 (price tiers), accountant #36 and #39.

Suggestion on merging

#906 to #909 are each a way for a default or common configuration to report less saving than it earns. None inflates a figure. Whether to merge #893 first and fix them after is a decision for the maintainers. The PR text asks for a human yes on the changed figures, and nothing on this PR shows one. CLAUDE.md also asks the person named in the docs/data-dependence.md row to confirm.

Limits of this review

  • No real traffic. There is none on the reviewing machine, so the A/B trace and every scenario are synthetic. The fake upstream models the provider's cache rules; it is not the provider.
  • B1 was verified at unit level only. Three mark shapes through the proxy did not show the 2.0x/2.9x/3.7x growth. B3 and B9 were not driven end to end.
  • Not covered: Bedrock and Vertex shapes, the 1h tier in a live run, thinking sessions, agentdiet/mask/collapse/coref, the browser UI itself (the API values behind each view were checked), a restart with SIGKILL beyond one short session, and the Components tab at 100k rows.
  • Latency: the accountant adds about 5 ms at 247 KB and 15 ms at 657 KB over the build without it (p50), and about 15 to 20% CPU. RSS is the same.
  • Test failures: the three packages that fail on the base (cmd/context-guru-proxy preflight, internal/modelinfo TestRateFillTableAndPrice, context-guru-plugin) fail here for environment reasons on macOS arm64 (bash 3.2 source <(...), FMA float format, /var against /private/var). The golden-text failures in context-guru-plugin were not explained.
  • Smaller review notes (the PR body names two pins, d3b2135 and d31126b, and says "two items are not fixed" while listing nine; PingStore.take is unused outside tests; B9's test needs both causes) are not filed.

@boazdavid

Copy link
Copy Markdown
Collaborator Author

Closed in favour of #930, the combined PR for the accountant integration. The accountant code that this PR fixes is no longer on main (#903 reverted #768), so it cannot merge. Its fixes are in #930. Nothing is lost: the branch stays. Assisted-By: Claude (Anthropic AI) [email protected]

@boazdavid boazdavid closed this Nov 8, 2026
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 8, 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.

1 participant