Local RAG Design: Store the Evidence First, Then Retrieve

How mt_rag separates replayable evidence, rebuildable query views, verified graph paths, and bounded generation—and why current source still wins.

On this page · 16 sections

Ask a vector database, “Who calls this provider method?” and it may return the file that defines the method, a design page that mentions it, and an issue with a similar name. Those are useful leads. None of them proves the call.

That distinction is where production-minded RAG begins. Search discovers candidates; version metadata establishes whether they are current; graph evidence proves relationships; generation explains only what survives those checks.

I built mt_rag around that separation. It is not a mandatory prelude to every Codex task. It is an on-demand evidence capability for questions that cross source code, documentation, work tracking, attachments, and approved configuration. When a question already names an exact file or symbol, reading the current workspace is usually faster and more authoritative.

The Design in One Sentence

Preserve facts once, rebuild query views from them, and never let fluent generation upgrade a plausible match into a proven engineering claim.

That produces three different responsibilities. The last column of the table is what each plane must not claim:

Plane What it owns What it must not claim
Evidence Immutable source bytes, typed IR/CPG, hashes, locators, commits, and manifest generations That a retrieved candidate answers the question
Projection Vector, keyword, and graph views bound to one evidence generation That similarity proves a relationship
Answer Bounded retrieval decisions, verified paths, citations, confidence, and limitations Facts outside the accepted evidence

Architecture Map

Local RAG evidence-system architecture map; open the full-size SVG

Open the diagram to zoom without losing detail, or download the editable draw.io source. Its ten numbered stages are dependencies inside the evidence system—not a workflow that every engineering task must traverse.

The first plane keeps replayable facts in a local SHA-256 content-addressed store (CAS; that is, content is stored and fetched by its hash). Raw snapshots, DocumentIR, and the full Code Property Graph (CPG) remain addressable by hash; an immutable manifest binds them to source identity, revision, locator, and parser version.

The second plane creates query-specific views:

  • Dense vectors serve semantic discovery.
  • The keyword lane serves lexical and exact-identifier discovery.
  • Neo4j serves evidence-backed relationship traversal.

These stores are deliberately replaceable: none is the final source of truth, and each must prove that its projection and consumer cursor match the active manifest before a query proceeds.

The third plane limits semantic judgment. A controller can answer, rerank, request one more retrieval, or stop as insufficient. Deterministic code owns the accepted path, citations, confidence, and evidence gaps. The final model may improve readability; it cannot create a missing edge or silently broaden the evidence set.

One Question Through the System

Consider: “What is the call chain from a GraphQL field to the provider method that handles it?”

  1. Start with the original question. The current grounded-query path sends it directly to hybrid retrieval. A rewrite step from a legacy answer path is not silently inserted in front of it.
  2. Discover candidates in two lanes. Dense retrieval finds semantically related code and documents. The keyword lane protects exact field, resolver, class, and method names. Exact identifiers remain part of that keyword lane rather than receiving an artificial third quota.
  3. Fuse ranks, not incomparable scores. Weighted reciprocal rank fusion combines the dense and keyword rankings at 70/30. If an exact keyword candidate is absent from the dense top set, the system obtains its real vector score before assigning its dense rank. It does not invent one.
  4. Restore context, then prove the relationship. Child chunks hydrate their parent context. Graph expansion starts only from the first ranked retrieval entity that has graph IDs, which prevents a lower-ranked but convenient result from lending an unrelated verified path to the answer. Neo4j returns only edges whose evidence is marked verified.
  5. Make a bounded decision. The controller may choose answer, rerank, retrieve_again, or insufficient. There are at most two retrieval rounds. An insufficient decision vetoes call-chain generation instead of becoming a suggestion that the final model can ignore.
  6. Separate proof from presentation. Deterministic code builds the structured chain, confidence, citations, and limitations. The public result contains a readable business summary and a compact call chain, while a sibling structured_answer retains the machine-checkable contract. The final renderer must stay inside both.

This is the practical difference between a search result and an engineering answer. A chunk can show that two names occur near each other. Only a current, evidence-backed path can justify “A calls B.”

