File size: 11,403 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
"""Step 3b: dense (embedding) search, for System A (naive windows) and B (chunks).



Each text becomes a 384-number vector (bge-small-en-v1.5 via fastembed) that encodes

its meaning, so "my car was stolen" can find "theft of the automobile" with no word in

common. A query is embedded the same way; the score is the cosine similarity, which

for unit-length vectors is a plain dot product.



Embedding is the slow step of the whole pipeline on this laptop CPU, so (owner's

decisions, all measured):

- batch size 1: fastembed pads every text of a batch to the longest one; with no

  batch there is no padding (3.2x faster, identical vectors; config.EMBED_BATCH_SIZE);

- a vector cache keyed by (model, text): a rebuild embeds only new or changed texts,

  and each identical text (120 SABS-2025/2026 chunks are word-for-word equal) once;

- progress saved every EMBED_SAVE_EVERY new vectors, so an interrupted build resumes;

- the model is loaded only when a text is missing from the cache.

The embedder is passed in as a function, so unit tests use a fake and never wait.

"""

import hashlib
import json
import os
import re
import zipfile
from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path
from typing import BinaryIO

import numpy as np

from coveragecheck import config
from coveragecheck.index.store import StaleIndexError, check_mask, content_hash

DIM = 384  # bge-small-en-v1.5

# texts -> one row per text, shape (len(texts), DIM)
Embedder = Callable[[list[str]], np.ndarray]


def fastembed_embedder(model_name: str = config.EMBED_MODEL) -> Embedder:
    """The real embedder. The model (0.3 s warm, 1.4 s cold) is loaded on the first

    call, never before, so a build whose texts are all cached never loads it."""
    model = None

    def embed(texts: list[str]) -> np.ndarray:
        nonlocal model
        if model is None:
            from fastembed import TextEmbedding  # slow import: only when needed

            model = TextEmbedding(model_name, cache_dir=str(config.MODEL_CACHE_DIR))
        vectors = model.embed(texts, batch_size=config.EMBED_BATCH_SIZE)
        return np.array(list(vectors), dtype=np.float32)

    return embed


def unit(vectors: np.ndarray) -> np.ndarray:
    """Rows scaled to length 1, so a dot product is the cosine similarity. bge's

    output is already normalized; doing it here makes that a guarantee, not a hope.

    A NaN / inf or all-zero row raises: cached, it would poison every later run."""
    if not np.isfinite(vectors).all():
        raise ValueError("an embedding contains NaN or inf")
    norms = np.linalg.norm(vectors, axis=-1, keepdims=True)
    if np.any(norms == 0):
        raise ValueError("an embedding is all zeros")
    return (vectors / norms).astype(np.float32)


def write_atomic(path: Path, write: Callable[[BinaryIO], None]) -> None:
    """write(file) into a temporary file, then rename it over path. The rename is

    atomic, so an interrupted write leaves the previous file intact, never half a file.

    (Single writer: on Windows the rename fails if another process holds the file.)"""
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_name(path.name + ".tmp")
    with tmp.open("wb") as f:
        write(f)
    os.replace(tmp, path)


# --- vector cache ------------------------------------------------------------------------


def text_key(text: str) -> str:
    """The cache key of a text: its SHA-256 in hex (the model is the cache file's

    name). Hex, not raw bytes: numpy's bytes arrays drop trailing NUL bytes, which

    would silently change about 1 key in 256 on a save / load round trip."""
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


@dataclass
class VectorCache:
    """Every vector ever computed for one model, by text_key. One .npz file per model

    (~1.8 KB per text). Never pruned automatically (owner's decision): 3d's passage

    variants then cost one embedding run each, ever. One writer at a time."""

    path: Path
    vectors: dict[str, np.ndarray] = field(default_factory=dict)

    @classmethod
    def open(cls, model_name: str = config.EMBED_MODEL, directory: Path | None = None):
        """The cache file of a model ("BAAI/bge-small-en-v1.5" -> BAAI_bge-small-en-v1.5.npz),

        loaded if it exists. A file that is unreadable, or holds vectors of another size

        or non-finite values, raises one clear error instead of failing later."""
        directory = config.EMBED_CACHE_DIR if directory is None else directory
        path = directory / (re.sub(r"[^\w.-]", "_", model_name) + ".npz")
        cache = cls(path)
        if not path.exists():
            return cache
        try:
            with np.load(path) as data:
                keys, vectors = data["keys"].tolist(), data["vectors"]
        except (OSError, ValueError, KeyError, EOFError, zipfile.BadZipFile) as error:
            raise ValueError(f"vector cache {path} is unreadable ({error}); delete it") from error
        if vectors.ndim != 2 or vectors.shape != (len(keys), DIM):
            raise ValueError(
                f"vector cache {path} holds {vectors.shape} vectors for {len(keys)} keys, "
                f"expected ({len(keys)}, {DIM}); delete it"
            )
        if not np.isfinite(vectors).all():
            raise ValueError(f"vector cache {path} contains NaN or inf; delete it")
        cache.vectors = dict(zip(keys, vectors, strict=True))
        return cache

    def save(self) -> None:
        """The whole cache, written atomically (write_atomic): ~14 ms at 2k vectors."""
        keys = np.array(list(self.vectors), dtype="<U64")
        vectors = np.array(list(self.vectors.values()), dtype=np.float32).reshape(-1, DIM)
        write_atomic(self.path, lambda f: np.savez(f, keys=keys, vectors=vectors))


