Growing context: failures when trimming and summarising

Study time
≈ 2 h (estimate)
Needs
L3-M05-L01
Updated
2026-11-04

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L3-M05 · Duration: ~120 minutes (estimate, including the independent exercise) · Previous: L01 (kinds of state) · Next: L03

1. Introduction

In L01, conversation state was "lost when the context is trimmed". This lesson opens that box. Every turn, the history grows by two messages; a ThuVien Mini book description reply is more than thirty tokens long. After eight turns, conversation c01 is already more than double the lab's budget of 140 tokens. The application has to choose: trim old messages, pin some messages, or replace the old part with a summary. Every choice throws something away. The tester's question is: which of the user's instructions survive the trim, and how do you prove it.

L1-M01-L02 introduced the context window and history trimming strategies at the level of a chat application. This lesson goes further, at the level of an agent: a deterministic context manager with five strategies, a simulated summariser with four built-in failure modes, and the function lost_facts, which compares what the assistant can read in the context with what is in the whole history. The product: tests for "an instruction lost after trimming", and a context configuration you choose yourself in §9.

2. Learning objectives

  1. Explain why an agent's context keeps growing and why "more context" is not automatically better. Read: §4.1.
  2. Compare the lab's five strategies and state what each one can lose. Read: §4.2, §5.1. Practice: §8.2 (parts A, D).
  3. Recognise the four summary failure modes (dropping rules, softening a negation, inventing, keeping a stale value) with lost_facts. Read: §5.2. Practice: §8.2 (parts B, C), §9 (TODO 1).
  4. Explain why checking "the keyword is still in the context" is not enough, and write a behaviour test for an instruction lost after trimming. Read: §6.1. Practice: §9 (TODO 3).
  5. Choose a context configuration that keeps every instruction within a given budget. Practice: §9 (TODO 2).

3. Prerequisites and tools

  • L01 (inventory, probes, control), L1-M01-L02 (tokens, context window, history trimming). Code lab code-labs/l3-m05.
  • Terms kept apart. The history is every message of the session, never edited. The context is the messages sent to the assistant at one turn, rebuilt from the history every turn. Trimming is dropping messages from the context; summarisation (providers call it compaction) is replacing a group of messages with one summary message. An instruction here is a rule or fact set by the user (or by the system message) (a name, a book category, an author to avoid, the loan period in the system message).
  • The lab's tokens are approximate tokens: one token per word or punctuation mark, plus 3 tokens per message (the role marker). Real tokenizers differ (L1-M01-L02); the lab only needs a stable count you can work out by hand.

4. Concepts

4.1 Context keeps growing, and more is not automatically better

Anthropic's documentation describes the context window as all the text the model can refer to when generating a reply, including the reply itself, and says everything in the request counts towards it: the system prompt, every message (including tool results), and the tool definitions [R1]. The same page says "more context isn't automatically better": as the token count grows, accuracy and recall degrade, a phenomenon called context rot [R1]. Chroma's report on context rot found that performance degrades as input length grows, "often in surprising and non-uniform ways" [R2]. The paper "Lost in the Middle" found that performance is often highest when the relevant information is at the beginning or end of the context, and degrades significantly when it is in the middle [R3].

For a tester, two things follow. First, the context has to be managed: OpenAI's documentation warns that exceeding the context window can lead to truncated output [R4]. Second, the way it is managed is a behaviour change that needs testing like any other change. The lab does not simulate context rot (the lab's assistant reads everything in the context perfectly); it simulates only what a tester can check directly: whether a message is still in the context or not.

4.2 Three approaches, three costs

  • Drop the oldest first (first in, first out). Anthropic's documentation says a chat interface can manage the context window on a "first in, first out" basis [R1]. Cheap and easy to understand; the cost is that the instructions at the start of the conversation go first. The naive version drops the system message too.
  • Pinning. Keep the system message and some selected messages. The cost: you have to decide which messages are instructions. A keyword rule misses when the user says the same thing in other words.
  • Summarisation (compaction). Anthropic's documentation describes compaction as replacing older turns with a summary; recent turns can be kept "word for word", and the page advises writing a custom summary prompt "when the default summary drops something a later turn needs" [R5]. Anthropic's article on context engineering says overly aggressive compaction can lose "subtle but critical context whose importance only becomes apparent later", and advises maximising recall first, then improving precision [R6]. The cost: a summary is the output of a model, and it can be wrong.

