Deep dive · Shik · ESPAD One

Context window management: retrieval, memory and long-context failure modes

A bigger window tells you how much a model will accept, not how well it will use it. The evidence on long-context failure, and the patterns that keep production systems reliable.

Key takeaways

  • Models use long inputs unevenly: facts in the middle of a long context are used less reliably than facts at the start or end.
  • Effective context length is often well below the advertised window, so test at the lengths you actually send.
  • Retrieval and long windows are complements: retrieval decides what goes in, the window provides headroom.
  • Long-lived facts belong in stores with owners and permissions, read by tools when a step needs them, not in an ever-growing prompt.

The context window is the most misread number in an AI vendor's pitch. A larger window tells you how much text a model will accept; it does not tell you how well the model will use that text, what each call will cost, or what happens when an untrusted document lands in the middle of it. Context window management is the engineering discipline of deciding, on every call, what the model sees, in what order, from which source and with what provenance. In a production system with several specialists it is most of the orchestration work.

This cluster article sits under our guide to multi-agent orchestration. It covers the evidence on long-context failure, the trade-off between retrieval and long windows, compression and memory, and the context budget we use when designing Shik, the ESPAD AI occasion planner, and the other ESPAD AI assistants.

Why bigger windows did not solve context window management

When Bai and colleagues released a bilingual, multitask long-context benchmark, they noted that most language models could handle inputs of only a few thousand tokens[1]. Within a year, research benchmarks were evaluating models that advertised windows of 200,000 tokens[2]. The capacity problem eased quickly. The utilisation problem did not, and three lines of evidence explain why it matters to a CTO.

Position matters. Liu and colleagues tested models on multi-document question answering and key-value retrieval while moving the relevant information through the input. Performance was usually highest when that information sat at the beginning or the end and fell when it sat in the middle, even for models built for long contexts[3].

Advertised length is not effective length. Hsieh and colleagues argued that the popular needle-in-a-haystack test, which plants a single fact in long filler text, measures only a shallow form of long-context ability. Their RULER benchmark adds multiple needles, multi-hop tracing and aggregation tasks. Across 17 long-context models and 13 tasks, nearly all models scored almost perfectly on the basic needle test yet degraded substantially as length grew, and only half of the models that claimed windows of 32,000 tokens or more performed satisfactorily at 32,000[2].

Irrelevant text is not free. Shi and colleagues built a grade-school arithmetic dataset with irrelevant sentences inserted and found that accuracy dropped substantially when the distracting information was present; self-consistency decoding and an explicit instruction to ignore irrelevant information reduced the damage[4].

Taken together, these results say that filling a window is an act with consequences. Every passage you add is a passage that can push the decisive fact into the middle, or distract the model from it.

Four long-context failure modes

The table below organises failure modes by what an operator can observe and what usually fixes them. The mitigations are engineering practice; the evidence column points to the research that describes each failure.

Failure modeWhat you seeEvidenceFirst mitigation
Positional lossAnswers ignore a fact that is present in the contextLiu et al.[3]Shorter contexts; decisive material near the start or end
Effective-length gapQuality falls well before the advertised limitHsieh et al.[2]Test at your real lengths; set an internal ceiling below the limit
DistractionPlausible answers built on the wrong passageShi et al.[4]Retrieve fewer, better passages; instruct the model to ignore irrelevant material
Context poisoningThe model follows instructions planted in retrieved contentGreshake et al.[5]Treat retrieved text as data; strip or flag instructions; limit tool authority

The fourth row is a security problem in a context costume. Greshake and colleagues showed that when an application feeds retrieved content to a model, an attacker who plants instructions in that content can steer the application, including which APIs it calls and what data it leaks[5]. The more a system pulls into its context automatically, the larger that surface becomes, which is why the OWASP Top 10 for LLM Applications puts prompt injection at the top of its list.

Retrieval and long context are complements

Retrieval-augmented generation, introduced by Lewis and colleagues, pairs a generator with a neural retriever over a dense vector index, so that the model conditions on passages fetched for each query rather than only on what it memorised during training[6]. The original motivation was knowledge access and provenance, because knowledge stored in parameters is hard to inspect and hard to update[6]. For context management the benefit is selectivity: the model sees a handful of relevant passages instead of everything.

Is a long window a substitute? The most direct test we know of is by Xu and colleagues. A model with a 4,000-token window plus simple retrieval performed comparably to a version fine-tuned to a 16,000-token window while using much less computation, and retrieval improved performance regardless of the extended window size; their best configuration combined a 32,000-token window with retrieval and was evaluated across nine long-context tasks[7]. LongBench reached a compatible conclusion from the other side: retrieval-based context compression helped models that were weak at long contexts, although they still trailed models with strong long-context ability[1].

