Skip to content

docs: Say how a host reports a defer_loading deferral (#60) - #61

Merged
boazdavid merged 3 commits into
mainfrom
feat/defer-loading-prefix-removal
Nov 10, 2026
Merged

boazdavid merged 3 commits into
mainfrom
feat/defer-loading-prefix-removal

Conversation

@boazdavid

Copy link
Copy Markdown
Contributor

Summary

The library already prices a defer_loading deferral. It needs no new field. This PR writes down how a host reports it, and adds tests.

Refs #60.

What we found

  • Issue Price tool deferral (defer_loading): the saving is invisible to a body diff #60 says the saving is invisible to a body diff. That is true when the host builds the forwarded Body from the wire bytes.
  • The provider keeps a deferred tool out of the prompt and bills a stub for it. If the host builds the forwarded Body as the prompt the provider bills, a deferred tool has the size of its stub.
  • The deferral is then a normal rewrite that shrinks tools positions. The engine prices it today.
  • I tested this before I wrote any code. With 2 deferred tools (750 + 500 tokens, 10-token stubs) the library books 1,230 saved tokens: written on the first request, read on a hot request, written again after the entry expires.

Why no new field

  • A per-position "off prompt" mark, like Media, would touch about 25 places. They are ratio, extent, the span sizes, the conservation check, persistence and others.
  • It would give no result that the host cannot already get by building the Body as the billed prompt.
  • A new field also puts the same fact in two places. The host could set one and not the other.

What changed

  • docs/spec.md: new rule R56.
  • docs/design.md §5.3: a short note that the forwarded Body is the prompt the provider bills.
  • internal/engine/deferral_test.go: 3 tests.
    • The deferral is priced as a shrink on a first, a hot and a cold request. The sum check, the conservation check and the cache effects are clean.
    • A host that builds the Body from the wire bytes fails the sum check.
    • A deferral with no ChangeID is not carried to the next request.
  • test/gen/gen_cases.py and one generated case: rewrite/tool-defer-stubs/first-hot-cold/5m.

Answers to the open questions in #60

  1. Field on Size or Operation? Neither. See "Why no new field".
  2. A deferred tool is loaded later. Its definition enters the messages. The host reports it as a rewrite that makes the context larger (R33), which is a cost. R56 says so. I did not add a link between the two operations. Nothing needs it yet.
  3. Models that ignore defer_loading. The host removes the definitions itself and the body shrinks. This already works. R56 says nothing applies there.

How it was tested

  • gofmt -l ., go vet ./... and go mod tidy -diff are clean.
  • go test ./... passes.
  • go generate ./test/cases adds one file. The 143 existing cases do not change.
  • I changed the expected value in the first test and it failed. I restored it.

Not covered

  • I wrote the tests after I found that the engine already works, so they did not fail first. There is no engine change for them to drive.
  • No real traffic. The case uses the fixture rate of 4 bytes a token.
  • The host side is not here. The host must build the forwarded Body with stub sizes. In context-guru this is a change in proxy/accountant_wire.go.
  • R56 does not say how a host finds the stub size. A host that cannot measure it cannot follow the rule.

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

A host that defers tools leaves each definition in the body it forwards.
The provider bills a stub for it. The library already prices this when the
host builds the forwarded Body as the prompt the provider bills, so no new
field is needed.

Add rule R56 to the spec, a note to design 5.3, three engine tests and one
generated case (first, hot and cold request).

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

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Contributor 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 @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 c6e9acd06590 approve

Verdict: approve

Findings

None.

Non-blocking

  • docs/design.md:1033-1039 — the new paragraph splits an old sentence pair. The old text was "A host may also send a token count in Size.Tokens (§4.2 rule 7). The same tokens in both hosts holds whenever...". The PR inserts the defer_loading paragraph between the two sentences. The sentence "The same tokens in both hosts holds..." now ends the new paragraph, far from its antecedent. A reader of the deferral paragraph meets it with no referent. Fix: move that sentence back to the Size.Tokens paragraph, before the new one.
  • docs/spec.md:358 — "the operation is not trusted" names no engine behavior. The engine has no "not trusted" state for an operation. Design §6.5 says a failed check does not stop pricing, and Result.Checks only reports it. The Go test confirms this: the op is priced and the check is listed. The words can suggest the library refuses the op. Fix: say "the sum check fails and the host sees the failure in Result.Checks (§6.5)".
  • No test for the load-later path. Spec R56 says a deferred tool loaded later is a rewrite that grows, priced as a cost (R33). No new test covers that path. The behavior is ordinary R33 pricing, already covered by other cases, so this is not blocking. A test would fix the doc claim to code.

What I checked

  • Read CLAUDE.md, docs/spec.md (R22, R29, R33, R52-R56), docs/design.md (§5.3, §6.5) and the full diff of all 5 files.
  • gofmt -l . prints nothing. go vet ./... clean. go test ./... passes all packages.
  • Regenerated the cases in a temp copy of the tree: go generate ./test/cases produces the committed JSON byte for byte. The new case rewrite-tool-defer-stubs-first-hot-cold-5m.json runs, because test/cases/cases.go:268 globs all *.json.
  • Checked the numbers by hand. Go test: tools 1,000+3,000+2,000 = 6,000; stubs 2 x 40 = 80; saving 4,920. Bill r1 = 1,080 + 3,000 + 1,000 = 5,080 = Usage.CacheWrite. r3 = 7,080 = 5,080 + 1,000. All match. JSON case: 1,250 - 20 = 1,230 saved; baseline minus usage = 1,230 on each step; tier follows the phase (write, read, write). All match.
  • Verified each spec claim against the tests: shrink pricing with no new field (test 1), ChangeID repeat as active:td:set-1 (test 1), no ChangeID means no repeat (test 3), wire-byte body fails the sum check (test 2).
  • Verified links: design.md#65-checks matches ### 6.5 Checks; R22, R33 anchors exist; R56 id is unique.
  • No engine or accountant.go change, so no API or R3 concern. New test file imports only testing and time.

…60)

