Compaction Is Lossy: How to Measure What Your Summary Threw Away
From the publisher’s feed, collected in the ZeroLabs newsroom.
A test harness for summarization fidelity, because every long-running agent is one bad compaction from amnesia.Image 01: When AI Memory Compression Becomes AI Amnesia (image by Author)Three hours into a debugging session, in this composite assembled from several teams’ traces, an agent had accumulated exactly the kind of context that makes long-running agents valuable: the original error message (a 400-character Redis connection string with a revealing typo), a list of four fixes already tried and failed, a growing hypothesis about a connection-pool exhaustion, and seventeen files touched along the way. Then the context hit 85% full, and the compaction fired — as designed, on schedule, exactly per the context engineering playbook.The summary it produced was, by any editorial standard, excellent. Clear narrative arc. Good prose. “The session has involved extensive debugging of Redis connectivity issues; several approaches have been attempted; investigation is ongoing into connection management.” A reader would have called it a model of concision.The next turn, the agent asked to see the original error message. Re-fetched it. Re-ran the diagnostic it had run at minute twenty. And then — the moment the team found when they audited the trace — it re-tried fix number two, the one that had already failed, because “several approaches have been attempted” contains no approaches. The compaction had saved roughly 120,000 tokens of context. The re-derivation it induced — re-fetches, re-runs, one repeated dead-end fix, and the human hour spent wondering why the agent was going in circles — cost multiples of that, before counting the humiliation.This is the failure the industry’s compression evaluations have now quantified, and the headline finding deserves quoting because it inverts the metric everyone optimizes: “compression ratio turned out to be the wrong metric entirely” — because lost details force re-fetching that consumes more than the compression saved. Teams celebrate 99% compression the way the cold-open team did, right up until they price the amnesia.So here is the sentence to carry: a summary is a bet about what the future will need, placed under a token budget, by a model that cannot see the future — and almost nobody checks who won the bet. Every compaction is this wager. The stakes are your agent’s continuity — its goal, its obligations, its doubts, its hard-won negative knowledge — and the house edge is brutal, because the summarizer optimizes for what summarizers have always optimized for: reading coherence, when the only consumer is a machine that needs to act. This article is about measuring the bet, structuring it, and gating it — the test harness for the operation your agent performs on its own memory, unsupervised, dozens of times a week.It closes the failure-shapes arc of the series that began with The Harness Is the Product — fittingly, because compaction loss has been the mechanism under half this arc’s stories: the telephone game that eroded goals, the dropped TODOs that became omissions, the stripped hedges that laundered confidence. Time to meet the machine itself.Image 02: The betPart 1: The Amnesia Inventory — What Summaries Systematically LoseCompaction isn’t optional — windows are finite, cost scales with context, and rot arrives before the window fills — so the question is never whether to compress but what your compressor throws away. Audit post-compaction failures across teams and the losses aren’t random; they cluster into seven classes, each with a signature downstream symptom:Exact identifiers. Error strings, file paths, ticket IDs, commit hashes, API parameters. Narrative summarization paraphrases — that’s what fluent summarization is — and a paraphrased identifier is a destroyed identifier: the successor needs the 400-character connection string byte-exact, not “a Redis connection error.” Symptom: re-fetching things the context used to contain.Negative knowledge. The tried-and-failed list is the most expensive loss in the inventory, because its absence doesn’t just cost a lookup — it costs a repetition: fix number two, re-tried with fresh confidence. The keep-errors-in rule from context engineering exists precisely because failure history steers the search; compaction is where that rule quietly dies, converting “tried X, failed because Y” into “several approaches attempted.” Symptom: the agent walking in circles that the trace shows it already walked.Obligations. The omission article’s dropped threads: a ten-step plan compacted twice is an eight-step plan with unmarked graves. Symptom: 214-minus-9-equals-done.Doubt and provenance tags. The confidence launderer: “probably X, single-source” summarizes to “X.” Hedges are exactly the kind of detail fluency sheds, and their loss is how step-12 guesses become step-37 premises. Symptom: downstream certainty the upstream never had.The goal itself. Telephone, played solo — “migrate 214 services without behavior change” → “improve logging.” Symptom: diligent work on a drifted objective.Quantities and specifics. Numbers rounded, thresholds dropped, “the 3 failing tests in auth_test.py” becoming “some test failures.” Symptom: decisions downstream made on vaguer ground than the run had earned.State-of-the-world markers. As-of tags, freshness stamps, which-version qualifiers. Symptom: stale beliefs with no expiry metadata, indistinguishable from fresh ones.Notice what unifies the list: every class is operationally critical and narratively optional. A human editor would cut all seven to make the summary read better — and the summarizer is, in effect, a human editor’s training distribution wearing an API. The mismatch is structural: the summary’s only reader is a machine that needs to act, and it’s being written for a reader who wants to understand. Nobody is ever going to curl up with your compaction. Stop writing it for them.Part 2: Measuring the Bet — The Probe HarnessYou can’t improve what you can’t score, and the compression-evaluation work that’s emerged gives the right template: probe the compacted context functionally — not “is this summary similar to the original?” (lexical overlap is the wrong question) but “can the successor still operate?” Four probe families, asked of the post-compaction context:Recall probes — “What was the original error message?” Tests identifier survival, verbatim.Artifact probes — “Which files have we modified?” Tests the working-set inventory.Decision probes — “What did we decide about the Redis issue, and why?” Tests conclusions with rationale — a decision without its why gets relitigated.Continuation probes — “What should we do next?” The integrative test: does the compacted context still imply the same next action the full context did?Score the answers on operational dimensions — accuracy, artifact-trail completeness, continuity-without-refetching, instruction retention — and you have a fidelity number that means something. When the public evaluations ran exactly this protocol across compression approaches, two findings stood out. First, structured summarization beat narrative summarization across the board (the best structured approach scored 3.70 against 3.35–3.44 for major providers’ defaults on a 0–5 scale) — foreshadowing Part 3’s entire argument. Second, the margin held even while compressing slightly less, which is the ratio-is-the-wrong-metric finding in numbers: the quality differences exceed the token savings, because every failed probe in production is a re-fetch, a re-derivation, or a repeated mistake billed against the “savings.”Two upgrades make the harness yours rather than generic. Mine your probes from your traces: every post-compaction re-fetch in your history is a labeled loss — the successor literally telling you what the bet lost — so the probe suite writes itself from the re-fetch log, weighted by what your runs actually needed. And track the two smoking guns as standing metrics: post-compaction re-fetch rate and post-compaction repeated-action rate. Those two numbers are your amnesia bill, itemized; the cold-open team’s audit started with exactly that query, and most teams who run it for the first time stop arguing about compression ratios the same afternoon.Two methodological notes for building the harness well. First, probes are a proxy, and the gold standard is downstream performance — the truest fidelity measure is running the same continuation task from full and compacted contexts and diffing the outcomes (the counterfactual method, aimed at memory). That’s expensive, so the working arrangement mirrors every measurement stack in this series: downstream-task evals run occasionally to validate the probes (do probe scores predict continuation quality? if not, your probes test the wrong things), and probes run routinely because they’re cheap. Second, calibrate probe difficulty against reality, not completeness. A probe suite that demands byte-recall of everything is testing for a summary that defeats compaction’s purpose; the suite should demand what successors actually needed — which is why mining probes from the re-fetch log matters more than inventing them: the log is a frequency-weighted record of real demand, and a probe suite built from it automatically prices identifier-recall above trivia. The failure mode of invented probe suites is uniform strictness; the re-fetch log teaches you where strictness pays.Image 03: The probe harnessPart 3: Engineering the Honest CompactionStructure over narrative — force the bet to cover its categories. The single highest-yield change: replace “summarize this conversation” with a schema whose sections are the amnesia inventory inverted — identifiers (verbatim, in a fenced block the summarizer may not rewrite), tried-and-failed (each with its failure reason), open obligations (the tracked list, untouched), decisions with rationale, current working state, and next steps. Structure wins for a mechanical reason: a narrative bet is placed holistically, and holistic bets under budget pressure shed the operationally-critical-but-narratively-optional — which is everything in Part 1. A schema’d bet is placed per category, and an empty “tried-and-failed” section is visible in a way a missing nuance never is. The obligation-schema logic from the omission article, applied to the summary itself: make absence conspicuous.The protected set crosses byte-for-byte. The series has been accumulating members: the goal, the obligations, the doubt and provenance tags — add exact identifiers, and enforce the set as a diff test, not a prompt suggestion: protected strings present before compaction must be present after, checked mechanically, compaction rejected on failure. This is a five-line test that retires four of the seven loss classes outright.Compress to pointers, not to prose. The deepest fix reframes what compaction is: the choice isn’t summarize-or-keep — it’s summarize-or-archive. Move the raw segment to storage (the filesystem, the memory system — context is RAM, disk exists); leave in context a structured summary plus a pointer (“full debugging transcript: archive/run-4471/segment-3”). Now a failed bet costs a lookup, not a re-derivation — the successor that needs the original error message retrieves it in one tool call instead of re-running twenty minutes of diagnosis. Addressable recall converts compaction from destructive to non-destructive compression, and it’s the difference between betting your memory and betting your working set. The corollary rule is absolute: never compact what you haven’t archived. An unarchived original makes every summarization error permanent.Brief the summarizer like the worker it is. The compaction prompt deserves the same craft as any sub-agent brief, and most are one careless sentence. The summarizer should be told, explicitly: its audience (“your only reader is the model that resumes this task; it needs to act, not to understand — no narrative flow required, no elegance, no transitions”); the current task phase (what’s in flight right now, so the hot working set gets protected weighting — the summarizer can’t know the plan’s position unless the plan is state and you hand it over); and relevance hints from the future (the remaining plan steps, so the bet on what-matters is informed by what’s coming — a summary made before a deployment phase should over-retain configuration details it would otherwise shed). This last one is the quiet advantage the harness holds over any generic compression: the summarizer inside your system doesn’t have to guess the future — the plan, the obligations, and the goal file are sitting right there, and a compaction brief that includes them converts the blind bet into an informed one. Generic compression compresses the past. A briefed compaction curates the past for a known future, which is a different and much easier problem.One record, two renderings. A quiet corollary of structure-over-narrative: once the compaction produces a structured record, prose becomes a view of it, not a replacement for it. Plenty of teams need a human-readable session summary too — for the reviewer approving a gate, for the inbox where escalations land, for the retro. The trap is letting that need shape the machine’s memory: one summary, written for both audiences, serves neither — and the human’s preferences always win the prompt war, because humans are the ones who complain about ugly summaries. The machine never complains; it just quietly re-runs fix two. So keep one source of truth — the schema’d record — and render twice: the successor gets the record itself, categories and verbatim blocks and all; the human gets a short narrative generated from the record, clearly downstream of it, free to be as elegant as it likes because nothing operational depends on it. This kills the beautiful-narrative failure mode at the root rather than fighting it per-prompt, and it means the two renderings can’t drift apart in substance — they share a parent.Budget by loss-cost, not by volume. Compaction budgets default to proportionality — big sections compressed hard — but volume anticorrelates with loss-cost: 80,000 tokens of tool noise compresses 100:1 nearly free, while 400 tokens of decisions-with-rationale barely compress at all without relitigating something. Allocate the survivor’s token budget the way the economics article allocates spend: by what it costs to lose, not what it costs to keep.Part 4: Advanced — The Cliff, the Clock, and the GateNever summarize a summary. Repeated compaction is where loss stops being linear and starts compounding — the k-round telephone game, and the mechanism behind the “compaction cliff” phenomenon long-running agents hit: each round re-bets on the previous round’s survivors, so a detail’s survival probability decays geometrically and the fifth-generation summary describes a different session. The rule that breaks the game is simple and rarely implemented: re-summarize from the archived original, every time. Round three’s summary is a fresh compression of the full archive (or its structured extract) under current relevance — not a compression of round two. With archives and pointers from Part 3, this costs one longer summarization pass and removes the compounding entirely; the fidelity curve goes flat instead of cliff-shaped. If you adopt one advanced practice from this article, it’s this one.Compact at boundaries, not at thresholds. The 85%-full trigger fires wherever it fires — routinely mid-task, when the working set is hottest and the loss-cost is maximal. The cold open’s compaction landed in the middle of a debugging loop; the same compaction after the fix landed, at a task boundary, would have lost almost nothing that mattered. The harness knows more than the threshold does: it knows task state, plan position, whether a tool call is in flight. Compaction timing should prefer natural boundaries — task completion, phase transitions, the moments checkpoints already prefer — deferring the guillotine briefly when the agent is mid-something, exactly like the drain logic already defers the stop. Threshold as backstop; boundary as policy.Keep the tail raw. One region of context should be exempt from the bet entirely: the most recent turns. Recency is the cheapest available proxy for the working set — the thing the agent is doing right now lives in the last handful of exchanges, and no summarizer, however well briefed, beats “just don’t touch it” for that span. The standard split, and the one worth copying: compact the cold head (everything before the current phase) into the structured record, carry the hot tail (the last N turns, N chosen by task rhythm rather than token count) verbatim, and let the boundary between them advance only at the task boundaries the previous rule prefers. The anti-pattern this replaces is proportional middle-out truncation — squeezing everything evenly, which degrades the working set exactly as much as the ancient history it should be spending its budget on. Loss-cost isn’t uniform across time any more than it’s uniform across content; the tail is where it peaks, and the correct compression ratio there is 1:1.The cache bill nobody itemizes. There’s a second economic term in the compaction decision that rarely makes it into the arithmetic: every compaction rewrites the context prefix, and a rewritten prefix is an invalidated prompt cache. The turn after a compaction is billed at full input rates for the whole rebuilt context, where the turn before it was paying cached rates on everything but the increment — on current pricing, a 5–10× difference on the cached span. Frequent small compactions are therefore worse than their token math suggests: each one trades a modest context reduction for a full cache rebuild, and a harness that compacts eagerly can spend more on invalidation than it saves on length. This tilts the same direction as everything else in this section — compact less often, at boundaries, in larger consolidations — which is the pleasant case where the fidelity argument and the economics argument agree. The EV gate below should carry the cache-rebuild cost as an explicit input; teams that add it find another slice of their compactions turning out to be negative expected value before a single probe runs.Gate the bet before committing it. The full circle: run the probe suite on the candidate summary before it replaces anything — recall probes against the protected identifiers, continuation probes against the pre-compaction next-step, the diff test on the protected set. Failures don’t ship; they become repair instructions (“the summary lost the tried-and-failed list; regenerate, preserving it”) for a second pass. This is the offline-gate philosophy from behavior flags aimed at the run’s own memory: the verdict happens before the amnesia, when the original still exists to check against. One extra model pass per compaction; at what a failed bet costs, it prices in easily for any run that matters — and with archives in place, even a gate miss is recoverable, which is what defense-in-depth looks like when the asset is memory.Sometimes the right compaction is none. With loss priced honestly, a fourth option joins summarize/archive/gate: carry the tokens. The economics that motivated compaction — context cost per turn — cuts both ways once you can quantify the other side: for a run in its final stretch, a compaction that risks the working set to save twenty turns of carrying cost is a bad trade; for a deadline-pressured run, the compaction pass itself costs latency the wall may not have. The decision is the same expected-value gate as everything else: expected loss-cost (probe-failure rate × re-derivation cost × remaining-run exposure) against carrying cost (tokens × remaining turns) — and the inputs are all things the harness knows. Teams that wire this arithmetic discover their compaction frequency was miscalibrated in both directions at once: firing mid-task where loss-cost was maximal, and firing near run-end where carrying twenty more turns was nearly free. The threshold wasn’t wrong; the question was — not “is the context full?” but “is this compaction, now, positive expected value?” Ask the second question and roughly a third of your compactions turn out to be neither necessary nor cheap.The fleet compacts at every seam. Worker summaries at fan-in are compactions — same physics, same losses, same fixes: schema’d summaries (the brief’s obligations reported per-item), protected identifiers crossing verbatim, pointers to full worker transcripts, and probe checks at synthesis. The telephone game between agents and the telephone game within one agent’s memory are the same game, and this article’s machinery plays both.Animation: The five-round telephonePart 5: Case StudiesThe Redis session, remediated. The cold open’s fix stack in shipped order: structured schema with a mandatory tried-and-failed section (day one — the repeated-fix class died immediately); protected-set diff test on identifiers (day two); archive-and-pointer (week two — re-fetch cost collapsed to lookups); probe gating on high-stakes runs (week three). The team’s summary line for the retro earned its frame: “the summary was optimized for a reader, and its only reader was a machine that needed to act.” Their post-compaction re-fetch rate — the metric that started the project — dropped by roughly four-fifths, and the residue is now mostly deliberate pointer-follows rather than confused re-derivations, which is the difference between a filing system and a memory hole.The evaluation that reframed the metric. The public compression evals deserve their case-study slot for what they legitimized: functional probing as the fidelity measure, structured-over-narrative as a measured result (3.70 vs 3.35–3.44), and the ratio finding — quality differences exceeding token savings — that gives every engineer the sentence they need in the meeting where someone proposes celebrating 99.3% compression. The methodological point generalizes past any vendor comparison: summaries are infrastructure, and infrastructure gets acceptance tests. Yours are four probe families and an afternoon away.The five-round telephone, measured. Composite. A team ran the k-round experiment on their own archived sessions: probe fidelity after each of five successive compactions, chained versus re-summarized-from-original. The chained curve fell off the cliff the literature names — near-parity at round one, degradation by round three, and a round-five summary that failed every continuation probe (it recommended, as next step, a phase the session had completed twice). The from-original curve stayed within noise of round-one fidelity throughout. Cost difference: seconds of additional summarization latency per round. The chart made the policy decision for them, and it will make it for you; this experiment is a day, and it ends the summary-of-a-summary practice in any organization that runs it.The key that almost vanished. Composite, short, and the reason probe gating exists on their payments path: a mid-run compaction candidate dropped an idempotency key for an in-flight refund — narratively irrelevant, operationally the only thing standing between a retry and a double charge. The recall probe on protected identifiers caught it; the regenerated summary carried it; the refund retried safely that afternoon. Cost of the gate: one model pass. The counterfactual: an article this series already wrote.Part 6: The LandscapeBuild: the probe suite (mined from your re-fetch logs); the structured compaction schema; the protected-set diff test; archive-and-pointer plumbing; the two smoking-gun metrics on the trace dashboard; boundary-preferring compaction triggers.Lean on: your harness’s compaction hooks (most frameworks now expose the summarization prompt — that’s where the schema goes); memory systems and files for the archive tier; your eval harness for probe scoring; provider compaction features — after you’ve probed what they lose, because defaults are exactly the narrative bets this article is about.My advice on choosing: run the re-fetch audit first — one trace query, and it tells you whether you have a problem and how big. Then the schema (an afternoon), then the diff test (an hour), then archives (the real project, and the one that changes the game). Probe gating comes last and only where stakes warrant.The whole idea in miniature:def compact(ctx, run): segment = ctx.compressible_region(prefer=task_boundary) # boundaries, not thresholds archive.put(run.id, segment) # NEVER compact the unarchived candidate = summarize(segment, schema=STRUCTURED, # categories, not narrative protect=run.goal | run.obligations | run.doubt_tags | run.identifiers) assert diff_protected(segment, candidate) == set() # byte-for-byte, mechanically for probe in PROBES.sample(run): # can the successor still act? if not probe.passes(candidate): candidate = resummarize(segment, repair=probe.failure) # gate, then repair return candidate + pointer(archive.ref(run.id)) # a lookup, not a re-derivation # and next time: re-summarize from archive.get(run.id) — never from this summaryPart 7: The Failure Modes Field GuideThe beautiful narrative. Reader-optimized prose for a reader who doesn’t exist. Cure: the schema — sections from the amnesia inventory, coherence demoted.The paraphrased identifier. The 400-character error string becomes “a connection error.” Cure: identifiers verbatim in the protected set, diff-tested.The vanished negative knowledge. “Several approaches attempted” → fix two, re-tried. Cure: tried-and-failed as a mandatory section with reasons.The summary of a summary. Geometric decay; the fifth generation describes a different session. Cure: re-summarize from the archived original, every round.The 85% guillotine. Compaction firing mid-debugging, at the working set’s hottest. Cure: boundary-preferring triggers; the threshold as backstop only.The unarchived original. Every summarization error made permanent. Cure: archive before compressing — no exceptions, it’s one PUT.The ratio trophy. 99.3% compression celebrated while re-fetches eat the savings. Cure: the two smoking-gun metrics next to the ratio, always.The launderer, again. Hedges and as-of tags stripped in transit. Cure: doubt and provenance in the protected set — you knew this one.The unprobed bet. Fidelity assumed, discovered at the repetition. Cure: probe gating where stakes warrant; the re-fetch audit everywhere.Part 8: How to Start — A One-Week PlanDay 1: Run the amnesia audit. Query last month’s traces: re-fetches and repeated actions within N turns after a compaction event. That number is your bill.Day 2: Write the schema. The structured summary with the inventory’s sections; deploy it in the compaction prompt.Day 3: Build the diff test. The protected set, checked mechanically, compaction rejected on failure.Day 4: Stand up the archive. Raw segments stored before compression; pointers in every summary. Verify a re-fetch resolves via lookup.Day 5: Mine the probes. Ten probes per major task type from your re-fetch history; score your current compaction against them for a baseline.Day 6: Fix the trigger. Boundary-preference with threshold backstop; defer when mid-task.Day 7: Run the telephone experiment. Five rounds, chained vs from-original, probes at each round. Frame the chart; it ends the argument.Conclusion: The Big-Window Camp and the Judgment CampThe big-window camp says this is transitional engineering for a closing constraint: context windows have grown a thousandfold and keep growing; the million-token window makes compaction a niche concern, and this article’s machinery will read like disk-defragmentation lore — craftsmanship for a problem hardware solved.The judgment camp says the window was never the binding constraint. Attention degrades long before windows fill — the million-token mirage was this series’ finding three arcs ago — cost scales with what you carry, and selection is not a workaround for small memory: deciding what the past means and what the future needs is a cognitive act, not a storage problem. Systems that keep everything don’t remember everything; they drown in everything, fluently.The big-window camp is right that the frequency changes — bigger windows mean fewer, later compactions, and some sessions will never need one. Take that win. But watch what every window generation has actually done: the tasks grew to fill it, the long-running agents got longer-running, and the compaction moved out to where it’s rarer and higher-stakes — a bet placed less often, for more. Which is the judgment camp’s deeper point: a summary is the agent exercising judgment about its own history, and judgment doesn’t deprecate — it just gets more expensive to get wrong. Engineer the bet. Archive the original. Probe the survivor. The window will keep growing, and none of those three sentences will stop being true.The homework is Day 1, and it’s one query: count last month’s post-compaction re-fetches and repeated actions. That’s the amnesia bill you’re already paying — and unlike most bills in this series, this one comes with the itemized list of exactly what to stop losing.Part of the series that began with The Harness Is the Product. This closes the failure-shapes arc: The Omission Bug, Almost Right, Whose Fault Was That?, Confidence Is a Feature, and this piece. Next, the series turns to law, records, and provenance — starting with the request this whole arc has been quietly complicating: the user who says “forget me”, and what deletion even means in a system built from vector stores, traces, checkpoints, and derived summaries.Compaction Is Lossy: How to Measure What Your Summary Threw Away was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.