The practical reading is to treat the long window as headroom and retrieval as the editor that decides what goes into it. A system that relies on the window alone pays for every token and inherits every failure mode in the table above. The published version of the lost-in-the-middle study is worth reading in full before any design review that proposes simply pasting more documents into a prompt.

Compression and summarisation

Sometimes the material genuinely does not fit, or fits only at a cost nobody will pay on every call. Two families of technique help.

Prompt compression removes tokens the model does not need. Jiang and colleagues built a coarse-to-fine method with a budget controller and token-level iterative compression, and reported compression of up to 20 times with little loss of performance across reasoning, conversation and summarisation datasets[8]. Compression of this kind suits long, redundant inputs such as worked examples and retrieved documents.

Summarisation replaces history with a shorter account of it. It is the default for long conversations, and it has a property that is easy to miss: a summary is a new, model-written text, so it can lose provenance and introduce errors that later steps will treat as fact. Two rules keep it honest. Summarise conversation, not records: a price, a date or a stored preference is re-read from its source, never carried forward in a summary. And keep the summary's own provenance: which turns it covers and when it was made.

Memory is a hierarchy, not a longer prompt

The most useful mental model for long-lived assistants comes from operating systems. Packer and colleagues treated the context window as a small, fast main memory and gave the model functions to move information between it and external storage, with interrupts to manage control flow; they evaluated the design on documents far longer than the window and on multi-session chat in which agents remember and update information over time[9]. The generative agents of Park and colleagues used a related structure: a complete natural-language record of experience, periodic reflections that condense it into higher-level conclusions, and retrieval of relevant memories when the agent decides what to do. Ablations showed that observation, planning and reflection each contributed to believable behaviour[10].

For a product, the lesson is to keep long-lived facts in a store with an owner, permissions and a delete function, and to bring into the window only what the current step needs. A family calendar, a list of birthdays or a person's stated preferences are records. They should be read by a tool at the step that uses them, not appended to every prompt.

Context in multi-agent hand-offs

In an orchestrated system every hand-off is a context decision. The default in many prototypes is to pass the whole conversation from agent to agent, which builds exactly the long, middle-heavy, distracting inputs the research above warns against[3][4]. We budget context in four tiers instead.

Filling a context window is an act with consequences: every passage you add can push the decisive fact into the middle.

Two rules sit across the tiers. First, scope before you budget: anything a specialist may not see should never reach its window at all. In Shik, nothing from a person's health assistant is ever read or used for an occasion, and family members see only what each person marks for the family. Second, facts that drive decisions come from tools at call time. Shik reads product names and prices from the shop when it builds a proposal, so no price sits in a context where it could go stale, and the assistant never states one on its own.

A useful side effect of the budget is that it makes context observable. When each tier has a ceiling and every call logs what filled it, an incident review can answer the questions that matter: did the specialist have the fact, where in the window was it, and which tier crowded it out? Without that record, a wrong answer from a long context is close to impossible to explain, and a vendor who cannot show you what entered the window on a given call cannot show you why the model answered as it did.

A production checklist for context

  1. Measure quality at the context lengths you actually send, not at the vendor's maximum; tests with several needles and aggregation tasks are more informative than a single needle[2].
  2. Set an internal ceiling per specialist below the advertised window, and alert when calls approach it.
  3. Put instructions first and the specific question last, with retrieved evidence between them, and keep that evidence short[3].
  4. Retrieve fewer, better passages, and include distractors in your test sets[4].
  5. Treat every retrieved or agent-written passage as untrusted data[5].
  6. Keep records in stores, not prompts, and re-read them at the step that uses them.
  7. Log what entered the window on every call. You cannot debug a context you did not record.

For the decision that comes before all of this, which model or specialist receives the request, see our article on LLM routing. For the wider system, visit the agent orchestration topic hub.

Frequently asked questions

If a model supports a very long window, why not send everything?

Because research shows models use long inputs unevenly and often perform worse well before the advertised limit. Facts in the middle of a long context are used less reliably, irrelevant passages distract the model, and every token adds cost and latency. Retrieved content can also carry injected instructions. Selecting what the model sees usually beats sending everything, even when everything fits.

Is retrieval-augmented generation still needed with long-context models?

Yes. Published comparisons found that a short-window model with simple retrieval can perform comparably to a longer-window model at much lower computational cost, and that retrieval helped regardless of window size. Retrieval also adds provenance, because each passage arrives with a source. The long window is best treated as headroom, with retrieval deciding what fills it.