All three can keep exactly the right number of tokens and lose exactly the wrong instruction. So a test must ask about instructions, not about token counts.

5. Technical deep dive

5.1 build_context: five strategies on the same history

build_context(history, config) returns {messages, tokens, dropped, summary, over_budget} and never changes history. config has strategy, budget, and for summarise also keep_recent (default 4) and summary_mode (default faithful). A broken configuration (an unknown strategy, a budget that is not a positive integer, keep_recent less than 1) makes build_context raise ValueError; check_config lists the errors. Every strategy keeps the last message (the student's current turn), even when it alone exceeds the budget.

Strategy Rule
keep_all keep everything; over_budget reports when it exceeds
drop_oldest drop the oldest message, any role, until it fits; the system message goes first
keep_system never drop messages with role system or memory; drop the oldest of the rest
pin_rules like keep_system, and never drop a student message that starts with one of PIN_PREFIXES ("Only recommend", "Never recommend books by", "My name is", ...)
summarise if the history does not fit: keep the system/memory messages and the last keep_recent of the remaining messages, replace the older messages with one summary message; if it still does not fit, drop the oldest of the kept recent messages (except the last message)

Note the last row: in summarise, a message dropped at the "still does not fit" step is not in the summary. The summary only condenses the part older than keep_recent.

lost_facts(history, context) reads both with the assistant's own reader (agent.facts_in) and returns error strings: lost:<fact> (in the history, no longer in the context), changed:<fact> (a different value), invented:<fact> (in the context, not in the history), and lost:exclude:<author> for an author to avoid. Single-valued facts (name, book category, class, loan period) take the last mentioned value; authors to avoid accumulate. Blind spot: lost_facts compares effective facts, so an invented rule in the summary that a recent message overrides is not reported; it comes back when that recent message is trimmed.

5.2 The simulated summariser and four failure modes

lab/summariser.py is an extractive, deterministic summariser: it reads the facts from the old messages and rewrites them as sentences the assistant understands. Five modes:

  • faithful: every fact.
  • drops_rules: keeps the name and class, drops the book category rule and the author to avoid ("summarise the topics, not the rules").
  • softens_negation: writes "The student talked about books by X." instead of "Never recommend books by X.": the author's name stays, the rule is gone.
  • invents: faithful, plus one rule nobody set.
  • keeps_stale: when a fact is corrected later, keeps the first value.

A real summariser is a language model, and its failures are not this tidy. The four failure modes are a simplification. drops_rules corresponds to the failure the sources in §4.2 describe (the summary leaves out context a later turn needs); invents, softens_negation and keeps_stale are failures a tester should add to the test suite on their own: inventing, inverting meaning, keeping an old value.

6. QA perspective

6.1 Checking "the keyword is still there" does not check the instruction

Part B of the demo (§8.2) is the reason this lesson uses lost_facts instead of keyword search. With softens_negation, mentions finds all three words "science", "Lan Huong", "Binh" in the context; a test like "the summary mentions Lan Huong" would pass. But the rule "do not recommend Lan Huong's books" has become "the student talked about Lan Huong's books", and lost_facts reports lost:exclude:Lan Huong. With keeps_stale, neither approach sees anything on c01, because c01 has no correction; the failure only shows on c02 (part C), where the student switches from story books to science books.

Consequences for test design:

  • Set the instruction, make the conversation long, then ask. Each important instruction needs a probe asked at the end of a conversation long enough to exceed the budget, and the expected reply must differ from the reply when the instruction is lost. On c01, keeping both rules gives B005; losing the author to avoid gives B004, losing both gives B002; but losing only the book category rule still gives B005 (B003 is on loan, so the first book still on the shelf that is not by Lan Huong is B005), so this probe cannot tell that loss apart, only lost_facts sees it (the test test_which_lost_rule_the_c01_probe_can_see).
  • Have one case per failure mode. A rule correction case (c02), a rule phrased differently (c03, "Please skip anything written by..."), a case that depends on the system message (c04, the loan period).
  • Measure what the agent can read, not only what it says. A probe can pass by luck: if no science book is by the author to avoid, "do not recommend X's books" is always true. lost_facts on the context catches that loss even when the reply looks right.
  • The budget is a test parameter. A configuration that passes at 200 tokens can lose instructions at 140. Run the suite at the budget the real product uses, and at a lower budget to see where it breaks.

7. Real-world scenarios

Scenario 1 (fictional): "The update saves 40% of tokens". The team switches from keep_all to keep_system to cut costs. The token-count tests are all green. The tester runs a c01-style case and sees the assistant recommend a book by the author the student asked to avoid, and forget the student's name. The report says: the saving is real, but it loses three instructions; it proposes summarise with a probe for each instruction.

Scenario 2 (fictional): "The summary mentions everything". A new summary prompt is approved because the reviewer sees that the summary "mentions every author and topic". A probe at the end of the conversation shows the assistant recommending exactly the book the student had excluded. The summary mentions the author's name but drops the word "not". The tester adds a "softened negation" case to the regression suite (L03).

8. Hands-on tutorial

8.1 Setup

As in L01 §8.1.

8.2 Run the demo

python -m lab.demo l02

Output (copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-04; both versions gave identical output). The assistant, the summariser and the tokens are all simulated:

A. c01 turn 8 ('Recommend a book.') under each strategy, budget 140, keep_recent 4
   history: 16 messages, 281 tokens
   keep_all: tokens=281 over_budget=True dropped=0 lost=[]
      reply: I recommend B005 Dinosaur Atlas by Mai Anh.
   drop_oldest: tokens=99 over_budget=False dropped=11 lost=['lost:exclude:Lan Huong', 'lost:loan_days', 'lost:name', 'lost:only']
      reply: I recommend B002 Fractions in the Kitchen by Lan Huong.
   keep_system: tokens=126 over_budget=False dropped=10 lost=['lost:exclude:Lan Huong', 'lost:name', 'lost:only']
      reply: I recommend B002 Fractions in the Kitchen by Lan Huong.
   pin_rules: tokens=105 over_budget=False dropped=9 lost=[]
      reply: I recommend B005 Dinosaur Atlas by Mai Anh.
   summarise: tokens=108 over_budget=False dropped=12 lost=[]
      reply: I recommend B005 Dinosaur Atlas by Mai Anh.
B. summarise, budget 140: the five summariser modes
   faithful: lost=[] mentions=['science', 'Lan Huong', 'Binh']
      summary: Summary of 11 earlier messages. The student's name is Binh. Only recommend science books. Never recommend books by Lan Huong.
   drops_rules: lost=['lost:exclude:Lan Huong', 'lost:only'] mentions=['Binh']
      summary: Summary of 11 earlier messages. The student's name is Binh. The student asked about several books.
   softens_negation: lost=['lost:exclude:Lan Huong'] mentions=['science', 'Lan Huong', 'Binh']
      summary: Summary of 11 earlier messages. The student's name is Binh. Only recommend science books. The student talked about books by Lan Huong.
   invents: lost=['changed:only'] mentions=['science', 'Lan Huong', 'Binh']
      summary: Summary of 11 earlier messages. The student's name is Binh. Only recommend science books. Never recommend books by Lan Huong. Only recommend story books.
   keeps_stale: lost=[] mentions=['science', 'Lan Huong', 'Binh']
      summary: Summary of 11 earlier messages. The student's name is Binh. Only recommend science books. Never recommend books by Lan Huong.
C. c02 (the student corrects the rule at turn 4), summarise budget 140, turn 8
   faithful: I recommend B004 Ocean Friends by Lan Huong.
   keeps_stale: I recommend B007 River Song by Thu Ha.
D. c04 (two loans): what the helper says about the loan period at turn 8
   drop_oldest: Done: B009 Shapes Everywhere is yours for 14 days.
   keep_system: Done: B009 Shapes Everywhere is yours for 7 days.

Reading the output: part A: the c01 history at turn 8 has 16 messages, 281 tokens. summarise has dropped=12 but the summary condenses only 11 messages: the 12th message is a recent message dropped at the "still does not fit" step (§5.1), and it is not in the summary. keep_all exceeds the budget. drop_oldest and keep_system fit the budget but lose the name and both rules, so they recommend B002 (Lan Huong's maths book); drop_oldest also loses the loan period because it drops the system message too. pin_rules and summarise keep every instruction and recommend B005. Part B: only faithful and (on c01) keeps_stale lose nothing; invents adds a story book rule after the real rule, so it overrides it (changed:only). Part C: the correction at turn 4 is ignored by keeps_stale, and the assistant goes back to story books. Part D: when the system message is trimmed, the assistant states the default loan period of 14 days instead of 7 days.

8.3 Try it yourself

Save this as try_l02.py in the lab's root folder (next to lab/), run python try_l02.py, then delete the file:

from lab import conversation as C

convs = {c["id"]: c for c in C.load_conversations()}
for cfg in ({"strategy": "pin_rules", "budget": 140}, {"strategy": "summarise", "budget": 140, "keep_recent": 4}):
    tr = C.run_conversation(convs["c03"], cfg)
    print(cfg["strategy"], "|", tr["turns"][6]["reply"], "|", [t["tokens"] for t in tr["turns"]])
tr = C.run_conversation(convs["c01"], {"strategy": "keep_all", "budget": 140})
print("keep_all", [t["tokens"] for t in tr["turns"]])

Output (Python 3.14.6 and 3.12.3, Linux, identical):

pin_rules | I recommend B002 Fractions in the Kitchen by Lan Huong. | [38, 57, 74, 119, 136, 136, 134]
summarise | I recommend B009 Shapes Everywhere by Thu Ha. | [38, 57, 74, 119, 104, 101, 139]
keep_all [35, 53, 72, 91, 139, 190, 237, 281, 301]

Reading: in c03, the student says "Please skip anything written by Lan Huong." The assistant understands that sentence, but pin_rules does not pin it because it does not start with any prefix in the list; by turn 7 the rule has been trimmed and the assistant recommends a book by Lan Huong. summarise reads that sentence with the assistant's own reader, so it keeps it. The last line shows the c01 context growing over nine turns when nothing is trimmed, exceeding 140 tokens from turn 6.

8.4 Run the lesson's tests

python -m pytest tests/test_l02_context.py -v

Result: 24 passed. Read test_c01_history_and_the_five_strategies (the part A table), test_summary_modes_on_c01 (with a comment on the softens_negation line) and test_every_strategy_keeps_the_current_turn_and_does_not_change_the_history.

8.5 Troubleshooting

Symptom Cause Fix
ValueError: unknown strategy or budget must be a positive int Broken configuration See check_config(config); the budget is an int, not a string or True
over_budget=True even though a trimming strategy was chosen The protected messages (system, memory, summary, current turn) already exceed the budget Raise the budget, or shorten the system message
lost_facts is empty but the probe fails The probe checks something that is not an instruction, or the expected text is wrong Run the control (L01 §5.2)
The probe passes but lost_facts reports a loss The reply is right by luck with this data Trust lost_facts; add a case where the reply changes when the instruction is lost

9. Independent exercise

Problem: The conversation exercises/ex_conv_l02.json (student S0315, 12 turns) has a rule phrased differently, a rule correction, and two probe turns at turns 11 and 12.

Requirements: complete exercises/test_l02_context.py:

  1. TODO 1: LOST: for each configuration in CONFIGS (budget 120), the lost_facts list of the context that configuration gives the assistant at turn 11.
  2. TODO 2: CONFIG: a configuration with a budget of at most 80 tokens such that at every turn the context is within budget and lost_facts is empty, and both of the conversation's checks pass.
  3. TODO 3: PROBE: the turns you add after turn 12 (at least one check, no equals): a test for an instruction that CONFIGS["drop_oldest"] loses and CONFIGS["keep_system"] keeps. Every check passes under keep_system and under your CONFIG; at least one check fails under drop_oldest.

Test data: exercises/ex_conv_l02.json.

Deliverable: the three variables above, in the file exercises/test_l02_context.py itself.

Acceptance criteria: python -m pytest exercises/test_l02_context.py passes (3 tests). The tests rebuild the context turn by turn with lab.context, and run the conversation plus your turns under three configurations.

Hints: TODO 1: where is the correction in the conversation relative to the last few turns, and which strategy can read the sentence "Please skip..."? TODO 2: try a few values before choosing; reread the last row of the table in §5.1 about what happens when the part kept verbatim does not fit the budget. TODO 3: compare the LOST of those two configurations in TODO 1; an instruction only shows in a reply when a turn needs it.

10. Knowledge check

0/10 done · Results are kept in this browser only.

P02 · True or false

Every strategy of build_context keeps the last message (the student's current turn), even when that message alone exceeds the budget.

P04 · Select all that apply

At turn 8 of c01, summarise with budget 140 and keep_recent 4: select every summary mode that gives a non-empty lost_facts (part B of the demo).

P05 · Put in order

Put the steps for writing an "instruction survives the trim" test in order.

  1. Choose the instruction to protect and a probe whose reply changes when the instruction is lost
  2. Ask the probe at the last turn, check the reply and lost_facts on that turn's context
  3. Repeat at a lower budget to see where it breaks
  4. Put the instruction at the start of a conversation
  5. Add turns until the history exceeds the budget of the configuration under test

P06 · Match

Match each symptom to the summary mode that causes it.

P07 · Spot the bug

This test was written to protect the rule "Never recommend books by Lan Huong." after summarisation (_history as in tests/test_l02_context.py). With MODE = "softens_negation" it still passes. Find the bug.

def test_rule_survives_summary(by_id):
    h = _history(by_id["c01"], 8)
    ctx = CX.build_context(h, {"strategy": "summarise", "budget": 140, "keep_recent": 4, "summary_mode": MODE})
    assert CX.mentions(ctx["messages"], ["Lan Huong"]) == ["Lan Huong"]

P09 · Apply now

Run on your machine, no API key needed, no model called. Every result is simulated. Create try_l02p.py in the folder code-labs/l3-m05 (next to lab/) with the content below, run PYTHONDONTWRITEBYTECODE=1 python try_l02p.py, then delete the file:

from lab import conversation as C

c01 = {c["id"]: c for c in C.load_conversations()}["c01"]
for budget in (100, 140, 200, 300):
    tr = C.run_conversation(c01, {"strategy": "keep_system", "budget": budget})
    print(budget, "|", tr["turns"][7]["reply"], "|", tr["turns"][8]["reply"])
Checklist

P10 · Recall

Lesson: L1-M01-L02

In the history trimming strategy table of L1-M01-L02 (§5.3), which case is called a serious bug?

11. Summary

  • Concepts: growing context; context rot and the position of information [R1][R2][R3]; dropping the oldest first, pinning, summarisation (compaction) [R5][R6]; instructions lost, changed, invented.
  • Skills: run build_context with the strategies; read lost_facts; write a probe whose reply changes when an instruction is lost.
  • Traps: checking keywords instead of instructions; dropping the system message too; keyword pinning; trusting the summary; a probe that passes by luck.
  • Now you can: write tests for "an instruction survives the trim" and choose a context configuration with evidence.

12. References

ID Title Publisher URL Accessed Relevance
R1 Context windows Anthropic (Claude API documentation) https://platform.claude.com/docs/en/build-with-claude/context-windows 2026-11-04 Everything in the request counts towards the context window; context rot; "first in, first out"
R2 Context Rot: How Increasing Input Tokens Impacts LLM Performance Chroma (research report) https://www.trychroma.com/research/context-rot 2026-11-04 Performance degrades with input length, non-uniformly
R3 Lost in the Middle: How Language Models Use Long Contexts (arXiv 2307.03172) arXiv (Liu et al.) https://arxiv.org/abs/2307.03172 2026-11-04 Information in the middle of a long context is used worse than at the beginning and end
R4 Conversation state OpenAI API documentation https://developers.openai.com/api/docs/guides/conversation-state 2026-11-04 Exceeding the context window can truncate the output
R5 Compaction Anthropic (Claude API documentation) https://platform.claude.com/docs/en/build-with-claude/compaction 2026-11-04 Replace older turns with a summary; keep recent turns verbatim; a custom summary prompt when the default one leaves things out
R6 Effective context engineering for AI agents Anthropic https://www.anthropic.com/research/effective-context-engineering-for-ai-agents 2026-11-04 Overly aggressive compaction loses important context; maximise recall first

Glossary (English ↔ Tiếng Việt)

English Tiếng Việt
Context manager Bộ quản lý context: quyết định message nào của lịch sử tới agent ở mỗi lượt
Token budget Ngân sách token của context (ở lab là token xấp xỉ)
Pinning Ghim: không bao giờ cắt một số message
Compaction / summarisation Tóm tắt: thay các lượt cũ bằng một message tóm tắt
Lost / changed / invented fact Dữ kiện bị mất / bị đổi / bị bịa trong context so với lịch sử
Softened negation Phủ định bị làm mềm: "không gợi ý X" thành "có nói về X"