Context Window Dropout and Mid-Session Hallucination
AI agents fail silently when context grows, obscuring instructions and breeding fabrication.

Traditional error monitoring fails for AI agents because it measures only execution success, leaving instruction adherence and answer correctness unchecked. Context window dropout and mid-session hallucination expose that gap as growing context causes agents to miss evidence or fabricate answers while their traces show success. These are predictable runtime failures, so catching them requires context management and semantic evaluation.
Why context window dropout and mid-session hallucination are not random LLM misbehavior
When an agent becomes vague or contradictory halfway through a task, blaming the model treats the failure as an unpredictable quirk. That diagnosis hides the changing condition inside the session, which is the amount and quality of information competing for attention. Earlier instructions and relevant evidence can become harder to retrieve as context grows and fills the window, even though the task still depends on them.
That distinction changes what builders can control. When a failure is random, a team can only react to bad outputs, but when it stems from context accumulation, the team has warning signals it can measure and points where it can step in. Those signals show where the risk is rising. The mechanism begins with what enters the window, continues through how the model uses it, and determines where engineering and monitoring must intervene.
How tool-call accumulation fills the context window faster than user messages do
The main source of context growth in production agents is often tool output. A database query, API call, or search function returns material that is appended to the context. These tool-call outputs are observation tokens, and repeated calls leave the window holding stale results, superseded lookups, and intermediate outputs that no longer serve the task. The active context therefore grows even when the user contributes little new text.
A 2025 NeurIPS workshop paper measured context growth on a coding agent and found that tool output tokens dominated the total count. That finding points to raw tool outputs as the main pruning target, ahead of conversation history. The distinction matters because removing user turns can discard the request while leaving the larger source of noise intact. Token accounting must count these groups separately to show what is taking up the space.
Reasoning models can compound this accumulation through extended think-traces that repeat plan content from earlier think blocks. Repetition adds volume without preserving the plan’s effective signal. Pressure thus depends on how often tools are called and how much reasoning builds up, as well as how long the session lasts. A short, tool-heavy session can degrade faster than a long conversation.
The two mechanisms that turn a full context window into degraded output
Accumulation creates two related attention problems. The first is a signal-to-noise problem, in which relevant evidence competes with growing amounts of material the agent no longer needs. The second is positional bias, commonly called the “lost-in-the-middle” effect. Models attend more reliably to information near the beginning or end of a long context, while information in the interior is more likely to be missed or misread.
Practitioners call the resulting quality decline “context rot”. It is a retrieval and attention failure, distinct from hallucination, which involves fabrication. An agent can overlook a valid constraint without inventing anything, or it can fill the resulting gap with a fabricated answer. A filling window can produce both outcomes, but they are not interchangeable diagnoses.
The distinction also determines what monitoring must measure. Token utilization provides a signal of context pressure and the conditions in which retrieval degrades. It does not prove that a particular statement was fabricated. Detecting hallucination requires comparing the output with the evidence and instructions the agent was supposed to use.
Why context rot is especially damaging for enterprise agents dealing with semantic conflict
The attention failure becomes more consequential when competing context contains conflicting meanings. Enterprise agents may receive stale data dictionary definitions that contradict the current schema, or departmental glossaries that assign different meanings to the same term. Finance’s “customer” and Sales’ “customer” may refer to different entities. Lineage gaps can also leave an agent unable to establish whether a column means what it assumes. When the agent misses the right definition in these cases, it reasons from a different starting point.
This is semantic conflict, and it is not resolved by giving the model a more forceful prompt. The contradiction originates upstream, in the data governance layer. An agent cannot reason its way to an authoritative definition when its inputs disagree about which definition applies.
The resulting failure is silent by default. The agent chooses a meaning, proceeds confidently, and passes the wrong answer downstream without throwing an error. Unlike developer-tooling context rot that can be recovered from with a restart, enterprise context rot can corrupt a report, financial query, or customer-facing response before anyone notices. The damage comes from reasoning under the wrong semantics.
Why does an LLM agent look fine in logs but still give bad outputs to users?
A successful execution trace establishes that a workflow ran. Consider the refund failure described in the notes’ production pattern. The payment tool times out, the harness retries, and the third attempt returns an empty body. The output parser converts that body into a valid-looking object with default fields, and the model writes a confident summary. The run can finish with no exceptions, normal duration, and green spans even though the refund never happened.
That pattern illustrates the monitoring gap rather than proving context rot caused every such failure. Degraded attention and fabrication can produce the same outward result, namely a plausible answer unsupported by the preceding work. A success status code cannot distinguish a sound reasoning decision from an unsound one.
The risk also compounds across a chain. Each new step that runs on degraded context multiplies the chance that the final output will be wrong, because later work relies on earlier decisions being sound. Detecting that silent divergence requires instruction-aware trace evaluation, including the kind available through agent observability tools such as Lemma. Evaluation must establish whether the full trace supports the claimed result.
Why bigger context windows do not fix context rot and may extend its reach
A larger context window has more room before it overflows, which can help with short tasks. It is therefore a reasonable response to a capacity limit, but not a complete response to declining context quality. Production agents running multi-turn, tool-heavy sessions continue accumulating observations and will eventually fill the added space. If the extra capacity holds more stale results and conflicting definitions, it prolongs the difficulty of retrieving relevant evidence and instructions.
VISTA research shows performance gains from managing what is in the window with the same untrained context-management interface across trajectories of different scales. Larger windows can hold more information, but to reason correctly, the model still has to choose, keep, and retrieve the right information.
Four engineering strategies that address context degradation at the right layer
Selective context injection costs the least to start with. Classify query intent first, then retrieve only the context products that match it. For an enterprise data query, that means the relevant glossary entry, schema definition, and lineage record. This keeps the initial window signal-dense and limits irrelevant material before pruning becomes necessary.
When context still grows, the next step is threshold-based monitoring within the pipeline. Count observation tokens separately from user and assistant turns, watch utilization at a lower threshold, and prune stale tool outputs when pressure reaches a higher threshold. Summarization belongs after pruning if further reduction is needed. It adds latency and can introduce hallucination risk when the summarizer is weaker than the primary model. This progression reserves the more costly intervention for cases that the simpler one cannot resolve.
For sustained sessions, compaction must also account for the cost of changing the prompt. TokenPilot demonstrates that naive truncation or compaction can invalidate KV cache prefixes, creating hardware pre-fill penalties that override savings from fewer tokens. Its cache-aware approach stabilizes prompt prefixes and defers structural eviction until a segment’s utility expires. TokenPilot reports that costs fall by 61% in continuous mode.
The final step is to make context state visible to the agent itself. VISTA research finds that frontier models are “proprioceptively blind” to their own context and cannot reliably infer block size, recency, or remaining budget from the prompt alone. A runtime dashboard that shows token usage, recency, archive status, and remaining budget gives the agent what it needs to decide what to keep or archive.
Why context-aware monitoring requires scoring what the agent was supposed to do, not just logging what it did
Context management reduces exposure, but it does not establish that the remaining outputs are correct. Tracing records what the agent did, while online evaluation scores how well that matched the task and the evidence behind it. Without this second layer, a correct answer and a confident fabrication can look identical to an infrastructure monitor.
For hallucination detection in a multi-step chain, each LLM span can be scored for faithfulness against its upstream retriever span. A threshold on that score supplies a detection signal even when execution succeeded. Instruction adherence adds another criterion, because an answer can draw from retrieved material yet still misinterpret the request or use the wrong tool. The evaluation must connect the output to what the agent was supposed to produce.
Lemma audits every trace against the agent’s instructions and groups recurring deviations automatically. This is one way to close the gap without requiring teams to define every possible failure pattern in advance. Context-driven failures depend on runtime state, so fixed expectations about code paths cannot cover them all. Agent observability must account for the instructions and context behind the behavior.
Caught failures should then become evaluation cases. A suite built from failed production traces draws on what real users do, beyond the examples a team thinks of in advance. A CI check can block future merges that reduce quality below a configured threshold.
What engineering teams shipping agents today should do differently
Start by instrumenting token utilization per turn and counting tool output tokens separately. That baseline makes graduated pruning and alerting possible. Set the thresholds before the first production deployment rather than waiting for an incident to reveal the pressure point. Tool-heavy sessions require this measurement from the outset because elapsed time is a poor substitute for accumulated context.
Apply reductions in order of intervention cost. Prune stale tool outputs first, mask old observations second, and reserve summarization for cases that still need it. When compaction is needed, check cache continuity along with how much the token count falls.
Add online evaluation to tracing from day one, with faithfulness scoring against upstream retrieval as the minimum bar for multi-step agents. Turn every caught context-driven failure into a regression case so the pattern can be tested after a model update or schema change. A smarter model, better prompt, or larger window does not eliminate the runtime conditions that create context degradation. Because those conditions are predictable, the right monitoring posture can catch their effects before users do, but only by evaluating intent and evidence rather than treating successful execution as proof of a correct result.


