Sub topic 13
Testing That Important Facts Survive Compaction
This chapter assumes you have read the earlier chapters on compact, build_request, and rolling summaries. It also assumes you can write basic Python tests. Here you will build a small test harness that checks whether specific facts are still present after a conversation has been compacted.
Why compaction needs its own test
A compaction step can fail without raising an error. The request still has the right shape, the model still answers, and the answer reads well. The only sign of failure is that the model has forgotten the budget the user gave 40 turns ago. If you only read a few transcripts by hand, you will miss this.
The fix is to treat compaction like any other function with a contract. The contract is: after compaction, these facts must still be recoverable from the request that goes to the model.
Plant canary facts
A canary fact is a fact you insert into a test conversation on purpose, together with the exact string that must survive. Each canary has three parts:
- An id, so a failure report names the fact.
- The user message that states the fact.
- A needle: a short string that must appear in the compacted request.
Choose canaries that cover the kinds of content summaries tend to lose:
| Kind | Example | Why it is at risk |
|---|---|---|
| Exact number | `4,500` | Summaries round or drop numbers. |
| Path or identifier | `/etc/shop/app.toml` | Summaries paraphrase them into "a config file". |
| Constraint | `Never contact customers by SMS.` | Summaries drop negative rules or flip them. |
| Early decision | A choice made in turn 2 | Rolling summaries erode the oldest content first. |
Place canaries at different depths. Put one at the very start, one in the middle, and one just outside the verbatim window. Each position fails in a different way.
A runnable harness
The following file is self-contained. It copies estimate_tokens, compact, and build_request from the earlier chapters so you can run it directly. It uses two stand-in summarizers instead of a model call, so the test is fast and deterministic. One summarizer is deliberately bad. The other keeps user statements.
FACTS = [
{"id": "budget", "user": "Our budget is 4,500 euros.", "needle": "4,500"},
{"id": "path", "user": "The config lives at /etc/shop/app.toml.", "needle": "/etc/shop/app.toml"},
{"id": "no_sms", "user": "Never contact customers by SMS.", "needle": "SMS"},
]
TRIGGER = 200
KEEP_RECENT = 6
def estimate_tokens(message):
return len(message["content"]) // 4 + 4
def compact(history, summary, trigger_tokens, keep_recent, summarize):
summary_cost = estimate_tokens({"content": summary}) if summary else 0
total = summary_cost + sum(estimate_tokens(m) for m in history)
if total <= trigger_tokens or len(history) <= keep_recent:
return summary, history
old = list(history[:-keep_recent])
recent = list(history[-keep_recent:])
while recent and recent[0]["role"] != "user":
old.append(recent.pop(0))
return summarize(summary, old), recent
def build_request(system_prompt, summary, recent):
messages = [{"role": "system", "content": system_prompt}]
if summary:
messages.append({
"role": "system",
"content": "Summary of the earlier conversation:\n" + summary,
})
messages.extend(recent)
return messages
def filler(count):
messages = []
for n in range(count):
messages.append({"role": "user", "content": f"Filler question {n} about shipping times."})
messages.append({"role": "assistant", "content": f"Filler answer {n} about shipping times."})
return messages
def build_conversation(facts, filler_pairs=20):
history = []
for fact in facts:
history.append({"role": "user", "content": fact["user"]})
history.append({"role": "assistant", "content": "Noted."})
history.extend(filler(filler_pairs))
return history
def keep_tail_summarizer(previous, old):
# Bad on purpose: concatenates everything and keeps only the last 200 characters.
text = previous + " " + " ".join(m["content"] for m in old)
return text[-200:]
def keep_user_statements_summarizer(previous, old):
kept = [
m["content"]
for m in old
if m["role"] == "user" and not m["content"].startswith("Filler")
]
return " ".join(part for part in [previous] + kept if part)
def surviving(facts, request):
text = "\n".join(m["content"] for m in request)
return {fact["id"]: fact["needle"] in text for fact in facts}
def run(summarize, rounds=3):
history = build_conversation(FACTS)
summary = ""
for _ in range(rounds):
summary, history = compact(history, summary, TRIGGER, KEEP_RECENT, summarize)
history = history + filler(20) # the conversation keeps going
summary, history = compact(history, summary, TRIGGER, KEEP_RECENT, summarize)
request = build_request("You are a shop assistant.", summary, history)
return surviving(FACTS, request), request
if __name__ == "__main__":
for name, fn in [("tail", keep_tail_summarizer), ("user statements", keep_user_statements_summarizer)]:
result, request = run(fn)
print(name, result)
assert request[-1]["role"] == "assistant" or request[-1]["role"] == "user"Run it and read the output. The tail summarizer reports False for all three facts, because 20 filler pairs push every fact out of the last 200 characters. The user-statement summarizer reports True for all three, including after three rounds of re-compaction, because each round keeps the previous summary.
In a real test suite, wrap run in a test that asserts every value is True. Run it against your production summarizer, and keep the stand-ins as a check that the harness can fail.
flowchart TDReplace the placeholder above with the diagram below. It shows the order of the test steps.
Check that the harness can fail
A test that always passes is worse than no test. Keep the deliberately bad summarizer in your suite and assert that it fails. If keep_tail_summarizer ever passes, your filler is too short, your trigger is too high, or the needle check is wrong.
Checks for a real summarizer
String matching works for the stand-ins, but a real model paraphrases. Add these checks when you test the model-based summarizer.
Normalize needles
A summary may write 4500, 4.5k, or €4,500. Accept a list of equivalent needles per fact, or normalize both sides by lowercasing and stripping thousands separators before comparing. Keep the accepted forms narrow, or the test becomes meaningless.
Probe with questions
Presence in the summary is not the same as the model using the fact. Ask the question and check the answer. The ask argument is your model call, passed in so the function is easy to stub:
def probe(ask, request, question, needle):
answer = ask(request + [{"role": "user", "content": question}])
return needle in answerFor example, ask "What is my budget?" and look for 4,500. This is slower and costs tokens, so run it on a smaller set of canaries than the string check. Set the temperature to 0 and repeat each probe a few times, because one pass can be luck.
Test constraints for flips
A needle check on SMS passes even if the summary says "SMS contact is fine." For constraints, probe with a question that would break the rule, such as "Draft a text message to the customer," and check that the answer refuses or redirects. Matching on the rule's words is not enough.
Plant decoys
A decoy is something the user never said, such as a second budget figure. After compaction, assert that its string does not appear in the summary. This catches invented facts, which the summarization prompt forbids but a model can still produce.
Check the size
The summary prompt caps length at 300 words. Assert that the summary stays under a token limit after many rounds. A summary that grows every round will eventually crowd out the recent messages.
Structural checks
Fact checks do not cover message integrity. Add assertions on the request itself:
- The first non-system message is a
usermessage. - Every assistant tool call in the window has its matching tool result, and no tool result lacks its call.
- The total estimated tokens fit the input budget you set in the budget chapter.
These are cheap and need no model. Run them on every compacted request in your tests.
Edge cases to cover
- A fact stated in the last message that falls outside the window because
keep_recentis small. - A fact that the user later corrects. The summary must keep the new value, so assert that the old value is absent.
- Two compactions in a row with no new messages between them. The result should be stable.
- A conversation shorter than the trigger.
compactshould return its inputs unchanged. - Non-English text and code blocks, where the character-based token estimate is least accurate.
Exercise
Add a canary for a correction. The user first says "Our budget is 4,500 euros" and 20 filler pairs later says "Correction: the budget is 5,200 euros." Which assertions should the test make about the compacted request, and which summarizer behavior would each one catch?
Show answer
Assert that "5,200" is present, which catches a summarizer that loses the later statement. Assert that "4,500" is absent, which catches a summarizer that keeps both values and leaves the model unsure which is current. Then probe with "What is my budget?" and check that the answer contains "5,200" and not "4,500". This shows whether the model uses the corrected value, not just whether the string appears.