Skip to content

test(dash): Compare the accountant cases with cg's saving logic - #592

Closed
boazdavid wants to merge 1 commit into
mainfrom
docs/context-operations-spec
Closed

boazdavid wants to merge 1 commit into
mainfrom
docs/context-operations-spec

Conversation

@boazdavid

@boazdavid boazdavid commented Oct 18, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

This PR adds a test that compares the shared accountant test cases with cg's saving logic. It also adds two reports on what differs.

The library, the specification, the design and the 63 cases now live in https://github.com/rossoctl/accountant (v0.1.0). This PR started as that library. It no longer contains it.

What changed

  • dash/accountant_play_test.go: plays every case through dash.Event.Price.
    • A case that is not in known-differences.json must agree with cg to within 1 µ$.
    • A listed case must really differ, so a stale entry fails.
    • A listed entry whose case no longer exists also fails.
  • dash/testdata/accountant/known-differences.json: the 27 known differences (20 differs, 7 notCovered). Each cites a spec section.
  • dash/testdata/accountant/README.md: says what the file is and how the test uses it.
  • docs/accountant/: two reports, regenerated from the current run.
  • go.mod, go.sum: require github.com/rossoctl/accountant v0.1.0.

What we found

  • 63 cases. 36 agree. 27 differ. Total gap: 1,273,201 µ$.
  • Eight root causes in cg's logic. The two largest are the missing cache-break charge (cause 1) and the rate that follows novelty, not position (cause 2). Together they hold 673,976 µ$.
  • Cause 5 (keep-alive) is resolved. The adapter now passes Provider and CacheTTL, and both cases agree.
  • Cause 8 is new: the unique-versus-replay split has no session or thread. It covers the three thread cases.

How it was tested

  • GOWORK=off go test ./dash/ -run TestCasesAgreeWithCurrentLogic: 63 subtests pass.
  • I changed one entry of known-differences.json to a wrong id and confirmed the test fails.
  • go vet, go build ./... and go mod tidy -diff are clean.

Data dependence

Metadata only. The test reads no stored customer data, writes none and registers no component. docs/data-dependence.md does not change.

Open questions

  • Should the accountant library read the parent's state for a forked thread? It decides one of the three cause 8 cases.
  • The reports name figures from a fixture model with 4 bytes per token, not real traffic.

Refs #633

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

@@ -0,0 +1,1232 @@
# Context operations: one object model for the changes plugins make, priced in one place

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

title is misleading, there is no concept of "plugins" in context-guru.

The proposal is for a holistic approach for calculating cost and savings of context engineering

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.

Changed. The title is now "Context operations: counterfactual accounting of cost and savings". The word "plugins" is gone from the document. (47dbe2d)

**Worked example:** [`2026-10-18-context-operations-example.md`](2026-10-18-context-operations-example.md).
Read it first. It shows one session from body to dollars.

## 0. Base, and the problem

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

this is a very bad way to present the goal and the problem we are trying to solve.
this document should not mention cortex at all.

The problem is that at the moment each component that plays a role in context enigneering is computing its own cost and savings, thus it is hard to maintain and verify.

examples can be extract_llm tail vs cache_aware_summarization.

the problem should also explain why it is hard to calculate things... we need to aggregate over a time period ( which itself needs one definition) and we need to calculate counterfactual alternatives

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.

Changed. Section 0 is rewritten and does not mention Cortex. It states the problem as you described it: each component computes its own cost and savings, with the extract_llm tail vs cache_aware_summarization example. It also explains why the calculation is hard: aggregation over a period (defined here as the session) and counterfactual alternatives.

**Paths.** `core/...`, `cmd/agentop` and `pctx` are in `rossoctl/cortex`. `components/...`,
`apply/...`, `dash` and `ops` are in this repo.

This design starts from the savings code on the Cortex branch `feat/contextguru-keepalive`, which

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

 I think the problem is that the document conflate two things
A. a holistic approach for calculating cost and savings of context engineering
B. the need in cortex for a plugin that does A, and avoiding cortex trying to calculate it or each plugin being responsible for its calcualtion.

for instance, I dont expect to see in this document an explanation of how context-guru plugin will publish events to the cost-ledger plugin. ( btw. do u have a name for that)

this should be part of the cortex documentation and not here.

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.

Changed. The host wiring (how components publish to the cost ledger, the collector, migration) moved to a separate document: 2026-10-18-context-operations-cortex-wiring.md. It is a draft and can move to the Cortex repo. I have no name for the component that writes to the cost ledger. The wiring document lists it as open.

inside a request (§4.6).
- **R6.** An operation has an ID that is unique inside its request. Results, check failures and
`cacheBreak` attribution refer to it. A reference to a change in another request uses `ChangeID`
(R22), not the operation ID.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

this is interesting, if a change has occurred, it may impact the attribution. i.e. expand stops the attribution of reduction + provides penalty.
so a changeID is kind of a chain in the operation

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.

Not changed in this commit. I did not model expand as a link in a chain of change IDs. I agree an expand ends the attribution of a reduction and adds a penalty. Today it shows as the reduction no longer being reported, plus a cacheBreak. Do you want an explicit link from the penalty to the reduction it ended?

calls the library once.
- **R33.** Operations that add tokens are costs: an injected tool declaration, injected text, a
restore.
- **R34.** A destination change (inference-router) is a separate kind. Its pricing is out of

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

