Skip to main content

Module prefix_cache

Module prefix_cache 

Source
Expand description

Prefix-cache stability manager (inspired by Reasonix’s Pillar 1).

DeepSeek’s automatic prefix caching activates only when the exact byte prefix of a request matches the prior request. Any system-prompt drift, tool-list reordering, or message-rewriting busts the cache for every token after the changed byte.

This module provides a PrefixStabilityManager that:

  1. Fingerprints the immutable prefix (system prompt + tool specs) at session start, using SHA-256 for strong collision resistance.
  2. Verifies the current prefix against the pinned fingerprint before every request.
  3. Attributes every change: a header change the engine declared (/model, /mode, goal edits, MCP or deferred-tool activation, session sync) re-pins under a logged reason; an undeclared change is drift — it is recorded and reported, and the original pin stays so later checks keep counting the miss instead of quietly adopting it.
  4. Emits events so the TUI can surface stability to the user.

The invariant this guards: after session start, system and tools are frozen bytes; history only grows; a miss is allowed only when we log why.

§Three-region model (from Reasonix)

┌─────────────────────────────────────────┐
│ IMMUTABLE PREFIX                        │ ← fixed for session
│   system + tool_specs                    │   cache hit candidate
├─────────────────────────────────────────┤
│ APPEND-ONLY HISTORY                     │ ← grows monotonically
│   [assistant₁][tool₁][assistant₂]...    │   preserves prefix of prior turns
├─────────────────────────────────────────┤
│ LATEST USER TURN                        │ ← the only new content per request
└─────────────────────────────────────────┘

Structs§

CachedCatalog
One entry in ToolCatalogCache. Production only needs the pre-computed SHA-256 digest of the in-order joined catalog.
PrefixChange
A change record describing what drifted in the prefix.
PrefixFingerprint
A snapshot of the immutable prefix’s fingerprint.
PrefixHistoryEntry
One attributed prefix event: a declared header change (re-pinned) or an undeclared drift (pin kept).
PrefixStabilityManager
Monitors and manages prefix-cache stability across turns.
ToolCatalogCache
Bounded LRU cache of (tool_set_identity) -> sha256_hex.

Enums§

PrefixCheck
Outcome of PrefixStabilityManager::check.

Constants§

CONTEXT_UPDATE_MAX_BYTES
CONTEXT_UPDATE_MAX_LINES
Bounded line delta between the session context the model last saw and a fresh composition, rendered as a <context_update> user-role message.

Functions§

context_update_message
system_prompt_text
Extract the system prompt text from an optional SystemPrompt, returning an owned String. This is used for prefix fingerprinting and avoids lifetime/leak issues with the rare SystemPrompt::Blocks case.