The 1h case keeps the 1,230-token saving as a read after the 5m TTL,
and writes it at the 1h tier once the entry is cold. The loaded-later
case adds the full definition of a loaded tool as a cost that is
written, while the other stub keeps the deferral saving.

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

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Contributor 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 @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 c6e9acd06590 blocking

Verdict: blocking

The engine code does not change. The PR adds spec rule R56, a design paragraph, a unit test, and one generated case. The code side is sound: go vet ./... and go test ./... are clean, and the JSON case is in sync with gen_cases.py. The defects are in the words the PR adds.

Findings

  1. docs/spec.md:358 — R56 says the operation is "not trusted", but the library prices it

    • What fails: a host that builds the forwarded Body from the wire bytes gets a sum check failure. R56 then says "the operation is not trusted". Design §6.5 says the opposite: "A failure does not stop pricing. The one exception is check 13 (size_range)". The library prices the operation and only records the check. The sum failure does not even name the operation, because the CheckFailure carries no Operator (internal/engine/compute.go:1856-1861).
    • Proof: docs/design.md:1431-1433 (§6.5 rule); internal/engine/compute.go:1856-1861 appends the check and returns; nothing unprices the operation.
    • Fix: say what happens. For example: "The sum check fails and names the section. The library prices the operation anyway (§6.5)."
  2. test/cases/rewrite-tool-defer-stubs-first-hot-cold-5m.json:3 — the description says "there is no cache break", but step 3 expects one

    • What fails: the cold step (r2, 21 minutes after r1) expects an effect of kind break, with the note "the entry expired; B* is 0, so the read extent to B* is empty". The description's last sentence says "there is no cache break". A reader who trusts the description will not expect the effect that the case asserts.
    • Proof: step 3 of the case, expected.effects[0] has "kind": "break". The case break-expiry-moves-no-tokens-cold-5m.json calls the same record a break: "The expiry is on the record as a break with no ChangeID (§5.2 row 5)".
    • Fix: split the claim. Say: "The deferral changes no forwarded position, so it breaks nothing. The cold request has one break, the expired entry, and it moves no tokens."
  3. docs/design.md:1034-1039 — the new paragraph is spliced into the middle of an existing paragraph

    • What fails: the sentence "The same tokens in both hosts holds whenever..." belonged to the paragraph that ends with "A host may also send a token count in Size.Tokens (§4.2 rule 7)." (docs/design.md:1032). The insert now separates the two. The orphaned sentence ends the deferral paragraph, so "the same tokens" reads as the stub tokens of defer_loading, not the host token counts.
    • Proof: the diff inserts a blank line and the new paragraph between "(§4.2 rule 7)." and "The same tokens in both hosts".
    • Fix: move the new paragraph below the old one. The old paragraph stays whole, and its last sentence keeps its antecedent.
  4. docs/issue_cases.md — no entry for the accountant#60 case

    • What fails: the repo records each batch of issue-driven cases in docs/issue_cases.md. Sections 9b (#40-41), 9c (#44), 9d (#49), 9e (#52-56) and 9f (the compaction cases) each landed in the same commit as their JSON cases (358f6d6, b285305, 8a65185). This PR adds rewrite/tool-defer-stubs/first-hot-cold/5m for accountant#60 and adds no section. The catalogue is now incomplete.
    • Proof: git show --stat 358f6d6 and b285305 show docs/issue_cases.md beside the new JSON files. The diff of this PR does not touch docs/issue_cases.md.
    • Fix: add a section "9g. Cases from accountant#60" with one row for the case, in the format of section 9f.

Non-blocking

  • spec.md puts R56 before R55 in the list (order R52, R56, R55, R54). The list was not sorted before this PR. A note only.
  • R56 describes the loaded-later direction: a deferred tool that is loaded again is a rewrite that grows the context (R33). This PR adds no test for that direction. The growth rule is covered by other cases, so this is a coverage note, not a defect.
  • testing.md §10.3 list B names some unit-test files (item 29 names mincacheable_test.go). The new deferral_test.go is not named. A note only.
  • The unit test uses a ratio of one token per byte, so its results are exact. The JSON case uses four bytes per token, so its results carry estimated: true. Both paths are covered. Good.

What I checked

  • The full diff: docs/spec.md, docs/design.md, internal/engine/deferral_test.go, test/gen/gen_cases.py, and the new JSON case.
  • go vet ./... and go test ./... from the worktree root. Both clean.
  • The JSON cases are in sync: I copied test/ to a temp folder, ran gen_cases.py there, and diffed the output against test/cases/. No difference. The repo files were not touched.
  • The figures of the new case, by hand: saved 1,230 = 1,250 - 20; baseline 2,500 (r0), 2,750 (r2); billed 1,270 (r0), 1,520 (r2); hot read 1,270 with write 250. Prices at the fixture-v1 rates: 1,230 x $0.30/M = $0.00037 (read), 1,230 x $3.75/M = $0.00461 (5m write). Both match the description.
  • The unit test assertions against the engine: the deferral prices as a shrink (4,920 written, then read, then written again), the replay carries the ID active:td:set-1, the wire-body host fails the sum check, and an op with no ChangeID does not replay. The tests pass and the assertions are not vacuous.
  • The R56 claims against the code: no new field, pricing by the ordinary shrink path, replay by ChangeID (R22). All hold.
  • The repo rules: no engine change, so no new exported name (api_test.go unaffected); stdlib only (boundary_test.go unaffected); Compute behavior unchanged, so the doc duty is about the new words themselves.

- R56 no longer says the operation is not trusted. A failed sum check
  names the section and the library still prices the operation (§6.5).
- The case description says the cold request has one break, the expired
  entry, and that it moves no tokens.
- The deferral paragraph in design §5.3 follows the old paragraph, so
  the sentence on the same tokens in both hosts keeps its antecedent.
- docs/issue_cases.md has a section 9g for the three #60 cases.

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

Copy link
Copy Markdown
Contributor Author

Replies to round 1

I fixed every finding. The fixes and two new cases are in af710ce and 589505a.

Reviewer 2, finding 1 (spec.md, "not trusted"): fixed.

  • R56 now says the sum check fails and names the section. The library still prices the operation (§6.5).
  • You were right. Design §6.5 says a failed check does not stop pricing, except size_range.

Reviewer 2, finding 2 (case description, "no cache break"): fixed.

  • The description now says the deferral breaks nothing. The cold request has one break, the expired entry, and it moves no tokens.
  • The case is regenerated with go generate ./test/cases.

Reviewer 2, finding 3 and reviewer 1, non-blocking 1 (design.md paragraph split): fixed.

  • The deferral paragraph now follows the old paragraph.
  • The sentence "The same tokens in both hosts holds ..." is back next to the Size.Tokens sentence.

Reviewer 2, finding 4 (issue_cases.md): fixed.

Both reviewers, no test for the load-later path: fixed.

  • New case rewrite/tool-defer-stubs/loaded-later/5m. A loaded tool adds its 750-token definition as a cost that is written. The other stub keeps the 1,230-token saving.
  • New case rewrite/tool-defer-stubs/first-hot-cold/1h. The 1h entry is still hot 21 minutes later. It is cold only after the 1h TTL.
  • Both cases were derived by hand from the spec, not from real traffic.

Not changed:

  • R56 sits before R55 in the list. The list was not sorted before this PR (reviewer 2, note).
  • testing.md §10.3 does not name deferral_test.go (reviewer 2, note). I will add it if you want it.

Checks on 589505a: go test ./..., go vet ./..., gofmt -l . and go mod tidy -diff are clean. go generate ./test/cases changes only the files listed above.

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

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Contributor 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 @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 589505a6ddb9 approve

Verdict: approve

All four findings of round 1 are fixed. The two new commits add two more cases and the catalogue entry. I found no new defect.

Findings

None.

Round 1 findings

  1. spec.md "the operation is not trusted" — fixed. R56 now says: "The sum check fails and names the section (§6.5). The library still prices the operation." This matches the code: the check detail is section=%s ops=%d bodies=%d bytes (internal/engine/compute.go:1858-1860), and pricing continues.
  2. Case description "there is no cache break" — fixed. The description now says: "The forwarded prefix does not change, so the deferral breaks nothing. The cold request has one break, the expired entry, and it moves no tokens." This matches the expected break effect of step 3. The JSON is regenerated and in sync.
  3. design.md paragraph split — fixed. The sentence "The same tokens in both hosts holds..." is back in the Size.Tokens paragraph (docs/design.md:1033). The deferral paragraph now follows it as a whole paragraph.
  4. issue_cases.md missing entry — fixed. New section 9g (docs/issue_cases.md:675) lists all three #60 cases and the two unit-test situations. I checked each row against its case; see below.

Reviewer 1 raised the same three points as non-blocking notes (paragraph split, "not trusted", load-later test). All three are fixed by the same changes. I checked each fix myself. Nothing to add.

What I checked

  • Last review: round 1, c6e9acd, 2026-11-10T05:28:45Z
  • New commits read: 2 (af710ce test: Add the 1h and loaded-later cases for a defer_loading deferral; 589505a docs: Fix the round 1 findings on the defer_loading rule)
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files)
  • New items since my last review: the author's reply comment (replies to all findings; I checked each claim), commit af710ce (two new generated cases; reviewed below), commit 589505a (the four fixes; verified above).