Three Lessons That Changed the Design

1. The most dangerous failure is not missing evidence—it is borrowing the wrong proof

Expanding the graph from several highly ranked candidates makes it easier to find an attractive verified path. But that path may belong to the second or third candidate rather than the user's primary intent. I therefore allow graph search to start only from the highest-ranked entity that has graph IDs.

This deliberately gives up some recall. The alternative is evidence borrowing: every edge in a chain can be true while the chain is still wrong for the question. That error is harder to spot than an ordinary hallucination because the citations look respectable.

2. Consistent indexes do not guarantee current facts

Aligned vector, keyword, and graph cursors prove that the projections came from one manifest. They do not prove that a repository pin still represents today's code or that an old document remains the active rule. This is why the implementation separates projection freshness, source currentness, and content identity.

When those concepts are collapsed, re-embedding stale material creates the appearance of an update without updating the fact. A new vector timestamp cannot repair an obsolete commit. Revision, commit, and authoritative-source checks have to remain explicit.

3. Readable prose should not own the proof

I used to think of a well-written answer as the final stage. I now treat it as a constrained view. Deterministic code fixes the path, citations, confidence, and limitations first; a model then turns that proof object into something a developer can scan.

This does not eliminate model error, but it changes the blast radius. A poor renderer damages clarity. A corrupted proof object damages trust. They need different contracts, tests, and failure behavior.

What Has Actually Been Validated

“Ready in shadow” and “serving production” are different states. The current runtime policy keeps System RAG in shadow mode (that is, running in parallel without serving production), requires separate approval for production cutover, and retains the legacy data path.

Capability Evidence today Boundary
Evidence, vector, keyword, and graph projections A real local backfill and readiness checks bind the stores to one manifest generation A point-in-time local state, not a permanent corpus-size or accuracy claim
Historical grounded queries End-to-end shadow examples were exercised with the earlier local answer runtime Useful baseline evidence, not validation of every later runtime change
Current Codex controller and answer layer Runtime configuration, contract tests, and deterministic smoke coverage are present A fresh live Codex query has not been counted as validated without the separate authorization it requires
Production cutover Not performed Readiness never grants deployment authority

This distinction matters because the current answer layer has changed since the historical end-to-end examples. Reusing those examples as proof of the new renderer would make the article sound stronger while making the evidence weaker.

Four Invariants

  1. Source identity survives embedding. Every chunk can return to its source record, locator, original hash, and CAS object.
  2. Similarity never becomes relationship proof. A vector hit is a candidate; every accepted graph edge needs independent evidence.
  3. Freshness does not redefine content identity. Time can affect ranking, but it cannot manufacture a new content hash and embedding every day.
  4. Readiness does not authorize deployment. Passing tests, aligned cursors, and a healthy shadow do not replace an explicit production decision.

Failure Is Part of the Contract

Each row below is one failure: the middle column is the system response, and the last column is what that response costs.

Failure System response Trade-off
An old document ranks highly Query-time freshness lowers its weight while preserving its historical identity A still-valid old document may rank lower, so actual revision changes override age alone
A code hit belongs to an old commit Currentness fails; the hit cannot represent the current implementation Repository pins and commit lineage require maintenance
Vector data is current but the graph lags The manifest/cursor gate reports stale and withholds a verified chain Availability yields to relationship correctness
No verified path exists The controller can retrieve once more, then returns insufficient Some plausible questions remain unanswered
The controller or renderer violates its output contract Deterministic fallback constrains or rejects the result The response may be less fluent, but unknown facts are not embellished
One projection update fails That consumer keeps its prior cursor and cannot masquerade as current Independent cursors add operational state but isolate failures

How I Would Measure It Next

Recall@K still matters, but it is not enough. I care more about four measurements:

  • Currentness rejection: does the system actually refuse to present an old commit or revision as current?
  • Verified-path coverage: how many consequential transitions in an answer have independent evidence rather than a nearby mention?
  • Wrong-anchor borrowing: does a true but off-topic path leak in from a secondary candidate? This should approach zero.
  • Abstention quality: when evidence is insufficient, does the system stop consistently and name the missing edge, version, or source class?

