DEV Community

Cover image for Context compaction silently reordered my retrieved chunks — an ordering checklist for RAG builders
InApp
InApp

Posted on Originally published at imapp.blogspot.com

Context compaction silently reordered my retrieved chunks — an ordering checklist for RAG builders

I had a RAG pipeline on top of a 90-page contract. Converted with the doc-to-markdown endpoint, chunked by section, retrieved top-5 by cosine, concatenated into the context window. Answers looked fine for a week, then a reviewer caught that my agent was citing terms in an order that contradicted the document. Not hallucination — the model was being honest about what it received.

The bug: my context compaction step was sorting chunks by relevance score before sending them to the model. The retriever returned them in document order, compaction reshuffled them to maximize signal near the start, and any clause that referenced "as defined in Section 4" suddenly had its referent land after the dependent clause. Models handle that fine when it's obvious; in dense legal text it was not obvious.

Three things I now check before compaction:

  1. Is the original document order semantically load-bearing? For most long docs the answer is yes — cross-references, numbered steps, version histories. Preserve it.
  2. Am I compacting content or metadata? I was folding chunk scores into the text as a hint, which the model occasionally quoted. Scores belong in the retrieval layer, not the prompt.
  3. Does the compacted block fit a single model turn, or does it get summarized again downstream? Double summarization is where most subtle loss happens. I now reject anything that would need a second pass and fall back to smaller chunks.

I also stopped using relevance as the primary sort. Retrieval still ranks; the context window assembly respects document order among the selected set. Confidence on multi-step questions went up noticeably once I did that.

Long docs are the case where this bites hardest. I convert them via the universal document-to-markdown endpoint at https://x402.freeq.one/tools/document_to_markdown.html so the input is at least clean; compaction decisions on messy HTML would have been worse. But the lesson is in the assembly step, not the conversion.

Top comments (0)