File size: 12,943 Bytes
23d418f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
"""Step 3c: System B's hybrid search: filters, then BM25 + dense, fused by rank.

1. Filters decide which documents a query may see, BEFORE ranking (so k results
   always come from allowed documents):
   - version filter (SPEC Step 3): a document is excluded only when it is NOT in force
     on the policy date while another version of the same form IS (SABS-2025 vs
     SABS-2026; OPCF 47 vs 47R, linked by the manifest's `supersedes`). A kept document
     that is not in force is "flagged": the answer may cite the wrong version.
     No date -> today.
   - form filter (optional): only the named forms, each with all its versions.
2. Each retriever returns its top CANDIDATE_K allowed chunks; Reciprocal Rank Fusion
   adds 1 / (RRF_K + rank) per list. Ranks, not scores: BM25 scores and cosines are on
   different scales, and the cosines sit in a narrow 0.65-0.83 band (3b audit).
3. Version twins (identical text, same form family, different documents) keep only
   their best-ranked copy. Identical text across different forms or sections is NOT
   merged: OAP 1 Sections 3-7 share an opening sentence but are different rules.

Latency (owner's priority): everything that depends only on the corpus (documents,
families, each row's document, twin groups) is computed once in Retriever.load();
a query costs one query embedding (~10 ms), two sub-millisecond searches, and array
lookups. Filter masks are cached per (date, forms).
"""

import functools
from collections.abc import Iterable
from dataclasses import dataclass
from datetime import date, datetime
from pathlib import Path

import numpy as np
import pandas as pd

from coveragecheck import config
from coveragecheck.index import dense, lexical
from coveragecheck.index.store import StaleIndexError, load_table

# --- documents and versions --------------------------------------------------------------


@dataclass(frozen=True)
class Doc:
    doc_id: str
    form_id: str
    effective_from: date | None
    effective_to: date | None
    supersedes: str | None


def documents(chunks: pd.DataFrame) -> list[Doc]:
    """One Doc per document, in table order, from the per-document columns that every
    chunk row carries (Step 2 copies them from the manifest). Expects load_table()'s
    output (None, not NaN, for a missing date). Raises if a document's rows disagree,
    since only its first row is read."""
    columns = ["form_id", "effective_from", "effective_to", "supersedes"]
    varying = chunks.groupby("doc_id")[columns].nunique(dropna=False).max(axis=1)
    if (varying > 1).any():
        raise ValueError(f"rows of one document disagree: {sorted(varying[varying > 1].index)}")
    first = chunks.drop_duplicates("doc_id")

    def day(value: str | None) -> date | None:
        return None if value is None else date.fromisoformat(value)

    return [
        Doc(r.doc_id, r.form_id, day(r.effective_from), day(r.effective_to), r.supersedes)
        for r in first.itertuples()
    ]


def families(docs: list[Doc]) -> dict[str, str]:
    """doc_id -> family: the versions of one form. Same form_id = same family, and
    `supersedes` joins two form_ids (OPCF 47R replaces OPCF 47). Similar names never
    join by themselves: OPCF 43 / 43A, 28 / 28A ... are different forms in force at
    the same time (3c corpus study). The family name is its smallest form_id."""
    parent = {d.form_id: d.form_id for d in docs}

    def root(form: str) -> str:
        while parent[form] != form:
            form = parent[form]
        return form

    form_of = {d.doc_id: d.form_id for d in docs}
    for d in docs:
        if d.supersedes is not None:
            if d.supersedes not in form_of:
                raise ValueError(f"{d.doc_id} supersedes {d.supersedes}: not in the corpus")
            a, b = root(d.form_id), root(form_of[d.supersedes])
            parent[max(a, b)] = min(a, b)
    return {d.doc_id: root(d.form_id) for d in docs}


def in_force(doc: Doc, day: date) -> bool:
    """In force on day: no start date or started, and no end date or not yet ended.
    An undated document is always in force (22 of 36 have no dates)."""
    started = doc.effective_from is None or doc.effective_from <= day
    not_ended = doc.effective_to is None or day <= doc.effective_to
    return started and not_ended


