Skip to content
Visual explainer 3h to learn 4 steps

Combine evidence across multiple retrieval steps

Aggregate sources across retrieval steps with full lineage, no repeated searches and drafts based only on permitted evidence.

By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 11 minutes to read.

Topic 21 of 34

In short

When an agent searches more than once, it collects evidence from several steps. Aggregation means merging those results into one clean evidence set: each source keeps a record of which step and query found it, repeated searches are skipped, duplicates are merged, and anything the caller may not see is dropped before drafting. The answer may cite only what is left in that set.

Think of it like this: Like a researcher keeping a notebook of where every quote came from, so the final report never cites a book they did not actually check out.

Explained simply

When the assistant searches more than once, for example after rewriting a query or splitting a two-part question, it ends up with several lists of results. Some results will repeat. Some may come from a tool rather than a search. Aggregation is the job of turning all of that into one tidy list of evidence.

Each piece of evidence keeps a short history called lineage: which step found it, with which query, and at what rank. Lineage lets you answer the question "why did the assistant cite this?" weeks later, when a user reports a wrong answer.

The assistant also keeps track of the searches it has already run. If it is about to run the same search again, it skips it. That saves time and money, and stops the agent getting stuck repeating itself.

Before writing the answer, the merged list is filtered once more so only evidence the caller is allowed to see remains. The model drafts from that list only, and any citation that points outside it is rejected.

Press Play on a diagram to walk through it one step at a time.

FlowFrom several searches to one permitted evidence set
  1. 1
    Search step 1..n

    Each returns chunks with scores

  2. 2
    Record lineage

    Step, query and rank for each chunk

  3. 3
    Merge

    One entry per chunk ID, keep best score

  4. 4
    Permission filter

    Drop chunks outside caller scope

  5. 5
    Draft

    Cite only IDs in the final set

MapAnatomy of one evidence item
Evidence item chunk_id 4f2a
  • Source
    • doc_id expenses-policy
    • doc_version 3
    • visibility staff
  • Lineage record 1
    • step 1, hybrid search
    • query: expense claim deadline
    • rank 2
  • Lineage record 2
    • step 2, rewrite
    • query: submit expenses within days
    • rank 1
  • Merged values
    • best rank 1
    • fused score 0.032
    • permitted: yes

In depth

What lineage should contain

Lineage is metadata attached to each evidence item. Keep it small but complete enough to replay the decision. For each hit record the run ID, the step number, the tool or search that produced it, the exact query text, the rank and the score. Keep the stable chunk ID, document ID and document version from your corpus, so the citation can be traced back to the exact text that was indexed.

When the same chunk is found by two steps, keep both lineage records under one evidence item. That tells you something useful: a chunk found by several different queries is usually strong evidence. Do not store the chunk text again in each lineage record; the chunk ID is enough to fetch it.

  • run_id, step, tool, query, rank, score
  • chunk_id, doc_id, doc_version
  • One evidence item, many lineage records
  • Text stored once, referenced by ID

Skipping repeated searches

Agents often repeat themselves. After a weak result the model may produce a rewrite that is the same query with different capital letters, or swap two words. A seen-queries set catches these cheaply. Normalise each query before checking it: lowercase, collapse spaces, strip punctuation at the ends. You can also include the search parameters, such as filters and top-k, in the key, because the same text with a different filter is a different search.

When a repeat is detected, do not count it as a failed search and do not call the search engine. Record a skipped step in the run log so evaluation can see that the agent tried to repeat itself. If the agent repeats more than once, that is a strong signal to stop and move to drafting or abstention.

FlowDeciding whether to run a search
  1. 1
    Proposed query

    From the model or a rewrite rule

  2. 2
    Normalise

    Lowercase, collapse spaces, add filters

  3. 3
    Seen before?

    Yes: log skipped and stop

  4. 4
    Run search

    No: search in caller scope

  5. 5
    Record key

    Add to seen set with lineage

Merging and deduplicating

Merge by stable chunk ID first. That handles exact repeats. Then handle near duplicates: the same paragraph can appear in two versions of a document, or in a policy and its FAQ. For versions, keep the current effective version and drop superseded ones, following the freshness rules from the conflicting-sources topic. For copies across documents, keep the more authoritative source.

When merging scores from different searches, be careful. Scores from a keyword search and a vector search are on different scales, so taking the maximum across them can be misleading. A safer approach is to keep the best rank per search and combine ranks with reciprocal rank fusion, the same method used for hybrid retrieval. Then cut the merged list to your context budget.

  • Exact repeats: merge by chunk_id
  • Versions: keep the current effective version
  • Different score scales: fuse ranks, not raw scores
  • Trim to the context token budget last

Drafting only from permitted evidence

Retrieval should already filter by the caller's scope, but aggregation is a second gate. A reference lookup tool, a cached result or a bug in one search path could still let a restricted chunk in. Apply the same permission check to the merged set, using the caller identity from the verified request, not from anything the model said.

