# Prompt cache prefix

A provider reuses a cached prompt only while every byte before the new part matches an earlier request. Each request is captured as its adapter writes it and compared, unit by unit, with the last answered request on its lane. The first unit that differs is where the cache stops reading; it names the cause on the usage event.

1. **Previous request** tools:read, system (base, open_work), history:user
2. **This request** tools:read, system (open_work changed), history:user, history:assistant
3. **Break at unit 1** break_cause system:open_work Units before it are read from the cache

## One capture point

Every adapter calls `capture_request(model, body, wire=…)` with the body it is about to send, after `on_payload` and before any byte leaves the process. Nothing else observes request bytes; the prefix check, the request-bytes contract test and the turn benches all read them from here.

| Listener | How it receives a request |
| --- | --- |
| Stream chokepoint | Each attempt in `streaming/stream.py` binds a `RequestSlot`; the adapter fills it, which runs the check before the request goes out. A slot takes one request, so an adapter called outside the chokepoint leaves it alone. When the attempt sends its request again, mended after the provider refused its shape (`request_repair.py`), it reopens the slot, so the slot holds the request that was answered |
| Tests and scripts | `capturing()` collects every body in the block. With `send=False` each request stops at the capture point with `RequestNotSent`, so a whole conversation can be serialized through every adapter without a network |

| Wire | Adapters |
| --- | --- |
| `anthropic-messages` | `anthropic` |
| `openai-responses` | `openai_responses`, `azure_openai_responses`, `openai_codex` |
| `openai-completions` | `openai_completions`, which every OpenAI-compatible provider uses |
| `google-generative-ai` | `google`, `google_gemini_cli` |
| `bedrock-converse` | `amazon_bedrock` |

## Units

A captured body is cut into units in the order a provider reads a prompt: each tool, then each system text, then each history item.

Anthropic and Bedrock messages are cut per content block, so a message that grows by a block still extends the one before it. Units match by the digest of their bytes alone; a label never decides a match.

| Label | Unit |
| --- | --- |
| `tools:<name>` | One tool definition |
| `system` | One system text, with the sections it was composed from: each a name, an end and a digest up to there. The runtime names them (`components.prompt_parts`, registered through `runtime/lower_layers.py`): the built sections such as `environment`, `agents_md`, `memory`, `open_work`, `capabilities`, `plan_mode`, then what a turn appends: `goal`, `goal_verification`, `pages`. A prompt it does not know as composed (sent again after a restart, or from a saved contract) has one section, `prompt`; its bytes still match |
| `history:<kind>` | One history item: a role, or an item type such as `function_call_output` |

Breakpoint markers (`cache_control`, `cachePoint`) move from request to request by design and are left out of the units. The lifetime they ask for is a setting.

## Two checks

- **Before the request**: `check_request` compares the request with the last answered one on its lane, and only reads. A changed setting comes first: `model`, then `setting:cache_key`, `setting:ttl`, `setting:effort`, `setting:format`, `setting:tool_choice`.
- **Before the request**: Then the units: the first that differs gives `break_at`, and its label gives `break_cause`.
- **Before the request**: A changed system text is named by its first section past the longest start both texts share at a section end they both have: `system:open_work`. A request shorter than the previous one gives `removed:<label>`. No provider usage is needed, so a provider that reports no cache tokens is checked the same way.
- **After the reply**: `settle_check` looks at cached input. When the request was intact and cached input fell by more than 5% and more than 2,000 tokens since the previous request, the cause is `ttl` if more time passed than the cache lifetime (5 minutes, or the 1-hour or 24-hour setting), otherwise `server`.
- **After the reply**: The answered request, with its cached input, then becomes the lane's baseline; a request that got no reply leaves the baseline as it was.
- **In the log**: A break nobody announced writes one line to the Worker log: the unit, its cause, and both texts from the first character they differ at. The worker keeps the last answered request's texts in memory for 16 lanes; the ledger keeps digests only.

## Lanes

A lane is the session, the kind of call, the lane label, the Agent and the conversation branch. Only conversation-shaped calls have one: chat, Agent-method and subagent turns. Requests are compared only within one lane, so calls with other instructions do not report each other as breaks.

| Call | Lane |
| --- | --- |
| A conversation's own turns | `chat` with no label. Turns from the App, the TUI, a channel or a check-in share it, so a prompt that changes with the source is reported |
| A Goal verification turn | Label `goal_verification` (`UsageContext.prefix_lane`, set where the turn binds its usage context) |
| A self-update turn | Label from its source, `self_update_*` |
| An Agent method or subagent turn | Its `call_kind` and `call_label` |
| Another branch of the conversation | The branch is the session's `active_branch_id`, bound once the turn's message is stored (`UsageContext.branch_id`). A new branch's first request is compared with the last request of the branch it left and records `branch` as expected; back on the old branch, a request is compared with that branch's own last request |
| A side call, or a call outside any session | None. A permission check, memory writing, a summary, a title, a prediction or a tool's own call sends a prompt of its own each time: it gets a prefix hash but is not compared |

