Review the prerequisites
Suitable for: Developers who can compare a request, a trace and an authoritative result.
- Retrieval
- Finding potentially relevant candidates in the knowledge base. This does not establish that they reach the final model input.
- Reranking
- Reordering candidates by priority, which determines which material is placed first in limited context.
- Necessary evidence
- The set of material sufficient to support the answer to this question; it may require both the main text and exception clauses.
- Evidence support
- Whether the actual source material and its applicability conditions support a conclusion. A citation link alone may provide no support.
How does the mechanism work?
- 1Corpus
Attach tenant, group, version and valid interval to base and exception clauses.
- 2Trusted query context
Filter applicable authorized IDs before rank fusion.
- 3Ranking
Fuse two authored rank lists; retain stage IDs.
- 4Assembly
Expand authorized same-version clauses and preserve the complete bundle or abstain.
- 5Verifier
Check context membership and bounded claim conditions; arbitrary prose remains not_scored.
This deep-dive uses authored rankings. The linked existing RAG pipeline retains its separately recorded real local embedding provenance.
Step-by-step explanation
- Verify source material
Verify that the original material exists, is valid, and is authorized for use.
- Retrieve and rank
Record candidate IDs and rankings.
- Assemble context
Retain the necessary material, conditions, and source IDs.
- Generate and verify
Check that each conclusion and decision to abstain matches the evidence.
Debugging · Diagnose failures
Locate a lost exception before changing retrieval
Objectives of this level: Use one fixed input and stage IDs to diagnose assembly loss, then rerun with the repaired context.
Visual guide · Preserve the rule and its exception
Citation membership only proves an ID reached context. A claim still needs applicable, complete evidence and a check for contradiction. Select the figure to open it at full size.
Reproduce assemble(include_exception=False). The current exception exists in eligible_ids and fused_ids but does not appear in assembled_ids. A candidate says eligible=True and cites the base. verify_claims returns missing_required_evidence. The earliest loss is context assembly after seed selection, not corpus ingestion or initial retrieval.
Inspect stages in order using fixed tenant, group, effective time and index fixture. If the original clause is absent, investigate ingestion or version filtering. If it is eligible but absent from candidates, investigate query/ranking input. If candidates contain it but selection drops it, investigate selection or reranking. If selection has it but actual context does not, investigate expansion, serialization, truncation or compression. If the complete context is present yet the claim is wrong, investigate generation and the verifier's rule coverage.
The repair expands authorized same-version clauses before the budget check. Rerun with include_exception=True: the base and exception enter context and eligibility=False passes. Sending eligibility=True with both citation IDs returns claim_contradicted, proving that merely adding IDs is not the repair.
Repeat budget=100 and groups=(). They must abstain with no assembled evidence; silently stripping the exception or falling back to a global corpus would reintroduce the error. Save the complete input/context/verdict trace from the JSON module and run RagTests. These traces are actual local outputs of authored data, not recorded model reasoning.
A complete worked run
from rag_evidence_deep_dive import assemble, candidate, verify_claims
bad = assemble(include_exception=False)
assert 'returns-v2-exception' in bad['fused_ids']
assert 'returns-v2-exception' not in bad['assembled_ids']
assert verify_claims(candidate(True, ['returns-v2-base']), bad)['reason'] == 'missing_required_evidence'
fixed = assemble()
assert verify_claims(candidate(), fixed)['accepted']
print(verify_claims(candidate(True), fixed)['reason'])
Actual output: claim_contradicted. Full evidence exposes the incorrect claim instead of letting citation presence bless it.
The exact first-loss comparison
Start with one fixed tenant-a/retail/at150 case and the unchanged authored index. The broken trace contains the exception in eligible_ids and fused_ids but not assembled_ids; the wrong candidate cites only the base and gets missing_required_evidence. After repair, both clauses are in the exact context, candidate(False) is accepted and candidate(True) gets claim_contradicted. The code above executes those comparisons; correcting citation IDs alone does not change the claim's truth.
For a code repair exercise copy rag_evidence_deep_dive.py to rag_evidence_learner.py and, in the copy, omit the same-policy/same-version neighbor expansion. Confirm that the same query loses the exception even when include_exception=True. Restore authorization-preserving expansion and rerun both candidate values plus budget100 and groups=(). Save the source diff and before/after stage IDs. Reference RagTests exercise the finished reference; they do not validate the learner copy automatically.
For the injected-fault script import from the learner copy explicitly: from rag_evidence_learner import assemble, candidate, verify_claims. The worked reference script above imports the original module and remains unchanged. Use a fresh instance for both before/after runs so an earlier effect cannot contaminate the comparison.
Run experiments and observe counterexamples
Authored corpus, rank lists, case facts and candidate claims; real filtering/assembly/rule checks. No embeddings, model generation, arbitrary prose entailment or live ACL service.
Python 3.10+ · Runs by default using only the standard library · Runs on your computer
- Compare failure and repair stage IDs and exact context.
- Test budget and empty permission-set failures.
- Run RagTests and distinguish citation membership from rule support.
python3 -B rag_evidence_deep_dive.pyView the entry-point script
"""Bounded RAG experiment: authored rankings and claims, real local checks.
The score fixtures are not embeddings. The claim verifier is a narrow rule
checker, not an entailment model or an evaluation of free-form prose.
"""
import json
from dataclasses import dataclass
@dataclass(frozen=True)
class Chunk:
id: str
tenant: str
group: str
version: int
valid_from: int
valid_to: int
policy: str
text: str
CORPUS = (
Chunk('returns-v1-base', 'tenant-a', 'retail', 1, 0, 100, 'returns', 'Old policy: unused products may be returned within 60 days.'),
Chunk('returns-v2-base', 'tenant-a', 'retail', 2, 100, 300, 'returns', 'Current policy: unused products may be returned within 30 days. Product exceptions apply.'),
Chunk('returns-v2-exception', 'tenant-a', 'retail', 2, 100, 300, 'returns', 'Opened batteries cannot be returned unless defective, even within 30 days.'),
Chunk('returns-v3-base', 'tenant-a', 'retail', 3, 300, 999, 'returns', 'Future policy: unused products may be returned within 45 days.'),
Chunk('tenant-b-base', 'tenant-b', 'retail', 2, 100, 300, 'returns', 'A different tenant accepts returns within 90 days.'),
)
INDEX = {chunk.id: chunk for chunk in CORPUS}
AUTHORED_VECTOR_ORDER = ['tenant-b-base', 'returns-v1-base', 'returns-v2-base', 'returns-v3-base', 'returns-v2-exception']
AUTHORED_LEXICAL_ORDER = ['returns-v2-base', 'returns-v2-exception', 'tenant-b-base', 'returns-v1-base', 'returns-v3-base']
FACTS = {'product': 'battery', 'opened': True, 'defective': False, 'age_days': 20}
def eligible(chunk, tenant, groups, at):
return chunk.tenant == tenant and chunk.group in groups and chunk.valid_from <= at < chunk.valid_to
def rrf(rankings, k=60):
scores = {}
for ranking in rankings:
if len(ranking) != len(set(ranking)):
raise ValueError('duplicate_rank_id')
for rank, item_id in enumerate(ranking, 1):
scores[item_id] = scores.get(item_id, 0) + 1 / (k + rank)
return [i for i, _ in sorted(scores.items(), key=lambda pair: (-pair[1], pair[0]))]
def assemble(tenant='tenant-a', groups=('retail',), at=150, budget=300, include_exception=True):
allowed = {c.id for c in CORPUS if eligible(c, tenant, groups, at)}
rankings = [[i for i in ranking if i in allowed] for ranking in (AUTHORED_VECTOR_ORDER, AUTHORED_LEXICAL_ORDER)]
fused = rrf(rankings)
selected = fused[:1]
expanded = list(selected)
if selected and include_exception:
seed = INDEX[selected[0]]
# Expansion repeats the authorization/time checks. Do not fetch a raw parent by ID.
for c in CORPUS:
if c.id in allowed and c.policy == seed.policy and c.version == seed.version and c.id not in expanded:
expanded.append(c.id)
chars = sum(len(INDEX[i].text) for i in expanded)
# Preserve the complete bundle or abstain. Never silently truncate the exception.
assembled = expanded if chars <= budget else []
return {'query': 'opened battery return at 20 days', 'tenant': tenant, 'at': at,
'eligible_ids': sorted(allowed), 'rankings': rankings, 'fused_ids': fused,
'selected_ids': selected, 'expanded_ids': expanded, 'required_chars': chars,
'budget_chars': budget, 'assembled_ids': assembled,
'assembly_status': 'budget_exceeded' if expanded and not assembled else ('assembled' if assembled else 'no_evidence'),
'context': [{'id': i, 'version': INDEX[i].version, 'text': INDEX[i].text} for i in assembled]}
def verify_claims(answer, trace, facts=FACTS):
if type(answer) is not dict or set(answer) != {'claims'} or type(answer['claims']) is not list or not answer['claims']:
return {'accepted': False, 'reason': 'answer_shape'}
assembled = set(trace['assembled_ids'])
if not assembled:
return {'accepted': False, 'reason': 'no_assembled_evidence'}
for claim in answer['claims']:
if type(claim) is not dict or set(claim) != {'field', 'value', 'citations'}:
return {'accepted': False, 'reason': 'claim_shape'}
citations = claim['citations']
if type(citations) is not list or not citations or any(type(i) is not str or i not in assembled for i in citations):
return {'accepted': False, 'reason': 'citation_not_in_context'}
if claim['field'] == 'eligible':
required = {'returns-v2-base'}
if facts['product'] == 'battery' and facts['opened']:
required.add('returns-v2-exception')
if not required.issubset(citations):
return {'accepted': False, 'reason': 'missing_required_evidence'}
expected = facts['age_days'] <= 30 and (not facts['opened'] or facts['defective'])
if type(claim['value']) is not bool or claim['value'] != expected:
return {'accepted': False, 'reason': 'claim_contradicted'}
elif claim['field'] == 'window_days':
if 'returns-v2-base' not in citations or type(claim['value']) is not int or claim['value'] != 30:
return {'accepted': False, 'reason': 'claim_contradicted'}
else:
return {'accepted': False, 'reason': 'unsupported_claim_field'}
return {'accepted': True, 'reason': 'bounded_rules_supported', 'semantic_prose': 'not_scored'}
def candidate(value=False, citations=None):
return {'claims': [{'field': 'eligible', 'value': value,
'citations': citations if citations is not None else ['returns-v2-base', 'returns-v2-exception']}]}
def demo():
broken = assemble(include_exception=False)
fixed = assemble()
short = assemble(budget=100)
denied = assemble(groups=())
return {'origin': 'authored_rankings_claims_local_rules',
'failure': {'trace': broken, 'candidate': candidate(True, ['returns-v2-base']),
'verdict': verify_claims(candidate(True, ['returns-v2-base']), broken)},
'repair': {'trace': fixed, 'candidate': candidate(), 'verdict': verify_claims(candidate(), fixed)},
'present_citation_wrong_claim': verify_claims(candidate(True), fixed),
'budget_failure': {'trace': short, 'verdict': verify_claims(candidate(), short)},
'permission_failure': {'trace': denied, 'verdict': verify_claims(candidate(), denied)},
'boundary': 'No embedding inference, model generation, arbitrary prose entailment, or live ACL update is tested.'}
if __name__ == '__main__':
print(json.dumps(demo(), indent=2, sort_keys=True))
Expected output when running locally
{
"boundary": "No embedding inference, model generation, arbitrary prose entailment, or live ACL update is tested.",
"budget_failure": {
"trace": {
"assembled_ids": [],
"assembly_status": "budget_exceeded",
"at": 150,
"budget_chars": 100,
"context": [],
"eligible_ids": [
"returns-v2-base",
"returns-v2-exception"
],
"expanded_ids": [
"returns-v2-base",
"returns-v2-exception"
],
"fused_ids": [
"returns-v2-base",
"returns-v2-exception"
],
"query": "opened battery return at 20 days",
"rankings": [
[
"returns-v2-base",
"returns-v2-exception"
],
[
"returns-v2-base",
"returns-v2-exception"
]
],
"required_chars": 163,
"selected_ids": [
"returns-v2-base"
],
"tenant": "tenant-a"
},
"verdict": {
"accepted": false,
"reason": "no_assembled_evidence"
}
},
"failure": {
"candidate": {
"claims": [
{
"citations": [
"returns-v2-base"
],
"field": "eligible",
"value": true
}
]
},
"trace": {
"assembled_ids": [
"returns-v2-base"
],
"assembly_status": "assembled",
"at": 150,
"budget_chars": 300,
"context": [
{
"id": "returns-v2-base",
"text": "Current policy: unused products may be returned within 30 days. Product exceptions apply.",
"version": 2
}
],
"eligible_ids": [
"returns-v2-base",
"returns-v2-exception"
],
"expanded_ids": [
"returns-v2-base"
],
"fused_ids": [
"returns-v2-base",
"returns-v2-exception"
],
"query": "opened battery return at 20 days",
"rankings": [
[
"returns-v2-base",
"returns-v2-exception"
],
[
"returns-v2-base",
"returns-v2-exception"
]
],
"required_chars": 89,
"selected_ids": [
"returns-v2-base"
],
"tenant": "tenant-a"
},
"verdict": {
"accepted": false,
"reason": "missing_required_evidence"
}
},
"origin": "authored_rankings_claims_local_rules",
"permission_failure": {
"trace": {
"assembled_ids": [],
"assembly_status": "no_evidence",
"at": 150,
"budget_chars": 300,
"context": [],
"eligible_ids": [],
"expanded_ids": [],
"fused_ids": [],
"query": "opened battery return at 20 days",
"rankings": [
[],
[]
],
"required_chars": 0,
"selected_ids": [],
"tenant": "tenant-a"
},
"verdict": {
"accepted": false,
"reason": "no_assembled_evidence"
}
},
"present_citation_wrong_claim": {
"accepted": false,
"reason": "claim_contradicted"
},
"repair": {
"candidate": {
"claims": [
{
"citations": [
"returns-v2-base",
"returns-v2-exception"
],
"field": "eligible",
"value": false
}
]
},
"trace": {
"assembled_ids": [
"returns-v2-base",
"returns-v2-exception"
],
"assembly_status": "assembled",
"at": 150,
"budget_chars": 300,
"context": [
{
"id": "returns-v2-base",
"text": "Current policy: unused products may be returned within 30 days. Product exceptions apply.",
"version": 2
},
{
"id": "returns-v2-exception",
"text": "Opened batteries cannot be returned unless defective, even within 30 days.",
"version": 2
}
],
"eligible_ids": [
"returns-v2-base",
"returns-v2-exception"
],
"expanded_ids": [
"returns-v2-base",
"returns-v2-exception"
],
"fused_ids": [
"returns-v2-base",
"returns-v2-exception"
],
"query": "opened battery return at 20 days",
"rankings": [
[
"returns-v2-base",
"returns-v2-exception"
],
[
"returns-v2-base",
"returns-v2-exception"
]
],
"required_chars": 163,
"selected_ids": [
"returns-v2-base"
],
"tenant": "tenant-a"
},
"verdict": {
"accepted": true,
"reason": "bounded_rules_supported",
"semantic_prose": "not_scored"
}
}
}- Missing exception returns missing_required_evidence.
- Full bundle plus eligibility=False passes; True returns claim_contradicted.
- Insufficient budget and denied scope produce no assembled evidence.
code example
The ID survives but its condition disappears
Consider a compressor that retains the returns-v2-exception ID but drops unless defective from its serialized text. An ID-only trace would miss the fault. Compare the exact span and test opened/non-defective versus opened/defective cases; they must preserve their opposite eligibility outcomes.
Acceptance task for this level
Using the fixed scope/time/index, diagnose missing exception, budget100 and cited-wrong-claim. In rag_evidence_learner.py inject and repair missing authorized neighbor expansion; save the source diff, before/after stage IDs and verdicts, then rerun reference RagTests.
Reading this browser’s record…
Hide the answer and check your understanding
Increasing top-k includes the exception in candidates, but the generated answer still ignores it. What must you inspect before increasing top-k again?
Expand reference derivation
Inspect the exact serialized model context and claim conditions. The exception may still be dropped during assembly or compression; if it is present in full, retrieval is no longer the earliest failure. Inspect generation and support checking.
Further explanations and practice
When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.
All linked explanations and exercises (4 )
Sources and verification scope
The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.