Zero-Copy Context Compression for Long-Horizon Agents: Semantic Pruning, KV-Cache Anchors, and Redis Episodic Memory
The Prefix-Cache Trap in Agent Compaction
Every long-horizon agent eventually hits context pressure. The standard fix—calling an LLM to summarize the first 40 turns and replacing them at the top of messages[]—has a hidden performance tax: it mutates the prompt prefix and busts 100% of your provider KV-cache.
On a 90k-token coding session, losing prefix cache turns a $0.02 turn into $0.18 and adds 4+ seconds of prefill latency.
Cache-Preserving Memory Architecture
Instead of mutating the head of the message list every few turns, structure agent context into three stable zones:
- Immutable Prefix Anchor (Turns 0–2): System instructions, MCP tool schemas, and repository map—never edited mid-session so KV-cache stays hot.
- Episodic Pointer Ring in Redis: Large tool outputs (
> 1,500tokens like raw test logs or file reads) are written to Redis (session:{id}:artifact:{key}) and replaced in-place with a 40-token summary + retrieval handle. - Epochal Checkpoint Rollover: Only compact older middle blocks at fixed 32k-token epochs, keeping the prefix anchor untouched.
Python Tool-Output Spillover Guard
pythonimport hashlib import json MAX_INLINE_CHARS = 3500 async def compact_tool_payload(redis_client, session_id: str, tool_name: str, raw_output: str) -> str: if len(raw_output) <= MAX_INLINE_CHARS: return raw_output digest = hashlib.sha256(raw_output.encode()).hexdigest()[:10] artifact_key = f"agent:{session_id}:blob:{digest}" await redis_client.set(artifact_key, raw_output, ex=7200) head = raw_output[:900] tail = raw_output[-700:] return json.dumps({ "truncated": True, "tool": tool_name, "total_chars": len(raw_output), "redis_ref": artifact_key, "preview_head": head, "preview_tail": tail, "hint": "Call read_artifact(redis_ref, start_char, end_char) if exact middle lines are needed." })
Takeaway
Offloading verbose tool payloads at insertion time keeps the active context lean for 100+ turns without rewriting history or invalidating your prefix KV-cache.