{"slug": "context-degradation-in-long-conversations-measuring-context-rot-and-fixing-it", "title": "Context degradation in long conversations: measuring context rot and fixing it", "summary": "A Node.js benchmark harness run against OpenAI's gpt-4.1-mini from 2,000 to 52,000 tokens found that classic needle-in-a-haystack retrieval accuracy barely dropped, but latency more than doubled and per-turn token cost jumped 25x, according to the author Flavio. The tests covered buried policies, multi-hop facts, noisy multi-turn rule checks and a polluted debugging session, and the author attributes real quality failures in long coding chats to mechanisms such as prefill cost and stale history competing for attention rather than raw prompt length. The author argues that advertised context windows of 128k, 200k or 1 million tokens describe only the hard ceiling before an HTTP 400 context_length_exceeded error, not the size at which a model still reasons reliably.", "body_md": "# Context degradation in long conversations: measuring context rot and fixing it\n\nBy [Flavio](https://flaviocopes.com/about/)\n\nTagged: [AI](https://flaviocopes.com/tags/ai/)\n\nWhy long agent chats slow down, cost 25x more, and drift before hitting the context limit, with live 2k to 52k token benchmarks and recovery patterns.\n\nYou’re forty turns into a coding session. The status bar says you’ve only used 28% of the [context window](https://flaviocopes.com/ai-glossary/context-window/), so there’s plenty of room left.\n\nYet the session starts falling apart. The model ignores a naming rule you gave in turn two, then edits a helper function you already fixed twenty minutes ago.\n\nEach reply takes twice as long to start, too. And your usage meter climbs faster with every turn.\n\nPeople call this **context degradation**, or **context rot**. Because the prompt still fits inside the model’s advertised limit, nothing throws an error, so quality, speed, and cost decay quietly while the chat keeps growing.\n\nI wanted to separate the folklore from what happens on a modern model. So I built a small Node.js benchmark harness and ran real prompts against OpenAI’s `gpt-4.1-mini` from 2,000 tokens up to 52,000 tokens.\n\nThe tests covered four scenarios: buried policies, multi-hop facts, noisy multi-turn rule checks, and a polluted debugging session.\n\nThe results surprised me. Classic “needle in a haystack” retrieval barely dropped in accuracy, yet latency more than doubled and per-turn token cost jumped 25x.\n\nThe real quality failures in long coding chats come from much messier mechanics than raw prompt length.\n\nIn this guide, we’ll compare advertised limits with effective capacity and look at the exact numbers from my benchmark. Then we’ll break down the four mechanisms that derail long chats and build recovery patterns you can drop into your own harness or daily workflow.\n\n## Advertised context window versus effective context window\n\nModel release pages highlight huge numbers: 128k, 200k, or 1 million tokens. Those numbers describe the hard architectural ceiling.\n\nThey only tell you how many tokens the API accepts without returning an HTTP 400 `context_length_exceeded` error. They say nothing about whether the model reasons as reliably at token 50,000 as it does at token 2,000.\n\nWhy does that happen? A transformer computes attention across every token in the input sequence.\n\nWhen a prompt holds 2,000 tokens, the model works inside a compact, clean workspace. Your system rules, your target file, and your current question sit right next to each other.\n\nAt 52,000 tokens, every extra token adds more keys and values to that attention step. Even with modern rotary positional embeddings (RoPE, which encode token order) and long-context training, two practical costs hit you right away.\n\n### The prefill tax and competing history\n\nFirst, prefill work scales with input length. Before emitting the first output token, the inference engine has to read the whole prompt and build (or load) the key-value cache, the internal memory map it uses across all layers.\n\nLonger inputs mean slower time to first token, even if the reply itself is only three lines long.\n\nSecond, every token you leave in the history competes for attention. Old terminal stack traces, superseded diffs, and half-baked theories from thirty minutes ago sit in the same token stream as your current instructions.\n\nThe model has no native “archive” flag for stale turns. Unless your harness strips them out, the model has to guess from wording alone which older messages are obsolete and which ones still govern the task.\n\nPrompt caching lowers the bill for resending a long prefix, as I covered in [prompt caching, compression, and compaction in coding agents](https://flaviocopes.com/agent-prompt-caching/). Caching helps your wallet and trims prefill time on repeated prefixes, but it doesn’t clean the noise out of the attention pass.\n\nA cached 60,000-token mess is still a 60,000-token mess inside the model’s forward pass.\n\nThat gap between the maximum input a model accepts and the working size where it stays fast, cheap, and sharp is the **effective context window**. For most real coding work, your effective context window is far smaller than the number on the marketing page.\n\n## What our 2k-to-52k gpt-4.1-mini benchmark measured\n\nTo see what degrades first, I ran four automated probes against `gpt-4.1-mini` using a local Node.js script (`node run.mjs`). I saved every prompt token count, latency measurement, and raw reply to JSON.\n\nHere is what the four probes tested:\n\n- **Buried policy with a stale distractor:** We hid a 5-field payment retry config (`retry_backoff_ms: 1450` ,`max_retries: 5` ,`idempotency_header: \"X-Ledger-Key\"` ,`circuit_open_sec: 42` ,`rejects_negative_cents: true` ) alongside a stale distractor block. We placed it at the`top` ,`middle` , or`bottom` of padding ranging from ~2k to ~56k target tokens (actual sizes: 2,092 to 52,034 tokens).\n- **4-fact multi-hop synthesis:** Four numeric facts (`alpha: 14` ,`beta: 27` ,`gamma: 19` ,`delta: 33` ) scattered across documents of 1,852, 12,983, and 37,843 tokens, asking the model to collect all four and return their exact sum (`93` ).\n- **5-rule simultaneous constraint adherence:** A SQLite indexing question with five strict formatting and length rules (including a hard 45-word cap and inline SQL keywords). We tested it after 0, 4, 10, and 18 noisy prior turns (102 to 10,712 prompt tokens), then tested it again after a fresh handoff (116 prompt tokens).\n- **Polluted versus fresh debugging:** A real JavaScript date-math bug on March 29, 2026 in`Europe/Rome` , a 23-hour DST spring-forward day where`Math.floor((b - a) / 86400000)` returns`0` instead of`1` . We tested it once in a clean prompt and once after earlier turns chased an unrelated IEEE-754 and`BigInt` hypothesis.\n\nHere is the raw terminal output from the first two suites:\n\nAnd here is the visual summary comparing context size, position, latency, token count, and rule adherence:\n\nBelow are the full numbers from the buried-policy grid and the 4-fact synthesis runs.\n\n| Benchmark probe | Target size | Position | Actual prompt tokens | Accuracy | Latency (ms) | Cost multiplier vs 2k | \n|---|---|---|---|---|---|---|\n| Buried 5-field policy | ~2k | Top | 2,093 | 5/5 | 1,053 | 1.0x | \n| Buried 5-field policy | ~2k | Middle | 2,092 | 5/5 | 958 | 1.0x | \n| Buried 5-field policy | ~2k | Bottom | 2,093 | 5/5 | 856 | 1.0x | \n| Buried 5-field policy | ~8k | Top | 7,096 | 5/5 | 904 | 3.4x | \n| Buried 5-field policy | ~8k | Middle | 7,097 | 5/5 | 1,473 | 3.4x | \n| Buried 5-field policy | ~8k | Bottom | 7,096 | 5/5 | 960 | 3.4x | \n| Buried 5-field policy | ~16k | Top | 13,826 | 5/5 | 1,170 | 6.6x | \n| Buried 5-field policy | ~16k | Middle | 13,826 | 5/5 | 1,078 | 6.6x | \n| Buried 5-field policy | ~16k | Bottom | 13,825 | 5/5 | 2,069 | 6.6x | \n| Buried 5-field policy | ~32k | Top | 28,864 | 5/5 | 1,500 | 13.8x | \n| Buried 5-field policy | ~32k | Middle | 28,866 | 5/5 | 2,565 | 13.8x | \n| Buried 5-field policy | ~32k | Bottom | 28,864 | 5/5 | 1,301 | 13.8x | \n| Buried 5-field policy | ~56k | Top | 52,034 | 5/5 | 2,467 | 24.9x | \n| Buried 5-field policy | ~56k | Middle | 52,033 | 5/5 | 1,624 | 24.9x | \n| Buried 5-field policy | ~56k | Bottom | 52,032 | 5/5 | 1,909 | 24.9x | \n| 4-fact synthesis ( `sum=93` ) | ~2k | Scattered | 1,852 | 4/4 + sum | 810 | 1.0x | \n| 4-fact synthesis ( `sum=93` ) | ~16k | Scattered | 12,983 | 4/4 + sum | 890 | 7.0x | \n| 4-fact synthesis ( `sum=93` ) | ~44k | Scattered | 37,843 | 4/4 + sum | 1,563 | 20.4x | \n\n### Clean retrieval holds up, but latency and cost climb fast\n\n`gpt-4.1-mini` aced every single clean retrieval cell in that table. It returned `5/5` fields at top, middle, and bottom all the way out to 52,034 tokens.\n\nIt also returned `{\"alpha\":14,\"beta\":27,\"gamma\":19,\"delta\":33,\"sum\":93}` at 1,852, 12,983, and 37,843 tokens without missing a single integer.\n\nNow look at the latency and cost columns instead.\n\nAverage latency on the buried-policy test more than doubled, jumping from **956 ms** at 2k tokens to **2,000 ms** at 56k tokens. Single requests swung from **856 ms** at 2,093 tokens up to **2,565 ms** at 28,866 tokens (middle) and **2,467 ms** at 52,034 tokens (top).\n\nOn the 4-fact synthesis task, latency nearly doubled from **810 ms** to **1,563 ms**.\n\nPer-turn input tokens jumped **24.9x**, from 2,093 to 52,034 tokens. And in a multi-turn agent loop, you don’t pay that cost once.\n\nYou pay it on every follow-up turn. Ten more turns at 52,000 tokens process half a million input tokens just to make a handful of small edits.\n\n### Why needle-in-a-haystack benchmarks mislead developers\n\nIf you only checked the `5/5` accuracy column above, you might conclude that long contexts are solved. That’s the trap built into classic needle-in-a-haystack benchmarks.\n\nModern models are heavily post-trained to pass clean retrieval tests. When a distinctive policy block (`X-Ledger-Key`, `1450`, `42`) sits inside generic filler paragraphs, retrieval attention heads have an easy job because nothing else resembles those target keys.\n\nReal coding chats almost never look like clean filler plus one distinct needle.\n\nIn a real session, the “haystack” is packed with lookalikes:\n\n- Old versions of the same file.\n- Half-applied refactors using identical variable names.\n- Earlier messages you later reversed (“scratch that, skip Redis and use SQLite”).\n- 12,000 lines of test output referencing the same functions.\n\nUnlike irrelevant boilerplate, those stale tokens look like valid answers.\n\n### What happens in multi-turn conversations\n\nYou can already see the early warning signs in our second pair of probes, where we moved from static documents to multi-turn chat history.\n\n| Multi-turn probe | Session state | Prompt tokens | Output tokens | Latency (ms) | Outcome and drift notes | \n|---|---|---|---|---|---|\n| 5-rule SQLite answer | 0 noisy turns | 102 | n/a | 1,087 | 5/5 rules, 40 of 45 max words | \n| 5-rule SQLite answer | 4 noisy turns | 2,553 | n/a | 1,020 | 5/5 rules, 39 of 45 max words | \n| 5-rule SQLite answer | 10 noisy turns | 6,122 | n/a | 1,268 | 5/5 rules, 39 of 45 max words | \n| 5-rule SQLite answer | 18 noisy turns | 10,712 | n/a | 1,269 | 5/5 rules, 44 of 45 max words (word creep right to ceiling) | \n| 5-rule SQLite answer | Fresh handoff | 116 | n/a | 1,082 | 5/5 rules, 41 words, 98.9% fewer tokens | \n| Europe/Rome DST bug | Polluted history | 418 | 132 | 1,570 | Found DST root cause, spent extra tokens rebutting stale IEEE-754 / `BigInt` theory | \n| Europe/Rome DST bug | Fresh session | 166 | 98 | 1,131 | Direct DST explanation, 52% fewer total tokens, 28% faster | \n\nLet’s compare the real outputs from the 5-rule SQLite probe at turn 0 and turn 18.\n\nAt 0 noisy turns (102 prompt tokens, 40 words):\n\n```\n- Use `CREATE INDEX` to improve query performance by reducing full table scans.\n- Run `EXPLAIN QUERY PLAN` to analyze how SQLite uses indexes during query execution.\n- Indexes on columns in `WHERE` or `JOIN` clauses optimize data retrieval paths.\n```\n\nAfter 18 noisy turns (10,712 prompt tokens, 44 words out of the 45-word ceiling):\n\n```\n- Use `CREATE INDEX` to add indexes on columns to improve query performance.\n- Run `EXPLAIN QUERY PLAN` to analyze how SQLite uses indexes in your `SELECT` statements.\n- Indexes speed up lookups but slow down `INSERT`, `UPDATE`, and `DELETE` operations due to maintenance.\n```\n\nIt still passed all five rules, so a binary pass/fail check would say everything looks fine. Yet the reply quietly crept right up to the 45-word limit (one more word and rule 5 fails) while burning **105x more prompt tokens** (10,712 versus 102).\n\nWhen we reset to a fresh handoff, prompt tokens dropped by **98.9%** (from 10,712 down to 116). Latency fell back to 1,082 ms, and the reply stayed crisp at 41 words:\n\n```\n- Use `CREATE INDEX` to improve query performance by reducing full table scans.\n- Run `EXPLAIN QUERY PLAN` to analyze how SQLite uses indexes during `SELECT` statements.\n- Avoid redundant indexes; `DROP INDEX` removes unused or duplicate indexes to optimize storage.\n```\n\nThe polluted debugging probe showed a second kind of drag. In the fresh session (166 prompt tokens, 98 completion tokens, 1,131 ms), the model went straight to the root cause:\n\n```\nThe root cause is that constructing dates with a time string (' 00:00:00') causes\nthe Date objects to be interpreted in the local timezone, which on the DST\nspring-forward day results in one date being 23 hours apart instead of 24. This\nleads to the difference in milliseconds being less than 86400000, so Math.floor\nreturns 0 instead of 1. The code incorrectly assumes each day is exactly 24 hours,\nignoring DST shifts in the local timezone.\n```\n\nIn the polluted session (418 prompt tokens, 132 completion tokens, 1,570 ms), earlier turns had speculated about IEEE-754 floating-point drift and `BigInt` timestamps. Even though `gpt-4.1-mini` spotted the DST bug, that stale hypothesis lingered in its reply:\n\n```\nThe root cause is that March 29, 2026 is a DST spring-forward day in Europe/Rome,\nmaking that day only 23 hours long, so (b - a) is 23 * 3600000 = 82800000 ms\ninstead of 86400000 ms, causing the division and floor to yield 0. You should not\nrely on fixed 86400000 ms per day for date differences spanning DST changes;\ninstead, calculate differences using UTC dates or count calendar days. The\nIEEE-754 / BigInt fix is unrelated and unnecessary here since the issue is due to\nDST-adjusted day length, not floating-point precision.\n```\n\nThat polluted turn consumed more than twice the total tokens (550 versus 264) and took 39% longer (1,570 ms versus 1,131 ms) on a tiny 418-token prompt. Now picture what happens when the wrong theory isn’t two short messages, but twelve turns of half-written `BigInt` helper code, failed unit tests, and agent apologies.\n\n## Four mechanisms that break long coding conversations\n\nOnce you stop picturing context rot as “the model forgot a random string in filler text,” the real failure modes get much easier to spot and prevent. In production agent sessions, four mechanisms do most of the damage.\n\n### Distractor interference and competing instructions\n\nA coding repository is full of near-duplicates. You might have `src/billing/retry.ts`, `src/billing/retry-legacy.ts`, `tests/billing/retry.test.ts`, and three earlier diffs of `src/billing/retry.ts` sitting in turns 4, 11, and 19.\n\nEvery past file read stays in the message history as a snapshot of what the file *used* to look like. When turn 32 asks for an error-handling update, attention has to reconcile four slightly different versions of that function plus two user messages that changed the requirements halfway through.\n\nClean needle tests rarely reproduce this. In a clean test, you have one valid policy surrounded by unrelated prose.\n\nIn a real repo session, three plausible versions of that policy share the same variable names. Only timestamps or turn order separate the live version from the obsolete ones.\n\nThat leftover context triggers subtle regressions in long sessions. The model reintroduces a deleted parameter, reverts a renamed import, or applies a rule you canceled twenty minutes earlier, because those obsolete tokens are still sitting right there in the prompt.\n\n### Multi-turn self-anchoring and reasoning drift\n\nLanguage models generate each new token based on everything that came before it, including their own earlier assistant replies.\n\nWhen an agent commits early to a wrong diagnosis, like blaming floating-point math for a timezone bug or blaming CORS for a missing auth cookie, those earlier turns become strong priors. Instead of discarding the bad theory, the model often tries to stay consistent with its own earlier explanation.\n\nYou see this in coding sessions all the time. The agent writes a workaround for a bug it misdiagnosed, and the test still fails.\n\nRather than questioning its first assumption, it stacks a second workaround on top of the first. By turn 25, you have three layers of defensive hacks built around a root cause that never existed.\n\nStarting a fresh session breaks that gravitational pull right away. A fresh model sees only the broken code and the failing test, with no history pushing it to defend turn 6’s wrong guess.\n\n### Tool-output flooding\n\nIn a chat between two people, a turn adds maybe 50 to 200 tokens. In a coding agent loop, a single shell command can dump 15,000 tokens in one second.\n\nThe same culprits show up in almost every project:\n\n- A full `npm test` or`vitest` run where one shared mock fails and prints 90 stack traces.\n- A TypeScript compiler cascade (`tsc --noEmit` ) dumping 400 type errors caused by one missing export.\n- A `git diff` that drags in`package-lock.json` or a generated OpenAPI schema.\n- Reading a minified bundle, an SVG asset, or a raw JSON fixture into the conversation.\n\nOnce that 15,000-token `tool_result` enters the message array, it stays there. If the agent takes 15 more turns to finish, you pay for those 15,000 tokens 15 more times: 225,000 extra input tokens from one careless tool call.\n\nEven worse, those raw log lines dilute everything around them and push your original task specification thousands of tokens away from the active turn.\n\n### Lossy auto-compaction drift\n\nMany coding tools try to hide context growth by running automatic [compaction](https://flaviocopes.com/ai-glossary/compaction/) once a thread crosses 75% or 85% of the window. The harness asks a model to summarize the earlier conversation, drops the raw messages, and puts the summary at the top.\n\nAuto-compaction saves you from hitting a hard token error and can rescue a thread clogged with old tool output. Still, summarization is lossy by nature.\n\nWhen a summarizer compresses 40 turns into 600 tokens, it keeps the broad narrative (“we are refactoring the ledger retry middleware and fixing failing integration tests”). What quietly disappears are the sharp edges:\n\n- The exact header name `X-Ledger-Key` .\n- The rule that negative cent amounts must be rejected before hitting the queue.\n- The fact that you already tried library X and rejected it because of a Bun compatibility bug.\n\nAfter two rounds of automatic compaction in the same thread, the agent is working from a summary of a summary. Each pass strips away a little more precision while the prose still sounds confident.\n\nHere is how a normal coding session transitions from clean work into context rot, and how a deliberate handoff resets it:\n\n## Measuring context health in your own harness\n\nIf you build your own agent loop, or wrap LLM calls inside an internal tool, you don’t have to guess when a session is rotting. You can track context health directly from the data every API response already returns.\n\nFour signals tell you almost everything you need to know:\n\n1. **Input token growth per turn:** Track`prompt_tokens` (or`input_tokens` ) on every turn. Steady growth of 300 to 800 tokens per turn is healthy, while a sudden jump of 10,000+ tokens means a tool output flooded the history.\n2. **Prompt-cache hit drop:** Compare`cached_tokens` to total`prompt_tokens` . If your prefix cache hit rate suddenly collapses to zero mid-session, something mutated an earlier message or tool definition, so every turn now pays full prefill cost and full latency. See[prompt caching, compression, and compaction in coding agents](https://flaviocopes.com/agent-prompt-caching/) for how prefix breaks work.\n3. **Repeated tool calls:** Hash every tool call (`name` plus normalized arguments). If an agent reads the same file twice without editing it, or runs the same failing test command three times with no diff in between, something is off. Either the context went stale or the agent is stuck in a self-anchored loop.\n4. **Output verbosity and constraint creep:** Just like our 5-rule SQLite probe crept from 39 words to 44 out of 45 words at turn 18, rising completion length on simple questions often signals the model is hedging against conflicting earlier turns.\n\nBelow is a small, zero-dependency `ContextHealthMonitor` class in Node.js that tracks these signals on every turn and recommends `healthy`, `compact`, or `reset`. It reads the real `usage` object returned by the API instead of estimating with `chars / 4`, and it checks both hard token ceilings and duplicate tool calls.\n\n``` python\nimport crypto from 'node:crypto'\n\nexport class ContextHealthMonitor {\n  constructor({\n    warnTokens = 24000,\n    resetTokens = 48000,\n    floodSpikeTokens = 8000,\n    maxDuplicateTools = 2,\n  } = {}) {\n    this.warnTokens = warnTokens\n    this.resetTokens = resetTokens\n    this.floodSpikeTokens = floodSpikeTokens\n    this.maxDuplicateTools = maxDuplicateTools\n    this.turns = []\n    this.toolCounts = new Map()\n  }\n\n  recordTurn({ usage, latencyMs, toolCalls = [] }) {\n    const promptTokens = usage.prompt_tokens ?? usage.input_tokens ?? 0\n    const cachedTokens =\n      usage.prompt_tokens_details?.cached_tokens ??\n      usage.input_tokens_details?.cached_tokens ??\n      0\n    const completionTokens = usage.completion_tokens ?? usage.output_tokens ?? 0\n    const prev = this.turns.at(-1)\n    const deltaTokens = prev ? promptTokens - prev.promptTokens : promptTokens\n    const cacheHitRatio = promptTokens > 0 ? cachedTokens / promptTokens : 0\n\n    const duplicateTools = []\n    for (const call of toolCalls) {\n      const signature = crypto\n        .createHash('sha1')\n        .update(`${call.name}:${JSON.stringify(call.args)}`)\n        .digest('hex')\n        .slice(0, 10)\n      const count = (this.toolCounts.get(signature) ?? 0) + 1\n      this.toolCounts.set(signature, count)\n      if (count >= this.maxDuplicateTools) {\n        duplicateTools.push(`${call.name} (${count}x)`)\n      }\n    }\n\n    const alerts = []\n    if (deltaTokens >= this.floodSpikeTokens) {\n      alerts.push(`tool flood spike (+${deltaTokens} tokens in one turn)`)\n    }\n    if (prev && prev.cacheHitRatio >= 0.6 && cacheHitRatio < 0.2) {\n      alerts.push(\n        `cache hit collapse (${Math.round(prev.cacheHitRatio * 100)}% -> ${Math.round(cacheHitRatio * 100)}%)`\n      )\n    }\n    if (duplicateTools.length > 0) {\n      alerts.push(`repeated tool calls: ${duplicateTools.join(', ')}`)\n    }\n\n    let status = 'healthy'\n    if (promptTokens >= this.resetTokens || duplicateTools.length >= 2) {\n      status = 'reset'\n    } else if (promptTokens >= this.warnTokens || alerts.length > 0) {\n      status = 'compact'\n    }\n\n    const entry = {\n      turn: this.turns.length + 1,\n      promptTokens,\n      deltaTokens,\n      completionTokens,\n      cacheHitRatio: Number(cacheHitRatio.toFixed(2)),\n      latencyMs,\n      status,\n      alerts,\n    }\n    this.turns.push(entry)\n    return entry\n  }\n}\n```\n\nWhen we wire `recordTurn()` right after each API call, a healthy session stays quiet while a bloated or looping session surfaces in your logs right away. Here is a four-turn trace where a raw test log dumps 14,900 tokens into turn 2 and the agent starts re-reading the same file on turn 4:\n\n```\nturn 1 |  2,100 tok (+2,100) | cache 0.00 |  940 ms | healthy\nturn 2 | 17,020 tok (+14,920) | cache 0.11 | 1,410 ms | compact [tool flood spike (+14920 tokens in one turn)]\nturn 3 | 17,640 tok (+620)   | cache 0.89 | 1,280 ms | healthy\nturn 4 | 26,410 tok (+8,770) | cache 0.08 | 2,190 ms | compact [tool flood spike (+8770 tokens in one turn), cache hit collapse (89% -> 8%), repeated tool calls: read_file (2x)]\n```\n\nNotice how turn 4 catches three separate problems at once: another large tool payload, a sudden cache-hit drop from 89% to 8%, and a duplicate `read_file` call. Your harness now has an objective signal to intervene instead of letting the loop burn ten more turns.\n\n## Four recovery patterns that work\n\nGood [context engineering](https://flaviocopes.com/ai-glossary/context-engineering/) comes down to two habits: keeping junk out of the main conversation, and resetting cleanly once a thread outlives its usefulness.\n\nBefore we look at the code for each pattern, here is how all five options compare across token reduction, prompt-cache impact, risk of dropping a detail, and best fit.\n\n| Strategy | What changes in the prompt | Token reduction | Prompt-cache impact | Risk of detail loss | Best fit | \n|---|---|---|---|---|---|\n| Keep going | Nothing removed, turns keep appending | 0% | High cache hits until prefix breaks | None from compaction, rising rot risk | Short focused loops under ~25k tokens | \n| Tool-output truncation | Cap raw stdout/stderr at the harness boundary, save full log to disk | 40% to 80% on noisy commands | Preserves prefix completely | Low (agent can read slices from saved log) | Every coding agent harness by default | \n| Subagent isolation | Run noisy search, log triage, or test bisect in a child context | 70% to 95% of exploration noise | Zero disruption to parent prefix | Low to medium (depends on child report schema) | Multi-file exploration, dependency audits, flaky test hunting | \n| Structured deliberate compaction | Replace older turns with an explicit structured state summary | 60% to 85% | One-time cache miss, then new smaller prefix | Medium (summary can drop subtle rules if unverified) | Mid-feature milestones where architecture is settled | \n| Fresh-session handoff ( `HANDOFF.md` ) | Close the thread, start a new session with a concise on-disk brief | 90% to 99% (98.9% in our benchmark) | Clean new prefix from turn 1 | Low when backed by repo files and tests | Phase switches, after 2 failed bug guesses, or past ~40k tokens | \n\nNow let’s build the four active recovery patterns with concrete code and templates.\n\n### Pattern 1: Tool-output truncation at the harness boundary\n\nThe cheapest way to prevent context rot is to stop giant tool results from ever entering the chat.\n\nWhen your harness runs a shell command like `npm test` or `rg`, don’t pass raw `stdout` straight back as the `tool_result`. Instead, handle the output at the boundary:\n\n- Save the full output to a temporary log file on disk.\n- Keep the exit code, the first few lines, and the last few lines (where test summaries and stack trace roots usually live).\n- Extract lines matching failure markers.\n- Hand back the log file path so the model can inspect specific lines, like lines 400 to 460, if it needs to.\n\nHere is a Node.js helper that implements this boundary cleanly. Normal short outputs pass through untouched, and only payloads above a configurable character threshold get summarized.\n\n``` python\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport crypto from 'node:crypto'\n\nexport async function formatToolOutput({\n  command,\n  exitCode,\n  stdout = '',\n  stderr = '',\n  maxChars = 3200,\n  logDir = '/tmp/agent-tool-logs',\n}) {\n  const combined = [stdout, stderr].filter(Boolean).join('\\n').trim()\n  if (combined.length <= maxChars) {\n    return `exit_code: ${exitCode}\\n${combined}`\n  }\n\n  await fs.mkdir(logDir, { recursive: true })\n  const id = crypto.randomBytes(4).toString('hex')\n  const logPath = path.join(logDir, `tool-${id}.log`)\n  await fs.writeFile(logPath, combined, 'utf8')\n\n  const lines = combined.split('\\n')\n  const head = lines.slice(0, 15)\n  const tail = lines.slice(-25)\n  const errorLines = lines\n    .filter((line) => /\\b(FAIL|ERROR|Error:|AssertionError|TS\\d{4}:)\\b/.test(line))\n    .slice(0, 20)\n\n  const omitted = Math.max(0, lines.length - head.length - tail.length)\n\n  return [\n    `command: ${command}`,\n    `exit_code: ${exitCode}`,\n    `full_log: ${logPath} (${lines.length} lines, ${combined.length} chars)`,\n    '',\n    '--- key failure lines (max 20) ---',\n    errorLines.length > 0 ? errorLines.join('\\n') : '(none matched)',\n    '',\n    '--- first 15 lines ---',\n    head.join('\\n'),\n    '',\n    `... [${omitted} lines omitted; read specific line ranges from ${logPath} if needed] ...`,\n    '',\n    '--- last 25 lines ---',\n    tail.join('\\n'),\n  ].join('\\n')\n}\n```\n\nPicture what this one function saves over a 25-turn debugging session. A single 55,000-character `vitest` failure (around 14,000 tokens) shrinks to roughly 650 tokens while keeping every failing assertion name, the final summary, and the path to the full log.\n\nIf the agent needs lines 310 to 350 of the stack trace, it can read just those 40 lines instead of dragging all 1,800 lines along for the next twenty turns.\n\n### Pattern 2: Subagent context isolation for noisy tasks\n\nSome tasks are naturally messy. Finding every caller of an internal function across a monorepo, tracing how an auth cookie flows through six middleware files, or grepping a 200-megabyte nginx access log all require dozens of dead-end reads.\n\nIf your main coding agent runs that exploration inside its primary thread, you inherit all 30,000 tokens of dead ends before writing the first line of code.\n\nSubagent isolation splits research from editing. The main agent spawns a read-only child agent with a tight prompt: “Find every file that reads `X-Ledger-Key` or sets retry backoff delays. Return only a list of file paths, line numbers, current values, and any conflicting defaults.”\n\nThe child agent can spend 25,000 tokens reading 18 files, chasing two wrong folders, and inspecting tests. When it finishes, it returns a 350-token report to the parent, and all 25,000 tokens of raw search clutter vanish the moment the child exits.\n\nThis pattern works especially well for three jobs:\n\n- Codebase discovery before editing starts.\n- Triaging a noisy CI log or flaky test failure.\n- Reviewing a finished diff with fresh eyes, free from self-anchoring to the reasoning that produced it.\n\nSkip subagents for a tiny two-file edit where you already know the exact lines to change. Spawning a child adds startup latency and loses implicit nuances unless you put them in the brief, so save isolation for high-volume, low-signal reads.\n\n### Pattern 3: Structured deliberate compaction\n\nAutomatic compaction usually triggers too late, right when the context is already 85% full and the agent has spent ten turns going in circles. A generic “summarize this conversation” prompt also lets the summarizer decide what matters, and subtle constraints vanish.\n\nDeliberate compaction works much better. You trigger it at a natural milestone, like right after a migration passes or a module’s tests go green, and force the summary into fixed, verifiable sections so key details survive.\n\nHere is the structured compaction prompt I use when I want to stay in the same thread while dropping old tool logs and dead-end attempts:\n\n```\nPause implementation and produce a structured compaction checkpoint.\nDo not omit exact values, file paths, or rejected approaches.\n\n## 1. Active goal\nOne or two sentences describing what \"done\" means for this task.\n\n## 2. Hard constraints (never violate)\nBulleted list of exact rules, config values, header names, schema limits,\nand style rules stated by the user. Quote exact identifiers.\n\n## 3. Verified facts and decisions\nWhat we confirmed directly from code or command output, plus why we chose\nthe current design.\n\n## 4. Rejected approaches (do not retry)\nDead ends we already tested and why they failed.\n\n## 5. Files modified so far\nExact relative paths with a one-line note of what changed in each.\n\n## 6. Current verification state\nLast command run, exact pass/fail count, and any remaining failing test names.\n\n## 7. Next concrete step\nThe single next action to take after compaction.\n```\n\nSection 4 (`Rejected approaches`) is the secret weapon here. Without it, a compacted session often repeats a broken fix you already ruled out twenty minutes ago because the failed attempt dropped out of the summary.\n\nKeeping two lines like “Do not use `BigInt` for date diffing. The bug is Europe/Rome DST 23-hour days, not float precision” stops the agent from hitting the same wall twice.\n\n### Pattern 4: Fresh-session handoff via an on-disk `HANDOFF.md`\n\nStructured compaction still leaves you inside the same conversation thread. Some tools retain hidden provider-side state or partial message blocks you can’t inspect.\n\nWhen a conversation crosses 35k to 45k tokens, or after two wrong debugging guesses in a row, the cleanest fix is a hard reset. You write a short handoff file to disk, close the old session, and start a new chat that reads only that file.\n\nIn our benchmark, moving from 18 noisy turns to a fresh handoff dropped prompt tokens from **10,712 down to 116** (a **98.9% reduction**). It also restored baseline latency (1,269 ms down to 1,082 ms) and pulled the reply comfortably back inside the word limit.\n\nHere is a real-world `HANDOFF.md` written for a payment-ledger retry task so a fresh session can pick up in ten seconds with zero dead-end baggage:\n\n```\n# Handoff: Ledger Retry Policy and DST Date Diff Fix\n\n## Goal\nUpdate the ledger client retry middleware to match the active production policy\nand fix the off-by-one day calculation bug across DST transitions.\n\n## Hard constraints\n- `retry_backoff_ms`: `1450`\n- `max_retries`: `5`\n- `idempotency_header`: `X-Ledger-Key`\n- `circuit_open_sec`: `42`\n- `rejects_negative_cents`: `true` (must reject before enqueueing)\n- Do not change the public signature of `calculateBillingDays(startIso, endIso)`.\n\n## Confirmed root cause (do not re-diagnose)\n`new Date(dateStr + ' 00:00:00')` parses in local timezone (`Europe/Rome`).\nOn 2026-03-29 (spring forward), the day is 23 hours (82,800,000 ms), so\n`Math.floor((b - a) / 86400000)` returns `0` instead of `1`.\nFix by parsing as UTC midnight (`Date.UTC(y, m - 1, d)`).\nIgnore earlier IEEE-754 / `BigInt` ideas; floating-point precision is not involved.\n\n## Files in scope\n- `src/ledger/retry-policy.js` (updated constants, needs negative-cents guard)\n- `src/ledger/billing-days.js` (needs UTC fix)\n- `tests/ledger/billing-days.test.js` (add 2026-03-29 Europe/Rome regression test)\n\n## Last check\n`node --test tests/ledger/*.test.js` -> 11 passed, 2 failed\n(`rejects negative cents before retry`, `counts 1 day across Europe/Rome DST`)\n\n## Next step\n1. Add the negative-cents guard in `src/ledger/retry-policy.js`.\n2. Switch `src/ledger/billing-days.js` to `Date.UTC`.\n3. Re-run `node --test tests/ledger/*.test.js`.\n```\n\nIf you run your own agent script, bootstrapping a fresh session from `HANDOFF.md` takes twenty lines of JavaScript. The function below reads the handoff file and builds a clean two-message array with zero prior turns attached.\n\n``` python\nimport fs from 'node:fs/promises'\n\nexport async function createFreshSessionMessages({\n  systemPrompt,\n  handoffPath = 'HANDOFF.md',\n  openingInstruction = 'Read the handoff carefully, verify the constraints, then execute Step 1.',\n}) {\n  const handoff = await fs.readFile(handoffPath, 'utf8')\n  return [\n    { role: 'system', content: systemPrompt },\n    {\n      role: 'user',\n      content: [\n        'Fresh session started from verified handoff state.',\n        'Treat the handoff below and the current files on disk as the only source of truth.',\n        '',\n        handoff.trim(),\n        '',\n        openingInstruction,\n      ].join('\\n'),\n    },\n  ]\n}\n```\n\nOnce the task finishes, delete `HANDOFF.md` (or keep it gitignored in `.tmp/handoff.md`) so temporary session state never pollutes your repository commits.\n\n## Verifying what survived compaction before editing continues\n\nNever assume a summary or handoff captured every important constraint. One of the easiest ways to waste thirty minutes is to compact a long session, immediately tell the agent “great, keep going,” and discover five edits later that compaction dropped an edge case.\n\nBefore letting an agent modify files after compaction or a fresh handoff, spend one cheap turn on a **survival check**.\n\nSend three direct questions in plain text:\n\n```\nBefore editing any files, reply in 6 lines or fewer with:\n1. The exact hard constraints and config values you must preserve.\n2. The exact files you plan to edit.\n3. Any rejected approaches you will avoid.\n```\n\nThat check costs a couple hundred tokens and takes about one second. Compare the reply against your real expectations.\n\nHere is a concrete example of what it catches. Suppose your pre-compaction thread had our five-field retry policy (`retry_backoff_ms: 1450`, `max_retries: 5`, `idempotency_header: \"X-Ledger-Key\"`, `circuit_open_sec: 42`, `rejects_negative_cents: true`).\n\nAfter auto-compaction, you run the survival check and the model answers:\n\n```\n1. Retry backoff 1450ms, max 5 retries, circuit breaker 42s, custom ledger header.\n2. src/ledger/retry-policy.js and tests/ledger/retry-policy.test.js.\n3. None noted.\n```\n\nLook at what quietly disappeared in that single compaction pass:\n\n- The exact header string `\"X-Ledger-Key\"` turned into the vague phrase “custom ledger header”, so next turn the agent may invent`X-Idempotency-Key` and break production clients.\n- `rejects_negative_cents: true` vanished completely.\n- The rejected approach list is empty.\n\nCatching those omissions before the agent writes code takes ten seconds to fix. Catching them after three commits and a broken staging deploy takes an hour.\n\n### Move permanent rules out of chat history\n\nEven better, stop storing permanent project rules inside chat history at all. Conversation memory is volatile by definition.\n\nAnything that must survive every turn, every compaction, and every fresh session belongs in a file on disk:\n\n- Architecture rules and coding conventions belong in `AGENTS.md` (or a scoped module README).\n- Behavioral requirements belong in failing unit tests (`node --test` ,`vitest` ,`pytest` ).\n- Exact configuration constants belong in typed schemas or config files the agent can read on demand.\n\nWhen your constraints live in tests and repo files, compaction can’t lose them. Even if a summary forgets `rejects_negative_cents: true`, the test suite fails the second the agent breaks it.\n\n## How I manage long conversations\n\nI used to treat a coding-agent thread like a day-long Slack channel, keeping one conversation open for hours while jumping across three unrelated bugs. That habit always produced the worst results: slower replies, rising token bills, and agents that felt weirdly stubborn after turn 30.\n\nNow I treat every conversation as a short-lived workspace scoped to one clean unit of work. It’s the same mindset I use when juggling multiple threads in [too many agent conversations](https://flaviocopes.com/too-many-agent-conversations/).\n\nHere is the decision flow I follow while working:\n\n### Four thresholds I use every day\n\nIn practice, my rules break down into four clear actions:\n\n- **Keep going** when the thread is under 25k to 30k tokens, we’re iterating tightly on one feature or module, the agent’s mental model is accurate, and prompt caching keeps replies fast. Resetting too early wastes time rebuilding context that is still clean and useful.\n- **Isolate with a subagent** whenever the next step requires reading ten unfamiliar files, grepping across a large dependency, or digging through a huge error log. That keeps my main editing thread tiny and sharp.\n- **Run deliberate structured compaction** at a clean checkpoint during a longer feature. Use it once the architecture is settled, recent tests pass, and the only dead weight left is 20 turns of earlier diffs and build logs, then run the one-turn survival check right after before approving the next edit.\n- **Close the thread and start fresh with `HANDOFF.md`** whenever the session crosses a clean boundary or starts fighting me.\n\nI trigger that hard reset without hesitation in three situations:\n\n1. Right after finishing exploration and planning, before writing the first line of production code.\n2. After two failed attempts to fix the same bug, since self-anchoring almost always locks the thread into patching the wrong theory.\n3. Whenever the model starts repeating mistakes, re-reading files it just opened, or ignoring a rule we already agreed on.\n\n### When resetting is the wrong move\n\nResetting or compacting isn’t always the right fit.\n\nIf I’m in a deep design brainstorming session, weighing subtle trade-offs across 15 back-and-forth turns, forcing an early reset often flattens the nuance we just built up. Until the design settles into concrete decisions I can write into a markdown spec, staying in the live conversation produces better pushback and cleaner synthesis.\n\nFor a quick 5-turn task too (fixing a typo, tweaking CSS, writing one small utility function), writing a `HANDOFF.md` or spawning a subagent adds pure overhead. I just finish the job and close the thread.\n\nLong context windows are a great safety net when you genuinely need to inspect a massive log file or cross-reference five large documents in a single pass. For day-to-day coding, though, smaller and cleaner contexts beat giant cluttered histories every time.\n\nIf you keep your active prompt lean, leave raw tool logs on disk, and verify what survives compaction, your sessions stay fast and accurate. And the moment a thread starts fighting you, start fresh.\n\nWant me to talk about your product? You can [sponsor this site](https://flaviocopes.com/sponsor/).", "url": "https://wpnews.pro/news/context-degradation-in-long-conversations-measuring-context-rot-and-fixing-it", "canonical_source": "https://flaviocopes.com/context-degradation/", "published_at": "2026-11-30 08:00:00+00:00", "updated_at": "2026-11-30 08:44:31.185030+00:00", "lang": "en", "topics": ["large-language-models", "ai-agents", "ai-tools", "mlops"], "entities": ["OpenAI", "gpt-4.1-mini", "Flavio", "Node.js"], "also_reported_by": [], "takeaway": "On gpt-4.1-mini, growing prompts from 2,000 to 52,000 tokens left needle-in-a-haystack retrieval accuracy nearly flat but more than doubled latency and raised per-turn token cost 25x, so long agent sessions should be measured on cost and time-to-first-token, not just context-limit headroom.", "recommendation": {"advice": "Benchmark your own agent sessions from 2k to 52k tokens on latency and per-turn token cost, not just retrieval accuracy, and strip stale history since prompt caching cuts prefill cost but not attention noise.", "playbook": "llm-cost", "playbook_url": "https://wpnews.pro/playbooks/llm-cost"}, "alternates": {"html": "https://wpnews.pro/news/context-degradation-in-long-conversations-measuring-context-rot-and-fixing-it", "markdown": "https://wpnews.pro/news/context-degradation-in-long-conversations-measuring-context-rot-and-fixing-it.md", "text": "https://wpnews.pro/news/context-degradation-in-long-conversations-measuring-context-rot-and-fixing-it.txt", "jsonld": "https://wpnews.pro/news/context-degradation-in-long-conversations-measuring-context-rot-and-fixing-it.jsonld"}}