this means change of model for a session?
this makes sense,
but I think more stuff like this exist... for instance change of relative effort

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.

Changed. R34 now covers a setting kind: the model, the host, or the effort. Pricing of a setting change is still out of scope, but it is recorded. Model and effort are also on the request facts (R18).

the same way. It prices `Saved`, `Caused` and `Call.Usage` with one resolver, at one time. So spend
has the same rates, provenance, currency and billing basis (§7.4) as the savings.

**What it replaces.** `core/cost/spend` (`Charge`, `CostRecorder`, `RecorderConsumer`) is removed.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I dont think we care about it in the document

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.

Changed. The paragraph about replacing core/cost/spend is removed.

A `stateChange` operation does not change the content. It changes how the provider bills content
that is already there.

| Mechanism | Producer | What changes | Reported on |

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

cant we find a more abstract/ generalize form?
when does a state changes?

  • prefix is warmed up
  • prefix is protected ( breakpoint)

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.

Changed. The Mechanism list is replaced by a state diff: a stateChange carries a prefix range and two states. The text names two cases: a prefix is warmed, and a prefix is protected by a breakpoint.

| `Host`, `Model`, `Usage`, `Status`, `Duration` | `Call` |
| `At` | `RequestOps.At` |

### 4.7 Replays: who remembers past changes

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

a question about performance and implementation, each replay causes a recalculation, I think those should be async and buffered, so for instance if another request comes in within the buffer window it replaces the current request and executes when that original one was in the queue, i.e. it takes its place in the queue ( to avoid starvation)
but what we dont want is to calculate everything all the time, it maybe too much.

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.

Not changed in the model. I agree: recalculation should be asynchronous and buffered, and a newer request for the same key should replace the queued one and keep its place. I added it as an open design point (section 12, item 7). The queue design is not written.

Settle->>Store: event.Saving (ping leg)
```

## 5. The collector

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I would like to switch things around, I dont want something collecting, I would prefer us pushing telemetry and if its updating, then its an update.
i.e. think prometheous

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.

Changed in principle. Section 5 now states the push model: each fact has an identity (name plus labels, as in Prometheus), a push with a known identity is an update, and totals are computed on request. The detailed section is not rewritten yet. Label volume in a long session is an open point (section 12, item 6).

B* = 0 when the cache expired
```

The collector keeps a fingerprint of each recent request, for each session:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think the collector should be dumb it shouldnt be keeping anything

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.

Same as the reply on push telemetry. The principle in section 5 says the receiver keeps no state and prices nothing. The state it still needs is the previous request's hashes for the counterfactual. Where they live is open (section 12, item 5). Do you prefer that they travel in each push, or that the producer keeps them?

@OsherElhadad OsherElhadad mentioned this pull request Oct 21, 2026
3 of 4 tasks
@boazdavid boazdavid changed the title docs: Add the context operations object model and a worked example feat(counterfactual): Add the counterfactual library and its design Oct 28, 2026
@boazdavid
boazdavid marked this pull request as ready for review October 28, 2026 09:35

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (claude, user of @boazdavid) Claude Code 2.1.241, claude-sonnet-5-5 offload-review skill, @boazdavid's session fresh 2 of 2 1 of 2 faa9e48126a4 blocking

Verdict: blocking

Findings

  1. counterfactual/compute.go:287 — restored compares cumulative hashes, so it misses a restore when any earlier position differs

    • What fails: PosHash.Hash is a chained prefix hash (fingerprint.go:29,47-51). restored tests client.Pos[ci].Hash == fwd.Pos[fi].Hash. This is true only if the whole prefix before the item is equal in both bodies. Take two active in-place rewrites A (messages[2]) and B (messages[5]). The operator of B stops applying B, but A is still applied. The forwarded prefix at messages[5] still holds A's shrunk bytes, so its hash differs from the client hash. restored returns false and B is never ended.
    • Proof: restored (lines 287-294) has no step that discounts earlier changes. forwardPositions (276) is the only caller that ends an in-place change. The only restore case I found is rewrite-restore-in-place-hot-5m (one change, no earlier change). The single-change case is the only one where the hash test works.
    • Effect: B stays in Active. price (742-761) credits B's Saved on every later request, although the forwarded body no longer has B's saving. The sum check (838-844) will fail, but the check does not stop pricing (result.go). The over-credit stays in the figures. This is the common multi-operator case.
    • Fix: compare the item's own bytes and hash relative to the prefix. For example, compare Bytes of the forwarded item with sp.before.Bytes (restored size equals the original size), or build per-item content hashes. Add a test with two active in-place changes where only the later one stops.
  2. counterfactual/doc.go:65-70 and counterfactual/compute.go:799-801 — the "Not implemented" text is false for code in this PR

    • What fails: doc.go says "The split, ttlPremium and ttlRescue effects ... Compute adds no figure for them" and "The order and conservation checks ... are not implemented". But compute.go implements all of these: split (644), headTTL (611) and conservation (777), and cacheEffects calls them. The comment above checks (799) also says conservation is not implemented. The head commit message says it adds "ttl, split and conservation".
    • Proof: grep -n "split\|headTTL\|conservation" counterfactual/compute.go shows the three functions called from calc and cacheEffects. doc.go is the package contract. A host author who reads it will believe Result.CacheEffects never holds EffectSplit, EffectTTLPremium or EffectTTLRescue, and that Checks never holds "conservation". A host that settles effects by exhaustive switch will then miss them.
    • Fix: remove the three bullets from "Not implemented" and add the new rules (split, headttl, conservation tolerance of tol+1, the restored inference) to "Implementation decisions". Fix the comment above checks.