def version_filter(
    docs: list[Doc], family: dict[str, str], day: date
) -> tuple[frozenset[str], frozenset[str]]:
    """(allowed, flagged) doc_ids for a policy date. Excluded: not in force while a
    family sibling is (owner's reading of the SPEC rule: two overlapping versions both
    in force are both kept). Flagged: kept although not in force (no sibling is)."""
    live = {family[d.doc_id] for d in docs if in_force(d, day)}
    allowed, flagged = set(), set()
    for d in docs:
        if in_force(d, day):
            allowed.add(d.doc_id)
        elif family[d.doc_id] not in live:
            allowed.add(d.doc_id)
            flagged.add(d.doc_id)
    return frozenset(allowed), frozenset(flagged)


def form_filter(docs: list[Doc], family: dict[str, str], form_ids: Iterable[str]) -> frozenset[str]:
    """doc_ids of the named forms and of every version in their families ("OPCF 47"
    also allows OPCF 47R; the version filter then picks by date). An unknown form_id
    raises: a typo must not silently return nothing."""
    by_form = {d.form_id: family[d.doc_id] for d in docs}
    unknown = sorted(set(form_ids) - set(by_form))
    if unknown:
        raise ValueError(f"unknown form_id(s): {unknown}")
    wanted = {by_form[f] for f in form_ids}
    return frozenset(d.doc_id for d in docs if family[d.doc_id] in wanted)


# --- fusion ------------------------------------------------------------------------------


def rrf(rankings: list[list[int]], k: int = config.RRF_K) -> list[tuple[int, float]]:
    """Reciprocal Rank Fusion: score(row) = sum over rankings of 1 / (k + rank), rank
    from 1. Best first; equal scores keep the order rows were first seen (ranking 0's
    order first), so the result is deterministic."""
    scores: dict[int, float] = {}
    for ranking in rankings:
        for rank, row in enumerate(ranking, start=1):
            scores[row] = scores.get(row, 0.0) + 1.0 / (k + rank)
    return sorted(scores.items(), key=lambda item: -item[1])  # sorted() is stable


def twin_groups(chunks: pd.DataFrame, family: dict[str, str]) -> np.ndarray:
    """Per row, a group number shared by its version twins (same family, identical
    text, different documents), or -1. Real corpus: the 120 SABS-2025/2026 pairs."""
    groups = np.full(len(chunks), -1, dtype=np.int64)
    rows_by_key: dict[tuple[str, str], list[int]] = {}
    for row, (doc_id, text) in enumerate(zip(chunks.doc_id, chunks.text, strict=True)):
        rows_by_key.setdefault((family[doc_id], text), []).append(row)
    for number, rows in enumerate(r for r in rows_by_key.values() if len(r) > 1):
        if len({chunks.doc_id.iat[r] for r in rows}) > 1:  # same doc twice = 2 sections
            groups[rows] = number
    return groups


def dedupe(fused: list[tuple[int, float]], groups: np.ndarray) -> list[tuple[int, float]]:
    """Keep the first (best-ranked) row of each twin group. This also "prefers the
    in-force version": the version filter never keeps a not-in-force twin next to an
    in-force one, so kept twins are either all in force or all flagged."""
    seen: set[int] = set()
    out = []
    for row, score in fused:
        group = int(groups[row])
        if group >= 0:
            if group in seen:
                continue
            seen.add(group)
        out.append((row, score))
    return out


# --- the retriever -----------------------------------------------------------------------


@dataclass(frozen=True)
class Candidate:
    row: int
    chunk_id: str
    doc_id: str
    source_id: str  # the citable section (Step 4 metrics, Step 8 citations)
    score: float  # RRF score
    lexical_rank: int | None  # 1-based rank in BM25's list, None if not in it
    dense_rank: int | None


@dataclass(frozen=True)
class Result:
    candidates: list[Candidate]
    day: date  # the policy date the version filter used
    flagged: frozenset[str]  # doc_ids among the candidates that may be the wrong version


