跪拜 Guibai
← All articles
Backend

Context Windows Are RAM, Not Disk: The Engineering Playbook Behind Production Agents

By XW ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Agent runs that hit hundreds of tool calls collapse without deliberate context management, and naive fixes such as a bigger window or hard-truncating history quietly break results: forgotten constraints, poisoned facts, hallucinated file paths. These techniques are the difference between a demo that works and an agent that survives a real codebase.

Summary

Context rot is the name for what happens when you stuff a model's window: the more tokens, the worse recall of intermediate facts. Anthropic says to treat context as a finite resource, and mainstream agents now engineer each step to feed only the minimal high-signal token set. That means four strategies: Write information to external storage (scratchpads, CLAUDE.md-style rule files, long-term memory services), Select only relevant files and tools each turn, Compress when the window approaches 80-95% (tool result clearing, auto-compact summaries, hierarchical summarization), and Isolate contexts by splitting work into sub-agents, sandboxes, and state schemas.

Product implementations show the same trade-offs. Claude Code preloads CLAUDE.md, relies on on-demand Read/Glob/Grep, auto-compacts at 95%, and can spawn sub-agents. Cline deliberately avoids codebase indexing because RAG indices go stale; it uses a Memory Bank of markdown and progressive disclosure of large results. Aider builds a tree-sitter-based Repo Map with importance scoring. LangGraph uses checkpointer state and summarization nodes. OpenAI handles threads server-side with automatic truncation.

Two costs often get overlooked. Tool results are the biggest source of bloat; the principle is to return indexes and samples, not full data, and let the model call the tool again for more. Prefix caching is the cheapest lever: keep system prompt, tools, and memory files fixed and in order, and input token cost drops to 10-20% of original, saving 5-10x on long-session bills. A pre-launch checklist covers fixed prefix share under 30% of the window, explicit truncation strategies, automatic compression before 80%, isolated cross-session memory, and regression testing on an offline case library.

Takeaways
— Context windows behave like RAM, not disk; context rot means recall of intermediate facts degrades as token count rises.
— Four failure modes when windows fill: context poisoning, distraction, confusion, and clash.
— Only about 50-70% of an agent's context changes per turn; the first 30-40% (system prompt, tools, memory files) is fixed and prefix-cacheable.
— Write strategy: external storage via scratchpads, procedural memory files (CLAUDE.md, .cursorrules), and long-term memory services (Mem0, Letta, Zep, ChatGPT auto-memory).
— Select strategy: preload stable rules, use just-in-time tools for dynamic content; RAG with hybrid retrieval (embedding + BM25) plus re-rank; tool RAG when tool count exceeds ~20 improves tool selection accuracy ~3x.
— Compress strategy: tool result clearing (replace old results with placeholders), auto-compact summarization at 80-95% (Anthropic's Claude Code at 95%), recursive hierarchical summaries, and trimming with system-message protection.
— Isolate strategy: sub-agents each get independent windows and return 1-2k token summaries; sandbox keeps large objects outside LLM context; state schemas expose only messages to the model.
— Prefix caching: keep fixed prefix (system, tools, memory) at the front and unchanged; input token cost drops to 10-20% and long sessions can be 5-10x cheaper.
— Tool results should return indexes and samples, not full data; file reads over ~200 lines return first N lines + size; search returns title+URL+snippet top-5; SQL limits to 20 rows; stdout truncated to ~2000 tokens.
— Pre-launch checklist: fixed prefix ≤30% of window; automatic compression before 80%; explicit keep/drop rules in summary prompts; per-user isolation for long-term memory; regression testing on offline case library.
Conclusions

Scaling context windows to 200k or 1M tokens does not remove the need for context management, because context rot degrades recall as tokens accumulate; the source states this as a core judgment, so the practical takeaway is that window size optimization has a ceiling.

The biggest cost lever in multi-turn agents is often input tokens, not output. With prefix caching, long sessions can be 5-10x cheaper; this reframes contextual engineering as a billing and latency issue, not just a correctness one.

Cline's explicit refusal to index codebases because RAG indices go stale suggests a fundamental tension: precomputed indexes optimize first-turn latency but decay with code changes, while on-demand navigation trades latency for freshness.

Compression introduces a correctness risk: summaries can drop details that later prove critical, so the guidance to tune recall before precision is a practical acknowledgment that context management is a quality trade-off, not a free win.

Concepts & terms
Context rot
The phenomenon where a model's recall accuracy on information in the middle of a long context decreases as token count increases, making larger windows not automatically better.
Prefix caching
A server-side optimization where a fixed leading segment of the prompt (system, tools, memory files) is computed once and reused across turns, dropping input token price to 10-20% and cutting first-token latency.
Auto-compact
A compression strategy that summarizes the full conversation history when the window approaches a threshold (e.g., 95% in Claude Code), then restarts with the summary plus recent raw messages.
Tool result clearing
Replacing old tool outputs with short placeholders that reference where the original result lives, saving tokens without changing model behavior.
Repo Map
Aider's approach to repository understanding: tree-sitter parses the codebase into a symbol map (classes/functions/methods), scored by import relationships and edit distance, with only top-N symbols fed to the model.
Just-in-time context
Anthropic's principle of giving the model navigation tools (Read, Glob, Grep) rather than precomputing and stuffing content into the window, at the cost of an extra tool round-trip.
Memory Bank
Cline's set of markdown files (projectBrief.md, techContext.md, productContext.md, activeContext.md) loaded at session start as procedural memory.
Source: juejin.cn ↗ Google Translate ↗ Backup ↗