Repository navigation
Description
docs(cache): clarify prompt-cache ownership, identity, accounting, and lifecycle boundaries
Audit coverage: five research workstreams completed, covering seven grouped subjects. Fixed implementation evidence exists for OpenPI/Pi, Codex CLI, Hermes, Grok Build, Gemini CLI, and OpenCode; Claude Code remains documentation-only because its implementation is proprietary.
Scope and evidence policy
This comparison covers seven client/runtime implementations plus their provider contracts:
- OpenPI / Pi
- OpenAI Codex CLI / Responses API
- Claude Code / Anthropic Messages API
- Hermes Agent
- Grok Build / xAI API
- Gemini CLI / Gemini API
- OpenCode
Claims below are limited to inspected source revisions and public API contracts. Provider-side routing, physical KV layout, eviction, encryption, and undisclosed cache-key construction are not inferred from latency, UI labels, or client options.
Evidence is classified as:
- Source fact: visible in a fixed client revision.
- Documented contract: stated by the provider.
- Inference: expected consequence of a documented prefix contract.
- Unknown: not established by available source or documentation.
1. Precise taxonomy
1.1 Prompt/KV caching
Provider-side reuse of computation for an exact or provider-equivalent request prefix.
Typical inputs include:
provider/account/model
+ system/developer instructions
+ tool definitions and ordering
+ early conversation messages
+ provider-specific request settings
+ optional cache key, breakpoint, or explicit cache-resource name
It may reduce latency and input cost. It does not mean the client restored conversation state, semantic memory, or a prior model response.
Three forms appear in this audit:
-
Automatic prefix caching
Provider detects reusable prefixes. Examples: OpenAI and Gemini implicit caching. -
Explicit prefix markers or breakpoints
Client marks cacheable prefix boundaries. Examples: Anthropiccache_control, Bedrock cache points. -
Explicit cache resources
Client creates, references, updates, and deletes a named provider object. Gemini API supports this, but the audited Gemini CLI revision does not use it.
A prompt_cache_key is an affinity/partitioning hint or identity input. Its presence does not prove that a cache entry exists or that a request hit it.
1.2 Context state
The messages and state used to construct the next request. This can be:
- locally replayed history;
- a server-side response chain such as
previous_response_id; - a provider conversation object;
- a persisted CLI session.
Context continuity does not guarantee prompt-cache continuity. Conversely, a cache hit does not prove that server-side conversation state was reused.
1.3 Memory
Durable or selectively injected knowledge outside the immediate transcript, such as:
- project instructions;
CLAUDE.md-style files;- skills and context files;
- user/project memory;
- searchable compacted records.
Memory affects caching only when rendered into the provider-visible request. Changing memory may alter the prefix even when the session ID is unchanged.
1.4 Compaction, summarization, pruning, and replay
These are distinct mechanisms:
- Compaction: replaces older context with a summary or provider compaction item.
- Pruning: removes or hides selected content, often old tool results.
- Summarization: creates new model-authored context.
- Replay: returns persisted execution output without making another provider request.
Compaction and pruning manage context-window pressure; they are not prompt caches. Replay can avoid a provider call entirely and must not be reported as a provider cache hit.
2. Fixed revisions and evidence boundaries
OpenPI / Pi
- OpenPI:
2a69d3f32994da4123f1312b7fa84ef3d6119be1 - Installed Pi:
@earendil-works/[email protected] - Corresponding upstream tag:
earendil-works/[email protected] - Exact
pi-aiadapter source was not independently inspected; bundled adapters, installed documentation, and changelog were used.
OpenAI Codex CLI / API
- Codex CLI:
a9e447a69dee4f2789dd8d8c776e314772c1f049 - OpenAI documentation is rolling; API claims are limited to the documented contract.
- Fixed-revision CLI claims below are limited to request construction and cache-key scope in
codex-rs/core/src/client.rs,guardian/review_session.rs, andsession/session.rs.
Claude Code / Anthropic
- Claude Code implementation is proprietary and has no auditable source revision here.
- Claude Code and Anthropic documentation are rolling.
- Exact Anthropic Cookbook commit was not fixed.
Hermes Agent
cbd8de8ad64530be01efea23b7764d5c37c634ed
Grok Build
c2ad97f87aea4303b6000a2c22128bc91ee76c9b
Gemini CLI
812f7a2bcf20b6e80e2e50c3c8fa8e26567bc1e8
OpenCode
8615731d46153dd29b89e205fb55b2cc16205cb0
3. Per-system mechanisms
3.1 OpenPI / Pi
Ownership
OpenPI
→ Pi AgentSession and prompt construction
→ pi-ai provider adapter
→ provider cache controls and normalized usage
OpenPI does not directly emit Anthropic cache_control, OpenAI prompt_cache_key, or provider affinity headers. Provider caching belongs primarily to pi-ai; Pi owns session construction, option forwarding, usage aggregation, and UI projection.
Mechanism
Pi compatibility metadata covers provider-specific capabilities including:
- cache-control format;
- long retention support;
- cache control on tools;
- session-affinity headers and formats.
For Anthropic-style routes, installed Pi documentation describes breakpoints on:
- system prompt;
- final tool definition;
- latest eligible message content.
OpenAI-compatible adapters support cache keys, retention, affinity metadata, and—in eligible adapters—deferred tools.
Prefix identity and invalidators
The effective prefix includes more than Pi’s default system prompt:
system prompt
+ context/resources and the always-listed skill names/descriptions
+ full `SKILL.md` content only after the skill is explicitly read
+ appended system instructions
+ active-tool snippets and guidelines
+ tool schemas
+ transcript
Likely invalidators include:
- capability activation or tool replacement;
- tool schema/order changes;
- prompt snippets and guidelines;
- resource, skill, or project-context changes;
- extension reload;
- model/provider change;
- child-specific agent instructions;
- structured-output schema;
- compaction or branch navigation.
OpenPI’s monotonic capability loading reduces repeated removal/re-addition but does not make the prefix immutable.
Writes, reads, TTL, and cost
- Provider adapters report normalized
cacheReadandcacheWrite. - Pi computes prompt size as
input + cacheRead + cacheWrite. PI_CACHE_RETENTION=longcan request longer provider retention where supported.- Compaction and branch-summary calls use
cacheRetention: "none". - Cost estimation uses model/provider input, cache-read, and cache-write prices when available.
Sessions, children, forks, workflows
- Each direct child receives a fresh resource loader and
AgentSession. - Children inherit model/thinking defaults, but receive fresh sessions without the parent transcript or client cache identity. Provider-side automatic reuse for any coincidentally compatible prefix remains provider-dependent and unproven.
- Child prompts may differ by type, tool allowlist, schema, trust, working directory, skills, and appended instructions.
- Workflow operators may reuse one in-memory child session during a run.
- Workflow replay is persisted-result reuse, not prompt caching.
- Child usage is not automatically represented by the parent footer.
Compaction interaction
Pi intentionally avoids low-value cache writes for the summary request and resets its miss-comparison baseline after compaction or branch summary. The next normal request should be treated as a structurally new comparison epoch.
Observability
Pi exposes:
- cache read/write token totals;
- latest cache-hit percentage;
- a heuristic estimated miss warning;
- cumulative usage and cost.
OpenPI additionally shows a branch-local cumulative cache N%.
Limitations:
- percentages do not identify which prefix segment hit;
- Pi’s miss warning ignores estimated misses at or below 1,024 tokens;
- branch-local and whole-session projections differ;
- compaction can reduce workflow usage reconstructed from retained messages;
- replay produces no provider usage.
3.2 OpenAI Responses API / Codex CLI
Fixed-revision Codex mechanism
At a9e447a69dee4f2789dd8d8c776e314772c1f049, Codex sends prompt_cache_key on Responses requests. The default is the session ID. Internal sessions with a parent thread use InternalSource:parent_thread_id; ordinary subagents otherwise retain their own session-derived key. Guardian review sessions have a dedicated guardian:parent_thread_id override, so they share a stable review scope without impersonating the parent main-turn key.
WebSocket incremental reuse is a separate context-state optimization: Codex uses previous_response_id only when request properties such as model, instructions, tools, reasoning, service tier, cache key, and text settings remain compatible and the new input extends the prior input. This is not provider cache-hit evidence.
Documented API mechanism
OpenAI prompt caching is automatic for eligible, sufficiently large exact prefixes. Responses supports:
prompt_cache_key;- default in-memory retention;
- optional extended retention up to 24 hours where eligible;
usage.input_tokens_details.cached_tokens.
previous_response_id is context-state linkage, not proof of a prompt-cache hit. It also has inheritance constraints: newly supplied instructions are not simply inherited from the previous response, and it cannot be combined with a conversation object in the documented cases.
Invalidators
At the API-contract level, changes to any early request component may reduce or eliminate reuse:
- system/developer instructions;
- tools or schemas;
- model;
- provider/endpoint;
- earlier messages;
- request settings that affect serialization.
For Codex CLI, any approval, sandbox, tool, compaction, or fork change matters only if it changes the provider-visible prefix or cache-key scope. The fixed source proves key derivation and compatibility checks; it does not prove provider-side matching or eviction.
Writes, reads, TTL, and cost
- Cache creation is automatic rather than exposed as a create operation.
- Reads are proven only by
cached_tokens. - A successful response with zero cached tokens is a normal miss.
- No public stable cache ID or hit/miss boolean is exposed.
- Internal eviction, sharding, region scope, and physical key composition are not public.
Compaction and ZDR
Responses supports provider compaction items and separate accounting. Documentation describes a ZDR-compatible compaction path, but this does not make prompt caching itself a ZDR guarantee. Extended retention must be evaluated against current account, model, and data-control eligibility.
3.3 Anthropic Messages API / Claude Code
Documented API mechanism
Anthropic supports:
- automatic prompt caching;
- explicit
cache_controlbreakpoints; - markers on tools, system content, and messages;
- up to four documented breakpoints.
The logical hierarchy is:
tools → system → messages
Changing an earlier component invalidates reuse after that point. Appending messages can preserve the earlier prefix; editing an earlier message cannot.
Writes, reads, TTL, and cost
Usage separates:
- uncached
input_tokens; cache_creation_input_tokens;cache_read_input_tokens;- output tokens.
Documented ephemeral lifetimes include:
- 5 minutes;
- 1 hour where supported.
Successful reads refresh the documented lifetime. Cache writes are priced differently from ordinary input and reads; exact rates and minimum cacheable prefix sizes vary by model.
Claude Code behavior
Public Claude Code documentation says caching is automatic and that structurally compatible workflow fan-out may reuse a prefix. Documented compatibility includes:
- model;
- effort;
- agent type;
- tools;
- schema;
- working directory.
Compatible siblings may wait approximately five seconds for an initial worker to establish the cache.
However, the following are not public implementation contracts:
- emitted marker placement;
- serialized prompt representation;
- physical cache key;
- ordinary parent/subagent sharing;
- exact settings or permission invalidation;
- retry and refresh behavior.
Compaction
Anthropic context editing or Claude Code compaction changes the provider-visible request. Retained byte-equivalent prefix material may still hit, while inserted summaries and rewritten history form new boundaries. Claude Code’s exact sequencing is not public.
3.4 Hermes Agent
Mechanism
Hermes is an explicit client-side cache planner for Anthropic-compatible routes:
- decorates request-local messages without mutating stored history;
- supports ephemeral 5-minute and optional 1-hour markers;
- caps wire-visible markers at four;
- can mark a declared static system prefix separately from its suffix;
- otherwise marks the system and latest cacheable completed turns.
Qwen/Alibaba routes clamp a requested one-hour TTL to five minutes according to Hermes’ provider-specific logic.
Stable-prefix registry
Hermes has a process-local LRU registry for builder-declared stable skill, webhook, and cron scaffolding. Volatile invocation tails are excluded. The registry is bounded to 32 entries and four million retained characters.
This local registry plans stable boundaries; it is not itself the provider prompt cache.
Sessions and children
Hermes resolves prompt-cache scope through compression lineage:
- compaction-created session rotations can retain the logical root scope;
- branches, delegates, and tool-created children remain isolated.
This explicitly distinguishes continuation after compression from a true fork.
Compaction
Default in-place compression keeps the live session ID while replacing middle history with a summary. Only unchanged prefix material remains reusable.
Hermes also supports native Responses compaction checkpoints for eligible direct OpenAI/Codex routes. Eligibility is re-evaluated after provider/model changes; issuer-incompatible checkpoints are dropped. xAI routes are not treated as eligible for OpenAI native compaction.
Observability
Plugin-facing usage includes input, output, cache read/write tokens, total tokens, and estimated cost. The audit did not find a dedicated main-turn cache dashboard.
3.5 Grok Build / xAI
Mechanism
Grok Build uses request-shape stability and cache identity:
- auxiliary side calls set
prompt_cache_keyto the parent session ID; - the parent session ID is also retained as conversation identity for backends that do not forward the key;
- model, reasoning effort, tools, hosted tools, and history are preserved;
- side-call-specific instructions are appended after the shared prefix.
/btw, recap, and turn-summary calls intentionally reuse the parent identity. These are cache-sharing auxiliary calls, not independent child agents.
Invalidators and anti-thrash
Compaction prework is guarded by:
- conversation-prefix fingerprint;
- model slug;
- prefix length.
Cached prework is rejected after prefix/model changes and cleared on model switch, rewind, apply, and edits.
Recap and summary work use idle gates, epochs, in-flight guards, and cancellation to avoid paying for work immediately invalidated by new user input.
Observability
Grok Build projects provider usage into:
- total prompt tokens;
- cached tokens;
- cache-creation tokens;
- uncached tokens;
- read/write rates;
- whether the backend forwarded the cache key.
TTL/privacy
The audited source proves key forwarding and usage accounting, but does not establish xAI’s exact TTL, cache isolation boundary, encryption, logging, or interaction with zero-retention settings. Those remain policy-level unknowns.
3.6 Gemini CLI / Gemini API
Gemini CLI mechanism
At the fixed revision, Gemini CLI sends ordinary generation requests with a generated system instruction and conversation history. The audit found no:
cachedContents.create;- explicit cache name;
- cache get/update/delete lifecycle;
- attached
cachedContentfield.
Therefore the CLI relies on eligible Gemini backend implicit caching. Its documentation limits token caching to Gemini API-key and Vertex authentication, excluding OAuth/Code Assist.
Gemini API distinction
The API separately supports explicit named cache resources:
- create cached content;
- receive a resource name;
- reference it in generation;
- update TTL/expiry;
- delete it.
This API capability must not be attributed to the audited CLI.
Identity and invalidators
Implicit identity is based on the provider-visible request prefix rather than the CLI session ID. Invalidators include:
- regenerated system instruction;
- memory or approval-state changes;
- tools;
- model;
- rewritten history;
- compression.
Resuming a local session reconstructs history but does not restore an explicit provider cache object.
Writes, reads, TTL, and cost
The CLI records cachedContentTokenCount and exposes savings through /stats. It does not control implicit-cache TTL.
For explicit API caches:
- TTL/expiry is part of the resource;
- cached-token use and storage duration have separate pricing dimensions;
- resource deletion is available;
- current model, region, minimum-size, and pricing rules must not be hardcoded from a stale table.
3.7 OpenCode
Mechanism
OpenCode preserves provider-specific semantics rather than introducing a universal cache object:
- Anthropic/OpenRouter/Alibaba cache-control options;
- Bedrock cache points;
- OpenAI-compatible cache controls;
- GitHub Copilot-specific controls;
- provider cache keys derived from
sessionIDfor selected providers; - gateway automatic caching where supported.
Accounting
OpenCode normalizes heterogeneous provider metadata into:
- uncached input;
- cache reads;
- cache writes;
- output;
- separate cache-read/write pricing.
These fields are persisted in session records.
Sessions, forks, and subagents
- Forks receive a new session ID after cloning and remapping messages.
- Forks receive new session IDs. Selected adapters derive cache keys from those IDs, but this is not universal and does not prevent provider automatic reuse of a compatible prefix.
- Subtasks use their own execution path and should be treated as child-scoped.
- Title and summary calls can have separate prompts and should not be assumed to reuse the main conversation cache.
Pruning and compaction
OpenCode distinguishes:
- pruning old completed tool outputs after thresholds;
- compaction by a dedicated agent that carries a head, recent tail, and previous summary.
Both change the provider-visible request and therefore create likely cache boundaries even if a session-level key remains unchanged.
4. Prefix identity and common invalidators
Across providers, the portable invariant is:
Reuse requires both compatible cache scope and a sufficiently stable provider-visible prefix.
Common invalidators are:
- model, provider, endpoint, account, or region changes;
- system/developer instruction changes;
- tool additions, removal, reordering, or schema changes;
- dynamic prompt snippets and status text;
- skills, project instructions, memory, or context-file changes;
- working-directory or trust changes that alter injected context;
- effort/reasoning or structured-output settings;
- editing earlier messages;
- pruning, compaction, rewind, or branch navigation;
- fork/subagent creation where a new cache principal is used.
A stable session ID or cache key cannot compensate for a changed prefix. Conversely, a new client session might still obtain provider reuse if its scope and exact prefix remain compatible; most audited clients conservatively avoid relying on that.
5. Writes, reads, TTL, and cost accounting
Correct accounting requires separate buckets:
uncached input
cache creation/write
cache read
output
explicit-cache storage, where applicable
Provider behavior differs:
- OpenAI: automatic write; cached input exposed through
cached_tokens; default in-memory or eligible 24-hour retention. - Anthropic: explicit/automatic breakpoints; separate creation/read usage; documented 5-minute and eligible 1-hour lifetimes.
- Gemini implicit: backend-managed; cached token metadata only.
- Gemini explicit: named object with TTL/expiry, deletion, cached use, and storage billing.
- xAI: key and usage buckets are documented, but exact retention/privacy details were not established by the audit.
- Pi/OpenCode/Hermes/Grok Build: normalize or expose provider-reported buckets; they do not prove hidden server behavior.
A cache miss is not an execution failure. Cost savings must be calculated from provider usage and current pricing, not inferred from latency or the presence of a cache option.
6. Session, subagent, side-call, and fork behavior
Three patterns emerge:
-
Separate principal by default
OpenPI children, OpenCode forks/subtasks, Hermes branches/delegates, and likely independent agents use distinct sessions or scopes. -
Deliberate compatible fan-out
Claude Code publicly documents compatible sibling fan-out reuse, including a short establishment wait. -
Parent-sharing auxiliary calls
Grok Build deliberately gives recap and/btwside calls the parent key while preserving the parent prefix.
The third pattern should not be generalized to arbitrary subagents. Sharing a cache identity when tools, trust, working directory, tenant, or instructions differ can create privacy and correctness risks.
7. Compaction and pruning interaction
Compaction introduces at least two requests:
- the summary/compaction operation;
- the next normal request containing rewritten context.
The summary call may have its own cache policy. The next request has a changed prefix wherever history was removed or a summary inserted.
Notable policies:
- Pi disables cache retention for compaction and branch-summary calls.
- Hermes preserves logical scope across compression lineage but accepts byte-level prefix changes.
- Grok Build fingerprints compaction prework and rejects stale results.
- Gemini CLI rewrites/truncates history.
- OpenCode separately prunes tool output and generates compaction summaries.
- OpenAI native compaction state remains distinct from prompt-cache evidence.
A compaction event should therefore reset cache-comparison heuristics without erasing historical usage totals.
8. Observability
What can be reported truthfully
- provider-reported cached tokens;
- cache-creation/write tokens;
- uncached input and output;
- requested retention mode;
- whether a client forwarded a key or marker;
- client-side prompt/cache-key fingerprints;
- session/child/compaction/replay boundaries;
- estimated cost based on current model pricing.
What cannot be proven from client telemetry
- physical server cache ID;
- exact cached segment;
- server-side eviction reason;
- cross-region or cross-key sharing;
- whether an unreported proxy cache was used;
- encryption or deletion guarantees;
- semantic equivalence;
- provider retention status inferred from a cache hit.
OpenPI’s existing request-fingerprint benchmark can detect changes to prompt_cache_key and payload shape, but cannot prove provider reuse.
9. Security, privacy, and ZDR
Prompt caching is provider-side reuse of a cached representation or computation associated with request prefixes, not a security boundary. The storage form—raw prompt, transformed representation, KV state, or something else—must remain unknown unless the provider contract documents it.
Required distinctions:
- local session deletion;
- provider implicit-cache expiration;
- explicit cache-resource deletion;
- conversation-state deletion;
- ZDR or modified-abuse-monitoring eligibility.
Provider-specific findings:
- Anthropic documents organization/workspace isolation, but not every same-workspace cross-key detail.
- OpenAI extended retention must not be equated with ZDR; eligibility is account/model dependent.
- Gemini explicit cache resources should be treated as sensitive objects and deleted on tenant/session teardown where required.
- Gemini implicit caches are not enumerable or individually revocable by the CLI.
- xAI cache retention, scope, encryption, and ZDR interaction remain unknown here.
- Pi/OpenPI long-retention options can extend provider retention and should remain explicit.
- Child/fork cache identities should not be shared across trust, tenant, credential, or working-directory boundaries.
Telemetry should record hashes/fingerprints and usage metadata without logging prompt bodies, credentials, cache-resource names, or tenant-sensitive cache keys.
10. Strengths and weaknesses
OpenPI / Pi
Strengths
- Correct provider-adapter ownership.
- Monotonic capability loading reduces avoidable prompt churn.
- Fail-closed child tool surface.
- Compaction avoids low-value writes.
- Replay is conceptually separate from provider caching.
Weaknesses
- Aggregate percentages obscure request type and prefix segment.
- Parent UI does not naturally account for child usage.
- Branch-local and session-wide metrics differ.
- Adapter behavior is difficult to verify without fixed
pi-aisource. - Capability activation still mutates the prompt/tool prefix.
Codex / OpenAI
Strengths
- Automatic caching with explicit cached-token accounting.
- Optional cache affinity and extended retention.
- Server-side context state and compaction primitives.
Weaknesses
- No public cache ID or invalidation reason.
- State linkage is easily confused with caching.
- Internal partitioning and eviction are undisclosed.
Claude Code / Anthropic
Strengths
- Explicit multi-boundary API design.
- Separate read/write accounting.
- Documented compatible fan-out optimization.
- Short default TTL with an eligible longer option.
Weaknesses
- Claude Code implementation is proprietary.
- Exact breakpoint placement and ordinary subagent behavior are unknown.
- Prefix mutations from project settings are not fully specified.
Hermes
Strengths
- Explicit stable-prefix planning.
- Bounded local registry.
- Compression lineage separates continuation from forks.
- Provider/model eligibility is rechecked.
Weaknesses
- More client-side policy and complexity.
- Some provider behavior relies on route-specific assumptions.
- No dedicated main-turn cache dashboard was found.
Grok Build
Strengths
- Deliberate side-call prefix preservation.
- Strong stale-result fingerprints and cancellation.
- Rich read/write/uncached observability.
Weaknesses
- Parent-key sharing is safe only for tightly controlled side calls.
- xAI retention and privacy contracts remain insufficiently established.
Gemini CLI / API
Strengths
- CLI records cached-token usage without pretending to own the cache.
- API offers a real explicit cache lifecycle when applications need it.
Weaknesses
- CLI has no explicit lifecycle or deletion control.
- Session resume can be mistaken for cache restoration.
- Compression changes request identity.
- Explicit-cache storage adds retention and billing complexity.
OpenCode
Strengths
- Preserves provider-specific controls.
- Strong normalized read/write accounting.
- Forks naturally receive distinct identities.
- Pruning and compaction are explicit mechanisms.
Weaknesses
- A session-derived key is only one part of prefix identity.
- Provider semantics remain heterogeneous.
- Background calls may fragment metrics and prefixes.
11. OpenPI/Pi ownership and current gaps
Current ownership
- Pi session layer: prompt assembly, transcript, compaction, branch lifecycle, event stream.
pi-ai: provider cache markers, keys, retention options, affinity headers, and usage normalization.- OpenPI: capability loading, child/workflow lifecycle, trust/tool boundaries, replay, and UI projections.
- Provider: actual cache storage, matching, isolation, eviction, and authoritative usage.
Gaps
- Architecture and terminology are not documented in one canonical place.
- Fixed adapter provenance is incomplete when diagnosing installed
pi-aibehavior. - Retention mode and its privacy implications need explicit documentation.
- Existing fingerprints detect request mutation but do not prove provider reuse.
- Per-turn diagnostics and boundary-reason UI belong to observability: 从累计 cache 命中率升级到逐 turn 的 prompt-cache 失效诊断 #156; cumulative branch-stat collection belongs to perf(model-info): 每次生命周期 refresh 都完整扫描 Session branch #188.
12. Relationship to existing Issues
- observability: 从累计 cache 命中率升级到逐 turn 的 prompt-cache 失效诊断 #156 owns per-turn cache invalidation diagnostics, boundary reasons, and related UI implementation.
- perf(model-info): 每次生命周期 refresh 都完整扫描 Session branch #188 owns the performance and redesign of cumulative branch cache-stat collection.
- context: 研究可回收的探索 checkpoint/rewind,不把它等同于 context_pivot #154 owns checkpoint/rewind behavior; this document only explains its cache boundary.
- memory: 研究 Project-scoped Durable Learning,并严格区分事实、经验与 Skill #167 owns durable memory; this document only explains when injected memory can alter a request prefix.
- design: 研究跨能力的可恢复资源引用,但不引入 OpenPI 全局资源路由器 #157 owns recoverable resource references; workflow replay remains distinct from provider caching.
This Issue is documentation-only: taxonomy, ownership, evidence levels, cross-system comparison, and non-goals.
13. Minimal Pi-native recommendations
-
Document ownership instead of adding an OpenPI cache manager.
Keep provider controls and normalized usage inpi-ai; keep canonical session/compaction state in Pi. -
Keep implementation work in the existing owners.
Per-turn projections, boundary reasons, and provider-evidence-vs-inference diagnostics belong to observability: 从累计 cache 命中率升级到逐 turn 的 prompt-cache 失效诊断 #156. Any redesign of cumulative branch cache statistics belongs to perf(model-info): 每次生命周期 refresh 都完整扫描 Session branch #188. This Issue documents architecture and terminology only; it does not duplicate either implementation scope. -
Define the evidence contract in documentation.
Provider-reported read/write tokens are evidence; keys, markers, latency, and client-derived boundary reasons are not proof of a hit. Replay means “no provider call,” never “cache hit.” -
Keep children and forks separate by default.
Preserve current distinct sessions and fail-closed authority. Only introduce parent-sharing for a narrowly specified side-call primitive with identical model, tools, trust, schema, working directory, and prefix. -
Strengthen reproducibility, not server simulation.
Extend the existing benchmark/fingerprint tooling to record sanitized request-shape hashes, cache-key hashes, provider-reported token buckets, revision, and request class. -
Escalate adapter normalization upstream.
Any missing provider cache usage fields or retention controls should be fixed inpi-ai, not duplicated in OpenPI.
14. Explicit non-goals
- Building an OpenPI-owned provider prompt cache.
- Persisting or replaying hidden model KV state.
- Treating workflow replay as provider caching.
- Sharing parent cache identities with arbitrary subagents.
- Creating a provider-neutral explicit-cache lifecycle over incompatible APIs.
- Inferring hits from latency, session IDs, keys, or markers.
- Logging prompt content or sensitive cache identifiers.
- Promising deletion of implicit provider caches.
- Encoding provider pricing or TTLs as timeless constants.
- Reordering tools or prompts solely for caching without correctness and authority review.
- Replacing Pi’s session, memory, compaction, or provider ownership.
15. Unknowns and preserved disagreements
- Exact
[email protected]adapter source must be pinned before making adapter-level claims. - Claude Code’s marker placement, serialization, and ordinary subagent cache sharing are not public.
- Anthropic documentation describes exact prefix matching, but the provider’s internal serialized representation is not public; “byte-identical” should be understood at the documented request-prefix level, not as a claim about hidden storage.
- xAI retention, isolation, encryption, logging, and ZDR interaction remain unknown.
- Gemini implicit-cache eviction and revocation are provider-controlled.
- OpenAI physical key composition, partitioning, eviction, and region behavior are not public.
- Compatibility metadata does not prove that an OpenAI-compatible proxy honors a cache option.
- A model change is treated as a billable miss by Pi’s heuristic, but provider-side cross-model behavior is not observable; the heuristic is intentionally conservative.
- Hermes preserves scope across compression lineage, while Pi resets cache comparison after compaction. These are not necessarily contradictory: one preserves logical affinity; the other avoids claiming continuity after prompt reconstruction.
- Grok Build shares parent identity with controlled side calls, while OpenPI/OpenCode isolate children. The disagreement reflects different semantics—auxiliary continuation versus independent child authority—not a universal best practice.
16. Acceptance criteria
- Documentation distinguishes prompt/KV caching, context state, memory, compaction, pruning, and replay.
- Installed OpenPI, Pi, and
pi-airevisions are recorded for every cache diagnosis. - Documentation defines latest-request, branch-cumulative, session-cumulative, and child usage, while implementation remains tracked in observability: 从累计 cache 命中率升级到逐 turn 的 prompt-cache 失效诊断 #156/perf(model-info): 每次生命周期 refresh 都完整扫描 Session branch #188.
- Provider-reported uncached input, cache read, cache write, output, and cost are retained as separate fields where available.
- Replay is explicitly reported as zero provider calls, not a cache hit.
- Compaction and branch-summary requests remain distinguishable from normal turns.
- Documentation labels any expected cache-boundary reason as inference and defers its implementation to observability: 从累计 cache 命中率升级到逐 turn 的 prompt-cache 失效诊断 #156.
- No telemetry logs prompt bodies, credentials, tenant identifiers, raw cache-resource names, or raw affinity keys.
- Children/forks retain separate cache principals unless a reviewed, narrow side-call contract proves identical authority and request prefix.
- A documentation verification matrix covers tool-surface mutation, model change, compaction, branch navigation, child isolation, and replay semantics without creating a second test/telemetry project here.
- Provider cache controls remain owned by
pi-ai; OpenPI introduces no parallel cache state. - Retention documentation warns that long retention is provider-side data retention and not a ZDR guarantee.
- Benchmarks record sanitized request/cache-key fingerprints and provider-reported usage without claiming hidden server behavior.
- Coverage records five completed workstreams, seven grouped subjects, fixed-source versus documentation-only evidence, and no failed workstream.
17. Primary sources
OpenPI / Pi
- OpenPI revision:
2a69d3f32994da4123f1312b7fa84ef3d6119be1 - Pi tag: https://github.com/earendil-works/pi/tree/v0.84.3
- Installed Pi documentation:
docs/models.mddocs/extensions.mddocs/custom-provider.mddocs/environment-variables.md
- OpenPI evidence:
extensions/shared/tool-surface.tsextensions/shared/child-session.tsextensions/subagents/src/backends/pi.tsextensions/workflows/runner.tsextensions/workflows/replay-safety.tsextensions/model-info/index.tsscripts/benchmark-provider-request-fingerprint.ts
OpenAI
- https://platform.openai.com/docs/guides/prompt-caching
- https://platform.openai.com/docs/api-reference/responses/create
- https://platform.openai.com/docs/guides/conversation-state
- https://platform.openai.com/docs/guides/conversation-state#compaction-advanced
- https://platform.openai.com/docs/guides/your-data
- Codex fixed revision: https://github.com/openai/codex/tree/a9e447a69dee4f2789dd8d8c776e314772c1f049
codex-rs/core/src/client.rscodex-rs/core/src/guardian/review_session.rscodex-rs/core/src/session/session.rs
Anthropic / Claude Code
- https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
- https://docs.anthropic.com/en/api/messages
- https://docs.anthropic.com/en/docs/build-with-claude/context-editing
- https://code.claude.com/docs/en/costs
- https://code.claude.com/docs/en/workflows
- https://code.claude.com/docs/en/sub-agents
- https://github.com/anthropics/anthropic-cookbook/tree/main/prompt_caching
Hermes Agent
Fixed revision: cbd8de8ad64530be01efea23b7764d5c37c634ed
Key files:
agent/prompt_caching.pyagent/prompt_cache_boundary.pyagent/prompt_cache_scope.pyagent/native_compaction.pyagent/codex_responses_adapter.pyagent/plugin_llm.pywebsite/docs/developer-guide/context-compression-and-caching.md
Grok Build / xAI
Fixed revision: c2ad97f87aea4303b6000a2c22128bc91ee76c9b
Key files:
crates/codegen/xai-grok-shell/src/session/acp_session_impl/side_call.rscrates/codegen/xai-grok-shell/src/session/compaction.rscrates/codegen/xai-grok-shell/src/session/compaction_config.rscrates/codegen/xai-grok-shell/src/session/acp_session_impl/recap.rscrates/codegen/xai-grok-shell/src/session/acp_session_impl/rewind.rs
Official sources:
- https://docs.x.ai/docs/guides/prompt-caching
- https://docs.x.ai/docs/api-reference
- https://x.ai/legal/enterprise-privacy-policy
- https://x.ai/legal/terms-of-service
Gemini
Gemini CLI revision: 812f7a2bcf20b6e80e2e50c3c8fa8e26567bc1e8
Key files:
packages/core/src/core/client.tspackages/core/src/core/geminiChat.tspackages/core/src/core/turn.tsdocs/cli/token-caching.mddocs/cli/session-management.mddocs/cli/telemetry.md
Official sources:
- https://ai.google.dev/gemini-api/docs/caching
- https://ai.google.dev/gemini-api/docs/caching#explicit-caching
- https://ai.google.dev/gemini-api/docs/caching#implicit-caching
- https://ai.google.dev/gemini-api/docs/pricing
- https://ai.google.dev/api/caching
OpenCode
Fixed revision: 8615731d46153dd29b89e205fb55b2cc16205cb0
Key files:
packages/opencode/src/provider/transform.tspackages/opencode/src/provider/provider.tspackages/opencode/src/session/session.tspackages/opencode/src/session/compaction.tspackages/opencode/src/session/prompt.ts
Activity
627150795 commentedon Aug 28, 2026
Hi! I would like to work on this documentation issue.
I will document prompt/KV caching separately from Session context, memory, compaction, pruning, summarization, and replay; define Pi/OpenPI/provider ownership, prefix identity and invalidation boundaries, cache-read/write/TTL and accounting evidence, child/fork/workflow behavior, and safe observability. I will not infer provider internals or add a cache registry.
627150795 commentedon Aug 28, 2026
Update: the cache ownership and lifecycle contract is implemented in PR #249: #249
Validation completed:
git diff --cached --check,bun run lint, andbun run typecheckpassed. This is documentation-only and does not change runtime behavior. The PR uses the repository template and will close this issue when merged.tt-a1i commentedon Aug 30, 2026
相关设计讨论已展开:Tool lifecycle across compaction #311。它进一步区分 Runtime authority state、模型可见 context、Provider-native tool reference 与 compaction 后的新 cache epoch;不新增 OpenPI-owned cache,也不把 summary 当作权限来源。