"""Step 6: System B's retrieval, structure-aware hybrid RAG. question -> version filter + BM25 + dense, fused by RRF (index/hybrid.py) -> cross-encoder rerank of the top RERANK_DEPTH -> keep RERANK_TOP_K -> + up to MAX_XREF_EXPANSION sections the kept chunks cite Choices measured in 6a on the dev probes (the gold set only confirmed them): - The cross-encoder reads embed_text (heading path + text), not the bare text: on text alone it ranked worse than no rerank at all (probes hit@1 .57 -> .43), because many chunks only say what they are about in their headings ("7.3 The Deductible"). - Depth 15: reranking all ~55 candidates was worse (long off-topic chunks come back) and costs ~70 ms per candidate on this 2-core laptop (~1 s at 15). - Cross-reference expansion comes AFTER the rerank and adds passages (it does not compete for the 8 slots): the cited section is evidence the question did not name ("subject to section 267.12 of the Act"). Gold: 3 more questions fully covered. - A cited section is shown as ONE chunk: the one where the cited subsection starts ("clause 263 (5.1) (b)" -> the chunk opening "(5.1)"), else the section's first chunk (sections open with their rule). Resolved at load time, so it costs nothing per query. Replaced "the chunk most query-similar" (owner, 6a audit): on 32 relevant hand-read cases the first chunk was adequate in 27, cosine in 21, and cosine's margins were noise (median 0.014); legal RAG work resolves a reference to the provision it cites (StrucChunk, RegulaRAG). - Endorsement attachment (SPEC: attach the OPCF that changes a retrieved OAP 1 section) was measured and LEFT OUT (owner, 6a): 0 gains on 23 probes + 53 gold questions, +1.5 passages of noise, because OAP 1 Sections 6 and 7 are mentioned by 16 and 12 OPCFs, so it attaches generic forms. System B (6b) = this retrieval + the answer step shared with A (agent/answer.py: same prompt, schema and checks), so B and A differ in what they retrieve. B's passages show the chunk's heading path below the document title, then its text (owner, 6b: a chunk often never says which rule it is; the title is already in the passage header); B cites section ids. Expansions carry no marker (same header form as A). Plain Python (no LangGraph, no evals import): System C and the app reuse it. """ import hashlib import re import time from collections.abc import Callable, Mapping from dataclasses import dataclass, field from datetime import date from pathlib import Path import numpy as np import pandas as pd from coveragecheck import config from coveragecheck.agent.answer import ( Passage, answer_or_fail, prompt_hash, version_label, work_from, ) from coveragecheck.agent.schemas import Response, Work from coveragecheck.index import dense from coveragecheck.index.hybrid import Candidate, Retriever from coveragecheck.llm import LLM, Usage # (query, passages) -> one relevance score per passage, in input order Reranker = Callable[[str, list[str]], list[float]] def fastembed_reranker(model_name: str = config.RERANK_MODEL) -> Reranker: """The real cross-encoder, loaded on its first call (like dense.fastembed_embedder), batch size 1: fastembed pads a batch to its longest text, and 3c measured batch 1 fastest on this CPU (65 ms per pair vs 98-118 ms at batch 8-64).""" model = None def rerank(query: str, passages: list[str]) -> list[float]: nonlocal model if model is None: from fastembed.rerank.cross_encoder import TextCrossEncoder # slow import model = TextCrossEncoder(model_name, cache_dir=str(config.MODEL_CACHE_DIR)) return [float(s) for s in model.rerank(query, passages, batch_size=1)] return rerank def files_hash(paths: list[Path]) -> str: """SHA-256 over the bytes of several files, in order, each prefixed by its size (so bytes can't slide from one file into the next unnoticed). For the run's settings: index_hash covers only the searched texts (embed_text), but B also shows the in-force dates and expands from the xrefs and sections tables (6b audit). ~1 MB in total: milliseconds, once per process.""" digest = hashlib.sha256() for path in paths: data = Path(path).read_bytes() digest.update(len(data).to_bytes(8, "big")) digest.update(data) return digest.hexdigest() # --- rerank ------------------------------------------------------------------------------ def rerank_order(scores: list[float]) -> list[int]: """Positions sorted by score, best first. Equal scores keep their input (RRF) order, so a tie never reorders what fusion decided.""" return sorted(range(len(scores)), key=lambda i: -scores[i]) # sorted() is stable # --- the outline: which sections are inside which ---------------------------------------- @dataclass(frozen=True) class Outline: """Section nesting from sections.parquet, for expansion. `within[s]` = s and its ancestors WITHOUT the document root: every OAP 1 section is inside "OAP1-2026", so with the root counted a front-matter chunk would look related to every section of OAP 1 (2d audit). The root keeps itself (an unnumbered form like OPCF 5C).""" within: dict[str, frozenset[str]] doc_of: dict[str, str] @classmethod def from_sections(cls, sections: pd.DataFrame) -> "Outline": parent = dict(zip(sections.source_id, sections.parent_source_id, strict=True)) doc_of = dict(zip(sections.source_id, sections.doc_id, strict=True)) within = {} for source in parent: chain, node = set(), source while node is not None and node not in chain: # a cycle stops at the repeat chain.add(node) node = parent.get(node) if source != doc_of[source]: chain.discard(doc_of[source]) within[source] = frozenset(chain) return cls(within, doc_of) def chain(self, source: str) -> frozenset[str]: """source and its ancestors below the root; an unknown source is only itself.""" return self.within.get(source, frozenset({source})) def doc(self, source: str) -> str: """source's document. The split is a fallback for a source missing from sections.parquet (none on the real corpus; 6a audit).""" return self.doc_of.get(source, source.split("#")[0]) def related(self, target: str, shown: str) -> bool: """Whether a shown section already covers a cited target, so expanding it adds nothing new: the same section, or one inside the other (6.4 vs 6.4.2). A whole document as target (an unnumbered form, "see OPCF 44R") is covered by any shown chunk of that document.""" if target == self.doc_of.get(target): return self.doc(shown) == target return target in self.chain(shown) or shown in self.chain(target) def subtree_rows(source_ids: list[str], outline: Outline) -> dict[str, list[int]]: """section -> the chunk rows inside it (its own and its descendants', in table = reading order), plus each document root -> all its rows. Built once.""" out: dict[str, list[int]] = {} for row, source in enumerate(source_ids): for key in set(outline.chain(source)) | {outline.doc(source)}: out.setdefault(key, []).append(row) return out # --- which chunk of a cited section ------------------------------------------------------ def cited_subsection(match: str, number: str) -> str | None: """The subsection a reference names right after its section number: "clause 263 (5.1) (b)" -> "5.1", "Subsections 25 (1), (3)" -> "1" (the first), "s. 267.12 (1) (a)" -> "1"; None if it names none ("section 260"). The number must not sit inside a longer one ("26" in "267.12 (1)").""" found = re.search(rf"(? bool: """Whether a line of text opens that subsection: "(5.1) Nothing ...", or the section's own first line "263 (1) This ..." / SABS "15. (1) Subject ...".""" pattern = rf"(?m)^(?:{re.escape(number)}\.?\s*)?\({re.escape(sub)}\)\s" return re.search(pattern, text) is not None def preferred_rows( xref_table: pd.DataFrame, chunk_ids: list[str], texts: list[str], subtree: dict[str, list[int]], ) -> dict[tuple[int, str], int]: """(citing row, target section) -> the row where the cited subsection starts, for every reference that names a subsection found in the target. Built once at load (zero cost per query). A chunk citing one section twice: the first reference whose subsection is found wins (text order). Pairs absent here use the first chunk.""" row_of = {c: i for i, c in enumerate(chunk_ids)} resolved = xref_table[xref_table.status == "resolved"] out: dict[tuple[int, str], int] = {} for chunk_id, match, number, target in zip( resolved.chunk_id, resolved.match, resolved.number, resolved.target_source_id, strict=True ): key = (row_of[chunk_id], target) sub = None if key in out or number is None else cited_subsection(match, str(number)) if sub is None: continue for row in subtree.get(target, []): if starts_subsection(texts[row], str(number), sub): out[key] = row break return out # --- cross-reference expansion ----------------------------------------------------------- @dataclass(frozen=True) class Expansion: target: str # the cited section (xrefs target_source_id) cited_by: str # chunk_id of the shown chunk that cites it row: int # the chunk added for it how: str # "subsection" (the cited subsection's chunk) or "first" (its first chunk) def expand( shown: list[int], xrefs: list[list[str]], source_ids: list[str], outline: Outline, subtree: dict[str, list[int]], preferred: Mapping[tuple[int, str], int], allowed: np.ndarray, twin_group: np.ndarray, chunk_ids: list[str], broad: frozenset[str] = frozenset(), cap: int = config.MAX_XREF_EXPANSION, ) -> list[Expansion]: """Up to `cap` sections cited by the shown chunks, each as ONE chunk. Order: shown chunks in prompt order, each chunk's targets in its xrefs order (sorted ids, so deterministic). A target is skipped when it is `broad` (longer than config.XREF_MAX_TARGET_CHARS: a whole Section points at no particular rule) or when a shown section (or an earlier expansion) already covers it; its slot goes to the next target. The chunk shown for a target is the cited subsection's (`preferred`), else the first usable chunk in reading order. Usable: passes the version filter (`allowed`; a SABS reference names both versions), not shown already, not a version twin of a shown chunk.""" in_prompt = list(shown) out: list[Expansion] = [] seen: set[str] = set() for row in shown: for target in xrefs[row]: if len(out) >= cap: return out if target in seen or target in broad: continue seen.add(target) if any(outline.related(target, source_ids[r]) for r in in_prompt): continue groups = {int(twin_group[r]) for r in in_prompt} - {-1} pool = [ r for r in subtree.get(target, []) if allowed[r] and r not in in_prompt and int(twin_group[r]) not in groups ] if not pool: continue best = preferred.get((row, target)) how = "subsection" if best in pool else "first" pick = best if best in pool else pool[0] out.append(Expansion(target, chunk_ids[row], pick, how)) in_prompt.append(pick) return out def expansion_trace(expansions: list[Expansion], chunk_ids: list[str]) -> list[dict]: """Expansions as trace records (JSON): target section, citing chunk, chunk shown, and how it was picked. Shared by B's retrieve and C's select node.""" return [ {"target": e.target, "cited_by": e.cited_by, "chunk_id": chunk_ids[e.row], "how": e.how} for e in expansions ] # --- the pipeline ------------------------------------------------------------------------ @dataclass(frozen=True) class Retrieval: """What B shows the model, in prompt order: the reranked chunks, then the expansions. trace holds the wider picture (Work contract: candidates that were not shown go in the trace, never in retrieved_*); it lists only the top `depth` candidates, not the whole fused list.""" rows: list[int] chunk_ids: list[str] source_ids: list[str] day: date flagged: frozenset[str] trace: dict = field(default_factory=dict) class StructuredRetriever: """System B's retrieval over hybrid.Retriever. Build once per process (load()); retrieve() costs one hybrid search (~10 ms) + `depth` cross-encoder calls (~1 s); everything else is under a millisecond (6a audit).""" def __init__( self, retriever: Retriever, sections: pd.DataFrame, xref_table: pd.DataFrame, reranker: Reranker, depth: int = config.RERANK_DEPTH, keep: int = config.RERANK_TOP_K, max_xref: int = config.MAX_XREF_EXPANSION, max_target_chars: int = config.XREF_MAX_TARGET_CHARS, ): if keep > depth: raise ValueError(f"keep ({keep}) must not exceed depth ({depth})") self.retriever, self.reranker = retriever, reranker self.depth, self.keep, self.max_xref = depth, keep, max_xref chunks = retriever.chunks self.embed_texts = list(chunks.embed_text) self.xrefs = [list(x or []) for x in chunks.xrefs] self.outline = Outline.from_sections(sections) self.subtree = subtree_rows(retriever.source_ids, self.outline) self.preferred = preferred_rows( xref_table, retriever.chunk_ids, list(chunks.text), self.subtree ) too_long = sections.text.str.len() > max_target_chars self.broad = frozenset(sections.source_id[too_long]) self.corpus_hash: str | None = None # load() sets it from the table files @classmethod def load(cls, embedder, reranker: Reranker) -> "StructuredRetriever": """Load the hybrid retriever, sections.parquet and xrefs.parquet, and fingerprint the three tables B reads (corpus_hash, for the run's settings).""" from coveragecheck.index.store import load_table sections = load_table(config.INDEX_DIR / "sections.parquet") xref_table = load_table(config.INDEX_DIR / "xrefs.parquet") built = cls(Retriever.load(embedder), sections, xref_table, reranker) built.corpus_hash = files_hash( [config.INDEX_DIR / f"{name}.parquet" for name in ("chunks", "sections", "xrefs")] ) return built def warm_up(self) -> None: """Load the embedding model and the cross-encoder now (both load lazily, ~1.5 s together), so the first real question doesn't pay for them. For B's harness warm-up, C and the app.""" dense.embed_query("warm up", self.retriever.embedder) self.reranker("warm up", ["warm up"]) def rerank(self, question: str, candidates: list[Candidate]) -> tuple[list[int], list[float]]: """(the kept rows best first, the scores of the top `depth` in RRF order).""" top = candidates[: self.depth] if not top: return [], [] scores = self.reranker(question, [self.embed_texts[c.row] for c in top]) if len(scores) != len(top): raise ValueError(f"reranker returned {len(scores)} scores for {len(top)} passages") return [top[i].row for i in rerank_order(scores)[: self.keep]], scores def expand_rows(self, rows: list[int], day: date) -> list[Expansion]: """Expansion of any selection of rows (B: its reranked 8; Step 7's C can pass its own). The version filter for `day` applies; a form filter deliberately does not: a section the shown text cites is evidence whatever form it is in.""" if not rows or self.max_xref <= 0: return [] r = self.retriever mask, _ = r.mask(day, None) return expand( rows, self.xrefs, r.source_ids, self.outline, self.subtree, self.preferred, mask, r.groups, r.chunk_ids, self.broad, self.max_xref, ) def retrieve(self, question: str, day: date) -> Retrieval: """Search (version-filtered), rerank, expand. A question with no searchable word retrieves nothing (and calls no model).""" r = self.retriever result = r.search(question, day) started = time.perf_counter() kept, scores = self.rerank(question, result.candidates) rerank_ms = (time.perf_counter() - started) * 1000 expansions = self.expand_rows(kept, result.day) rows = kept + [e.row for e in expansions] # every doc the version filter flags for this date (Result.flagged covers only # the candidates, and an expansion can bring in a document that was not one) _, flagged = r.mask(result.day, None) shown_flagged = flagged & {r.doc_ids[x] for x in rows} trace = { "candidates": [c.chunk_id for c in result.candidates[: self.depth]], "rerank_scores": [round(s, 4) for s in scores], "rerank_ms": round(rerank_ms, 1), "expansions": expansion_trace(expansions, r.chunk_ids), "flagged": sorted(shown_flagged), } return Retrieval( rows, [r.chunk_ids[x] for x in rows], [r.source_ids[x] for x in rows], result.day, frozenset(shown_flagged), trace, ) # --- System B: the retrieval above + the shared answer step (6b) ------------------------- def passage_text(heading_path: str | None, text: str) -> str: """What the model reads for a chunk: its heading path BELOW the document title (the title is already in the passage header), then the text. "OAP 1: ... > Section 1: Introduction > 1.8.2 Excluded Drivers" -> "Section 1: Introduction > 1.8.2 Excluded Drivers" + the text. A chunk directly under the title (an unnumbered form) shows its text only.""" below = " > ".join((heading_path or "").split(" > ")[1:]) return f"{below}\n{text}" if below else text def passages(chunks: pd.DataFrame, rows: list[int]) -> list[Passage]: """The chunks at these rows as the model sees them, in the given (prompt) order: cited by their section id, labelled with the document's title and in-force dates (as A's). Takes plain rows, so C can pass its own selection (6b audit).""" out = [] for row in rows: c = chunks.iloc[row] label = version_label(c.title, c.effective_from, c.effective_to) out.append(Passage(c.source_id, label, passage_text(c.heading_path, c.text))) return out def work(retrieval: Retrieval, usage: Usage) -> Work: """What B did for one question: exactly the passages shown, in prompt order (Work contract), the retrieval trace (candidates, rerank scores, expansions), and the LLM's usage.""" return work_from(usage, retrieval.chunk_ids, retrieval.source_ids, trace=retrieval.trace) class StructuredSystem: name = "b" def __init__(self, retriever: StructuredRetriever, llm: LLM): self.retriever, self.llm = retriever, llm hybrid = retriever.retriever self.settings = { "retriever": "hybrid BM25 + dense (RRF), version filter, cross-encoder rerank, " "cross-reference expansion", "embed_model": config.EMBED_MODEL, "index_hash": hybrid.lexical.input_hash, # proves which chunk texts were searched # the chunks/sections/xrefs files B reads (dates shown, expansions): 6b audit "corpus_hash": retriever.corpus_hash, "candidate_k": config.CANDIDATE_K, "rrf_k": config.RRF_K, "version_filter": True, "rerank_model": config.RERANK_MODEL, "rerank_text": "embed_text", "rerank_depth": retriever.depth, "rerank_keep": retriever.keep, "max_xref": retriever.max_xref, "xref_max_target_chars": config.XREF_MAX_TARGET_CHARS, "xref_chunk": "cited subsection, else the section's first chunk", "endorsement_attachment": False, # measured in 6a: 0 gain "passage_text": "heading path below the title + chunk text", "passage_label": "source_id | title | in force: from to to", "prompt_hash": prompt_hash(), **llm.settings, } def warm_up(self) -> None: """Load both retrieval models now (StructuredRetriever.warm_up). The LLM needs no warm-up (its client connects on the first call).""" self.retriever.warm_up() def answer(self, question: str, day: date) -> Response: """Retrieve (version-filtered for day), then answer from the passages. An LLM failure becomes AnswerFailed carrying what was retrieved and spent. A retrieval failure (e.g. the reranker) propagates: the run records it as an exception row, never a silent fallback that would change what B is.""" retrieval = self.retriever.retrieve(question, day) shown = passages(self.retriever.retriever.chunks, retrieval.rows) return answer_or_fail(self.llm, question, day, shown, lambda usage: work(retrieval, usage)) def build() -> StructuredSystem: """The registry factory: load the indexes (each checked against chunks.parquet), sections, xrefs, both models (lazily) and the LLM, once.""" retriever = StructuredRetriever.load(dense.fastembed_embedder(), fastembed_reranker()) return StructuredSystem(retriever, LLM.load())