class Retriever:
    """System B's search over one chunks table and its two indexes. Build it once per
    process (Retriever.load); search() is then cheap. self.chunks keeps the table, so
    later steps read a candidate's text, heading_path or xrefs by its row."""

    def __init__(
        self,
        chunks: pd.DataFrame,
        lexical_index: lexical.LexicalIndex,
        dense_index: dense.DenseIndex,
        embedder: dense.Embedder,
    ):
        ids = list(chunks.chunk_id)
        if lexical_index.ids != ids or dense_index.ids != ids:
            raise StaleIndexError("the indexes and the chunks table have different rows")
        if lexical_index.input_hash != dense_index.input_hash:
            raise StaleIndexError("the lexical and dense indexes were built from different texts")
        self.chunks = chunks
        self.chunk_ids = ids
        self.doc_ids, self.source_ids = list(chunks.doc_id), list(chunks.source_id)
        self.lexical, self.dense, self.embedder = lexical_index, dense_index, embedder
        self.docs = documents(chunks)
        self.family = families(self.docs)
        doc_index = {d.doc_id: i for i, d in enumerate(self.docs)}
        self.row_doc = np.array([doc_index[d] for d in chunks.doc_id], dtype=np.int64)
        self.groups = twin_groups(chunks, self.family)
        self.mask = functools.lru_cache(maxsize=256)(self._mask)

    @classmethod
    def load(
        cls,
        embedder: dense.Embedder,
        index_dir: Path = config.INDEX_DIR,
        bm25_dir: Path = config.BM25_DIR,
        dense_dir: Path = config.DENSE_B_DIR,
    ) -> "Retriever":
        """Read chunks.parquet and load both saved indexes, each checked against it."""
        chunks = load_table(index_dir / "chunks.parquet")
        ids, texts = list(chunks.chunk_id), list(chunks.embed_text)
        return cls(
            chunks, lexical.load(bm25_dir, ids, texts), dense.load(dense_dir, ids, texts), embedder
        )

    def _mask(
        self, day: date, form_ids: frozenset[str] | None
    ) -> tuple[np.ndarray, frozenset[str]]:
        """(bool mask over rows, flagged doc_ids) for a date and an optional form set.
        The mask is cached and shared between searches, so it is made read-only."""
        allowed, flagged = version_filter(self.docs, self.family, day)
        if form_ids is not None:
            allowed = allowed & form_filter(self.docs, self.family, form_ids)
        doc_allowed = np.array([d.doc_id in allowed for d in self.docs])
        mask = doc_allowed[self.row_doc]
        mask.flags.writeable = False
        return mask, flagged

    def search(
        self,
        query: str,
        day: date | datetime | None = None,
        form_ids: str | Iterable[str] | None = None,
        k: int = config.CANDIDATE_K,
    ) -> Result:
        """Fused, deduped candidates for a query (each retriever contributes its top k
        allowed chunks, so at most 2k candidates). day: the policy date (a datetime is
        cut to its date; None = today). form_ids: None = every form; one form_id or a
        non-empty list of them (an empty list raises: it would silently find nothing).
        A query with no searchable word (blank, stopwords, punctuation) returns none:
        dense search has no score floor and would return arbitrary chunks."""
        day = date.today() if day is None else day
        day = day.date() if isinstance(day, datetime) else day
        if isinstance(form_ids, str):
            form_ids = [form_ids]
        forms = None if form_ids is None else frozenset(form_ids)
        if forms is not None and not forms:
            raise ValueError("form_ids is empty; pass None for no form filter")
        if not lexical.tokenize(query):
            return Result([], day, frozenset())
        mask, flagged = self.mask(day, forms)
        lex = [row for row, _ in lexical.search(self.lexical, query, k, mask)]
        query_vector = dense.embed_query(query, self.embedder)
        den = [row for row, _ in dense.search(self.dense, query_vector, k, mask)]
        lex_rank = {row: rank for rank, row in enumerate(lex, start=1)}
        den_rank = {row: rank for rank, row in enumerate(den, start=1)}
        candidates = [
            Candidate(
                row,
                self.chunk_ids[row],
                self.doc_ids[row],
                self.source_ids[row],
                score,
                lex_rank.get(row),
                den_rank.get(row),
            )
            for row, score in dedupe(rrf([lex, den]), self.groups)
        ]
        used = {c.doc_id for c in candidates}
        return Result(candidates, day, flagged & used)