
Graph RAG’s Error Migration Problem: A Test Harness That Separates Retrieval Failures From Generation Failures
On this page
Introduction — Why a Better Graph RAG Score Can Hide a New Error Distribution
What this harness measures
This post builds a Node.js test harness for Graph RAG that scores entity linking, graph completeness, retrieval coverage, context assembly, citation support, and answer correctness as six separate checks, so a change in final-answer accuracy can be traced back to the stage that caused it. Everything runs against a small fictional corpus with deterministic fixtures, so you can reproduce each result before pointing the harness at a real one.
Frame the technical position
Graph RAG gets sold on one number: the hallucination rate went down. That number is an aggregate over at least seven stages, and an aggregate won't tell you where the remaining errors landed. My position is that graph retrieval should be evaluated as a chain of independently testable stage contracts, with a per-question trace recording what each stage actually produced. The question worth asking isn't only "did final answer accuracy improve" — it's "where did the errors move, and are the new locations worse".
That matters for a specific reason. Graph retrieval changes the shape of available evidence. Vector search hands back passages that are individually similar to the query. Graph traversal hands back paths that may be individually less similar but are jointly necessary. Swap one for the other and you can convert a visible failure into an invisible one: where the model used to invent a rule, it now cites a real section that was retrieved but truncated out of the context window. Both are wrong answers. Only one shows up in a naive hallucination metric, because the second arrives with a valid citation attached.
Introduce the supplied December 2, 2026 reports
Bioengineer.org published two items on 2026-12-02:
- Knowledge Graph Retrieval Cuts Legal AI Hallucinations While Shifting Error Sources — headline claim is fewer hallucinations in legal AI, with the sources of the remaining errors changing.
- LegalGraph maps Kazakhstan statutes into traceable graphs for accountable LLM reasoning — describes a system that maps Kazakhstan statutes into traceable graphs intended to support LLM reasoning.
The second is the more interesting engineering claim, because "traceable graph" is a statement about provenance and not about accuracy. Traceability is what makes error migration measurable at all. If every node and edge carries a source span, you can ask which span was missing from the context instead of guessing.
Establish the evidence boundary: what the snippets do not say
I have titles and one-line snippets. Nothing more. From that I cannot establish:
- whether the two reports describe the same study or two different efforts;
- which models were used, at which versions;
- corpus size, question count, or any effect size;
- how "hallucination" was operationalized, or what the "shift" moved toward;
- LegalGraph's schema, entity-linking method, or evaluation protocol.
So this post is not a replication and contains no numbers attributed to those reports. What follows is an independent harness design that takes the headline claim — "errors moved" — as a hypothesis worth being able to test. Everything measured below runs on fixtures I define, and every fixture number is labelled as a fixture expectation.
"Traceable" and "accurate" are different properties. A graph can be perfectly traceable and still be the wrong graph. Keep the two measurements separate or the second one hides inside the first.
Define Error Migration Before Measuring It
Map the seven stages of a Graph RAG pipeline
Error migration only means something if the pipeline is partitioned into stages with explicit contracts. Otherwise "the error moved" just means "a different part of the code looked suspicious".
| Stage | Input contract | Output contract | Failure it can own |
|---|---|---|---|
| Ingest | source bytes + revision metadata | revision text with stable offsets | wrong revision selected, spans lost |
| Entity linking | question text + scoped dictionary | entity IDs or explicit unresolved | wrong entity, silent guess |
| Graph construction | revisions + relation extraction | typed edges with provenance + validity interval | invented edge, dropped exception |
| Retrieval | entity IDs and/or query embedding | evidence units | shallow traversal, stale path, missed hop |
| Context assembly | evidence units + token budget | ordered context for the model | critical evidence dropped |
| Generation | question + context + answer schema | claims + citations | unsupported claim, contradiction |
| Citation rendering | claims + citations | resolved doc/section/span links | invalid span, dead identifier |
The two columns people skip are input contract and output contract. Without them, every failure looks like a generation failure, which is the most expensive place to debug.
Separate upstream retrieval failures from downstream generation failures
Four labels, kept independent:
- Evidence failure — the required source span is not in the retrieved set, or not in the final context.
- Support failure — the span is present but the generated claim is not entailed by it.
- Answer failure — a claim contradicts the gold fact.
- Rendering failure — the citation identifier or span does not resolve.
The cell that matters is correct answer, insufficient support. Three things cause it: the question leaks the answer, a gold path leaked into retrieval input, or prior knowledge filled the gap. Fictional corpora earn their keep here precisely because prior knowledge can't help. A model that answers a question about invented statutes correctly, with no supporting context, has exposed a harness bug rather than a capability.
The mirror case counts too: sufficient evidence, wrong answer. That's a prompt, schema, or instruction-following problem, and no amount of graph engineering fixes it.
Separate an observed shift in failure location from a causal claim
If "unsupported-claim" errors drop and "missing-evidence" errors rise, you've observed a change in distribution. The causal claim — "graph retrieval caused it" — needs an intervention: same generator, same question, gold evidence injected, everything else pinned. If the failure disappears, the blocking stage is upstream of generation. If it persists, it isn't.
What would falsify the causal story: failures persisting under gold evidence, or failures appearing under gold evidence because the oracle context is formatted differently from real context. That second one is a real trap and I've hit it — gold evidence assembled as tidy JSON reads more easily than real retrieved context with duplicate spans and mid-sentence truncation.
Build a Small, Auditable Evaluation Corpus
Create fictional statutes with stable section identifiers
The fixtures below cover a jurisdiction I invented for this post: the Republic of Veltra. None of it is Kazakhstan law, and none of it should be cited as anything but a test fixture. That's deliberate. Invented law can't be recalled from pretraining, so a correct answer with no supporting evidence is diagnosable instead of ambiguous.
{
"corpusVersion": "veltra-fixture-4",
"documents": [
{
"docId": "demo/stat/2021-11",
"title": "Veltra Family Benefit Act (fictional)",
"revisions": [
{
"revisionId": "r1",
"validFrom": "2021-03-01",
"validTo": "2024-06-30",
"text": "... s.14(2) A parent caring for a child under 7 years is entitled to the child care benefit for the whole of the assessment year ...",
"sections": [
{
"sectionId": "s.14(2)",
"span": [1042, 1187],
"validFrom": "2021-03-01",
"validTo": "2024-06-30"
}
]
}
]
},
{
"docId": "demo/reg/2024-07",
"title": "Veltra Family Benefit Regulations (fictional)",
"revisions": [
{
"revisionId": "r2",
"validFrom": "2024-07-01",
"validTo": null,
"text": "... s.3(1) A seasonal worker is entitled to the child care benefit only for the months in which the worker is not engaged in seasonal employment ...",
"sections": [
{
"sectionId": "s.3(1)",
"span": [412, 612],
"validFrom": "2024-07-01",
"validTo": null
}
]
}
]
}
]
}
Six documents, nineteen sections, two revisions of one act, one regulation carrying an exception, one alias table. Enough to exercise every failure class, small enough that a reviewer can read it end to end.
Design questions that cover every failure class
| Class | Count (dev) | What it exercises |
|---|---|---|
| Direct lookup | 8 | single section, no traversal |
| Two-hop | 10 | entitlement + exception in different documents |
| Ambiguous entity | 6 | alias shared by two benefit types |
| Temporal validity | 6 | which revision was in force asOf a date |
| Exception | 6 | a rule that inverts the base entitlement |
| Contradiction | 4 | two sections that conflict across revisions |
| Unanswerable | 6 | corpus does not contain the fact; abstention required |
Forty development questions and forty held out separately. Forty is small: two-hop recall moving from 4/10 to 7/10 is a real signal about mechanics and a weak signal about a production legal corpus. Write that down in the report rather than letting a percentage imply more precision than the denominator supports.
Store gold data in versioned fixtures
{
"questionId": "q-014-exception",
"split": "dev",
"question": "In the 2025 assessment year, does a parent of a 4-year-old who works as a seasonal worker receive the child care benefit for the full year?",
"asOf": "2025-09-15",
"gold": {
"entityIds": [
"demo/entity/benefit-child-care",
"demo/entity/role-seasonal-worker"
],
"ambiguityGroup": null,
"requiredEvidenceSets": [
["demo/stat/2021-11@r1#s.14(2)", "demo/reg/2024-07@r2#s.3(1)"]
],
"criticalEvidenceIds": ["demo/reg/2024-07@r2#s.3(1)"],
"expectedFacts": [
{ "key": "entitlement", "value": "partial-year" },
{ "key": "reason", "value": "seasonal-worker exception" }
],
"abstain": false
}
}
requiredEvidenceSets is an array of arrays on purpose: some questions have more than one legitimate support path, and scoring a single canonical path punishes a correct alternative route. criticalEvidenceIds marks the spans whose absence makes an answer unsupportable no matter how good the rest is.
Note the evidence ID format — docId@revisionId#sectionId. Revision inside the identifier means a stale-version retrieval can't accidentally match gold.
Keep development and held-out questions separate
Two rules, both enforceable in code:
- The retriever receives the question text, the
asOfdate, and access constraints. Never thegoldobject. - Tuning — hop limits, top-k, chunk size, prompt wording — touches the dev split only. The held-out split runs on release candidates and nothing else.
A recursive guard catches the leak that code review misses:
// harness/guards.mjs
const GOLD_KEYS = new Set([
'gold',
'requiredEvidenceSets',
'criticalEvidenceIds',
'expectedFacts',
'requiredNodeIds',
'requiredEdgeKeys',
'abstain',
]);
export function assertNoGoldLeak(payload, path = 'payload') {
if (payload === null || typeof payload !== 'object') return;
for (const [key, value] of Object.entries(payload)) {
if (GOLD_KEYS.has(key)) {
throw new Error(`gold field leaked into retriever input: ${path}.${key}`);
}
assertNoGoldLeak(value, `${path}.${key}`);
}
}
Wrap every retriever and generator call in this. I've been bitten by exactly this bug — a debug log that serialized the whole question object into the prompt — and it produced a beautiful, meaningless accuracy score.
Implement the Harness Around Explicit Stage Contracts
Define a JavaScript contract for each stage
// harness/contracts.mjs
/**
* @typedef {Object} LinkedEntity
* @property {string} mentionText
* @property {string|null} entityId // null means unresolved, never a guess
* @property {number} confidence
* @property {'canonical'|'alias'|'ambiguous'|'unresolved'} resolution
* @property {string|null} ambiguityGroup
*/
/**
* @typedef {Object} Evidence
* @property {string} evidenceId // `${docId}@${revisionId}#${sectionId}`
* @property {string} docId
* @property {string} revisionId
* @property {string} sectionId
* @property {[number, number]} span // absolute offsets into revision text
* @property {string} text
* @property {string} validFrom
* @property {string|null} validTo
* @property {'graph'|'vector'} retrievedBy
* @property {number} score
* @property {number} tokens
*/
/**
* @typedef {Object} Claim
* @property {string} claimId
* @property {string} text
* @property {Array<{docId: string, revisionId: string, sectionId: string, span: [number, number]}>} citations
*/
/**
* @typedef {Object} Answer
* @property {Claim[]} claims
* @property {boolean} abstained
*/
export const STAGES = [
'link',
'retrieve',
'assemble',
'generate',
'cite',
];
entityId: null with resolution: 'unresolved' is the most useful line in that file. It turns "I don't know which entity this is" into a first-class state instead of a silent nearest-neighbour guess, and it keeps the linking checker's denominators honest.
Capture a per-question trace across every stage
Every question writes one JSONL line. Trace text is stored as spans plus a short excerpt; full source text stays in the corpus file, not in traces you share.
{
"questionId": "q-014-exception",
"runId": "dev-graph-2026-12-04T09-12-00",
"linked": [
{ "mentionText": "child care benefit", "entityId": "demo/entity/benefit-child-care", "resolution": "alias", "confidence": 0.94 },
{ "mentionText": "seasonal worker", "entityId": "demo/entity/role-seasonal-worker", "resolution": "canonical", "confidence": 0.97 }
],
"traversedEdges": [
"demo/entity/benefit-child-care -SUBJECT_TO_EXCEPTION-> demo/entity/exception-seasonal-worker"
],
"retrieved": ["demo/stat/2021-11@r1#s.14(2)", "demo/reg/2024-07@r2#s.3(1)"],
"inContext": ["demo/stat/2021-11@r1#s.14(2)"],
"claims": [{ "claimId": "c1", "citations": ["demo/stat/2021-11@r1#s.14(2)"] }],
"labels": ["context"],
"earliestBlocker": "context",
"timings": { "link": 11, "retrieve": 84, "assemble": 2, "generate": 1740, "cite": 1 },
"errors": []
}
That single line is the argument of this post in one object. Retrieval succeeded. Context assembly dropped the exception. The generator answered from an incomplete rule set and cited a real section. Final-answer scoring sees a confident, cited, wrong answer.
Pin every setting that can change behaviour
{
"runId": "dev-graph-2026-12-04T09-12-00",
"split": "dev",
"corpusVersion": "veltra-fixture-4",
"corpusHash": "sha256:<written by scripts/hash-corpus.mjs>",
"graphBuild": { "extractor": "stub-relations-v1", "hopLimit": 2, "edgeFilters": ["SUBJECT_TO_EXCEPTION", "AMENDS"], "seedStrategy": "linked-entities" },
"embedding": { "model": "pinned-embedding-id", "dimensions": 1024, "chunker": "section-220tok-40overlap-v2" },
"generator": { "modelId": "exact-provider-model-string", "promptVersion": "answer-schema-v7", "temperature": 0, "topP": 1, "maxTokens": 900 },
"dependencies": { "node": "22.x", "harness": "0.4.2" }
}
modelId means the exact provider string, date suffix included. "GPT-class model" is not a pin; a rerun six weeks later is a different experiment.
Minimal Node.js project layout and reproducible commands
fixtures/
corpus/veltra-fixture-4.json
questions/dev.json
questions/heldout.json
scripts/citation-faults.json
harness/
contracts.mjs
guards.mjs
run.mjs
checks/linking.mjs
checks/graph.mjs
checks/coverage.mjs
checks/citations.mjs
checks/outcomes.mjs
stub/generator.mjs
scripts/
hash-corpus.mjs
validate-fixtures.mjs
runs/
node --version # v22.11.0 here; node:test needs >= 20.11
node scripts/validate-fixtures.mjs # span bounds, ID uniqueness, gold/eval consistency
node scripts/hash-corpus.mjs # prints corpusHash for the manifest
node --test harness/checks/ # checker tests only, zero model calls
node harness/run.mjs --split dev --retriever graph --generator stub
validate-fixtures.mjs is not optional. It asserts every span lies inside its revision text, every requiredEvidenceSets ID resolves to a real revision and section, every question ID is unique, and every criticalEvidenceIds entry also appears in some required set. A fixture with a dangling evidence ID scores zero recall forever, silently, and you'll spend a day blaming the retriever.
Check Entity Linking Before Blaming Retrieval
Test the cases that actually break linking
- Canonical IDs — the exact entity name maps to itself.
- Aliases — "CCB", "childcare allowance", "child care benefit" all resolve to
demo/entity/benefit-child-care. - Ambiguous names — "child benefit" is shared by two entities; the correct behaviour is a resolution using jurisdiction or context, or
unresolved, never a coin flip. - Unresolved mentions — a term absent from the dictionary must return
null. - Constraint-bound mentions — the same phrase under
asOf: 2021-06-01andasOf: 2025-09-15may resolve to different sections, not different entities.
// harness/checks/linking.mjs
export function scoreLinking(linked, question) {
const goldEntityIds = new Set(question.gold.entityIds);
const predicted = linked.filter((l) => l.entityId !== null);
const predictedIds = new Set(predicted.map((l) => l.entityId));
const truePositives = [...predictedIds].filter((id) => goldEntityIds.has(id));
const unresolved = linked.filter((l) => l.entityId === null);
return {
recall: goldEntityIds.size === 0 ? null : truePositives.length / goldEntityIds.size,
precision: predictedIds.size === 0 ? null : truePositives.length / predictedIds.size,
denominators: {
goldEntities: goldEntityIds.size,
predictedEntities: predictedIds.size,
mentions: linked.length,
},
unresolvedLinkRate: linked.length === 0 ? null : unresolved.length / linked.length,
ambiguity:
question.gold.ambiguityGroup === null
? null
: {
group: question.gold.ambiguityGroup,
resolvedTo: [...predictedIds],
correct: predictedIds.size === 1 && truePositives.length === 1,
},
};
}
Two deliberate choices. First, precision and recall always print their denominators alongside, because precision of 1.0 over one predicted entity is not a result. Second, unresolvedLinkRate is a first-class metric rather than a failure: a system that resolves 40% of mentions and abstains on the rest is more useful and far easier to debug than one that resolves 100% and is wrong on a third of them.
Inject a wrong-entity mapping and watch the checker catch it
// harness/checks/linking.test.mjs
test('wrong-entity mapping is caught by the linking checker', () => {
const question = loadQuestion('q-007-ambiguous-parent');
// Fixture expectation: the correct target is demo/entity/benefit-child-care.
const linked = [
{
mentionText: 'child benefit',
entityId: 'demo/entity/benefit-child-disability',
resolution: 'ambiguous',
confidence: 0.81,
ambiguityGroup: 'child-benefit',
},
];
const score = scoreLinking(linked, question);
assert.equal(score.recall, 0);
assert.equal(score.precision, 0);
assert.equal(score.ambiguity.correct, false);
assert.deepEqual(score.denominators, {
goldEntities: 1,
predictedEntities: 1,
mentions: 1,
});
});
Expected fixture output:
$ node --test harness/checks/linking.test.mjs
▶ linking checks
✔ wrong-entity mapping is caught by the linking checker (2.4ms)
✔ unresolved mention is not silently mapped (0.7ms)
✔ alias resolves to canonical entity id (0.5ms)
✔ linking checks (4.1ms)
ℹ tests 3
ℹ pass 3
ℹ fail 0
That output is a fixture expectation about the checker, not an observation about any model. The point of the test is that a future refactor of the linker can't quietly make the checker stop noticing.
Mitigate entity-linking failures before they reach retrieval
- Return
unresolvedinstead of the top candidate when the top two scores sit within a margin you define. - Scope the dictionary by jurisdiction and date before ranking candidates.
- Keep alias entries as data with their own provenance, so a bad alias is revertible.
- Attach the matched surface form and dictionary version to every link for audit.
Measure Graph Completeness Against Required Evidence
Preserve provenance on nodes and edges
{
from: 'demo/entity/benefit-child-care',
type: 'SUBJECT_TO_EXCEPTION',
to: 'demo/entity/exception-seasonal-worker',
provenance: {
docId: 'demo/reg/2024-07',
revisionId: 'r2',
sectionId: 's.3(1)',
span: [412, 612],
},
validFrom: '2024-07-01',
validTo: null,
}
SPAN, REVISION, and the validity interval are what make the graph auditable. They map cleanly onto W3C PROV-O if you need an interchange format: the section is an Entity, the extraction run an Activity, the extractor an Agent. You don't need a triple store to borrow the discipline.
Define completeness relative to annotated questions
Never claim "the graph is complete" — you can't measure that. Claim something narrower: "for the 40 annotated dev questions, the graph contains 37 of 41 required nodes and 29 of 34 required edges." Both numbers have denominators, both are reproducible, and neither overstates what was tested.
Pair coverage with unsupported-edge rate
// harness/checks/graph.mjs
export function scoreGraph(graph, question, corpus) {
const nodeIds = new Set(graph.nodes.map((n) => n.id));
const edgeKeys = new Set(graph.edges.map(edgeKey));
const requiredNodes = question.gold.requiredNodeIds ?? [];
const requiredEdges = question.gold.requiredEdgeKeys ?? [];
const unsupported = graph.edges.filter((edge) => {
const prov = edge.provenance;
if (!prov) return true;
const revision = findRevision(corpus, prov.docId, prov.revisionId);
if (!revision) return true;
const [start, end] = prov.span;
if (start < 0 || end > revision.text.length || start >= end) return true;
// Fixture-only exactness check: the annotated span must be present verbatim.
const expected = revision.sections.find((s) => s.sectionId === prov.sectionId);
if (!expected) return true;
return !revision.text.slice(start, end).includes(expected.anchorText ?? '');
});
return {
requiredNodeCoverage:
requiredNodes.length === 0
? null
: requiredNodes.filter((id) => nodeIds.has(id)).length / requiredNodes.length,
requiredEdgeCoverage:
requiredEdges.length === 0
? null
: requiredEdges.filter((k) => edgeKeys.has(k)).length / requiredEdges.length,
unsupportedEdgeRate:
graph.edges.length === 0 ? null : unsupported.length / graph.edges.length,
denominators: {
requiredNodes: requiredNodes.length,
requiredEdges: requiredEdges.length,
edges: graph.edges.length,
},
unsupportedEdgeKeys: unsupported.map(edgeKey),
};
}
function edgeKey(edge) {
return `${edge.from}->${edge.type}->${edge.to}`;
}
On real corpora the verbatim-anchor check isn't enough; you need a relation-extraction precision pass over a human-labelled sample. On fixtures it's exact, which is the point — the checker is deterministic, so you can trust it before you trust the numbers it produces.
Coverage and unsupported-edge rate have to be reported together. Coverage alone rewards an extractor that invents edges: emit all 34 required edges plus 200 fabricated ones and coverage is 1.0. The pair makes that visible.
Distinguish missing content from a traversal failure
Two isolated fixtures, each with one deliberate defect:
| Fixture | Injection | Checker result | Diagnosis |
|---|---|---|---|
g-missing-edge | delete SUBJECT_TO_EXCEPTION edge | requiredEdgeCoverage drops, unsupportedEdgeRate unchanged | graph construction |
g-traversal-broken | graph intact, hop limit set to 1 | requiredEdgeCoverage unchanged, retrieval recall drops | traversal / hop limit |
g-misleading-edge | add EXEMPTS edge with a span that does not contain the relation cue | unsupportedEdgeRate rises, coverage unchanged | construction precision |
g-stale-revision | edge provenance pinned to r1 while asOf is 2025 | temporal validity check fails | revision selection |
Without the intact-but-shallow fixture, every retrieval miss looks like a construction bug. Without the intact-but-misleading fixture, every construction bug looks like a coverage improvement.
Construction precision, temporal consistency, and exceptions matter as much as depth
Depth is the easiest thing to tune and the least likely to be the problem. The expensive failures in legal-style corpora look like this:
- an exception modelled as prose rather than an edge, so traversal never reaches it;
- an edge valid only until a date, still traversed after that date;
- a definition node that changes the meaning of every term in a section, absent from the graph entirely.
A deeper traversal over a graph missing the exception clause produces more confident wrong answers, not fewer. That's error migration in its purest form.
Compare Graph Retrieval With a Fair Vector-Search Baseline
Feed both retrievers identical inputs
Same corpus revision, same questions, same asOf dates, same access constraints, same evidence-ID format. If the vector baseline sees a different corpus hash, the comparison is worthless.
Specify both configurations completely
| Setting | Graph retriever | Vector retriever |
|---|---|---|
| Seed selection | linked entity IDs, max 4 seeds | query embedding |
| Expand | typed edges, SUBJECT_TO_EXCEPTION, AMENDS | n/a |
| Hop limit | 2 | n/a |
| Rank | path score then span length | cosine similarity |
| Chunking | section-level | 220-token target, 40-token overlap |
| Embedding | pinned ID, 1024 dims | pinned ID, 1024 dims (identical) |
| Top-k | 12 evidence units | 12 evidence units or reranked |
| Stopping rule | token budget, not count | token budget, not count |
Normalize both outputs into one evidence format
This is the most important implementation decision in the whole comparison. Both retrievers must emit Evidence objects with evidenceId derived from docId@revisionId#sectionId. A graph path that touches s.14(2) and a vector chunk that overlaps s.14(2) have to produce the same identifier, or you end up comparing two vocabularies instead of two retrievers.
// harness/normalize.mjs
export function toEvidenceId({ docId, revisionId, sectionId }) {
return `${docId}@${revisionId}#${sectionId}`;
}
export function equalizeByTokens(evidence, budgetTokens) {
const sorted = [...evidence].sort((a, b) => b.score - a.score);
const kept = [];
let used = 0;
for (const unit of sorted) {
if (used + unit.tokens > budgetTokens) continue;
kept.push(unit);
used += unit.tokens;
}
return kept;
}
Equal top-k is not equal opportunity. A graph hop can return three adjacent sections that are individually low-scoring but collectively decisive; a vector search returns twelve independent chunks. Cutting both at top-k = 12 hands one side a token advantage for no principled reason. Equalize on tokens.
Report online latency separately from build cost
Graph construction and embedding are batch costs. Traversal and context assembly are online costs. Blending them into one "cost per query" figure hides the fact that graph construction is usually the larger absolute spend and the online path is usually faster. Report:
- build: documents processed, extraction calls, wall-clock, spend;
- online: p50/p95 retrieval latency, context tokens, generator tokens;
- and tune both retrievers on dev questions only.
Measure Evidence Coverage at Retrieval and Context Assembly
Compute recall and complete-set success
// harness/checks/coverage.mjs
export function scoreEvidenceCoverage(evidence, question) {
const present = new Set(evidence.map((e) => e.evidenceId));
const sets = question.gold.requiredEvidenceSets;
let best = null;
for (const set of sets) {
const hit = set.filter((id) => present.has(id));
const ratio = set.length === 0 ? null : hit.length / set.length;
if (best === null || ratio > best.ratio) {
best = { set, hit, ratio, missing: set.filter((id) => !present.has(id)) };
}
}
return {
requiredEvidenceRecall: best?.ratio ?? null,
completeEvidenceSetSuccess: best?.ratio === 1,
missingFromBestSet: best?.missing ?? [],
denominators: {
requiredEvidenceSets: sets.length,
idsPerSet: sets.map((s) => s.length),
},
};
}
Macro-average across questions, not micro-average across IDs. Micro-averaging lets questions with five required IDs dominate questions with one, and the one-ID questions are usually the abstention cases where a failure hurts most.
Why relevance is not the same as sufficiency
Take q-014-exception. Retrieval returns demo/stat/2021-11@r1#s.14(2) with a high score — the entitlement rule, clearly relevant, obviously about child care benefit. demo/reg/2024-07@r2#s.3(1), the exception, is not retrieved. Required-evidence recall is 0.5. Complete-set success is false. A generator reading only the first section produces a confident, well-cited, wrong answer: full-year entitlement.
A "relevance" metric misses this case entirely, because the retrieved passage really is relevant. It's just not sufficient.
Compare pre-assembly retrieval with the actual context
Three things can go wrong between retrieval and generation: budget truncation, deduplication that collapses two distinct sections sharing boilerplate, and serialization that drops the validity dates the prompt needed.
// harness/checks/context.mjs
export function checkContext(retrieved, context, question) {
const contextIds = new Set(context.map((e) => e.evidenceId));
const dropped = retrieved.filter((e) => !contextIds.has(e.evidenceId));
const droppedCritical = dropped.filter((e) =>
question.gold.criticalEvidenceIds.includes(e.evidenceId),
);
return {
retrievedUnits: retrieved.length,
contextUnits: context.length,
contextTokens: context.reduce((n, e) => n + e.tokens, 0),
dropped: dropped.map((e) => e.evidenceId),
droppedCritical: droppedCritical.map((e) => e.evidenceId),
verdict: droppedCritical.length > 0 ? 'CONTEXT_LOSS' : 'OK',
};
}
Deterministic fixture: retrieval returns both required sections, the assembly budget is 700 tokens, the exception section is 410 tokens and the entitlement section is 300. Priority ordering by retrieval score keeps the entitlement section and drops the exception.
Expected fixture output:
{
"retrievedUnits": 2,
"contextUnits": 1,
"contextTokens": 300,
"dropped": ["demo/reg/2024-07@r2#s.3(1)"],
"droppedCritical": ["demo/reg/2024-07@r2#s.3(1)"],
"verdict": "CONTEXT_LOSS"
}
The mitigation is not "raise the budget". It's: mark criticalEvidenceIds-class evidence as non-droppable, rank by sufficiency rather than score, and force abstention when the budget genuinely cannot hold a critical unit. Dropping an exception and answering anyway is the worst available option.
Evaluate Citation Support Separately From Answer Correctness
Require structured claims with validated identifiers
The generator returns claims, each with zero or more citations shaped {docId, revisionId, sectionId, span}. The checker resolves each against the corpus. Two guardrails:
- Retrieved text is treated as data. It never becomes an instruction. In a legal corpus, retrieved text is adversarial by default — statute text can contain phrases that read like directives, and a document from an untrusted source can contain anything. Wrap evidence in explicit delimiters, state in the prompt that context is quoted material, and validate every emitted citation against the corpus rather than trusting the model's rendering of it.
- A citation must resolve to a section that was actually in the context. A citation to a real section the model never saw is either memorization or a leak, and it has to be flagged, not rewarded.
Four separate citation checks
| Check | Question | Deterministic on fixtures? |
|---|---|---|
| Citation existence | Does the doc/section/revision exist? | Yes |
| Span validity | Is the span inside the section and does the quoted fragment appear there? | Yes |
| Claim-level entailment | Does the cited text support the claim? | Yes with labelled fixtures; needs review or a versioned judge in production |
| Citation coverage | What share of material claims carry at least one supporting citation? | Yes |
A valid identifier is not proof of support. Splitting these four is the whole point.
// harness/checks/citations.mjs
export function checkCitations(answer, contextIds, corpus) {
const issues = [];
const claimsWithSupport = new Set();
for (const claim of answer.claims) {
if (claim.citations.length === 0) {
issues.push({ claimId: claim.claimId, type: 'NO_CITATION' });
continue;
}
for (const citation of claim.citations) {
const evidenceId = toEvidenceId(citation);
if (!contextIds.has(evidenceId)) {
issues.push({ claimId: claim.claimId, type: 'NOT_IN_CONTEXT', evidenceId });
}
const revision = findRevision(corpus, citation.docId, citation.revisionId);
if (!revision) {
issues.push({ claimId: claim.claimId, type: 'UNKNOWN_REVISION', evidenceId });
continue;
}
const section = revision.sections.find((s) => s.sectionId === citation.sectionId);
if (!section) {
issues.push({ claimId: claim.claimId, type: 'UNKNOWN_SECTION', evidenceId });
continue;
}
const [start, end] = citation.span;
if (start < section.span[0] || end > section.span[1] || start >= end) {
issues.push({ claimId: claim.claimId, type: 'SPAN_OUT_OF_SECTION', evidenceId });
continue;
}
if (citation.quotedFragment && !revision.text.slice(start, end).includes(citation.quotedFragment)) {
issues.push({ claimId: claim.claimId, type: 'SPAN_TEXT_MISMATCH', evidenceId });
continue;
}
claimsWithSupport.add(claim.claimId);
}
}
const distinctClaims = new Set(answer.claims.map((c) => c.claimId));
return {
citationCoverage:
distinctClaims.size === 0 ? null : claimsWithSupport.size / distinctClaims.size,
issues,
verdict: issues.length === 0 ? 'PASS' : 'FAIL',
};
}
Score answer facts independently of citation formatting
Four separate outcomes, no combining until the report:
- expected facts present and correct;
- material omissions (a required fact absent);
- contradictions (a claim whose value conflicts with the gold value);
- justified abstention (abstained on an
abstain: truequestion).
A confident wrong answer and a well-cited wrong answer are the same failure with different cosmetics.
Deterministic where possible, semantic where required
Fixture IDs and exact fact values are exact-match checks. Entailment isn't, and pretending otherwise is how harnesses rot. If you use a model-based judge:
- pin its model ID and prompt version;
- calibrate it against a human-reviewed sample of at least 30–40 examples;
- report agreement rate alongside every judge-derived number;
- if agreement lands around 0.7 on a 40-example sample, the judge cannot resolve a 5-point difference between two systems. Don't let it try.
Three labelled synthetic answers
These are fixture labels written by hand to exercise the checkers — not observations of any model:
[
{
"label": "unsupported-but-correct",
"goldFacts": [{ "key": "entitlement", "value": "partial-year" }],
"answer": { "claims": [{ "claimId": "c1", "text": "Partial year.", "citations": [] }], "abstained": false },
"expected": { "answerFactsCorrect": true, "citationCoverage": 0, "verdict": "UNSUPPORTED" }
},
{
"label": "supported-but-incomplete",
"goldFacts": [
{ "key": "entitlement", "value": "partial-year" },
{ "key": "reason", "value": "seasonal-worker exception" }
],
"answer": { "claims": [{ "claimId": "c1", "text": "Partial year.", "citations": ["demo/reg/2024-07@r2#s.3(1)"] }], "abstained": false },
"expected": { "answerFactsCorrect": false, "materialOmissions": ["reason"], "verdict": "INCOMPLETE" }
},
{
"label": "confidently-wrong",
"goldFacts": [{ "key": "entitlement", "value": "partial-year" }],
"answer": { "claims": [{ "claimId": "c1", "text": "Full year.", "citations": ["demo/stat/2021-11@r1#s.14(2)"] }], "abstained": false },
"expected": { "answerFactsCorrect": false, "contradictions": ["entitlement"], "citationCoverage": 1, "verdict": "WRONG_BUT_CITED" }
}
]
Keep the third row in the test suite forever. Perfect citation coverage of 1.0, completely wrong.
Use Controlled Interventions to Localize Failures
Run four controlled interventions against the same answer contract
| Run | Entity linking | Graph | Context | Isolates |
|---|---|---|---|---|
normal | real | real | real | the system as shipped |
gold-evidence | real | real | gold spans injected | generator + prompt + parser |
gold-entity | gold entity IDs | real | real | linking vs. everything downstream |
repaired-graph | real | missing edge restored | real | construction vs. traversal |
All four use the same prompt version, the same decoding settings, the same citation schema. If gold-evidence uses a tidier context format than normal, you've introduced a confound and you'll chase a retrieval bug that's actually a formatting bug.
Preserve multiple labels and an earliest blocker
// harness/checks/outcomes.mjs
export const BLOCKER_ORDER = [
'link',
'graph',
'retrieval',
'context',
'generation',
'parser',
'rubric',
];
export function earliestBlocker(labels) {
const ranked = labels
.map((label) => BLOCKER_ORDER.indexOf(label))
.filter((index) => index >= 0)
.sort((a, b) => a - b);
return ranked.length === 0 ? null : BLOCKER_ORDER[ranked[0]];
}
q-014-exception in the trace above gets labels: ["context", "generation"] and earliestBlocker: "context". Both are true: the context was incomplete, and the generator failed to notice it was working from an incomplete rule set. Forcing that into one causal bucket loses the fact that fixing either one alone still leaves a defect.
The limit of oracle tests
Passing with gold evidence supports a retrieval-side diagnosis. It doesn't prove one, because gold context may be easier to read than real context. Failing with gold evidence is stronger information: it rules out retrieval and points at the prompt, the answer schema, the parser, or the scoring rubric — including the possibility that the rubric is wrong and the system is right.
I've had exactly that. A "contradiction" label that turned out to be the gold value being wrong about which revision was in force on the asOf date. The harness was correct; the answer key wasn't.
Turn Failure Hypotheses Into Executable Regression Tests
Fault-injection matrix for each stage
| Fault | Injection point | Expected failing check | Expected label |
|---|---|---|---|
| Ambiguous linking | linker returns top candidate | scoreLinking.ambiguity.correct === false | link |
| Missing edge | graph build drops SUBJECT_TO_EXCEPTION | requiredEdgeCoverage below 1 | graph |
| Unsupported edge | graph build adds edge with invalid span | unsupportedEdgeRate > 0 | graph |
| Shallow traversal | hop limit 1 | requiredEvidenceRecall drops | retrieval |
| Stale revision | edges pinned to r1 at asOf: 2025-09-15 | temporal validity check | graph |
| Context truncation | budget 700, critical unit 410 | checkContext.verdict === 'CONTEXT_LOSS' | context |
| Invalid citation | span outside section | SPAN_OUT_OF_SECTION | parser |
| Unretrieved citation | citation to a section never in context | NOT_IN_CONTEXT | generation |
| Contradictory answer | claim value conflicts with gold | contradictions non-empty | generation |
Assert checker behaviour with a deterministic stub before spending tokens
// harness/checks/citations.test.mjs
test('citation to a real section that was never in context is flagged', () => {
const question = loadQuestion('q-021-two-hop');
const contextIds = new Set(['demo/stat/2021-11@r1#s.14(2)']);
const answer = {
claims: [
{
claimId: 'c1',
text: 'The exception applies from 2024-07-01.',
citations: [
{ docId: 'demo/reg/2024-07', revisionId: 'r2', sectionId: 's.3(1)', span: [430, 590] },
],
},
],
abstained: false,
};
const result = checkCitations(answer, contextIds, loadCorpus());
assert.equal(result.verdict, 'FAIL');
assert.deepEqual(
result.issues.map((i) => i.type),
['NOT_IN_CONTEXT'],
);
assert.equal(result.citationCoverage, 0);
});
node --test harness/checks/
Expected fixture output:
▶ citation checks
✔ citation to a real section that was never in context is flagged (1.9ms)
✔ span outside section bounds fails SPAN_OUT_OF_SECTION (0.6ms)
✔ quoted fragment mismatch fails SPAN_TEXT_MISMATCH (0.5ms)
✔ citation checks (3.6ms)
▶ coverage checks
✔ complete evidence set requires every required id (0.9ms)
✔ context loss is reported when a critical unit is dropped (0.8ms)
✔ coverage checks (2.1ms)
ℹ tests 5
ℹ pass 5
ℹ fail 0
These are assertions about checkers. They should run with no network access and no credentials.
Scope, credentials, and trace hygiene
- All fixtures local and synthetic. No real legal text, no client documents.
- Credentials from environment variables only, never in fixtures or traces.
- Shared traces store evidence IDs and short excerpts, not full source text. A trace file is the easiest way to leak a document you were allowed to process but not to share.
- Fault injection stays inside the test harness. No injected faults against a live corpus.
Report Whether Errors Improved, Moved, or Became Harder to See
Paired tables
Every table is graph-versus-vector on the same questions, with per-question denominators:
| Metric | Vector baseline | Graph | Paired delta |
|---|---|---|---|
| Required-evidence recall (mean, n questions) | <computed> | <computed> | <computed> |
| Complete-evidence-set success | <computed> | <computed> | <computed> |
| Citation coverage | <computed> | <computed> | <computed> |
| Answer facts correct | <computed> | <computed> | <computed> |
| Justified abstention rate | <computed> | <computed> | <computed> |
| p95 online retrieval latency (ms) | <computed> | <computed> | <computed> |
| Online cost per question | <computed> | <computed> | <computed> |
Everything in <computed> comes from the harness. Nothing in this post is a measured result from any system.
Per-question transition table exposes error migration
Aggregate deltas hide migration. The transition table exposes it:
| Cell | Meaning | Count |
|---|---|---|
fail → pass | graph fixed a baseline failure | <computed> |
pass → pass | both succeeded | <computed> |
fail → fail | both failed | <computed> |
pass → fail | graph introduced a failure | <computed> |
The fourth row deserves reading question by question. Typical contents: temporal questions where the vector baseline retrieved the current revision by lexical accident and the graph traversed a stale edge; exception questions where the graph found the base rule with high confidence and stopped at the hop limit.
Conditional generator performance
Report two numbers, not one:
- full-dataset accuracy over all 40 questions;
- generator accuracy conditional on evidence sufficiency — only on questions where
completeEvidenceSetSuccesswas true.
Illustrative arithmetic, not a measurement: if evidence sufficiency is 60% and the generator gets 90% of sufficient cases right, full-dataset accuracy is 54%. That figure understates the generator badly and overstates how much a smarter model would help. It also hides the real lever, which is retrieval coverage. Conditional reporting makes the denominator visible; full-dataset reporting alone lets a strong generator flatter a weak retriever.
Reporting discipline for small samples
Every live-model result states: task, inputs, success criterion, question count, exact model ID, repeat count. For paired binary outcomes on small samples, use a paired test with an exact variant — with n = 40 paired questions, McNemar's exact test is appropriate and a naive chi-square approximation isn't. Report the interval, and put the sample-size limitation next to the number rather than in a footnote nobody reads.
Keep schemas separate from results
The tables above are report schemas. They contain no measurements, and no measurement from the two supplied reports appears anywhere in this post, because the supplied snippets don't contain one.
Turn Diagnostics Into Targeted Mitigations and Release Gates
Map each failed check to an intervention
| Failed check | Intervention |
|---|---|
ambiguity.correct === false | add disambiguation context, raise the unresolved margin, scope the dictionary |
requiredNodeCoverage low | extend extraction to definition and exception sections |
requiredEdgeCoverage low | graph repair pass over sections whose spans mention relations |
unsupportedEdgeRate > 0 | provenance validation gate: reject edges without a resolvable span |
| Temporal validity failure | filter edges by asOf before traversal |
requiredEvidenceRecall low, graph intact | raise hop limit, adjust seed selection or edge filter |
CONTEXT_LOSS | mark critical evidence non-droppable; force abstention when it does not fit |
NO_CITATION / NOT_IN_CONTEXT | tighten the answer schema; verify prompt delimiters around evidence |
contradictions non-empty | claim verification pass, or abstain when claims conflict with gold-adjacent spans |
Release thresholds are application-specific
There's no universal accuracy cutoff, and a post that hands you one is selling something. Define gates per application, on held-out questions, with a non-regression clause on the upstream metrics:
Gate (held-out, graph retriever, pinned manifest):
complete-evidence-set success >= baseline
unsupported-edge rate <= declared ceiling
citationCoverage >= baseline
justified-abstention rate >= baseline on abstain questions
answer facts correct >= baseline
p95 online retrieval latency <= declared budget
The non-regression clause is the part people drop. A new extraction pass can raise final-answer accuracy by adding edges while raising unsupportedEdgeRate; that trade stays invisible unless the gate watches both.
Keep traces and fixture versions together
A trace without a fixture version is unreproducible. Store corpusVersion, corpusHash, promptVersion, and the manifest with the run. When the final-answer score improves, diff the upstream metrics against the previous release. An improvement in final answers combined with a new CONTEXT_LOSS class or a higher unsupportedEdgeRate isn't an improvement; it's a defect that hasn't produced a visible wrong answer yet.
Conclusion — Graph Structure Does Not Replace Evidence Accounting
Two claims, two measurements
The hook in both supplied reports is attractive: fewer hallucinations, and a traceable graph of statutes. Separate claims, separate measurements. A graph can be fully traceable and still incomplete for the question being asked. A system can reduce hallucinations on average while shifting failures into a category the metric doesn't see — cited-but-unsupported answers, or answers that are right for the wrong reason.
The supplied snippets don't establish that the two reports describe the same work, which models were evaluated, how large the corpora were, or how much hallucination reduction occurred. Those are open questions, not details to be assumed.
A decision rule for adopting graph retrieval
Adopt graph retrieval when paired tests show better-supported answers under declared latency and cost budgets — meaning required-evidence recall and complete-set success improved, citation support did not degrade, and the pass → fail cell of the transition table is understood question by question. Keep the harness afterwards. Error migration doesn't stop at adoption; it's the thing you're buying, and the only way to find out where the errors went next is to keep measuring each stage, on the same fixtures, with the same pinned manifest.
Further Reading and Source Verification
Supplied secondary reporting (relationship unverified):
- Knowledge Graph Retrieval Cuts Legal AI Hallucinations While Shifting Error Sources, Bioengineer.org, 2026-12-02. Supplied as a one-line snippet via a Google News RSS redirect; the publisher's canonical URL could not be verified from the supplied material, so it is not linked here.
- LegalGraph maps Kazakhstan statutes into traceable graphs for accountable LLM reasoning, Bioengineer.org, 2026-12-02. Same caveat. The snippet does not describe LegalGraph's schema, entity-linking method, or evaluation protocol, so none of those details appear in this post.
Treat both as secondary reporting. No underlying paper, dataset, or repository is linked here because their identities could not be verified from the provided snippets, and inventing a reference is worse than leaving the gap visible.
Primary technical references used in this walkthrough:
- Node.js test runner documentation —
node:test, the runner used for the deterministic checker tests. - W3C PROV-O — the provenance model the node and edge metadata follows if you need an interchange format.
More posts

Testing AMD GAIA 0.27’s C++ Overhead Claims with a Reproducible Agent Benchmark
A reproducible benchmark methodology for separating agent orchestration overhead from model inference in AMD GAIA 0.27, covering startup time, memory usage, tool-call latency, and end-to-end task completion.
Auditing HPE's Reported AI Controls: Token Tracking Is Not an AI Budget
A deep technical audit of HPE's reported AI controls and token tracking, examining why usage observability is not the same as budget enforcement and what platform teams should verify before adopting it.
Loading comments…