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, versio...