Skip to content

The view starts by the caller's token oracle: a start keeps its grant as the final prompt prices it - #5819

Merged
joelteply merged 5 commits into
canaryfrom
fable/view-start-token-oracle
Nov 7, 2026
Merged

joelteply merged 5 commits into
canaryfrom
fable/view-start-token-oracle

Conversation

@joelteply

@joelteply joelteply commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

How this serves the minds: when her view starts a new epoch, it now stays within its token grant. The final fit no longer has to cut what she was just shown. Plan line 2 (a mind's context as an epoch), goal 7 (one budget).

Stacked on #5814 (fable/every-claim-collapses). The merge gate holds this PR until #5814 lands.

The defect (Codex, reproduced on Windows)

View::start → start_grants turned each source's TOKEN grant into characters, using the source's AVERAGE tokens per character (share * full_chars / requested_max). Long old turns cost few tokens per character and short new ones cost many. So the average bought enough characters for several new turns whose own cost was over the grant (100 tokens against a 32-token grant on his base).

The fix: the view decides with the caller's own cost function

  • continuum-context::cost::Cost<T> is the caller's price of a block (block, plus stored for a body evicted from RAM). Chars serves callers whose grants are in characters. cost::whole is now the only place an item's whole price is computed; source::whole_chars is deleted.
  • These all take the cost and price by it: View::start, turn_over, start_would_restore, readmit, view::claims, view::floor, the allotment (allot, fold_of) and depth::collapsible.
  • Claim sizes (floor, full, newest, logged), depth::Collapsible (whole, saves) and depth::Growing (base, logged) are all in that cost's units now. Growing::per_char is gone.
  • The start order (Motion) is still measured in characters.
  • Cognition's cost function is ViewCost(calibration): each block costs calibration.charge(message_cost(..)), the same function the final prompt is charged with.
    • Charging block by block overestimates by less than one token per block, never under.
    • view_claims builds the plan's claims with the same cost function through view::claims. Its own floor and whole pricing is removed, and view.rs no longer charges the claims a second time.
    • start_grants returns token shares: the share itself, or the claim's full cost when the source was granted everything it asked for.
    • It takes one act's growth in tokens from fit_view's next_act_tokens, and reads Claim::newest directly.
    • admit_view passes its token budget straight to readmit.
  • No leaf trimming, no retry loop, no new constants. The calibration belongs to the cost function; it is not a second conversion.

Character conversions removed:

  • start_grants' grant mapping, its newest_of, and its wanted_tokens / wanted_chars ratio
  • depth's per_char (growing(share, requested_max / full_chars))
  • admit_view's budget * view.chars() / view_tokens limit
  • view_claims' price-raw-then-charge path
  • the fold decision made in characters

Tests

  • Codex's regression a_view_start_keeps_its_token_grant_with_uneven_message_sizes: cherry-picked byte for byte as the first commit (c0cc361, from 9f1b18c). It passes on this base both before and after the fix.
  • a_view_start_keeps_its_token_grant_when_her_newest_turns_are_denser: the same defect on this base.
    • The estimate counts bytes, so CJK newest turns cost three times as many tokens per character as ASCII old turns.
    • Red before the fix: 36 tokens in 3 messages against a 32-token grant. Green after.
  • a_view_start_with_uniform_message_sizes_keeps_what_it_kept: with uniform sizes the start keeps its 5 newest turns, before and after.
  • a_measured_depth_never_starts_her_under_her_newest_item: the fixture is rewritten in tokens. The rounding gap it guarded came from the removed per-char conversion; its invariant still holds.

Second commit (b9ccbd0): the template's share, measured per kind (card 484d0c47)

#5814 was right to remove PER_MESSAGE_TEMPLATE_TOKENS: it was a constant. But it measured nothing in its place, so an "ok" turn now costs 0 tokens. A start priced on text alone keeps twenty of them against a 32-token grant, which is Codex's 100 > 32.

Engine side (llama_server/template_overhead.rs):

  • The serving lane's template is measured once per engine process and model, inside the reconcile that already reads the lane's build.
  • Probe messages for each kind of message: system, user, assistant, a native tool result, and a native tool call with 0 to 3 parameters. Each probe sits in the middle of a conversation, is rendered by /apply-template in the same wire format real requests use, and is counted by /tokenize. These are HTTP-thread calls: no slot, no decode.
  • A difference between two renders is not a universal per-message cost (BPE joins, role, tool markup and the generation suffix all move it). So the engine publishes the raw observations: each probe message and the tokens it added.
  • MessageShape is now the only place a message is classified: its kind, how many calls or results it carries, and how many parameters.
  • TemplateMeasurement::Unmeasured is a type, not a number. It reaches the caller through AIProviderAdapter::template_overhead.

Cognition side (prompt/template.rs):

  • TemplateEstimate works out each kind's share as the highest amount the engine was observed adding beyond her own text estimate. For tool calls it is a line over the parameter count, the one that sits on or above every observation while overcharging least.
  • That makes the estimate err high on every observation, and the spread (highest minus lowest) is stated.
  • PromptCalibration carries it, and estimate(message) adds it to the text estimate. estimated_prompt_tokens includes it, so the measured density calibrates only the remainder.
  • Unmeasured means the estimate is text alone and the density absorbs the template, as before. The delib.prompt.density probe reports which case applied.

The view's cost function is renamed for what it is: AllocationEstimate in cognition, implementing the continuum_context::cost::Estimate trait (formerly Cost). Its docs say it decides what the view keeps, errs high, and claims no exact token count or token prefix. Dispatch does not go through it; the engine's exact quote of the finalized body is still the authority there.

Measured on the M5 engine (Qwen3.6-35B-A3B-Q4_K_M, build b11017-444f386cf, 2026-11-07T11:38Z, via /apply-template + /tokenize; recorded as the fixture template::recorded_qwen36):

Tokens each probe added to the conversation:

Probe Tokens added
Plain turns (system, user, assistant; identical for all three roles) 6 / 12 / 10 / 7 / 11
Tool results 10 / 16 / 14 / 11 / 15
Tool calls with 0 / 1 / 2 / 3 parameters 17 / 31 / 43 / 57

Per-kind share beyond her text estimate:

Kind Highest (charged) Lowest Spread
System, user, assistant 9 1 8
Tool result 13 5 8
Tool call 17 base, plus 8 per parameter 14 base 3

Error bound, tested (the_allocation_estimate_errs_high_on_the_recorded_engine):

  • Every probe is estimated at or above the engine's count for it.
  • A six-message conversation mixing roles (system, user, a native call, its result, assistant, a CJK user turn): the engine counts it at 97 tokens, or 92 without the 5-token generation suffix. The estimate is 118.

Red/green for the template:

  • Codex's regression is unchanged except for the View::start cost argument the new API requires. It stays green before and after, because its "ok" turns are priced by message_cost, which counts text only.
  • a_view_start_keeps_its_token_grant_with_the_measured_template_overhead runs on his conversation:
    • Priced by text alone, the start keeps 20 "ok" turns. The recorded engine counts those at 120 tokens (6 each), against a 32-token grant.
    • Priced by the allocation estimate, it stays within every grant from 32 to 512, and the recorded engine count stays under the estimate.

Third commit (2654bad): one price for a message (card 484d0c47)

The view's start, the final fit (fit_messages) and the retry after an engine refusal (refit_rejected_prompt) now all price a message through PromptCalibration::estimate / estimate_all. Before, the start used the allocation estimate while the fit and the retry used text-only messages_cost: two pricing paths for one fact.

  • PromptMessages and DeliberationPromptView carry the pricing they were estimated with.
  • Every prompt-assembly reader goes through it: required parts, history tokens, her last-move evidence, each fitted message, the newest result's levels, the view build, fit_view and the budget ledger.
  • LlmDeliberationFaculty::messages_cost is removed: no production caller was left. Tests now use PromptCalibration::default().estimate_all, which gives the same number when the template is unmeasured.
  • message_cost stays, as the text-only part that estimate builds on.
  • Codex's regression changes one more call because of the removal (messages_cost(&rendered) becomes PromptCalibration::default().estimate_all(&rendered), same number). It stays green.
  • New test: the_final_fit_and_a_view_start_price_a_multi_role_sequence_identically. On a user turn, a native call, its result, an assistant turn and a CJK user turn, at the recorded engine's template, the view's start and the final fit's receipt give the same number, and a budget of exactly that number keeps the whole sequence.
  • Dispatch still rests on the engine's exact quote of the finalized body.

Measured

Run on the M5 (local, nice 19, own target dir), commit 2654bad (re-run after the third commit), 2026-11-07:

  • cargo test -p continuum-context (lib + replay example): 98 + 21 passed. Same counts as the base; no tests added or removed in this crate.
  • cargo test -p continuum-cognition --lib --features test-fixtures,metal: 970 passed, 0 failed, 1 ignored. That includes the 3 tests above, the two template tests and the same-price test.
  • cargo test -p continuum-engine --lib -- llama_server: 96 passed (including the template module test).
  • cargo test -p continuum-core --lib --features test-fixtures,metal -- deliberation (includes every_claim_collapses): 18 passed, 1 failed.
    • The failure is pinned_act_result_reaches_the_prompt_even_with_an_empty_broadcast (panics at custody.handle().expect("saved inventory")).
    • It fails the same way on the base, with this change stashed. It does not depend on this change.
  • Red run before the fix: on cc9c95c plus the new tests, the CJK test failed with "the start rendered 36 tokens in 3 messages against a 32-token grant".
  • Source hygiene against cc9c95c (Every budgeted part collapses by its levels instead of refusing: hands, framing, grounding as consumers in one searched allocation #5814 head), from the repo root:
    • tools/scripts/oversized-edits.sh: exit 0
    • ratchets: exit 0, every count at or below the base
  • cargo clippy -p continuum-context --all-targets: no warnings in the crate.
  • Not yet measured live: whether the M5 residents' turnovers stop being cut at the final fit. To check after Every budgeted part collapses by its levels instead of refusing: hands, framing, grounding as consumers in one searched allocation #5814 and this land: delib.view.sized against delib.prompt fit receipts over a 15-minute read.

Rebased onto canary 7b7d277 (2026-11-07), head bf0e87c

#5814 merged as e5f57d9, so this branch now holds only its own four commits plus one rebase commit.

Conflicts, resolved in favor of canary's newer behavior:

Rebase commit bf0e87c: canary's new tests were written against the character-based API (view/tests/shed.rs from #5815, context_streams/blocks.rs from #5827). They now pass the cost and read Claim::full.

Measured on the M5 (local, nice 19, own target dir, serving untouched) at bf0e87c:

  • cargo test -p continuum-context --lib --examples: 103 + 21 passed.
  • cargo test -p continuum-cognition --lib --features test-fixtures,metal: 973 passed, 0 failed, 1 ignored.
  • cargo test -p continuum-engine --lib --features test-fixtures,metal -- llama_server: 101 passed.
  • cargo test -p continuum-core --lib --features test-fixtures,metal -- deliberation: 19 passed, 0 failed. The earlier pinned_act_result... failure is fixed on canary by The pinned-act prompt test installs its own writer fixture (card 4f57ad95) #5825.
  • ratchets origin/canary: exit 0, every count unchanged.
  • oversized-edits.sh origin/canary: clean.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

@joelteply
joelteply force-pushed the fable/view-start-token-oracle branch from 2654bad to cb3b9a1 Compare November 7, 2026 14:19
Base automatically changed from fable/every-claim-collapses to canary November 7, 2026 14:36
joelteply and others added 5 commits November 7, 2026 11:15
… as the final prompt prices it

Codex's defect: View::start converted a source's TOKEN grant into characters at the source's
AVERAGE tokens per character (start_grants: share * full_chars / requested_max), so a source of
cheap long old turns and dear short new ones bought characters enough for new turns whose own
cost overran the grant.

continuum-context::cost::Cost<T> is the caller's price of a block (block, stored), with Chars for
callers whose grants are characters and cost::whole as the one owner of an item's whole price
(source::whole_chars deleted). View::start / turn_over / start_would_restore / readmit, view::claims,
view::floor, the allotment (allot, fold_of) and depth::collapsible all price by it; Claim's sizes
(floor, full, newest, logged), depth's Collapsible (whole, saves) and Growing (base, logged) are in
the oracle's unit, and Growing::per_char is gone. Motion's order stays in characters.

Cognition's oracle is ViewCost(calibration): each block at calibration.charge(message_cost), the
function the final prompt is charged with (charged per block it errs high by under a token a block,
never low). view_claims prices the plan's claims by the same oracle through view::claims (its own
floor/whole pricing removed, view.rs no longer re-charges them); start_grants hands back token
shares (the share itself, or the claim's full when granted all), takes one act's growth in tokens
from fit_view's next_act_tokens, and reads Claim::newest directly; admit_view hands readmit its
token budget.

Removed char conversions: start_grants' grant mapping and its newest_of and wanted_tokens/
wanted_chars ratio; depth's per_char (claims[i].growing(share, requested_max / full_chars));
admit_view's budget * view.chars() / view_tokens limit; view_claims' raw-then-charge path;
the fold decision in chars (fold_of now decides in the oracle the view allots by).

Tests: Codex's regression (previous commit) passes on this base before and after: #5814 removed
the per-message template tokens, so his short "ok" turns cost nothing here.
a_view_start_keeps_its_token_grant_when_her_newest_turns_are_denser is the same defect on this
base (CJK newest turns: a byte-counted estimate makes them three times as dense per char): red
before (36 tokens in 3 messages against 32), green after. a_view_start_with_uniform_message_sizes_
keeps_what_it_kept: five newest turns before and after.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…er allocation estimate

#5814 removed PER_MESSAGE_TEMPLATE_TOKENS (no constant) but nothing measured in its place, so an
"ok" turn cost 0 and a start priced by text alone kept twenty of them against a 32-token grant
(Codex's 100 > 32).

Engine (llama_server/template_overhead.rs): the serving lane's template is measured once per engine
process and model, from the reconcile that already reads its build (observe_template beside
observe_served_engine). Probe messages per kind (system, user, assistant, native tool result, native
tool call with 0-3 parameters) are rendered in the middle of a conversation through /apply-template
on the request wire (request_body::wire_messages) and counted by /tokenize (HTTP-thread calls, no
slot, no decode); each records the tokens it added. MessageShape is the one owner of how a message is
classified (kind, calls or results, parameters). TemplateMeasurement::Unmeasured is a type; the
adapter seam reports it (AIProviderAdapter::template_overhead, OpenAI adapter for the serving lane,
the placement switch forwards). Probe: serving.template_overhead.

Cognition (prompt/template.rs): TemplateEstimate derives each kind's share against her own text
estimate (message_cost) at its HIGHEST observation, a call's as the least-overcharging line over its
parameters on or above every observation, so the estimate errs high on every observation and states
its spread. PromptCalibration carries it (fit_within, from the adapter); estimate(message) =
message_cost + its kind's share (unmeasured: text alone, density carries the template, probed on
delib.prompt.density); estimated_prompt_tokens counts it, so density calibrates the rest.

The view's oracle is renamed for what it is: AllocationEstimate (cognition) over
continuum_context::cost::Estimate (the trait, was Cost). Its docs say it decides what to keep, errs
high, claims no exact count or token prefix; dispatch still rests on the engine's exact quote.

Measured on the M5 engine (Qwen3.6-35B-A3B-Q4_K_M, build b11017-444f386cf, 2026-11-07T11:38Z),
tokens each probe added: plain turns 6/12/10/7/11 for every role, tool results 10/16/14/11/15,
calls 17/31/43/57 (0/1/2/3 parameters). Beyond her text estimate: system/user/assistant highest 9,
lowest 1 (spread 8); tool result 13, lowest 5 (spread 8); call line 17 + 8 per parameter
(base lowest 14, spread 3).

Tests: Codex's regression stays byte-identical but for the View::start cost argument, and stays
green (its "ok" turns are priced by message_cost, which counts text). The template's red/green is
a_view_start_keeps_its_token_grant_with_the_measured_template_overhead on his conversation: priced
by text alone the start keeps 20 "ok" turns, 120 tokens as the recorded engine counts them (6 each)
against 32; priced by the allocation estimate it keeps within every grant 32..512, and the recorded
engine count is under the estimate. the_allocation_estimate_errs_high_on_the_recorded_engine: every
probe is estimated at or above the engine's count, and a six-message multi-role conversation counted
at 97 (92 without the 5-token generation suffix) is estimated at 118.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…l's refit all estimate through PromptCalibration::estimate

The view's start priced each block by her allocation estimate (text plus the measured template
share) while the final fit and a refusal's refit priced text alone (LlmDeliberationFaculty::
messages_cost): two pricing paths for one fact. Now PromptCalibration::estimate / estimate_all is
the one owner, and every prompt-assembly reader goes through it:

