29. The context window as a budget
Why this layer exists
The loop of chapter 26 resends the whole history every turn, and chapter 26 derived what that costs in tokens reported: (cited, not re-derived; is the turn’s prompt_tokens and the history’s growth). Two things bound that number from outside the loop. One is the slot’s context size, which a request must fit with room left for the answer. The other is the provider’s bill, which counts every reported token. The loop controls neither the window nor the price. It controls the growth per turn and the stability of the prefix, and this chapter is the accounting that makes both controllable: an estimate of the next prompt before it is sent, a measure of how much of it a server can reuse, and the budget decision. Chapter 31 is what to do when the decision is “does not fit”.
The numbers come from three places that already exist. llm.Usage is what the client reports (Part IV’s carry-forward); the model_call span carries the same numbers into the trace; and Usage.Cached, new in this chapter, carries prompt_tokens_details.cached_tokens where a provider sends it. The Anthropic adapter leaves Cached at 0 on purpose: its cache_read_input_tokens is a sibling of input_tokens, not a share of it (chapter 24), and putting a sibling in a field documented as a share would make Evaluated, the prompt less its cached part, wrong.
Mechanism
The figure below is the whole chapter in three bars. A window of tokens holds the prompt and everything the model will generate; the prompt is split into the part a server found in its cache and the part it had to evaluate; a reserve is held back for the completion; whatever is left is headroom.
The budget identity
A slot of tokens holds the prompt and what it generates. llama-server reports prompt_n + cache_n + predicted_n as the context in use (README, “Timings and context usage”, line 1421 at b29c606) and sets truncated when the prompt’s tokens plus the generated ones exceed (line 674). A request therefore fits when
with the completion the loop will allow. A Reserve of or more leaves no room for any prompt; that is a configuration error (ErrWindow), not a request that fails to fit. The reserve is a promise, and the budget checks only its own side of it: a loop that checks a reserve of 1,024 and sends no max_tokens has promised nothing, and cmd/aec is such a loop (its -reserve feeds the check, and the request carries no max_tokens). A harness that means its reserve sends it as max_tokens.
Where comes from is not a settled number on a llama.cpp router. GET /v1/models lists each child’s --ctx-size in status.args (131072 for dixie’s 9b). GET /props without a model answers for the router process, not a child. GET /slots?model=ornith-1.5-9b-uncensored&autoload=false on dixie, on 2026-10-03 with the 9b loaded, listed eight slots, ids 0 to 7, each with n_ctx 131072 and none processing: the eight slots sit over one unified KV cache of 131072 cells, not eight caches of 16384 (131072 divided by 8). So no slot has a window of its own. How much one request can use depends on what the other seven are holding, and the server’s number does not answer the question the budget asks.
The loop therefore takes as configuration, and -window 16384 in the captures below is that fair share, 131072/8, the window a harness can keep to if every slot keeps to its own share. It is a policy the budget manager can hold itself to, not a limit the server enforces and not a guarantee about other clients of the same cache: the same request, with the other slots idle, would fit in a window eight times larger. That is why Window.Size is configuration and not a probe.
Where the estimate comes from
Before a request is sent the manager wants its prompt tokens. There are three sources, in decreasing order of trust.
Reported plus delta. By the definition of , , and was reported by the provider, so the best estimate of the next prompt is the last report plus an estimate of what was appended since: reported+delta. Whatever the counter gets wrong about the fixed part of the request (the template’s own framing, the tool list rendered as prose) is already inside the reported and cancels; only the appended messages are estimated. The source fails when the history behind the report was rewritten (a compaction, chapter 31), which the manager detects by the message count: a request shorter than the one reported cannot extend it, and the manager falls back to counting the whole request.
Counted. When the counter is a server’s own tokeniser (Tokenizer: POST /apply-template renders the messages through the model’s chat template, POST /tokenize counts the result), the whole-request count is reported as counted. The README documents only messages for /apply-template (line 728 onward), but the handler reads tools as well, so the tool definitions go in the same body and the template renders its own tool block; the Walkthrough measures the difference.
Estimated. Otherwise the counter is Ratio. A prompt of characters in framed units (messages plus tool definitions) costs about
with tokens per character and tokens of framing per unit. Given reports for , least squares minimises
is a convex quadratic in , so its minimum is where both partial derivatives vanish:
Expanding and moving the unknowns to the left gives the normal equations, a 2 by 2 system :
With , Cramer’s rule gives
Every sum is a scalar over the observations, so the estimator keeps five running sums and refits in constant time. needs two observations of different shape (different ratios ); with observations that all share a shape, and only the combination is identified, so the fit keeps the ratio through the origin, ; with a single observation Observe holds Overhead and fits alone. A fit that would make or negative is also discarded for that fallback. Worked once, with the two observations and :
So and (the sums come from a script, and TestRatioRefit checks the same pair). Before any report the defaults are 4 and 4.
Prefix-cache economics
On a server with a warm slot, the compute of turn is the suffix. llama-server reports , and cached_tokens on the OpenAI wire is the same number as cache_n (chapter 26 saw them agree). If the rendered prefix is stable, the slot’s cache holds the previous prompt and the server reuses it up to the point where the new rendering diverges from what is cached. Chapter 26 measured the divergence as a constant 4 tokens: with the template’s framing at the join (the generation prefix, and whatever the template renders differently for a stored assistant turn, such as a dropped reasoning block, since SendReasoning is off),
Summing the work over turns, with the first turn’s cache_n (0 on a cold slot):
The sum telescopes: , and the cancels. is linear in where is quadratic. The two compare like with like, since both count prompt positions and neither counts the completions. Check against chapter 26’s live run (prompts 382, 435, 490; prompt_n 382, 57, 59): .
If the divergence varies by turn, the same telescoping gives . A change that breaks the prefix costs the evaluation of everything after the break once, on the turn that sends it. The next turn’s slot holds the new prompt, and the line resumes. would need every turn to break.
StablePrefix predicts a break from the requests alone. It compares two consecutive requests field by field in the order the wire renders them (the model, the tools, tool_choice and the Extra keys such as reasoning_effort that a template can read, then the messages in order) and names the first difference; a change in any request-level field is reported as a break, since missing one is the unsafe direction. It compares the bytes the encoder sends, not the structs: parts the OpenAI encoder drops (thinking, redacted_thinking, tool_use) are skipped, and a message’s reasoning text counts only when the provider sends it back (SendReasoning). It reads wire bytes, and a server reads tokens: two measurements below show a byte difference that costs nothing, and a shared prefix that a server did not use.
A worked projection, with , and over 20 turns: and , which is 8.3% (exercise (c) varies it).
The hosted providers do the same thing with different rules, and the behaviours are quoted rather than priced. OpenAI: “Cache reuse requires the entire rendered prefix to match”; cached_tokens is rounded down to a multiple of 128; the minimum cacheable prompt is 1,024 tokens for GPT-5.6 and later and varies by request settings for earlier models. Anthropic: “Cache prefixes are created in the following order: tools, system, then messages”, and the read is reported as cache_read_input_tokens, a sibling of input_tokens. z.ai: implicit caching (“Automatic Cache Recognition”), with no minimum length and no lifetime stated beyond “reasonable time limits”. What none of these pages, and nothing a client can see, shows is which slot or replica answered, or whether another client evicted the prefix in between; llama-server sends a request to the slot whose cached prompt matches best (--slot-prompt-similarity, default 0.10; chapter 19).
Reasoning as a line in the budget
llm.Usage.Reasoning (chapter 24: completion_tokens_details.reasoning_tokens on the OpenAI wire, output_tokens_details.thinking_tokens on Anthropic’s) is a share of the completion. It is paid inside Reserve, and in latency on the turn it happens. Part IV’s client keeps the text beside the message (Message.Reasoning, and the Anthropic adapter’s signed thinking parts) and the OpenAI-wire client sends the text back only when SendReasoning is set. The Anthropic adapter has no such option: it always replays its signed thinking blocks verbatim, as that API requires. On the OpenAI wire the reasoning is usually dropped from the history on the next turn, so does not carry it: chapter 26’s 88 and 112 completion tokens both left a growth of 53.
The identity therefore reads with . Anthropic says so outright: “Thinking tokens count toward the max_tokens limit for the turn, so the budget must leave room for the final response”. OpenAI: reasoning tokens “are not visible via the API, they still occupy space in the model’s context window and are billed as output tokens”.
“Effort” means a different thing on each provider, quoted from its page. llama-server’s --reasoning-budget N is a token budget enforced by the sampler: when it is spent, the sampler forces the template’s end-of-thinking sequence (common/arg.cpp:3707-3713 defines the flag, common/reasoning-budget.cpp:117-130 is the exhaustion and :174-188 the forcing of the logits to the forced token). Dixie’s 9b runs with 2048. A request can override it with reasoning_budget_tokens in the body (tools/server/server-common.cpp:1388-1398; -1 falls back to the server’s value). reasoning_effort is handed to the template, and none disables thinking (README, line 1320); chat_template_kwargs can carry enable_thinking; and reasoning_control lets a client end a reasoning block mid-stream through POST /v1/chat/completions/control with action: reasoning_end (README, 1324 and 1445-1458; the handler calls the same forcing at tools/server/server-context.cpp:2488). Anthropic’s thinking: {type: "enabled", budget_tokens: N} (its page now calls this manual mode and points newer models to adaptive thinking) is a target with a 1,024-token minimum that must stay below max_tokens, and changing it between requests “invalidates cache breakpoints”, which is this chapter’s prefix argument again. OpenAI’s reasoning.effort is a level (none, minimal, low, medium, high, xhigh, max, depending on the model). z.ai’s thinking.type is enabled or disabled, and “GLM-5.3 and GLM-5.3-FLASH no longer support disabling thinking”; GLM-5.3-FLASH is the model in the book’s routes.json. Chapter 38 makes effort an axis of its model-selection matrix. Here it is one more line the loop must reserve for, measured below on the one knob the fleet exposes.
What a rewrite costs
Compaction (chapter 31) rewrites message onward. The next turn’s cache holds the untouched head , the server evaluates once, and every turn after that is back on the linear line with a smaller . With before, after and : 1,100 tokens evaluated once, against 2,500 fewer reported on every later turn. The budget treats a compaction as a one-turn cost, which is why Compactor waits until the request does not fit rather than trimming every turn, and why Hermes’s proactive prune requires “a full regrowth runway” (agent/context_compressor.py at bed0d53, lines 3350-3365; chapter 31). The measurement below shows that can be 0.
Walkthrough
The package is internal/budget; it imports the standard library and internal/llm only. Window is configuration, Usage is the provider’s report, and Evaluated is the prompt less its cached share, which on llama-server equals timings.prompt_n when cached_tokens equals cache_n. FromLLM records a Cached outside as 0: a faulty provider cannot make the prefix look better than the prompt it was part of.
// Window is one model's context in tokens and what the loop keeps back.
// Size is the window the budget keeps to. It comes from configuration, never
// from a server probe: GET /props without a model answers for the router
// process only (Part IV Facts), /v1/models lists a child's --ctx-size, and
// GET /slots reports the same n_ctx for every slot of a unified KV cache, so
// no server number says how much of the cache this client may use.
type Window struct {
Size int // the window the budget keeps to (a policy; the server's n_ctx may be larger)
Reserve int // tokens held back for the completion (the max_tokens the loop will ask for)
}
// Usage is one turn's accounting as the provider reported it. Cached is
// prompt_tokens_details.cached_tokens when the provider sends it (llama-server
// at b29c606, z.ai, OpenAI), else 0; Prompt includes the cached share.
type Usage struct {
Prompt int
Completion int
Reasoning int
Cached int
}
// FromLLM copies the client's report. A Cached outside [0, Prompt] is not a
// share of the prompt and is not trusted: it is recorded as 0, so a faulty
// provider cannot make the prefix look better than the prompt it was part
// of.
func FromLLM(u *llm.Usage) Usage {
if u == nil {
return Usage{}
}
out := Usage{Prompt: u.Prompt, Completion: u.Completion, Reasoning: u.Reasoning, Cached: u.Cached}
if out.Cached < 0 || out.Cached > out.Prompt {
out.Cached = 0
}
return out
}
// Evaluated is the prompt work the server did for this turn: Prompt less the
// cached share. On llama-server it is timings.prompt_n when cached_tokens
// equals cache_n (chapter 26's live run).
func (u Usage) Evaluated() int { return u.Prompt - u.Cached }
Counter is the one method the manager needs of an estimator. Exact is a marker for the one whose answer is a server’s own.
// Counter estimates the prompt tokens of a request before it is sent.
type Counter interface {
Count(ctx context.Context, msgs []llm.Message, tools []llm.Tool) (int, error)
}
// Exact is implemented by a Counter whose count is the server's own
// tokenisation (Tokenizer). A Manager reports such a count as "counted";
// any other Counter's as "estimated".
type Exact interface{ Exact() bool }
Manager.Check is the three sources in code. The first case is reported+delta, taken when the previous report describes a prefix of the request; the default counts or estimates the whole request, and reports counted only if the counter says it is exact. Observe records the usage the provider reported, with the number of messages that call sent; Reset forgets it after a rewrite. The comment in the first case is a limit on the design: the appended tail is counted on its own, so the counter there must be an estimator, because a tokeniser would render the tail as a standalone conversation with its own preamble.
// Manager decides before a model call whether the request fits the window.
// Its best source is the previous turn's reported prompt_tokens plus an
// estimate of what was appended since ("reported+delta"); without a previous
// turn, or after the history was rewritten, it counts or estimates the whole
// request.
type Manager struct {
Window Window
Counter Counter // nil: a Ratio with the defaults, created on first use and kept, so a Client can refit it
Last Usage // the previous turn as reported; zero before the first call
lastLen int // messages in the request Last was reported for
}
// Report is one check.
type Report struct {
Estimated int // prompt tokens the request is expected to cost
Window int // Window.Size
Reserve int // Window.Reserve
Headroom int // Window - Reserve - Estimated; negative means it does not fit
Fits bool // Headroom >= 0
Source string // reported+delta | counted | estimated
}
// Sources of a Report.
const (
SourceReportedDelta = "reported+delta"
SourceCounted = "counted"
SourceEstimated = "estimated"
)
func (m *Manager) counter() Counter {
if m.Counter != nil {
return m.Counter
}
m.Counter = &Ratio{CharsPerToken: DefaultCharsPerToken, Overhead: DefaultOverhead}
return m.Counter
}
// Check estimates msgs and tools against the window. With a previous turn
// whose request is a prefix of msgs (nothing before lastLen was rewritten,
// which the caller guarantees by calling Observe after every call and
// Compact between), the estimate is the reported prompt plus the Counter's
// count of the appended messages; otherwise the Counter counts everything.
func (m *Manager) Check(ctx context.Context, msgs []llm.Message, tools []llm.Tool) (Report, error) {
rep := Report{Window: m.Window.Size, Reserve: m.Window.Reserve}
if err := m.Window.Valid(); err != nil {
rep.Headroom = m.Window.Size - m.Window.Reserve
return rep, err
}
c := m.counter()
switch {
case m.Last.Prompt > 0 && m.lastLen > 0 && len(msgs) >= m.lastLen:
// The appended tail is counted on its own, so c must be an
// estimator (Ratio). An Exact counter (Tokenizer) would render the
// tail as a standalone conversation, with its own preamble, and a
// template may reject it: do not pair one with this path until a
// caller needs it (none in Part V).
delta, err := c.Count(ctx, msgs[m.lastLen:], nil)
if err != nil {
return rep, err
}
rep.Estimated = m.Last.Prompt + delta
rep.Source = SourceReportedDelta
default:
n, err := c.Count(ctx, msgs, tools)
if err != nil {
return rep, err
}
rep.Estimated = n
rep.Source = SourceEstimated
if e, ok := c.(Exact); ok && e.Exact() {
rep.Source = SourceCounted
}
}
rep.Headroom = m.Window.Size - m.Window.Reserve - rep.Estimated
rep.Fits = rep.Headroom >= 0
return rep, nil
}
// Observe records the usage the provider reported for the call that
// followed Check, and the number of messages that call sent, so the next
// Check starts from a measured number.
func (m *Manager) Observe(u llm.Usage, msgs int) {
m.Last = FromLLM(&u)
m.lastLen = msgs
}
// Reset forgets the previous turn: after a compaction rewrote the history,
// the reported prompt no longer describes a prefix of it.
func (m *Manager) Reset() {
m.Last = Usage{}
m.lastLen = 0
}
// Count is the Manager's Counter applied to any messages: what chapter 31's
// compactor uses to size a head, a tail or a candidate history without
// touching Last.
func (m *Manager) Count(ctx context.Context, msgs []llm.Message, tools []llm.Tool) (int, error) {
return m.counter().Count(ctx, msgs, tools)
}
Ratio keeps the five running sums of the derivation and refits on every report. With one observation only the ratio moves; from two on both coefficients are the least-squares solution; a degenerate or negative fit falls back to the ratio through the origin with Overhead 0.
// Ratio is the characters-per-token estimator, refitted from every reported
// prompt_tokens. Overhead is the per-unit framing the template adds (role
// tokens, separators; a unit is one message or one tool definition), fitted
// jointly with the ratio by least squares. It never contacts a server.
type Ratio struct {
CharsPerToken float64 // initial 4.0
Overhead int // per message or tool; initial 4
// Sums for the fit of reported = a·chars + o·units over every
// observation: a is 1/CharsPerToken, o is Overhead.
n int
sxx, sxm, smm, sxy, smy float64
}
// Chars is what a Ratio measures: the bytes of text the wire will carry for
// msgs and tools (text parts, tool-call names and arguments, tool-call ids,
// the JSON of each tool definition), and the number of framed units
// (messages plus tools). Reasoning is not counted: the client does not send
// it back unless asked (chapter 24).
func Chars(msgs []llm.Message, tools []llm.Tool) (chars, units int) {
for _, m := range msgs {
for _, p := range m.Parts {
chars += len(p.Text) + len(p.URL) + len(p.Data)
}
for _, c := range m.ToolCalls {
chars += len(c.ID) + len(c.Name) + len(c.Arguments)
}
chars += len(m.ToolCallID) + len(m.Name)
}
for _, t := range tools {
b, _ := json.Marshal(t)
chars += len(b)
}
return chars, len(msgs) + len(tools)
}
func (r *Ratio) ratio() float64 {
if r.CharsPerToken <= 0 {
return DefaultCharsPerToken
}
return r.CharsPerToken
}
// Count estimates from byte lengths: ceil(chars / CharsPerToken) plus
// Overhead per unit.
func (r *Ratio) Count(ctx context.Context, msgs []llm.Message, tools []llm.Tool) (int, error) {
chars, units := Chars(msgs, tools)
return int(math.Ceil(float64(chars)/r.ratio())) + r.Overhead*units, nil
}
// Observe refits CharsPerToken and Overhead from a request and the
// prompt_tokens the provider reported for it. With one observation only the
// ratio moves (Overhead is kept); from two on, both are the least-squares
// solution of reported ≈ a·chars + o·units; a fit that would make either
// negative keeps Overhead at zero and fits the ratio alone. A reported
// count of zero or fewer is ignored.
func (r *Ratio) Observe(msgs []llm.Message, tools []llm.Tool, reported int) {
if reported <= 0 {
return
}
chars, units := Chars(msgs, tools)
x, m, y := float64(chars), float64(units), float64(reported)
if x <= 0 {
return
}
r.n++
r.sxx += x * x
r.sxm += x * m
r.smm += m * m
r.sxy += x * y
r.smy += m * y
if r.n == 1 {
if a := (y - float64(r.Overhead)*m) / x; a > 0 {
r.CharsPerToken = 1 / a
}
return
}
det := r.sxx*r.smm - r.sxm*r.sxm
if det > 0 {
a := (r.sxy*r.smm - r.smy*r.sxm) / det
o := (r.sxx*r.smy - r.sxm*r.sxy) / det
if a > 0 && o >= 0 {
r.CharsPerToken = 1 / a
r.Overhead = int(math.Round(o))
return
}
}
// Degenerate (every observation has the same chars-to-units shape) or
// a negative coefficient: fit the ratio alone through the origin.
if a := r.sxy / r.sxx; a > 0 {
r.CharsPerToken = 1 / a
r.Overhead = 0
}
}
// Observations is how many reports the fit has seen.
func (r *Ratio) Observations() int { return r.n }
StablePrefix is the prefix report. wireEqual compares what the encoder sends and nothing else: it skips the three part types llm/wire.go drops, and compares Reasoning only for a provider that sends it back, which StablePrefixFor takes as an argument. StablePrefix itself assumes the default, a provider that does not.
// PrefixReport says how much of next a server's prompt cache can reuse from
// prev: the rendered prefix is stable up to the first field that differs,
// in the order the wire renders them (the model, the tools, the request
// fields a template can read, then the messages in order). It compares what the OpenAI encoder sends, not what
// the structs hold: parts the encoder drops are skipped, and a message's
// reasoning counts only when the provider sends it back (SendReasoning).
type PrefixReport struct {
Messages int // leading messages byte-identical on the wire in both requests
ToolsSame bool // the tool definitions did not change
Changed string // what broke the prefix: "" (nothing but the appended tail) | model | tools | tool_choice | extra | message:<i>
}
// StablePrefix compares two consecutive requests of one session. It
// bounds llama-server's timings.cache_n up to the template's framing: with
// Changed empty the server can reuse every token of prev's prompt; with
// Changed set it can reuse at most the tokens before the first differing
// field, which for message:<i> is the rendering of messages 0..i-1 and for
// tools or model is nothing but the template's fixed preamble. A change in
// tool_choice or in any Extra key (reasoning_effort, chat_template_kwargs)
// counts as a break, because a template can render either: it is the unsafe
// direction to miss. It compares the bytes the encoder sends, so whitespace a chat template trims is a
// difference here and none to the server; and how much of the bound a
// server uses is its own business (chapter 29 measures both on dixie).
// StablePrefix assumes the provider's default, which does not send
// reasoning back.
func StablePrefix(prev, next llm.Request) PrefixReport {
return StablePrefixFor(prev, next, false)
}
// StablePrefixFor is StablePrefix for a provider whose SendReasoning is
// sendReasoning: when it is set the encoder puts each message's reasoning
// text on the wire as reasoning_content, so a change there breaks the
// prefix like any other.
func StablePrefixFor(prev, next llm.Request, sendReasoning bool) PrefixReport {
rep := PrefixReport{ToolsSame: sameTools(prev.Tools, next.Tools)}
n := 0
for n < len(prev.Messages) && n < len(next.Messages) && wireEqual(prev.Messages[n], next.Messages[n], sendReasoning) {
n++
}
rep.Messages = n
switch {
case prev.Model != next.Model:
rep.Changed = "model"
case !rep.ToolsSame:
rep.Changed = "tools"
case !sameJSON(prev.ToolChoice, next.ToolChoice):
rep.Changed = "tool_choice"
case !sameJSON(prev.Extra, next.Extra):
rep.Changed = "extra"
case n < len(prev.Messages):
rep.Changed = fmt.Sprintf("message:%d", n)
}
return rep
}
// wireEqual compares the fields the OpenAI encoder renders for a message:
// role, content parts, tool calls, tool_call_id and name, and the reasoning
// text when sendReasoning is set. The parts the encoder drops (thinking,
// redacted_thinking and tool_use, which the Anthropic adapter adds) are
// skipped on both sides, and IsError is not on this wire.
func wireEqual(a, b llm.Message, sendReasoning bool) bool {
pa, pb := wireParts(a.Parts), wireParts(b.Parts)
if a.Role != b.Role || a.ToolCallID != b.ToolCallID || a.Name != b.Name || len(pa) != len(pb) || len(a.ToolCalls) != len(b.ToolCalls) {
return false
}
if sendReasoning && a.Reasoning != b.Reasoning {
return false
}
for i := range pa {
if pa[i].Type != pb[i].Type || pa[i].Text != pb[i].Text || pa[i].URL != pb[i].URL ||
pa[i].Format != pb[i].Format || !bytes.Equal(pa[i].Data, pb[i].Data) {
return false
}
}
for i := range a.ToolCalls {
if a.ToolCalls[i] != b.ToolCalls[i] {
return false
}
}
return true
}
// wireParts keeps the parts the OpenAI encoder sends (llm/wire.go skips the
// other three types).
func wireParts(parts []llm.Part) []llm.Part {
out := make([]llm.Part, 0, len(parts))
for _, p := range parts {
if p.Type != "thinking" && p.Type != "redacted_thinking" && p.Type != "tool_use" {
out = append(out, p)
}
}
return out
}
// sameJSON compares two values by their JSON, with nil and empty alike: a
// nil ToolChoice and a missing Extra are the same request.
func sameJSON[T any](a, b T) bool {
ja, _ := json.Marshal(a)
jb, _ := json.Marshal(b)
return bytes.Equal(emptyJSON(ja), emptyJSON(jb))
}
func emptyJSON(b []byte) []byte {
if s := string(b); s == "null" || s == "{}" {
return nil
}
return b
}
// sameTools compares tool definitions by their JSON; no tools and an empty
// list are the same.
func sameTools(a, b []llm.Tool) bool {
if len(a) == 0 && len(b) == 0 {
return true
}
if len(a) != len(b) {
return false
}
ja, _ := json.Marshal(a)
jb, _ := json.Marshal(b)
return bytes.Equal(ja, jb)
}
Tokenizer is the exact counter, behind the fleet guard: GET /v1/models immediately before each request that names the model, refusal unless status.value is exactly loaded, and ?autoload=false on the request. Its query is built with url.Values, so a model id with + or & cannot add a parameter.
// Tokenizer counts exactly through llama-server's POST /tokenize on the
// server that will answer, after rendering the chat template through POST
// /apply-template, behind the fleet guard: GET /v1/models immediately
// before each request that names the model, refusing unless status.value is
// exactly "loaded", and ?autoload=false on the request. The README documents
// only `messages` for /apply-template, but the handler reads `tools` as well
// (chapter 29 measures it: the same messages render 74 characters without a
// tools array and 1,203 with one), so the tool definitions go in the same
// body and the template renders its own tool block. With tools but no
// messages there is nothing to render, and the tools' JSON is counted alone,
// a floor.
type Tokenizer struct {
BaseURL string // server root, e.g. http://dixie:11434
Model string
HTTP *http.Client // nil: a proxy-free client that refuses redirects
}
var _ Exact = (*Tokenizer)(nil)
// Exact marks the count as the server's own.
func (t *Tokenizer) Exact() bool { return true }
// fleetClient is proxy-free and refuses redirects, so a prompt never leaves
// for a host the guard did not check.
var fleetClient = func() *http.Client {
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.Proxy = nil
return &http.Client{
Timeout: 60 * time.Second,
Transport: tr,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
}()
func (t *Tokenizer) client() *http.Client {
if t.HTTP != nil {
return t.HTTP
}
return fleetClient
}
// Count renders msgs and tools through the template and tokenises the
// result.
func (t *Tokenizer) Count(ctx context.Context, msgs []llm.Message, tools []llm.Tool) (int, error) {
n := 0
if len(msgs) > 0 {
var out struct {
Prompt string `json:"prompt"`
}
body := map[string]any{"model": t.Model, "messages": wireMessages(msgs)}
if len(tools) > 0 {
body["tools"] = wireTools(tools)
}
if err := t.post(ctx, "/apply-template", body, &out); err != nil {
return 0, err
}
k, err := t.tokenize(ctx, out.Prompt, true)
if err != nil {
return 0, err
}
n += k
} else if len(tools) > 0 {
b, err := json.Marshal(tools)
if err != nil {
return 0, err
}
k, err := t.tokenize(ctx, string(b), false)
if err != nil {
return 0, err
}
n += k
}
return n, nil
}
func (t *Tokenizer) tokenize(ctx context.Context, content string, special bool) (int, error) {
var out struct {
Tokens []json.RawMessage `json:"tokens"`
}
if err := t.post(ctx, "/tokenize", map[string]any{"model": t.Model, "content": content, "add_special": special, "parse_special": true}, &out); err != nil {
return 0, err
}
return len(out.Tokens), nil
}
// loaded is the guard's check, run immediately before every request that
// names the model.
func (t *Tokenizer) loaded(ctx context.Context) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(t.BaseURL, "/")+"/v1/models", nil)
if err != nil {
return err
}
resp, err := t.client().Do(req)
if err != nil {
return fmt.Errorf("budget: GET /v1/models: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("budget: GET /v1/models: %s", resp.Status)
}
var list struct {
Data []struct {
ID string `json:"id"`
Status struct {
Value string `json:"value"`
} `json:"status"`
} `json:"data"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&list); err != nil {
return fmt.Errorf("budget: GET /v1/models: %w", err)
}
for _, m := range list.Data {
if m.ID == t.Model && m.Status.Value == "loaded" {
return nil
}
}
return ErrNotLoaded
}
func (t *Tokenizer) post(ctx context.Context, path string, body any, out any) error {
if err := t.loaded(ctx); err != nil {
return err
}
b, err := json.Marshal(body)
if err != nil {
return err
}
q := url.Values{"model": {t.Model}, "autoload": {"false"}}.Encode()
target := strings.TrimRight(t.BaseURL, "/") + path + "?" + q
req, err := http.NewRequestWithContext(ctx, http.MethodPost, target, bytes.NewReader(b))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
resp, err := t.client().Do(req)
if err != nil {
return fmt.Errorf("budget: POST %s: %w", path, err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusMethodNotAllowed {
return fmt.Errorf("%w (%s answered %s)", ErrUnsupported, path, resp.Status)
}
if resp.StatusCode/100 != 2 {
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return fmt.Errorf("budget: POST %s: %s: %s", path, resp.Status, bytes.TrimSpace(msg))
}
return json.NewDecoder(io.LimitReader(resp.Body, 16<<20)).Decode(out)
}
// wireMessages is the OpenAI shape /apply-template reads: role, content as
// a string, tool_calls, tool_call_id. It mirrors chapter 24's encoder for
// text; image and audio parts are not rendered by a template.
func wireMessages(msgs []llm.Message) []map[string]any {
out := make([]map[string]any, 0, len(msgs))
for _, m := range msgs {
var text strings.Builder
for _, p := range m.Parts {
if p.Type == "text" {
text.WriteString(p.Text)
}
}
w := map[string]any{"role": string(m.Role), "content": text.String()}
if len(m.ToolCalls) > 0 {
calls := make([]map[string]any, 0, len(m.ToolCalls))
for _, c := range m.ToolCalls {
calls = append(calls, map[string]any{"id": c.ID, "type": "function", "function": map[string]any{"name": c.Name, "arguments": c.Arguments}})
}
w["tool_calls"] = calls
}
if m.ToolCallID != "" {
w["tool_call_id"] = m.ToolCallID
}
if m.Name != "" {
w["name"] = m.Name
}
out = append(out, w)
}
return out
}
// wireTools is the OpenAI shape of the tool list, as chapter 24's encoder
// sends it: a schema-less tool gets the explicit empty object.
func wireTools(tools []llm.Tool) []map[string]any {
out := make([]map[string]any, 0, len(tools))
for _, t := range tools {
params := t.Parameters
if len(params) == 0 {
params = json.RawMessage(`{"type":"object","properties":{}}`)
}
fn := map[string]any{"name": t.Name, "parameters": params}
if t.Description != "" {
fn["description"] = t.Description
}
if t.Strict {
fn["strict"] = true
}
out = append(out, map[string]any{"type": "function", "function": fn})
}
return out
}
Whether the router forwards POST /apply-template and POST /tokenize was an open question. The live probe (AEC_LIVE=dixie, two guarded POSTs, /apply-template and then /tokenize, each after its own /v1/models check, the 9b loaded) answered it on 2026-10-03 from talos:
live_test.go:85: dixie ornith-1.5-9b-uncensored: exact=382 (messages and tools rendered through the template) estimate=133 chars=481 units=3
The router forwards both. The request is chapter 26’s arithmetic prompt with the add and mul tools: 481 characters in three framed units, so the default Ratio estimate is . The count of 382 equals the server’s own report for the same request: sent through cmd/aec with -max-turns 1 (the same message and the same two tools), the server reported prompt=382, the figure chapter 26 saw. It is exact only because the tools travel in the /apply-template body. With the messages alone the same request counted 127, 255 tokens short (an earlier run of this probe, talos, 2026-10-03, before the Tokenizer sent tools). The 255 are the tool block the template renders in the system turn: # Tools, You have access to the following functions:, the JSON per tool, and the instructions for calling them. The README documents only messages for this endpoint, so whether the handler reads tools was settled by two guarded calls on 2026-10-03, each after a /v1/models check showing the 9b loaded: the same one-message conversation rendered to 74 characters without a tools array and 1,203 with one. The default Ratio estimate of 133 lies 249 below the reported 382, because it counts the tools as bare JSON characters. Manager still anchors on the last report and counts only the delta, since the report is free and carries the fixed part of the prompt with it.
Client wraps an llm.Client, so the loop itself is untouched. After each completion it calls Manager.Observe with the usage and the request’s message count, refits a Ratio from the same report, and computes the prefix report of this request against the previous one; OnTurn sees all three, after the lock is released. A Manager without a counter keeps one default Ratio for its lifetime, so the refit takes effect.
// Client wraps an llm.Client so that every usage the provider reports is
// observed: after each completion it calls Manager.Observe with the usage
// and the request's message count, refits a Ratio counter from the same
// report, and computes the prefix report of this request against the
// previous one. OnTurn, when set, sees all three. The loop itself is not
// changed: this is where chapter 29 reads what chapter 26's loop sends.
type Client struct {
Client llm.Client
Manager *Manager
OnTurn func(req llm.Request, resp *llm.Response, prefix PrefixReport)
// SendReasoning mirrors the wrapped Provider's option: when set, a change
// in a message's reasoning text breaks the prefix report.
SendReasoning bool
mu sync.Mutex
prev *llm.Request
}
var _ llm.Client = (*Client)(nil)
// fitter is a Counter that learns from reports (Ratio).
type fitter interface {
Observe(msgs []llm.Message, tools []llm.Tool, reported int)
}
// Complete forwards the call and observes its usage.
func (c *Client) Complete(ctx context.Context, req llm.Request) (*llm.Response, error) {
resp, err := c.Client.Complete(ctx, req)
if err != nil || resp == nil {
return resp, err
}
c.observe(req, resp)
return resp, nil
}
// Stream forwards the call; the usage is observed when the stream's Response
// is assembled.
func (c *Client) Stream(ctx context.Context, req llm.Request) (llm.Stream, error) {
s, err := c.Client.Stream(ctx, req)
if err != nil {
return s, err
}
return &observedStream{Stream: s, c: c, req: req}, nil
}
type observedStream struct {
llm.Stream
c *Client
req llm.Request
once sync.Once
}
func (s *observedStream) Response() (*llm.Response, error) {
resp, err := s.Stream.Response()
if err == nil && resp != nil {
s.once.Do(func() { s.c.observe(s.req, resp) })
}
return resp, err
}
func (c *Client) observe(req llm.Request, resp *llm.Response) {
prefix := c.record(req, resp)
if c.OnTurn != nil { // unlocked, so the callback may call back into the Client
c.OnTurn(req, resp, prefix)
}
}
// record updates everything the Client keeps under its lock and returns the
// prefix report of req against the previous request.
func (c *Client) record(req llm.Request, resp *llm.Response) PrefixReport {
c.mu.Lock()
defer c.mu.Unlock()
var prefix PrefixReport
if c.prev != nil {
prefix = StablePrefixFor(*c.prev, req, c.SendReasoning)
}
saved := req
saved.Messages = append([]llm.Message(nil), req.Messages...)
saved.Tools = append([]llm.Tool(nil), req.Tools...)
c.prev = &saved
if resp.Usage != nil && c.Manager != nil {
c.Manager.Observe(*resp.Usage, len(req.Messages))
if f, ok := c.Manager.Counter.(fitter); ok {
f.Observe(req.Messages, req.Tools, resp.Usage.Prompt)
}
}
return prefix
}
The hook into the loop is agent.ContextManager. prepareContext runs at the start of a turn, before the model call, so its context span precedes the call it shaped in Seq order, as the routing span of chapter 28 does. With Loop.Context nil nothing happens and no span is written, so every earlier trace is byte-identical. A Refuse ends the run with StopContextExceeded and no model call is made.
// ContextManager is chapter 29 and 31's hook (Loop.Context). Prepare sees the
// whole session before a turn's model call and may rewrite s.Messages; it
// returns what it did for the span. Compaction never runs inside a tool
// batch, and a cut never separates an assistant message's tool_calls from
// its tool replies.
type ContextManager interface {
Prepare(ctx context.Context, s *Session, tools []llm.Tool) (ContextDecision, error)
}
// ContextDecision is written as a policy_decision span named "context" with
// attrs action plus whatever Attrs carries (estimated, window, reserve,
// headroom, pruned, summarised_from, summarised_to, pins, lost, reason).
type ContextDecision struct {
Action string // Keep | Prune | Summarise | Refuse
Attrs map[string]string
}
// Context actions.
const (
Keep = "keep"
Prune = "prune"
Summarise = "summarise"
Refuse = "refuse"
)
// prepareContext runs Loop.Context at the start of a turn, before the model
// call, so its span's Seq precedes the call it shaped (as route's does). nil
// Context: nothing happens and no span is written, so every existing trace
// is byte-identical. A Refuse decision ends the run with StopContextExceeded
// and no model call is made; a Go error from Prepare is StopError. The span
// is a policy_decision named "context": status ok for keep, prune and
// summarise, denied for refuse, error for an error.
func (r *run) prepareContext(ctx context.Context, turn *obs.Span) *Stop {
if r.l.Context == nil {
return nil
}
span := r.l.Tracer.Start(turn, "policy_decision", "context")
dec, err := r.l.Context.Prepare(ctx, r.s, append([]llm.Tool(nil), r.specs...))
attrs := map[string]string{"action": dec.Action}
for k, v := range dec.Attrs {
if k != "action" {
attrs[k] = v
}
}
if err != nil {
attrs["error"] = err.Error()
if dec.Action == "" {
attrs["action"] = Refuse
}
r.l.Tracer.End(span, "error", attrs, nil)
return &Stop{Reason: StopError, Err: fmt.Errorf("context: %w", err)}
}
switch dec.Action {
case Keep, Prune, Summarise:
r.l.Tracer.End(span, "ok", attrs, nil)
return nil
case Refuse:
r.l.Tracer.End(span, "denied", attrs, nil)
reason := dec.Attrs["reason"]
if reason == "" {
reason = "the request cannot be made to fit the context window"
}
return &Stop{Reason: StopContextExceeded, Err: errors.New("context: " + reason)}
}
attrs["error"] = fmt.Sprintf("unknown context action %q", dec.Action)
r.l.Tracer.End(span, "error", attrs, nil)
return &Stop{Reason: StopError, Err: fmt.Errorf("context: unknown action %q", dec.Action)}
}
cmd/aec gets four flags, -window, -reserve, -system and -v, and -extra for provider-specific request fields. budgetChecker is the smallest ContextManager: it checks the budget before every turn and refuses when the request does not fit. It never rewrites the history; that is chapter 31’s Compactor. printTurn is -v’s per-turn line, and the captures below are its output. reasoning_tokens is what the provider reported, and reasoning_chars is the length in bytes of the reasoning_content the model produced, printed beside it because llama-server at b29c606 reports no reasoning_tokens (neither the README nor the server sources name it in usage).
// budgetChecker is the smallest agent.ContextManager: it checks the budget
// before every turn and refuses when the request does not fit. It never
// rewrites the history; compaction is chapter 31's Compactor, which the
// daemon (chapter 40) configures. Under -v each check is printed.
type budgetChecker struct {
m *budget.Manager
out io.Writer
verbose bool
}
func (b *budgetChecker) Prepare(ctx context.Context, s *agent.Session, tools []llm.Tool) (agent.ContextDecision, error) {
rep, err := b.m.Check(ctx, s.Messages, tools)
attrs := map[string]string{
"estimated": strconv.Itoa(rep.Estimated), "window": strconv.Itoa(rep.Window), "reserve": strconv.Itoa(rep.Reserve),
"headroom": strconv.Itoa(rep.Headroom), "source": rep.Source,
}
if err != nil {
return agent.ContextDecision{Action: agent.Refuse, Attrs: attrs}, err
}
if b.verbose {
fit := ""
if r, ok := b.m.Counter.(*budget.Ratio); ok {
fit = fmt.Sprintf(" chars_per_token=%.2f overhead=%d observations=%d", r.CharsPerToken, r.Overhead, r.Observations())
}
fmt.Fprintf(b.out, "aec: budget estimated=%d window=%d reserve=%d headroom=%d source=%s fits=%v%s\n",
rep.Estimated, rep.Window, rep.Reserve, rep.Headroom, rep.Source, rep.Fits, fit)
}
if !rep.Fits {
attrs["reason"] = fmt.Sprintf("the request is %d tokens over the budget (estimated %d, window %d, reserve %d)", -rep.Headroom, rep.Estimated, rep.Window, rep.Reserve)
return agent.ContextDecision{Action: agent.Refuse, Attrs: attrs}, nil
}
return agent.ContextDecision{Action: agent.Keep, Attrs: attrs}, nil
}
// printTurn is -v's per-turn line: the provider's usage, the reasoning the
// provider reported (reasoning_tokens; llama-server at b29c606 reports none,
// so the reasoning_content's length in bytes is printed beside it),
// llama-server's timings when the body carries them, and the prefix report
// against the previous request. Chapter 29's captures read these lines.
func printTurn(out io.Writer, turn int, req llm.Request, resp *llm.Response, prefix budget.PrefixReport) {
u := budget.FromLLM(resp.Usage)
cacheN, promptN := "-", "-"
if tm, ok := budget.ParseTimings(resp.Raw); ok {
cacheN, promptN = strconv.Itoa(tm.CacheN), strconv.Itoa(tm.PromptN)
}
fmt.Fprintf(out, "aec: turn %d messages=%d prompt=%d completion=%d cached=%d reasoning_tokens=%d reasoning_chars=%d cache_n=%s prompt_n=%s prefix_messages=%d tools_same=%v changed=%q\n",
turn, len(req.Messages), u.Prompt, u.Completion, u.Cached, u.Reasoning, len(resp.Message.Reasoning), cacheN, promptN, prefix.Messages, prefix.ToolsSame, prefix.Changed)
}
// parseExtra reads -extra: a JSON object, or @FILE holding one. Its keys go
// into llm.Request.Extra, which the client copies onto the wire untouched
// and refuses when a key collides with a named field (chapter 24).
func parseExtra(s string) (map[string]json.RawMessage, error) {
if s == "" {
return nil, nil
}
if strings.HasPrefix(s, "@") {
b, err := os.ReadFile(s[1:])
if err != nil {
return nil, err
}
s = string(b)
}
var m map[string]json.RawMessage
if err := json.Unmarshal([]byte(s), &m); err != nil {
return nil, fmt.Errorf("not a JSON object: %w", err)
}
return m, nil
}
// extraClient sets Request.Extra on every call: how a capture asks
// llama-server for a reasoning budget (reasoning_budget_tokens) without the
// loop knowing anything about reasoning.
type extraClient struct {
llm.Client
extra map[string]json.RawMessage
}
func (c *extraClient) Complete(ctx context.Context, req llm.Request) (*llm.Response, error) {
req.Extra = merged(req.Extra, c.extra)
return c.Client.Complete(ctx, req)
}
func (c *extraClient) Stream(ctx context.Context, req llm.Request) (llm.Stream, error) {
req.Extra = merged(req.Extra, c.extra)
return c.Client.Stream(ctx, req)
}
func merged(a, b map[string]json.RawMessage) map[string]json.RawMessage {
out := make(map[string]json.RawMessage, len(a)+len(b))
for k, v := range a {
out[k] = v
}
for k, v := range b {
out[k] = v
}
return out
}
The captured runs
Every run below is cmd/aec on talos against dixie’s ornith-1.5-9b-uncensored, on 2026-10-03, through the fleet guard (-fleet-guard is auto, which is on for dixie: GET /v1/models before every request, ?autoload=false on the request, the 9b loaded each time). The task is , eight operations, so a model that obeys makes eight tool calls and one final turn. The command, shown once; the system prompt is a file so that its text stays off the command line:
aec -model ornith-1.5-9b-uncensored -base http://dixie:11434/v1 -tools add,mul \
-window 16384 -reserve 1024 -v -system @system.txt \
-trace cap-a1.jsonl -keep-bodies -session cap-a1 \
'Compute ((((2+3)*4+5)*6+7)*8+9)*10 with the tools, one call per step, and answer with the number only.' \
2> cap-a1.err
system.txt holds You are aec, a terse assistant. Use the add and mul tools for every arithmetic step, one call per step, and answer with the number only. and a newline. Run a2 is the same command started right after a1 ended. Run b differs from a1 by one trailing space in the system prompt (136 bytes sent in a1, 137 in b: only the file’s trailing newline is trimmed). Run c changes byte 16 of the prompt, terse to Terse. Every run printed 12650. -v prints, per turn, one line like these (run a1, turns 1 and 2, verbatim, with the budget line before each):
aec: budget estimated=172 window=16384 reserve=1024 headroom=15188 source=estimated fits=true chars_per_token=4.00 overhead=4 observations=0
aec: turn 1 messages=2 prompt=422 completion=177 cached=0 reasoning_tokens=0 reasoning_chars=222 cache_n=0 prompt_n=422 prefix_messages=0 tools_same=false changed=""
aec: budget estimated=485 window=16384 reserve=1024 headroom=14875 source=reported+delta fits=true chars_per_token=1.53 overhead=4 observations=1
aec: turn 2 messages=4 prompt=475 completion=55 cached=418 reasoning_tokens=0 reasoning_chars=36 cache_n=418 prompt_n=57 prefix_messages=2 tools_same=true changed=""
A script reads each .err file and prints the tables below. prefix_messages and changed come from StablePrefix against the previous request of the same process; on turn 1 there is no previous request, so those fields are the zero report and the column is left blank. Run a1 made one more tool call than the task needs, so it has 10 turns where the others have 9.
Run a1, a cold slot (dixie, 2026-10-03).
| turn | prompt_tokens |
cached_tokens |
cache_n |
prompt_n |
prefix_messages |
changed |
|---|---|---|---|---|---|---|
| 1 | 422 | 0 | 0 | 422 | ||
| 2 | 475 | 418 | 418 | 57 | 2 | ““ |
| 3 | 530 | 471 | 471 | 59 | 4 | ““ |
| 4 | 585 | 526 | 526 | 59 | 6 | ““ |
| 5 | 642 | 581 | 581 | 61 | 8 | ““ |
| 6 | 699 | 638 | 638 | 61 | 10 | ““ |
| 7 | 756 | 695 | 695 | 61 | 12 | ““ |
| 8 | 815 | 752 | 752 | 63 | 14 | ““ |
| 9 | 874 | 811 | 811 | 63 | 16 | ““ |
| 10 | 936 | 870 | 870 | 66 | 18 | ““ |
Run a2, the same command, a warm slot (dixie, 2026-10-03).
| turn | prompt_tokens |
cached_tokens |
cache_n |
prompt_n |
prefix_messages |
changed |
|---|---|---|---|---|---|---|
| 1 | 422 | 418 | 418 | 4 | ||
| 2 | 475 | 418 | 418 | 57 | 2 | ““ |
| 3 | 530 | 471 | 471 | 59 | 4 | ““ |
| 4 | 585 | 526 | 526 | 59 | 6 | ““ |
| 5 | 642 | 581 | 581 | 61 | 8 | ““ |
| 6 | 699 | 638 | 638 | 61 | 10 | ““ |
| 7 | 758 | 695 | 695 | 63 | 12 | ““ |
| 8 | 817 | 754 | 754 | 63 | 14 | ““ |
| 9 | 879 | 813 | 813 | 66 | 16 | ““ |
Run b (a trailing space on the system prompt) has the same prompt_tokens, cache_n and prompt_n columns as a2 in every cell, turn 1 included (cache_n 418, prompt_n 4). Run c (terse to Terse):
Run c, one byte of the system prompt changed (dixie, 2026-10-03).
| turn | prompt_tokens |
cached_tokens |
cache_n |
prompt_n |
prefix_messages |
changed |
|---|---|---|---|---|---|---|
| 1 | 423 | 0 | 0 | 423 | ||
| 2 | 476 | 419 | 419 | 57 | 2 | ““ |
| 3 | 531 | 472 | 472 | 59 | 4 | ““ |
| 4 | 586 | 527 | 527 | 59 | 6 | ““ |
| 5 | 643 | 582 | 582 | 61 | 8 | ““ |
| 6 | 700 | 639 | 639 | 61 | 10 | ““ |
| 7 | 759 | 696 | 696 | 63 | 12 | ““ |
| 8 | 818 | 755 | 755 | 63 | 14 | ““ |
| 9 | 880 | 814 | 814 | 66 | 16 | ““ |
The checks, computed by the same script on every turn of every run:
cache_n + prompt_n == prompt_tokensholds on every turn (ok; llama-server’s accounting, README line 1421, lesspredicted_n, which is the completion and is outside the prompt).cached_tokens == cache_non every turn.- is 4 on every turn from 2 on, in all four runs: 9, 8, 8 and 8 values, none different. The constant- model of Mechanism holds on this server and this template.
- Totals, with and :
a1, : , , .a2, : , , 0.085.b: 5,807, 493, 0.085.c: 5,816, 912, 0.157. The identity gives , and .
Three results. First, the economics are as derived: a stable prefix turns a quadratic 5,807 tokens into 493 evaluated, and in the cold run turn 1 is 422 of the 972 evaluated tokens, so 43% of that run’s work is the first turn. Second, run b is a request whose bytes changed and whose prefix did not: the model’s chat template trims the system content (/props?model=ornith-1.5-9b-uncensored&autoload=false returns the template, and it reads render_content(messages[0].content, false, true)|trim), so a trailing space renders to the same tokens. StablePrefix, comparing the bytes the encoder sends, would call that a break at message:0, and here it was wrong in the safe direction. Third, run c is the opposite: the changed byte lies after the tool block that this template renders first in the system turn, so everything up to the system text, the whole tool block included, is unchanged, and the server still reused none (cache_n 0, prompt_n 423). The tokens before the first differing field would have allowed a large reuse; the server took none of it. This 9b has recurrent layers (chapter 19: a recurrent state has folded every token into one array and cannot be rolled back to an arbitrary position; llama-server saves whole states as context checkpoints for prefix reuse), and that is a candidate explanation. Slot choice is another candidate: run a1’s turn 1 also got cache_n 0, and a request that lands on a slot holding a different prompt would show the same number. This run looked at neither the server’s checkpoints nor its slots, so one sample does not establish the cause; it establishes the number, and that in this run the cost of the mid-prompt change was the whole prompt, once. Turn 2 of run c is back on the line (), as the one-time-cost argument predicted.
Run a1’s turn 1 depended on what the slot held: it got nothing back from the slot, and a2’s turn 1 found 418 of 422 tokens. Which slot answered is the server’s choice and the client cannot see it.
The fit. Run a1, the budget check before each turn against that turn’s reported prompt_tokens:
| turn | source | estimated | reported | estimated − reported | chars_per_token |
overhead |
observations |
|---|---|---|---|---|---|---|---|
| 1 | estimated | 172 | 422 | −250 | 4.00 | 4 | 0 |
| 2 | reported+delta | 485 | 475 | +10 | 1.53 | 4 | 1 |
| 3 | reported+delta | 533 | 530 | +3 | 1.48 | 0 | 2 |
| 4 | reported+delta | 588 | 585 | +3 | 1.49 | 0 | 3 |
| 5 | reported+delta | 644 | 642 | +2 | 1.49 | 0 | 4 |
| 6 | reported+delta | 701 | 699 | +2 | 1.50 | 0 | 5 |
| 7 | reported+delta | 758 | 756 | +2 | 1.50 | 0 | 6 |
| 8 | reported+delta | 816 | 815 | +1 | 1.50 | 0 | 7 |
| 9 | reported+delta | 875 | 874 | +1 | 1.50 | 0 | 8 |
| 10 | reported+delta | 936 | 936 | 0 | 1.50 | 0 | 9 |
The default estimate missed the first prompt by 250 tokens: the characters it can count are the system prompt, the task and the tools’ JSON, and the 250 are mostly the template’s rendering of the tool block. After nine reports the fit was 1.50 characters per token and 0 tokens of framing per unit, with the overhead dropping to 0 from the second report on: Observe falls back to the ratio through the origin when the two-parameter solution is degenerate or has a negative coefficient. Those coefficients describe this session and not the language: a law with no constant term bends its slope to absorb a constant, and the template’s tool block is a constant. In the right column of errors, from the second check on, reported+delta was within 10 tokens of the truth, and from the third within 3, never under the truth (it overestimated, and the last check was exact), because the fixed part is inside the report.
One kept body. -keep-bodies writes each call’s request and response. The timings object of run a1’s first call, verbatim from its file:
"timings":{"cache_n":0,"prompt_n":422,"prompt_ms":427.551,"prompt_per_token_ms":1.013154028436019,"prompt_per_second":987.0167535568856,"predicted_n":177,"predicted_ms":3305.342,"predicted_per_token_ms":18.780352272727274,"predicted_per_second":53.24713751254787}
It carries no id or address. prompt_n is what -v printed. The millisecond and rate fields vary run to run: run a2’s first call evaluated 4 tokens in 62.695 ms against this call’s 422 in 427.551 ms, which says a fixed cost per call dominates a 4-token request; nothing here is bit-exact across machines (chapter 19’s caveat on batch-size logits applies to the generated text; the token counts are what this chapter uses).
Reasoning at three settings (dixie, 2026-10-03). The same task, system prompt and -window as a1, three more runs, with -v and no trace: r0, the server’s default of a 2,048-token budget; r64, -extra '{"reasoning_budget_tokens": 64}'; rnone, -extra '{"reasoning_effort": "none"}'. reasoning_tokens is 0 on every line of all three, because this server does not report it. The budget is the server’s doing, not the model’s choice: at the limit the sampler forces the end-of-thinking tag and the model goes on to its answer.
| turn | r0 completion |
r0 reasoning_chars |
r64 completion |
r64 reasoning_chars |
rnone completion |
rnone reasoning_chars |
|---|---|---|---|---|---|---|
| 1 | 181 | 236 | 100 | 118 | 35 | 0 |
| 2 | 201 | 282 | 55 | 36 | 36 | 0 |
| 3 | 48 | 12 | 48 | 12 | 36 | 0 |
| 4 | 63 | 39 | 102 | 87 | 37 | 0 |
| 5 | 316 | 692 | 102 | 206 | 37 | 0 |
| 6 | 108 | 94 | 67 | 43 | 38 | 0 |
| 7 | 163 | 178 | 84 | 80 | 38 | 0 |
| 8 | 50 | 20 | 51 | 10 | 40 | 0 |
| 9 | 20 | 27 | 20 | 27 | 6 | 0 |
| total | 1,150 | 1,580 | 629 | 619 | 303 | 0 |
All three answered 12650. The longest reasoning of r0 was 692 bytes (turn 5, 316 completion tokens), and of r64 206 bytes (also turn 5, 102 tokens): the cap held where the default was spending most, and it cost nothing in the answer. The three runs are different samples, so a turn-by-turn match is not expected, and on the turns where the model barely reasoned, turns 3 and 9 are identical in r0 and r64 (48 and 12, 20 and 27) while turn 8 is close but not equal (50 completion tokens and 20 bytes of reasoning against 51 and 10). With reasoning_effort: none, reasoning_chars is 0 on every turn, so this 9b’s template honours it, and the completions fall to a few dozen tokens. It changed the prompt as well: turn 1’s prompt_tokens is 424 instead of 422 and each later turn’s is 2 higher than in runs a2 and b, so the template renders two more tokens when thinking is disabled, and run rnone has its own cache_n line:
| turn | prompt_tokens |
cached_tokens |
completion |
|---|---|---|---|
| 1 | 424 | 418 | 35 |
| 2 | 477 | 458 | 36 |
| 3 | 532 | 512 | 36 |
| 4 | 587 | 567 | 37 |
| 5 | 644 | 623 | 37 |
| 6 | 701 | 680 | 38 |
| 7 | 760 | 738 | 38 |
| 8 | 819 | 797 | 40 |
| 9 | 881 | 858 | 6 |
Here is not 4 but −34, −35, −35, −36, −36, −37, −37, −39: the cache reaches past the previous prompt into the tokens the model generated, because with no reasoning block to drop the stored assistant turn is what was generated, and on every turn. That makes against , 3.0%. Exercise (b) works it from the formula.
z.ai (Coding Plan endpoint) through talos, 2026-10-04. The same task, system prompt, tools, -window 16384 and -reserve 1024 as a1, run twice against glm-5.3-flash as sessions cap-z1 and cap-z2, with -v and no trace. The Coding Plan endpoint (https://api.z.ai/api/coding/paas/v4) is a different endpoint from the general API (https://api.z.ai/api/paas/v4), and the general one answered HTTP 429, “Insufficient balance or no resource package”, for this key, so these runs went to the Coding Plan one. This server reports no timings, so cache_n and prompt_n are -; cached is the cached_tokens the response carried, and prompt includes it. Both runs answered 12650.
| turn | prompt |
cap-z1 cached |
cap-z2 cached |
|---|---|---|---|
| 1 | 296 | 192 | 256 |
| 2 | 318 | 256 | 256 |
| 3 | 340 | 256 | 320 |
| 4 | 362 | 320 | 320 |
| 5 | 384 | 320 | 320 |
| 6 | 406 | 384 | 384 |
| 7 | 429 | 384 | 384 |
| 8 | 453 | 384 | 448 |
| 9 | 477 | 448 | 448 |
| total | 3,465 | 2,944 | 3,136 |
The prompt column is identical in the two runs. Verbatim, turns 1 and 9 of cap-z1, then turns 1 and 9 of cap-z2:
aec: turn 1 messages=2 prompt=296 completion=161 cached=192 reasoning_tokens=144 reasoning_chars=302 cache_n=- prompt_n=- prefix_messages=0 tools_same=false changed=""
aec: turn 9 messages=18 prompt=477 completion=4 cached=448 reasoning_tokens=0 reasoning_chars=0 cache_n=- prompt_n=- prefix_messages=16 tools_same=true changed=""
aec: turn 1 messages=2 prompt=296 completion=84 cached=256 reasoning_tokens=67 reasoning_chars=164 cache_n=- prompt_n=- prefix_messages=0 tools_same=false changed=""
aec: turn 9 messages=18 prompt=477 completion=4 cached=448 reasoning_tokens=0 reasoning_chars=0 cache_n=- prompt_n=- prefix_messages=16 tools_same=true changed=""
What two runs show: z.ai’s implicit cache reported a nonzero cached on every turn of both runs, including turn 1 of the first, and the figure grows with the prompt, from 192 or 256 of 296 tokens on turn 1 to 448 of 477 on turn 9, so 2,944 and 3,136 of 3,465 prompt tokens were reported as read from the cache. Every value is a multiple of 64. cached can reach or pass the previous turn’s prompt, as the llama-server runs above did: turn 6 of both runs is 384, equal to turn 5’s prompt, and turn 8 of cap-z2 is 448 against a turn-7 prompt of 429. The page states no minimum length; what was seen is that on the Coding Plan endpoint a 296-token prompt had 192 or 256 tokens cached. Two runs do not show why the first run’s turn 1 was already warm (the system prompt and tool list may have matched earlier requests from the same key, which this capture cannot rule in or out), what the rounding unit is in general, how long an entry lives, or whether the figure is stable across days or accounts; and the completions differ between the runs (161 and 84 tokens on turn 1), so they are two samples.
What the runs showed and what they did not: the slot was the server’s choice; run a1’s first turn depended on what the slot held; cache_n and prompt_n are the server’s accounting, not checked against its logs; one run per condition, so the reasoning table is three samples and not a distribution; and the captures stand for one model and one chat template. The token counts are stable across the runs here (422 in a1, a2 and b); nothing is claimed bit-exact across machines.
Exercises
(a) Run c found nothing cached on turn 1. Suppose instead its turn 1 had found the 418 tokens that run a2’s turn 1 found. Using the identity and the two tables, give and for that hypothetical run, and say why is not exactly a2’s 493.
Answer
does not depend on the cache: it is the sum of the prompt sizes in c’s table, 5,816, so it does not move. and (the constant of Mechanism, which the cache does not change), so , against 912 for the cold run: the saving is exactly . It is one more than a2’s 493 because c’s prompts are each one token longer than a2’s (the changed byte adds a token: the column of differences is 1 on all nine turns), so and not 879 while and are the same.
(b) Run rnone has below zero. Show from the table that , then compute from and compare it with .
Answer
Turn 2: ; turn 3: ; turn 9: , and the five between agree. So . With and , . The server’s own column sums to the same 174, as it must: the formula is the telescoped sum of , and no assumption about went into it. What the negative says is that the cache held all of the previous prompt and all but one of the generated tokens.
(c) Take Mechanism’s twenty-turn projection (, ). The system prompt is now edited before turns 6, 11 and 16, and each edit breaks the whole prefix. Find and its ratio to , and say what the bill does.
Answer
A broken turn evaluates tokens instead of . For turns 6, 11 and 16 that is 657, 932 and 1,207, so the extra work is and , which is 22.8% of the unchanged . The bill does not move (it counts reported tokens); only the work does. The turn after each edit is back on the line because the slot now holds the edited prompt.
(d) Mechanism’s two observations fit and . Add a third observation and say why the fit does not move; then replace it with , ten tokens off the law, and refit.
Answer
The sums and of Mechanism give and . The third point lies on the same law (), so with all three residuals are zero and . everywhere, so that pair is a minimum; and because the observations now have two different shapes , the minimum is unique. The normal equations’ solution is unchanged (TestRatioRefit checks exactly this). With the sums become , , , , and , so (3.54 characters per token) and : no pair fits all three, and the least-squares pair moves to the compromise.
(e) Reserve is 1,024 and the estimate says the request fits with 10 tokens of headroom, but the server tokenises it 30 tokens larger. What happens on llama-server at b29c606, and what would each source have said?
Answer
The prompt is 20 tokens over the budget, and the prompt is evaluated: nothing in the request tells the server about the reserve. Generation then runs until the model stops or the context is full, and the response carries truncated: true (README, line 674) if the prompt plus the generated tokens exceed n_ctx; whether that happens depends on how long the answer runs, which is why a reserve nothing enforces (no max_tokens) is a hope and not a bound. As for the sources: reported+delta is wrong by the delta’s error only, because the previous report already contains everything else, and Observe corrects it on the next turn. The Tokenizer counts the whole rendered request, tool block included (it matched the server’s own report on the probe request), so a counted check would have refused before the request was sent; it pays two guarded calls for that, which is the price of a number that is not anchored on the last report.
(f) The 9b runs with a 2,048-token reasoning budget and a request asks for 64. Which terms of change on that turn and on the next, and what does the server do at token 64?
Answer
On that turn must still cover thinking plus answer, but the thinking is at most 64 tokens, so the completion is shorter and the latency lower; is unchanged. On the next turn is unchanged because the reasoning is not sent back (SendReasoning off), so the prefix and the growth are exactly what they would have been. At the budget the sampler forces the template’s end-of-thinking tag (and reasoning_budget_message if set) and the model goes on to its answer (common/reasoning-budget.cpp:117-130 and :174-188). Whether that answer is still right is the run’s result and not a property of the budget: in the capture it was, and the longest reasoning shrank from 692 bytes to 206.
(g) Anthropic reports input_tokens, cache_read_input_tokens and cache_creation_input_tokens as three siblings. Write the budget identity for that wire and say what Usage.Prompt must hold for Manager.Check to stay correct.
Answer
The slot analogue is . Prompt must be the sum of the three. The adapter today keeps input_tokens alone (chapter 24), so a budgeted Anthropic session undercounts by the cached share. Cached stays 0 by design, and the fix, when a key exists, is one line in the adapter’s usage().
Lab
go/labs/ch29 declares Manager (Check, Observe, Reset) and Impl, and checks at compile time that the reference (internal/budget) and go/labs/ch29/mine have the same API. You write mine/budget.go: Manager, Ratio and StablePrefix. Run
make lab CH=29 IMPL=mine
Provided: llm.Fake, the loop, the tracer, budget.Window, Usage and the Counter interface. The tests, offline against the reference or mine:
TestBudget: the first turn with no previous report; a request that fits by estimate (700) and does not by count (810);reported+deltaover an appended tail; a history shorter than the observed request (a full count, neverreported+delta);Reset;Reserveequal toSizeasErrWindowwithFitsfalse; andFromLLMzeroing aCachedlarger thanPromptwhile leaving an Anthropic-shaped usage at 0.TestRatio: the default count,ceil(chars/4)plus 4 per unit (messages and tools); the refit against a known law (3.5 characters per token, 7 tokens of framing), followed by a fresh request within one token of the law.TestStablePrefix: an appended tail, one edited byte of the system prompt, changed tools, a changed model, and a shorter request after a rewrite.
TestTokenizerLive skips without AEC_LIVE; with AEC_LIVE=dixie it checks that the 9b is loaded, counts chapter 26’s arithmetic request through /apply-template and /tokenize, and logs the count beside the default estimate. It wakes nothing. With AEC_IMPL=mine the starter fails TestBudget and TestRatio with chapter 29 lab: not implemented, and TestStablePrefix on the zero report it returns, with no panic. The reference’s three offline tests take 3 ms together on talos.
Further reading
- llama.cpp,
tools/server/README.mdatb29c606: timings and context usage (lines 1395-1421),cache_prompt(587),truncated(674),/tokenize(677),/apply-template(728),/slots(974),--cache-ram(167),--slot-prompt-similarity(242). - llama.cpp, pull request 16391: the host-memory prompt cache behind
--cache-ram. - OpenAI, Prompt caching: the rendered-prefix rule, the minimum length and the 128-token rounding of
cached_tokens. - Anthropic, Prompt caching: the
tools,system,messagesorder andcache_read_input_tokens. - z.ai, Context caching: implicit caching, with no stated minimum.
- Anthropic, Extended thinking:
budget_tokens, its 1,024 minimum, and the rule that changing it invalidates cache breakpoints. - OpenAI, Reasoning models:
reasoning.effort, and reasoning tokens that occupy the context window and are billed as output. - z.ai, Deep thinking:
thinking.typeand the models that cannot disable it. - Woosuk Kwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention, 2023: the paged KV cache and prefix sharing across requests.
- In Gim et al., Prompt Cache: Modular Attention Reuse for Low-Latency Inference, 2023.
- Lianmin Zheng et al., SGLang: Efficient Execution of Structured Language Model Programs, 2023: RadixAttention, a prefix tree over KV caches, the general form of what a slot does.