kv-prefix-guard
Wire-protocol context partitioning, $K$-bounded cache breakpoint scheduling ($K \le 4$), and commit-time relational artifact distillation for multi-turn LLM KV-caches ($86.2%$ context token reduction, $95.4%$ block-aligned KV-cache hit rate, and $6.74\times$ lower net prefill cost).
- Author: David Charles Michael (ORCID:
0009-0007-8679-6941| DOI:10.5281/zenodo.24488870|davidchar@gmail.com) - Built For Modern Applied AI & Context Engineering Stacks: Multi-turn coding agents (
Claude Code,Cursor,Windsurf,OpenHands,SWE-agent), Model Context Protocol (MCP) servers and clients, AI gateways (LiteLLM,OpenRouter,Portkey), and agent orchestration frameworks (LangGraph,LangChain,LlamaIndex,Vercel AI SDK,PydanticAI,AutoGen,CrewAI,DSPy,SmolAgents,Mastra). - High-Throughput Cache-Preserving Alternative To: Retroactive mid-prefix token pruners (
LLMLingua,LongLLMLingua,Selective Context), sliding-window chat history truncation, and unnormalized dynamic system prompts that invalidate downstream KV-cache blocks. - Compatible With All 4 Frontier & Open-Weight KV-Cache Protocols:
- Explicit Breakpoint Caching (
[Tools] -> [System] -> [Messages], $K \le 4$cache_control: {"type": "ephemeral"}): Anthropic Claude API (including Claude 5.5 Opus / Sonnet and extended thinking blocks). - Implicit Block-Aligned Prefix Caching ($\ge 1,024$ tokens in $128$-token blocks): OpenAI GPT API (including GPT-6, GPT-5, and reasoning series).
- Isolated System-Context Caching (
systemInstruction+contents): Google Gemini API (including Gemini 4 and 3.8 series). - Radix-Tree Block Hashing (
PagedAttention/RadixAttention, $16$- and $64$-token blocks):vLLMandSGLangserving open-weight Meta Llama 4, DeepSeek, and Qwen deployments.
- Explicit Breakpoint Caching (
Why Use kv-prefix-guard Instead of LLMLingua or Sliding Windows?
In causal self-attention, the key and value vectors at token position $j$ depend on all tokens in $[0, j-1]$. If an application edits tokens inside an earlier turn (via retroactive token dropping, sliding-window eviction, unordered tool JSON serialization, or per-turn system timestamps), every cached KV block after the edit offset is invalidated. Under discounted cache-read pricing ($\alpha = 0.10$), triggering a cache miss costs more than leaving the prompt uncompressed whenever the retained token ratio exceeds $r > \alpha$.
Pipeline / Baseline (MultiTurnCacheBench-1200, $14,400$ turns) |
Track A Hit (%) | Track B Hit (%) | Track C Hit (%) | Overall KV Hit (%) | Context Token Reduction (%) | Structural Contract Survival (%) | Relative Billed Prefill Cost (%) |
|---|---|---|---|---|---|---|---|
| Uncompressed Append-Only | 99.1% | 99.1% | 99.5% | 99.3% | 0.0% | 100.0% | 100.0% ($1.00\times$) |
| Naive Dynamic System / Tools | 0.0% | 0.0% | 0.0% | 0.0% | 0.0% | 100.0% | 410.2% ($4.10\times$ worse) |
| Sliding-Window Eviction ($W = 4$) | 27.4% | 27.2% | 15.7% | 21.3% | 44.5% | 61.2% | 188.5% ($1.89\times$ worse) |
Mid-Prefix Salience Pruner (LLMLingua-Style) |
8.0% | 8.6% | 4.5% | 6.0% | 46.6% | 83.6% | 209.3% ($2.09\times$ worse) |
| Static Skeleton (No Two-Zone Decoupling) | 21.2% | 25.9% | 14.7% | 18.4% | 86.2% | 98.5% | 48.6% ($2.06\times$ cheaper) |
kv-prefix-guard (Ours) |
94.6% | 93.5% | 96.3% | 95.4% | 86.2% | 98.5% | 14.8% ($6.74\times$ cheaper vs. Uncompressed, $14.1\times$ vs. LLMLingua) |
5 Core Capabilities & Architecture
- Canonical
[Tools] -> [System]Normalization & Two-Zone Splitting (partitioner.rs): Sorts tool JSON schema keys deterministically via recursiveBTreeMapstructures, anchors session dates to a stable UTC calendar day in Zone 1 ([LIVE TEMPORAL CONTEXT: Date: YYYY-MM-DD]), and isolates volatile MCP tool telemetry and dynamic format overrides in the Zone-2 user tail. - Provider-Aware Monotonic Breakpoint Scheduler ($K \le 4$,
breakpoints.rs): Pins breakpoint $1$ on the immutable Zone-1 system anchor and advances up to $3$ ephemeral checkpoints across committed assistant turns for Anthropic Claude, mapsisolated_system_instructionandmodelroles for Google Gemini, and stripscache_controlfields for strict OpenAI GPT andvLLM/SGLangvalidators. - Signature-Safe Scratchpad Scrubber (
pruners.rs): Removes unsigned inline XML planning blocks (<scratchpad>,<thought>,<plan>,<think>) and operational status lines upon turn commit while leaving cryptographically signed<thinking signature="...">blocks untouched. - Idempotent Commit-Time Relational & AST Distiller (
distiller.rs): Condenses completed HTML5/Canvas/Three.js WebGL applications, Mermaid architecture diagrams, 3D voxel scenes, multi-section legal/technical documents, and general source code once at commit time ($\mathcal{D}(\mathcal{D}(a_t)) = \mathcal{D}(a_t)$) into $120\text{--}180$ token relational blueprints and brace-depth AST skeletons that preserve $100%$ of top-level DOM#idselectors, state stores, function signatures, and directed event edges. - Active-Turn Bulk Literal Pruners & Cold-Start Session Compaction: Strips Base64 data URIs ($\ge 60$ bytes), long SVG
d="..."vector paths ($\ge 100$ bytes), numeric WebGL float arrays ($\ge 150$ bytes), and repeated MermaidclassDef/stylelines during active code refinement turns, and collapses superseded blueprints when resuming saved sessions.
Tri-Registry Installation & Quickstart
1. Python (PyPI, Native PyO3 C-Extension)
# A. Canonicalize unordered MCP / OpenAI / Anthropic tool JSON schemas for prefix-hash invariance
=
# B. Idempotent commit-time distillation (preserves signed thinking + DOM/Mermaid/AST contracts)
=
=
# C. Brace-depth AST code skeletonization (TypeScript / Python / Rust / Go)
=
2. JavaScript / TypeScript (npm, Zero-Dependency WebAssembly)
import {
canonicalizeToolsJson,
distillTurnForCommit,
pruneCodeForActiveRefinement,
} from 'kv-prefix-guard';
// 1. Canonicalize tool declarations so dictionary key order never invalidates block 0
const toolsJson = canonicalizeToolsJson(JSON.stringify([{ name: 'mcp_search', type: 'object' }]));
// 2. Distill completed assistant turns once before appending to conversation history
const blueprint = distillTurnForCommit(assistantHtmlOrMermaidResponse);
// 3. Prune Base64 assets, SVG path strings, and Float32Array buffers from active refinement code
const cleanActiveCode = pruneCodeForActiveRefinement(currentArtifactCode);
3. Rust (crates.io)
use ;
let config = TwoZoneConfig ;
let mut session = new;
let = session.prepare_turn;
Citation
See CITATION.cff, or cite:
License
MIT License. Copyright (c) 2026 David Charles Michael. See LICENSE.