Review the prerequisites
Suitable for: Developers comfortable with Python dictionaries and local SQL transactions.
- 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.
Implementation · Build it
Build an inspectable evidence pipeline and a narrow verifier
Objectives of this level: Run applicability filtering, rank fusion, exception-preserving assembly and deterministic claim checks.
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.
Download the core experiment bundle on a computer and extract the agent-core-deep-dive-v1 folder. Install Python 3.9+ with its standard library, open a terminal in that folder and run:
python3 -B rag_evidence_deep_dive.py > rag_evidence_deep_dive.results.json
python3 -B -m unittest discover -v
Open the saved JSON and compare its statuses/counts with the worked example in this body. The implementation and debugging snippets run from the same extracted folder; the bundle includes every imported module. Save the body’s Python snippet as a .py file in that folder and run python3 -B your_file.py; its printed output is stated beside it. The source can also be downloaded at https://ai.lwkjob.com/lab/deep-dive/rag_evidence_deep_dive.py. The engineering route continues the same complete after-sales Agent project; full stages are in that package's README.
Run python3 -B rag_evidence_deep_dive.py. Each Chunk has id, tenant, group, version, valid_from/valid_to, policy and text. A trusted tenant/group context and at=150 select only the v2 base and exception before ranking. The two ranking lists are authored fixtures; no vector model is called in this experiment.
rrf combines positions as a sum of 1/(60+rank). This avoids treating unrelated score scales as directly additive; it does not turn rank into a probability of correctness. Duplicate IDs within one ranking are rejected. Azure's RRF description distinguishes the fusion constant from nearest-neighbor count.
The top seed expands to same-policy, same-version authorized neighbors. The whole two-clause bundle requires 163 characters. The lab measures characters, not tokenizer tokens. At budget=300 it includes both; at budget=100 it returns budget_exceeded and no partial bundle. Production systems can compress or select more carefully, but must preserve every condition needed for the target claim.
The response schema is a list of typed claims with field, value and citations. verify_claims checks shape, citation membership and explicit rules for eligible/window_days. It rejects a claim contradicted by the exception and unknown claim fields. It does not grade arbitrary prose. Keep labels and required-evidence annotations in the evaluator, not in model input when adding generation. For real local embedding provenance and a richer runnable pipeline, continue the existing RAG pipeline course.
A complete worked run
from rag_evidence_deep_dive import assemble, candidate, verify_claims
trace = assemble()
assert set(trace['assembled_ids']) == {'returns-v2-base', 'returns-v2-exception'}
assert verify_claims(candidate(), trace)['accepted']
assert verify_claims(candidate(True), trace)['reason'] == 'claim_contradicted'
print(trace['required_chars'], trace['assembly_status'])
The module records required_chars from the actual authored text and preserves the complete context in its JSON trace. Both candidates cite the same two chunks; only one satisfies the supplied rule conditions.
Visible outputs and an independent partial-answer adapter
The worked code prints 163 assembled. assemble(at=150,budget=300) has both returns-v2 IDs in eligible_ids/fused_ids/expanded_ids/assembled_ids. assemble(at=150,budget=100) retains the trace but has assembled_ids=[] and assembly_status=budget_exceeded. Each assemble call constructs an independent trace; it does not mutate a database or remember the prior budget.
Use assemble(at=300,budget=300) to inspect v3. Only returns-v3-base remains applicable in this corpus. The verifier is intentionally v2-specific: attaching a v2 citation fails citation_not_in_context; citing v3 for an eligible claim cannot satisfy its required v2 evidence. Refusal here means the implemented rule coverage is insufficient, not that every v3 answer is wrong.
Independently implement partition_claims(answer,trace). Check each typed claim separately with verify_claims and return supported claims plus gaps/reasons. Test an answer containing window_days=30 with the base ID, eligible=False with both v2 IDs, and refund_already_sent=True with the base ID. The expected partition is two supported claims and one unsupported_claim_field gap. Any dependent refund action remains blocked; source membership and useful partial text cannot establish that it was sent.
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
A gap belongs to a claim
If window_days=30 is supported but shipping_cost is absent, the adapter may expose the supported window and an explicit unknown shipping gap. It must not collapse the three claim verdicts into one accepted Boolean or infer a payment receipt from policy.
Acceptance task for this level
Run assemble at budgets300/100 and effective times150/300, saving all stage IDs and verdicts. Independently implement the per-claim partition_claims adapter using the three specified inputs; save its supported/gap output and state which action remains blocked.
Reading this browser’s record…
Hide the answer and check your understanding
Does RRF score 2/(60+1) mean the answer has a calibrated probability of being correct?
Expand reference derivation
No. It is a ranking fusion score from positions. Answer correctness also depends on applicability, full context, facts and claim support; calibration requires separate labeled evidence.
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.