TBM99's picture
Deploy coverage-check 3559250
23d418f verified
Raw History Blame Contribute Delete
3.29 kB
"""Step 3a: load the Step 2 parquet tables as plain Python values, and fingerprint them.
Parquet round-trips are lossy for this project's data: pandas reads a missing string
(a law's section_number, an open-ended effective_to) as float NaN, a nullable page
number as pd.NA, and a list column (xrefs, covers_sources) as a numpy array. Code
that tests `value is None` or `value == []` then silently goes wrong. Every later step
loads the tables through load_table(), so it only ever sees None, int, str and list.
content_hash() fingerprints the rows an index was built from. A saved index stores
it, and loading checks it again, so an index built from older chunks can never be
searched by mistake (the owner's decision: fail loudly, never rebuild silently).
"""
import hashlib
import math
from collections.abc import Iterable
from pathlib import Path
import numpy as np
import pandas as pd
class StaleIndexError(RuntimeError):
"""A saved index doesn't match the current chunks or settings: rebuild it.
Shared by the lexical and dense indexes, so callers catch one error."""
def check_mask(mask: np.ndarray | None, n: int) -> None:
"""A row filter must be a bool array with one entry per row (or None = all rows).
An int array would be read as row NUMBERS by numpy indexing, silently."""
if mask is not None and (mask.dtype != bool or mask.shape != (n,)):
raise ValueError(f"mask must be a bool array of shape ({n},)")
def plain(value: object) -> object:
"""One cell as a plain Python value: numpy array -> list (recursively), any numpy
scalar -> its Python value (np.int64 -> int, np.str_ -> str, np.bool_ -> bool;
.item() also turns a datetime64 NaT into None), then every missing marker
(None, pd.NA, pd.NaT, NaN) -> None."""
if isinstance(value, np.ndarray | list | tuple):
return [plain(v) for v in value]
if isinstance(value, np.generic):
value = value.item()
if value is None or value is pd.NA or value is pd.NaT:
return None
if isinstance(value, float) and math.isnan(value):
return None
return value
def load_table(path: Path) -> pd.DataFrame:
"""Read a parquet table with every cell converted by plain(). All columns become
object dtype: slower for arithmetic, but these tables are small (< 2k rows) and
are read for their values, never for vectorized math."""
df = pd.read_parquet(path)
out = pd.DataFrame(index=df.index)
for column in df.columns:
out[column] = pd.Series([plain(v) for v in df[column]], index=df.index, dtype=object)
return out
def content_hash(ids: Iterable[str], texts: Iterable[str]) -> str:
"""SHA-256 over (id, text) pairs in order. Changing a text, an id, the order or the
number of rows changes the hash. A NUL after every field keeps characters from
sliding across a field boundary ("ab"+"c" vs "a"+"bc", or a text's end into the
next row's id); neither ids nor corpus text contain NUL."""
digest = hashlib.sha256()
for row_id, text in zip(ids, texts, strict=True):
for field in (row_id, text):
digest.update(field.encode("utf-8"))
digest.update(b"\x00")
return digest.hexdigest()