返回 CodeWhale
CACHE.md
根目录 / docs / CACHE.md
1 # Prompt-cache stability (the pinned prefix)
2
3 > 阅读简体中文版:[zh_hans/CACHE.md](zh_hans/CACHE.md)。
4
5 Provider prompt caches (DeepSeek KV cache, Anthropic `cache_control`) only pay
6 off when the **byte prefix** of a request matches the previous one: the system
7 prompt, then the tool catalog, then `messages[0..n-1]`. Any change to those
8 bytes invalidates the cache for every token after the first difference.
9
10 ## The invariant
11
12 **After session start, the system prompt and tool catalog are frozen bytes.
13 History only grows. A cache miss is allowed only when we can name why.**
14
15 Concretely:
16
17 - The **header** (system prompt + tools) is composed once at session start and
18 re-composed **only** on an explicit, logged header-change op. The tool loop
19 performs **no** mid-loop system-prompt refresh, so an agent writing a file
20 (which changes the project-context pack, a directory listing, a skills scan)
21 cannot move the pinned prefix under the model's feet mid-turn.
22 - **History only grows.** Volatile facts the model must see (LSP diagnostics,
23 steer input, subagent completions) are appended to the message list, never
24 spliced into the frozen prefix. Workspace drift is delivered the same way:
25 at the start of each **new user turn** (never mid-tool-loop) the engine
26 recomposes the volatile contributors and, if anything differs from what the
27 model last saw, appends **one** `<context_update>` user-role message with a
28 bounded `+`/`-` line delta (new files in the project pack, edited AGENTS.md
29 lines, added skills, memory entries, goal text) *before* the user's message.
30 The header bytes stay pinned; the update is a normal append, so the prefix
31 still extends. The pinned system prompt tells the model once that updates
32 arrive this way. Each delta is delivered exactly once (`/cache stats` shows
33 `Context updates: N`).
34 - Every miss is **attributable**. `PrefixStabilityManager` (`prefix_cache.rs`)
35 records each change with a reason and reports it through `/cache stats`.
36
37 ## What counts as a declared header change
38
39 These re-pin the prefix under a logged `change:<what>` reason. A changed
40 tool header can invalidate the remaining conversation prefix, requiring a full
41 refill and, for some providers, cache-write charges. A named change does not
42 make that cost small or prove a provider cache miss:
43
44 | Op | Reason |
45 | --- | --- |
46 | `/model` (SetModel) | `change:model` |
47 | Mode change (Plan or Work) | `change:mode` |
48 | Goal set / pause / resume / clear / status | `change:goal` |
49 | Mid-turn tool-surface change (deferred-tool admission/eviction, tool-search activation, runtime MCP tool arrival) | `change:tool_surface` |
50 | Session sync / restore (SyncSession) | `resume` |
51 | Session construction | `initial` |
52
53 History resets that legitimately invalidate the tail (not the header) are
54 logged as `reset:<what>` — `reset:compaction`, `reset:clear`, and
55 `reset:image_window` when a provider's per-request image limit moves the
56 request image window (the oldest images go as fixed text notes).
57
58 Anything else that changes the header bytes with **no** declared reason is
59 **drift**: it is logged as `drift:<component>`, the original pin is **kept**
60 (so the same undeclared prefix keeps counting as a miss instead of quietly
61 becoming the new baseline), and `/cache stats` shows a `WARNING`. After the
62 mid-loop-refresh removal, drift should stay at zero in normal operation; a
63 non-zero drift count is a real bug to investigate.
64
65 ## Attribution vs. the old behavior
66
67 Two earlier behaviors are rejected, matching the DeepSeek Harness design:
68
69 - **Detect-and-report + re-pin on drift.** The manager used to re-pin to the
70 new prefix on every change, so `/cache stats` looked "stable" again after one
71 bad step while the provider cache was already dead. It now keeps the original
72 pin on undeclared drift.
73 - **Recompose the system prompt from disk on every tool step.** The turn loop
74 used to call `refresh_system_prompt()` before every model request, including
75 mid-tool-loop. That is removed. Header refreshes happen only at the declared
76 edges above.
77
78 Tool-result redaction (`prepare_model_bound_request`) is content-preserving
79 when no secret is configured (the common case), so it does not move the prefix.
80 When a configured secret appears in a tool result, redacting it is a security
81 requirement that correctly overrides cache stability for that one message.
82
83 ## Compaction summary requests
84
85 A compaction summary request is the turn's request plus one trailing
86 instruction: the same model, system prompt, tools and reasoning tier, then the
87 selected older history in order. A manual `/compact` sends the tools the last
88 turn sent (reconstructing active tools after `/resume` when no turn has run
89 yet); automatic and overflow-recovery passes send the tools the next request
90 will carry. Across all providers the summary also sends the turn's own
91 `tool_choice` (`auto`), because sending `none` when ordinary turns send `auto`
92 moves the cached prefix (#7564); a reply that calls a tool is rejected as an
93 unusable summary and retried once with `tool_choice: "none"`. Image capping
94 runs over the full conversation before slicing off the retained tail so the
95 prefix stays byte-identical to the turn before it.
96
97 ## Per-request receipts
98
99 `provider_request_receipt` in exec stream JSON and `turn.provider_request` in
100 Runtime events join the current preparation's logical prefix outcome with
101 provider-wire tool bytes and digest, route identity and endpoint fingerprint,
102 and that request's reported usage. A prepared wire observation does not prove
103 provider delivery. Missing usage or adapter measurements remain
104 unknown. Receipts bind physical send identities and typed transmission
105 confidence to the captured route. Automatic retries require an ordinary rate
106 limit or a proven transient connection failure before dispatch. Server
107 failures and interrupted streams remain uncertain and do not authorize
108 another inference request. A request that received no response headers is
109 sent again `stream.open_retries` times (default once); its first send stays
110 uncertain. Missing per-attempt usage is never presented as free
111 work; primary late cumulative contribution reconciliation remains separate work.
112
113 These are observations, not additional billing records. They do not establish
114 that eviction caused every cache miss. A cache refill can depend on provider
115 retention, routing, message changes and other conditions outside the local pin.
116
117 ## Verifying the fix
118
119 `/cache stats` reports prefix stability, the pin reason, the last miss reason,
120 the undeclared-drift count, and the aggregate provider cache hit rate. In a
121 coding session, a stable eligible prefix can be reused within the provider's
122 retention window. Read reported usage to establish a hit; local stability alone
123 does not prove one.
124
125 ### Live end-to-end check (manual, key-gated)
126
127 With a real `DEEPSEEK_API_KEY`, run a session that makes the agent take at
128 least three tool steps in one turn, then open `/cache inspect`. Keep the route
129 and tool surface fixed and compare `prompt_cache_hit_tokens`, reported input
130 usage and the per-request receipt. Stable prefix and tool-catalog hashes show
131 local continuity; provider cache counters establish reported reuse. A local
132 re-pin can explain a change, but its absence does not establish the cause of a
133 provider miss.
134
135 ## KV-cache effect note (for contributors)
136
137 Any new contributor to the session context must state its **KV-cache effect**:
138 does it belong in the frozen prefix (system + tools) or in append-only history?
139 Never splice a volatile fact (time, an instruction edit, a skill-catalog
140 change, a project-file change) into the prefix — append it as a user-role
141 message instead. A later request must be `previous ⊕ suffix` unless a logged
142 header change or a history reset explains the difference.
143
144 ## Deferred: full reconstructability (Layer 3)
145
146 DeepSeek Harness derives every request from an append-only session log via a
147 pure `deriveMessages()` projection, so prefix-extension is emergent rather than
148 managed. Codewhale now pins the header and delivers drift as `<context_update>`
149 appends; the remaining step is to make the session log the single source of
150 truth with a pure projection (and to persist the context-update baseline with
151 it). That is a follow-up lane, not part of this change.
152
152 lines MARKDOWN