Non-blocking

  • go.work is committed and the root go.mod has no require/replace for github.com/rossoctl/context-guru/counterfactual. dash/counterfactual_play_test.go imports it. This builds only in workspace mode. With GOWORK=off, or in go mod tidy on the root module, the import fails to resolve. Add a require plus replace ./counterfactual, or say in the PR that workspace mode is required. The Dockerfile and CI build only non-test code, so they are not affected today.
  • extent with no candidates calls cumBytes inside a loop over all positions (body.go:131). This is O(n²) per call, and Compute calls it twice per request. It is fine for tests. For a 5,000-message thread it is about 25M additions per call. A prefix-sum array in Body would remove it.
  • CLAUDE.md asks each feature PR to state its data dependence and update docs/data-dependence.md. This PR does not change that file. The code uses hashes and byte sizes only, so the entry is likely "metadata only". Please say so in the PR text.
  • Compute has no recover. The doc says a panic leaves ThreadState unchanged, which is true. The host must still wrap the call to fail open. A line in doc.go would make this clear.

What I checked

  • Read all of counterfactual/*.go non-test code in full: compute.go, types.go, state.go, body.go, fingerprint.go, result.go, doc.go, and opscases/opscases.go.
  • Read the test names in compute_test.go, effects_test.go, state_test.go, review_test.go, opscases_test.go, boundary_test.go, and the head of dash/counterfactual_play_test.go.
  • Skimmed docs/counterfactual/*.md for the conservation and end-of-change rules. I did not read every line of design.md (1,714 lines) or the examples.
  • Checked go.work, the go.mod files, the Dockerfile and ci.yaml for module wiring.
  • Traced concurrency: snapshot/replace give an optimistic lock, and the Compute loop retries on a version change. This is correct.
  • Traced empty-body and out-of-range inputs through flat, mustFlat, position, cumBytes. I found no panic.
  • I did not open any .json fixture. I did not run Go.

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (claude, user of @boazdavid) Claude Code 2.1.241, claude-sonnet-5-5 offload-review skill, @boazdavid's session fresh 1 of 2 1 of 2 faa9e48126a4 blocking

Verdict: blocking

Findings

  1. counterfactual/compute.go:287-294 — restored compares cumulative hashes across the client body and the forwarded body, so it misses a restore whenever anything earlier differs

    • What fails: PosHash.Hash is cumulative (fingerprint.go:29, NewBody). restored tests c.client.Pos[ci].Hash == c.fwd.Pos[fi].Hash. These two hashes are equal only if the whole prefix up to that position is equal in both bodies. Case: mask changes message 1 and coref changes message 3, both in place. On request N, coref stops applying and message 3 is the client's own item again. The forwarded hash at message 3 still differs from the client hash, because message 1 is still masked. restored returns false. The coref change stays in Active and is priced as a saving on every later request. The same happens when the forwarded body differs from the client body in tools or system (for example a delivered cachesplit). The end rule in design.md §11 question 12 says "same hash as the client item". It describes the same wrong test.
    • Proof: fingerprint.go:46-51 chains h across all sections and positions, and never resets it per position. compute.go:293 indexes Pos[ci] and Pos[fi] and compares .Hash only. No test in counterfactual/*_test.go has a second in-place change before the restored one. The only restore case is rewrite-restore-in-place-hot-5m, which has one change at message 1.
    • Fix: Compare an item-local hash. Either add a non-cumulative hash to PosHash, or compare Bytes plus the difference of consecutive cumulative hashes. Add a case with two in-place changes where the later one is restored first. The sum check (§6.5 check 1) may catch the wrong guess after the fact. It does not stop the wrong saving from being booked in the meantime.
  2. go.mod:1 — the root module imports counterfactual but does not require it; only go.work makes it resolve

    • What fails: dash/counterfactual_play_test.go:11-12 imports github.com/rossoctl/context-guru/counterfactual and .../opscases. The root go.mod has no require and no replace for that module. counterfactual/go.mod is a separate module. With go.work the build works. With GOWORK=off, or in any tool that ignores the workspace, go test ./dash/... fails to resolve the import. make fmt runs go mod tidy (Makefile:51). I expect it to try a network lookup for the module and fail. I could not run Go here, so this part is a prediction.
    • Proof: grep counterfactual go.mod go.sum returns nothing. go.work is the only link between the two modules. The design doc (D7) says the module path is a placeholder and its home is not decided. The code now depends on that path.
    • Fix: Pick one. Either keep one module and delete counterfactual/go.mod and go.work. Or add require plus replace ../counterfactual to the root go.mod. Or say in the PR that the go.work setup is deliberate, and show that go mod tidy and GOWORK=off go vet ./... still pass.
  3. docs/counterfactual/design.md:229, 763-767, 1679 — the spec says both "decided" and "not defined" for how a change ends

    • What fails: §11 question 12 (line 1679) now says "Decided: Compute infers the end from the bodies and the splice". D11 (line 229) still says "How Compute finds the end is not defined (§11, question 12)". §4.5 (lines 763-767) still says "The rule that finds the end is not defined". D14 (line 232) still lists question 12 as open. A reader who follows D11 gets the wrong answer. This spec is the base for the opscases tests.
    • Proof: grep "not defined" and "questions 11 and 12" in design.md. Compare with line 1679.
    • Fix: Update D11, §4.5 and D14 to point at the decided rule (the three end conditions in question 12).

Non-blocking

  • counterfactual/compute.go:799-801 — the comment on checks says "The order, attribution and conservation checks are not implemented". conservation is now implemented (line 777) and called from calc. Remove "conservation" from that comment.
  • counterfactual/state.go:29-49 — Trackers.m never evicts a thread. Memory grows with every session and thread for the life of the process. Question 13 covers persistence, but not eviction. Note it as an open item.
  • counterfactual/compute.go:24-36 — Compute called twice on one Request prices the second call against the state that the first call stored, and counts the active changes again. Preview is the safe repeat call. Say so in the doc comment, or guard it with a flag.
  • Compute does no recover. Fail-open (CLAUDE.md) is then the host's job. design.md says the ThreadState stays unchanged on panic. A one-line note in doc.go that each host must wrap the call would make the contract clear.
  • docs/data-dependence.md is not changed. This is correct today: the package registers no component and stores only hashes and sizes. If a host wires it into a feature, that PR must add the row.

What I checked

  • Read CLAUDE.md and docs/design.md.
  • Read all of counterfactual/*.go that are not tests: types.go, state.go, body.go, fingerprint.go, result.go, compute.go (every line).
  • Read counterfactual/opscases/opscases.go and the start of opscases_test.go.
  • Read the call site in dash/counterfactual_play_test.go and checked AttributeCache has the string cause argument in dash/event.go:1181.
  • Read go.work, counterfactual/go.mod, the root go.mod, the Makefile, the Dockerfile and the CI workflow for module wiring.
  • Read the design.md sections for D11, D14, §4.5 and §11 question 12. Did not read all 1,700 lines of design.md or the other docs/counterfactual files line by line. Did not read the test files compute_test.go, effects_test.go, review_test.go, state_test.go in full. Did not read gen_cases.py. I skipped the JSON fixtures as told.
  • Traced: phase and B* selection, break rows 1-6, rescue, headTTL, split, tier pricing, check 1 (sum), check 3 (unique change), conservation, nextState. Found no other defect.
  • Did not run any Go code (not approved).

@boazdavid

Copy link
Copy Markdown
Collaborator Author

Round 1 fixes are in commit 5accdd4.

Fixed:

  1. restored (compute.go): it now compares the size of the item, not the cumulative hash. Test: TestARestoreIsFoundWhileAnEarlierChangeStaysApplied. It fails on the old hash test and passes now. Known limit: another operator that rewrites the item to exactly the client size looks restored. The comment says so.
  2. Module link: the root go.mod has require and replace ./counterfactual. GOWORK=off go vet ./dash/, go build ./... and go mod tidy -diff pass.
  3. Spec: D11, D14, section 4.5, and the other places that said the end rule is "not defined" or open now point to question 12. Question 12 says the size is compared, not the hash. cortex-wiring.md, examples.md and issue_cases.md are updated too.
  4. doc.go and the comment above checks: split, ttlPremium, ttlRescue and conservation are no longer listed as not implemented. doc.go has a new rule 12.
  5. Doc notes added: Compute is called once for each request (use Preview to price again), the host wraps Compute to fail open, and Trackers never evicts a thread.

Not changed:

  • extent is O(n^2) on long threads. The code is correct. We will fix it when a host measures it.
  • docs/data-dependence.md: no change is needed. The package stores only hashes and sizes, and registers no component.

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

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (claude, user of @boazdavid) Claude Code 2.1.241, claude-sonnet-5-5 offload-review skill, @boazdavid's session resumed 1 of 2 2 of 2 5accdd466c30 approve

Verdict: approve

Findings

None. All round-1 findings are fixed.

Status of earlier findings:

  1. restored used cumulative hashes (mine 1, reviewer 2 finding 1): fixed. compute.go:287-306 now compares Bytes of the client item and the forwarded item. I traced TestARestoreIsFoundWhileAnEarlierChangeStaysApplied by hand. On request 3, opB sits at msg 5. Client size is 3000 and forwarded size is 3000, so it ends. opA sits at msg 2. Forwarded size is 500, so it stays. Active holds only opA, as the test expects. The author names the limit: another operator that rewrites the item to the client size looks restored. The comment and design.md question 12 state it. I accept this.
  2. Root go.mod lacked require (mine 2, reviewer 2 non-blocking): fixed. go.mod has require ... v0.0.0 and replace => ./counterfactual. I could not run GOWORK=off go vet here. The author reports that it passes.
  3. design.md said "decided" and "not defined" (mine 3): fixed. D11, D14 and section 4.5 now point at question 12 as decided. My grep for "not defined", "questions 11 and 12" and "same hash" finds only unrelated or correct uses.
  4. doc.go and the checks comment said split, headttl and conservation were not implemented (reviewer 2 finding 2): fixed. The three bullets are gone, doc.go has rule 12, and the checks comment is correct.
  5. My non-blocking notes (double Compute, no recover, no eviction): documented in compute.go and state.go.
  6. Reviewer 2's O(n²) extent: the author defers it until a host measures it. I accept this, because the code is correct.
  7. docs/data-dependence.md: the author states that no row is needed, because the package stores hashes and sizes only and registers no component. I agree.

Non-blocking

  • doc.go "Not implemented" now has a sentence about recover mixed into its intro. Move it to its own paragraph or to the Compute rule list.
  • Add a test for the size-collision limit (another operator rewrites the item to the client size), so the known limit has a fixed expected result.
  • The inline comments from @amiddavid on the earlier spec path (docs/superpowers/specs/...) are from before the move to docs/counterfactual/. The author answered each. Two items remain open by the author's own words: the end operation and the push model. They need no change in this PR.

What I checked

  • Last review: round 1, faa9e48, 2026-10-28T11:59:41Z
  • New commits read: 1 (5accdd4 fix(counterfactual): Find a restore by size, link the module, update the spec)
  • Read in full: 21 reviews (19 empty, 2 reviewer reviews), 1 comment, 20 inline comments (from the three files)
  • New items since my last review:
    • Author comment of 2026-10-28T13:04:54Z (round 1 fixes): checked each of its 5 fixed items and 2 "not changed" items against the diff. All match.
    • Commit 5accdd4: read the full Go diff (compute.go, compute_test.go, doc.go, state.go, go.mod). Grepped the doc changes in design.md, cortex-wiring.md, examples.md and issue_cases.md.
    • Reviewer 2's round-1 review: all its findings are covered above.
  • Did not run Go (not approved). I did not read the doc diffs line by line, only the greps above.

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (claude, user of @boazdavid) Claude Code 2.1.241, claude-sonnet-5-5 offload-review skill, @boazdavid's session resumed 2 of 2 2 of 2 5accdd466c30 approve

Verdict: approve

Findings

None.

Status of earlier findings

  • Mine 1 (restored used cumulative hashes): fixed. compute.go:287-306 now compares Pos[ci].Bytes == Pos[fi].Bytes. Item size does not depend on the prefix. I traced TestARestoreIsFoundWhileAnEarlierChangeStaysApplied: on request 3, item 5 is back to 3000 bytes (client 3000), so opB ends. Item 2 stays at 500 bytes (client 3000), so opA stays. The old hash test fails on this input, so the test pins the fix. The false positive (another operator rewrites the item to exactly the client size) is stated in the code comment, in doc.go rule 12 and in design.md. I accept it as a known limit. The sum check still catches it after the fact.
  • Mine 2 (doc.go "Not implemented" was false): fixed. Split, ttlPremium, ttlRescue and conservation are removed from the list. Rule 12 is added. The comment above checks is corrected.
  • Reviewer 1, finding 1 (same defect as mine 1): fixed, as above.
  • Reviewer 1, finding 2 and my non-blocking go.work note: fixed. Root go.mod now has require .../counterfactual v0.0.0 and replace => ./counterfactual. The Dockerfile does COPY . ., so the replace path exists in the image build.
  • Reviewer 1, finding 3 (design.md says both "decided" and "not defined"): fixed. D11, D14, §4.5, risk point 3, the config-change paragraph and the memory paragraph now point to the decided rule. grep "not defined" in docs/counterfactual/*.md returns nothing now.
  • Non-blocking items: the double-Compute note, the host-wraps-Compute note and the no-eviction note are added to the code comments. The extent O(n²) and data-dependence.md points are rejected with reasons (fix when measured; the package stores only hashes and sizes and registers no component). Both reasons are right for a library with no host wiring yet.

Non-blocking

  • doc.go "Not implemented": the sentence about Compute not recovering from a panic sits inside the "not implemented" intro. It is not a missing feature. Move it to the package overview.
  • design.md D14 still says "A failure or a panic leaves the old ThreadState". This is true. No change needed.

What I checked

  • Last review: round 1, faa9e48, 2026-10-28T11:57:42Z
  • New commits read: 1
    • 5accdd4 fix(counterfactual): Find a restore by size, link the module, update the spec
  • Read in full: 40 review entries (2 with bodies: my round 1 and reviewer 1 round 1; the rest are empty inline-review wrappers), 1 comment, 25 inline comments (from the three files, read with the Read tool, no truncation)
  • New items since my last review:
    • Reviewer 1 round 1 review: checked each finding against the new commit (above).
    • Author comment of 2026-10-28T13:04:54Z (five fixes, two "not changed"): checked each claim against the diff. All match.
    • No new inline comments after 2026-10-20. No comment from a person that asks for something new.
  • Read the full Go diff (compute.go, compute_test.go, doc.go, state.go, go.mod) and the full docs diff (design.md, cortex-wiring.md, examples.md, issue_cases.md).
  • Checked the Dockerfile for the replace path. I did not run Go. I did not open any .json fixture.

@amiddavid

Copy link
Copy Markdown
Collaborator

Root cause 2 (the rate follows "first time", not position): review result

Result: outside coref, the first two cases do not happen in real use. We treat the third case as a restart bug, not as an error in the saving formula. It is tracked in #766.

The three cases

  1. rewrite/after-last-breakpoint/input/5m: does not happen. Our components edit only the tail, which is not cached yet. The tail is at or before the last breakpoint: Claude Code puts its last breakpoint on the last message, and cacheinject does the same. So a tail token that is not removed is written, and cg's write rate is correct.
  2. rewrite/no-breakpoint/input/5m: does not happen. The same reason applies. The only exception is an Anthropic client that sets no breakpoints while cacheinject is off. There the over-credit is 25% of a small figure.
  3. boundary/state-lost-reads-cache: a bug, tracked in fix(restart): restart grace must use the thread's last request time, and a replay after a restart is priced as a write #766. After a proxy restart, cg loses its in-memory state:

The components that edit the cached part

The open spec question about where B* is (design §5.1) still matters for coref. With a literal reading, B* is at the end of system, and cg's write rate would be correct for that case.

@amiddavid

Copy link
Copy Markdown
Collaborator

Root cause 3 (added tokens count as zero, and an ended change still gets credit): review result

Result: cause 3 does not happen in normal use. The request total is correct. Only the split between components is wrong, and a missing break charge on failure paths falls under cause 1.

Part 1: an edit that adds tokens (four-operations, fixed-restore-cost)

  • cg adds expand and restored content at the tail. That content is written once and read after that, like any other new content. No cached part changes.
  • Event.Saved() nets the added tokens, so the request total is correct.
  • ComponentSavedUSD sets a negative figure to zero, so the restore shows as free and mask keeps its full credit. This is a display problem in the per-component figure.
  • Open: check whether a feature makes a decision from the per-component figure (for example save-more or the cleanup page). If one does, it sees mask as better than it is.

Part 2: a change that ends (restore-in-place, the second half of decision-flips-inside-prefix)

  • cg replays a frozen edit on every request (mask.go:76). The provider sees only the marker, and the original stays in the proxy. So in normal use the provider never sees a change end.
  • The provider sees a change end only when the replay fails:
    1. A component panics or returns an error. The pipeline then reverts all of that component's edits, frozen replays included (components/pipeline.go:154, :191).
    2. The freeze is lost and repairLostFreeze cannot rebuild it.
    3. The preset or the config changes during a session.
  • In these cases the originals go back inside the cached part, and that is a break. cg charges no one for it. This is the cause 1 gap on a failure path. It is not a separate pricing error.

@amiddavid

Copy link
Copy Markdown
Collaborator

Root cause 4 (a setting change): review result

Result: out of scope for cg today. It is not a gap in cg. It is a feature that the counterfactual library must support, and the library in this PR already has the cases for it.

Why it is out of scope for cg now

  • No cg component changes the model, effort or another setting during a session.
  • A router or the client made the change in these cases. cg reports the saving from its own edits, so 0 is the correct answer for cg.
  • When a cg component starts to change a setting during a session, cg must price the break it causes. The counterfactual library is the place to do that.

What this PR must keep

The library must price a setting change correctly. The cases are already in counterfactual/opscases/cases/:

  • setting-model-change-break
  • setting-effort-change-break-from-messages
  • setting-effort-change-read-intact-no-break
  • setting-web-search-toggle-break-from-system
  • setting-nil-position-penalty-unknown

In differences.json they stay notCovered against cg. They are not cg defects.

A correction to cg-differences.md

It says "cg does not read effort". That is wrong. cg already detects setting changes as the cause of a cache miss, but does not price them:

  • effort_changed, for effort, thinking mode or thinking budget (dash/prefixcause.go:138)
  • model_changed, tools_changed, system_changed (dash/event.go:40)

Still open in the spec

  1. Which rates price a model-change break. The case uses the new model's rates (−36,800 µ$). The old model's rates give −138,000 µ$ (design §11, question 10).
  2. Where effort sits in the prompt. The effort case assumes it comes before the messages. That comes from cached-prefix.md and was not tested on a real model.

@amiddavid

Copy link
Copy Markdown
Collaborator

Root cause 5 (keep-alive credit floor): review result

Result: no cg defect. Case 1 is a gap in this PR's test helper. Case 2 is a change to the spec: the owner decided that OpenAI's 30-minute minimum counts as the lifetime.

Case 1: keepalive-ping-on-1h-entry-no-rescue-1h: fix Play in this PR

  • Play (dash/counterfactual_play_test.go) does not set Provider or CacheTTL on the event. So cg falls back to the 5-minute floor and credits a 9-minute return on a 1-hour entry.
  • The real proxy sets both fields on every event (proxy/dashcapture.go:442 and :707). In production cg uses the 1-hour floor and gives no credit, the same answer as the spec.
  • To do in this PR: set Provider and CacheTTL in Play from the case, then run the test again. The case should then agree with cg. If it does not, report the gap that remains.
  • The small difference that remains: the spec uses the TTL of the breakpoint that wrote the entry. cg uses the TTL that the returning request asks for. They differ only if a client changes tier during a session.

Case 2: keepalive-ping-minimum-lifetime-no-rescue: change the spec

  • Owner decision: "assume 30 min is 30 min". We cannot know whether an entry stays in the cache past OpenAI's minimum. So a gap of more than 30 minutes counts as an expiry, and a ping before it counts as a rescue.
  • This is what cg does now (keepaliveCreditFloorMs, dash/event.go:1069).
  • To do in this PR:
    1. Change design §4.4 condition 2 and R45: a documented minimum lifetime counts as the lifetime.
    2. Change the case to a rescue, with cg's figure as the expected figure. Rename it, for example keepalive-ping-minimum-lifetime-rescue.
    3. Check keepalive-no-ping-minimum-lifetime-evidence-hot against the same rule.
  • Separate, in main: the comment at dash/event.go:1083 ("OpenAI's minimum must not be used as proof that an entry has expired") contradicts the code and this decision. It needs a comment fix. The behavior does not change.

@amiddavid

Copy link
Copy Markdown
Collaborator

Root cause 6 (credits outside the per-component figure): review result

Result: there are two parts. The cachesplit cases show a gap in this PR's test helper. The 1-hour head is a real gap in cg, and this library fills it. We do not fix it in cg: cg adopts the library.

Part 1: cachesplit (split/delivered/stable-half-read): fix Play in this PR

  • Play adds CachesplitSavedUSD to the result, but it does not set TailChanged or SplitStableTokens. So the first check in cachesplitSavedUSD (dash/event.go:977) returns 0.
  • The real proxy sets both fields from the trace (FromTrace, dash/event.go:675).
  • To do in this PR: set both fields in Play from the case, then run the test again. If a gap remains, report it.

Part 2: the 1-hour head (ttl/head-1h/*, 3 cases): a gap in cg, filled by this library

A deeper check shows that cg has no measured figure for the 1-hour-head strategy:

  1. apply records HeadTTL1h and HeadTTLTokens on the trace (apply/apply.go:442). Nothing in dash/ or proxy/dashcapture.go reads them.
  2. CostUSD includes the 1-hour write premium (dash/event.go:810). BaselineCostUSD includes it too, so the premium cancels out of the saving. cg charges the premium to no one.
  3. The keep-alive credit needs a ping (KeepAlivePings > 0). 1-hour-head sends no pings, so a 1-hour rescue never gets credit.
  4. The cache campaign's 1-hour arms sum the same ping credit, so they read 0 for the head.
  5. The KV-cache page only simulates the 1-hour tier. It does not measure it.

This library covers both parts: EffectTTLPremium for the cost and EffectTTLRescue for the saving (counterfactual/compute.go:635, :648). We do not add a 1-hour ledger to cg. It comes when cg adopts the library.

A correction to cg-differences.md and differences.json: they say "cg books the headttl credit outside the per-component figures". That is wrong, because cg has no such credit. The 3 cases are a real gap in cg, not a gap in the test helper.

Why it has not mattered yet: the strategy is off by default. Of the models we measured, only Haiku 4.5 grants the 1-hour tier (apply/headttl.go).

@amiddavid

Copy link
Copy Markdown
Collaborator

Root cause 7 (no check for an unreported edit): review result

Result: this is a check the library needs. It is not a gap in cg's proxy.

How cg arrives at 1,500 µ$

  • Event.Saved() is TokensBefore − TokensAfter (dash/event.go:557). It is the size difference of the whole request, not the sum of the components.
  • Play sets TokensBefore from the client body and TokensAfter from the forwarded body. So any size difference counts as a saving: 5,000 × $0.30 = 1,500 µ$.

Why the real proxy is not at risk

  • The proxy measures TokensBefore and TokensAfter at the start and the end of cg's own pipeline (components/pipeline.go:85). It does not see a plugin edit made outside the pipeline.
  • Inside the pipeline, every change belongs to a component. A component that cuts tokens without stashing an original is reverted (components/pipeline.go:191).
  • The envelope steps in apply (system split, tool filter) are reported in their own fields (SplitStableTokens, FilteredDeclTokens).

Why the library needs the check

A host such as Cortex can let a plugin edit the body without reporting it. The library's sum and conservation checks catch that. Keep the case.

The unknown_kind half of the case agrees with cg. The sizes do not change, so cg books 0 too.

@amiddavid

amiddavid commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

Review summary: all 26 cases that differ from cg

Result: every case that differs from cg traces to one of the seven root causes in the notes above. No case is left without a cause.

The 26 cases are the full set at the PR head (5accdd46), and TestCasesAgreeWithCurrentLogic fails if a differing case is missing from differences.json.

# Case Cause Category Note
1 summary/break-then-payback 1 Library The summarizer's break is not charged
2 coref-break-inside-prefix 1, 2 Library coref is in no preset
3 four-operations 3 Library The request total is right. Only the expand line is wrong.
4 setting/model-change 4 Library Out of scope for cg until a component changes a setting
5 setting/effort-change 4 Library Same as 4
6 state-lost-reads-cache 2 cg fix (#766) + Library #766 part 1 fixes what the proxy edits after a restart. The library fixes the replay pricing (#766 part 2, owner decision: wait for the library).
7 searchfold-inside-prefix 1 Library Rare: needs a decision change
8 decision-flips-inside-prefix 1, 3 Library Rare: needs lost state
9 replay-at-new-position 1 Library Only with allow_cached_prefix
10 break-then-payback-turns 1 Library coref
11 fixed-restore-cost 3 Library Per-component display only
12 restore-in-place 3 Library Failure paths only
13 split/stable-half-read 6 Test Play does not set TailChanged or SplitStableTokens
14 ping-on-1h-entry 5 Test Play does not set Provider or CacheTTL
15 ping/minimum-lifetime 5 Test Owner decision: 30 min is 30 min. Change the spec and the case.
16 after-last-breakpoint 2 Library Does not happen in real use
17 no-breakpoint 2 Library Does not happen in real use
18 two-spans-two-tiers 1, 2 Library failed_run, rare
19 expand-first-injection 1 Library Not checked: whether the expand declaration is added mid-session
20 toolschema-mid-session 1 Library Once per deployment
21 setting/web-search-toggle 4 Library Out of scope for cg
22 setting/nil-position 4 Library Out of scope for cg
23 head-1h/never-read 6 Library cg has no 1-hour ledger
24 head-1h/read-after-20-minutes 6 Library Same as 23
25 head-1h/read-after-3-minutes 6 Library Same as 23
26 unknown-kind-and-unreported-edit 7 Library The library needs this check for other hosts. cg does not.

Things to know about the table

  • "Library" means cg gets the fix when it adopts the library. cg's own code does not change. Of these, only 1, 2 and 10 (summarizer and coref) matter in real use today. The others are rare or out of scope.
  • Fixes in this PR:
    • the 3 Play fixes (cases 13 and 14) and the spec and case change for case 15
    • the doc corrections: the effort sentence (cause 4) and the head-TTL credit (cause 6)
  • Outside this PR, in main:
    • fix(restart): restart grace must use the thread's last request time, and a replay after a restart is priced as a write #766 part 2 (replay pricing after a restart): owner decision, wait for the library. cg's dashboard keeps its record of removed content in memory only. So after a restart it prices a replayed removal at the write rate, and the saving shows too high. The library prices the replay from the read in the usage and does not need that record. Until cg adopts the library, the figures after a restart stay too high.
    • The comment at dash/event.go:1083 contradicts the 30-minute decision. It needs a rewording, with no behavior change.

@amiddavid

Copy link
Copy Markdown
Collaborator

Missing test: two threads in one session

Summary. No case in this PR has more than one thread. All 59 cases use the thread main. ThreadKey puts the thread ID in the key, so the design keeps threads apart. But no test proves it.

Why it matters

  • We found a bug of this type in the shipped dashboard, in the summarizer credit (dash/compactepisode.go). groupConversations groups rows by session and model, not by thread.
  • On one real session, side requests (2 messages each) and subagents added about 15 times more new content than the main thread. That new content used up the main thread's span 4 minutes after the summary. The dashboard then counted almost all of the summary's saving as $0.
  • The dash tests also have only one thread, so they did not find it.
  • This PR is meant to replace that kind of logic, so it should prove that it does not have the same bug.

Proposal

Add a case like state/session-isolation, but with two threads in one session:

  1. On thread main, an operator reports a change, for example a summary.
  2. Then thread p:side, and after it thread a:sub, send requests with large cache writes and their own changes.
  3. Then thread main sends a request again.

The checks:

  • The change on main is still active, and only main's requests price it.
  • The requests on p:side and a:sub do not end, replace or move the change on main.
  • The Version lock of each thread moves on its own requests only.
  • No unique_change failure if two threads report the same ChangeID.

Open question

Does a thread ever share a cached prefix with its parent? A side request often starts with the main thread's system prompt and tools. If yes, a case should show how a parent's change prices on the child's request.

@amiddavid

Copy link
Copy Markdown
Collaborator

Two more questions about replacing the dashboard ledger

These follow from the comment above. The summarizer figure on the dashboard today comes from dash/compactepisode.go, not from this library.

1. Does the dashboard's summarizer figure move to this library?

  • docs/counterfactual/cortex-wiring.md says what the library replaces in Cortex (core/cost/spend). For the proxy, it adds a dashEmitter.
  • It does not say that dash/compactepisode.go (the summarize ledger) goes away.
  • Until the dashboard reads the summarizer figure from this library, the thread-mixing bug stays visible. On the session we checked, the dashboard credits about $1.26. The proxy stored $63.42 per request.

Question: Is it part of this work to take the dashboard's summarizer credit from the library and delete the old ledger? If not, which issue tracks it?

2. Does the library model the compaction the client would have done without us?

  • The old ledger credits a summary only until the conversation adds 10% of the window in new content. The reason: without the summary, Claude Code would have compacted by itself at about that point. After that, both worlds carry a compacted transcript, so the saving is not ours.
  • This library prices each request against the cached prefix. It ends a change when a client compaction really happens. I found no rule for a compaction that the client would have done without us.
  • On the session we checked, the summary fired at 946k of a 1M window. Without it, Claude Code would have compacted after about 54k more tokens. The summary was then replayed for about 8.5 hours. Without that rule, the library would likely credit close to the full $63.42.

Question: Should the library model the client's own compaction point (internal/compactionpoint), so a summary stops earning credit where the client would have compacted? If not, which figure is the correct saving, and who decides?

@boazdavid
boazdavid force-pushed the docs/context-operations-spec branch from caed9a9 to 9c13433 Compare November 2, 2026 10:10
@boazdavid boazdavid changed the title feat(counterfactual): Add the counterfactual library and its design test(dash): Compare the accountant cases with cg's saving logic Nov 2, 2026
Plays the 63 shared test cases of github.com/rossoctl/accountant (v0.1.0) through
dash.Event.Price and compares the result with each case's expected figures. A
case that is not in testdata/differences.json must agree to within 1 µ$. A
listed case must really differ, and an entry whose case no longer exists fails.

What differs is written up in docs/accountant/: 27 of 63 cases (20 differs, 7
notCovered), grouped into eight root causes in cg's logic.

The specification, the design and the cases moved to the accountant repository.
This change only adds the comparison on the cg side. It reads no stored customer
data and registers no component, so data-dependence.md does not change.

Refs #633

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
@boazdavid
boazdavid force-pushed the docs/context-operations-spec branch from 9c13433 to 2705885 Compare November 2, 2026 10:22
boazdavid added a commit that referenced this pull request Nov 2, 2026
@boazdavid boazdavid closed this Nov 2, 2026
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants