Repository navigation
Fix: Count the fixed_restore copy in the saved figure (#481) - #1067
Conversation
… it in the saved figure (#481) With expand.fixed_restore, a later turn sends a restored copy of the output the model asked for. The dashboard still credited the full compaction on every one of those turns. - finishRestore no longer drops every accountant operation. It keeps the pipeline's operations and adds one context-guru.expand_restore operation for each copy: a message splice with the wire size of the copy and a ChangeID from the marker id. The accountant library already prices this shape (case rewrite/fixed-restore-cost/hot/5m). A later turn no longer falls back with ops_dropped. - finishRestore adds the copy's tokens to the run's TokensAfter, so a turn that carries the copy is not credited a saving. - expand_restore is an envelope component in dash. Without it the accountant falls back with figure_without_row. - New requests.restored_tokens column. SafetyCost.RestoredTokens is ExpandTokens plus the stored copies. SavedAdjusted is unchanged: SavedUnique is counted once per content, and the copies are counted once per turn. Tests: restore_savings_test.go drives an in-band expand and three later turns through a real recorder. The control with fixed_restore off passes before and after. Two tests fail before this change. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
boazdavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @boazdavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 | offload-review skill, @boazdavid's session | fresh | 2 of 2 | 1 of 2 | 5373859e9999 |
blocking |
Verdict: blocking
Findings
- apply/restore.go:150-158 — the restore operation never sets DryRun, so an observe-mode report claims a wire change that was never sent
- What fails:
BodyOptswithMode: observeruns the full path, includingfinishRestore(apply/apply.go:876, apply/apply.go:1075).opsFromRunmarks every pipeline operationDryRunfor observe mode (apply/ops.go:69, contract at apply/ops.go:27-29: "a report that ran in observe mode is DryRun too ... its operations are computed but never sent"). The newexpand_restoreoperation sets noDryRunfield. A library host that runs observe mode and passesTrace.Opsto the accountant books the copy's cost as real, although the observe body is never forwarded. - Proof:
restorePlan.ops(apply/restore.go:150-158) builds theaccountant.OperationwithKind,Operator,At, sizes,ChangeIDandMessageSpliceonly. The observe entry point is proxy/modes.go:160-176 (Mode: components.ModeObserve), which callsBodyOptsand reachesfinishRestore. The in-repo proxy discards the observe trace (proxy/modes.go:41-44), so no in-repo host mis-books today.applyis an importable library by design (CLAUDE.md), so the contract break is live for external hosts. Severity is low for this repo, but the fix is one line. - Fix: pass
applied(or the mode) intofinishRestoreand setDryRun: !appliedon the restore operation, asopsFromRundoes. Add a test that an observe-mode run's restore op carriesDryRun.
- What fails:
Non-blocking
finishRestorecomputes the copy positions twice and walks the body three extra times:pre(apply/apply.go:2306),outMsgsinsideinsert(apply/restore.go:98), andnb(apply/apply.go:2323). Each is a fullgjsonwalk of a body that can be 600 KB. Only requests with a restore plan pay it, but every later turn of a fixed_restore session is such a request.insertcould return the positions it already computed.- The
/statsaggregator still credits the compaction on fixed_restore later turns: itssaved_tokenscomes from the component reports insidepipe.Run, which run before the copy is inserted. The dashboard row now shows no saving on those turns. The two figures disagree for the same request. Changing the aggregator touches the append-only/statscontract, so it needs the owner's decision; the PR's open questions do not name it. restoredCopiesin dash/overview.go:589 holds a token sum, not a copy count. The name misleads.- The PR stores
restored_tokens, a token count. That is metadata only. The PR description says what it stores but does not use the data-dependence vocabulary of docs/data-dependence.md. No doc row is needed (no new component), but the PR should state "metadata only" in the data-dependence terms.
What I checked
- Read the full diff (10 files) and the code around each change:
finishRestore,restorePlan.positions/insert/ops,opsFromRun,wireSizes,tailOp, the tail-breakpoint defer, and bothfinishRestorecall sites on the Messages and Responses wires. - Verified the new operation's shape against the accountant library pinned in go.mod (
rewrite/fixed-restore-cost/hot/5m): kind, operatorcontext-guru.expand_restore,At.Index == messageSplice.at,SizeBefore 0,SizeAfter= the copy's wire bytes,ChangeID cg:restore:<id>. Read the library'sitems,toFwd,undo,apply,sawOriginal,checksandnextStateto confirm the position mapping and the sum check reconcile with the copy on the wire. - Verified the rank math in
opsagainstexpand.InsertRestored's ordering (same-index insertions keep plan order; ascending positions; append-at-end) for mixed, duplicate and unsorted plans. - Verified
envelopeComponents["expand_restore"]is required: without itFallbackFigureWithoutRowfires (dash/accountant_price.go:351-355) and the request books no saving. - Verified the dash SQL: insert column count equals the placeholder count (106 fixed + token columns);
requestCols/scanRequestand the Overview SELECT/Scan pairs stay aligned; the new column is additive with default 0. - Verified the Responses wire never feeds the accountant (
accUnsupportedWire, proxy/proxy.go:1521), so the restore ops appended there cannot fail the sum check. - Verified anchors are deduped by id (
expand.RecordAnchor), so no duplicateChangeIDcan fireunique_change. - Read the new tests in
apply/ops_restore_test.goandproxy/restore_savings_test.go, and checked their helpers and config keys exist (fixedPricer,waitForRows,expand.fixed_restore). - Did not run Go builds or tests: live tests are not approved for this review.
boazdavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @boazdavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 | offload-review skill, @boazdavid's session | fresh | 1 of 2 | 1 of 2 | 5373859e9999 |
approve |
Verdict: approve
Findings
None. The change is correct on every path I could trace. Details below.
Non-blocking
-
/stats and the prom
cg_saved_tokens_total/cg_tokens_after_totallines still over-credit a fixed_restore session. The pipeline emits the run report insidePipeline.Run(components/pipeline.go:122), beforefinishRestoreadds the copy's tokens toTokensAfter(apply/apply.go:2321). So the dash row is corrected, but the aggregator's saved figure still credits the full compaction on every later turn. The issue scopes itself to the dash ("dash: the saved figure..."), and the gross figures are documented as re-counted per turn (promexport.go:423), so this is a known surface left as it was. If #481's rule is meant to hold on /stats too, that needs a separate change (emit after restore, or re-emit). -
The fallback path still credits the token figure. When
plan.insertfails,finishRestoreforwards the pre-pipeline body (apply/apply.go:2309-2314) and drops the ops, but leavesRun.TokensAfterat the compacted value. The dash then credits a compaction for a request whose originals went out in full. This is the same wrong figure #481 describes, on the one branch the fix does not reach. It is pre-existing and near-unreachable:positionsclamps everyAtinto[1, len(outMsgs)], soInsertRestoredcan only fail on an sjson error. Worth a follow-up lineres.Trace.Run.TokensAfter = res.Trace.Run.TokensBefore(or the equivalent) in that branch. -
Mixed report after a count-changed give-up. In the count-changed path,
wireSizescan drop the pipeline ops (apply/apply.go:864-866) andfinishRestorethen appends the restore ops anyway, soTrace.Opsis non-empty whileOpsDropped > 0. No wrong figure can come out:PriceModereturnsFallbackOpsDropped(dash/accountant_price.go:305) and the tail-op gate skips (apply/apply.go:420). Only the state is odd. No action needed. -
The token figure and the dollar figure now treat the copy differently, by design.
TokensAfter += tokenssubtracts the copy at full text-token weight on every later turn, while the accountant op prices it by tier (written once, read later). The two figures already had this split (gross wire tokens vs tiered dollars), and the issue asked for both. Stating it here so a later reader does not report it as a bug.
What I checked
- Read
CLAUDE.md,docs/design.md, the full diff, and the code around every change. - The op math.
InsertRestored(expand/anchor.go:376-417) places every insertion in pre-splice coordinates, ties in plan order, emission ordered byAt.opssorts the plan stable byat, ties in plan order, and reportspos = at + rank. I traced both orderings by hand for the tie case, the all-fallback case, and the mixed case: the emission order and the sorted order are the same list, soposis the copy's true index innb.Removed == 0makes the splice'sAtvalid in both pre- and post-splice coordinates, so it composes with the pipeline's own ops, which are stated in input coordinates. The sizes come fromnb[pos].Raw, the bytes the provider actually bills. The unreachable-position guard fails closed (drops all ops). - The library contract. The shared accountant case
rewrite/fixed-restore-cost/hot/5m(test/cases in the accountant module) uses exactly this shape: operatorcontext-guru.expand_restore,at= the copy's index in the final forwarded body,messageSplice {removed: 0, inserted: 1},sizeBefore 0, ChangeIDcg:restore:<marker id>, cost applied once per ChangeID. The engine'sapply/undo(internal/engine/compute.go:405-430) maps earlier ops' positions past such a splice. - Both wire paths.
finishRestoreruns on the chat path (apply/apply.go:876, 1075) and the Responses path (apply/responses.go:601, 625). Observe mode never reaches it: the enforced path does not callBodyOpts, and the off-path run discards the result (proxy/modes.go:162-197). So no DryRun inconsistency. - The token correction.
Run.TokensAfteris read afterfinishRestoreonly by the dash capture (dash/event.go:806), the proxy log (proxy/proxy.go:1703) and the control rows, all of which should see the corrected figure. The aggregator's copy was emitted earlier and is unchanged.Saved()clamps at zero. Per-componentReport.Saved()uses the component's own counts, not the run's. - The dash plumbing end to end.
Event.RestoredTokensfromTrace.RestoredTokens(dash/event.go:799); therequests.restored_tokenscolumn is in the insert list, the value list,requestColsandscanRequestat the same position (I counted the insert columns against the placeholders: 146 = 106 + 40 token columns). The overview SELECT and its Scan stay aligned (restoredCopiesafterReverts). The additive-column entry matches the existing pattern. TheenvelopeComponentsentry is required and present; the restore op is correctly absent fromtoolSectionOperators(it acts on messages), and it adds nothing tocountedSavedTokens(Saved is zero on that op), so the plausibility bound holds. - The tests.
TestRestoreOpsRankByPositionmatches the realInsertRestoredemission order (I derived it by hand). The proxy test drives a real recorder through an in-band expand and three later turns; the control (fixed_restore off) answers the issue's open question, and the assertions would fail on the pre-fix code, as the commit message claims. - Fail-open. No request-path behavior changes:
positionsis a pure refactor of the old inline loop, the forwarded bytes are the same as before, and every new failure mode (a copy that cannot be placed) drops the figure only, never the rewrite. - Did not run Go builds or tests (not approved). Read the accountant library v0.1.1-0.20261108152158 from the module cache instead.
…481) Review round 1 of #1067. - The expand_restore operation is a dry run in observe mode, like the pipeline's own operations. The body is never forwarded there. - When the insert fails and the pre-pipeline body is forwarded, the run reports no saving: TokensAfter is set back to TokensBefore. - finishRestore resolves the copy positions once (insertAt). - Rename restoredCopies to restoredTok in dash/overview.go. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Round 1 repliesReviewer 2, finding 1 (restore op not a dry run in observe mode). Fixed in 7bb2c6f.
Reviewer 1, non-blocking 2 (fallback path still credits a saving). Fixed in 7bb2c6f.
Reviewer 2, non-blocking (positions computed twice). Fixed in 7bb2c6f. Reviewer 2, non-blocking ( Both reviewers:
Reviewer 1, non-blocking 1, 3 and 4. No action.
Reviewer 2, data-dependence. Tests: |
boazdavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @boazdavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 | offload-review skill, @boazdavid's session | resumed | 2 of 2 | 2 of 2 | 7bb2c6f4ea0e |
approve |
Verdict: approve
Findings
None. My round-1 finding is fixed correctly, and the new commit introduces no defect I can show.
Status of the earlier findings
- Mine, finding 1 (restore op not a dry run in observe mode) — fixed.
finishRestoretakesdryRunand sets it on the operation (apply/restore.go:161). All four call sites passmode == components.ModeObserve(apply/apply.go:876, apply/apply.go:1075, apply/responses.go:601, apply/responses.go:625);modeis resolved tosyncbefore each, so an emptyOpts.Modestays enforced. The condition equals!applied(apply/apply.go:829), the same ruleopsFromRunuses.TestRestoreOpIsADryRunInObserveModecovers observe and the enforced control. - Reviewer 1, non-blocking 2 (fallback still credited a saving) — fixed, and I checked it myself. The failed-insert branch now sets
Run.TokensAfter = TokensBefore(apply/apply.go:2312-2314). That is right: the branch forwards the pre-pipeline body, so nothing was compacted on the wire.TokensBeforecounts the same messages the fallback carries (the envelope rewrites before the pipeline touch no message content).TestRestoreFallbackReportsNoSavingdrives the branch through a body with no messages array (MessagesField("bogus")returnsmessages, soInsertRestoredfails). - Mine, non-blocking (positions computed twice) — fixed.
finishRestoreresolves the positions once and callsinsertAt;insertkeeps its signature for the tests. The semantics are identical:insertAtreceives the sameatsliceinsertcomputed internally. - Mine, non-blocking (
restoredCopiesname) — fixed. It isrestoredToknow. - Both reviewers (/stats and the prom lines still over-credit restore turns) — rejected by the author, and the reason is right. The aggregator reads the run report inside
Pipeline.Run, before the copies are inserted. Correcting it touches the append-only/statscontract, which needs the owner's yes (CLAUDE.md, RELEASING.md). The author left it as an open question on the PR. I accept this. The dashboard and the accountant now agree;/statskeeps the old semantics until the owner decides. - Mine, non-blocking (data-dependence wording) — answered. The author states
restored_tokensis metadata only. That matches what the code stores: a token count per request, no content. - Reviewer 1, non-blocking 3 (mixed ops after a count-changed give-up) — no action, reason verified.
accOverridereturnsFallbackOpsDroppedwhenaccOpsDropped != 0(dash/accountant_price.go:304-305), so the mixed state books no figure. Only the state is odd. - Reviewer 1, non-blocking 4 (token figure vs dollar figure weight the copy differently) — by design. I agree. The token figure is gross wire tokens; the accountant prices by tier. Both were asked for by #481.
Non-blocking
- The fallback fix zeroes the run-level figure only. On that branch the per-component rows (
CompRow.SavedGross),SavedUniqueandTrace.Changesstill describe rewrites that were not forwarded. A reader of the row sees component savings besidetokens_before == tokens_after. The path is rare (the insert fails only on a body shapeInsertRestoredrefuses), andChangeson a discarded rewrite predates this PR. A follow-up could clear the component figures there too. - The
/statsopen question should stay visible until the owner answers it, so it is not lost at merge.
What I checked
- Last review: round 1, 5373859, 2026-11-11T07:05:55Z
- New commits read: 1 —
7bb2c6f4fix(apply): Mark the restore operation as a dry run in observe mode (#481) - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files in my folder; the inline file is empty)
- New items since my last review, and what I did about each:
- Reviewer 1's round-1 review (approve, 4 non-blocking notes): read in full. Its claim that observe mode never reaches
finishRestorewas wrong (the off-path observe run callsBodyOpts, proxy/modes.go:160-176), but its other notes were sound; note 2 became a fix I verified myself (item 2 above). - The author's round-1 replies: read in full. Each reply checked against the code (items 1-8 above).
- Commit
7bb2c6f4: read the full diff and the code around each change. Verified thedryRunthreading at all four call sites, the fallbackTokensAfterreset, theinsertAtrefactor against the oldinsert(identical semantics), the rename in dash/overview.go, and both new tests.
- Reviewer 1's round-1 review (approve, 4 non-blocking notes): read in full. Its claim that observe mode never reaches
- Confirmed
FallbackOpsDroppedgates the mixed-ops state (dash/accountant_price.go:304-305) andFallbackObservegates observe rows, so the dry-run fix is defense in depth for hosts outside this repo. - Confirmed the new commit changes no forwarded bytes: the dry run is a flag on a report, the fallback already forwarded the pre-pipeline body, and
insertAtis a refactor. - Did not run Go builds or tests: live tests are not approved for this review.
boazdavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @boazdavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 | offload-review skill, @boazdavid's session | resumed | 2 of 2 | 2 of 2 | 7bb2c6f4ea0e |
approve |
Verdict: approve
What I checked
- Last review: round 1,
5373859e99992da495c50dff662bdd7a00080704, 2026-11-11T07:06:56Z. - New commits read: 1 —
7bb2c6f4ea0e"fix(apply): Mark the restore operation as a dry run in observe mode (#481)". I read the full diff and the code around each change. - Conversation read since then: 2 reviews (reviewer 2 round 1, mine round 1), 1 issue comment (the author's round-1 replies, 2026-11-11T07:12:11Z), 0 inline comments.
- I verified each fix by hand, on the code only. Live tests are not approved.
Dispositions
Reviewer 2, finding 1 (the restore operation was not a dry run in observe mode). Fixed. Reviewer 2 was right, and my round-1 statement "observe mode never reaches it" was wrong. It holds only for the in-repo proxy, which discards the observe trace. BodyOpts is an exported library entry point (CLAUDE.md: apply is importable), and a host that calls it with Mode: observe reaches finishRestore on both wires. The fix is correct:
finishRestoretakesdryRunand sets it on the restore operation (apply/restore.go:161).- All four call sites pass
mode == components.ModeObserve(apply/apply.go:876, apply/apply.go:1075, apply/responses.go:601, apply/responses.go:625).modeis in scope at each. - The new test holds.
effModestamps the mode on every report (components/pipeline.go:141, components/component.go:811), so the pipeline op isDryRunviaopsFromRun(apply/ops.go:69) and the restore op via the new parameter. Both operations in the observe run carryDryRun. The control normalizes mode""toModeSync(apply/apply.go:393), so the enforced run's restore op does not.
My round-1 non-blocking 2 (the fallback path still credited a saving). Fixed. TokensAfter is set back to TokensBefore on the insert failure (apply/apply.go:2314-2316), with a nil guard on Run. I checked the consumers: Saved() clamps at zero (dash/event.go:666-669), and PriceMode books no dollar saving while OpsDropped > 0. The test setup is valid: the pipeline body has no messages array, so InsertRestored fails closed (expand/anchor.go:382).
Reviewer 2, non-blocking (positions computed twice). Fixed. finishRestore resolves the positions once and passes them to insertAt (apply/apply.go:2307-2308). insert keeps its signature and delegates. The semantics are the same: pre is the same walk insert used to make.
Reviewer 2, non-blocking (restoredCopies name). Fixed. It is restoredTok now, at the scan and both uses.
Reviewer 2, non-blocking (data dependence). Addressed. The author states it in the round-1 reply: restored_tokens is metadata only, a token count per request, no content stored. No new component exists, so no doc row is required by components/all/datadep_test.go.
/stats and the Prometheus counters (my non-blocking 1, reviewer 2's non-blocking). Deferred, and I accept the reason. The aggregator reads the run report inside Pipeline.Run, before the copy is inserted. Changing it touches the append-only /stats contract, which needs the owner's decision. The author put the open question to the owner. No figure the issue names is wrong.
My non-blocking 3 (ops non-empty beside OpsDropped > 0). No action, agreed. PriceMode returns ops_dropped in that state, so no figure is wrong.
My non-blocking 4 (token figure vs dollar figure treat the copy differently). No action, agreed. By design, as the author says.
The new commit
I reviewed 7bb2c6f4 as a first review. No new findings.
- The
dryRunparameter changes the op's flag only. The enforced path is unchanged: the shared accountant caserewrite/fixed-restore-cost/hot/5mhas noDryRun, and an enforced run sets none. - The fallback branch now reports no saving, which is the behavior #481 asks for: the pre-pipeline body was forwarded, so nothing was compacted on the wire.
restoredTokis a rename. The SELECT and the Scan stay aligned.
Non-blocking
-
The pre-existing
giveUppaths still credit a saving (apply/apply.go:943, 949, 963, 972, 1028). Each of those returns forwards the original messages but leavesRun.TokensAfterat the compacted value. That is the same wrong figure #481 names, on paths this PR does not touch, and the restore fallback is now more correct than they are. The same one-liner (TokensAfter = TokensBefore) would fitgiveUp. These paths fire only on writeback failures (editOf,sjson,json.Marshal), so they are rare. Follow-up, not this PR. -
e.SavedUniqueand the componentSavedGrossrows still describe the compaction on the restore-fallback path.noteTracereadsrep.Saved()before the fallback is known (proxy/dashcapture.go:232-236). The saved figure (saved_tokens) and the dollar figure are both zero there now, so the figure the issue names is right.DropUnbilledSavingszeroesSavedUniqueon rejected requests for the same reason (dash/event.go:867-868). Follow-up with item 1, not this PR. -
The data-dependence statement lives in a review reply, not the PR description. The PR body says "stores its size per request" in plain words. The vocabulary statement ("metadata only") is in the author's comment. The rule asks the PR to state it; a comment on the PR satisfies it in substance. Moving the sentence into the description would make it easier to find.
Summary
expand.fixed_restore, every later turn sends a restored copy of the output the model asked for.TokensAfter, and stores its size per request.Fixes #481.
What we found
Reproduced on
origin/mainwith a real recorder: one in-band expand, then three later turns.saved_grossops_dropped(books nothing)SafetyCost.RestoredTokensWhy it happens
finishRestoreinserts the copy after the pipeline ran. The pipeline'sTokensAfterdid not include it.finishRestorealso dropped every accountant operation, because the insert shifts wire indexes. So the accountant booked no saving at all on those turns, and the token figures kept the old credit.Result.RestoredTokens) and only wrote it to the log.What changed
finishRestorekeeps the pipeline's operations. It adds onecontext-guru.expand_restoreoperation for each copy: a message splice, the wire size of the copy, and a ChangeID from the marker id. The accountant library already prices this shape (caserewrite/fixed-restore-cost/hot/5m), so the library is not changed.finishRestoreadds the copy's tokens to the run'sTokensAfter.expand_restoreis an envelope component indash. Without it the accountant falls back withfigure_without_row.requests.restored_tokenscolumn (additive, default 0).SafetyCost.RestoredTokensisExpandTokensplus the stored copies.How it was tested
proxy/restore_savings_test.go: three tests through a real recorder. The control withfixed_restoreoff passes before and after. The other two fail before this change.apply/ops_restore_test.go: the old test that pinned the drop is replaced by tests for the kept operations, the restore operation,TokensAfter, and the order of several copies.go testpasses fordash,apply,proxyandexpand.go vetandgofmtare clean.confighas one failure,TestStrategyTableMatchesPlugin(python3 -Icannot readsettings.py). This PR does not touch that file. I did not run it on a cleanmain.Open questions
SavedAdjustedis unchanged (SavedUnique - ExpandTokens).SavedUniqueis counted once per content and the copies are counted once per turn, so netting them would make it negative. Should it change?No test asserts a priced dollar saving on a restore turn. Logs show later turns no longer fall back.
With
fixed_restoreoff, the original goes back in place. The control test shows the figure is already right there.Data dependence:
requests.restored_tokensis metadata only. It is a token count per request. It stores no content, and no component depends on it.Technical notes
insertappends the copy at the end (a count-changing pipeline whose anchor cannot be proven), the position is the end of the pipeline's body. The operation uses that position.len(body)/5tokens. At/4the accountant's plausibility check rejects the request, because the fake usage disagrees with the host's estimate.Assisted-By: Claude (Anthropic AI) [email protected]