The Context Window Is Not a Dump Bucket
Your RAG pipeline retrieves 40 chunks. You stuff all 40 into the prompt. The model returns a confident answer that ignores the three most relevant chunks completely.
You check the chunks. They were retrieved correctly. They contained the right information. The model just... didn't use them.
You blame the retriever. You tune your embeddings. You rewrite your prompt. You switch models. The problem persists, across every variation, because you're fixing the wrong thing.
Here's what's actually happening: the relevant chunks were buried in the middle of a 40,000-token context, among 37 chunks that were nearly relevant. Long context hurts models in two documented ways. The 2023 "Lost in the Middle" study found content in the middle of a long context used less than content at the beginning or end. Newer work finds that quality falls as input grows and as distractors pile up, wherever the answer sits. Your 40 chunks triggered both.
direction: down
classes: {
grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
window: "40,000-token context, 40 chunks in retrieval order" {
label.near: top-center
grid-rows: 1
grid-gap: 10
start: "chunks 1-12\nnear-misses" {class: grey}
mid: "chunks 13-28\nthe 3 relevant ones\nburied here" {class: green}
end: "chunks 29-40\nnear-misses" {class: grey}
}
model: "Model" {class: yellow}
answer: "Confident answer that\nignores the 3 chunks" {class: red}
window -> model
model -> answer
Retrieval did its job: the three green chunks are in the window. The failure is everything around them, 37 near-misses competing for attention with the answer sitting in the middle.
The retriever was fine. The embeddings were fine. The model was fine.
Your context design failed. And no amount of prompt tuning fixes a structural assembly problem.
This is Part 3 of the Harness Engineering series. Part 1 introduced the seven-layer Harness Architecture. Part 2 covered the Normalization Layer. This article goes deep on Layer 2 - Context Orchestration - covering memory architectures, retrieval strategies, context compression, and the Lost in the Middle problem.
This series grew into a book: Harness Engineering for Production AI Systems. Chapter 5, "Context Assembly as Managed Infrastructure," covers this layer.
17 November 2026: updated for what newer long-context research shows ("context rot", NoLiMa), prompt caching's effect on ordering, provider compaction and memory tools, and a compression loop that never summarises away your constraints. Every component now has its own diagram.
What Context Engineering Actually Is
Most teams treat context assembly as a retrieval problem. Find the relevant documents, put them in the prompt, done.
This misses the point entirely.
Context engineering - the name Anthropic and much of the field now use for this work - is the discipline of deciding, precisely and intentionally, what information the model sees at each step of execution, how that information is structured, and in what order it appears. Anthropic's own write-up, Effective context engineering for AI agents, calls it "the natural progression of prompt engineering". It's not retrieval. It's curation, compression, and assembly.
The context window is the model's entire working memory. Everything it knows about the current task lives there. Every decision it makes is a function of what's in that window and how it's arranged. For many production failures, the quality of your context assembly matters as much as the model you chose.
grid-columns: 1
grid-gap: 8
classes: {
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
teal: {style: {fill: "#4B0082"; stroke: "#3A0066"; font-color: "#FFFFFF"}}
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
}
sys: "System prompt and constraints - chosen" {class: green}
mem: "Memory: standing facts, prior sessions - selected" {class: violet}
ret: "Retrieved chunks - reranked and ordered" {class: blue}
hist: "Conversation history - compressed" {class: teal}
q: "The query - placed last" {class: yellow}
Every band in that window is a decision someone made, or failed to make. The verb on the right is the engineering.
What goes into the context window is what the model reasons over. Nothing more. Nothing less.
This is why I treat context orchestration as a distinct engineering discipline - not a retrieval concern, not a prompt engineering concern, but its own layer in the Harness Architecture with its own failure modes, its own tools, and its own metrics.
The Three Failure Modes of Naive Context Assembly
Before building solutions, understand what breaks. Naive context assembly - retrieve, concatenate, send - fails in three specific ways.
Failure Mode 1: Lost in the Middle
Liu et al. (2023) demonstrated what practitioners had been observing anecdotally: on the models they tested, performance was "often highest when relevant information occurs at the beginning or end of the input context", and degraded significantly when the answer sat in the middle. The degradation was not linear - it was a U-shaped curve, with the middle of the context as the dead zone.
Newer models have moved the picture, not erased it. Chroma's 2025 "context rot" study tested 18 models, including Claude Opus 4, GPT-4.1 and Gemini 2.5, and found that "model performance consistently degrades with increasing input length". In its needle-in-a-haystack test, though, the needle's position made no notable difference. What hurt more were distractors and a needle phrased differently from the question. NoLiMa makes the same point harder: when the needle shares little wording with the question, 11 of 13 models fall below half their short-context score by 32K tokens.
grid-rows: 1
grid-gap: 16
classes: {
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
}
liu: "Lost in the Middle (2023 models)" {
label.near: top-center
grid-rows: 1
grid-gap: 6
a: "start\nstrong" {class: green}
b: "middle\nweak" {class: red}
c: "end\nstrong" {class: green}
}
rot: "Context rot (2025 models)" {
label.near: top-center
grid-columns: 1
grid-gap: 6
d: "longer input -> worse, wherever the answer is" {class: red}
e: "distractors and low word overlap hurt most" {class: red}
f: "measure position on your own model" {class: grey}
}
Both effects punish the same design. Concatenating every retrieved chunk in retrieval order makes the input longer and the distractors more numerous, and leaves the best chunk wherever the retriever happened to rank it.
The implication is still severe. If your retriever returns 20 chunks and you concatenate them in retrieval order, the most relevant chunk can land in positions 10-15, the zone where the 2023 models were weakest. And all 20 chunks are input length and distraction the model has to read past.
What breaks: RAG systems that naively concatenate retrieved chunks. Summarization pipelines that dump full documents into context. Any system where content ordering is determined by retrieval rank rather than model attention dynamics.
Failure Mode 2: Context Bloat
Every token in the context window costs money and consumes attention capacity. Boilerplate, redundant content, and low-relevance chunks don't just waste tokens - they dilute the signal-to-noise ratio for the model's attention mechanism. Tools are a quiet source of this bloat: every tool description an agent carries is a standing deduction from the window, which is why adding a navigation tool to a coding agent can make it dumber on a repo small enough not to need it.
A window of hundreds of thousands of tokens feels enormous until your agent is 30 steps into a complex task and has accumulated tool outputs, intermediate reasoning, error messages, and retry attempts. Window size is not usable capacity: the context-rot results above mean the model is working worse long before the window is full. Without active context management, the window fills with stale content and the model starts losing track of the original task.
grid-rows: 1
grid-gap: 14
classes: {
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
s1: "Step 1\ntask + system prompt\nmost of what's there" {class: green}
s10: "Step 10\ntask now a small share\nof tool output" {class: grey}
s30: "Step 30\ntask buried under\nstale outputs and retries" {class: red}
s1 -> s10 -> s30
The task statement never got shorter. Everything around it got longer, so its share of the window, and of the model's attention, kept falling.
What breaks: Long-running agentic workflows. Multi-document summarization. Any task where context accumulates over multiple turns without compression.
Failure Mode 3: Memory Amnesia
Across sessions, most LLM systems start from scratch. The user's preferences established in session 1 are unknown in session 2. The decision made three conversations ago has to be re-explained. The agent that worked on a task yesterday has no memory of what it did.
This isn't just a UX problem. For complex agentic tasks that span multiple sessions, memory amnesia means the agent re-does work, re-asks questions, and loses the accumulated context that makes it effective.
grid-rows: 1
grid-gap: 16
classes: {
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
s1: "Session 1" {
label.near: top-center
grid-columns: 1
a: "user: prefers Python,\nproject uses Postgres" {class: blue}
b: "decided: no ORM" {class: blue}
}
s2: "Session 2" {
label.near: top-center
grid-columns: 1
c: "agent: which language?" {class: red}
d: "agent: shall we add an ORM?" {class: red}
}
Nothing connects the two boxes. Everything session 1 settled has to be settled again, and nothing records the earlier decision for the agent to check against.
What breaks: Any agentic system designed for ongoing tasks. Customer-facing assistants. Code agents working on multi-session projects.
The Context Orchestration Stack
A production context orchestration layer has four components. Each addresses a specific failure mode.
Component 1: Retrieval with Re-ranking
Basic RAG uses embedding similarity to retrieve chunks. This is a good start and a terrible finish.
Embedding similarity retrieves semantically related content - but semantic relatedness is not the same as task relevance. A chunk that mentions the same topic isn't necessarily the chunk that helps answer the specific question. Re-ranking adds a second pass that scores retrieved chunks against the specific query for relevance, not just similarity.
The classes in this article are sketches: vector_store, reranker, llm and the stores stand in for whichever clients you use, so read their method calls as interfaces, not a specific library's API.
from typing import Listclass ContextRetriever: def __init__(self, vector_store, reranker, top_k: int = 20, final_k: int = 5): self.vector_store = vector_store self.reranker = reranker self.top_k = top_k # retrieve broadly self.final_k = final_k # rerank to precise set def retrieve(self, query: str) -> List[str]: # Stage 1: broad embedding retrieval candidates = self.vector_store.similarity_search(query, k=self.top_k) # Stage 2: rerank for task relevance scored = self.reranker.score(query, candidates) ranked = sorted(scored, key=lambda x: x.score, reverse=True) return [chunk.content for chunk in ranked[:self.final_k]]The two-stage approach - retrieve broadly, rerank precisely - is now standard in production RAG systems. The reranker (cross-encoder models like Cohere Rerank, or bge-reranker) has access to both query and document together, which produces dramatically better relevance scores than embedding similarity alone.
Without re-ranking: you retrieve the 5 most semantically similar chunks. With re-ranking: you retrieve the 5 most task-relevant chunks. Anthropic's Contextual Retrieval measurements show the size of the effect: on their benchmarks, the top-20 retrieval failure rate fell from 5.7% to 2.9% with contextual embeddings and contextual BM25, and to 1.9% once reranking was added.
direction: down
classes: {
grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
corpus: "Document store" {class: grey}
broad: "Stage 1: embedding search\ntop_k = 20, similar to the query" {class: violet}
rerank: "Stage 2: cross-encoder reranker\nreads query and chunk together" {class: blue}
final: "final_k = 5\nrelevant to this question" {class: green}
corpus -> broad: "cheap, broad"
broad -> rerank: "20 candidates"
rerank -> final: "expensive, precise"
The expensive model only ever sees 20 candidates, never the whole store. That's what makes it affordable to run a reranker on every query.
Without this component: you're paying retrieval cost for chunks the model won't use.
Component 2: Position-Aware Assembly
Given the Lost in the Middle problem, chunk ordering is not neutral. Put the most important content at the beginning and end of the context, not the middle.
This is primacy-recency ordering, and it's not new: LangChain ships it as LongContextReorder. It places the highest-value content where the 2023 models attended most. On a current model, measure whether it still helps. The context-rot results suggest that cutting the near-misses out of the window often matters more than how you order the ones that stay.
def assemble_context(chunks: List[str], query: str, system_prompt: str) -> str: if not chunks: return system_prompt # Most relevant chunk first, second most relevant last, # remaining chunks fill the middle - exploiting the U-curve if len(chunks) == 1: ordered = chunks elif len(chunks) == 2: ordered = chunks else: ordered = [chunks[0]] + chunks[2:] + [chunks[1]] context_block = "\n\n---\n\n".join(ordered) return f"{system_prompt}\n\n<context>\n{context_block}\n</context>\n\nQuery: {query}"The query goes last on purpose. Anthropic's long-context guidance is to place long documents "near the top of your prompt, above your query", and reports that queries at the end can improve response quality "by up to 30 percent in tests", especially with complex, multi-document inputs.
Order for the cache, too. Prompt caching matches an exact prefix: tools, then system prompt, then messages. A change anywhere in the prefix invalidates the cache from that point on, and cache reads cost a tenth of the base input price or less, so an unstable prefix gets expensive. Keep everything that is the same for every request at the front: tools, system prompt, standing instructions. Put per-user facts and per-query chunks after the cache breakpoint. That includes the <known_facts> block from the memory section below, which changes per user and belongs after the stable system prompt, not inside it.
direction: down
classes: {
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
}
cached: "Cached prefix - identical on every request" {
label.near: top-center
grid-rows: 1
grid-gap: 10
tools: "Tools" {class: green}
sys: "System prompt" {class: green}
}
perq: "After the cache breakpoint - changes per request" {
label.near: top-center
grid-rows: 1
grid-gap: 10
facts: "known_facts\n(per user)" {class: grey}
c1: "chunk 1\nbest" {class: blue}
mid: "chunks 3..n" {class: grey}
c2: "chunk 2\nsecond best" {class: blue}
q: "Query" {class: yellow}
}
cached -> perq
Two orderings are stacked here. The bottom row is ordered for the model's attention, with the best chunk first, the second best just before the query, and the query last. The top row is ordered for the cache, and nothing that varies per request is allowed into it.
Without this component: you've sorted your chunks by embedding rank and handed them to the model in a order optimized for your retriever, not for the model's attention.
Component 3: Context Compression
Not all content that needs to be in the context needs to be in the context at full length. Long documents can be summarized. Conversation history can be compressed. Intermediate agent reasoning can be distilled into structured checkpoints.
class ContextCompressor: def __init__(self, llm, max_tokens_per_chunk: int = 500): self.llm = llm self.max_tokens = max_tokens_per_chunk def compress_history(self, messages: List[dict], keep_last_n: int = 3) -> List[dict]: if len(messages) <= keep_last_n: return messages # Keep recent messages verbatim recent = messages[-keep_last_n:] # Compress older messages into a summary older = messages[:-keep_last_n] summary_text = self._summarize(older) summary_message = { "role": "system", "content": ( f"[Conversation summary - {len(older)} earlier messages]: " f"{summary_text}" ), } return [summary_message] + recent def compress_document(self, document: str, focus: str) -> str: prompt = ( f"Extract only the information relevant to: {focus}\n\n" f"Document:\n{document}\n\n" "Return only the relevant excerpts, verbatim. " "If nothing is relevant, return 'No relevant content.'" ) return self.llm.call(prompt) def _summarize(self, messages: List[dict]) -> str: text = "\n".join(f"{m['role']}: {m['content']}" for m in messages) prompt = ( "Summarize the key decisions, facts, and context " f"from this conversation:\n\n{text}" ) return self.llm.call(prompt)The key principle: compress toward task relevance, not toward brevity. A compression that removes task-relevant detail to save tokens is worse than no compression at all. The focus parameter in compress_document ensures the compressor knows what to preserve.
One rule matters more than the summary prompt: never feed your constraints to the summarizer. compress_history as written summarizes every message older than the last three. If an early message carries an operating constraint ("refunds over 500 need approval"), the summary can turn it into a sentence that no longer constrains anything. Pin the system prompt, the constraints and any span the task requires, pass them through verbatim, and compress only what's left. The later part on the context policy nobody wrote shows that failure in a real budget loop.
direction: down
classes: {
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
teal: {style: {fill: "#4B0082"; stroke: "#3A0066"; font-color: "#FFFFFF"}}
}
pinned: "Pinned\nsystem prompt, constraints,\nrequired spans" {class: green}
older: "Older turns" {class: grey}
recent: "Last 3 turns" {class: teal}
summ: "Summarizer" {class: violet}
out: "Pinned spans verbatim + summary + last 3 turns" {class: teal}
older -> summ
summ -> out
pinned -> out: "verbatim"
recent -> out: "verbatim"
Only the grey box passes through the summarizer. The green box never does, however tight the budget gets.
Without this component: context bloat accumulates silently across turns. The model loses the thread. Long-running tasks degrade in coherence proportional to their length.
Component 4: Memory Architecture
For agents that operate across sessions, you need a memory system. Memory in this context is not conversation history - it's structured, persistent, retrievable knowledge about the user, the task, and prior decisions.
Three tiers:
Working memory - the current context window. Volatile, token-bounded, task-specific. Managed by the context assembler within each session.
Episodic memory - a structured store of past interactions, decisions, and outcomes. Retrievable by semantic similarity. Used to surface relevant prior context at the start of new sessions.
from datetime import datetime, timezonefrom typing import Listclass EpisodicMemory: def __init__(self, vector_store): self.store = vector_store def save(self, session_id: str, summary: str, metadata: dict): self.store.add( id=session_id, content=summary, metadata={**metadata, "timestamp": datetime.now(timezone.utc).isoformat()} ) def recall(self, query: str, top_k: int = 3) -> List[str]: results = self.store.similarity_search(query, k=top_k) return [r.content for r in results]Semantic memory - long-term facts about the user, project, or domain. Structured key-value store, not vector search. Things that don't change session to session: the user's preferred programming language, the project's tech stack, standing decisions already made.
class SemanticMemory: def __init__(self, kv_store): self.store = kv_store def remember(self, key: str, value: str): self.store.set(key, value) def recall(self, key: str) -> str | None: return self.store.get(key) def inject_into_context(self, system_prompt: str) -> str: facts = self.store.get_all() if not facts: return system_prompt facts_block = "\n".join(f"- {k}: {v}" for k, v in facts.items()) return f"{system_prompt}\n\n<known_facts>\n{facts_block}\n</known_facts>"direction: down
classes: {
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
}
episodic: "Episodic memory\npast sessions, vector search" {class: violet}
semantic: "Semantic memory\nstanding facts, key-value" {class: blue}
working: "Working memory: the context window\nvolatile, token-bounded, this session" {class: yellow}
episodic -> working: "1. recall similar"
semantic -> working: "1. inject facts"
working -> episodic: "2. save summary"
The arrows are the whole design. Two stores feed the window at the start of a session, and only one is written back at the end. Standing facts change rarely and on purpose, so they shouldn't be overwritten by every session's summary.
You may not need to build all of this yourself. Providers now ship the pieces. Anthropic's memory tool lets the model read and write files in a memory directory that your application stores. The docs pair it with compaction because "memory preserves the information that must survive summarization". The three tiers are still the right way to think about what to keep. The tool changes who does the writing.
Without a memory architecture: every session starts blind. The agent re-asks questions, re-establishes context, and re-makes decisions that were already made. For users doing ongoing work, this is the single largest friction point in production agentic systems.
The Full Context Orchestration Pipeline
grid-rows: 8
grid-columns: 2
grid-gap: 34
classes: {
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
teal: {style: {fill: "#4B0082"; stroke: "#3A0066"; font-color: "#FFFFFF"}}
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
none: {style: {opacity: 0}}
}
q: "1. Incoming query" {class: blue}
n0: "" {class: none}
mem: "2. Semantic inject + episodic recall" {class: violet}
n1: "" {class: none}
ret: "3. Two-stage retrieval" {class: violet}
n2: "" {class: none}
comp: "4. Compression (pinned spans untouched)" {class: violet}
n3: "" {class: none}
asm: "5. Position-aware assembly" {class: violet}
n4: "" {class: none}
budget: "6. Token budget check" {class: green}
again: "Over budget, above floor:\ncompress again, back to 5" {class: red}
llm: "7. LLM call on assembled context" {class: yellow}
refuse: "Would cut below the floor:\nrefuse before the call" {class: red}
save: "8. Save to episodic memory" {class: teal}
n7: "" {class: none}
q -> mem -> ret -> comp -> asm -> budget
budget -> again
budget -> refuse
budget -> llm: "within budget"
llm -> save
Every query goes through this pipeline. The token budget check is not optional - it's the mechanism that prevents context bloat from accumulating silently. If assembled context exceeds budget, compression runs again before the LLM call proceeds - but never below the floor. When the only way to fit is to cut a pinned span or drop below the minimum the task needs, the pipeline refuses the call instead of sending a context that can no longer do the job. A later part makes the case for refusing below a context floor in full.
Budget your context window the way you budget compute. It is a finite resource with a cost per token and a quality curve that degrades with misuse.
Token Budget Management
The context window is a budget. Spend it intentionally.
A production context budget looks like this:
| Slot | Allocation | Content |
|---|---|---|
| System prompt | 10-15% | Instructions, persona, constraints |
| Semantic memory | 5-10% | Standing facts, user preferences |
| Episodic recall | 10-15% | Relevant prior sessions |
| Retrieved context | 30-40% | RAG chunks, documents |
| Conversation history | 15-20% | Recent turns (compressed) |
| Output headroom | 15-20% | Space for model response |
These are illustrative starting percentages, not measured ones and not hard rules. The right allocation depends on your task. A summarization task needs more retrieved context. A conversational task needs more history. A first-turn task needs no episodic recall.
The critical constraint: output headroom must never be sacrificed. Running out of context mid-generation produces truncated, broken outputs. Always reserve it.
grid-rows: 1
grid-gap: 6
classes: {
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
teal: {style: {fill: "#4B0082"; stroke: "#3A0066"; font-color: "#FFFFFF"}}
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
}
sys: "System\n10-15%\nnever trimmed" {class: green}
sem: "Semantic\n5-10%" {class: violet}
epi: "Episodic\n10-15%" {class: violet}
ret: "Retrieved\n30-40%\ntrimmed first" {class: blue}
hist: "History\n15-20%" {class: teal}
out: "Output\n15-20%\nnever trimmed" {class: yellow}
The two ends of the bar are fixed. Everything between them is negotiable, and the trimmer below works from the most negotiable slot inward. Keep the fixed slots out of priorities entirely: _trim_half cuts text blindly, so a system prompt listed as low priority would be cut in half like anything else. Providers now do some of this server-side. Anthropic's API, for example, can clear old tool results and compact long conversations. A provider's trimmer doesn't know which of your spans are load-bearing, though, unless you tell it.
class TokenBudgetManager: def __init__(self, model_context_limit: int, output_reserve: int): self.limit = model_context_limit self.reserve = output_reserve self.available = model_context_limit - output_reserve def fits(self, text: str, tokenizer) -> bool: return tokenizer.count(text) <= self.available def trim_to_fit(self, components: dict, tokenizer, priorities: list) -> dict: """ Trim components in reverse priority order until context fits. priorities: list of keys in order of what to cut last. """ result = dict(components) while not self.fits(self._join(result), tokenizer): # Cut from lowest priority first for key in reversed(priorities): if key in result and result[key]: result[key] = self._trim_half(result[key]) break else: # Only components outside `priorities` are left: the floor raise ValueError("context cannot fit without cutting pinned content") return result def _join(self, components: dict) -> str: return "\n\n".join(v for v in components.values() if v) def _trim_half(self, text: str) -> str: if len(text) < 200: return "" # halving a short text would make it longer return text[:len(text) // 2] + "...[truncated]"What Observability Looks Like for This Layer
Track these metrics in production:
Context utilization rate - what fraction of your token budget is actually used on average? Consistently above 90% signals context bloat risk. Consistently below 40% signals over-allocation in retrieval - you're paying for tokens you don't need.
Retrieval hit rate - of the chunks retrieved and included in context, what fraction are actually referenced in the model's output? A low hit rate means your retriever is returning irrelevant content. Measure this by checking whether retrieved chunk IDs appear in citations or are semantically echoed in the response.
Position distribution of cited content - are citations clustering at the beginning and end of context (expected with Lost in the Middle) or distributing evenly? If they're clustering heavily at position 0, your middle content is being ignored regardless of relevance.
Memory recall precision - when episodic memory is recalled, does it actually improve output quality on the subsequent task? Track this with A/B comparison: sessions with memory recall vs. sessions without.
grid-rows: 2
grid-columns: 4
grid-gap: 12
classes: {
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
}
c1: "Token budget" {class: violet}
c2: "Retrieval + rerank" {class: violet}
c3: "Assembly order" {class: violet}
c4: "Memory" {class: violet}
m1: "Context utilization\n(>90% or <40%: act)" {class: grey}
m2: "Retrieval hit rate" {class: grey}
m3: "Position of\ncited content" {class: grey}
m4: "Recall precision\n(A/B)" {class: grey}
Each metric watches one component, so when quality drops the metric that moved names the component to look at first.
Context Gravity: Where Attention Lands
A useful way to picture position bias is as context gravity, the pull that position exerts on model attention. The metaphor isn't mine alone; others write about "gravity wells" in the window. Content at the beginning and end of the context window has high context gravity - in the Lost in the Middle results, the model was reliably drawn to it. Content in the middle has low context gravity - it exists in the prompt but often doesn't meaningfully influence the output.
Context engineering is the practice of managing context gravity intentionally. You don't just fill the window - you place content where gravity will work in your favor, and you keep the window short enough that gravity matters less.
High-gravity positions: beginning of context (right after system prompt), end of context (right before the query).
Low-gravity positions: the middle of a long context. Where "long" starts depends on the model, so measure it rather than borrowing someone else's threshold.
grid-rows: 1
grid-gap: 8
classes: {
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
}
start: "Start\nhigh gravity\nmost critical chunk" {class: green}
middle: "Middle\nlow gravity\nsupporting chunks only" {class: grey}
end: "End\nhigh gravity\nsecond chunk, then query" {class: green}
The rule falls straight out of the picture: nothing you would be upset to see ignored goes in the grey box.
The engineering rule: never place your most critical content in a low-gravity position. If a chunk is important enough to retrieve, it's important enough to place where the model will actually attend to it.
What the Field Added Since This Was First Written
The components above are the ones you build. In 2025 and 2026 the field added a second set: techniques that keep the window small instead of packing it better. Anthropic's context-engineering write-up treats context as "a finite resource with diminishing marginal returns", and most of the new techniques follow from that.
- Just-in-time retrieval. Instead of loading every document up front, the agent keeps lightweight references (file paths, IDs, queries) and pulls content in with tools when it needs it. It can be combined with some retrieval up front.
- Sub-agents with clean windows. A sub-agent explores in its own context and returns a condensed summary, so the main agent's window holds the conclusion and not the search.
- Compaction. When a conversation nears the limit, summarize it and continue in a fresh window. This is the compression component above, now offered as a provider feature. The pinning rule still applies to what you let it summarize.
- Context editing. Clear old tool results the agent no longer needs. Anthropic's API offers this as a beta feature, and clearing changes the prompt prefix, so it trades cache hits for space.
- Memory tools. The model writes notes to storage outside the window and reads them back later, as in the memory section above.
grid-rows: 1
grid-gap: 16
classes: {
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
pack: "Pack the window better (this article)" {
label.near: top-center
grid-columns: 1
grid-gap: 8
a: "rerank" {class: blue}
b: "order by position" {class: blue}
c: "compress, never below the floor" {class: blue}
d: "budget the slots" {class: blue}
}
keep: "Keep the window small (added since)" {
label.near: top-center
grid-columns: 1
grid-gap: 8
e: "just-in-time retrieval" {class: green}
f: "sub-agent isolation" {class: green}
g: "compaction, context editing" {class: green}
h: "memory outside the window" {class: green}
}
The two columns don't compete. The right column decides how much reaches the window, and the left column decides how what remains is arranged. A long-running agent needs both.
What to Build First
First: Two-stage retrieval. Replace single-pass embedding search with retrieve-then-rerank. This is the highest-impact change to a RAG system and can be added in a day using Cohere Rerank, bge-reranker, or a cross-encoder from Sentence Transformers. If you control indexing, add contextual chunk embeddings and BM25 as well. In Anthropic's measurements, those two plus reranking cut retrieval failures from 5.7% to 1.9%.
Second: Token budget enforcement. Add explicit token counting before every LLM call. Reject or compress contexts that exceed budget. This prevents silent context bloat from accumulating in long-running tasks.
Third: Position-aware assembly. Reorder your chunks using the primacy-recency pattern. Most-relevant first, second-most-relevant last, remainder in the middle.
Fourth: Conversation compression. For multi-turn systems, add history summarization. Keep the last 3-5 turns verbatim, summarize everything older into a structured summary message.
Fifth: Semantic memory. Add a lightweight key-value store for standing facts. User preferences, project context, standing decisions. Inject at session start.
Sixth: Episodic memory. Add vector-stored session summaries. Recall at session start based on query similarity to prior session topics.
The first three address immediate RAG quality issues. Four through six are what separate a good RAG system from a production agentic memory system. If you're building an agent loop rather than a single RAG call, add just-in-time retrieval and sub-agent isolation alongside them: in agent loops, keeping content out of the window often beats packing it in well.
grid-columns: 1
grid-gap: 14
classes: {
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
}
rag: "RAG quality (first three)" {
label.near: top-center
grid-columns: 1
grid-gap: 8
a: "1. Two-stage retrieval" {class: blue}
b: "2. Token budget enforcement" {class: blue}
c: "3. Position-aware assembly" {class: blue}
}
memory: "Agentic memory (four to six)" {
label.near: top-center
grid-columns: 1
grid-gap: 8
d: "4. Conversation compression" {class: violet}
e: "5. Semantic memory" {class: violet}
f: "6. Episodic memory" {class: violet}
}
The bottom group pays off far less while the top group is missing: memory recalled into a badly assembled window lands in the same middle as everything else.
The Principle
The context window is not a staging area. It's not a place to put everything you retrieved and hope the model sorts it out.
The context window is the model's mind. What you put in it, and where you put it, determines what the model thinks.
Context Engineering is the discipline of taking that seriously - of treating the token budget as a managed resource, of understanding how position affects attention, of building memory systems that make agents more effective over time rather than starting blind on every session.
You can't make the model smarter by giving it more tokens. You can make it dramatically more effective by giving it better-organized, better-prioritized, better-compressed context.
The model reasons over what you give it. Give it the right things, in the right order, at the right size.
What's Next in This Series
- Part 1: Harness Engineering - The Missing Layer - The full seven-layer Harness Architecture overview
- Part 2: Normalization and Input Defense - Prompt injection, input sanitization, and multi-surface consistency
- Part 4: Gated Execution - Policy engines, human-in-the-loop design, dry-run patterns, and budget guards for agentic systems with real-world side effects
- Part 5: Validation Layer Design - Schema validators, semantic checks, repair prompt patterns, and when to fail fast vs. recover
- Part 6: Retry, Fallback, and Circuit Breaking - Building resilient LLM infrastructure that survives model outages and latency spikes
- Part 7: State Management for Agentic Systems - Checkpoint-resume strategies, cross-session memory, and durable state for long-running agents
- Part 8: Deterministic Constraint Systems - Building tool registries and action manifests that prevent hallucinated actions in agentic systems
Going deeper: Chapter 5 of the book
This is Part 3 of the Harness Engineering series, which grew into Harness Engineering for Production AI Systems. This layer became Chapter 5, "Context Assembly as Managed Infrastructure," which builds the context budget as a TOML spec checked at startup, wires assembly into a LangGraph node that lowers a run's authority when anything was evicted, and explains where deduplication belongs and why the assembler is an inner component whose record an outer component reads across a run.
The code for that chapter is the ch05-context-assembly tag of the companion repository. Its tests need no model and no API key.
For a chapter-length treatment on this blog, including where it departs from the book, see LLM Context Window Management: The Policy Nobody Wrote, Part 5 of the chapter-by-chapter guide to the book.
References
-
Liu, N. F., Lin, K., Hewitt, J., et al. (2023). Lost in the Middle: How Language Models Use Long Contexts. Transactions of the Association for Computational Linguistics, 12, 157-173. https://doi.org/10.1162/tacl_a_00638
-
Gao, Y., Xiong, Y., Gao, X., et al. (2023). Retrieval-Augmented Generation for Large Language Models: A Survey. arXiv:2312.10997. https://arxiv.org/abs/2312.10997
-
Nogueira, R., & Cho, K. (2019). Passage Re-ranking with BERT. arXiv:1901.04085. https://arxiv.org/abs/1901.04085
-
Cohere. (2024). Rerank API Documentation. https://docs.cohere.com/reference/rerank
-
Park, J. S., O'Brien, J. C., Cai, C. J., et al. (2023). Generative Agents: Interactive Simulacra of Human Behavior. ACM UIST 2023. https://arxiv.org/abs/2304.03442
-
Zhong, W., Guo, L., Gao, Q., et al. (2024). MemoryBank: Enhancing Large Language Models with Long-Term Memory. AAAI 2024. https://arxiv.org/abs/2305.10250
-
Anthropic. Prompting best practices: long context prompting. https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#long-context-prompting
-
Kumar, R. (2026). Harness Engineering for Production AI Systems. Chapter 5, "Context Assembly as Managed Infrastructure." https://harness.ranjankumar.in/
-
Anthropic. (2025). Effective context engineering for AI agents. https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents
-
Hong, K., Troynikov, A., & Huber, J. (2025). Context Rot: How Increasing Input Tokens Impacts LLM Performance. Chroma. https://www.trychroma.com/research/context-rot
-
Modarressi, A., Deilamsalehy, H., Dernoncourt, F., et al. (2025). NoLiMa: Long-Context Evaluation Beyond Literal Matching. arXiv:2502.05167. https://arxiv.org/abs/2502.05167
-
Anthropic. (2024). Contextual retrieval in AI systems. https://www.anthropic.com/news/contextual-retrieval
-
Anthropic. Prompt caching. https://platform.claude.com/docs/en/build-with-claude/prompt-caching
-
Anthropic. Memory tool. https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool
-
Anthropic. Context editing. https://platform.claude.com/docs/en/build-with-claude/context-editing
-
LangChain.
LongContextReorderdocument transformer (source, langchain-community). https://github.com/langchain-ai/langchain-community/blob/main/libs/community/langchain_community/document_transformers/long_context_reorder.py
Related Articles
- Deterministic Constraint Systems: Building Tool Registries That Keep Agents in Scope
- Normalization and Input Defense: Hardening the Entry Point of Your LLM System
- State Management for Agentic Systems: How to Build Agents That Don't Start Over
- Harness Engineering: The Missing Layer Between LLMs and Production Systems






