Chapter 2: Context Engineering & Transformer Limits
Context Engineering treats the LLM context window as scarce, stateful working memory rather than an unlimited prompt string. Because Transformer attention scales quadratically in prefill compute, KV cache memory grows linearly with sequence length and batch size, and softmax dilution degrades recall in the middle of long contexts, reliable agents decouple the ground-truth event log from the projected LLM context—enforcing append-only KV prefix stability alongside observation masking, compaction, progressive disclosure, and subagent isolation.
1. From Prompt Engineering to Context Engineering
In single-turn applications, Prompt Engineering focuses on wording a static template to elicit a desired format or reasoning style. In multi-turn autonomous agents, the prompt is no longer static—it is a dynamically evolving state buffer rebuilt on every iteration of the control loop.
Context Engineering (Stanford CS329Z, Lecture 2) is the systems discipline of deciding what information enters the model’s context window, in what order, at what level of fidelity, and when it is evicted or offloaded so that the agent maximizes decision quality under strict latency, memory, and cost budgets.
At step , the context window is the LLM’s entire working RAM:
Stuffing everything into a 128k–1M token window fails in practice for two distinct reasons: hardware/systems bottlenecks (compute, HBM capacity, Time-to-First-Token) and cognitive/attention bottlenecks (context rot and interference).
2. Transformer Mechanics & Hardware Limits
2.1 Scaled Dot-Product Attention & Quadratic Cost
In standard causal self-attention, input hidden states are projected into queries, keys, and values and :
where enforces causal masking ( for ).
- Compute Complexity: Computing and multiplying the resulting probability matrix by requires floating-point operations per layer. Doubling context length quadruples prefill attention FLOPs.
- Memory & I/O Bottleneck: Naive attention materializes the score matrix in slow GPU High Bandwidth Memory (HBM). IO-aware kernels such as FlashAttention tile into fast on-chip SRAM and use online softmax to cut HBM memory footprint from to , but the compute scaling during prefill remains fundamental for full attention.
2.2 The KV Cache Bottleneck During Decoding
During autoregressive token generation, recomputing keys and values for all prior tokens at every decode step would cost per generated token. Instead, inference engines cache past and tensors in GPU HBM. For a Transformer with layers, key-value heads (under Multi-Query or Grouped-Query Attention, GQA), head dimension , sequence length , batch size , and bytes per element:
(The factor of accounts for storing both and tensors.)
Worked Systems Example (70B-Class GQA Model)
Consider a Llama-style 70B model with layers, KV heads (GQA), , and BF16 precision ():
- At tokens for a single request (), the KV cache alone consumes of HBM—on top of for BF16 weights.
- At concurrent agent trajectories of length , the KV cache demands , saturating an entire H100 node.
- Because decoding is memory-bandwidth bound (every generated token must stream the entire active KV cache from HBM to SRAM), bloated agent contexts directly degrade Time-Between-Tokens (TBT) and reduce server throughput.
3. Effective Context vs. Nominal Context (“Context Rot”)
Even when a model accepts or tokens without an out-of-memory error, effective reasoning length is far smaller than nominal context length.
3.1 Lost in the Middle & Softmax Dilution
Empirical needle-in-a-haystack and multi-document QA evaluations (Liu et al., 2023) demonstrate a pronounced U-shaped performance curve: models retrieve facts reliably at the beginning (primacy bias) and end (recency bias) of the context, while accuracy drops sharply for information placed in the middle.
Two mechanisms drive this degradation:
- Softmax Attention Dilution: For token , the attention weight on a relevant token is: As grows with noisy tool outputs or irrelevant files, the denominator accumulates thousands of small positive terms, flattening and drowning out sparse signal tokens.
- Positional Extrapolation & Decay: Rotary Position Embeddings (RoPE) experience phase aliasing and long-range attention decay when sequences stretch near or beyond pretraining distribution lengths.
3.2 Four Agentic Context Failure Modes
| Failure Mode | Mechanism in Agent Loops | Observable Symptom |
|---|---|---|
| Context Poisoning | An early hallucination or misdiagnosis enters the conversation history and is treated as ground truth in later turns | Agent stubbornly edits the wrong file or repeats a broken assumption across 10 steps |
| Context Distraction | High-volume logs, stack traces, or irrelevant retrieved files crowd out instructions and active goals | Agent forgets output formatting rules or loses track of the original user objective |
| Context Confusion | Too many overlapping tool definitions or redundant few-shot examples compete in attention | Agent invokes deprecated tools, passes wrong parameter names, or hallucinates tool schemas |
| Context Clash | Contradictory facts coexist across turns (e.g., an old file snapshot vs. a newly edited file) | Agent reverts its own fix or cites obsolete configuration values |
4. KV Cache Stability & Prefix Engineering
In an agent loop running turns, the total tokens processed without caching grows quadratically with turns: . Automatic Prefix Caching (APC) / RadixAttention eliminates most of this cost by reusing computed KV blocks for any token prefix that matches a prior request byte-for-byte.
The Append-Only Context Invariant
KV cache lookup operates as a strict prefix match. A single changed token at index invalidates all cached KV blocks from index through :
- Anti-pattern (Cache-Busting): Putting a live timestamp (
Current time: 12:04:31), dynamic user memory summary, or shuffled tool list at the top of the system prompt invalidates the entire prefix on every turn—forcing full prefill recomputation and forfeiting 50–90% cached-token discounts. - Canonical Prefix-Stable Ordering:
- Immutable System Prompt (role, invariants, formatting rules)
- Deterministic Tool Schemas (alphabetically sorted, never mutated mid-session)
- Stable Project Context (repository tree, static docs)
- Append-Only Trajectory History (past thoughts, actions, observations appended strictly at the tail)
- Ephemeral Turn State (current timestamp, scratchpad counters, or live reminders placed last)
If an agent must prune or mask earlier observations, do so at deterministic checkpoint boundaries (e.g., compacting only every turns) rather than sliding-window trimming one turn at a time, which shifts every subsequent token position and invalidates the entire KV cache on every single step.
5. Ground-Truth Event Log vs. LLM Context Projection
A foundational systems pattern from CS329Z is never treating the LLM context array as your database of record. Maintain two separate structures:
- Ground-Truth Event Log (): An immutable, append-only ledger storing every user prompt, model reasoning step, exact tool arguments, full raw stdout/stderr, timestamps, token counts, and exit codes. Used for auditing, replay, debugging, and evaluation.
- Context Projection Function (): A deterministic view layer that renders a clean, token-budgeted message list for the next LLM forward pass.
Separating storage from projection allows engineers to mask noisy observations, swap serialization formats, or trigger compaction without losing ground-truth observability.
6. Four Context Optimization Strategies: Write, Select, Compress, Isolate
| Strategy | Core Mechanism | When to Use | Key Trade-off |
|---|---|---|---|
| Write (Externalize) | Persist plans, scratchpads, and large outputs to files or structured state outside the prompt | Long-horizon coding, research notes, multi-step artifacts | Agent must issue explicit read/write actions to retrieve external state |
| Select (JIT Retrieval) | Inject only relevant tools, skills, and file slices dynamically per step | Large toolsets (>20 tools) or massive codebases | Risk of missing critical context if selector recall is poor |
| Compress (Mask & Compact) | Replace bulky stale observations with references; summarize old turns at checkpoints | High-volume terminal outputs, long multi-turn debugging | Lossy compression can drop subtle details needed later |
| Isolate (Subagents) | Delegate noisy subtasks to isolated child contexts that return only synthesized results | Broad codebase exploration, parallel web research, log triage | Coordination overhead; subagents lack parent’s full nuanced history |
Deep Dive on Three High-Leverage Techniques
- Observation Masking: In terminal and coding agents, tool outputs (test logs,
catdumps, HTML) account for >80% of tokens, yet most outputs older than 2–3 turns are obsolete. Keep the most recent observations verbatim (e.g., ), and replace older bulky observations with a compact pointer ([Observation #4 omitted: 2,410 lines from pytest; full output at .agent/logs/obs_4.txt]). Importantly, preserve the action calls and short status so the model still knows what it tried and whether it succeeded. - Checkpoint Compaction: When token utilization approaches a threshold (e.g., 70–80% of effective context), invoke a structured summarizer that distills the trajectory into a typed handoff state (
confirmed_facts,modified_files,failed_attempts,next_actions) and resets the active window cleanly. - Progressive Disclosure (Skills & Tools): Instead of loading 50 verbose tool manuals (15,000+ tokens) upfront, expose only lightweight names + one-line descriptions (
~20 tokenseach). Load the full schema, examples, orSKILL.mdbody into context only when the agent selects that capability.
7. Key Takeaways & Interview Synthesis
- Context is finite working memory, not cheap disk: Effective context degrades well before nominal token limits due to softmax dilution and middle-context attention loss.
- KV cache reuse dictates prompt architecture: Keep static instructions and sorted tool schemas at the prefix, append trajectory events strictly at the tail, and compact at coarse checkpoints rather than sliding every turn.
- Decouple the Event Log from the Context Projection: Store full raw traces for observability, while projecting a masked, progressively disclosed, and isolated view into the model.