After the model drafts the answer, validate citations: every cited ID must be in the final permitted set. If the draft cites something else, reject the draft and retry once with a reminder, or abstain. Never quietly drop the bad citation and keep the sentence, because the sentence may contain information from the hidden source.

  • Check scope on the merged set, not just at search time
  • Identity comes from the request, never from model text
  • Every citation must be in the final set
  • Bad citation: retry once or abstain, never patch silently

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Track lineage for each source~45m
  2. 2
    Skip repeated searches~45m
  3. 3
    Merge and deduplicate evidence~45m
  4. 4
    Draft only from permitted sources~45m

Key points

  • Every evidence item keeps its lineage: which step, which query and which rank found it.
  • Normalise each query and keep a set of seen queries so the agent never repeats a search.
  • Deduplicate by stable chunk ID, keeping the highest score and all lineage records.
  • Filter by permission again at merge time, even if retrieval already filtered.
  • After drafting, reject any citation that is not in the permitted evidence set.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
seen_queries: set[str] = set()
evidence: dict[str, dict] = {}

def add_results(step: int, query: str, hits: list[dict]) -> bool:
    key = ' '.join(query.lower().split())
    if key in seen_queries:
        return False  # skip repeated search
    seen_queries.add(key)
    for rank, hit in enumerate(hits, start=1):
        item = evidence.setdefault(hit['chunk_id'], {**hit, 'lineage': []})
        item['score'] = max(item['score'], hit['score'])
        item['lineage'].append({'step': step, 'query': query, 'rank': rank})
    return True

Results are merged by chunk ID and each hit keeps its lineage.

A two-part question across two searches

A user asks: "How long do I have to file expenses, and who approves them?" Step 1 searches "expense claim deadline" and finds the expenses policy section on deadlines (rank 1) and an outdated version 2 of the same section (rank 3). Step 2 searches "expense approval" and finds the approvals section (rank 1) and the deadlines section again (rank 4). Aggregation merges the repeated deadlines chunk into one item with two lineage records, drops version 2 as superseded, and checks both remaining chunks are visible to the caller. The draft cites exactly those two chunk IDs.

Rejecting a draft with an outside citation

The model's draft cites chunk c9 alongside the two permitted chunks. c9 is not in the final set, perhaps because it was filtered out as restricted. The validator below returns the bad IDs, the run retries once with a reminder to cite only the listed IDs, and if the retry still fails the assistant abstains.

python
def invalid_citations(cited: list[str], permitted: set[str]) -> list[str]:
    return [c for c in cited if c not in permitted]

permitted = {'c1', 'c4'}
bad = invalid_citations(['c1', 'c4', 'c9'], permitted)
if bad:
    print('reject draft, unknown sources:', bad)  # ['c9']

Quick reference

  • Lineage per hit: run_id, step, tool, query, rank, score, chunk_id, doc_version
  • Normalise queries (case, spaces, filters) before checking the seen set
  • A skipped repeat is logged, not sent to the search engine
  • Merge by chunk_id; keep all lineage records under one item
  • Fuse ranks across searches; raw scores from different methods do not compare
  • Permission check again on the merged set, using request identity
  • Any citation outside the final set: retry once or abstain

Common mistakes

  • Concatenating results from every step, so the same chunk appears three times in the prompt.
  • Trusting that retrieval filtered permissions and skipping the check at merge time.
  • Dropping lineage, which makes a wrong citation impossible to debug later.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1The same chunk is found by step 1 at rank 3 and by step 2 at rank 1. How should it appear in the evidence set?

Question 2

2The model proposes the query "Expense Claim Deadline" after already searching "expense claim deadline". What happens?

Question 3

3Why is taking the maximum raw score across a keyword search and a vector search risky?

Question 4

4Retrieval already filters by scope. Why filter again at aggregation?

Question 5

5A draft cites a chunk that is not in the permitted set. What should you never do?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write normalise_query(text, filters) that returns a key you can store in a seen set, so that case, extra spaces and filter order do not matter.

  2. Exercise 2medium

    Write merge_hits(steps) where steps is a list of (step, query, hits) and each hit has chunk_id. Return one dict per chunk with best_rank and a lineage list.

  3. Exercise 3hard

    Build an aggregator test with two caller scopes. Plant a restricted chunk that a mock lookup tool returns. Show the merged set for a staff caller never contains it and that a draft citing it is rejected.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is lineage the same as a citation?
No. A citation tells the user which source supports a sentence. Lineage is internal metadata that explains how the system found that source, used for debugging and evaluation.
How many searches should an agent run before drafting?
Set a cap in the run budget, often three to five, and stop earlier when the evidence covers the question. Evaluation will show whether more searches ever help.
Can I just put every result into the prompt and let the model sort it out?
You can, but duplicates waste tokens, conflicting versions confuse the model and restricted chunks could leak. Merging and filtering first gives a smaller, safer prompt.

Go deeper

ShareXLinkedInWhatsApp