Context Compaction for AI Agents: Keeping Long Runs Inside the Window
When an agent run outgrows the context window, dropping the oldest turns is the default and the fastest way to lose the idempotency key, the job handle, and the constraint the user stated in their first message. This article builds context compaction as a memory design: a structured anchor block the harness renders and updates outside the transcript, an audited summary for the narrative, side-effect machinery that reads the ledger and never the context, and a test battery that pins each property.
A data-migration agent is on step 41 of a run that has read thirty schema dumps, fixed two failing mappers, and opened a ticket. The transcript holds 190,000 tokens; the window is 200,000; the next request does not fit. The harness does what most do — drops the oldest turns until it does. Three things leave with them: the idempotency key minted at step 3 for the migration job, the user's first-message constraint "never write to the production database", and the handle of the validation job still running in the background. Step 42 relaunches the migration with no key. The run succeeds twice.
Context compaction is the component that decides what survives that moment. It is not a summarization feature bolted onto the harness. It is a memory design with two constraints — the model's working set must fit the window for the length of the run, and nothing the run's correctness depends on may be paraphrased — and this article is about building it so that both hold.
The window is a budget the run spends
Every turn adds to the context, and nothing in the default loop ever removes from it. The cost arrives in three forms:
The hard limit. At some point the request no longer fits and the harness has to choose what to drop. With no design behind it, the choice is "the oldest" — which is exactly where the run's foundational facts live: the goal, the constraints, the first identifiers.
Attention. A fact can be present and still be missed. Long contexts degrade the model's use of middle material, so a constraint stated 180,000 tokens ago carries less weight than a tool result from the last step even when nothing was dropped at all.
Cost. Each turn re-sends the whole prefix. Ten steps that each grow the context by 20,000 tokens add up to a million tokens of cumulative prefill; prompt caching discounts the repeated bytes but does not shrink the growth.
So the question is not whether to compact but what the compacted context is allowed to forget. That is a split, and the split is the whole design.
Two kinds of memory: the ledger and the narrative
What sits in a transcript falls into three classes, and compaction treats each one differently:
- Anchors are facts whose exact form the run depends on: identifiers (order 8123, cluster prod-eu-2), idempotency keys, job handles, ETags and versions, the goal, the user's constraints, approvals and denials with their reasons, and the decisions taken so far. Losing one does not degrade the run — it silently redirects it.
- Narrative is what was tried, what came back, and what it meant. It can be summarized: the cost of a lossy summary is a repeated question, not a duplicate write.
- Raw results are tool outputs — schema dumps, list pages, logs. They can be evicted behind a stub, because the ledger knows how to fetch them again, and result caching makes refetching cheap.
The compaction step rewrites the narrative, carries the anchors verbatim, and replaces raw results with references. The rule that carries the most weight: anchors never pass through the summarizer. They are extracted by code from the places the harness already records them, never from the model's recollection of the conversation.
Design the anchor block like a schema, not a prompt
The anchors need a shape, because a shape can be rendered, validated, and budgeted:
@dataclass
class Anchors:
goal: str
constraints: list[str] # user-stated, kept verbatim
entities: dict[str, str] # "order" -> "8123", "cluster" -> "prod-eu-2"
idempotency_keys: dict[str, str] # logical operation -> key
job_handles: dict[str, str] # logical operation -> handle
decisions: list[dict] # what, verdict, by, why
next_steps: list[str]
def render_anchors(a: Anchors) -> str:
lines = ["<anchors>", f"goal: {a.goal}"]
lines += [f"constraint: {c}" for c in a.constraints]
lines += [f"{name}: {value}" for name, value in sorted(a.entities.items())]
lines += [f"idempotency_key[{op}]: {key}" for op, key in sorted(a.idempotency_keys.items())]
lines += [f"job_handle[{op}]: {handle}" for op, handle in sorted(a.job_handles.items())]
lines += [f"decision: {d['what']} -> {d['verdict']} ({d['why']})" for d in a.decisions]
lines += [f"next: {step}" for step in a.next_steps]
lines.append("</anchors>")
return "\n".join(lines)
Three properties matter more than the fields. The block is rendered by the harness on every request from the structured record, so it is byte-identical before and after every compaction. It is updated by the harness, not the model: the key is recorded when the harness mints it — the idempotency chapter put key generation in the harness because the harness owns the retry loop — the handle when the async call returns one, the approval when the gate answers. The one class only the model hears is a user constraint stated mid-conversation, and that gets a remember(constraint=...) tool: a write into the record, not a note in the transcript. And the block is budgeted — two thousand tokens is plenty — with a fail-closed check: a run whose anchors outgrow the budget stops and reports, because an anchor block that itself needs compacting has lost the property it exists to provide.
Compaction is a step with a contract
Trigger on tokens, never on step count — the same step can cost three thousand tokens or thirty — and make the step itself explicit:
def maybe_compact(run, window, reserve, threshold=0.7):
if estimate_tokens(render_request(run)) <= threshold * (window - reserve):
return
compact(run)
def compact(run, keep_last=4, summary_budget=800):
assert not run.in_flight() # every call settled; handles live in anchors
old_tokens = estimate_tokens(render_request(run))
summary = summarize(run.messages[:-keep_last], anchors=run.anchors, budget=summary_budget)
problems = audit_summary(summary, run.anchors, run.ledger)
if problems:
summary = summarize(run.messages[:-keep_last], anchors=run.anchors,
budget=summary_budget, fix=problems) # one repair pass
problems = audit_summary(summary, run.anchors, run.ledger)
if problems:
run.trace.event("compaction_aborted", problems=problems)
return # keep the old context; the budget guard stops the run
run.messages = [system_message(run.anchors), summary_message(summary), *run.messages[-keep_last:]]
run.trace.event("compacted", before=old_tokens, after=estimate_tokens(render_request(run)),
anchors=run.anchors.count())
Five details carry the value. Freeze first: no call in flight when the context is rewritten, because the result would arrive into a conversation that no longer contains the call that produced it (a running job is fine — its handle is already an anchor, and the first step after compaction polls it). The summarizer sees the anchors so it describes the narrative around them instead of paraphrasing them. Audit the output: an anchor string that appears in the summary must appear exactly — a key with one character dropped is worse than a key that is absent — and any identifier-shaped token in the summary that is not in the ledger is an invention, which rejects the summary. Record the event: the trace gets a compacted entry with before and after sizes, because replay and observability both need to know why the context changed mid-run. Keep the last few turns verbatim: the current step's reasoning must not be summarized underneath the model.
The transcript is not the record of truth
The failure in the opening had one cause: the key existed only in the transcript. The rule that removes the whole class: side-effect machinery reads the ledger, never the context. The write path looks up the idempotency key by logical operation in the record and injects it at execution time; the approval gate checks the decisions table; the resume path reads the handle table. Whether the model remembers is then irrelevant, because it does not need to.
def execute(call, run):
op = logical_operation(call) # "migrate_orders", from the tool manifest
key = run.anchors.idempotency_keys.get(op) or mint_key(run.id, op)
run.anchors.idempotency_keys[op] = key # recorded before the first attempt
return transport.send(call, idempotency_key=key)
Two corollaries. A repeat detector keyed on the ledger — same tool, same argument hash, as a call that already failed earlier in the run — catches the loop a compacted model falls into, and it survives compaction because it never lived in the context. And compaction itself must never be the thing that triggers a side effect: it is a read of the transcript and a write of the context, with no tool calls in between.
Summaries drift; anchors don't
A model-written summary is optimistic by nature. "Investigated the schema mismatch and made progress" is not a summary; it is a status report. Constrain the form instead of hoping:
- Fixed sections: Done (with references to ledger entries, not re-descriptions), Tried and failed (tool, argument hash, error class — one line each), Open questions, Next.
- Failures come from the ledger, explanations from the model. The harness lists the failed calls; the model says why each one failed. A summary that omits a failure the ledger records is rejected by the audit.
- User text stays verbatim. A paraphrased constraint is a new constraint.
- Deterministic decoding and a hard budget. A summary that is a third of the window is a transcript with extra steps.
Measure compaction like a component
- Repeat-after-compaction rate. Same tool and argument hash called again within a few steps of a compaction event. This is the direct measure of lost knowledge, and it should sit near zero.
- Compactions per run and tokens at trigger. A run that compacts every three steps is a run whose results are not being evicted — fix the result handling, not the summarizer.
- Anchor size against its budget, and rejections per compaction. A rising rejection rate means the summarizer has started paraphrasing anchors; the audit is doing its job, and the summarizer's prompt needs to change.
- Long-horizon eval. Tasks that plant a fact early and need it late — an identifier from step 2 used at step 40 — run with and without a forced compaction in between. The delta is the component's real cost.
Pin the behavior with a fake transcript
Every property above is testable with a fake transcript and a scripted summarizer, no model in the loop:
KEY = "7f9d2c1e-44a2-4b61-9d0e-2f1c0b9a7e33"
def test_anchors_survive_compaction_byte_exact():
run = Run(messages=transcript(40))
run.anchors.idempotency_keys["migrate_orders"] = KEY
compact(run)
assert f"idempotency_key[migrate_orders]: {KEY}" in render_request(run)
def test_summary_that_alters_a_key_is_rejected():
run = Run(messages=transcript(40))
run.anchors.idempotency_keys["migrate_orders"] = KEY
before = list(run.messages)
SUMMARIZER.reply = "Migrated orders under key " + KEY[:-1] + "." # one character short
compact(run)
assert run.trace.last("compaction_aborted").problems == ["anchor altered: " + KEY]
assert run.messages == before # the old context is kept intact
def test_write_after_compaction_carries_the_ledger_key():
run = Run(messages=transcript(40))
run.anchors.idempotency_keys["migrate_orders"] = KEY
compact(run)
call = Call("migrate_orders", orders=[8123]) # the model forgot the key
sent = harness.execute(call, run)
assert sent.idempotency_key == KEY # injected from the ledger
def test_handle_and_constraint_survive():
run = Run(messages=transcript(40))
run.anchors.job_handles["validate_schema"] = "job_42"
run.anchors.constraints.append("never write to the production database")
compact(run)
request = render_request(run)
assert "job_42" in request
assert "never write to the production database" in request
def test_compaction_is_a_trace_event():
run = Run(messages=transcript(40))
compact(run)
event = run.trace.last("compacted")
assert event.after < event.before and event.anchors == run.anchors.count()
The long-horizon eval is the one test that needs the model: a fixed set of tasks, a fact planted at the start, a compaction forced in the middle, and an assertion on the fact's exact form at the end. Keep the compaction point as a parameter so the same eval measures the summarizer, the anchor extraction, and the audit in one sweep.
The model gets a working set; the run keeps its memory
The rules compress to five. The context is a budget the run spends, and compaction is a designed component, not an emergency eviction. Split what the context holds into anchors, narrative, and raw results — anchors verbatim and never through the summarizer, narrative summarized under a fixed form, results replaced by references. Render the anchor block from a structured record the harness owns and updates; keep it small, budget it, and stop the run when it outgrows the budget. Make compaction a step with a contract — frozen, audited, recorded — and keep side-effect machinery reading the ledger, never the transcript. And measure the repeat-after-compaction rate, because a compaction nobody measured is a truncation with extra steps.
The series built the pieces this chapter leans on: idempotency keys minted in the harness, command ledgers that hold the record outside the model's reach, result caches that make eviction cheap, async calls whose handles are capabilities. Compaction is where they stop being per-call safeguards and become the run's memory. The model gets a working set that fits; the run keeps what it cannot afford to forget.
About this story
This article was written by Gen-AI using GPT 5.5 or Opus 4.7. Verify technical guidance before using it in production systems.