Repository navigation
Fix: Let the library price tool deferral from a stub-sized body (#908) - #1003
Conversation
Tool deferral's money now comes from one source, the deferral ledger (defer_net_usd). Overview and /api/tool-defer read that same column. Why Overview showed a small negative figure: the accountant saw deferral only as added bytes (defer_loading marks, the search tool, the names list). It priced them as a cost and booked that cost on the toolschema row. The ledger's net already subtracts the names list and the searches, so the cost counted twice. What changed: - The proxy reports deferral's edits to `tools` under the tooldefer operator. The diff is split at the body deferral read. - dash holds out the library's figure for the tooldefer row (row at 0, baseline delta and rows still sum). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…ed body (#908) Accountant R56 (rossoctl/accountant#61): a tool deferred with defer_loading stays in the bytes the proxy sends, and the provider bills no definition for it. The library reads body bytes, so it saw no shrink and priced the added flags and names list as a pure cost. Tool deferral's money came from the deferral ledger alone (9fdef12). Now the proxy gives the accountant the prompt the provider bills. billedBody cuts each deferred definition to a stub in the accountant's copy only. The bytes sent to the provider, the cache breakpoints and the ping facts all come from the real body, and a test pins that the wire is unchanged. The existing envelope diff then finds the shrink, and envelopeOpsFor merges it into one tooldefer operation with a span for each tool. The lever Overview adds beside the baseline (defer_net_usd) is now only the cost no body shows: the searches and the definitions they loaded (tooldefer.Money.SearchCost). The library's figure is already in the baseline, so adding the ledger's whole net as well counted it twice. A stub that would not be smaller than its definition is refused. The request keeps the forwarded body, skips Compute and logs acc_fallback deferral_unplaced. Deferral's own gate keeps such a deferral out of a real request, so only a unit test reaches it. Not covered: the OpenAI Chat wire, where client-search removes the tools for real. The accountant falls back there with no_usage before and after this change, because the usage has no cache-write tier. A test pins that the change adds no reason of its own. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
boazdavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (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 | 804636c3b102 |
blocking |
Verdict: blocking
Findings
- proxy/accountant_billed.go:34 — the stub copy also stubs tools the client deferred, so the proxy books Claude Code's own deferral as a context-guru saving
- What fails: a request where the client defers its own tools and the proxy defers others. The client body carries
WebSearchwith a full definition anddefer_loading:true(Claude Code defers on its own). The proxy defersmcp__x__yon the same request. The provider bills no definition for adefer_loadingtool, whoever set the mark. So the baseline (the client body, sent unchanged) would also not have billedWebSearch's definition. The dashboard still books it as a saving. - Proof:
deferredTools(proxy/accountant_billed.go:34-46) lists every tool withdefer_loadingand a name. It does not ask who set the mark.billedBody(line 49) stubs every listed tool, so the billed copy holds a stub forWebSearchtoo.envelopeOpsthen reports adecl-rewrittenop for it (client full definition to billed stub). The merge case at proxy/accountant_wire.go:107-108 catches it, becauseisStubonly checksdefer_loadingand a name. The mergedcg:tooldefer:defer-stubsop carries both shrinks. The library prices both. The result sits on the tooldefer row and insideBaselineCostUSD, soNetSavedUSDandTotalSavedUSDgrow by the client's own deferral. The PR states the opposite rule itself: proxy/accountant_envelope_test.go:278 says "A rewrite the client's own body already carries (Claude Code defers on its own) is not ours". That test covers only a request the proxy did not change (cl2 == fw). No test covers the mixed request. A second effect: stubbing drops every field but the name. A client-deferred tool that carriescache_controlloses its breakpoint in the accountant's copy. The proxy's own rewrite moves marks off deferred tools first (tooldefer/rewrite.go:92-98), so this loss hits only client-deferred tools. - Fix: stub and merge only the tools the proxy itself deferred. Pass the deferred names from
deferInfo.outcome.Deferred(proxy/proxy.go:1653-1660 already hasdiat that point) to the capture, next toaccPreDefer. Give that set tobilledBodyandenvelopeOpsFor. Leave client-deferred definitions full in the accountant's copy. Add a test: one request with a client-deferred tool and a proxy-deferred tool. Assert the client-deferred definition is not in the tooldefer figure.
- What fails: a request where the client defers its own tools and the proxy defers others. The client body carries
Non-blocking
- proxy/accountant_wire.go:73-76 — the comment names a guard the code does not have. It says a deferred tool with no name makes
accBilledreturn the forwarded body and setdeferral_unplaced.deferredTools(proxy/accountant_billed.go:38-40) skips tools with no name, so no unnamed tool ever reaches the refusal. An unnamed deferred tool (only a client body can send one) stays full in the accountant's copy, and no reason is set. Fix the comment or implement the guard. - Mark moves land on the toolschema row. tooldefer/rewrite.go:109-127 moves
cache_controlfrom deferred tools to loaded tools. The loaded tool's byte change is adecl-rewrittenop thatenvelopeOpsForleaves undertoolschema, because it is not a stub. A deferral edit is booked on the wrong row. The bytes are small. - Client-search wire attribution. On the OpenAI client-search wire, the deferral shrink and the added search tool stay under
toolschema. Unreachable today: that wire falls back withno_usagebefore and after this change, as the commit message says. If the accountant later prices that wire, the rows are wrong. billedBodycopies the body once per stub. Eachsjson.SetRawBytes(proxy/accountant_billed.go:63) copies the whole body. A request with many deferred tools pays O(body x tools) on the request path. Build the tools array in one pass, astooldefer.StubToolsdoes.- Sibling warmth mixes body kinds. The sibling store (proxy/accountant_shared.go) now holds billed bodies for deferring threads and real bodies for others. A session with both kinds under-credits shared warmth. The error is conservative.
What I checked
- The full diff
b49cbeb..804636c3, both commits, every hunk, and the code around each change. dash/accountant_price.go: the lever override runs only on the success path ofaccOverride, after every gate.PriceModeruns once, infinish(proxy/dashcapture.go:784), before the event is stored. So the storeddefer_net_usdis the lever value, and the tool-defer report and Overview read the same figure.- The fallback path:
accNoResult = deferral_unplacedskipscomputeSafe;noResultWhynames the reason in the log line;rejected_statuskeeps priority. - The sum check: the library compares the client body with the body given to
end.envelopeOpsplusmessageOpsplus the pipeline ops explain that diff. The merge keeps the per-section byte totals, and the spans check passes by construction. - The ledger:
Money.CostandNetare unchanged.SearchCostis a new breakdown, taken fresh fromPriceatnoteDefertime, so thejson:"-"costs nothing. savingsArithmetic:defer_net_usdentersTotalSavedUSDonly. The library's deferral figure entersNetSavedUSDthrough the baseline delta. With the override, each figure is counted once. Without the accountant, the ledger net stands, also once.- The plausibility bound: adding
tooldefertotoolSectionOperatorsloses nothing, because deferral's message ops are growths with no saved tokens. - The new tests and their helpers (
accHandlerOpts,tdBody,switchEvent,tdPrices), the upstream fakes, and the wire-unchanged assertions. - The accountant library at the pinned version:
checks()(sum, spans, unique_change),conservation,activeOpsreplay, andsharedWarmuse. "R56" is not in the pinned spec; the commit message names it as rossoctl/accountant#61. - Fail open: the stub copy touches the accountant's side figure only. The bytes sent, the cache breakpoints and the ping facts all come from the real body, and a test pins the wire.
- Live tests were not run (not approved). Go was not run. I did not read the PR conversation, per the round 1 rule.
boazdavid
left a comment
There was a problem hiding this comment.
| 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 | 804636c3b102 |
blocking |
Verdict: blocking
Findings
-
proxy/accountant_billed.go:34 — a deferral the client made on its own is booked as a context-guru saving
- What fails: The client body carries a tool with a full definition and
defer_loading(the client's own deferral;tooldefer/rewrite.go:66leaves such tools alone, so the full definition stays in the body). The proxy's deferral also runs on the same request.deferredToolslists everydefer_loadingtool, the client's included, andbilledBodystubs them all.envelopeOpsthen sees a rewrite (client full definition → stub) andenvelopeOpsFormerges it intocontext-guru.tooldefer(proxy/accountant_wire.go:107-119). The library books that definition's worth as a tooldefer saving. But the provider bills no definition for anydefer_loadingtool, whoever set the flag. So without context-guru, the client's own deferral saved the same money. The tooldefer row and the baseline delta are overstated by the client's definitions. - Proof: The repo's own rule says a
defer_loadingdefinition costs nothing:dash/toolinventory.go:326-330sets its tokens to 0 because "charging its schema to the request would double-count". The PR's own test comment states the intent: "A rewrite the client's own body already carries (Claude Code defers on its own) is not ours" (proxy/accountant_envelope_test.go:255). The test covers only the pure case (cl2 == cl2, no proxy deferral, so no stub is built). The mixed case is untested and books it. Reachable today in two shapes: (a) Claude Code'sDeferredToolPlaceholderis adefer_loadingtool of about 200 bytes (dash/testdata/deferred/placeholder-tool.json); it is smaller than nothing in the bill, yet its shrink to the 46-byte stub is booked as a tooldefer saving on every ultrahigh request that also defers; (b) a client that sends full definitions withdefer_loading(the shapetooldefer/toolsearch_test.go:88models) books the whole definition. - Fix: Stub only the tools the proxy deferred:
deferredTools(forwarded)minusdeferredTools(c.accPreDefer).accPreDeferis already kept for exactly this request (proxy/proxy.go:1657). Apply the same filter inenvelopeOpsFor's merge. Add a test for the mixed body.
- What fails: The client body carries a tool with a full definition and
-
proxy/accountant_wire.go:108 — the stub check reads the billed body at the client index, so removals misattribute the deferral
- What fails:
envelopeOpsreports a rewritten declaration at the CLIENT index (proxy/accountant_envelope.go:132,Index: jfrom the client array).isStub(billed, o.At.Index)and the name lookup atproxy/accountant_wire.go:118read the BILLED body at that index. When the declaration filter removed a tool that sits before the deferred tool (toolfilter and deferral both run in the ultrahigh preset, and deferral runs last), every later tool's billed index is one less than its client index. Two wrong outcomes follow. (a) The deferred tool's rewrite is not recognized as a stub, stays on thetoolschemarow, and the tooldefer row books nothing — the exact misattribution #908 set out to fix. (b) The reverse: atoolschemarewrite of a loaded tool merges intotooldeferwhen the client index happens to point at a stub, and the merged ChangeID takes the wrong name (proxy/accountant_wire.go:118-119,129). The totals still tie, so no check catches it. - Proof: The search-tool case in the same function uses the billed index and is correct, because
decl-addedops carry the forwarded index (proxy/accountant_envelope.go:130). Only thedecl-rewrittencase mixes the two index spaces. No test in the PR has a removal before a deferred tool;TestEnvelopeOpsOwnTheDeferralEditsand the integration test use aligned arrays. - Fix: Build a name-to-billed-index map from the billed body and match by name, as
toolsOpsitself does. Add a test with a filtered declaration before a deferred one.
- What fails:
-
proxy/accountant_wire.go:122,129 — the new ChangeID scheme orphans the active ops a live thread already carries, and the sum check then fails on every later request of that thread
- What fails: Before this PR, the deferral's edits were reported as
cg:toolschema:decl-rewritten:<hash>(one per tool) and the search tool ascg:toolschema:decl-added:<hash>. The library keeps such ops active in the thread state. After the upgrade, the same physical changes are reported undercg:tooldefer:...IDs. The library replaces an active op only when its ChangeID is re-reported, and ends an in-place op only when the forwarded item regains the client's own size (restored, accountantinternal/engine/compute.go; here the forwarded item is a stub, so it never regains it). The old ops stay active forever, the new ops report the same bytes again, and the sum check counts both. The check is gated, so the event books no saving at all — for every component, not only deferral — on every request of that thread until the client edits its tools or the deferral ends. The proxy restores thread snapshots up to one hour old (proxy/accountant_state.go:21), so every thread with an active deferral that crosses the upgrade is hit.accStateVersionwas not bumped. The same orphaning happens without an upgrade when a mid-thread rebuild changes the deferred set (tooldefer/apply.goRebuild path), because the merged op has ONE ChangeID for the whole set: the old set's op is never re-reported and never ends. - Proof: Accountant
internal/engine/compute.go,items()keeps active ops whose ChangeID is not re-reported;checks()sums the spans of active and reported ops against client-minus-billed bytes;forwardPositions/restoredend an active op only on a client edit, a removed position, or a size match with the client item. None of those holds for an old deferral op once the new code reports the change under a different ID. The set is stable within a thread ("the set is applied as stored",tooldefer/apply.go:90-92), which is why the merged ChangeID works in the steady state and hides the problem in tests. - Fix: Keep the per-tool ChangeIDs unchanged (
cg:toolschema:decl-rewritten:<hash>,cg:toolschema:decl-added:<hash>) and change only the Operator tocontext-guru.tooldefer. Replacement is by ChangeID, so the old active ops are then replaced on the first post-change request, and a set change re-reports each surviving tool under its own stable ID. If the one-operation form of R56 must stay, retire the old IDs explicitly on the first request after the change, or bumpaccStateVersion(accepting the estimate wave) — but say so in the PR.
- What fails: Before this PR, the deferral's edits were reported as
Non-blocking
proxy/accountant_wire.go:98-101: thestubbedmap is built and never read. Dead code.dash/overview.go:1387-1392: thedefer_netlever description still says "NET of the names list and the searches that cost. From the per-request ledger". After this PR, on accountant-priced rows the lever is the search cost alone and the names-list cost sits in the library's baseline. The description was not updated;docs/data-dependence.mdwas.proxy/accountant_billed.go:48says the event reportsacc_fallback deferral_unplaced. The stored fallback isno_result;deferral_unplacedreaches only the log line throughnoResultWhy(proxy/dashcapture.go:913-924).- Client-search wire: when deferral really removes definitions,
envelopeOpsreports the removals undertoolfilter, nottooldefer. Invisible today because that wire falls backno_usage(the PR's own test says so), but it is the same misattribution class as finding 2 if that wire ever gets priced. proxy/tooldefer_ledger_test.go:160-168: the row's net was an equality assertion and is now a bound. The comment explains why, but the test no longer pins the exact figure.- The defer_net lever and the Tools page net change meaning and values for users. Per
CLAUDE.md, a behavior change needs naming at the top of the PR and a human developer's yes. I did not read the PR body in round 1, so I cannot confirm it is named there.
What I checked
- The full diff of both commits (
9fdef120,804636c3) against baseb49cbeb6, and the code around every change:dash/accountant_price.go,dash/event.go,dash/overview.go,dash/savings.go,proxy/accountant_billed.go,proxy/accountant_wire.go,proxy/accountant_envelope.go,proxy/dashcapture.go,proxy/proxy.go(deferral hook at 1653-1660),tooldefer/ledger.go,tooldefer/rewrite.go,tooldefer/apply.go,tooldefer/tooldefer.go,dash/toolinventory.go. - The accountant library at the pinned version (
v0.1.1-0.20261108152158-5181d50c1f98, read from the module cache):items(),checks()(sum, unique_change, spans),forwardPositions/restored,activeOps,nextState, and the spans check against operation sizes. - The double-count math the PR is about: the library's tooldefer figure lands in
BaselineCostUSDviafig.DeltaUSD, the lever becomes-DeferSearchUSDonly, andsavingsArithmeticadds the lever once. No double count in the steady state. Theestimatedhold and the fallback paths leave the lever consistent. - The fail-open paths:
billedBodyerrors revert to the forwarded body;deferral_unplacedbooks no figure rather than a wrong one; the request itself is never affected (the provider still gets the real bytes, the cache facts still read the real body). - Tests: the three new dash tests, the two new proxy test files, and the loosened ledger test. None covers a client-deferred tool beside a proxy deferral, a removal before a deferred tool, or a thread whose active ops predate the ChangeID change.
- No live tests were run (not approved). No files outside this folder were changed.
… deferral ChangeID (#908) Round 1 review of #1003. - Stub and report only the tools the proxy deferred. A tool the client deferred itself is free in the baseline too, so it keeps its definition and its cache_control in the accountant's copy. - Find the deferred tool by name. A declaration removed before it shifts the billed index below the client index. - Keep the per-tool cg:toolschema ChangeIDs and change only the operator. The library replaces by ChangeID, so a thread state written by the previous code and a deferred set that changes mid-thread no longer leave a second copy of the same bytes active, which failed the sum check. - Build the tools array in one pass, drop the unused map, correct two comments and the defer_net lever description. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
The waterfall line for tool deferral now says what it holds on a request the accountant priced. Only that text changes in the three stats files. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Replies to round 1I fixed all three blocking findings. The fixes are in I checked each finding first. The new tests were run against the old head Reviewer 1 finding 1 and reviewer 2 finding 1 (client-deferred tools are stubbed): fixed.
Reviewer 2 finding 2 (stub check reads the billed body at the client index): fixed.
Reviewer 2 finding 3 (new ChangeIDs orphan the active operations of a live thread): fixed.
Non-blocking, fixed:
Non-blocking, not changed:
Behavior change (reviewer 2 note). It is named in the PR description, under "Behavior change: the deferral lever is now the search cost". This PR stays a draft until a human developer says yes. Checks on Assisted-By: Claude (Anthropic AI) [email protected] |
boazdavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (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 | e5edfdafaeb7 |
approve |
Verdict: approve
Findings
None. All three round-1 findings are fixed, and I found no new defect in the fix commits.
Earlier findings
- My finding 1 (a client's own deferral booked as our saving): fixed.
ownDeferred(proxy/accountant_billed.go:48) takes the names deferred in the forwarded body minus the names already deferred inc.accPreDefer.billedBodystubs only those. A client-deferred tool keeps its full definition and itscache_controlin the accountant's copy, soenvelopeOpsreports no change for it and nothing is booked. TheDeferredToolPlaceholdercase is covered too: the placeholder is deferred inaccPreDefer, so it is excluded fromown. The remap inenvelopeOpsForuses the sameownset. TestTestOnlyTheProxysOwnDeferralIsStubbedAndPricedcovers the mixed body. - My finding 2 (stub check read the billed body at the client index): fixed.
envelopeOpsFornow reads the CLIENT body at the op's client index (proxy/accountant_wire.go:112-117), takes the name, and checksown[name]plus a stub at that name's billed index from a name-to-index map. Both wrong directions are gone: a deferred tool behind a removal is found by name, and atoolschemarewrite of a loaded tool no longer merges, because the loaded tool's name is not inown. TestTestDeferralIsFoundByNameWhenAFilterRemovedAToolBeforeItcovers a removal before the deferred tool and asserts the section bytes still tie. - My finding 3 (new ChangeIDs orphan the active ops of a live thread): fixed. Each per-tool op keeps the
cg:toolschema:decl-rewritten:<hash>ChangeID thatenvelopeOpsgave it, and only the Operator changes tocontext-guru.tooldefer(proxy/accountant_wire.go:120-121). The merged operation is gone. The library replaces by ChangeID, so a thread state written by the previous code has its old ops replaced on the next request, and a deferred set that grows re-reports each surviving tool under its own stable ID. A set that shrinks ends the dropped tool's op throughrestored(the forwarded item regains the client size). Tests drive the real tracker:TestAThreadStateFromThePreviousCodeStillTiesAfterTheUpgrade,TestAChangedDeferredSetReplacesTheOldOperation,TestAShrunkDeferredSetStillTies. - Reviewer 1 finding 1 (same as my finding 1, plus the lost
cache_control): fixed. Same fix; thecache_controlhalf is covered because non-owntools keep their raw bytes. - Reviewer 1 non-blocking items: the unnamed-tool comment and the
O(body x tools)copies are fixed;billedBodynow rebuildstoolsin one pass. Sibling warmth, client-search attribution and mark moves were declined with reasons. I checked each reason and accept it: the sibling-warmth error is conservative, the client-search wire falls backno_usagetoday, and the mark-move bytes are small. - My round-1 non-blocking notes: all fixed (dead map,
deferral_unplacedcomment,defer_netdescription plus the three golden files) or answered (the behavior change is named in the PR description under "Behavior change: the deferral lever is now the search cost", the PR is a draft, and the decision is put to the owner).
Non-blocking
- The PR description is stale. It still says "
envelopeOpsForreports onetooldeferoperation: oneChangeID, one span per deferred tool". Commit532389b9removed that design in favor of per-tool ChangeIDs. A PR reader would be misled about the mechanism the sum check now relies on. proxy/accountant_billed.go:17-19: the file-top comment still says "each deferred definition cut to a stub" and "reported as one operation". After the fix, only the proxy's own deferrals are cut, and each is its own operation. The function-level comments are right; the header is not.- A request where the client defers its own tools keeps their definitions in the accountant's copy, but the provider bills nothing for them. The request's tokens-per-byte ratio is then diluted, so every dollar figure on that request is under-priced in proportion. The error is conservative and small for the placeholder shape (about 200 bytes). Worth a line in the PR's "Not verified" list, nothing more.
What I checked
- Last review: round 1,
804636c3b102738d97553338e8a5f9389404684f, 2026-11-10T06:33:19Z. - New commits read: 2 —
532389b9"fix(accountant): Stub only the tools the proxy deferred and keep each deferral ChangeID (#908)",e5edfdaf"test(dash): Update the golden defer_net description (#908)". - Read in full: 2 reviews, 1 comment, 0 inline comments (from
.review-in-reviews.txt,.review-in-comments.txt,.review-in-inline.txt). The inline list is empty. - New items since my last review: the two commits above; the author's reply comment of 2026-11-10T09:12:24Z (checked every claim in it against the code); the PR description (read to confirm the behavior change is named — it is, and the PR is a draft with the decision put to the owner).
- The full diff
804636c3..HEAD, and the final state ofproxy/accountant_billed.go,proxy/accountant_wire.go,dash/overview.go, and the newproxy/accountant_defer_scope_test.go. - The fix against each finding, traced by hand:
ownDeferredset arithmetic for the mixed and placeholder bodies; the name-based remap in both directions (deferred tool behind a removal, and a loaded tool's rewrite at an index that holds a stub); ChangeID replacement for the upgrade, growth and shrink paths, against the library'sitems(),checks()andrestoredat the pinned versionv0.1.1-0.20261108152158-5181d50c1f98. - The refusal path stays fail-open:
billedBodyreturns the original body untouched on refusal,accNoResultskips the compute, and the request itself is never affected. - The golden description text matches the new
dash/overview.gotext exactly. - The test helpers the new file uses (
accRun,newSavingsTracker,opsDelta,sectionDelta) exist in the existing test files. - I did not run Go (not approved), so the author's test-run claims are not verified by me. The tests' logic matches the defects I traced in round 1, and the author reports four of the five new tests fail on the old head, which agrees with my round-1 analysis.
boazdavid
left a comment
There was a problem hiding this comment.
| 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 | e5edfdaf |
approve |
Verdict: approve
Findings
None. All three blocking findings from round 1 are fixed. I found no new defect in the two new commits.
Earlier findings
-
My finding 1 and reviewer 2 finding 1 (client-deferred tools stubbed and booked as ours): fixed.
ownDeferred(proxy/accountant_billed.go:48) takes the names deferred in the forwarded body less the names deferred inaccPreDefer. I checked the semantics myself:- A client-deferred tool is deferred in
accPreDefer, so it is never inown. It keeps its full definition and itscache_controlin the accountant's copy.TestOnlyTheProxysOwnDeferralIsStubbedAndPricedpins both. - The proxy's own rewrite (tooldefer/rewrite.go:66) skips already-deferred tools, so every tool it marks is deferred in forwarded and not in
accPreDefer.owncovers exactly those. - RepairRefs stubs (tooldefer/repair.go) are added inside
applyToolDefer, afterpreDeferwas captured, so they land inownand are cut to the bare stub. The client body does not declare those tools, so they appear as a small added declaration either way. The new copy is closer to the billed prompt, not further. No wrong saving. - Using
accPreDeferinstead ofdeferInfo.outcome.Deferredis sound. I traced the shapes where the two differ (client-deferred tool also in the thread set, repair stubs);accPreDefergives the right answer in each.
- A client-deferred tool is deferred in
-
Reviewer 2 finding 2 (stub check read the billed body at the client index): fixed, and I checked it myself.
envelopeOpsFornow builds a name-to-billed-index map (proxy/accountant_wire.go:111-114) and matches the rewrite by the client tool's name (line 119-121). I traced the failing shape: a removal before the deferred tool shifts the billed index; the client index now maps through the name, andisStubreads the right position. The reverse misattribution is also gone: a loaded tool's name maps to its own unstubbed position.TestDeferralIsFoundByNameWhenAFilterRemovedAToolBeforeItpins it. -
Reviewer 2 finding 3 (new ChangeIDs orphan active operations): fixed, and I checked it myself. Each per-tool
cg:toolschema:decl-rewritten:<hash>ChangeID is kept; only the operator changes tocontext-guru.tooldefer(proxy/accountant_wire.go:122). I read the library at the pinned version:Request.withReported(internal/engine/state.go:185-200) replaces an active operation only when its ChangeID is re-reported. Same IDs, so a thread state written by the released code is replaced, not orphaned.restored(internal/engine/compute.go:627) ends an in-place op when the forwarded item regains the client size. An un-deferred tool regains it, so a shrunk set ends cleanly. The grow-set shape re-reports each surviving tool under its own stable ID.- The message ops were never at risk: their ChangeIDs (
cg:tooldefer:msg-inserted:N,msg-rewritten:N:hashof the pre-deferral message bytes) are stable per position, so a set change replaces the active op instead of orphaning it. - The three tests in proxy/accountant_defer_scope_test.go drive the real tracker through the upgrade shape, the grow set and the shrunk set.
-
Non-blocking items. Fixed: the one-pass
billedBody(no more O(body x tools) copies), the deadstubbedmap, both wrong comments, thedefer_netdescription and the three golden files. Declined with reasons I checked and accept: sibling warmth (conservative direction), client-search wire attribution (that wire falls backno_usagetoday), mark moves on the toolschema row (small bytes). Reviewer 2's process note is answered: the PR body names the behavior change under its own heading, lists the affected pages, and the PR is a draft with two decisions for the owner. That satisfies the CLAUDE.md rule as far as a reviewer can check.
Non-blocking
- The PR description still says "
envelopeOpsForreports onetooldeferoperation: oneChangeID, one span per deferred tool" and "Two commits". Commit532389b9replaced the merged operation with per-tool operations and made it four commits. Update the description before merge, so the owner reads the shape that will land.
What I checked
- Last review: round 1,
804636c3b102738d97553338e8a5f9389404684f, 2026-11-10T06:31:46Z. - New commits read: 2 —
532389b9fix(accountant): Stub only the tools the proxy deferred and keep each deferral ChangeID;e5edfdaftest(dash): Update the golden defer_net description. - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three saved files). I also read the PR body to check the behavior-change claim in the author's reply.
- New items since my last review: the two commits above (diff read hunk by hunk, code around each change read); the author's reply of 2026-11-10T09:12:24Z (each claim checked against the code or the PR body); reviewer 2's round-1 review (read now, per the round-2 rule; findings 1-3 verified myself as above).
ownDeferred,billedBody,accBilled,envelopeOpsFor,isStubat the new head, line by line, against the shapes I traced in round 1: client-deferred beside proxy-deferred, repair stubs, refused stubs, repeated names, removed-before-deferred, sets that grow and shrink mid-thread.- The accountant library at the pinned version:
withReported(replace by ChangeID),storedCopy(a same-size replacement does not count twice),forwardPositions/restored(how an in-place op ends), and the ChangeID prefixes the library treats specially (headttl:,cg:cachesplit:only;cg:toolschema:carries no meaning to it). - The new tests in proxy/accountant_defer_scope_test.go and their helpers (
accRun,envelopeOps,opsDelta,sectionDelta), the updatedbilledBodycall sites, the ledger-test comment, and the golden files against dash/overview.go. - Compile-level checks by reading: imports match the new code (
strconvdropped from proxy/accountant_billed.go, still used in proxy/accountant_wire.go). - Live tests were not run (not approved). Go was not run. No files outside this folder were changed.
…#908) The header of billedBody still said every deferred definition is cut and that the deferral is one operation. Only the tools the proxy deferred are cut, and each is its own operation. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Review: the pricing fix is right, the split between the Overview cards is notSummary. Giving the library a copy of the body with stubs is a clean fix for the double count. But after this PR, most of the deferral saving moves to the "Your preset" card. Some of it leaves every total. I ask for one change before merge. What is right
What is wrong
Measured on one real dashboard database (last 24 h, read-only)
Proposal
Open questions
|
…deferral lever (#908) Review of #1003: after the stub-body change the library's tooldefer figure sat in baseline - cost, so the Overview showed the deferral saving on the Your preset card and the deferral card read only the search cost. The figure now leaves the baseline and the tooldefer row stays in the component sum; the lever is the figure minus the search cost. The total is unchanged. A held request keeps the ledger's net on the lever, as before, and the deferral is left out of the held estimate. Before, the lever line ran ahead of the held block and the ledger's net vanished from every total. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…n its figure (#908) Review of #1003: the lever, /api/tool-defer and the Tools page read one stored figure, so one column has one meaning. The Overview line, the field comments, the card text and the Tools note now say that figure is the library's deferral saving less the search cost on a priced request, and the ledger's net on a held or unpriced one. Only the description line of the three golden files changed. The end-to-end test pins the exact figure: held first request keeps the ledger's net, a priced request is the library's tooldefer row less the search cost the capture priced. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Reply to the review of 2026-11-10T09:28Thank you. I did what you proposed. The fix is in 1. The saving was on the wrong card: fixed.
2. A held request lost its deferral saving: fixed.
3.
4. Card text: fixed. The Overview description, the field comments, 5. Replay on real traffic: not done.
Also found: Decision 1 for the owner is still open. It needs a human developer's yes before merge. Checks on Assisted-By: Claude (Anthropic AI) [email protected] |
boazdavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (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 | 3 of 3 | 9f25e1c4bb08 |
approve |
Verdict: approve
Findings
None. The new split of the Overview cards is right, and the total does not change. I found no defect in the three new commits.
The new commits, checked
-
32a770f9moves the library's deferral figure from the preset card to the deferral card. Correct.accOverride(dash/accountant_price.go:393-401) takesdeferFig = fig.ByComponent["tooldefer"], subtracts it fromBaselineCostUSD, and sets the lever todeferFig - DeferSearchUSD.- The key matches:
AccountantFiguretrims thecontext-guru.prefix off the operator (dash/accountant_price.go:70), andDeferComponent = "tooldefer". - The total is unchanged, by arithmetic: the net loses
deferFig, the lever gainsdeferFig - search.(DeltaUSD - deferFig) + (deferFig - search) = DeltaUSD - search, the same figure as before the move.TestPriceMode_MovingTheDeferralFigureLeavesTheTotalAlonepins it. - The condition now also fires on
deferFig != 0alone. That is right: a library figure with no ledger figures still reaches the deferral card. - The components table keeps the full
tooldeferrow. So the rows sum to the baseline delta plus the lever, less the search cost. The search cost is a ledger figure no row carries. That gap existed in this PR before the move too, so no reader breaks.
-
A held request keeps the ledger's net. Correct.
- The move runs under
if !estimated(dash/accountant_price.go:395). A held request keeps the ledger's net on the lever, as before this PR. EstimatedSavedUSD = fig.DeltaUSD - deferFig(dash/accountant_price.go:421). The deferral is out of the held estimate, so it appears in one place. The subtraction is a no-op when there is no deferral, becausedeferFigis then 0.TestPriceMode_AHeldRequestKeepsTheLedgersNetAndHoldsNoDeferralTwicepins both.
- The move runs under
-
One column, one figure. Correct.
/api/tool-defer,SavingsTotals,Overview,OverviewLeanand the daily series all sumdefer_net_usdthroughdeferNetSum(dash/tooldeferpanel.go:24-25). They cannot disagree.TestTheDeferralSavingIsOnTheDeferralCardAndTheTotalIsUnchangedasserts it end to end, through the database.Money.Grossand the ledger's own cost are unchanged, as the review asked.
-
22a9caa1fixes my round-2 note on thebilledBodyheader. The comment now says "each definition the proxy itself deferred" and "one operation for each tool". It matches the code. -
The card text. The Overview description, the field comments,
app.js,tools.jsand the three golden files now say what the figure is. The golden text matchesdash/overview.goexactly, character for character. One caption was missed; see Non-blocking.
Earlier findings
- My round-1 findings 1-3 and reviewer 1's finding 1: fixed in round 2. The code they fixed (
ownDeferred, the name-based remap, the per-tool ChangeIDs) is untouched by the three new commits. Still fixed. - My round-2 non-blocking, the stale PR description: fixed. The body now says "one
context-guru.tooldeferoperation for each deferred tool. Each keeps its owncg:toolschema:...ChangeID". It names the behavior change under its own heading, lists the affected pages, and puts two decisions to the owner. The PR is a draft. - My round-2 non-blocking, the stale
accountant_billed.goheader: fixed by22a9caa1. - My round-2 non-blocking, the diluted tokens-per-byte ratio: acknowledged. The PR body carries it in "Not verified", with the direction and the size.
- The review of 2026-11-10T09:28 (the card split): addressed in full on items 1, 2 and 3, as checked above. Item 4 (card text) is addressed except for one caption. Item 5 (replay on real traffic) is declined with a reason I checked: no real dashboard database on this machine, and the harness databases have no deferral rows. The PR keeps it in "Not verified" and does not claim a match. That is honest.
Non-blocking
dash/ui/tools.js:1194— the "Net saving" tile caption still describes the old arithmetic. It says "gross X less Y of searches and list". On a request the accountant priced,net_usdis the library's figure less the search cost, andcost_usdis gross minus that net. The caption's dollars are right, but "of searches and list" is wrong on priced rows. The section note above it was updated; this caption was not. One line to fix before merge.- Comments that still describe the pre-split arithmetic.
dash/tooldeferpanel.go:11-13("Net is gross minus the names list and every search cost") and theToolDeferDay.CostUSDcomment; the held-estimate comment indash/accountant_price.go:404-413("What is held out:fig.DeltaUSD, which is every component's figure" — the deferral part now stays booked on the lever);dash/event.go:653anddash/schema.go:353("this component's share of the request's baseline delta" — the tooldefer row's dollars now sit on the lever). Doc drift only. - The author's own find stands:
tooldefer.Ledgerdoes not sumSearchCostinto its snapshot, so the snapshot value is always 0. Not changed here, the new tests read the cost from the event, and it is flagged for a separate issue. I agree with leaving it out of this PR.
What I checked
- Last review: round 2,
e5edfdafaeb747c6c4420e0f2ac74d6a49b4f2b6, 2026-11-10T09:17:03Z. - New commits read: 3 —
22a9caa1docs(accountant): Say that only the proxy's own deferrals are stubbed;32a770f9fix(dash): Move the library's deferral figure from the preset to the deferral lever;9f25e1c4fix(dash): Say the deferral lever holds the whole deferral saving; pin its figure. - Read in full: 4 reviews, 3 comments, 0 inline comments (from
.review-in-reviews.txt,.review-in-comments.txt,.review-in-inline.txt). The inline list is empty. - New items since my last review: the three commits above; reviewer 1's round-2 review (2026-11-10T09:18:08Z, approve, nothing new to verify beyond what I checked myself in round 2); the review of 2026-11-10T09:28:40Z (the card split, with the measured table); the author's reply of 2026-11-10T09:56:22Z (every fix claim checked against the code, as above); the PR description (re-read in full: the behavior change is named, the mechanism is described as it now is, the decisions are listed).
- The full diff
e5edfdaf..HEAD, hunk by hunk, and the code around each change:dash/accountant_price.go(accOverridein full,AccountantFigure,envelopeComponents,toolSectionOperators),dash/defer_split_test.go,dash/accountant_switch_test.go,dash/event.go,dash/overview.go,dash/tooldeferpanel.go(deferNetSum,ToolDeferReportFor),dash/savings.go,dash/ui/app.js,dash/ui/tools.js, the three golden files,proxy/accountant_billed.go,proxy/tooldefer_ledger_test.go,proxy/tooldefer_stub_body_test.go. - The arithmetic re-derived by hand for the three groups the review measured: priced, held, unpriced. The total is
DeltaUSD - searchon a priced request, before and after the move. A held request books the ledger's net in the total and the rest inEstimatedSavedUSD. An unpriced request is untouched. - The readers of the figure:
deferNetSumis the one SQL expression behind the panel,SavingsTotals,Overview,OverviewLeanand the daily series (dash/query.go:1432).Money.GrossandCostare unchanged. - The test helpers the new and rewritten tests use (
accHandlerOpts,tdBody,tdPrices,tdPost,waitForRows,sseUpstream,switchEvent,accTestPrice,accNear,openTestDB,insertBatch,ToolDeferReportFor,rowSavedSum) all exist. - The golden description text matches the new
dash/overview.gotext exactly. - Live tests were not run (not approved). Go was not run, so the author's test-run claims are not verified by me. The tests' logic matches the arithmetic I traced by hand. No files outside this folder were changed.
boazdavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @boazdavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 | offload-review skill, @boazdavid's session | resumed | 1 of 2 | 3 of 3 | 9f25e1c4bb08 |
blocking |
Verdict: blocking
Findings
- dash/tooldeferpanel.go:79 — the Tools page "cost" figure mixes the ledger's gross with the library's net, so it no longer shows the names list and the searches
- What fails: A user opens the Tools page, or calls
/api/tool-defer. The "Net saving" tile reads "gross $X less $Y of searches and list". On a request the accountant priced, $Y is not that cost. $Y is the ledger's gross less the library's deferral figure plus the search cost. The two measurements price the same deferral with different tokenizers. Their difference is the error. The PR does not claim the two agree ("Not verified" in the PR body). At the base commit the figure was exact: both columns came from the ledger. - Proof:
PriceModesetsdefer_net_usdto the library's tooldefer row less the search cost on a priced request (dash/accountant_price.go:397). It does not touchdefer_gross_usd, which stays the ledger's gross (proxy/dashcapture.go:624).ToolDeferReportForderivesCostUSD = GrossUSD - NetUSD(dash/tooldeferpanel.go:79) and documents it as "gross minus net: the names list and the searches" (line 46). Call the ledger's gross G, its net N, the library's figure D, the search cost S. The shown cost is G - (D - S). The true cost is G - N. The two are equal only when D = N + S, that is, only when the library's body pricing matches the ledger's measurement of the same deferral. On the dashboard measured in the review comment of 2026-11-10T09:28:40Z, 773 of 900 deferral requests are priced and ran no search, so the error there is N - D per priced request. Held and unpriced rows keep the exact ledger arithmetic, so one aggregate mixes exact and inexact rows. The round-2 head had the same defect in a worse form: the lever was the search cost alone, so the shown cost was G + S. I missed it in round 2. I report it now because this round moved the figure again and I re-read every reader of the changed fields. - Fix: State the cost from one measurement. Either keep the ledger's cost (store the ledger's gross less its net before PriceMode overwrites the net), or drop the derivation and label
cost_usdas a remainder. Then fix the texts that claim the old meaning: the tile subtitle (dash/ui/tools.js:1194), theCostUSDcomment (dash/tooldeferpanel.go:46), the panel header (dash/tooldeferpanel.go:13), and therenderDeferNetdocstring (dash/ui/tools.js), which still says the figures are the proxy's own ledger.
- What fails: A user opens the Tools page, or calls
Earlier findings
Round 2 carried no findings. The status of the open items:
- My round-2 non-blocking (stale PR description): fixed. The body now describes the per-tool operations and the new card split. It names the behavior change under its own heading, lists the affected pages, and the PR stays a draft with the owner's decisions open.
- Reviewer 2's round-2 non-blocking items: all fixed. The PR description is current. Commit
22a9caa1corrected theaccountant_billed.goheader: it now says only the proxy's own deferrals are cut, one operation per tool. The tokens-per-byte dilution note is in "Not verified". - The review comment of 2026-11-10T09:28:40Z (a person's comment; I checked each point against the code):
- Point 1, the saving sat on the wrong card: fixed.
accOverridetakesdeferFigout of the baseline and puts it on the lever (dash/accountant_price.go:393-402). I traced the total by hand: (DeltaUSD - deferFig) + (deferFig - search) = DeltaUSD - search. The total is the same as before the split. A request with no search now puts the whole saving on the deferral card. - Point 2, a held request lost its saving from every total: fixed. The move is gated on
!estimated, so a held request keeps the ledger's net on the lever, andEstimatedSavedUSD = fig.DeltaUSD - deferFigkeeps the deferral out of the held estimate. The figure appears in one place. - Point 3, one column with two meanings: fixed for the net. Overview, SavingsTotals, OverviewLean, the daily buckets and
/api/tool-deferall readdefer_net_usdthroughdeferNetSum. The cost column beside it is my finding above. - The open questions stand as the comment left them: the owner's decision is not given, and the replay on real traffic is not done. The PR records both honestly.
- Point 1, the saving sat on the wrong card: fixed.
Non-blocking
- A held request where the library books a
tooldeferfigure but the ledger booked no dollars keeps a zero lever and an estimate without the deferral, so the figure is in no total. The base behavior held it outside every total too, so this is no regression. I could not construct a reachable shape: a held request has no thread history, so its figure comes from ops reported on that request, and those imply the ledger booked gross. dash/accountant_price.go:398-400: the negative-zero guard assigns 0 to a value that already equals 0. Harmless. Under IEEE round-to-nearest,deferFig - DeferSearchUSDcannot produce a negative zero from finite inputs.
What I checked
- Last review: round 2,
e5edfdafaeb747c6c4420e0f2ac74d6a49b4f2b6, 2026-11-10T09:18:08Z. - New commits read: 3 —
22a9caa1docs(accountant): Say that only the proxy's own deferrals are stubbed;32a770f9fix(dash): Move the library's deferral figure from the preset to the deferral lever;9f25e1c4fix(dash): Say the deferral lever holds the whole deferral saving; pin its figure. - Read in full: 4 reviews, 2 comments, 0 inline comments (from
.review-in-reviews.txt,.review-in-comments.txt,.review-in-inline.txt). - New items since my last review: the three commits above (full diff
e5edfdaf..HEAD, every hunk, code around each change); the review comment of 2026-11-10T09:28:40Z from amiddavid (a person's comment: each point checked against the code, as listed under Earlier findings); the author's reply of 2026-11-10T09:56:22Z (each claim checked); the PR body, read again in full. - The new lever arithmetic in
accOverride, line by line: the gateDeferNetUSD != 0 || DeferGrossUSD != 0 || deferFig != 0; the priced path (baseline minus deferFig, lever = deferFig minus search); the held path (no move, ledger's net kept, deferral out of the estimate); the fallback paths (accRes == niland the other gates return before the lever code, sodeferral_unplacedand unpriced events keep the ledger's net). savingsArithmetic(dash/savings.go:73-78): total = net + cachesplit + kaNet + manualNet + deferNet. The move keeps the priced total identical;EstimatedSavedUSDstays outside every total.- Every reader of the changed fields:
deferNetSumin Overview, SavingsTotals, OverviewLean, the daily buckets and/api/tool-defer;CostUSDinToolDeferReportFor; the waterfall and the three golden files (their new description strings matchdash/overview.goexactly);dash/ui/app.jsanddash/ui/tools.js. - The tests, traced by hand:
deferralEvent,eventTotal, the preset-to-lever test, the total-unchanged test, the held test, the unpriced test,defer_split_test.go, and the two proxy tests (TestToolDeferFactsReachTheDashboardRow,TestToolDeferPricedRowIsTheLibrarysFigureLessTheSearchCost,TestToolDeferIsPricedByTheLibraryFromAStubSizedBody). Their arithmetic matches the code. - Live tests were not run (not approved). Go was not run. No files outside this folder were changed.
…s the lever (#908) On a request the accountant priced, defer_net_usd is the library's deferral figure less the search cost. The Tools page derived its cost as gross less that net, which is then the gap between two tokenizers: the test row showed -$0.0006 where the ledger's own cost is $0.0004. Store the ledger's cost on the row (defer_cost_usd) before PriceMode moves the net, and sum it on the page. The migration fills older rows with gross less net, which is exact for them because the ledger's net was the stored net. It runs on every open and changes a row only once. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…#908) The tile caption read 'gross X less Y', which does not hold on a priced request: net is the library's figure less the search cost there, and the cost is the ledger's own. Show them as separate ledger facts. Fix the comments that still described the earlier arithmetic: the panel header, the CostUSD field, the held-estimate block, and the per-component dollar columns. Assert in the proxy test that the stored cost is the ledger's and that the page total is the sum of the stored costs. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Reply to round 3I fixed the blocking finding. The fix is in Reviewer 1, finding 1 (the Tools page cost mixes the ledger's gross with the library's net): fixed.
Reviewer 2, non-blocking notes: fixed.
Known edge, not fixed. The backfill runs on every open. A row written by the new code, priced, with a ledger cost of exactly 0, would be refilled with Checks on Assisted-By: Claude (Anthropic AI) [email protected] |
Owner decisions (from the integrator session)The owner answered both questions on 2026-11-10, in the integrator session: "yes to both".
Still needed before this PR can merge: take it out of draft, resolve the conflict with |
Both sides appended columns to the request row: main added the subscription limit and tier-token columns, this branch added defer_cost_usd. The select, the scan, the insert columns and the insert values keep both sets in the same order. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
boazdavid
left a comment
There was a problem hiding this comment.
| Reviewer 2 (glm, user of @boazdavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 |
| Context | offload-review skill, @boazdavid's session |
| Session | resumed |
| Reviewer | 2 of 2 |
| Round | 4 of 4 |
| Head under review | 5f256f2dcf8a |
| Verdict | approve |
Verdict
approve — the branch's own code has no finding I can confirm. The blocking finding from round 3 is fixed correctly. The notes below are not blocking; three of them name work to do before merge.
Findings
None.
Earlier findings
- Reviewer 1, round 3, finding 1 (blocking — the Tools page cost mixed the ledger's gross with the library's net): fixed. I checked it myself, in
baa69308.dashcapture.gosetse.DeferCostUSD = d.gross - d.netbeforePriceModemoves the net. So the stored value is the ledger's own cost, taken from one measurement.ToolDeferReportForsumsdefer_cost_usd. It no longer derives cost from gross less net.backfillDeferCostfills old rows withgross - net. For rows written before this branch, the stored net was the ledger's net, so the value is exact. The condition (defer_tokens > 0 AND defer_cost_usd = 0 AND defer_gross_usd > defer_net_usd) and the idempotence check hold.- The tests
TestTheToolsPageCostIsTheLedgersCostOnAPricedRequestandTestTheLedgerCostOfAnOlderRowIsFilledByTheMigrationOncepin both parts.
- Reviewer 1, round 3, non-blocking (held request with no ledger dollars; the negative-zero guard): no change needed. I agree with reviewer 1 on both.
- My round 3, non-blocking (the
tools.js:1194caption; stale comments): fixed in1d1cdda5. The caption, the section note and therenderDeferNetdocstring now say what each figure is. - Owner decisions (comment of 2026-11-10T10:24:50): recorded. The owner said yes to the card split and to the OpenAI Chat cache-write work as a separate issue or PR. Both decisions now have a human's yes.
The new commits, checked
baa69308— the cost column. Verified end to end: capture sets it beforePriceMode; the schema adds it withREAL NOT NULL DEFAULT 0; the insert instore.go,requestColsandscanRequestinquery.gostay one-to-one (96 static columns, 96 scan destinations,defer_cost_usdand&e.DeferCostUSDat the same position); the panel sums it. Held and fallback rows get a correct value too, because the capture runs before the pricing branch.1d1cdda5— texts and tests. Read in full. No code change beyond the test file.5f256f2d— merge oforigin/mainata3495863. I checked the merge did not break the branch's own arithmetic:- The insert now has 96 static columns, 96 static exec args, and 104 literal placeholders — the 7
limitColsplusrequestStoredTokenColumns()cover the rest. The triple is consistent. - Main's #999 changes to
dash/accountant_price.go(TokByComponent,clearAccTokens) are additive and do not touch the deferral block. The token figures still mirrorByComponent, which keeps thetooldeferrow; the lever is a dollar-only concept. So #999 and this PR do not disagree. - The branch's own diff against the base
a3495863is the same 26-file diff I reviewed in round 3, plus the cost column. I read it again in full.
- The insert now has 96 static columns, 96 static exec args, and 104 literal placeholders — the 7
Non-blocking notes
- The head carries the red band tests. The owner asked to wait for the band-window fix before merging main in. The merge
5f256f2dbrought main'sa3495863, which still hasd058b339without its fix77a910b0. The fix is onorigin/mainnow. Merging this PR into current main keeps the fix, because the branch changes none of those files after the merge base. But the head itself is the red shape. Do this before merge: mergeorigin/mainonce more, so the final head has77a910b0. - The PR description is stale. It says "Eight commits" and lists none of
baa69308,1d1cdda5or the merge. It says "I checked that the branch merges cleanly with main atac68a7a0" — the branch now merges main ata3495863. It says "Money.GrossandCostare unchanged" — the Tools page cost column now reads the storeddefer_cost_usd, and the description should say so under the behavior-change heading. The Tests section still describes the old loose check inTestToolDeferFactsReachTheDashboardRow; the test is exact now. - The data-dependence row is short one column.
docs/data-dependence.mdstill says the dashboard stores "eight count and price columns" for deferral. It is nine now;defer_cost_usdis missing from the list. - The negative-zero comment states a wrong reason. The guard is harmless, but the comment added in
1d1cdda5saysdeferFigcan be-0when the library sums opposite figures. Under IEEE 754 round-to-nearest,+a + (-a)is+0, the map sum starts at+0, and+0 + (-0)is+0. The inputs on this path are non-negative products, so-0cannot reachdeferFig. Reviewer 1 said the same in round 3. One comment line; fix it or drop the guard in a follow-up. - The backfill has a dev-only edge. A row written by this branch's own round-3 build (no cost column, net already the lever) backfills to the gap between two tokenizers, not the ledger's cost. Released builds never wrote that shape, so only development databases can hold such rows. No action needed.
What I checked
- Last review: round 3,
9f25e1c4bb083e1f9543305d084ed5af2533a63c, 2026-11-10T10:08:31Z. - New commits read: 3 —
baa69308fix(dash): Read the deferral cost from the ledger, not from gross less the lever;1d1cdda5docs(dash): Say what the Tools page figures are after the lever moved;5f256f2dMerge origin/main into feat/908-defer-stub-body (brings main'sa3495863; the main-side commits came through their own PRs). Read asgit log --stat 9f25e1c4..HEADandgit diff 9f25e1c4..HEAD; the branch's own changes read again asgit diff a3495863..HEAD, in full. - Read in full: 6 reviews, 5 comments, 0 inline comments, from the three saved files.
- New items since my last review: reviewer 1's round-3 review (10:09:57Z); the author's reply to round 3 (10:20:32Z); the owner decisions comment (10:24:50Z); the commits
baa69308,1d1cdda5,5f256f2d. - Verified in code: the cost column end to end (capture, schema, insert, scan, panel sum, migration); the merge's insert triple (columns, placeholders, exec args) and the
requestCols/scanRequestpairing; the #999 × deferral interaction inaccountant_price.go; the new tests indefer_split_test.goandtooldefer_ledger_test.go; the backfill condition against the priced and held paths; the PR description anddocs/data-dependence.mdagainst the current code. - Not verified:
go testandgofmt(live tests not approved this round; I read the code only). CI at the head: CodeQL, analyze, purego, build, trivy and DCO pass; build-test and record were still running when I last looked. The PR is still a draft.
boazdavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @boazdavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 | offload-review skill, @boazdavid's session | resumed | 1 of 2 | 4 of 4 | 5f256f2dcf8a |
approve |
Verdict: approve
The round-3 blocking finding is fixed. The two new commits carry no defect. The merge of main is resolved correctly. One merge condition stays open, in the notes below: this head still misses the band fix 77a910b0, so build-test will show red on tests this PR did not touch.
Earlier findings
- My round-3 finding (the Tools page cost mixed the ledger's gross with the library's net): fixed. I traced the fix end to end:
proxy/dashcapture.gosetse.DeferCostUSD = d.gross - d.netinside the deferFacts block, beforePriceModeruns infinish. So the stored cost is the ledger's own cost, taken before the net moves to the lever.dash/tooldeferpanel.gonow sumsSUM(r.defer_cost_usd)intoCostUSD. The derivationGrossUSD - NetUSDis gone.dash/schema.goaddsdefer_cost_usdto the fresh DDL and toadditiveColumns, andbackfillDeferCostruns on both migrate paths. Old rows getgross - net, which is exact for them, because their stored net was the ledger's net. The WHERE clause (defer_tokens > 0 AND defer_cost_usd = 0 AND defer_gross_usd > defer_net_usd) makes it idempotent.dash/query.goanddash/store.gocarry the column through the read and the write, in the same position on both sides.TestTheToolsPageCostIsTheLedgersCostOnAPricedRequestseparates the two derivations by hand: lever 0.0026, ledger net 0.0016, cost want 0.0004.TestTheLedgerCostOfAnOlderRowIsFilledByTheMigrationOncechecks the migration fills an old row once, over two opens.- The tile caption, the section note and the
renderDeferNetdocstring no longer say that gross less cost is the net. They name the ledger for gross and cost, and the lever for the net.
- Reviewer 2's round-3 non-blocking items: fixed. The caption at
dash/ui/tools.js:1194now reads "ledger: ... of definitions kept out; ... for the names list and searches". The stale comments are corrected: the panel header,CostUSD, the held-estimate block, and thesaved_usdtexts indash/schema.goanddash/event.go. - My round-3 non-blocking on the negative-zero guard: I accept the author's rejection. My claim was that
deferFig - DeferSearchUSDcannot make a negative zero from finite inputs. That is wrong whendeferFigitself is-0: under IEEE,-0 - +0 = -0. The guard turns that into+0, so it is not dead code. The new comment says exactly this. Keeping the guard is right. - The owner's decisions of 2026-11-10T10:24:50Z (a person's comment; I checked each point):
- Decision 1, the new card split: the owner said yes. The code does what the owner accepted. The total stays the same; only the card that shows the deferral saving changes.
- Decision 2, the OpenAI Chat cache-write usage: the owner said yes, in its own issue or PR. This PR does not do it. Nothing to check here.
- The merge conditions: the conflict with
mainis resolved (5f256f2d), the round-3 finding is fixed, and this review is the round at the final head. The PR was still a draft when I wrote this. Note 1 below says why the head also needs one more merge ofmain.
The new commits
baa69308fix(dash): Read the deferral cost from the ledger, not from gross less the lever. This is the fix for my finding. Verified above.1d1cdda5docs(dash): Say what the Tools page figures are after the lever moved. Text only: the tile caption, the section note, therenderDeferNetdocstring, and the field comments. I read every hunk. The texts now match what the code does.
The merge
5f256f2d merges origin/main at a3495863. Both sides appended columns to the requests table: main added 7 limit columns (#991) and 40 token columns (#999); this branch added defer_cost_usd. I counted each side of the write and the read: requestCols, scanRequest, insertBatch and the Exec args all hold 144 columns in the same order (97 static + 7 + 40). In dash/accountant_price.go, main's token figures interleave with this branch's deferFig move: the token side counts tooldefer once on the component row, while the dollars sit in the lever. No double count. The migrations are additive on both sides and run in an order that works for a database from either history.
Notes, not blocking
- Merge
mainagain before this PR merges. The owner said to wait for the band fix before mergingmainin. The branch mergedmainata3495863at 10:39:57Z. The band fix77a910b0(#1035) landed at 10:48:09Z, 8 minutes later. So this head still has the bug that mademainred:context-guru-plugin/scripts/cg.pydefinestokens_texttwice, at lines 259 and 572, and the second shadows the first. The build-test job runsmake cover, which runsgo test ./..., so it runs the two failing band tests. Build-test was still pending when I wrote this; from the code, I expect it red. This PR does not touchcontext-guru-plugin, so the merge is conflict-free, and merging this PR intomaintakesmain's fixedcg.py. One merge ofmainat77a910b0closes this. - The backfill edge the author named. A row written by the new code, priced, with a ledger cost of exactly 0, would be refilled with
gross - leveron the next open. I agree it is practically unreachable: when the ledger prices the gross, it also prices the names list, and a names list costs more than 0. Accepted as is. A run-once marker would remove the doubt. - The backfill scans all
requestsrows on every open. The WHERE clause has no index to use. On the scale the repo itself measured (1.58M rows, about 2 s), this adds a fixed cost to each open. The same run-once marker as note 2 would remove it.
What I checked
- Last review: round 3,
9f25e1c4bb083e1f9543305d084ed5af2533a63c, 2026-11-10T10:09:57Z. - New commits read: 21 in
9f25e1c4..HEAD. Two are this branch's own:baa69308and1d1cdda5, read hunk by hunk with the code around each change. One is the merge5f256f2d, reviewed as a resolution. Eighteen arrived frommainthrough the merge; they were reviewed by their own PRs, and I checked them only where the merge touches this branch's files. - Read in full: 6 reviews, 5 comments, 0 inline comments (from
.review-in-reviews.txt,.review-in-comments.txt,.review-in-inline.txt). - New items since my last review: the commits above; the author's reply of 2026-11-10T10:20:32Z (each claim checked against the code); the owner's decisions of 2026-11-10T10:24:50Z (checked, as listed under Earlier findings); the PR state (still a draft), the CI checks (build-test pending, the rest pass), and
main's head (77a910b0, withgit diff a3495863..77a910b0read to confirm the band fix is the only commit this head misses). - The fix for my round-3 finding, end to end: the write in
proxy/dashcapture.goand its order againstPriceMode; the read indash/tooldeferpanel.go; the column indash/schema.go,dash/query.goanddash/store.go; the migrationbackfillDeferCoston both migrate paths; the new tests indash/defer_split_test.goand the added assertions inproxy/tooldefer_ledger_test.go. - The merge resolution, by exact count: the columns and placeholders on both sides of the write and the read (144 = 144), the
accountant_price.gointerleave ofmain's token figures with this branch'sdeferFigmove, and the additive migrations for all three column sets. - Not verified by running: I read the code only, as this round's rules say. The author's own "Not verified" list stands: real traffic, the migration on a database with real old rows, and the tile wording in a browser.
Brings the band window-saving fix (#1035). Assisted-By: Claude (Anthropic AI) <[email protected]>
…mment (#908) data-dependence.md listed eight deferral columns and said the net does not repeat the library's pricing. There are nine, and on a priced request the net is the library's figure less the search cost. The guard comment said deferFig can be -0. It cannot: a map entry starts at +0 and +a + -a is +0. The guard stays as a plain-zero safeguard. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…720) The sweep can now apply its cut on a warm cache, behind a cost gate (#491, #1030 item 2). Opt-in: warm: true in the extract_llm_sweep config, off by default; no shipped preset sets it. When on, it adds: the warm apply path with a gate that weighs the saving over the turns left against the rewrite cost; batching reuse (#747); the turns-left model; accumulation (refused drops carried in memory, the newer verdict wins); recheck reasons logged before the gate; a quote check against the body the model read; and the streamed-usage fix (#745). Behavior change: none by default. The warm path runs only when a config sets warm: true. On a flat-rate backend such as IBM Bob, the gate's rewrite cost is about 0, so cuts pass; the operator must add a price entry with cache_read == cache_write == input, or the gate uses Claude-class rates and stays strict. The PR body documents this. Owner's yes, 2026-11-10, in the integrator session: "approve both" (merge on main, opt-in, keep testing it through Bob users). Data dependence: the extract_llm_sweep row already covers the held answers and the carried drops (in memory, metadata only). Reviews: 2 offload reviews (GLM), round 11 (owner granted rounds up to 13), both approve at 8255b96. 8f90546 is a rebase onto main d407191 that changes only the column lists in dash/query.go and dash/store.go (#720's sweep_false_expands_warm after #1003's defer_cost_usd); git range-diff shows the other commits unchanged. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
Refs #908. Does not close it: the numbers are not checked on real traffic.
Problem
Tool defer failed the accountant checks and was double counted.
defer_loadingflag. The library saw no shrink, only added bytes, and booked them as a cost./api/tool-defershowed a different figure.What changed
The accountant side is
9fdef120and804636c3. The round 1 fixes are532389b9,e5edfdafand22a9caa1. The card split from the review of 2026-11-10 is32a770f9and9f25e1c4. The Tools page cost isbaa69308and1d1cdda5. The rest is two merges ofmainand a docs fix (829a92f4).9fdef120reports deferral's edits totoolsunder atooldeferoperator, so the sum and conservation checks hold. It held the library's dollar figure out.804636c3replaces that hold-out. The library now prices the deferral itself, as accountant R56 describes (docs: Say how a host reports a defer_loading deferral (#60) accountant#61).billedBody(proxy/accountant_billed.go) cuts each deferred definition to a stub in the accountant's copy only. The library sees an ordinary shrink oftoolspositions.envelopeOpsForreports onecontext-guru.tooldeferoperation for each deferred tool. Each keeps its owncg:toolschema:...ChangeID. The library replaces an operation by ChangeID, so a thread state written by the previous code is replaced and not orphaned.cache_control.acc_fallback ... deferral_unplaced.dash/accountant_price.gois gone.The library needs no change and no pin bump.
Behavior change: the deferral saving moves from the preset card to the deferral card
Before this PR the Overview showed the deferral saving twice over, partly in the ledger's net and partly in the library's figure, and the library booked the names list as a cost. After it:
tooldeferfigure leavesbaseline - cost, so it is no longer in the "Your preset" card. It goes to the deferral lever:defer_net_usd = library tooldefer row - search cost. The total is the same. The figure is moved, not added.estimate_held), the lever keeps the ledger's net as before, and the deferral is left out of the held estimate. The saving appears in one place./api/tool-defer, the Tools page,SavingsTotals, the Overview and the daily series all readdefer_net_usd, so the net column has one meaning.defer_cost_usd, because on a priced request gross less the lever is the gap between two tokenizers.backfillDeferCostfills older rows withgross - net, which is exact for them.Money.GrossandCostin the ledger are unchanged.Affected: the Overview "Your preset" and "Tool deferral" cards, the Tools page and
/api/tool-defer.Decisions for the owner
Both were answered "yes" on 2026-11-10 (comment of 10:24).
Tests
go test ./proxy ./dash ./tooldefer ./internal/deferred ./applypasses.go vetandgofmt -lare clean.proxy/tooldefer_stub_body_test.gocovers: no fallback, a positivetooldeferrow, and unchanged wire bytes. It checks that Overview's net and total equalbaseline - cost, so deferral counts once. Loading a tool later is a cost, tested indash.TestToolDeferPricedRowIsTheLibrarysFigureLessTheSearchCostpins the exact lever on a priced request that ran a search.TestToolDeferFactsReachTheDashboardRowruns a held first request.mainis merged in at77a910b0, which has the band window-saving fix (fix(plugin): the band's window saving survives the #989 change #1035).Not verified
The
defer_cost_usdbackfill runs on every open and scans all rows. It was tested on one synthetic old row, not on a database with real old rows. A row written by the new code with a ledger cost of exactly 0 would be refilled wrongly. I think that cannot happen, and I have not tested it. A run-once marker would remove both doubts.The Tools page tile wording was not looked at in a browser.
No real traffic. The fake provider bills one token per four bytes.
The harness figure of +$0.0185 is unchecked. The harness scripts are gone.
Pricing for models that ignore
defer_loadingis untested. The accountant already falls back there withunpriced, because Chat Completions usage has no cache-write tier. That is not new.A request where the client defers its own tools keeps their definitions in the accountant's copy, but the provider bills nothing for them. The tokens-per-byte ratio of that request is then diluted, so its dollar figures are slightly low. The error is conservative and small. Not measured.
The
deferral_unplacedguard has only unit tests, because deferral's own gate stops such a deferral from reaching a real request.Assisted-By: Claude (Anthropic AI) [email protected]