File size: 3,293 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
"""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()