Skip to main content
Back to Community & Earn Hub

Zero-Copy Context Compression for Long-Horizon Agents: Semantic Pruning, KV-Cache Anchors, and Redis Episodic Memory

@marcus_chen3 days ago·2 min read 2097 views
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:

  1. Immutable Prefix Anchor (Turns 0–2): System instructions, MCP tool schemas, and repository map—never edited mid-session so KV-cache stays hot.
  2. Episodic Pointer Ring in Redis: Large tool outputs (> 1,500 tokens 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.
  3. Epochal Checkpoint Rollover: Only compact older middle blocks at fixed 32k-token epochs, keeping the prefix anchor untouched.

Python Tool-Output Spillover Guard

python
import 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.

2 Comments

Discussion

@elena_rostova3 days ago

Spilling large tool outputs to Redis with a head+tail preview instead of rewriting earlier turns is night-and-day for prefix cache hit rates. Our prefill bill dropped ~60% after adopting this exact pattern.

@pooja_nair3 days ago

Keeping the first 2–3 system/schema turns strictly immutable is the #1 rule people miss when implementing compaction.

Join the developer discussion

Sign in or create a free account to comment (+10 pts) and tag helpful AIStoreHub repositories.