The two new cases, checked by hand against the spec:

  • rewrite/tool-defer-stubs/first-hot-cold/1h. Breakpoints and facts are 1h. r1 at 21 minutes: a 5m entry would be expired, the 1h entry is alive, so the phase is hot and the 1,230-token saving is a read. r2 at 79 minutes after r1: past the 1h TTL, cold, the saving is written at the 1h tier (cacheWrite1h 1,230), with one break from the expired entry that moves no tokens. All figures match: baselines 2,500/2,750, billed 1,270/1,520.
  • rewrite/tool-defer-stubs/loaded-later/5m. The model loads t1 on r2. The host forwards message 2 with the 750-token definition in it (1,000 tokens against the client's 250), as a rewrite with its own ChangeID (td:load-t1). Expected: caused cacheWrite5m 750 (a cost, R33, written because the new message is past the cached prefix) and the deferral replay saved cacheRead 1,230. Figures match: billed read 1,520 + write 1,000 against baseline read 2,750 + write 250; conservation 3,000 - 2,520 = 480 = 1,230 - 750. Sum check per section: tools 1,500 - 270 = 1,230, messages 750 - 1,500 = -750, both equal to the operations' spans.

Verification runs:

  • go vet ./... and go test ./... on 589505a: clean, all three packages pass.
  • The JSON cases are in sync: I copied test/ to a temp folder, ran gen_cases.py there, and diffed the output against test/cases/. No difference. The repo files were not touched.
  • No Go file changed since round 1, so the round-1 checks on deferral_test.go stand.
  • The 9g rows match their cases: the 5m row, the 1h row (21 minutes hot, cold after the 1h TTL) and the loaded-later row (750 tokens written as a cost, the other stub keeps the 1,230-token saving).

Non-blocking

  • docs/spec.md:359: the fixed sentence makes one long line ("The library still prices the operation. When a deferred tool is loaded later..."). The file wraps most lines near 110 characters. Cosmetic only.
  • In the loaded-later case, the load action reuses the operator name tool-defer for the rewrite that grows message 2. The operator name is host-chosen data, and the ChangeID is its own. A name such as tool-load would read better. Cosmetic only.

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Contributor 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 @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session resumed 1 of 2 2 of 2 589505a6ddb9 approve

Verdict: approve

Findings

None.

Status of the round 1 findings

  • Reviewer 2, finding 1 (spec.md, "not trusted"): fixed. R56 now says the sum check fails and names the section, and that the library still prices the operation. I checked the claim against the code. internal/engine/compute.go:1858-1860 writes the failure detail as section=%s ops=%d bodies=%d, so the check does name the section. Design §6.5 says a failure does not stop pricing. The words now match the code.
  • Reviewer 2, finding 2 (case description, "no cache break"): fixed. The description now says the deferral breaks nothing, and the cold request has one break, the expired entry, that moves no tokens. The JSON r2 effect matches: kind break, empty saved and caused, inBaseline true. The 5m JSON changed in the description lines only.
  • Reviewer 2, finding 3 and my non-blocking 1 (design.md paragraph split): fixed. The sentence "The same tokens in both hosts holds..." is back in the Size.Tokens paragraph, before the deferral paragraph. The deferral paragraph now ends at "hold (spec R56).".
  • Reviewer 2, finding 4 (issue_cases.md): fixed. Section 9g lists all three cases and the two unit-test situations. I checked each row against the case it names. The 5m row matches the JSON. The 1h row matches: r1 is 21 minutes after r0 and hot under a 1h entry; r2 is 79 minutes after r1, past the 1h TTL, cold. The loaded-later row matches: a 750-token cost, written, with its own ChangeID.
  • My non-blocking 2 ("not trusted"): fixed. Same change as reviewer 2, finding 1.
  • My non-blocking 3 (no test for the load-later path): fixed. Commit af710ce adds rewrite/tool-defer-stubs/loaded-later/5m and rewrite/tool-defer-stubs/first-hot-cold/1h.
  • Reviewer 2, note (R56 before R55): declined by the author. The reason is right. The list was not in numeric order before this PR (R53 sits before R52). I accept.

The new cases, checked by hand

  • 1h case. r0 writes 1,230 at the 1h tier. r1, 21 minutes later, reads 1,230 (a 5m entry would be dead, a 1h entry is not). r2, 79 minutes after r1, is cold: it writes 1,230 at the 1h tier, with one break, the expired entry, in the baseline. Usage and baseline figures match the token sums (1,270 / 1,520 billed, 2,500 / 2,750 client).
  • Loaded-later case. The load op grows messages[2] from 250 to 1,000 tokens, SizeBefore - SizeAfter = -750. The messages section difference is 750 - 1,500 = -750, so the sum check holds. r2 books the load as a cost of 750 written (R33) and keeps the deferral saving of 1,230 read. The bill difference is 3,000 - 2,520 = 480 = 1,230 - 750, so the conservation check holds.

Non-blocking

  • The author's question on testing.md §10.3. My answer: no change needed. List B names behavior categories, not files. Item 29 names mincacheable_test.go because that behavior is not a generated dimension. The deferral unit tests fall under item 5 (each CheckFailure, the wire-body case) and the replay items (no ChangeID, no repeat). The generated cases are catalogued in issue_cases.md 9g. The list stays exhaustive without a new item.
  • test/gen/gen_cases.py:3475 — the load op reuses the operator name tool-defer. The defer op and the load op are two different changes, but both carry Operator: "tool-defer". The ChangeIDs differ, so nothing in the engine or the checks is wrong. A name such as tool-load would read better in the fixtures. A note only.

What I checked

  • Last review: round 1, c6e9acd, 2026-11-10T05:26:08Z.
  • New commits read: 2 (af710ce test: Add the 1h and loaded-later cases for a defer_loading deferral; 589505a docs: Fix the round 1 findings on the defer_loading rule).
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three saved files).
  • New items since my last review: reviewer 2's round 1 review (read in full, each finding checked myself against the code); the author's reply comment (each reply checked, both declined notes evaluated); commits af710ce and 589505a (full diff and the changed files read around each change).
  • gofmt -l . prints nothing. go vet ./... clean. go test ./... passes all packages.
  • Regenerated the cases in a temp copy of the tree at 589505a: go generate ./test/cases produces the committed JSON byte for byte, for all three #60 cases.
  • Verified the spec and design wording against the engine: the sum failure names the section (compute.go:1858-1860), and pricing continues (§6.5).
  • No engine or accountant.go change in either commit, so no API or R3 concern.

@boazdavid
boazdavid merged commit 61b8b9b into main Nov 10, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant