Skip to content

Feat: Re-land the accountant pricing of proxy savings (#768) with the #893 fixes - #923

Closed
boazdavid wants to merge 30 commits into
mainfrom
feat/reland-accountant
Closed

boazdavid wants to merge 30 commits into
mainfrom
feat/reland-accountant

Conversation

@boazdavid

Copy link
Copy Markdown
Collaborator

NOTICE. This PR undoes the revert #903 in effect. The repo owner took #768 out of the release and approved that revert. Do not merge this PR without the owner's explicit yes. Savings figures change for every user. This PR is a DRAFT and must stay a draft until the owner says yes.

Summary

What it contains

Merge conflicts with main:

git diff origin/fix/accountant-integration shows only files that main changed since the branch point (tooldefer, Responses work, keep-alive touchAlias).

How it was tested

  • gofmt -l, go vet ./..., go build ./..., go mod tidy -diff: all clean.
  • go test -count=1 on dash, proxy, apply, keepalive, components, cmd/context-guru-proxy: all pass, except 2 preflight tests in cmd/context-guru-proxy. They fail on macOS bash 3.2 and are not caused by this PR.
  • Dash golden files pass. node --test dash/savings.test.mjs: 10 pass.
  • The tool deferral lever still shows next to the accountant pricing.

Open questions

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]>
)

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]>
- 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]>
…768)

This reverts commit 38c00e1 (#903).
It brings back #768 on top of current main.
Conflicts in keepalive/keeper.go and keepalive/manual.go: main added touchAlias
(#904) and #768 adds gapStart to the same struct literals. Both fields are kept.

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

# Conflicts:
#	dash/overview.go
#	dash/overview_lean.go
Pin accountant at 5fa1986. It holds PR 46 (media pricing, faster extent
search) and PR 47 (TTL per breakpoint, a billed read beats the clock).

dash, proxy, apply, keepalive and components tests pass with it.

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

Copy link
Copy Markdown
Collaborator Author

Closed in favour of #930, the combined PR for the accountant integration. The commits of this PR 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