Each lane's last answered request is kept in memory and in `prefix_baselines` in the usage database, written when the reply settles. The database is read only for a lane's first request in a process, so the first request after a Worker restart is compared with the last one before it. A lane not written to for 30 days is dropped.

## Breaks made on purpose

The runtime announces a break it makes with `expect_break(session, cause)`. With a session, every lane of that session is told; with none, only the lane of the call being prepared, as compaction rewrites the request about to go out.

The next request on the lane records the cause in `expected` when it breaks; an announcement is used once, by the next answered request.

| Cause | Announced by |
| --- | --- |
| `compaction` | `engine.compact` after it stores a summary; `compaction/request.py` when a request summarizes part of its own history |
| `rewind` | `rewind_marks.take_rewind_note`, when the note is taken onto the next turn's message |
| `model_switch` | `session_model.write_session_chat_model`, when the pinned model changes |
| `branch` | The check itself, for a new branch's first request |
| `effort_switch` | `branch_settings.write_branch_settings`, when a branch's reasoning effort changes |
| `ttl_switch` | `settings.set_setting` for `models.prompt_cache_ttl`: the cache lifetime applies to every conversation, so every lane of every session is told (`expect_break_everywhere`) |
| `tool_loaded` | The agent loop, when a deferred tool is loaded on a provider without native loading and joins the array |

## What the usage event records

| Column | Value |
| --- | --- |
| `prefix_hash` | Hash of the request's settings and units |
| `break_at` | Index of the first unit that differs; none for an intact request and for `ttl` or `server` |
| `break_cause` | The label, setting, `ttl` or `server` |
| `expected` | The announced causes that explain the break, comma-separated |

All three ways a request is metered (unbudgeted, budgeted, Goal receipt) build the event with the check, so a receipt replayed after a restart keeps it.

## What keeps the prefix

A conversation's system prompt changes only when something the model must read there changes. Everything else reaches the model beside a turn's message, stored on that message, so later requests send the same bytes.