The ceiling of an engineering RAG system is defined not only by how many questions it can answer, but also by how reliably it recognizes the questions it should not answer yet.

When RAG Is the Wrong First Tool

  • Use the current source directly for exact code facts.
  • Use runtime logs for a runtime incident.
  • Use the authoritative operational system for deployment or production state.

Use RAG when the hard part is discovering which repository, document, issue, attachment, and relationship deserve inspection together.

That boundary keeps RAG useful. It narrows a large cross-source search space and preserves provenance; it does not replace primary evidence or permission to act on it.

If You Are Adopting This on a Team

The architecture above is the easy part to copy. What determines whether an evidence-first RAG system survives contact with a real engineering organization is ownership, rollout, and what you agree to measure.

Decide who owns each plane.

  • The evidence plane is a data product: someone must own source onboarding, retention, and access control.
  • Projections are infrastructure: someone must own rebuilds, cursor health, and capacity.
  • The answer contract is a product surface: someone must own its schema and refusal behaviour.

When one team owns all three by default, the projection work always wins because it is the most visible, and currentness quietly erodes.

Roll out as a read-only shadow first. Run the system beside the way engineers already find answers, record what it would have said, and review disagreements weekly. Promote it only for question classes where its abstentions are trusted, not merely where its answers are fluent.

Agree on the non-goals in writing. This system does not replace reading current source, does not authorize changes, and does not speak for production state. Writing that down early prevents the most common failure of internal AI tools: being blamed for decisions they were never meant to make.

Budget the cost explicitly. Embedding, re-indexing, graph maintenance, and model calls all have a run-rate. Tie each to a question class with an owner, so the system can be scaled down as deliberately as it was scaled up.

Each rollout stage has an explicit exit criterion:

Rollout stage Exit criterion
Shadow Currentness rejection and wrong-anchor borrowing measured on a fixed question set
Opt-in Engineers in one domain prefer it for cross-source discovery; abstentions are reviewed, not ignored
Default for discovery Evidence gaps are routed to owners; stale sources are visible on a dashboard
Never Treating it as authority for production state or code changes

Verifiable Project Evidence

  • README.md describes the current data scope, commands, and shadow boundary.
  • config/rag-runtime.json defines CAS verification, the local embedding profile, weighted RRF, controller limits, and cutover policy.
  • src/mt_rag/system/pipeline.py assembles raw evidence, typed IR/CPG, chunks, and manifests.
  • src/mt_rag/retrieval/system_index.py implements hybrid retrieval, exact-candidate vector completion, temporal reranking, and parent hydration.
  • src/mt_rag/system_graph/query.py enforces projection/cursor checks and verified-only path traversal.
  • src/mt_rag/query/controller.py, runtime.py, and answer.py separate bounded decisions, deterministic proof objects, and readable output.
  • The shadow validation reports distinguish real backfill readiness, historical live-query evidence, and the current runtime's remaining live-validation boundary.

Series Map

The rest of the series follows each boundary separately: what it protects, how the current code enforces it, where the system stops, and which complexity that choice introduces:

  1. Architecture (this article)
  2. One Question, Three Sources: How Far Code, Jira, and Confluence Can Each Answer It
  3. When Local RAG Is Worth Calling, and When Reading the Source Is Faster
  4. Why a Local Immutable CAS Holds the Evidence Foundation
  5. Why DocumentIR, Issue IR, and CodeIR Have to Be Split
  6. Why a Code Hit Is Not Yet an Answer
  7. How Incremental Projection Lets Vector, Keyword, and Graph Evolve Independently
  8. Why Vector, Keyword, and Neo4j Use Different Stores
  9. Balancing 70/30 Hybrid Retrieval and the Graph Anchor
  10. Why the LLM Controller Is Allowed at Most Two Retrieval Rounds
  11. Turning Retrieval Candidates into an Engineering Conclusion You Can Deliver

References

Related notes

Working on something similar?

I'm always happy to compare notes on distributed systems, delivery, and applied AI.

[email protected]