tech-trans-rag / scripts /reindex_embeddings.py
phaethon-order's picture
Implement retrieval text and embedding utilities, evaluation scripts, and regression tests
34d9afb
Raw History Blame Contribute Delete
5.03 kB
"""Safely backfill metadata-enriched chunk embeddings.
The command is dry-run-only unless ``--apply`` is supplied. It scans chunks in
stable ID order so an interrupted run can resume with ``--after-chunk-id``.
"""
from __future__ import annotations
import argparse
from infrastructure.database import (
TOK_VER,
Chunk,
get_embedding_backfill_batch,
upsert_embeddings,
)
from infrastructure.embeddings import DEFAULT_MODEL, generate_embeddings
from infrastructure.logger import get_logger, setup_logger
from infrastructure.retrieval_text import (
EMBEDDING_INPUT_VERSION,
count_tokens,
embedding_input_for_chunk,
embedding_input_sha256,
)
logger = get_logger()
def backfill_embeddings(
*,
apply: bool,
batch_size: int = 64,
after_chunk_id: int = 0,
limit: int | None = None,
) -> dict[str, int]:
"""Scan and optionally replace stale embeddings, returning run counts."""
if batch_size < 1 or batch_size > 512:
raise ValueError("batch_size must be from 1 to 512")
if after_chunk_id < 0:
raise ValueError("after_chunk_id cannot be negative")
if limit is not None and limit < 1:
raise ValueError("limit must be positive")
scanned = 0
stale = 0
updated = 0
failed = 0
cursor = after_chunk_id
while limit is None or scanned < limit:
fetch_limit = batch_size
if limit is not None:
fetch_limit = min(fetch_limit, limit - scanned)
chunks = get_embedding_backfill_batch(
after_chunk_id=cursor,
limit=fetch_limit,
)
if not chunks:
break
batch_last_chunk_id = chunks[-1].chunk_id
scanned += len(chunks)
pending: list[tuple[Chunk, str, str]] = []
for chunk in chunks:
embedding_input = embedding_input_for_chunk(chunk)
input_sha256 = embedding_input_sha256(embedding_input)
is_current = (
chunk.has_embedding
and chunk.embedding_model == DEFAULT_MODEL
and bool(chunk.embedding_dim)
and chunk.embedding_input_version == EMBEDDING_INPUT_VERSION
and chunk.embedding_input_sha256 == input_sha256
)
if not is_current:
stale += 1
pending.append((chunk, embedding_input, input_sha256))
if apply and pending:
try:
vectors = generate_embeddings(
[item[1] for item in pending],
model=DEFAULT_MODEL,
)
if len(vectors) != len(pending):
raise RuntimeError(
"Embedding provider returned a different number of vectors"
)
records = [
{
"chunk_id": item[0].chunk_id,
"model": DEFAULT_MODEL,
"dim": len(vector),
"vector": vector,
"input_version": EMBEDDING_INPUT_VERSION,
"input_sha256": item[2],
"token_count": count_tokens(item[0].text),
"tok_ver": TOK_VER,
}
for item, vector in zip(pending, vectors, strict=True)
]
updated += upsert_embeddings(records)
except Exception as exc: # noqa: BLE001 - model/database batch boundary
failed += len(pending)
logger.error(
"Backfill batch failed after chunk_id=%d; retry from that "
"checkpoint: %s",
cursor,
exc,
)
break
logger.info(
"Updated %d embeddings through chunk_id=%d",
len(records),
batch_last_chunk_id,
)
cursor = batch_last_chunk_id
summary = {
"scanned": scanned,
"stale": stale,
"updated": updated,
"failed": failed,
"last_chunk_id": cursor,
}
logger.info("Embedding backfill summary: %s", summary)
return summary
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--apply",
action="store_true",
help="Generate and write embeddings; without this flag the run is read-only.",
)
parser.add_argument("--batch-size", type=int, default=64)
parser.add_argument("--after-chunk-id", type=int, default=0)
parser.add_argument("--limit", type=int)
return parser
def main() -> int:
setup_logger()
args = _parser().parse_args()
summary = backfill_embeddings(
apply=args.apply,
batch_size=args.batch_size,
after_chunk_id=args.after_chunk_id,
limit=args.limit,
)
return 1 if summary["failed"] else 0
if __name__ == "__main__":
raise SystemExit(main())