| Rule | How |
| --- | --- |
| One owner of the recorded prompt | Only the conversation's own turn records its branch's prompt and keeps it (`loop_runner.owns_conversation_contract`). A Goal verification and a background check-in build a prompt of their own and neither read nor write it |
| Movable sections | When the new prompt differs from the recorded one only in `environment`, `agents_md`, `memory`, `open_work` or `capabilities`, the recorded prompt is sent again and each changed section's whole text goes beside the message (`turn_context.kept_sections`). Open Pages never go in the conversation's own prompt; they are a section beside the message. Any other change rebuilds the prompt |
| Whole sections, not patches | A section is sent when its text differs from the last note of it the request renders, or from the prompt's section when none renders (compacted, clean or bounded history). A section that is gone gets a note saying it no longer applies |
| One storage | The user node's `turn_context` list: the date, an interruption, a rewind note, the section notes, the plan-mode note, the Goal note, the todo reminder, recalled memory, the run note, in that order. A node from before the list renders from its old keys in the same order; new nodes are also written with the old keys |
| Written when it happens | Recalled memory, the run note and a pending rewind note are written when the message is stored; the section notes and the notes decided from the view when the turn's first request is built. A message sent again keeps its rewind note and decides the rest from the same view |
| Notes decided from the view | What the request's rendered history shows decides them (`turn_context.turn_view`): the date goes only when it differs from the last date in view; the plan-mode note on entering, then every fifth turn, every fifth note full and the rest short, one exit note on leaving |
| Goal and todo notes | Decided from the same view: the Goal note in full when no full note in view has the same objective, status, revision, budget band (75%) and verification feedback, else one short note with the usage; the Goal's todo list after 10 turns without a `todo_*` call and without a reminder. A compaction that drops a note brings it back in full |
| One tools array per epoch | The conversation's own turn sends every tool it may use. What depends on the turn leaves the tools in place: `chat_send` off a channel, a question with nobody to answer, `handoff` off the head, a scheduled run's `always_on_report`, a report preference from outside text, memory tools with memory off, `computer_use` with no Page, the local `web_search` while the provider searches |
| Refused, not removed | Calls to those tools are refused (`TOOL_UNAVAILABLE`, nothing is asked) and the `tool_availability` section beside the message lists them once. Plan mode and deny rules are refused at dispatch too ([deferred tools](https://fzkuji.github.io/OpenProgram/docs/reference/design/function/deferred-tools.html)). A verification, a check-in and a self-update step drop such tools from their own array |
| Memory off takes nothing back | Turning memory off stops new recalls and refuses the memory tools. Recalled memory and memory-section notes stay in the history, the recorded prompt keeps its memory section and the next message says it no longer applies. A compaction's input leaves recalled memory out (`turn_context.without_recall`), and the first prompt rebuilt after that compaction has no memory section |
| One replay rule | Every render takes an explicit `audience`. Only the conversation's own request shows section notes; a call with a prompt of its own shows none. Whether a request recalls memory and whether it is told the date are the loop's own settings (`AgentLoopConfig.recall`, `dated`), not context variables |
| The branch record is the prompt's authority | A checkpoint of the conversation's own turn keeps the hash of the prompt recorded on its branch (`system_prompt_sha256`), not its text; a resume reads the text from the record and is refused when the record no longer matches. A checkpoint with the text (older ones, turns with a prompt of their own) resumes from it |
| Hash against hash | Two contracts that both name the prompt by hash, such as a checkpoint checked against itself when it is loaded, compare by that hash (`runtime_contract.validate_runtime_contract`). A turn is kept by hash only when its branch held a record before it began; the first turn's record sits at its own reply, so its checkpoint keeps the text |
| A runtime note is not the turn's message | The note of the current permission mode goes after everything else in each request and is never stored (`message_context.RuntimeNote`). Recall searches with the person's own words, and the date and recalled memory go in front of their message, as later turns render it |
| One key for one-off calls | A call that names no conversation is keyed by its provider, model, instructions and tool names (`providers.shared.cache_key`), whether it goes through a Runtime or straight to an adapter |

## Why this design

Anthropic's preserved-thinking models check the request: a rebuilt system prompt is `system_rerendered`, a tool added or removed is `tool_set_changed`, and either is refused or drops the model's reasoning. Every other provider re-reads everything after the first changed byte. So what changes during a conversation goes beside a message, and the system prompt and the tools stay as they were.

### The Goal

Follows Kimi Code's two Goal reminders: the full one when the Goal's state changed or after a compaction, a short one with the usage otherwise.

Codex repeats the whole rules in every continuation message, which costs more tokens each turn. Any Goal text left in the system prompt would rebuild it when a Goal starts or ends.

The todo list follows Claude Code: the model sees it in its todo tools' results, so it comes back only after 10 turns without them.

### The tools array

Follows Codex, which refuses at dispatch and states permission changes as a message section, and Hermes, which pins a session's `tools[]` and says which pinned tools are inert where they are.

Claude Code removes tools that a deny rule names, but its rules are set at start; ours change mid-conversation, and the refusal at dispatch is what enforces them either way.

### Plan mode

Follows Claude Code's schedule (Kimi Code has the same two notes): full on entering, a note every five turns, every fifth note full. Codex sends its collaboration mode once per change, which leaves a long conversation without a reminder that it is still planning.

### The date

Claude Code, Codex, Kimi Code and OpenCode all send the date only when it changed. Repeating it every turn tells the model nothing and fills a small window.

### Memory turned off

Hermes rereads memory only at a rebuild such as a compaction, and Codex and Claude Code keep what was recalled.

Content already sent has reached the provider; taking it out of the history is a rewrite that breaks the prefix and, on the models above, is refused. Turning memory off means nothing more is read or written, which stopping recalls and refusing the memory tools achieves.

### Effort and cache lifetime

Claude Code, Codex and Pi apply a new effort at once and show no warning; Claude Code records it as the cause of the break. A change of either is applied at once and announced as expected, with no prompt to the person.

### Recall and date as loop settings

Follows Codex, which passes each turn's state in an explicit `TurnContext`. A context variable set by one caller reached nested and parallel calls it was not meant for.

### One record of the prompt

Codex resumes from the `base_instructions` it persisted, and Hermes replays a session's pinned prompt and tools until a compaction. Two copies (checkpoint and branch) drift apart across compactions, restarts and resumes, so the branch keeps the text and the checkpoint a hash that the resume check compares.

### xAI misses without a byte changed

Measured on the Grok subscription endpoint: of 72 requests whose prefix was intact, about one in eight read only the first 1,152 tokens from cache, and the same request sent again two seconds later could hit or miss. The usage event records these as `server`, or `ttl` after a long pause.

xAI documents an `x-grok-conv-id` header that routes a conversation to one server. Sent beside `prompt_cache_key` it changed nothing: 31 of 36 hits with it, 32 of 36 without. So no header is added.

The miss does not follow the pause. Repeating one request after gaps of 30, 60, 120 and 240 seconds, twice over, missed once at 60 seconds and once at 240, and hit at every other gap, 240 seconds included. So no keep-alive request is sent either.

## Request bytes contract

A finished turn renders, in the next turn, the bytes its own requests sent. `tests/support/request_bytes.py` runs real turns (dispatcher, agent loop, DAG render) with a scripted reply and serializes each request with the real adapter in `capturing(send=False)`. Two suites use it.

| Suite | What it holds |
| --- | --- |
| `tests/contracts/providers/test_request_bytes.py` | Anthropic, Responses, Chat Completions and Codex: the next turn re-sends a tool call, a failed tool, a tool image, a user image, a long paste and a large `tool_search` result as they were sent |
| `tests/unit/context/render/test_turn_prefix_cache.py` | Codex and Anthropic: memory, run notes, journal resume, old tool results resent whole, midnight, the date once a day, a permission mode the owner set, plan mode in and out, a Goal's full and short notes, a refused tool; a scenario matrix that changes one thing between two turns, checks that the prefix check names it, and checks whether the prefix holds; and the preserved-thinking rule that every request on one model sends the same system and tools bytes |

A known place where a later render differs is marked `xfail(strict=True)` with the gap it shows. The change that closes a gap removes its mark.

## Implementation status

| Part | Coverage |
| --- | --- |
| In place | Capture, both checks, lanes with branches, baselines, announced breaks, the ledger columns and both suites; one owner of the recorded prompt, movable sections, one storage and replay rule, the rewind note on the message, one key for one-off calls |
| Also in place | The Goal, plan mode, date and todo notes decided from the view; one tools array with refused calls and the availability section; memory off taking nothing back; checkpoints naming the prompt by hash; the loop's own recall and date settings; the cache lifetime announced on every lane |
| Scenario matrix | Open work, an active Goal, a rewind, a browser Page, AGENTS.md, a skill, a worktree, memory changed, memory turned off, nobody to answer, a source switch, plan mode in and out, an added tool, a Worker restart |
| The check alone | Goal verification beside the main turn, side calls, branches, a provider that reports no cached input, the cache lifetime |
| Not yet in the matrix | Switching models and back, a compaction, resuming after an approval wait, toggling web search, loading a deferred tool on Anthropic, a small window's bounded tail |

Neither suite marks a gap today: a failed tool, images, a picture-only message, a long paste and a large `tool_search` result are all re-sent as sent. One known break stays outside the suites: `tools:<name>` breaks when a tool joins the array, a new Program or MCP tool on a provider without native deferred loading.

Not yet built:

- A new effort on Anthropic as a `role: system` message with `output_config.effort` (beta `mid-conversation-output-config-2026-07-01`), which keeps the cache. The message stays in every later request, so each turn's effort must be stored on its message; the 400 fallback needs a paid check. Until then a new effort goes in the top-level setting and is announced.
- One contract record on the branch with the epoch's tool names and schema hashes, the effort baseline and the cache lifetime, with a placeholder for a tool whose Program was removed: the branch keeps the prompt node, and the epoch's refused set lives in the deferred-tool epoch record.
- Announcing `web_search_toggle` when the provider's search option changes, and a one-time `goal_moved` when a conversation with an active Goal first sends its Goal beside the message.

**Files**

| File | Role |
| --- | --- |
| `models/providers/recording/capture.py` | Capture point, scopes, slot, units and settings per wire |
| `models/usage/prefix_fingerprint.py` | Fingerprint, both checks, lanes, baselines, `expect_break` |
| `models/providers/streaming/stream.py` | Binds a slot per attempt, settles the check, passes it to metering |
| `models/usage/ledger.py` | `prefix_baselines` and the four event columns |
| `runtime/context/prompt_assembly/components.py` | `prompt_parts`, `remember_composed` |
| `runtime/conversation/turn_runtime/loop_runner.py` | Composes the sent prompt from named parts; the tools array and `turn_availability`; the notes decided from the view; the prompt by reference in checkpoints |
| `runtime/context/prompt_assembly/turn_context.py` | Entries, `turn_view`, `date_to_send`, sections and `kept_sections` |
| `runtime/conversation/session_settings/plan_mode.py` | The plan-mode notes and their schedule |
| `programs/tools/planning/goal/chat.py` | `goal_note`, `todo_reminder` |

[Composition: the layers a prompt is built from](https://fzkuji.github.io/OpenProgram/docs/reference/design/context/composition.html)
