The Dark Art of Context Truncation & Dynamic Prompt Compaction in Production RAG
Figure: taxonomy of agentic RAG systems. Under Memory & Context, note dynamic context pruning — the production name for what this post calls truncation and prompt compaction. Used as a conceptual map of where these techniques sit among architecture, retrieval, and reasoning choices.
Every serious RAG deployment eventually hits the same wall: the model’s context window is finite, your retrieved evidence is not, and the prompt template wants to be a novel. Something has to go. That decision — what to keep, what to compress, what to drop, and in what order — is not a formatting detail. It is the difference between a grounded answer and a confident hallucination that happened to see the wrong half of the evidence.
This post is about that decision as a first-class system: conceptually (what information is), practically (what pipelines do under load), and operationally (how to measure whether you are solving the right problem or just making the prompt shorter).
1. The real problem is not “too many tokens”
Token limits are the symptom. The disease is asymmetric value of information under a hard budget. A 200-token citation that contains the exact clause a lawyer needs is worth more than 2,000 tokens of near-duplicate FAQ fluff. A one-line system policy that forbids leaking PII is worth more than an entire retrieved chapter that merely restates it. Truncation that treats tokens as interchangeable destroys that asymmetry.
So the production question is never “how do I fit everything?” It is:
Given a fixed budget B, a user question q, and a candidate set of context units C, choose a subset (or compressed representation) C′ that maximizes answer quality and constraint satisfaction while |encode(C′)| ≤ B.
Once you write it that way, naive left-to-right chopping looks as crude as it is.
2. Mentally separate four layers of the prompt
Production prompts are not one bag of text. They are layers with different loss tolerances:
| Layer | Examples | Truncation tolerance |
|---|---|---|
| Policy / system | Safety rules, tool rules, output schema | Near zero — cut here last, or never |
| Task framing | “Answer only from context; cite chunk IDs” | Low |
| Evidence | Retrieved chunks, tool results, memories | High — this is where compaction belongs |
| Conversation | Prior turns, user clarifications | Medium — keep recent + salient older turns |
Most failures I see come from applying one strategy across all four layers: “keep the last N tokens of the whole prompt.” That can delete the policy line that made the system safe, while preserving a long, low-value appendix of a retrieved PDF.
3. What “context” means in agentic RAG
The taxonomy above is useful because it shows that memory and context are not just “stuff in the window.” In agentic RAG, context is assembled from architecture (who plans/retrieves), retrieval strategy (one-shot vs iterative vs self-refining), reasoning style (ReAct, reflection, tree search), and memory type (persistent, episodic, pruned, refreshed). Dynamic context pruning sits specifically under Memory & Context: it is the runtime policy that decides which of those streams survive into the final call.
That matters conceptually. Truncation is not only a post-retrieval trim. In iterative or multi-agent setups, you may compact after each hop: drop dead-end tool traces, summarize intermediate plans, keep only the evidence that survived self-critique. Compaction becomes part of the control loop, not a final polish.
4. A map of truncation strategies (from blunt to intentional)
4.1 Hard cut / sliding window
Keep the first K or last K tokens. Cheap, predictable, often wrong. Prefer it only for ephemeral debug UIs — never as the sole production policy for evidence.
4.2 Priority queues by source
Assign each unit a priority: system > task > top-k retrieved > chat history > debug traces. Fill the budget from the top. Still coarse, but it stops policy from being eaten by logs.
4.3 Relevance-ranked evidence packing
Score each chunk against q (embedding similarity, cross-encoder, or hybrid). Pack highest scores until the budget fills. This is the default serious baseline for classic RAG. Failure modes: near-duplicates waste the budget; high lexical similarity can miss the decisive paragraph that uses different wording; long chunks starve diversity.
4.4 Diversity-aware packing (MMR-style)
Maximize relevance while penalizing redundancy. Conceptually: you are buying coverage of the answer’s information needs, not a pile of paraphrases of the same sentence. In practice this fixes “five chunks that all say the refund window is 30 days” while the exception case never enters the window.
4.5 Structural truncation
Prefer cutting at semantic boundaries: sections, paragraphs, sentences, not mid-token. Keep headers with their bodies. Prefer whole atomic claims over fragments that lose truth conditions (“…except for enterprise customers” disappearing while the general rule remains).
4.6 Dynamic prompt compaction (the dark art)
Compaction is truncation plus lossy encoding of meaning. Instead of dropping a unit entirely, you replace it with a shorter surrogate that preserves task-relevant content:
- Extractive compression: keep key sentences; delete the rest.
- Abstractive summarization: rewrite a chunk conditioned on q.
- Claim / triple extraction: turn prose into (subject, relation, object) or bullet facts.
- Schema projection: for tables/JSON, keep only columns/fields needed by q.
- Trace folding: for agents, collapse tool I/O into “called X, got Y, decided Z.”
Compaction is powerful because it can raise information density. It is dangerous because it can invent structure that was not in the source, or drop negations and exceptions — the exact failure mode that creates “almost true” answers.
5. A practical production algorithm
Here is a pattern that has held up across several RAG systems I have worked on. Treat it as a reference design, not dogma.
- Reserve budgets. Split B into hard partitions: e.g. 15% policy+task, 70% evidence, 15% dialogue/memory. Never steal from policy.
- Normalize candidates into units. Chunks, memory items, tool results — each with id, source, raw text, token estimate, metadata.
- Score for the question. Hybrid retrieval score + optional reranker. Store why it scored (for audits).
- Deduplicate. Near-duplicate collapse before packing; keep the highest-scoring exemplar and maybe one dissenting source.
- Pack with diversity. Greedy MMR or similar until the evidence budget is nearly full.
- Compact overflow, don’t only drop. For the next-best units that did not fit, run query-conditioned extractive compression into a “secondary evidence” block with a smaller token cap.
- Protect critical spans. Regex/heuristic guards for numbers, dates, “except”, “not”, legal section IDs — never summarize those away without keeping the original span.
- Render with delimiters and IDs. Each unit keeps a stable id for citations. Compactions cite parent ids.
- Fail loud when evidence is insufficient. If packed evidence is below a coverage threshold, instruct the model to refuse or ask a clarifying question — do not silently answer from priors.
6. Solving the information problem (not just the length problem)
Good compaction is an information-selection problem. Three useful lenses:
Coverage of answer facets
Decompose q into facets (“who”, “when”, “under what exception”, “what evidence”). Score whether C′ covers each facet. Truncation that maximizes similarity but leaves a facet empty is a known path to hallucinated completion of that facet.
Contradiction handling
If two high-scoring chunks disagree, naive packing may keep only one. Prefer keeping both short excerpts with explicit conflict markers, or escalate to a clarifying answer. Compacting away the conflict is how systems invent false certainty.
Provenance density
Every compacted claim should remain linkable to a raw span. If your compressor cannot point to a character range or chunk id, you have created unverifiable text — which belongs in a scratchpad at best, not in the evidence channel.
7. Conceptual pitfalls that show up as “random” bugs
- Lost-in-the-middle: even when units fit, models under-attend mid-context. Put the highest-value evidence first or last deliberately; do not rely on accidental order from the vector DB.
- Recency bias in chat: truncating oldest turns can erase the user’s constraints stated early (“answer in German”, “ignore vendor marketing”). Pin constraint turns.
- Self-refining retrieval loops: each iteration can append more context until the window is garbage. Cap hops and compact intermediates aggressively.
- Tool vomit: agents dump full JSON payloads into the prompt. Project to schemas; keep hashes/ids for re-fetch instead of pasting megabytes.
- Compressor drift: an abstractive summary trained for “helpful paragraphs” will smooth away uncertainty. Prefer extractive for legal/medical/compliance.
8. Measurement: how you know compaction is working
If you only measure “tokens per request,” you will optimize for cheap wrongness. Track:
| Metric | Why it matters |
|---|---|
| Answer faithfulness / citation support rate | Did claims stay grounded after compaction? |
| Facet coverage | Did evidence address all parts of q? |
| Refusal quality on insufficient evidence | Does the system notice empty budgets? |
| p95 tokens and cost | Budget discipline under load |
| Duplicate ratio in packed set | Are you wasting the window? |
| Ablation: full vs compacted on a gold set | Quality delta attributable to compaction |
Run offline evals with paired prompts: same q, same retrieval candidates, different compaction policies. Promote a policy only when faithfulness does not drop more than your tolerance for the cost win.
9. A minimal reference shape in code
def build_evidence(q, units, budgets):
policy = render_policy() # fixed, never truncated
task = render_task(q) # fixed template
ranked = rerank(q, dedupe(units))
primary = mmr_pack(ranked, token_budget=budgets.evidence_primary)
overflow = [u for u in ranked if u not in primary]
secondary = [
extractive_compress(q, u, max_tokens=budgets.per_overflow)
for u in overflow[:budgets.max_overflow_items]
]
dialogue = pack_dialogue(budgets.dialogue) # pin constraints + recent
return render_prompt(policy, task, primary, secondary, dialogue)
The important part is not the function names. It is the existence of budgets, dedupe, pack, compress overflow, and pinned policy as separate stages you can test and roll back independently.
10. Where this sits relative to “just use a longer context model”
Longer windows help, but they do not erase the economics or the attention problem. A 1M-token window filled with duplicates and tool dumps is still a bad information channel — only more expensive. Compaction remains the art of raising the density of decision-relevant bits per token the model will actually use.
In agentic systems especially (planner-executor, multi-agent, iterative retrieval), dynamic pruning is how you keep the loop stable as traces accumulate. Without it, every successful tool call makes the next call less coherent.
Closing
Context truncation is easy to implement badly and hard to implement honestly. The honest version admits that you are throwing information away, measures what that costs, and spends the remaining budget on evidence that still carries provenance. Dynamic prompt compaction is the upgrade path: not shorter prompts for their own sake, but denser prompts that still answer the question the user actually asked.
If your RAG stack does not have an explicit compaction policy with reserved budgets and evals, you already have an implicit one — usually “whatever fit after concatenation.” Make it explicit. That is the whole dark art.