Group passage hits by a stable parent ID, budget enough candidates for distinct documents and keep permission filtering ahead of grouping.
Collapse retrieval results by document without losing the best passage
Passage rank is not document rank
A long source can contribute many similar passages to the top results. If the interface promises a set of documents but displays every passage separately, one manual may occupy the entire first page. Result collapse selects one representative hit per stable parent document, commonly the highest-ranked eligible passage. That improves source variety for browsing, but it can hide a second passage from the same document that contains another required fact. Evidence packing should retain supporting spans when answer generation needs them even if navigation shows one card per document.
Filter before choosing representatives
Permission and deletion checks apply to every candidate passage before grouping. A private high-score passage must not be selected as the document representative, and its existence must not leak through group counts or 'more from this document' links. Use a tenant-scoped document key where IDs can collide across tenants. A representative should carry its passage ID, source revision and the exact score branch that produced it. Corpus permissions and delete tombstones remain authoritative even when a grouping API operates inside the search engine.
Candidate depth sets the diversity ceiling
Collapsing a top-12 passage pool cannot return twelve documents if ten passages came from one manual. Retrieve deeper, group, then take the requested number of distinct parents, or use a backend feature that performs collapse before final top-K selection. Oversampling has a latency cost and no fixed multiplier guarantees diversity for every query. Track unique-parent count at several candidate depths. If a rare document never entered the pool, post-processing cannot recover it. Reranker windows need the same distinction between passage count and unique-source count.
Choose a deterministic representative
Within a group, rank by the retrieval score or a reranked score under one stable policy, then break ties by passage ID or source order. Keep the original passage score visible to diagnostics. When multiple passages from the same source answer different aspects, offer an explicit expansion rather than quietly merging fragments into one invented excerpt. Near-duplicate documents from distinct parents require a separate duplicate policy. Independent support explains why two copies of the same text are not two independent sources. Collapse is for presentation and candidate allocation; it does not establish source independence.
Counts and pagination require a contract
A result count before collapse may describe passages, not distinct documents. Facet counts can also reflect the uncollapsed set, depending on the backend. Label the unit in the UI and avoid promising an exact number of groups unless you compute it. Paginating grouped hits needs a stable sort and a consistent index view; a changing candidate pool can repeat or skip documents. Point-in-time pagination sets that boundary. Evaluate grouped recall and answer support alongside visual variety, because hiding duplicate cards is useful only when important evidence remains reachable.
Worked contract
from dataclasses import dataclass
@dataclass(frozen=True)
class PassageHit:
tenant_id: str
document_id: str
passage_id: str
score: float
permitted: bool
def distinct_documents(hits: list[PassageHit], limit: int
) -> list[PassageHit]:
if limit < 0:
raise ValueError("negative result limit")
best = {}
for hit in hits:
if not hit.permitted:
continue
key = (hit.tenant_id, hit.document_id)
current = best.get(key)
if current is None or (-hit.score, hit.passage_id) < (
-current.score, current.passage_id):
best[key] = hit
return sorted(best.values(), key=lambda hit: (
-hit.score, hit.tenant_id, hit.document_id, hit.passage_id))[:limit]
hits = [PassageHit("plant-a", "manual-47", "p2", .81, True),
PassageHit("plant-a", "manual-47", "p4", .88, True),
PassageHit("plant-a", "manual-81", "p1", .95, False),
PassageHit("plant-a", "manual-94", "p3", .76, True)]
chosen = distinct_documents(hits, 2)
assert [(hit.document_id, hit.passage_id) for hit in chosen] == [
("manual-47", "p4"), ("manual-94", "p3")]Performance and operating cost
For C candidate passages, grouping takes O(C) expected time and O(G) space for G eligible parent groups; sorting those groups costs O(G log G). The code assumes the caller already fetched candidates and made permission decisions. A deeper candidate pool increases search, transport and rerank costs, while backend inner-hit expansion may issue additional searches. Measure distinct-parent yield at each depth and keep a latency budget. If authorization is unavailable, fail closed before this function rather than treating an absent permission as true.
Common Mistakes
- Collapsing before permission checks and leaking the identity of a private document.
- Fetching only K passages and assuming K distinct parent documents will remain.
- Reporting raw passage hit counts as distinct-document counts.
- Discarding other passages from a parent when the answer requires evidence from more than one span.
Validation drill
Construct 64 queries whose top 30 passages include repeated manuals and near duplicates. Compare document recall at 8, unique-parent yield and answer support before and after grouping; inject one forbidden highest-scoring passage per test group.