How should we test a vendor's long-context claims?

Run your own documents at the lengths you will actually send, and place the decisive facts at different positions, including the middle. Use several facts per test and tasks that require combining them, not a single planted fact. Add irrelevant passages to see whether answers drift. Report results by length and position rather than one average score.

Should conversation summaries be stored as memory?

Only as history, never as the record of facts that matter. A summary is model-written text that can drop or distort details. Prices, dates, preferences and calendar entries should live in a store with an owner and permissions, and be re-read from that store when a step needs them. Keep note of which turns each summary covers and when it was created.

How does context management change in a multi-agent system?

Every hand-off between agents becomes a context decision. Passing whole transcripts from agent to agent builds long, distracting inputs and spreads data to agents that should not see it. A structured hand-off with required fields, sourced evidence under a token ceiling and permission scoping before anything enters the window keeps each specialist's context short, relevant and auditable.

References

  1. Bai, Y., Lv, X., Zhang, J., Lyu, H., Tang, J., Huang, Z., Du, Z., Liu, X., Zeng, A., Hou, L., Dong, Y., Tang, J., & Li, J. (2024). LongBench: A bilingual, multitask benchmark for long context understanding. Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), 3119-3137. doi.org/10.18653/v1/2024.acl-long.172
  2. Hsieh, C.-P., Sun, S., Kriman, S., Acharya, S., Rekesh, D., Jia, F., Zhang, Y., & Ginsburg, B. (2024). RULER: What's the real context size of your long-context language models? Conference on Language Modeling (COLM 2024). arXiv:2404.06654. arxiv.org/abs/2404.06654
  3. Liu, N. F., Lin, K., Hewitt, J., Paranjape, A., Bevilacqua, M., Petroni, F., & Liang, P. (2024). Lost in the middle: How language models use long contexts. Transactions of the Association for Computational Linguistics, 12, 157-173. doi.org/10.1162/tacl_a_00638
  4. Shi, F., Chen, X., Misra, K., Scales, N., Dohan, D., Chi, E., Schärli, N., & Zhou, D. (2023). Large language models can be easily distracted by irrelevant context. Proceedings of the 40th International Conference on Machine Learning, PMLR 202. proceedings.mlr.press/v202/shi23a.html
  5. Greshake, K., Abdelnabi, S., Mishra, S., Endres, C., Holz, T., & Fritz, M. (2023). Not what you've signed up for: Compromising real-world LLM-integrated applications with indirect prompt injection. arXiv:2302.12173. arxiv.org/abs/2302.12173
  6. Lewis, P., Perez, E., Piktus, A., Petroni, F., Karpukhin, V., Goyal, N., Küttler, H., Lewis, M., Yih, W., Rocktäschel, T., Riedel, S., & Kiela, D. (2020). Retrieval-augmented generation for knowledge-intensive NLP tasks. Advances in Neural Information Processing Systems 33 (NeurIPS 2020). arXiv:2005.11401. arxiv.org/abs/2005.11401
  7. Xu, P., Ping, W., Wu, X., McAfee, L., Zhu, C., Liu, Z., Subramanian, S., Bakhturina, E., Shoeybi, M., & Catanzaro, B. (2024). Retrieval meets long context large language models. International Conference on Learning Representations (ICLR 2024). arXiv:2310.03025. arxiv.org/abs/2310.03025
  8. Jiang, H., Wu, Q., Lin, C.-Y., Yang, Y., & Qiu, L. (2023). LLMLingua: Compressing prompts for accelerated inference of large language models. Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing (EMNLP 2023). aclanthology.org/2023.emnlp-main.825
  9. Packer, C., Wooders, S., Lin, K., Fang, V., Patil, S. G., Stoica, I., & Gonzalez, J. E. (2023). MemGPT: Towards LLMs as operating systems. arXiv:2310.08560. arxiv.org/abs/2310.08560
  10. Park, J. S., O'Brien, J., Cai, C. J., Morris, M. R., Liang, P., & Bernstein, M. S. (2023). Generative agents: Interactive simulacra of human behavior. ACM Symposium on User Interface Software and Technology (UIST 2023). arXiv:2304.03442. arxiv.org/abs/2304.03442

Owen Fardi

AI systems editor, ESPAD AI Journal

Owen covers multi-agent orchestration, routing, context management and evaluation in production AI systems, drawing on the research literature and on the engineering of ESPAD AI's own specialist assistants.

Reviewed by the ESPAD AI editorial desk under our sourcing and review standards. Next scheduled review: .

ESPAD One

Shik is the ESPAD AI model for specialist agent orchestration.

Meet Shik All Specialist agent orchestration articles