- PromptMessages carries its pricing (set by its one builder from the faculty's binding, and by
  the act's view build to that act's calibration); required_parts, tokens, recent_move_evidence,
  fit_messages (each message and the quiet-tick minimum) and the newest result's levels price with it.
- DeliberationPromptView carries the pricing its messages were estimated with; refit_rejected_prompt
  reprices and rebuilds with it.
- The view build (view tokens, the quiet minimum, the tail budget, the sent sample, the assembled
  context's used tokens), fit_view (view and admitted tokens) and the budget ledger
  (estimate_system for the system message) price through it.

Removed: LlmDeliberationFaculty::messages_cost (no production caller left; tests use
PromptCalibration::default().estimate_all, numerically the same text-only estimate when unmeasured).
message_cost stays as the text part estimate builds on, documented as never a price by itself.
PromptCalibration derives Debug (the view snapshot carries it).

Codex's regression changes one more call for the removal: messages_cost(&rendered) ->
PromptCalibration::default().estimate_all(&rendered) (same number; his test stays green).

Test: the_final_fit_and_a_view_start_price_a_multi_role_sequence_identically: a user turn, a native
call, its result, an assistant turn and a CJK user turn, priced at the recorded engine's template:
the view's start (AllocationEstimate per block) and the final fit (its receipt's history_tokens)
give the same number, and a budget of that number keeps all of it.

The engine's exact quote of the finalized body before generation stays the authority for dispatch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…board tests start and turn over at a cost

Rebasing onto canary (7b7d277) brought tests written against the
character-unit view API (#5815 shed, #5827 collapsed navigation). They
now pass the cost the API requires and read Claim::full. The rebase's
conflict in context_streams/tests.rs had dropped this branch's own
updates to that file; they are re-applied, minus the tally test #5827
moved into blocks.rs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
@joelteply
joelteply force-pushed the fable/view-start-token-oracle branch from cb3b9a1 to bf0e87c Compare November 7, 2026 17:36
@joelteply
joelteply merged commit db7f38f into canary Nov 7, 2026
33 checks passed
@joelteply
joelteply deleted the fable/view-start-token-oracle branch November 7, 2026 18:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant