Skip to content

fix(tooldefer): one savings figure for tool deferral, from the accountant - #1445

Merged
amiddavid merged 11 commits into
mainfrom
fix/tooldefer-one-figure
Nov 26, 2026
Merged

amiddavid merged 11 commits into
mainfrom
fix/tooldefer-one-figure

Conversation

@amiddavid

@amiddavid amiddavid commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Owner approvals (David Amid, 2026-11-26, in the integrator session): part 1 ("1445 yes": one tool-deferral figure from the accountant) and part 2 (#1465: one Withhold gate). The owner granted up to 6 review rounds for the fail-open fix.

Fail open (#1504): the accountant step in capture.finish and the deferral ledger hook run under a recover that logs and drops. A panic there no longer escapes into the handler. The dashboard row is still written (marked no_result), and the early-scan stop and the log line still run.

Second behavior change: one gate rule (#1465)

Dashboard, /stats and the metrics push all gate with accountant.Withhold (#1465). Dashboard figures rise on requests with a check_sum failure that no operation claims (Check.Claims 0). The owner approved this in the integrator session, 2026-11-26. accrec.Gate calls Withhold for the library's gates (checks, unpriced). The host keeps its own: dropped operations, observe, the size bound (Withhold's bound counts tool declarations and the host's measure does not, and the push gives no measure), figure without row, duplicate name, acted without figure. Fixes #1465.

Behavior change: needs a human's yes before merge

Tool deferral now has one savings figure: the accountant's. Three shown figures change.

  • Who: every user with tool deferral on (the ultrahigh preset, bob-ultrahigh). It affects /stats (tool_defer.ledger and accounts), the Tools-page deferral panel (/api/tool-defer), the Overview "Tool deferral" line, and the dashboard component row tooldefer.
  • Old:
    • /stats and the panel used tooldefer.Price. It had no tier re-rate.
    • The component row had the re-rate but not the search-turn costs. The panel net was the component figure less the ledger's search cost.
    • A held request (no thread history) kept the ledger's net on the lever.
  • New:
    • All of them show the accountant's figure for tooldefer: body change, tier re-rate, less names list, less search-turn costs.
    • Gross is the saved side of that figure. Cost is gross less net.
    • A held request books no lever. Its deferral figure joins the held estimate (estimated_saved_usd) with every other component's, as the repo rule for held requests says.
    • A request with no accountant figure (unpriced model, no result, or a held estimate) books no dollars. Its counts stay. It counts in unpriced_requests, as a held request does.
  • Dashboard off (the default): works. The figure comes from the always-on accountant (feat(proxy): run the accountant on every request, with or without the dashboard #1451, merged), so /stats shows deferral dollars with the dashboard off, the same as with it on.
  • Metrics: the shared metrics sink now books the tooldefer spend calls as added cost on the tooldefer component, so the cg_* and llm_savings_* metrics change. Each call is priced at its own size.
  • Off switch: none. This is a change of how a figure is computed, not a feature.

Same /stats JSON shape (gross_usd, cost_usd, net_usd). Gross and cost no longer match the old numbers exactly (see Open questions).

Local tests: waived (owner rule)

Summary

  • One figure for tool deferral, from the accountant.
  • The search turns are now accountant spend operations on the tooldefer operator.
  • The ledger and the panel read the accountant figure. tooldefer.Price is removed.

Fixes #1441

What changed

The search-turn costs, as spend operations (accrec.DeferSpendOps). Each is a Call with its own usage, with no ChangeID.

Operation Usage Estimated?
defer-search-output Output = the search calls' output tokens Yes today: usage does not give it, so 30 per search, as the ledger did
defer-search-second-pass Input = billed weight of the loaded definitions Yes: our token weight, scaled by the billed factor
defer-search-next-write CacheWrite (and CacheWrite1h on a 1-hour thread) = the same weight Yes: the next request has not happened

Each op carries Params estimated=true.

Where the next-request write is booked. On this request's ops, not the next one's. Why:

  • This response causes the cost. It loads the definitions.
  • The next request's body has them in its client transcript. The library sees no change there, so it has no op to carry the cost.
  • Booking on the next request needs state kept across requests. This is simple and the same as the old ledger.
  • The cost to the user is an estimate. The next request may never come.

Pricing of the spend calls. The library prices them (accountant.Figure, v0.9.0: a separate bill, CallUSD). The Calls name no model, so they price on the request's own model, which is the one model the dash hostPricer prices. accrec.DeferSpendUSD sums the library's spend lines on the tooldefer operator. The dashboard row takes that sum off the component figure, and /stats takes it off in accrec.DeferMoney (net = figure less spend; gross = first plus replay; cost = gross less net). spendUSD and bookDeferSpend are removed from dash. No dollar math is added in proxy/, dash/ or tooldefer/.

One gate for the row and /stats (accrec.Gate). It holds the dashboard's decisions: dropped operations, observe, fatal checks, unpriced operations, the size bound, a figure with no row, duplicate names, and a component that acted with no figure. The row and accFigure both call it, and accrec.Held (no thread history) holds the request on both. So a request the row refuses is unpriced on /stats too.

The panel and /stats read the accountant figure, set on the request row by PriceMode:

  • net_usd = the tooldefer component figure.
  • gross_usd = its saved side (first plus replay).
  • cost_usd = gross less net.
  • Ledger keeps the counts (Add) and adds dollars (AddMoney) from the accountant figure when the request is priced. A held request (no thread history) counts as unpriced, as on the panel. It no longer prices anything.

Removed: tooldefer.Price, Money.SearchCost, Event.DeferSearchUSD, Booked.Money. Flow.Prices and Request.PromptTokens stay as Deprecated fields, unused, so library users still build.

Also updated: the tool-deferral comments, the Tools-page tile text, 3 golden files (one description string), docs/dashboard.md.

How it was tested

macOS, Go 1.27.4. Plain go test, no local-tests.sh.

  • go build ./... and go vet ./...: clean.
  • go test: tooldefer, accrec, accwire, lifecycle, metrics, proxy, proxyapp, dash all pass.
  • -race -run on the new and changed tests in tooldefer, accrec, proxy, dash: pass.

New or rewritten tests:

  • 1 search, 2 loaded definitions (dash/defer_onefigure_test.go, TestDeferSearchTurnsArePricedFromTheirOwnUsage, and proxy TestToolDeferPricedRowIsOneFigureWithTheSearchTurns through a real streamed search): the component figure, the lever, the panel columns, /stats and /api/tool-defer show one figure. The request carries 3 spend ops.
  • Above a price line (TestDeferFigureAboveAPriceLineHoldsTheReRateAndTheSearchTurns, gpt-5.6, line 272,000): the re-rate is in the figure, the lever and gross.
  • Unpriced model (TestDeferUnpricedModelBooksNoFigure, TestLedgerCountsAndMoney): no dollars; unpriced_requests counts it.
  • Held request: no lever, figure in the held estimate (TestPriceMode_AHeldRequestHoldsTheDeferralWithTheRest).

Mutations (both fail the tests):

  1. Drop the spend ops (accDeferSpend returns at once): TestToolDeferPricedRowIsOneFigureWithTheSearchTurns fails ("0 tooldefer spend operations, want 3").
  2. Make the ledger take a figure other than the row's (gross as net): the same test fails ("/stats ledger ... want net ... from the rows"). The old Price cannot be wired back, since it is removed; this is the equivalent.

Metrics note

Data dependence

Metadata only. Token counts, usage, and our token weights. No text.

  • Off: no deferral, nothing booked.
  • Metadata only: works, as before.
  • Everything: the same.

docs/data-dependence.md changes in the "Dashboard database" row: it said gross and cost came from the proxy ledger and net from the library less search cost. It now says all three come from the one accountant figure. The data dependence does not change.

Open questions

  1. Held requests. They now book no lever (before: the ledger's net). Is that the wanted rule? It matches every other component, and it is part of the behavior change above.
  2. Gross is not the old gross. The old gross was our tokenizer's weight of the deferred definitions at the request's tier. The new gross is the library's saved tokens (definitions less their stubs) plus a share of the re-rate. The numbers move a little.
  3. The search output stays an estimate (30 tokens per search). The usage does not give the search calls' output. A later change can read it from the response.
  4. The spend ops add no tokens to the component row. The row tokens hold the body change only.

Fixes #1504.

…tant

Tool deferral had two figures. The /stats ledger and the panel used
tooldefer.Price. The dashboard component used the accountant figure.

Now the accountant figure is the only one.
- The search turns are booked as three spend operations on the tooldefer
  operator: the search output, the second pass, and the next request's
  cache write. Each is a Call with its own usage.
- The dash prices a spend Call at its own prompt size.
- The panel columns and the /stats ledger read that figure. Net is the
  component figure, gross is its saved side, cost is gross less net.
- tooldefer.Price and Money.SearchCost are removed.
- A held request books no lever. Its deferral figure joins the held estimate.

Fixes #1441

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid amiddavid added the openai OpenAI / Codex traffic and pricing label Nov 25, 2026
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Note: the owner rule on savings (2026-11-25)

The owner rule: the accountant library is the source of every savings figure. This PR adds 2 small dash functions, spendUSD and bookDeferSpend. They price the 3 new spend calls inside the one AccountantFigure path. The library returns those calls for the host to price. They are interim. rossoctl/accountant#115 adds accountant.Figure, which prices calls (CallUSD). #1440 then removes both functions.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: blocking

Findings

  1. docs/data-dependence.md:237 — the generated page was edited by hand; the row file was not
    • What fails: the next go run ./cmd/gen-datadep rebuilds the page from the row files and silently reverts this PR's data-dependence text to the old wording ("the proxy's own ledger", "the net is the ledger's own net").
    • Proof: the diff changes only docs/data-dependence.md (git diff 41152b61..HEAD --stat -- docs/data-dependence/ is empty). cmd/gen-datadep/main.go:1 says the command "writes docs/data-dependence.md from the row files under docs/data-dependence/". The row file docs/data-dependence/features/dashboard-database.md:10 still carries the old sentences the PR removed from the page: "The gross and the cost are the proxy's own ledger" and "On any other request the net is the ledger's own net". CLAUDE.md forbids editing the page by hand and requires the row file edit plus a regen for a PR that changes a feature.
    • Fix: move the new wording into docs/data-dependence/features/dashboard-database.md, then run go run ./cmd/gen-datadep so the page and its source agree.

Non-blocking

  • dash/schema.go:263-264 — the defer_cost_usd comment now contradicts itself. The first line states the new rule ("gross less net, the accountant's one figure"). The next sentence keeps the old rule ("defer_net_usd ... is the library's figure less the search cost, so gross less net no longer says what the deferral cost"). Under this PR, net IS the figure and gross less net IS the cost. Update the second sentence.
  • tooldefer/flow.go:56-57 — Flow.Prices is dead in the library. Book no longer prices, and no tooldefer file reads f.Prices any more. The proxy still sets it (proxy/tooldefer.go:280). Its comment ("prices a model for the ledger") is now wrong. Remove the field or fix the comment in a follow-up.
  • tooldefer/ledger.go:57-59 — Request.SearchOutput says "from usage when known", but no production code sets it (Book never does). The search output is always the 30-per-search estimate, so OutputEstimated is always true in production. Pre-existing before this PR; the new spend ops inherit it. Worth an issue of its own.
  • Behavior change to confirm. This PR changes what users see: a request the accountant held or could not price now books no deferral dollars on the lever, in /stats and in /api/tool-defer (before: the ledger's own net). The figure also gains the tier re-rate. CLAUDE.md needs this named at the top of the PR with a human developer's yes. I did not read the PR body (round 1 independence), so I cannot confirm it is there. The tests cover the change (held, unpriced, fallback paths), so I assume it is intended.
  • Old rows keep the old meaning. Rows written before this PR hold the ledger's gross, net and cost; rows after hold the accountant's one figure. /api/tool-defer totals mix the two across the switch. Inherent to the change; no migration is possible without re-pricing. No action asked.

What I checked

  • Read the full diff (git diff 41152b61..HEAD) and the code around each hunk: accrec/deferspend.go, accwire/spend.go, tooldefer/{flow,ledger}.go, dash/{accountant_price,event,overview,tooldeferpanel,schema,fallback}.go, dash/ui/tools.js, proxy/{accountant_wire,dashcapture,tooldefer}.go, and every changed test.
  • Traced the one-figure math end to end: SearchSpend (token counts) → accrec.DeferSpendOps (three spend operations) → accDeferSpend in BeforeCompute → bookDeferSpend/spendUSD in AccountantFigure → accOverride (lever, gross, cost) → deferBook → Ledger.AddMoney. The spend lowers ByComponent and DeltaUSD once; the lever move subtracts deferFig from the baseline once, so the total is unchanged (the new dash tests assert this).
  • Verified the accounting arithmetic: spendUSD splits the write into 5m and 1h parts the way accountant.Usage defines them (CacheWrite1h is a part of CacheWrite), and the prompt-size param picks the tier for all three ops. Cross-checked the expected numbers in dash/defer_onefigure_test.go against gpt56() (2x input above 272k, 1.5x output) and accTestPrice.
  • Checked ordering and concurrency: lifecycle.Finish runs deferLedger (which sets deferFacts and deferBook) synchronously before cp.finish calls PriceMode and then deferBook; Ledger.Add and AddMoney both lock; the account for a tenant always exists before AddMoney because Add ran first; both deferFlow(nil) calls return the same handler-wide ledger.
  • Checked the accountant module (v0.8.0): spend operations in a main Compute are a supported kind, badCall/resultUnknown cannot fire on the ops this PR builds (usage always non-zero, CacheWrite1h <= CacheWrite), and empty ChangeID on a spend is allowed.
  • Checked fail-open: no new error path can drop a request; the spend path is skipped when accReq or deferFacts is nil, and every gate (!priced, held, fallback) degrades to zero dollars plus an Unpriced count, never to a wrong figure.
  • Checked for leftovers: no remaining reference to DeferSearchUSD, Money.SearchCost or tooldefer.Price; accOverride is the only writer of the three Defer*USD fields; no time.Sleep in the new tests.
  • Did not run builds or tests (not approved for this review).

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: blocking

Findings

  1. proxy/tooldefer.go:415 — with the dashboard off, /stats deferral dollars silently become 0, and the requests do not count as unpriced

    • What fails: a proxy started without --dashboard (the default, DASHBOARD=false, proxyapp/main_run.go:153) and with deferral on (ultrahigh). Each deferred request runs Book → Ledger.Add, so /stats tool_defer.ledger counts requests, searches, deferred_tokens. But deferBook is set only under if ok && cp != nil, and cp is nil when the dashboard is off (newCapture, proxy/dashcapture.go:237). AddMoney is never called. So gross_usd, cost_usd, net_usd all read 0 and unpriced_requests reads 0. A reader sees "deferral saved $0" on real traffic. Before this change, Ledger.Add(r, p) booked dollars from f.Prices (the proxy price table) with no dashboard needed.
    • Proof: AddMoney has exactly one non-test caller, the deferBook closure at proxy/tooldefer.go:419, and the closure is created only inside if ok && cp != nil (proxy/tooldefer.go:415). /stats serves snap.ToolDefer = h.deferStats() regardless of the dashboard (proxy/proxy.go:2768), and deferStats reads the same ledger (proxy/tooldefer.go:447). This also breaks the PR's own stated rule: "A request with no accountant figure ... counts in unpriced_requests" — these requests count nowhere. The existing dashboard-off tests (proxy/tooldefer_866_test.go:147, proxy/tooldefer_test.go:208) assert counts only, so nothing fails.
    • Fix: book the dollars (or at least the Unpriced count) without cp. Either give deferLedger a cp == nil path that calls ledger.AddMoney(tenant, tooldefer.Money{}, false), or keep a fallback price in Book for that case. If dropping the dashboard-off dollars is intended, name it in the behavior-change section and get the owner's yes — it changes the default deployment's /stats.
  2. docs/data-dependence.md:237 — the generated data-dependence page was edited by hand; the row file was not, so the next generator run reverts the change

    • What fails: the "Dashboard database" row text was rewritten in docs/data-dependence.md (the generated page) to describe the new one-figure rule. The source row docs/data-dependence/features/dashboard-database.md still holds the old text ("The gross and the cost are the proxy's own ledger ... On any other request the net is the ledger's own net"). The first later PR that touches any row file and runs go run ./cmd/gen-datadep rebuilds the page from the row files and silently restores the old, now-wrong text.
    • Proof: git diff 41152b61..HEAD -- docs/data-dependence/ shows a change to docs/data-dependence.md only; docs/data-dependence/features/dashboard-database.md is unchanged (verified: the old sentence is still in the row file at line 10). CLAUDE.md: edit the feature's row file, then run the generator; never edit the generated page by hand. cmd/gen-datadep/main.go:1 confirms the page is written from the row files.
    • Fix: move the new text into docs/data-dependence/features/dashboard-database.md and run go run ./cmd/gen-datadep so the page is regenerated, not patched.

Non-blocking

  • dash/schema.go:262-263 — the comment under defer_cost_usd still says "gross less net no longer says what the deferral cost", which the new first line (line 261) now contradicts. Update the stale lines.
  • dash/tooldeferpanel.go:50 — "Unpriced is the changed requests whose model has no price" is now too narrow: held requests and requests with no accountant result also count there (proxy/dashcapture.go:875).
  • The shared metrics sink now sees the new spend ops: acmetrics.Sink.Observe books every spend Call as added tokens/USD on the tooldefer component (accountant metrics v0.8.0, metrics.go:173-179, reached through proxy/metricsink.go:78). The PR does not name this cg_* metrics change. Also, the sink prices the spend at the call's own token size (callSize), not the stated prompt_tokens, so above a price line the cg_* figure and the dashboard figure can disagree.
  • tooldefer.Request.SearchOutput is never set by Book (tooldefer/flow.go:342-351), so SearchSpend.OutputEstimated is always true today. The PR names this in Open questions; the struct comment implies usage can state it.

What I checked

  • Read the full diff (29 files) and the code around each change: accrec/deferspend.go, accwire/spend.go, tooldefer/flow.go, tooldefer/ledger.go, proxy/tooldefer.go, proxy/dashcapture.go, proxy/accountant_wire.go, dash/accountant_price.go, dash/event.go, dash/tooldeferpanel.go, dash/overview.go, dash/schema.go, dash/fallback.go, the UI and docs, and every changed test.
  • Traced the wiring: deferLedger runs in lifecycle.Finish's Ledger step, synchronously before cp.finish on the same goroutine (proxy/proxy.go:1860, lifecycle/finish.go:51-57) — no race on c.deferBook. h.deferFlow(nil).Parts().Ledger and deferStats' ds.ledger are the same object (proxy/tooldefer.go:267-283, 447).
  • Checked the spend ops against the accountant library v0.8.0: Request.Add after EndRequest is a plain append; spends are not stored as active changes, do not trip the unique-change, sum, spans or size checks, and pass badCall (CacheWrite1h ≤ CacheWrite, non-negative counts). Compute does not price spend Calls itself, so there is no double count with dash.bookDeferSpend.
  • Checked the pricing math: spendUSD prices output at the output rate, the second pass at the input rate, the write at the 5m or 1h write rate, each at the stated prompt tier — the same rates the old tooldefer.Price used, verified against tierUSD and modelinfo.Price.CacheWrite1h.
  • Checked AccountantFigure/accOverride invariants: spends lower ByComponent[tooldefer] and DeltaUSD but not ByComponentFirst/ByComponentReplay, so gross = saved side + re-rate share, net = figure, cost = gross − net; the lever takes the whole figure out of the baseline, so the request total is unchanged. Spends are skipped in accPrices, reRateUSD, countedSavedTokens and heldFloorUSD, so they distort no other figure.
  • Checked the held path: a held request books no lever, its figure joins EstimatedSavedUSD, and the ledger counts it as unpriced — as the tests assert.
  • Checked that the removed symbols (tooldefer.Price, Money.SearchCost, Booked.Money, Event.DeferSearchUSD) have no remaining readers.
  • Live tests were not run (not approved). Read the code only.

…pendence source

- With the dashboard off no accountant runs, so no figure exists. The
  ledger now counts the request as unpriced, with no dollars.
- Revert the hand edit of the generated data-dependence page. The new
  wording is in the dashboard-database row file, and the page is regenerated.
- Fix three stale comments.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Nov 26, 2026
- Docs: the metrics-push row says the savings set works with no dashboard
  and names the machine-id file and its path. The accountant row and the
  accFigure comment say the hook has no production caller yet (#1445).
- finishAccountant drops the record in a closure, after the join sets it.
- The lean capture starts at the same moment as the dashboard capture.
- Remove an unused parameter in the test helper and a stale comment.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Nov 26, 2026
… dashboard (#1456)

feat(proxy): run the accountant on every request, with or without the dashboard

The accountant ran only inside the dashboard capture. With the dashboard off
(the default), no request got a Result, the llm_savings metrics push was
refused, and #1445 would show $0 in /stats.

- The savings tracker is built always. A lean capture carries the accountant
  when cp is nil (Handler.accCapture).
- accCompute prices once and is idempotent. finish and the new accFigure hook
  share it, so the order of the two does not matter.
- accFigure gives dollars per component, priced with the host pricer at the
  model's prompt tiers (Price.At). It fails open.
- The metrics push no longer needs the dashboard for the savings sink.
- Data dependence updated. Nothing new is stored.

Fixes #1451

feat(proxy): price the per-request figure with accountant.Figure (v0.9.0)

Bump accountant and accountant/metrics to v0.9.0. The hook accFigure now calls
accountant.Figure with the host pricer (PriceAt) and returns USDFigure. It
applies accountant.Withhold with no size gate. No pricing stays in proxy/.

perf(proxy): finish the accountant off the handler path when there is no dashboard

finish runs in the handler's defer, so waiting there for the accountant job
held the next request on a keep-alive connection. The lean capture now
finishes on its own goroutine. accCompute takes a lock because the deferral
ledger's hook and that goroutine can both call it. The benchmark reports the
time to the response head next to the total.

fix(proxy): round-1 fixes for the always-on accountant

- Docs: the metrics-push row says the savings set works with no dashboard
  and names the machine-id file and its path. The accountant row and the
  accFigure comment say the hook has no production caller yet (#1445).
- finishAccountant drops the record in a closure, after the join sets it.
- The lean capture starts at the same moment as the dashboard capture.
- Remove an unused parameter in the test helper and a stale comment.

Behavior changes (the accountant runs on every request; the metrics push starts without the dashboard when a collector URL is set; machine-id file without the dashboard; accountant v0.9.0 with #118 and #120) approved by the owner in the integrator session: "1456 yes". Proxy-boundary check: wiring only; fail-open kept.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
Wire the deferral ledger to the always-on accountant hook (#1451).
- deferLedger reads accFigure on the dashboard's capture or the lean one.
- accrec.DeferMoney maps the library figure to gross, cost and net.
- accrec.FigureWithheld and accrec.Held hold the gate decisions, so
  proxy/ stays wiring.
- A spend call prices at its own size, as accountant.Figure does.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Replies to round 1, and the merge of main

ab6d41eb merges origin/main (8dee073a, #1456: the accountant now runs on every request) and fixes the round-1 findings.

Reviewer 1, finding 1: with the dashboard off, /stats showed $0 and nothing counted as unpriced. Fixed by the owner decision "run the accountant always" (#1451, merged as #1456).

  • deferLedger now calls ac.accFigure(ctx, u, usageOK) on the dashboard's capture or on the lean one, so /stats shows the figure with the dashboard on or off. The $0 fallback is gone. ok=false books unpriced.
  • The gate decisions moved out of proxy/ into accrec. FigureWithheld covers observe mode, dropped operations and Withhold. Held covers penalty_unknown.
  • TestToolDeferLedgerCountsSearchesOnEveryPath covers the dashboard-off case. The first request of a thread is held (unpriced). The second shows its figure.

Both reviewers, finding 2: the generated data-dependence page was edited by hand. Fixed. The hand edit is reverted. The wording is in docs/data-dependence/features/dashboard-database.md, and the page is regenerated.

The mapping is in accrec.DeferMoney and prices nothing. Net is ByComponent[context-guru.tooldefer] less its spend lines. Gross is first plus replay. Cost is gross less net. TestDeferMoneyMapsTheLibrarysFigure runs the real accountant.Figure.

The interim dash pricing: spendUSD and bookDeferSpend stay until #1440 moves the dashboard onto accountant.Figure. A spend call now prices at the size of its own usage, as accountant.Figure does.

Tests (macOS, Go 1.27.4): build and vet are clean. Plain go test passes on tooldefer, proxy, proxyapp, dash, accrec and accwire. -race -run on the new tests passes, and the dashboard-off test also passes with -race -count=5.

Local tests: waived (owner rule)

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.332 offload-review skill, @amiddavid's session resumed 2 of 2 2 of 4 ab6d41ebf9d3 blocking

Verdict: blocking

Earlier findings

  • Data-dependence page edited by hand (mine and reviewer 1, round 1): fixed. The new wording is in docs/data-dependence/features/dashboard-database.md and the page is regenerated. I verified: the page contains the row body verbatim, and the old sentence ("the proxy's own ledger ... the net is the ledger's own net") is gone from both files.
  • Reviewer 1, finding 1 (dashboard off: $0, nothing unpriced): fixed. The merge brings #1456 (the always-on accountant, a lean capture with the dashboard off) and deferLedger now books from cp.accFigure on both paths (proxy/tooldefer.go:416-428). I checked the fix myself: accCapture returns the lean capture when cp is nil, noteModel/noteTrace feed it, and TestToolDeferLedgerCountsSearchesOnEveryPath covers the dashboard-off case (1 held request unpriced, the second one priced with a figure).
  • Stale schema comment (mine): fixed (9acff04d removed the two stale lines under defer_cost_usd).
  • Flow.Prices dead field (mine): fixed as a comment update. The field stays, the comment now says the ledger no longer reads it. Acceptable.
  • Request.SearchOutput never set (mine, reviewer 1): still open, acknowledged in the PR's Open questions. Its own issue, not this PR's.
  • Behavior change (mine, round 1): the human direction is recorded. The owner note of 2026-11-25 states the rule ("the accountant library is the source of every savings figure"), and #1451/#1456 landed it. I accept this as the owner's yes for the figure change.

Findings

  1. proxy/tooldefer.go:424 — the deferral ledger prices the accountant on the handler goroutine, undoing #1456's off-path finish

    • What fails: dashboard off (the default) and deferral on (ultrahigh). Every successful deferred request runs the accountant's job join, Compute and Figure inside the handler's terminal defer, before serve returns. The next request on the same keep-alive connection waits for it. #1456, merged into this PR, moved exactly this work onto go c.finishAccountant so the handler path would not wait; this PR calls it earlier, on the handler goroutine, and the goroutine's own accCompute becomes a cache hit.
    • Proof: proxy/proxy.go:1868 runs the Ledger step of lifecycle.Finish synchronously in the terminal defer. deferLedger (proxy/tooldefer.go:424) calls cp.accFigure → accCompute → accWait (<-job.done, proxy/accountant_wire.go:66) and savings.Price (accountant_wire.go:183). At the base 8dee073, deferLedger did no accountant work (verified with git show 8dee073:proxy/tooldefer.go); the lean path priced only on the finishAccountant goroutine (proxy/dashcapture.go:571). The async tests pin only the pre-forward path (TestAccEndDoesNotWaitForTheAccountantWork); no test pins the terminal defer.
    • Fix: keep noteDefer synchronous (the spends must be known before Compute) and book asynchronously on the lean path: leave a closure on the capture that finishAccountant runs, or spawn the accFigure + AddMoney pair on its own goroutine (accMu already serializes accCompute).
  2. proxy/tooldefer.go:425-428 — /stats books deferral dollars on requests the dashboard refuses, so /api/tool-defer and /stats disagree

    • What fails: a request whose figure fails a dashboard-only gate. The row books $0 and acc_fallback is set, but deferLedger still books the figure into /stats, because accFigure's gates (Withhold, held, model price) are a subset of PriceMode's. The dashboard-only gates: the plausibility bound (FallbackImplausibleSize), TokensBefore unknown, a library figure with no dashboard row, a duplicate row name, a component that acted with no figure (dash/accountant_price.go:510-566). The panel then shows $0 while /stats shows dollars — the PR's own docs claim "the panel, /stats and the component figure agree" (dash/tooldeferpanel.go:14-16), and its test asserts that equality.
    • Proof: accFigure returns ok with Withhold(res, accountant.SizeNotGiven) — the size check is skipped by design ("the size gate is the dashboard's", proxy/accountant_wire.go:210). deferLedger books AddMoney(..., true) on that ok alone. The implausible-size gate exists to stop an inflated figure from a body/usage mismatch: /stats now publishes exactly those dollars. The row gates can fire on version skew between the library and dash.
    • Fix: gate the booking on the same decision. The trace is on the capture (ac.noteTrace, proxy/proxy.go:1425), so FigureWithheld can take the plausibility bound, or the booking can read the row's final fallback on the dashboard path.

Non-blocking

  • Agree with reviewer 1, round 1 (cg_ metrics see the spend ops), still unaddressed.* I re-checked at accountant/metrics v0.9.0: the sink books each spend Call as added tokens and USD on the tooldefer component (metrics.go:189-190), priced at the call's own size. The PR does not name this cg_* change. The author did not reply to it. Name it in the PR's behavior-change section.
  • The two pricing engines (dash's AccountantFigure + spendUSD, and accountant.Figure + accrec.DeferMoney) must stay in step until #1440 removes the dash side. metricsPricer uses the same modelinfo.Price.At tier rule, and TestAccountantFigureMatchesTheDashboardRow plus the proxy ledger tests pin the equality. The dash spendUSD comment already says "Interim: #1440 replaces it". Fine.

What I checked

  • Last review: round 1, 627fc78, 2026-11-25T20:57:13Z
  • New commits read: 2 on the PR — 9acff04d (fix tooldefer: dashboard off unpriced; data-dependence source) and ab6d41eb (merge of origin/main 8dee073, #1456). The merge brought 12 main commits (8dee073a #1456, c4a6dd86 #1414, 25580ca3 #1296, bf68543d #1453, e0ad5c51 #1452, 3ef26ffd #1444, 31476335 #1442, 76eadd35 #1443, 883905bc #1446, e9d4a6f1 #1435, 3606f6ef #1422, 967cc772 #1427), each from its own merged PR; I read this PR's full diff against the new base (git diff 8dee073..HEAD, 30 files) and the merge resolution on the PR's files.
  • Read in full: 2 reviews, 2 comments, 0 inline comments (from the three saved files).
  • New items since my last review: the owner note of 2026-11-25 20:46 (the savings-figure rule — read now, it predates my round-1 post but round 1 was independent), reviewer 1's round-1 review, the author's reply of 2026-11-26 12:53, and the two commits above. I acted on each: verified both round-1 fixes myself (data-dependence by text comparison, dashboard-off by reading accCapture/deferLedger/finish), and reviewed the new wiring as a first review.
  • Traced the new wiring end to end: deferLedger → noteDefer (spend facts) → accFigure (joins the accEnd job, Compute under accMu, accountant.Figure with metricsPricer) → accrec.DeferMoney (net = ByComponent less the spend lines, gross = first + replay, cost = gross less net) → AddMoney.
  • Checked ordering and concurrency: lifecycle.Finish runs the Ledger step before ac.finish spawns the lean goroutine, so noteDefer always precedes the first accCompute and the spend operations are never missed; accCompute is idempotent behind accMu; the dashboard capture needs no lock (its only callers are sequential on one goroutine); the accEnd job writes a private capture.
  • Checked the gates one by one against dash's accOverride: Withhold (v0.9.0) passes penalty_unknown and fails every other unpriced reason, so held and unpriced match the dashboard; server-held history never opens a record (accBegin skipped, proxy/proxy.go:1443-1446), so both sides refuse; the dashboard-only gates are finding 2.
  • Checked DeferMoney against the library's USDFigure (v0.9.0): spend calls are lines, not ByComponent, so subtracting them once is right; TestDeferMoneyMapsTheLibrarysFigure runs the real accountant.Figure.
  • Checked the lean capture's inputs: noteModel, noteTrace (so OpsDropped is seen), observe, pricer, start, accMu are all set on it (accCapture, proxy/accountant_wire.go:158-167).
  • Verified the data-dependence regen by comparing the page text with the row file (verbatim match).
  • Did not run builds or tests (not approved). The author reports plain go test passing on tooldefer, proxy, proxyapp, dash, accrec and accwire (macOS, Go 1.27.4).

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: blocking

Earlier findings

  1. Round 1, finding 1 (dashboard off: /stats showed $0, nothing counted as unpriced): fixed. The merge brings #1456 (the accountant runs on every request) and wires deferLedger to accFigure on the dashboard's capture or the lean one (proxy/tooldefer.go:413-429). I traced the no-dashboard path end to end: New always builds the savings tracker (proxy/proxy.go:467), accCapture builds a lean capture when cp is nil, noteRounds moved before lifecycle.Finish so the ledger hook sees final rounds, and AddMoney runs on both paths. TestToolDeferLedgerCountsSearchesOnEveryPath builds the handler with no dashboard and asserts 1 held request plus the second request's real figure. The PR body now names the dashboard-off behavior.
  2. Round 1, finding 2 (generated data-dependence page edited by hand): fixed. docs/data-dependence/features/dashboard-database.md carries the new wording and the page is regenerated. I compared the page's "Dashboard database" row body with the row file byte for byte: equal.
  3. Reviewer 2's round-1 finding (same data-dependence defect): fixed, agree after checking it myself.
  4. Non-blocking round-1 notes: the dash/schema.go and dash/tooldeferpanel.go comments are fixed, Flow.Prices has an honest comment, and the spend now prices at its own size in both the dashboard and the metrics sink, so the two no longer disagree. Request.SearchOutput is still never stated by Book (the PR names it in Open questions).

Findings

  1. proxy/tooldefer.go:424 — with the dashboard off, a deferred request joins the accountant job on the handler path, undoing #1456's off-path finish

    • What fails: a proxy without --dashboard (the default) and with deferral on. deferLedger runs in serve's terminal defer (proxy/proxy.go:1867, the Ledger step of lifecycle.Finish) and calls cp.accFigure → accCompute → accWait, which blocks on <-job.done (proxy/accountant_wire.go:66) until the accountant's body-hashing job finishes. The handler has already written the response, so this wait holds the next request on the keep-alive connection. The base commit #1456 moved exactly this wait off the handler path: finish says "a synchronous wait would hold the next request on a keep-alive connection" and spawns go c.finishAccountant (proxy/dashcapture.go:571). The merge puts the wait back for every request deferral changed, before the goroutine is even spawned.
    • Proof: deferLedger → accFigure (proxy/tooldefer.go:424) → accCompute → accWait (proxy/accountant_wire.go:60-66), all synchronous in the defer; ac.finish runs after lifecycle.Finish in the same defer (proxy/proxy.go:1895). On main before the merge (git show 8dee073a:proxy/tooldefer.go), deferLedger touched no accountant state, so the no-dashboard path never joined.
    • Fix: keep Book and noteDefer (cheap, no join) in the Ledger step, and book the dollars off the handler path when rec == nil: hand a closure to finishAccountant that calls accCompute, DeferMoney and AddMoney after the join. Or name the latency cost in the PR and get the owner's yes.
  2. dash/accountant_price.go:128 — the row and /stats split a negative re-rate differently, so the "one figure" breaks on tiered models when the operations net-added tokens

    • What fails: a request on a tiered model (a price line) whose operations net-ADD tokens — the case the repo's own comments name as real ("a tooldefer names list, an injected expand or adjudicate declaration", dash/accountant_price.go:623). The sent prompt sits above the line, the client's body would have sat below it. The re-rate of the staying tokens is then a cost. The dashboard row prices it with dash.AccountantFigure, which splits the re-rate over the net SAVERS only (if n > 0, dash/accountant_price.go:128) or drops it on ended_change when there is none. The /stats ledger prices it with the library's accountant.Figure, which charges the net ADDERS (sum < 0 && s.net < 0, accountant v0.9.0 usd.go:423). Tool deferral is an adder on such a request, so the row's defer_net_usd and the ledger's net_usd differ for the same request, and /api/tool-defer (reads rows) disagrees with /stats.
    • Proof: dash/accountant_price.go:128-130 builds shares from operations with n > 0 only; bookReRate splits over those. accountant v0.9.0 usd.go:231 builds shares from operations with n != 0, and usd.go:420-429 picks the savers when the size shrank and the adders when it grew. deferLedger feeds the ledger from the library figure (accFigure → accrec.DeferMoney) on both paths, while PriceMode feeds the row from dash's own figure. The dashboard-on test TestToolDeferPricedRowIsOneFigureWithTheSearchTurns asserts st.Net == netSum from the rows, but its tdPrices price table is flat (no tiers), so the re-rate is 0 and the two implementations cannot disagree in the test.
    • Fix: until #1440 moves the dashboard onto accountant.Figure, make one side follow the other for the re-rate split — either dash picks the library's owner rule (adders own a growth premium), or DeferMoney reads a figure priced by dash's AccountantFigure. Add a test with a tiered price table and a net-adding request that asserts row == ledger.

Non-blocking

  • The ledger skips gates the row keeps: the size gates (TokensBefore unknown or implausible), figure_without_row, acted_without_figure and duplicate_name. On such a request the row books $0 (a fallback) while /stats books the figure, so the panel and /stats disagree. The size gate is a documented choice (the accFigure comment); the row-shape gates have the same effect and no test covers it.
  • TestToolDeferLedgerCountsSearchesOnEveryPath snapshots the ledger right after tdPost returns. Add and AddMoney run in the handler's terminal defer, which can still be running when the client finishes reading the response. The repo rule says a test waits on a condition; this one can flake under load.
  • Dead fields: tooldefer.Request.PromptTokens is set by Book and read by nothing outside tests (SearchSpend dropped it), and Flow.Prices is documented as unread. Worth a cleanup follow-up.
  • The second-pass spend prices at its own size, so above a price line it under-charges the true cost (the pass runs on the whole prompt). Accepted and now consistent everywhere; #1440 can revisit.

What I checked

  • Last review: round 1, 627fc78, 2026-11-25T20:58:02Z.
  • New commits read: 14 — ab6d41eb (merge, wires the ledger to the always-on accountant hook), 9acff04d (round-1 fixes), 8dee073a (#1456 always-on accountant, accountant v0.9.0), c4a6dd86 and 25580ca3 (opencode installer), bf68543d (offload-review locks), e0ad5c51 (timing test), 3ef26ffd (#1444 substitute value rule), 31476335 (#1442 decl-filter pricing), 76eadd35 (#1443 ping input constant), 883905bc and e9d4a6f1 (owner-attribution removal), 3606f6ef and 967cc772 (timing tests). The main-side commits outside this PR's area (opencode installer, keepalive, kvcache) were read at message and file-stat level; every file that intersects this PR (proxy/, tooldefer/, accrec/, accwire/, dash/ pricing, go.mod) was read in full from the 627fc783..HEAD diff.
  • Read in full: 2 reviews, 2 comments, 0 inline comments (from the three saved files).
  • New items since my last review: the author's reply comment (fix summary) — each claim checked against the code; the merge commit's new wiring (accCapture, accCompute, accFigure, finishAccountant, deferLedger) — read in full and traced for ordering and locking; accrec.DeferMoney, FigureWithheld, Held — read and checked against accountant v0.9.0's Figure, USDFigure and Withhold source (ByComponent keyed by the full operator, spend lines carried separately with DirAdded, SizeNotGiven skips the size gate, penalty_unknown does not gate).
  • Verified the generated data-dependence page equals the row file, and that go.mod pins the released tags v0.9.0 (no pseudo-version).
  • Checked concurrency: deferLedger runs on the request goroutine before ac.finish spawns the lean finish goroutine; accMu plus the sequential order keep accCompute safe; accWait is idempotent; noteRounds and noteUpstream complete before the ledger hook reads them.
  • Checked the round-1 invariants that still hold: the spend ops lower the tooldefer figure once, the lever move keeps the request total unchanged, and the held and unpriced paths book Unpriced with no dollars on both the dashboard and lean paths.
  • Live tests were not run (not approved). Read the code only.

deferLedger joined the accountant job in serve's terminal defer. That
undid the off-path finish of #1456. Now it books the facts at once, and
leaves a closure that finishAccountant (no dashboard) or finish
(dashboard) runs after the job.

Also remove the dead Request.PromptTokens and Flow.Prices.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
The dashboard now maps accountant.Figure (#1462). So:
- Drop spendUSD and bookDeferSpend from dash. The library prices the spend
  calls; dash takes the tooldefer spend lines off the figure with
  accrec.DeferSpendUSD, the same sum /stats reads.
- Put the gates in one library decision, accrec.Gate. The dashboard row and
  the /stats ledger both use it, so a request the row refuses is unpriced
  on /stats too. ComponentFigure, EnvelopeComponents and the size bound move
  with it.
- The spend calls name no model: the library prices them on the request's own
  model, and the host pricer prices that one model.
- Put back Flow.Prices and Request.PromptTokens, marked Deprecated.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Replies to round 2 (both reviewers blocked)

b338e67b (handler path) and 63e8eded (main merged with #1462, one gate) fix both findings.

Both reviewers, finding 1: the ledger joined the accountant job on the handler path. Fixed in b338e67b.

  • Book and noteDefer stay synchronous.
  • The dollars are a closure (capture.deferBook, run by runDeferBook). finishAccountant runs it after the join on the lean path, and finish runs it on the dashboard path.
  • TestDeferLedgerDoesNotWaitForTheAccountantJob blocks the job and checks that deferLedger returns. A mutation that books synchronously makes it fail.
  • The ledger tests wait on a condition, not on a snapshot (reviewer 1's flake note).

Reviewer 1, finding 2, and reviewer 2, finding 2: the row and /stats could disagree. Fixed in 63e8eded, on top of #1462, where the dashboard now uses accountant.Figure.

  • spendUSD and bookDeferSpend are gone from dash. The library prices the spend calls, and accrec.DeferSpendUSD sums them.
  • One gate, accrec.Gate, is used by both the dashboard row and accFigure. It covers dropped operations, observe, fatal checks, unpriced operations, the size bound, a figure with no row, duplicate names and acted-without-figure. A request the row refuses is unpriced on /stats too.
  • TestDeferRowEqualsTheLedgerOnATieredNetAddingRequest: gpt-5.6, a net-adding request across the 272K line. The row's net, gross and cost equal accrec.DeferMoney. A flat table gives a different figure, so the re-rate is exercised. accrec.TestGate covers each gate reason.

Reviewer 2: the cg_* / llm_savings_* change. Named in the behavior block. The tooldefer spend calls are booked as added cost on the tooldefer component.

Non-blocking: Flow.Prices and Request.PromptTokens stay, marked Deprecated and unused, because the package is a public library. The second pass prices at the size of its own call, which is consistent everywhere.

Tests (macOS, Go 1.27.4): build and vet are clean. Plain go test passes on tooldefer, proxyapp, accrec, accwire, proxy and dash. -race -run on the new tests passes.

Local tests: waived (owner rule)

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: approve

Earlier findings

  1. Round 2, finding 1 (the ledger joined the accountant job on the handler path): fixed. b338e67b keeps Book and noteDefer synchronous and leaves the dollars in a closure (capture.deferBook, proxy/tooldefer.go:426-431) that runDeferBook runs after the join: finishAccountant on the no-dashboard path (proxy/accountant_wire.go:254), finish on the dashboard path (proxy/dashcapture.go:865). I checked the ordering (the Ledger step sets the closure before finish spawns the goroutine, so noteDefer always precedes the first accCompute and the spend operations are never missed), the idempotency (runDeferBook nils the closure first) and the happens-before (the go statement orders the write and the read). TestDeferLedgerDoesNotWaitForTheAccountantJob blocks the accountant job and proves deferLedger returns with the counts only; a synchronous booking would fail it.
  2. Round 2, finding 2 (the row and /stats split a negative re-rate differently): fixed. The merge brings #1462, where dash's AccountantFigure stopped pricing and now maps accountant.Figure (dash/accountant_price.go:100-143). Both surfaces read the one library figure: the row through ComponentFigure plus accrec.DeferSpendUSD, the ledger through accrec.DeferMoney. I checked the two pricers are the same rule by construction: dash's hostPricer and the proxy's metricsPricer both delegate to modelinfo.Price.RateAt (internal/modelinfo/rateat.go:14), which resolves the model and applies the tier rule. TestDeferRowEqualsTheLedgerOnATieredNetAddingRequest covers my exact scenario — gpt-5.6 across the 272k line, a net-adding request, the row's net, gross and cost equal to DeferMoney, and a flat table giving a different figure, so the re-rate is exercised.
  3. Reviewer 2's round-2 finding 2 (the ledger booked dollars the row refused): fixed, agree after checking it myself. One accrec.Gate now serves both: accOverride (dash/accountant_price.go:298-304) and accFigure (proxy/accountant_wire.go:228-236). The gate covers the size bound and the row-shape rules too. I verified the gate inputs match on the two paths: TokensBefore comes from tr.Run.TokensBefore on both (dash/event.go:839), and GateRowsOf's acted rule (!Reverted && !Skipped && Saved() > 0) is the same rule that builds CompRow.Acted (dash/event.go:850). accrec.TestGate covers each reason.
  4. Non-blocking round-2 notes: the ledger tests now wait on a condition; Flow.Prices and Request.PromptTokens are kept deprecated for library users, with Book no longer setting PromptTokens; the metrics change is named in the PR's behavior block.

Findings

None.

Non-blocking

  • waitLedger (proxy/tooldefer_ledger_test.go:242-251) is a hand-rolled fixed-deadline poll loop with runtime.Gosched. The repo rule names testutil.WaitFor for exactly this shape. The helper would drop in unchanged.
  • The accountant-savings row (docs/data-dependence/features/accountant-savings.md) still says of the per-request figure "Nothing calls that figure yet in this PR". At this head deferLedger calls it. The data dependence itself (numbers only) is unchanged; only that sentence is stale.
  • accwire.SpendParamEstimated is written on the three spend operations and stored with the Result, but no production code reads it now that dash's bookDeferSpend is gone. Either feed it into the figure's estimated mark or note it as wire documentation.
  • On the dashboard path the deferBook closure recomputes accountant.Figure and Gate a second time (PriceMode already ran both). Bounded, off the client's critical path. No action asked.

What I checked

  • Last review: round 2, ab6d41e, 2026-11-26T13:06:16Z.
  • New commits read: 10 — 63e8eded (merge: one gate, DeferSpendUSD, spend calls name no model), b338e67b (ledger dollars off the handler path), f9ec697c (#1462, dash prices with accountant.Figure), c2dccc73 (#1461, ping savings without the dashboard), 632d0ab5 (#1463, warm-sweep test waits), dec2ef0e (#1455, sweep tier cut), e2d4177e (#1193, warm copy without a ping), ec84ede3 (#1458, interaction row), 5dcb70fa (#1450, accountant v0.9.0 docs), f174d823 (#1454, next-request input size). The main-side commits outside this PR's area were read at message and file-stat level; every file that intersects this PR (accrec, accwire, dash pricing, proxy accountant wiring, tooldefer, docs) was read in full from the ab6d41eb..HEAD diff and the current files.
  • Read in full: 4 reviews, 3 comments, 0 inline comments (from the three saved files).
  • New items since my last review: the author's round-2 reply — each claim checked against the code (listed under Earlier findings); the new accrec/gate.go — read in full, each gate reason checked against the old dash gates and the library's Withhold; accrec/heldfloor.go and ComponentFigure — read; the spend ops' model removal — checked that the library prices a model-less call on the request's model (v0.9.0 usd.go:213-216), so the dash and proxy figures agree.
  • Verified the one-figure claim end to end on both paths: row (PriceMode → ComponentFigure − DeferSpendUSD) and ledger (accFigure → DeferMoney) read the same library figure with the same rates, the same gate and the same held rule; the held request books Unpriced with no dollars on both paths.
  • Checked the merged gates for equality of inputs: TokensBefore, the row set and the acted rule are the same on the dashboard path and the lean path.
  • Verified the data-dependence page against every row file under docs/data-dependence/ (all row bodies appear in the page; the dashboard-database row matches its two-paragraph body).
  • Checked that the removed symbols (FigureWithheld, spendUSD, bookDeferSpend, DeferSpendOps's model parameter) have no remaining callers.
  • Live tests were not run (not approved). Read the code only.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.332 offload-review skill, @amiddavid's session resumed 2 of 2 3 of 4 63e8eded28f8 blocking

Verdict: blocking

Earlier findings

  • Round 2, finding 1 (the ledger joined the accountant job on the handler path): fixed (b338e67b). deferLedger now books the facts synchronously (Book, noteDefer) and leaves a closure (capture.deferBook); runDeferBook runs it from finishAccountant after the join on the lean path, and from finish on the dashboard path (proxy/accountant_wire.go, proxy/dashcapture.go:865). I traced the ordering myself: lifecycle.Finish sets deferFacts and deferBook before ac.finish spawns the lean goroutine, so the spend operations are never missed and no accountant work runs on the handler goroutine. TestDeferLedgerDoesNotWaitForTheAccountantJob blocks the job and pins that deferLedger returns.
  • Round 2, finding 2 (/stats and the row could disagree on gate decisions): fixed (63e8eded). One gate, accrec.Gate, is now called by both accFigure (proxy/accountant_wire.go:230-237) and dash's accOverride (dash/accountant_price.go:296-300). I checked the gate list against the old dash gates one by one: dropped operations, observe, fatal checks, unpriced operations, the size bound, figure-without-row, duplicate names, acted-without-figure — all present, penalty_unknown passes (held, not refused). I checked the inputs match on both paths: GateRowsOf(c.trace.Run) builds the same rows and the same Acted rule as FromTrace (!Reverted && !Skipped && Saved() > 0), and TokensBefore comes from the same run report. A rejected request cannot diverge: deferLedger requires status 200.
  • Reviewer 1, round 2, finding 2 (the re-rate split differed between dash and the library): fixed by #1462, merged here. Dash's AccountantFigure now calls accountant.Figure and only maps the USDFigure; spendUSD, bookDeferSpend, bookReRate, reRateUSD, accPrices and tierUSD are gone from dash. Both surfaces read the library's figure, and TestDeferRowEqualsTheLedgerOnATieredNetAddingRequest pins row == accrec.DeferMoney on a tiered, net-adding request. I checked the fix myself in the diff.
  • My round-2 non-blocking (name the cg_* metrics change): done. The PR body's behavior block and its metrics note name it.
  • Dead fields (Flow.Prices, Request.PromptTokens): kept as Deprecated with honest markers, because the package is a public library. Acceptable; Book no longer sets PromptTokens.
  • Request.SearchOutput never set: still open, named in the PR's Open questions. Its own issue.

Findings

  1. proxy/tooldefer_ledger_test.go:242-248 and :273 — the new test code adds two unmarked timing patterns, so go test ./internal/timingguard fails
    • What fails: the timing guard scans *_test.go files and fails on a new time.Sleep, a poll loop limited by a time.Now().Add(...) deadline, or a time.After select timeout, unless the line carries //timing:ok <reason> or the file is in the shrinking baseline. This PR adds both patterns in a file with no baseline entry, with no markers.
    • Proof: waitLedger (lines 242-248) is a for loop whose limit is deadline := time.Now().Add(30 * time.Second) checked with time.Now().After(deadline) — the guard's "poll" kind (internal/timingguard/timingguard_test.go, pollLoop: a deadline name from time.Now().Add checked in the loop body counts). The select in TestDeferLedgerDoesNotWaitForTheAccountantJob (line 273) has case <-time.After(30 * time.Second): — the "after" kind. internal/timingguard/baseline.txt lists no entry for proxy/tooldefer_ledger_test.go (it lists proxy/accountant_async_test.go and tooldefer/support_test.go after=3 for the pre-existing ones), and the PR does not touch the baseline. The guard runs inside make cover (go test ./..., the CI build-test job): tier 3, on main after the merge, and the interim rule sends the failure back to this PR. The author's test list (tooldefer, proxyapp, accrec, accwire, proxy, dash) does not include internal/timingguard.
    • Fix: replace waitLedger with testutil.WaitFor(t, "...", cond) — it is exactly that helper, with the safety bound and a sleep-poll instead of the runtime.Gosched() spin. Replace the select with testutil.WaitFor on the returned channel, or mark both lines //timing:ok <reason> if the shape must stay.

Non-blocking

  • The PR body's metrics note still says the sink prices a call "not at the stated prompt_tokens". That parameter no longer exists (removed in round 2). Stale sentence in the PR description only; no repo file affected.
  • The two pre-existing time.After selects in tooldefer/support_test.go are in the baseline (after=3), so they are fine. Only the new file matters.

What I checked

  • Last review: round 2, ab6d41e, 2026-11-26T13:05:43Z
  • New commits read: 10 — b338e67b (branch: book the ledger dollars off the handler path), 63e8eded (merge of origin/main, one gate), and from main: f9ec697c (#1462 dash prices with accountant.Figure), c2dccc73 (#1461 ping savings without the dashboard), 632d0ab5 (#1463 warm-sweep test waits), dec2ef0e (#1455 tier-target cut), e2d4177e (#1193 warm copy without a ping), ec82ede3 (#1458 interaction row), 5dcb70fa (#1450 accountant v0.9.0), f174d823 (#1454 next-request input size). I read the branch commit and the merge resolution in full, and the PR's whole diff against the new base (git diff f9ec697c..63e8eded, 33 files). Main-side commits outside this PR's area were read at message and stat level; every file that intersects this PR I read in full.
  • Read in full: 4 reviews, 3 comments, 0 inline comments (from the three saved files). I also fetched the PR body to check the behavior block and the metrics note.
  • New items since my last review: reviewer 1's round-2 review (its finding 2, the re-rate split, I verified as fixed above), the author's reply of 2026-11-26 14:11 (each claim checked against the code), and the two new commits.
  • Checked the new closure wiring end to end: deferLedger → noteDefer (facts, synchronous) → deferBook closure → runDeferBook from finishAccountant (lean, after accCompute joins the job) or finish (dashboard, after the result is in). No accountant call remains on the handler goroutine; the closure's accFigure/accCompute are cache hits by then.
  • Checked accrec.Gate against the old dash gates and the library: Gate covers every old gate, ComponentFigure keeps the zero-token-key rule for a component that acted, the tailbreakpoint and ended-change mapping match the old behaviour, and TestGate covers each reason.
  • Checked the spend pricing at v0.9.0: the library prices a spend call at op.Call.Model, falling back to the request's model when empty (usd.go:213-215), so the ops with no model price at the request's model through metricsPricer/hostPricer, both of which price that one model.
  • Verified the data-dependence page is the faithful regeneration of the row files at this head (the generator normalizes whitespace; the normalized cell text matches exactly).
  • Checked the timing guard's detection rules against the new test code line by line (finding 1), and swept every test file this PR touches for the three patterns.
  • Did not run builds or tests (not approved). The author reports plain go test passing on tooldefer, accrec, accwire, lifecycle, metrics, proxy, proxyapp and dash (macOS, Go 1.27.4) — internal/timingguard is not in that list.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Replies to round 3 (in progress)

Reviewer 2, finding 1: the timing guard. Being fixed: waitLedger and the time.After select become testutil.WaitFor, and the next push runs go test ./internal/timingguard. That push also merges main (accountant v0.10.0) and fixes the stale data-dependence sentence and PR body lines. #1445 is the last PR for v0.7.10.

- Replace the poll loop and the time.After select in the ledger tests
  with testutil.WaitFor, so the timing guard passes.
- Say in the accountant-savings row that the deferral ledger reads the figure.
- Note that SpendParamEstimated is wire documentation only.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
…ld (#1465)

accrec.Gate used CheckFailure.Fatal(). It now calls accountant.Withhold, the
rule of the metrics push, so the accountant decides alone on checks and
unpriced operations. A sum failure that no operation claims (Check.Claims 0)
no longer blocks the dashboard row or the /stats ledger.

The host keeps its own gates: dropped operations, observe, the size bound
(Withhold's bound counts tool declarations, the host's measure does not),
figure without row, duplicate name, acted without figure.

Fixes #1465

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Replies to round 3, and the #1465 fix

a7a4b1e8 fixes round 3 and merges main (accountant v0.10.0). 20686090 adds the owner's #1465 decision.

Reviewer 2, finding 1: the timing guard. Fixed. waitLedger and the time.After select now use testutil.WaitFor. The blocked job is released by t.Cleanup. go test ./internal/timingguard passes.

Reviewer 1, non-blocking:

  • The accountant-savings row now says the deferral ledger reads the figure. The page is regenerated.
  • SpendParamEstimated is commented as wire documentation. Figure takes its estimated mark from the pricer.
  • The double compute on the dashboard path stays. It is bounded and off the handler path.

Reviewer 2, non-blocking: the stale prompt_tokens sentence is gone from the body.

#1465, owner decision (in the integrator session, 2026-11-26): one gate rule.

  • accrec.Gate calls accountant.Withhold for the library gates (checks, unpriced). The dashboard row, /stats and the metrics push follow one rule. A check_sum failure that no operation claims no longer blocks the row or /stats, so dashboard figures rise on those requests.
  • The host gates stay host gates: dropped operations, observe, figure without row, duplicate name, acted without figure, and the size bound. Each reason constant says which side it belongs to.
  • The size bound stays on the host. Withhold's bound counts every operation's tokens, tool declarations included, but TokensBefore counts message text only (Accountant integration: the plausibility gate drops the whole result when removed tool declarations exceed message tokens #907). The push gives no size, so it skips this gate. One gap is left: a request that fails only the host size bound is withheld on the row and on /stats, but booked by the push.
  • Tests: accrec.TestGate covers the claimed and unclaimed check_sum against Withhold. dash.TestSumFailureGateIsWithholdOnTheRowAndTheLedgerAndThePush and proxy.TestAccFigureGatesSumFailuresWithWithhold cover the row and /stats.
  • docs/dashboard.md and docs/metrics/spec.md are updated. The PR body has the behavior block at the top and says "Fixes dash: gate savings with accountant.Withhold, like the metrics push #1465".

Tests (macOS, Go 1.27.4): build and vet are clean. Plain go test passes on tooldefer, proxyapp, accrec, accwire, internal/timingguard, proxy and dash. -race -run on the new tests passes.

Local tests: waived (owner rule)

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: approve

Earlier findings

  • Round 3, finding 1 (the timing guard fails on the new test code): fixed (a7a4b1e8). waitLedger now calls testutil.WaitFor, the time.After select is a non-blocking channel check inside WaitFor, and t.Cleanup releases the blocked job through a sync.OnceFunc when a wait fails. I grepped the file: no time.Sleep, no time.Now().Add deadline loop, no time.After select, no Gosched spin remains. The author reports go test ./internal/timingguard passing, and that package is now in the test list.
  • Round 2, finding 1 (handler-path join) and finding 2 (gate divergence): fixed in round 3, unchanged and still correct at this head. I re-checked that deferBook still runs only from finishAccountant/finish and that accrec.Gate still feeds both accFigure and accOverride with the same inputs.
  • Reviewer 1's round-3 non-blocking notes: all addressed — the accountant-savings row names the deferral ledger as the figure's reader, SpendParamEstimated is documented as wire-only, the stale prompt_tokens sentence is gone from the PR body, and the double compute on the dashboard path stays bounded and off the client path (accepted).
  • Request.SearchOutput never set: still open, named in the PR's Open questions. Its own issue, as before.

Findings

None.

Non-blocking

  • dash/accountant_price_test.go:336 — the test name is stale. TestAnUnnamedFatalCheckStillGates now tests the opposite: a NON-fatal check (CheckConservation) does not gate. The comment above it says the right thing; only the name is old. Rename in a follow-up.
  • The known push gap, named by the author, is accepted. A request that fails only the host size bound is withheld on the row and /stats but booked by the metrics push. The reason is sound: the push has no message-token measure to apply (Withhold's own bound counts tool declarations, which is why the host keeps its own). Named in the round-3 reply; no action asked.

What I checked

  • Last review: round 3, 63e8ede, 2026-11-26T14:22:27Z
  • New commits read: 4 — a7a4b1e8 (use WaitFor in the ledger tests; refresh docs), 824ddc17 (merge of origin/main), ebd659bb (#1464, from main: accountant v0.10.0 bump), 20686090 (#1465: gate the row, /stats and the push with accountant.Withhold). I read the two branch commits in full, the PR's whole diff against the new base (git diff ebd659bb..20686090, 35 files), and the dep-bump commit at file level.
  • Read in full: 5 reviews, 5 comments, 0 inline comments (from the three saved files).
  • New items since my last review: reviewer 1's round-3 review (approve, with the waitLedger note that matched my finding), the author's replies of 14:23 and 14:36, and the four commits. I acted on each: verified the WaitFor fix in the code, and reviewed #1465 as a first review.
  • Checked #1465 against accountant v0.10.0: Withhold skips a fatal CheckSum failure that no operation claims (unreportedChange, Claims == 0), passes penalty_unknown, and its Withheld* reason strings equal the old stored acc_fallback values, so requests.acc_fallback keeps its meaning. The host gates (dropped operations, observe, the message-token size bound, figure without row, duplicate name, acted without figure) stay in accrec.Gate, and both callers still feed it the same rows, Acted rule and TokensBefore — so the row and /stats stay on one decision, now with the push's rule too.
  • Checked the behavior change in #1465 (an unclaimed sum failure now prices; dashboard figures rise on those requests): the owner decision is recorded in the PR comment ("one gate rule", integrator session, 2026-11-26), and docs/dashboard.md and docs/metrics/spec.md name it.
  • Verified go.mod pins the released tags v0.10.0 for both rossoctl/accountant and rossoctl/accountant/metrics (no pseudo-version).
  • Verified the data-dependence pages are the faithful regeneration of the row files at this head (accountant-savings and dashboard-database both match under the generator's whitespace normalization).
  • Checked the new tests: accrec.TestGate (claimed and unclaimed sum failures, agreement with Withhold), dash.TestSumFailureGateIsWithholdOnTheRowAndTheLedgerAndThePush, and proxy.TestAccFigureGatesSumFailuresWithWithhold cover the row, /stats and the push on the new rule.
  • Checked CheckConservation is non-fatal in v0.10.0 (only sum, unique_change and spans are fatal), so the renamed dash test's expectation is right.
  • Did not run builds or tests (not approved). The author reports plain go test passing on tooldefer, proxyapp, accrec, accwire, internal/timingguard, proxy and dash, and -race -run on the new tests (macOS, Go 1.27.4).

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: approve

Earlier findings

  1. Reviewer 2's round-3 finding (the new test code broke the timing guard): fixed. a7a4b1e8 replaces the waitLedger poll loop with testutil.WaitFor (proxy/tooldefer_ledger_test.go:242-246) and the time.After select with a testutil.WaitFor over a non-blocking read of the returned channel (proxy/tooldefer_ledger_test.go:269-276). The blocked job is released through sync.OnceFunc registered in t.Cleanup, so a failed wait cannot leak the goroutine. Both patterns the guard forbids are gone from the file.
  2. My round-3 non-blocking notes: all fixed. The accountant-savings row now says "The tool deferral ledger reads that figure" (row file and regenerated page agree). SpendParamEstimated is documented as wire documentation only (accwire/spend.go:5-6). The double compute on the dashboard path stays, as I expected it would.
  3. Reviewer 2's round-3 non-blocking (the stale prompt_tokens sentence in the PR body): gone. Verified by fetching the body.
  4. Rounds 1 and 2 findings remain fixed at this head (re-checked the wiring and the tests still stand: TestDeferLedgerDoesNotWaitForTheAccountantJob, TestDeferRowEqualsTheLedgerOnATieredNetAddingRequest, the one-gate tests).

Findings

None.

What I checked in the new commits

  • 20686090 (#1465, the one gate rule). accrec.Gate now calls accountant.Withhold(res, accountant.SizeNotGiven) for the library's gates and keeps the host gates (dropped operations, observe, the size bound, the three row rules). I read the change against accountant v0.10.0's Withhold (withhold.go:40-65): a check_sum failure with Check.Claims 0 does not gate (unreportedChange), penalty_unknown does not gate, unknown cache-effect kinds gate as unpriced, and SizeNotGiven skips the size gate. The reason constants now alias the library's Withheld* values, so the stored acc_fallback strings are unchanged. The gate order is unchanged. The detail extraction for GateUnpriced still reads fig.Unpriced, as before. Tests cover the rule at three levels: accrec.TestGate (claimed and unclaimed check_sum, and a pin that Withhold agrees), dash.TestSumFailureGateIsWithholdOnTheRowAndTheLedgerAndThePush (row, gate and Withhold together) and proxy.TestAccFigureGatesSumFailuresWithWithhold (the /stats hook). The behavior change is named at the top of the PR body with the owner's yes in the integrator session.
  • a7a4b1e8 (test and docs refresh). Read in full; the fixes are listed under Earlier findings.
  • 824ddc17 / ebd659bb (accountant v0.10.0). go.mod pins the released tags v0.10.0 for both modules (no pseudo-version). The replay digests change only because v0.10.0 marshals Check.Claims; the commit says no booked figure changed, and the digest list is consistent with that. The docs that name the accountant version are updated (metrics spec, metrics-push row, the regenerated page).
  • The named gap (a request that fails only the host size bound is withheld on the row and /stats but booked by the push) is pre-existing — the push's sink always called Withhold with no size — and the author now names it in the #1465 note. Not a new defect.

What I checked

  • Last review: round 3, 63e8ede, 2026-11-26T14:20:48Z.
  • New commits read: 4 — 20686090 (#1465 gate the row, /stats and the push with accountant.Withhold), a7a4b1e8 (WaitFor in the ledger tests; refresh docs), 824ddc17 (merge of origin/main), ebd659bb (#1464 accountant v0.10.0). Every file they touch was read in full from the 63e8eded..HEAD diff: accrec/gate.go, accrec/gate_test.go, dash/accountant_price_test.go, proxy/tooldefer_ledger_test.go, proxy/accountant_replay_test.go, accwire/spend.go, go.mod, and the docs.
  • Read in full: 6 reviews, 5 comments, 0 inline comments (from the three saved files).
  • New items since my last review: the author's two reply comments (14:23 and 14:36) — each claim checked against the code; reviewer 2's round-3 review — its timing-guard finding verified as fixed; the #1465 gate change — read against the v0.10.0 library source.
  • Re-verified the invariants that must survive the gate change: the gate inputs are the same on the row path and the lean path (TokensBefore from the run report, the same row set and acted rule), penalty_unknown still holds rather than refuses, and the held request still books Unpriced with no dollars.
  • Verified the data-dependence page matches the row files for the rows this round touched (accountant-savings, metrics-push), and that the PR body carries both behavior blocks with the owner's yes recorded.
  • Live tests were not run (not approved). Read the code only.

On the dashboard path finish runs the accountant in the handler's terminal
defer, and the ledger hook runs there too. A panic in either escaped into
the handler and cost the dashboard row, stopEarlyScan and the log line.

- failOpenAccountant: one recover-log-drop helper. finish runs the accountant
  step and savings.finished under it, so the row still comes out as
  no_result. finishAccountant uses it too.
- The ledger hook recovers its own panic and books the request as unpriced.
  runDeferBook guards the call too.
- Tests: TestFinishFailsOpenWhenTheAccountantPanics and
  TestDeferBookPanicIsRecoveredAndBooksUnpriced. Removing the recovers makes
  each fail.
- Rename TestAnUnnamedFatalCheckStillGates to TestANonFatalCheckDoesNotGate,
  to match what it tests.

Fixes #1504

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
The one conflict was in docs/data-dependence/features/accountant-savings.md.
It takes main's text, with #1470's single-tenant ping wording, and keeps
this PR's line that the tool deferral ledger reads the figure. The page
is regenerated with go run ./cmd/gen-datadep.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 4: both approve. Then the fail-open fix (#1504).

Both reviewers approved round 4 at 20686090. The integrator's proxy-boundary check then found a fail-open gap. The owner granted up to 6 rounds for it.

07e04a2f fixes it:

  • A shared helper, failOpenAccountant, recovers, logs and drops one accountant step. finishAccountant uses it as well.
  • fix(proxy): the dashboard path's accountant call fails open #1504: in capture.finish, the accountant step and savings.finished run under that helper. The recover covers only those steps, so the dashboard row (marked no_result), PriceMode, Record, stopEarlyScan and the log line still run after a recovered panic.
  • The deferral ledger hook (deferBook and runDeferBook) recovers on its own and books the request as unpriced.
  • Tests: TestFinishFailsOpenWhenTheAccountantPanics and TestDeferBookPanicIsRecoveredAndBooksUnpriced. Each one fails when its recover is removed.
  • TestAnUnnamedFatalCheckStillGates is renamed TestANonFatalCheckDoesNotGate (reviewer 2's round-4 note).

98b59b9e merges origin/main (#1469, #1470). The one conflict was in the accountant-savings row. It takes main's text and keeps "the tool deferral ledger reads that figure". The page is regenerated.

Tests (macOS, Go 1.27.4): go build ./... and go vet ./... are clean. Plain go test passes on proxy, dash, accrec, internal/timingguard and tooldefer. -race -count=3 on the 2 new tests passes.

Round 5 re-checks this delta.

Local tests: waived (owner rule)

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: approve

Earlier findings

  • Round 4: no findings (approve). Nothing to re-check from my own round.
  • My round-4 non-blocking (the stale test name TestAnUnnamedFatalCheckStillGates): fixed. 07e04a2f renames it to TestANonFatalCheckDoesNotGate, which matches what it tests.
  • Rounds 1 to 3 findings (data-dependence source, dashboard-off dollars, handler-path join, gate divergence, timing guard): all fixed in earlier rounds and unchanged at this head. I re-checked the wiring still stands: deferBook runs only from finishAccountant/finish, both under a recover, and accrec.Gate still feeds accFigure and accOverride with the same inputs.
  • The known push gap (a request that fails only the host size bound is booked by the push but withheld on the row and /stats): unchanged, still named and accepted. Reviewer 1 showed it is pre-existing (the push's sink always called Withhold with no size). I agree with that check.

Findings

None.

Non-blocking

  • The synchronous part of deferLedger (Book, noteDefer, the tokenizer weight) still runs in the handler's terminal defer without a recover. A panic there would escape into the handler. Pre-existing since the ledger step exists (#869), not introduced or widened by this PR, and the body was already parsed by the pipeline. No action asked; a later PR could put the whole Ledger step under the same failOpenAccountant helper.

What I checked

  • Last review: round 4, 2068609, 2026-11-26T14:39:48Z
  • New commits read: 6 — 07e04a2f (#1504: fail open in the deferral ledger hook and in finish), 98b59b9e (merge of origin/main), and from main: 50fc1385 (#1474 refactor-scan docs), db4c38fa (#1470 keepalive audit-sink in hosted mode), d0af063a (#1469 record headers by allowlist), 2c38eb58 (#1468 opencode test waits). I read 07e04a2f in full, the merge's whole delta on this PR's files, and the main-side commits at message and stat level (none of them touches this PR's logic; the record, keepalive and docs files they change are outside it).
  • Read in full: 7 reviews, 6 comments, 0 inline comments (from the three saved files).
  • New items since my last review: reviewer 1's round-4 review (approve), the author's reply of 17:39 (the #1504 story: the integrator's proxy-boundary check found the gap, the owner granted the extra rounds), and the two new commits. I acted on each: read the fix as a first review and verified every claim in the reply against the code.
  • Checked the fail-open fix end to end:
    • failOpenAccountant (proxy/accountant_wire.go) recovers, logs and drops exactly one step. In capture.finish, the accountant step (accCompute, SetAccountant, recordThinking) and savings.finished each run under it, and the calls after them (SetAccountantContext, PriceMode, the record write, stopEarlyScan, the log line) still run after a recovered panic — the order of the steps is unchanged from before the commit.
    • On a recovered panic in finish's accountant step, e.accRes stays nil, so PriceMode books no_result and the row is still written. TestFinishFailsOpenWhenTheAccountantPanics asserts exactly that.
    • The deferBook closure recovers its own panic and books the request as unpriced (AddMoney(tenant, Money{}, false)); runDeferBook adds a second guard around the call itself. The two recovers cannot double-book: the closure's recover fires first and returns normally. TestDeferBookPanicIsRecoveredAndBooksUnpriced asserts the unpriced booking, and it exercises the real gap (the closure's accCompute call, which sits outside accFigure's own recover).
    • finishAccountant keeps the same protection as before: its whole body, including the record drop, runs under the helper.
  • Checked that the gap the fix closes was real at the round-4 head: the deferBook closure's second call, cp.accCompute(u, usageOK), ran in the handler's terminal defer on the dashboard path with no recover around it (accFigure recovers only its own body).
  • Verified the merge conflict resolution: docs/data-dependence/features/accountant-savings.md takes main's #1470 wording and keeps this PR's line that the tool deferral ledger reads the figure; the regenerated page matches both that row and the dashboard-database row under the generator's whitespace normalization.
  • Verified the PR's diff against the new base is the same file set I reviewed across rounds, plus the fail-open changes; no other file changed between the round-4 head and this head on this PR's paths.
  • Did not run builds or tests (not approved). The author reports go build and go vet clean, plain go test passing on proxy, dash, accrec, internal/timingguard and tooldefer, and -race -count=3 on the two new tests (macOS, Go 1.27.4).

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: approve

Earlier findings

  1. All findings of rounds 1 to 4 remain fixed at this head. I re-checked the three anchors: deferBook still runs only from finishAccountant (no dashboard) and finish (dashboard), after the join; accrec.Gate still feeds both accFigure and accOverride with the same inputs; the one-figure tests (TestDeferRowEqualsTheLedgerOnATieredNetAddingRequest, TestToolDeferPricedRowIsOneFigureWithTheSearchTurns, TestToolDeferLedgerCountsSearchesOnEveryPath) all stand.
  2. Reviewer 2's round-4 non-blocking (the stale test name): fixed. 07e04a2f renames TestAnUnnamedFatalCheckStillGates to TestANonFatalCheckDoesNotGate, which is what it tests (a CheckConservation failure does not gate).

The new delta

  • 07e04a2f (#1504, fail open in the ledger hook and in finish): reviewed as a first review, no findings. The integrator's proxy-boundary check found that on the dashboard path a panic in the accountant step or the ledger hook escaped into the handler and cost the dashboard row, stopEarlyScan and the request's log line. The fix is right:
    • failOpenAccountant (proxy/accountant_wire.go:258-266) recovers, logs and drops one step. finish runs the accountant step (compute, SetAccountant, recordThinking) and the savings.finished hook under it (proxy/dashcapture.go:854-869), so everything after — PriceMode, the row enqueue, stopEarlyScan, the log line — still runs, and the row books as no_result. finishAccountant wraps its whole body, with the drop closure inside the wrapped step, so the record is dropped even on a panic.
    • The ledger hook recovers its own panic and books the request as unpriced (proxy/tooldefer.go:431-437), and runDeferBook guards the call itself (proxy/accountant_wire.go:289-293). The priced AddMoney is the last statement of the closure, so the recover's unpriced fallback cannot double-book.
    • The ordering is preserved: endAcc() runs after the recover, not inside it.
    • Both tests inject a real panic (an open accountant.Request with a nil tracker behind it). TestDeferBookPanicIsRecoveredAndBooksUnpriced leaves the model empty on purpose, so accFigure returns early and the closure's own accCompute is the panicking call — exactly the uncovered path #1504 names. TestFinishFailsOpenWhenTheAccountantPanics asserts finish returns, the row is written and its fallback is no_result.
  • 98b59b9e (merge of origin/main): clean. The one conflict (docs/data-dependence/features/accountant-savings.md) takes main's #1470 wording and keeps this PR's line that the tool deferral ledger reads the figure. The merge leaves every PR-owned file byte-identical (verified: git diff 07e04a2f..98b59b9e is empty for accrec/, accwire/, tooldefer/, proxy/tooldefer.go, proxy/accountant_wire.go, proxy/dashcapture.go, dash/accountant_price.go). The main-side changes to shared files (the Ping route mounted with no dashboard, the recorder's header allowlist) touch neither the terminal defer nor the deferral wiring.
  • Main-side commits (50fc1385 docs, db4c38fa #1470 keepalive single-tenant, d0af063a #1469 header allowlist, 2c38eb58 opencode test): read at message and file-stat level; each carries its own owner approval in its commit message, and none intersects this PR's paths.
  • Verified the data-dependence page against every row file at this head, including the merged accountant-savings row and the rows #1470 and #1469 changed: all row bodies appear in the page.

Findings

None.

What I checked

  • Last review: round 4, 2068609, 2026-11-26T14:39:54Z.
  • New commits read: 5 — 98b59b9e (merge of origin/main), 07e04a2f (#1504 fail open in the deferral ledger hook and in finish), 50fc1385 (#1474 refactor-scan docs), db4c38fa (#1470 keepalive audit-sink hosted-only), d0af063a (#1469 record header allowlist), plus 2c38eb58 (#1468 opencode test) inside the merge — 6 in all. The PR-owned commit and the merge resolution were read in full; the main-side commits at message and file-stat level, with their intersecting proxy changes checked.
  • Read in full: 8 reviews, 6 comments, 0 inline comments (from the three saved files).
  • New items since my last review: the author's round-4/5 comment (the #1504 fix summary) — each claim checked against the code; reviewer 2's round-4 review (approve; its test-name note verified fixed); the #1504 fail-open change — reviewed as a first review, tracing every recover's scope and what still runs after it; the merge — verified the conflict resolution and that no PR-owned file changed.
  • Checked the fail-open change for double-booking and lost drops: the priced AddMoney is last in the closure; the unpriced fallback runs only from the recover; drop is inside the wrapped step in finishAccountant; endAcc is outside the recover.
  • Re-verified the data-dependence page equals the row files for every row, and that the PR's whole diff against the new base (git diff 50fc1385..HEAD) still carries the round-1-to-4 fixes.
  • Live tests were not run (not approved). Read the code only.

Only the generated docs/data-dependence.md conflicted, after #1472. It is
regenerated with go run ./cmd/gen-datadep.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 5: both approve. Main merged again.

Both reviewers approved round 5 at 98b59b9e. Reviewer 2 named a gap that predates this PR: the synchronous part of deferLedger (Book, noteDefer) runs with no recover. That is now #1510 (priority high), for a follow-up.

ae173ff0 merges origin/main (#1472). Only the generated docs/data-dependence.md conflicted, and it is regenerated with go run ./cmd/gen-datadep. go build ./... and go vet are clean. Plain go test passes on dash, proxy and components/all.

approved: 98b59b9e20aa (base 50fc138577c4) patch-id d94448c6f704
head:     ae173ff0ca3f (base 7a02270f2492) patch-id 965615abe94d
CHANGED: the head has new code or a conflict resolution. Each reviewer re-checks the delta.

Round 6 re-checks this merge.

Local tests: waived (owner rule)

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: approve

The new delta

  • ae173ff0 (merge of origin/main 7a02270f, #1472 dash declaration_text purge): no change to this PR. I verified the merge's whole delta on this PR's files is empty (git diff 98b59b9e..ae173ff0 is empty for accrec/, accwire/, tooldefer/, proxy/, and the dash pricing, panel and event files). The one conflict was the generated docs/data-dependence.md, and it is regenerated. The merge's dash/schema.go changes sit in the declaration-text tables, far from this PR's defer_cost_usd comment, which is intact (dash/schema.go:261).
  • 7a02270f (#1472, main-side) was read at message and diff level for the files it shares with this PR: only dash/schema.go overlaps, and the overlap is disjoint from this PR's change. It carries its own owner approval in its commit message.
  • Verified the data-dependence page against every row file at this head: all row bodies appear in the page, including the regenerated rows #1472 touched.

Earlier findings

  • All findings of rounds 1 to 5 remain fixed at this head. The three anchors still hold: the ledger dollars book off the handler path (deferBook run by runDeferBook from finishAccountant/finish), one gate (accrec.Gate → accountant.Withhold) feeds the row, /stats and the push, and the fail-open recovers of #1504 wrap the accountant step, the savings.finished hook and the ledger hook.
  • Reviewer 2's round-5 non-blocking (no recover around the synchronous part of deferLedger): correctly filed as #1510. I agree with the triage: the Ledger step has run in the terminal defer since #869, before this PR, and #1504 (the same class of gap, but on paths this PR made hot) was fixed here while the pre-existing one gets its own PR. Not a finding on this PR.

Findings

None.

What I checked

  • Last review: round 5, 98b59b9, 2026-11-26T17:42:48Z.
  • New commits read: 2 — ae173ff0 (merge of origin/main) and 7a02270f (#1472 delete declaration_text with retention and account purge). The merge was verified file by file against this PR's paths; #1472 was read at message and diff level for the shared file.
  • Read in full: 10 reviews, 7 comments, 0 inline comments (from the three saved files).
  • New items since my last review: the author's round-5/6 comment (both approved at 98b59b9e; the head moved by a main merge only; the patch-id check names the delta) — verified against the code; reviewer 2's round-5 review (approve, with the pre-existing deferLedger recover note now filed as #1510) — the triage checked and agreed.
  • Re-verified the PR's whole diff against the new base (git diff 7a02270f..HEAD) carries the same file set I reviewed across the rounds, plus nothing new.
  • Verified the data-dependence page equals the row files for every row at this head.
  • Live tests were not run (not approved). Read the code only.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: approve

Earlier findings

  • Rounds 1 to 5: every finding fixed, and each fix still stands at this head. The data-dependence source, the dashboard-off dollars, the handler-path join, the gate divergence, the timing guard, and the #1504 fail-open gap — I re-checked the anchors once more (below).
  • My round-5 non-blocking (the synchronous part of deferLedger runs with no recover): filed as issue #1510, priority high, for a follow-up. That is what I asked for. Not this PR's defect (it predates it, since #869); a fix belongs in its own PR off main.

Findings

None.

What I checked

  • Last review: round 5, 98b59b9, 2026-11-26T17:42:13Z
  • New commits read: 2 — ae173ff0 (merge of origin/main into the branch) and 7a02270f (#1472, from main: delete declaration_text with retention and account purge). No commit sits on this PR's branch itself: git log --oneline --no-merges 98b59b9e..ae173ff0 lists only those two.
  • Read in full: 9 reviews, 7 comments, 0 inline comments (from the three saved files).
  • New items since my last review: reviewer 1's round-5 review (approve), the author's reply of 17:47 (round-5 approval, #1510 filed, the merge), and the merge commit. I acted on each: verified the merge changes nothing in this PR's code and checked the reply's claims.
  • The merge leaves this PR byte-identical where it owns the code. I diffed the PR's own paths (proxy/, tooldefer/, accrec/, accwire/) between the round-5 head and this head: the patches are identical. The whole round-5-to-round-6 delta is main's #1472 (dash declaration_text purge: dash/declarationtextpurge_test.go, dash/dedupetext.go, dash/schema.go, dash/toolinventory.go, the page template), which was reviewed in its own PR.
  • This PR's dash/schema.go hunk survived the merge: the defer_cost_usd comment still carries the new wording ("the accountant's one figure, #1441", lines 261-262), beside #1472's new tables.
  • The regenerated data-dependence page matches every row file at this head — I checked all row files under docs/data-dependence/features/ and components/, not only the two this PR touched. The merge's only conflict was the generated page, and it was regenerated, not hand-edited.
  • Re-checked the standing invariants one last time: deferBook runs only from finishAccountant/finish under a recover; accrec.Gate feeds accFigure and accOverride the same inputs; the one-figure tests and the fail-open tests are unchanged in the diff.
  • Did not run builds or tests (not approved). The author reports go build and go vet clean and plain go test passing on dash, proxy and components/all (macOS, Go 1.27.4).

@amiddavid
amiddavid merged commit 17e5633 into main Nov 26, 2026
12 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 26, 2026
amiddavid added a commit that referenced this pull request Nov 26, 2026
The ledger no longer prices (#1445), so TierOf now calls accountant.HeadTier
and the ledger Price call is gone. go.mod pins accountant v0.11.0 and
accountant/metrics v0.11.0.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

openai OpenAI / Codex traffic and pricing

Projects

Status: Done

1 participant