def embed_texts(

    texts: list[str],

    embedder: Embedder,

    cache: VectorCache,

    save_every: int = config.EMBED_SAVE_EVERY,

    progress: Callable[[int, int], None] | None = None,

) -> np.ndarray:
    """Unit vectors for texts, in order, shape (len(texts), DIM). Only texts missing

    from the cache are embedded, each distinct text once, in pieces of save_every

    with a cache save after each piece. progress(done, total) is called after each."""
    keys = [text_key(t) for t in texts]
    text_of = dict(zip(keys, texts, strict=True))
    missing = [k for k in dict.fromkeys(keys) if k not in cache.vectors]
    for start in range(0, len(missing), save_every):
        piece = missing[start : start + save_every]
        vectors = embedder([text_of[k] for k in piece])
        if vectors.shape != (len(piece), DIM):
            raise ValueError(f"embedder returned {vectors.shape}, expected ({len(piece)}, {DIM})")
        cache.vectors.update(zip(piece, unit(vectors), strict=True))
        cache.save()
        if progress:
            progress(start + len(piece), len(missing))
    if not texts:
        return np.zeros((0, DIM), dtype=np.float32)
    return np.stack([cache.vectors[k] for k in keys])


def embed_query(query: str, embedder: Embedder, prefix: str | None = None) -> np.ndarray:
    """A query's unit vector, with the optional bge query instruction in front

    (prefix, default config.EMBED_QUERY_PREFIX; never added to passages). The argument

    lets 3d's probes compare prefixes without touching config. Not cached: ~10 ms."""
    prefix = config.EMBED_QUERY_PREFIX if prefix is None else prefix
    return unit(embedder([prefix + query]))[0]


# --- index -------------------------------------------------------------------------------


@dataclass
class DenseIndex:
    """Unit vectors in row order. Row i of every search result is ids[i]."""

    vectors: np.ndarray  # (n, DIM) float32
    ids: list[str]
    input_hash: str
    model: str


def build(

    ids: list[str],

    texts: list[str],

    embedder: Embedder,

    cache: VectorCache,

    model_name: str = config.EMBED_MODEL,

    progress: Callable[[int, int], None] | None = None,

) -> DenseIndex:
    """Embed every text (through the cache) into an index aligned with ids."""
    if len(ids) != len(texts) or len(set(ids)) != len(ids):
        raise ValueError("ids must be unique and aligned with texts")
    vectors = embed_texts(texts, embedder, cache, progress=progress)
    return DenseIndex(vectors, list(ids), content_hash(ids, texts), model_name)


def save(index: DenseIndex, directory: Path) -> None:
    """vectors.npy (float32, row = id order; written atomically) plus meta.json

    (model, input hash)."""
    write_atomic(directory / "vectors.npy", lambda f: np.save(f, index.vectors))
    meta = {"model": index.model, "input_hash": index.input_hash}
    (directory / "meta.json").write_text(json.dumps(meta, indent=1), encoding="utf-8")


def load(

    directory: Path, ids: list[str], texts: list[str], model_name: str = config.EMBED_MODEL

) -> DenseIndex:
    """Load a saved index after checking it was built from exactly these (ids, texts)

    with this model and holds one vector per id; StaleIndexError otherwise (the same

    rule as the lexical index: a stale index is never searched)."""
    meta_path = directory / "meta.json"
    if not meta_path.exists():
        raise StaleIndexError(f"no dense index at {directory}; build it first")
    meta = json.loads(meta_path.read_text(encoding="utf-8"))
    problems = []
    if meta.get("model") != model_name:
        problems.append(f"model: saved {meta.get('model')!r}, current {model_name!r}")
    if meta.get("input_hash") != content_hash(ids, texts):
        problems.append("the texts changed since the index was built")
    if not problems:
        try:
            vectors = np.load(directory / "vectors.npy")
        except (OSError, ValueError) as error:
            raise StaleIndexError(f"unreadable {directory / 'vectors.npy'}: {error}") from error
        if vectors.shape != (len(ids), DIM):
            problems.append(f"vectors.npy is {vectors.shape}, expected ({len(ids)}, {DIM})")
    if problems:
        raise StaleIndexError(f"stale dense index at {directory}: " + "; ".join(problems))
    return DenseIndex(vectors, list(ids), meta["input_hash"], model_name)


def search(

    index: DenseIndex, query_vector: np.ndarray, k: int, mask: np.ndarray | None = None

) -> list[tuple[int, float]]:
    """Top-k (row, cosine) pairs, best first, ties in row order. mask (bool, one per

    row) removes rows BEFORE ranking. No score floor (owner's decision): unlike BM25,

    a low cosine doesn't mean "no match", so the k best allowed rows always return.

    query_vector must be a unit vector (embed_query() makes one); a wrong shape or a

    NaN raises, since NaN scores would otherwise come back looking like results."""
    check_mask(mask, len(index.ids))
    if query_vector.shape != (DIM,) or not np.isfinite(query_vector).all():
        raise ValueError(f"query_vector must be {DIM} finite numbers")
    scores = index.vectors @ query_vector
    rows = np.arange(len(scores)) if mask is None else np.flatnonzero(mask)
    order = rows[np.argsort(-scores[rows], kind="stable")[: max(k, 0)]]
    return [(int(i), float(scores[i])) for i in order]