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)
pip install -U kv-prefix-guard
import kv_prefix_guard as kpg
# A. Canonicalize unordered MCP / OpenAI / Anthropic tool JSON schemas for prefix-hash invariance
canon_tools = kpg.py_canonicalize_tools_json(
'[{"name":"sql_query","input_schema":{"type":"object","required":["q"]}}]'
)
# B. Idempotent commit-time distillation (preserves signed thinking + DOM/Mermaid/AST contracts)
raw_assistant_turn = """<thinking signature="sig_verified_123">Signed reasoning</thinking>
<scratchpad>Drafting Three.js dashboard...</scratchpad>
```html
<!DOCTYPE html><html><head><title>Telemetry Console</title></head>
<body>
<button id="refresh-btn">Refresh</button>
<canvas id="latency-canvas"></canvas>
<script>
let pollIntervalMs = 2000;
function handleRefresh(evt) { pollIntervalMs = 1000; }
document.getElementById('refresh-btn').addEventListener('click', handleRefresh);
</script>
</body></html>
```"""
committed_turn = kpg.py_distill_turn_for_commit(raw_assistant_turn)
print(committed_turn)
# C. Brace-depth AST code skeletonization (TypeScript / Python / Rust / Go)
skeleton = kpg.py_compact_code_skeleton(
"export class CacheRouter {\n public route(key: string): boolean {\n const h = key.length * 31;\n return h > 0;\n }\n}",
10,
)
print(skeleton)
2. JavaScript / TypeScript (npm, Zero-Dependency WebAssembly)
npm install kv-prefix-guard
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)
cargo add kv-prefix-guard
use kv_prefix_guard::{
canonicalize_tools_json, KvPrefixGuardSession, TurnInput, TwoZoneConfig,
};
let config = TwoZoneConfig {
base_system_prompt: "You are a distributed systems architect.".to_string(),
session_date_utc: "2026-11-23T18:30:00Z".to_string(),
session_output_requirement: "Emit runnable HTML5 or Mermaid diagrams.".to_string(),
trailing_task_scope: None,
};
let mut session = KvPrefixGuardSession::new(config, "claude-opus-5-5", 4);
let (turn_prompt, schedule) = session.prepare_turn(&TurnInput {
user_message: "Build a cluster KV-cache hit monitor.".to_string(),
dynamic_output_override: None,
live_tool_context: Some("us-east-1 p99: 11.4ms".to_string()),
});
Citation
See CITATION.cff, or cite:
@article{michael2026kvprefixguard,
title = {Prefix-Invariant Context Partitioning and Commit-Time Relational Artifact Distillation for Multi-Turn Agentic and Multimodal LLM KV-Caches},
author = {Michael, David Charles},
year = {2026},
doi = {10.5281/zenodo.24488870},
url = {https://doi.org/10.5281/zenodo.24488870},
note = {ORCID: 0009-0007-8679-6941}
}
License
MIT License. Copyright (c) 2026 David Charles Michael. See LICENSE.
Metadata
Release files for kv-prefix-guard 1.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| kv_prefix_guard-1.0.0.tar.gz | 30.9 kB | Without provenance | Details for kv_prefix_guard-1.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| kv_prefix_guard-1.0.0-cp39-abi3-manylinux_2_34_x86_64.whl | CPython 3.9 | abi3 | Linux glibc 2.34+ x86-64 | Details for kv_prefix_guard-1.0.0-cp39-abi3-manylinux_2_34_x86_64.whl |
Total release size: 375.6 kB
Release files / kv_prefix_guard-1.0.0.tar.gz
| Download URL | kv_prefix_guard-1.0.0.tar.gz |
|---|---|
| Size | 30.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d3ebe676a47188b32a00b865170fc5b03f51c4db83d01e9a976cec4b77062079
|
|
BLAKE2b-256 checksum How to use checksums |
3e24546b220a8332d853577197dbb54d637fbee07fa0d9163ce0a81435f51c8c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.2
|
Release files / kv_prefix_guard-1.0.0-cp39-abi3-manylinux_2_34_x86_64.whl
| Download URL | kv_prefix_guard-1.0.0-cp39-abi3-manylinux_2_34_x86_64.whl |
|---|---|
| Size | 344.6 kB |
| Tags | CPython 3.9 Linux glibc 2.34+ x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
c631181c4ace858bbd62817c76d5ffa39fb6a205e49671aa4e0eeeef43388d25
|
|
BLAKE2b-256 checksum How to use checksums |
d0b5db51f272fe250985fd56e62d4d26d7791efcd30522958b65b3687d4bd8f4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.2
|
Security for kv-prefix-guard 1.0.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.