diff --git a/CHANGELOG.md b/CHANGELOG.md index 30437bc..e9cb157 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ internal versions are summarized under 0.3.33. ## [Unreleased] ### Fixed +- Backfill embeds each missing paper and passage once per pass when index saves are throttled. Reconciliation checks revised vectors before marking them indexed. (#6) +- Removing or replacing chunks in an IVF-PQ index preserves search IDs and scores for the remaining passages. +- Resubmitting a cluster build preserves populated FAISS indexes. A writer rebuild also retires detached shard checkpoints so producers can add new archives afterward. +- Node-local transfers publish the checkpoint, database, segments and completion marker from a recoverable copy on shared storage. +- Completed consumers now mark every saved paper and chunk as indexed when FAISS saves are throttled. Incremental producers embed files recorded by SQLite-only workers and keep revised documents, passages and vectors together after a shard merge. +- Tar builds commit articles in batches. An interrupted producer resumes from the last batch for which it published both paper and chunk segments. Without `--strict-ingest`, an error after which SQLite has rolled back the batch, such as a full disk, now stops the build instead of skipping the article. If a shard interrupted on an older release has unverifiable or missing embeddings, rebuild from the original archives in a fresh workspace. (#13, #3, #4) - Keyword search now matches Unicode forms such as `fibrosis`, `CD4`, and `marker²` in existing indexes. Applications executing `sqlite_norm_expr()` on their own SQLite connections can call `litkit.retrieval.register_search_normalizer(conn)` once. LitKit handles registration for its own searches. (#20) - Capped Stage-2 searches keep newly fetched chunks inside the paper shortlist. Sparse-shortlist fallback and explicit global lexical searches can still return other papers. (#25) - Corpus manifests accept dotted shard names without a tar extension. The CLI reports entries it cannot resolve. (#19) @@ -15,11 +21,10 @@ internal versions are summarized under 0.3.33. - `query_terms()`, `find_rare_terms()`, and Stage-2 lexical front-loading now retain 3–4 character all-uppercase acronyms (such as `HIV`, `EGFR`, and `ALL`, plus plurals like `TLRs`) with word-boundary matching that still accepts plural, numbered, and inhibitor forms (`RNAs`, `TLR4`, `ACEi`), prioritize digit/hyphen and long-term matches ahead of acronyms, and normalize SQLite-compatible dashes and subscripts before tokenizing. All-caps prose such as `WHAT IS THE ROLE OF RNA` does not turn ordinary words into acronyms, while all-caps keyword queries such as `EGFR NSCLC` keep theirs. (#9) - Multi-node consumers merge every producer's shard database. The merge stopped after 10 shards, losing the rows of producers 10 and up while reporting success; a shard that can't be detached now stops the merge with an error. (#1) - `--consume-only` deletes a segment file only after a saved index covers its vectors, so a job killed between throttled saves can be rerun, also with `vector_resume_consumer.sbatch`, without losing vectors or adding duplicates to the HNSW paper index. (#2) -- A producer's checkpoint advances only after the tar's segments are finalized. It used to count articles whose segments were still pending, which a failed tar-boundary flush deletes. (#3) +- A producer's checkpoint advances only after both paper and passage segments for its batch are finalized. It used to count articles whose segments were still pending, which a failed tar-boundary flush deletes. (#3) - The consumer and `--rebuild` ignore unfinished `*_pending.npz` segments. (#4) - A successful `--consume-only` run removes the producers' `producer_N.done` markers, and `vector_build_multi.sbatch` and each producer remove old ones when they start, so the next multi-node job waits for its producers and `--rebuild` is no longer blocked. (#5) - The batch scripts and the cluster guide remove the writer guard litkit creates, `workspace/sqlite/faiss_writer.guard`, instead of `workspace/.writer_guard`. (#15) -- Builds commit articles in batches instead of one at a time. A producer commits a tar's articles only at the tar boundary, just before it finalizes the tar's segments, so after a failed flush or a job killed mid-tar, a restart without `--rebuild` processes them again instead of skipping them with no vectors. A writer commits at each flush, once the batch is embedded, at each checkpoint and at each tar boundary, so a failed embedding rolls back only the articles since the last of those; earlier rows of the batch still wait for the backfill. Without `--strict-ingest`, an error after which SQLite has rolled back the batch, such as a full disk, now stops the build instead of skipping the article. (#13) - Removing vectors from a FAISS index before re-adding them (`--update`, backfill, segment ingestion) takes time proportional to the index size instead of index size times IDs removed. Removing 20,000 IDs from 1M vectors took 10.3 s and now takes 0.03 s. (#14) ## [0.3.36] - 2026-11-30 diff --git a/src/litkit/build/backfill.py b/src/litkit/build/backfill.py index d03dfe3..3c9217c 100644 --- a/src/litkit/build/backfill.py +++ b/src/litkit/build/backfill.py @@ -20,11 +20,13 @@ faiss_present_ids, faiss_save, faiss_save_force, - make_id_selector, + kind_and_core, report_faiss_index, - safe_remove_ids, ) +from litkit.index.ids import copy_hnsw_without_ids +from litkit.segments.ingest import remove_obsolete_chunks from litkit.db import mark_in_index, flush_pending_marks +from litkit.db.schema import paper_embedding_column from litkit.progress import eprint if TYPE_CHECKING: @@ -66,85 +68,57 @@ def backfill_unindexed_vectors( chunk_bs: Batch size for chunk embedding """ cur = conn.cursor() - - # Papers - while True: - rows = cur.execute( - "SELECT id, (COALESCE(title,'') || ' ' || COALESCE(abstract,'')) " - "AS txt FROM papers WHERE in_index=0 LIMIT ?", - (batch,), - ).fetchall() - if not rows: - break - ids = [r[0] for r in rows] - texts = [(r[1] or "untitled").strip() for r in rows] - Xp = paper_embedder.encode( - texts, - progress_label=f"Embedding papers (backfill, {len(texts)})", - batch_size=paper_bs, - progress_done_summary=False, - ) - - if not isinstance(paper_index, faiss.IndexIDMap2): - paper_index = faiss.IndexIDMap2(paper_index) - - prior_ntotal = int(getattr(paper_index, "ntotal", 0) or 0) - with FileLock(faiss_lock_path): - # add_with_ids_dedup handles removal internally - no explicit safe_remove_ids needed - added, ids_added = add_with_ids_dedup(paper_index, ids, Xp) - saved = False - if added: - if prior_ntotal == 0: - saved = faiss_save_force(paper_index, paper_index_path) - else: - saved = faiss_save(paper_index, paper_index_path) - if added and saved: - with FileLock(db_lock_path): - mark_in_index(cur, "papers", [int(i) for i in ids_added]) - flush_pending_marks(cur) - conn.commit() - else: - # Save failed - vectors are in FAISS but not marked in DB. - # reconcile_sqlite_flags_with_faiss() will fix this on next run. - conn.commit() - - # Chunks - while True: - rows = cur.execute( - "SELECT id, text FROM chunks WHERE in_index=0 LIMIT ?", (batch,) - ).fetchall() + recorded_text = paper_embedding_column(conn) + paper_rows = ( + f"SELECT p.id, COALESCE({recorded_text}, (" + "SELECT c.text FROM chunks c WHERE c.paper_id=p.id AND c.ord=-1 ORDER BY c.id DESC LIMIT 1" + "), TRIM(COALESCE(p.title,'') || ' ' || COALESCE(p.abstract,''))) FROM papers p" + ) + remove_obsolete_chunks(conn, chunk_index, chunk_index_path, faiss_lock_path, db_lock_path, FileLock) + for table, select, index, path, embedder, bs in ( + ("papers", paper_rows, paper_index, paper_index_path, paper_embedder, paper_bs), + ("chunks", "SELECT id, text FROM chunks", chunk_index, chunk_index_path, chunk_embedder, chunk_bs), + ): + query = f"{select} WHERE in_index=0" + rows = cur.execute(query + " ORDER BY id LIMIT ?", (batch,)).fetchall() if not rows: - break - ids = [r[0] for r in rows] - texts = [r[1] for r in rows] - Xc = chunk_embedder.encode( - texts, - progress_label=f"Embedding chunks (backfill, {len(texts)})", - batch_size=chunk_bs, - progress_done_summary=False, - ) - if not isinstance(chunk_index, faiss.IndexIDMap2): - chunk_index = faiss.IndexIDMap2(chunk_index) - - prior_ntotal = int(getattr(chunk_index, "ntotal", 0) or 0) - with FileLock(faiss_lock_path): - # add_with_ids_dedup handles removal internally - no explicit safe_remove_ids needed - added, ids_added = add_with_ids_dedup(chunk_index, ids, Xc) - saved = False - if added: - if prior_ntotal == 0: - saved = faiss_save_force(chunk_index, chunk_index_path) - else: - saved = faiss_save(chunk_index, chunk_index_path) - if added and saved: - with FileLock(db_lock_path): - mark_in_index(cur, "chunks", [int(i) for i in ids_added]) - flush_pending_marks(cur) - conn.commit() - else: - # Save failed - vectors are in FAISS but not marked in DB. - # reconcile_sqlite_flags_with_faiss() will fix this on next run. - conn.commit() + continue + if not isinstance(index, faiss.IndexIDMap2): + index = faiss.IndexIDMap2(index) + if kind_and_core(index)[0] == "hnsw" and index.ntotal: + present = faiss_present_ids(index) or set() + replacing = present.intersection(row[0] for row in cur.execute(f"SELECT id FROM {table} WHERE in_index=0")) + if replacing: + with FileLock(faiss_lock_path): + copy_hnsw_without_ids(faiss.clone_index(index), index, replacing) + pending = [] + while rows: + ids = [row[0] for row in rows] + texts = [row[1] for row in rows] + if table == "papers": + texts = [(text or "untitled").strip() for text in texts] + vectors = embedder.encode(texts, batch_size=bs, + progress_label=f"Embedding {table} (backfill, {len(texts)})") + with FileLock(faiss_lock_path): + first = not index.ntotal + added, ids_added = add_with_ids_dedup(index, ids, vectors) + if added != len(ids): + raise RuntimeError(f"Unable to replace every {table} vector in this backfill batch.") + pending.extend(int(i) for i in ids_added) + saved = faiss_save_force(index, path) if first else faiss_save(index, path) + # Advance past unsaved IDs. They stay at zero in SQLite until a + # durable snapshot includes them, so a restart can repeat the work. + rows = cur.execute(query + " AND id>? ORDER BY id LIMIT ?", (ids[-1], batch)).fetchall() + if not rows and not saved: + with FileLock(faiss_lock_path): + faiss_save_force(index, path) + saved = True + if saved: + with FileLock(db_lock_path): + mark_in_index(cur, table, pending) + flush_pending_marks(cur) + conn.commit() + pending.clear() def reconcile_sqlite_flags_with_faiss( @@ -158,64 +132,25 @@ def reconcile_sqlite_flags_with_faiss( Tuple of (papers_reset, chunks_reset) """ cur = conn.cursor() - reset_p = reset_c = 0 - - # Papers - ids_present = faiss_present_ids(paper_index) - if ids_present is not None: - cur.execute("SELECT id, in_index FROM papers") - bad = [ - row[0] - for row in cur.fetchall() - if row[0] not in ids_present and row[1] == 1 - ] - good_missing_flag = [ - row[0] - for row in cur.execute( - "SELECT id FROM papers WHERE in_index=0" - ).fetchall() - if row[0] in ids_present - ] - if bad: - cur.executemany( - "UPDATE papers SET in_index=0 WHERE id=?", [(i,) for i in bad] - ) - reset_p = len(bad) - if good_missing_flag: - cur.executemany( - "UPDATE papers SET in_index=1 WHERE id=?", - [(i,) for i in good_missing_flag], - ) - - # Chunks - ids_present = faiss_present_ids(chunk_index) - if ids_present is not None: - cur.execute("SELECT id, in_index FROM chunks") - bad = [ - row[0] - for row in cur.fetchall() - if row[0] not in ids_present and row[1] == 1 - ] - good_missing_flag = [ - row[0] - for row in cur.execute( - "SELECT id FROM chunks WHERE in_index=0" - ).fetchall() - if row[0] in ids_present - ] - if bad: - cur.executemany( - "UPDATE chunks SET in_index=0 WHERE id=?", [(i,) for i in bad] - ) - reset_c = len(bad) - if good_missing_flag: - cur.executemany( - "UPDATE chunks SET in_index=1 WHERE id=?", - [(i,) for i in good_missing_flag], - ) - + revised = conn.execute("SELECT 1 FROM sqlite_master WHERE name='merged_paper_revisions'").fetchone() + resets = [] + for table, index, paper_key in (("papers", paper_index, "id"), ("chunks", chunk_index, "paper_id")): + present = faiss_present_ids(index) + if present is None: + resets.append(0) + continue + missing = [i for i, in cur.execute(f"SELECT id FROM {table} WHERE in_index=1") if i not in present] + # After merging a revision, the numeric ID can still refer to the + # previous vector. Only a saved replacement may mark these rows. + query = f"SELECT id FROM {table} WHERE in_index=0" + if revised: + query += f" AND {paper_key} NOT IN (SELECT paper_id FROM merged_paper_revisions)" + saved = [i for i, in cur.execute(query) if i in present] + cur.executemany(f"UPDATE {table} SET in_index=0 WHERE id=?", ((i,) for i in missing)) + cur.executemany(f"UPDATE {table} SET in_index=1 WHERE id=?", ((i,) for i in saved)) + resets.append(len(missing)) conn.commit() - return reset_p, reset_c + return resets[0], resets[1] def post_build_sanity_check( diff --git a/src/litkit/build/consume.py b/src/litkit/build/consume.py index 908bb62..a17af42 100644 --- a/src/litkit/build/consume.py +++ b/src/litkit/build/consume.py @@ -10,20 +10,23 @@ from __future__ import annotations +import time +from contextlib import ExitStack +from functools import partial from pathlib import Path from sqlite3 import Connection from typing import TYPE_CHECKING, Callable -from litkit.db import ( - merge_shard_databases, - flush_pending_marks, -) +from litkit.db import flush_pending_marks +from litkit.concurrent.locking import FileLock as ProducerFileLock +from litkit.db.sharding import drained_producers, merge_drained_shards from litkit.index import faiss_load from litkit.segments import ( ConsumerCoordinator, ingest_paper_segments, ingest_chunk_segments, ) +from litkit.segments.metadata import has_segment_files from litkit.progress import eprint if TYPE_CHECKING: @@ -72,7 +75,8 @@ def default_progress(complete: int, total: int) -> None: eprint(f"[consumer] Progress: {complete}/{total} producers complete") cb = progress_callback or default_progress - + sqlite_dir = Path(conn.execute("PRAGMA database_list").fetchone()[2]).parent + eprint("[consumer] Starting consume-only mode") # Load existing indices @@ -84,51 +88,57 @@ def default_progress(complete: int, total: int) -> None: eprint("[consumer] Waiting for producers to complete...") - completed = consumer_coordinator.wait_for_completion( - poll_interval=poll_interval, - timeout=timeout, - progress_callback=cb, - ) - - if not completed: - eprint("[consumer] TIMEOUT waiting for producers; aborting consume-only run.") - return False - - eprint("[consumer] All producers have completed") - - # Merge shard databases FIRST (before segment ingestion) - # This populates the main DB so doc_id → paper_id resolution works - eprint("[consumer] Merging shard databases...") - merge_stats = merge_shard_databases(conn, delete_after_merge=True) - if merge_stats["shards"] > 0: - eprint( - f"[consumer] Merged {merge_stats['shards']} shard DB(s): " - f"{merge_stats['papers']} papers, {merge_stats['chunks']} chunks, " - f"{merge_stats['files']} files" + deadline = None if timeout is None else time.monotonic() + timeout + with ExitStack() as owners: + while True: + try: + owners.enter_context(drained_producers(sqlite_dir, partial(ProducerFileLock, blocking=False))) + except BlockingIOError: + # A live producer may still be copying its shard or replacing an old marker. + complete = len(consumer_coordinator.completed_shards()) + else: + complete = len(consumer_coordinator.completed_shards()) + if complete == num_shards: + cb(complete, num_shards) + break + owners.close() + + cb(complete, num_shards) + delay = poll_interval + if deadline is not None: + remaining = deadline - time.monotonic() + if remaining <= 0: + eprint("[consumer] TIMEOUT waiting for producers; aborting consume-only run.") + return False + delay = min(delay, remaining) + time.sleep(delay) + + eprint("[consumer] All producers have completed. Merging shard databases...") + merge_stats = merge_drained_shards(conn, sqlite_dir, True, seg_dir) + if merge_stats["shards"] > 0: + eprint( + f"[consumer] Merged {merge_stats['shards']} shard DB(s): " + f"{merge_stats['papers']} papers, {merge_stats['chunks']} chunks, " + f"{merge_stats['files']} files" + ) + + # NOW ingest segments - main DB has all data for doc_id resolution + eprint("[consumer] Ingesting embedding segments...") + paper_index, p_added = ingest_paper_segments( + conn, paper_index, seg_dir, faiss_lock_path, paper_index_path, db_lock_path, + FileLock=FileLock, ) - - # NOW ingest segments - main DB has all data for doc_id resolution - eprint("[consumer] Ingesting embedding segments...") - paper_index, p_added = ingest_paper_segments( - conn, paper_index, seg_dir, faiss_lock_path, paper_index_path, db_lock_path, - FileLock=FileLock - ) - chunk_index, c_added = ingest_chunk_segments( - conn, chunk_index, seg_dir, faiss_lock_path, chunk_index_path, db_lock_path, - FileLock=FileLock - ) - eprint(f"[consumer] Ingested {p_added} paper vectors and {c_added} chunk vectors") - - # No save here: each ingest function saves what it added before it returns, - # and the segment files it consumed are deleted only after that save (#2). - - with FileLock(db_lock_path): - flush_pending_marks(conn.cursor()) - conn.commit() - - # The next multi-node job in this workspace must wait for its own producers, - # and --rebuild refuses to run while these markers exist (#5). - consumer_coordinator.cleanup_done_files() + chunk_index, c_added = ingest_chunk_segments( + conn, chunk_index, seg_dir, faiss_lock_path, chunk_index_path, db_lock_path, + FileLock=FileLock, + ) + eprint(f"[consumer] Ingested {p_added} paper vectors and {c_added} chunk vectors") + + with FileLock(db_lock_path), conn: + flush_pending_marks(conn.cursor()) - eprint("[consumer] Consume-only mode completed") - return True + if has_segment_files(seg_dir): + raise RuntimeError("Segment ingestion stopped before completion. Retry the remaining segments.") + consumer_coordinator.cleanup_done_files() + eprint("[consumer] Consume-only mode completed") + return True diff --git a/src/litkit/build/helpers.py b/src/litkit/build/helpers.py index 77f68f5..3f87c5c 100644 --- a/src/litkit/build/helpers.py +++ b/src/litkit/build/helpers.py @@ -87,9 +87,9 @@ def pack_body(meta: ArticleMeta, max_chars: int, min_chars: int, overlap_chars: def dedupe_papers_with_doc_ids( - ids: list[int], texts: list[str], doc_ids: list[str] + ids: list[int], texts: list[str], doc_ids: list[str], *, keep_last: bool = False ) -> tuple[list[int], list[str], list[str]]: - """Keep the first occurrence of each id; return aligned id/text/doc_id lists. + """Return aligned values in first-ID order, optionally retaining later revisions. Args: ids: Paper database IDs @@ -99,18 +99,11 @@ def dedupe_papers_with_doc_ids( Returns: Tuple of (unique_ids, unique_texts, unique_doc_ids) """ - out_ids: list[int] = [] - out_texts: list[str] = [] - out_doc_ids: list[str] = [] - seen: set[int] = set() - for i, t, d in zip(ids, texts, doc_ids, strict=False): - if i in seen: - continue - seen.add(i) - out_ids.append(i) - out_texts.append(t) - out_doc_ids.append(d) - return out_ids, out_texts, out_doc_ids + entries = {} + for pid, text, doc_id in zip(ids, texts, doc_ids, strict=False): + if keep_last or pid not in entries: + entries[pid] = (text, doc_id) + return list(entries), [v[0] for v in entries.values()], [v[1] for v in entries.values()] def dedupe_chunks_with_doc_ids( diff --git a/src/litkit/build/indices.py b/src/litkit/build/indices.py index 20963c6..34611a2 100644 --- a/src/litkit/build/indices.py +++ b/src/litkit/build/indices.py @@ -36,7 +36,7 @@ def init_empty_indices( paper_dim: int = 768, chunk_dim: int = 768, ) -> None: - """Create empty FAISS indices for bootstrap mode (--init-indices-only). + """Create any missing FAISS indices for bootstrap mode (--init-indices-only). This is used in multi-node setups where the consumer needs pre-existing indices before producers start. Creates both paper and chunk indices @@ -59,37 +59,26 @@ def init_empty_indices( if not cfg.faiss_writer: raise ValueError("--init-indices-only requires --faiss-writer") - _eprint("[bootstrap] Creating empty FAISS indices...") - - # Create paper index (HNSW or FLAT based on config) - if cfg.papers_index == "flat": - paper_base = flat_ip_index(paper_dim) - else: # hnsw (default) - paper_base = hnsw_index( - paper_dim, - M=cfg.hnsw_m, - ef_construction=cfg.efconstruction, - ef_search=cfg.efsearch, - ) - paper_index = faiss.IndexIDMap2(paper_base) - - ensure_parent(cfg.paper_index_path) - with FileLock(cfg.faiss_lock): - faiss_save_force(paper_index, cfg.paper_index_path) - - # Create chunk index (FLAT or IVF-PQ based on config) - if cfg.chunks_index == "flat": - chunk_base = flat_ip_index(chunk_dim) - else: # ivfpq (default) - m_safe = safe_pq_m(chunk_dim, cfg.pq_m) - chunk_base = ivfpq_index(chunk_dim, nlist=cfg.ivf_nlist, m=m_safe) - chunk_index = faiss.IndexIDMap2(chunk_base) - - ensure_parent(cfg.chunk_index_path) with FileLock(cfg.faiss_lock): - faiss_save_force(chunk_index, cfg.chunk_index_path) - - _eprint("[bootstrap] Empty indices created. Exiting.") + if not cfg.paper_index_path.exists(): + if cfg.papers_index == "flat": + paper_base = flat_ip_index(paper_dim) + else: + paper_base = hnsw_index( + paper_dim, M=cfg.hnsw_m, ef_construction=cfg.efconstruction, ef_search=cfg.efsearch, + ) + ensure_parent(cfg.paper_index_path) + faiss_save_force(faiss.IndexIDMap2(paper_base), cfg.paper_index_path) + if not cfg.chunk_index_path.exists(): + if cfg.chunks_index == "flat": + chunk_base = flat_ip_index(chunk_dim) + else: + m_safe = safe_pq_m(chunk_dim, cfg.pq_m) + chunk_base = ivfpq_index(chunk_dim, nlist=cfg.ivf_nlist, m=m_safe) + ensure_parent(cfg.chunk_index_path) + faiss_save_force(faiss.IndexIDMap2(chunk_base), cfg.chunk_index_path) + + _eprint("[bootstrap] FAISS indices ready.") def load_or_create_paper_index( diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index ae39b55..ca29231 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -8,14 +8,15 @@ import json import os +import sqlite3 import sys import time +from contextlib import ExitStack, nullcontext from pathlib import Path from types import SimpleNamespace -from typing import TYPE_CHECKING, Callable, Iterator, Sequence +from typing import TYPE_CHECKING, Iterator, Sequence import faiss -import numpy as np from litkit.progress import eprint as _eprint from litkit.embeddings.base import ( @@ -35,6 +36,7 @@ make_id_selector, safe_remove_ids, add_with_ids_dedup, + faiss_load, faiss_save, faiss_save_force, ) @@ -44,10 +46,14 @@ mark_in_index as db_mark_in_index, flush_pending_marks as db_flush_pending_marks, ) -from litkit.segments import ( - load_checkpoint as seg_load_checkpoint, - save_checkpoint as seg_save_checkpoint, -) +from litkit.build.publication import BatchPublication +from litkit.db.connection import batch_transaction, commit_transaction +from litkit.db.handoff import completed_checkpoint, merged_checkpoints, readable_database +from litkit.db.queries import available_citation_ids +from litkit.db.publication import read_publication +from litkit.db.schema import ensure_paper_embedding_column +from litkit.db.sharding import producer_shard_lock +from litkit.segments.metadata import verify_legacy_shard from litkit.build.helpers import ( pack_body, dedupe_papers_with_doc_ids, @@ -55,7 +61,6 @@ ) if TYPE_CHECKING: - import sqlite3 from litkit.embeddings.base import Embedder from litkit.segments import SegmentWriter, ChunkSegmentWriter @@ -82,9 +87,9 @@ def iter_tar_articles( - article_meta is the parsed ArticleMeta dict """ from litkit.progress import is_quiet - + use_parallel = parse_workers > 1 and is_uncompressed_tar(tar_path) - + if use_parallel: if not is_quiet(): _eprint(f"[scan] using parallel XML parsing ({parse_workers} workers) for {tar_path.name}") @@ -110,6 +115,37 @@ def iter_tar_articles( pass +def _find_paper(cur, pmcid, pmid, path, *, merged=False): + # Older main databases may have no embedding_text column. + fields = "p.doc_id, p.pmid, p.pmcid" if merged else "p.id, p.doc_id, p.embedding_text" + for column, value in (("pmcid", pmcid), ("pmid", pmid)): + if value: + row = cur.execute(f"SELECT {fields} FROM papers p WHERE p.{column}=? AND p.{column}<>''", + (value,)).fetchone() + if row: + return row + return cur.execute(f"SELECT {fields} FROM files f JOIN papers p ON p.id=f.paper_id WHERE f.path=?", + (path,)).fetchone() + + +def _stage_index(cur, table, index, path, ids, vectors, removed, *, rebuild): + """Stage the FAISS snapshot selected by its save throttle before committing the rows.""" + if not ids: + return index, None, 0 + if not isinstance(index, faiss.IndexIDMap2): + index = faiss.IndexIDMap2(index) + force = not index.ntotal or bool(removed) + if removed: + stale = removed if rebuild else removed.union(ids) + safe_remove_ids(index, make_id_selector(sorted(stale))) + added, ids_added = add_with_ids_dedup(index, ids, vectors, skip_dedup=rebuild or bool(removed)) + save = faiss_save_force if force else faiss_save + if (added or removed) and save(index, path): + db_mark_in_index(cur, table, [int(i) for i in ids_added]) + return index, path, added + return index, None, added + + def process_tar_files( *, tar_paths: Sequence[Path], @@ -152,11 +188,12 @@ def process_tar_files( ckpt_shard_id: int | None, # Parse workers parse_workers: int, + _producer_locked: bool = False, ) -> tuple[faiss.Index, faiss.Index, int, int]: """Process tar files and ingest articles into DB and indices. - + This is the main tar processing loop extracted from cli.py's build_or_update_indices(). - + Args: tar_paths: Sequence of tar file paths to process conn: SQLite connection (already open) @@ -188,24 +225,27 @@ def process_tar_files( chunk_overlap: Overlap characters between chunks ckpt_shard_id: Shard ID for per-shard checkpoints (None for shared) parse_workers: Number of parallel XML parsing workers - + Returns: Tuple of (paper_index, chunk_index, papers_added_total, chunks_added_total) Indices may be wrapped in IDMap2 during processing. + + A failed FAISS write can partially mutate a nonempty index. Discard those + handles and reopen the saved indexes before retrying. The writer CLI also + reconciles and backfills any earlier batches whose saves were throttled. """ cur = conn.cursor() - + supplied_indexes = (paper_index, chunk_index) + # A batch that spilled from the page cache to the database file would hold an # EXCLUSIVE lock until its commit, locking searches out through the embedding. Keep - # it in memory until the next flush, checkpoint or tar boundary commits it (#13). A - # producer's tar can be large, and no one else reads its shard database. + # it in memory until the batch commits (#13). A producer's tar can be large, and no + # one else reads its shard database. if not embed_producer: conn.execute("PRAGMA cache_spill=OFF") - # Load checkpoint - ckpt = seg_load_checkpoint(ckpt_path, shard_id=ckpt_shard_id) - ckpt_stream = ckpt.get("build_stream", {}) - + if embed_producer and (paper_seg_writer is None or chunk_seg_writer is None): + raise ValueError("Producer mode requires paper and chunk segment writers") # Buffers for batch processing paper_ids_buf: list[int] = [] paper_texts_buf: list[str] = [] @@ -214,57 +254,182 @@ def process_tar_files( chunk_texts_buf: list[str] = [] chunk_paper_doc_ids_buf: list[str] = [] # Track parent paper doc_ids for chunks chunk_ords_buf: list[int] = [] # Track chunk ordinals within papers - + papers_added_total = 0 chunks_added_total = 0 - - # Per-cycle timing instrumentation - cycle_scan_start = time.time() # Reset after each batch flush - cycle_docs = 0 # Docs processed since last flush - cycle_chunks = 0 # Chunks generated since last flush - total_docs_for_avg = 0 # Total docs (for chunks/doc rolling avg) - total_chunks_for_avg = 0 # Total chunks (for chunks/doc rolling avg) - - for tpath in tar_paths: + + replaced_papers: set[int] = set() + replaced_chunks: set[int] = set() + revised_shard_papers: set[int] = set() + + def flush_batch(tar: str, members: int) -> None: + nonlocal paper_index, chunk_index, papers_added_total, chunks_added_total + if not (paper_ids_buf or chunk_ids_buf): + if publication.token is not None: + publication.discard_uncommitted() + commit_transaction(conn) + publication.checkpoint_tar(tar, members) + return + + pids, texts, doc_ids = dedupe_papers_with_doc_ids( + paper_ids_buf, paper_texts_buf, paper_doc_ids_buf, keep_last=True + ) + cids, passages, parents, ords = dedupe_chunks_with_doc_ids( + chunk_ids_buf, chunk_texts_buf, chunk_paper_doc_ids_buf, chunk_ords_buf + ) + if replaced_chunks: + current = [ + (i, t, d, o) + for i, t, d, o in zip(cids, passages, parents, ords, strict=True) + if i not in replaced_chunks + ] + cids, passages, parents, ords = map(list, zip(*current, strict=True)) + + papers_added, chunks_added = len(pids), len(cids) + if embed_producer or faiss_writer: + embed_start = time.monotonic() + xp = paper_embedder.encode( + texts, + progress_label=f"Embedding papers (batch of {len(texts)})", + batch_size=paper_embed_bs, + progress_done_summary=False, + ) if pids else None + xc = chunk_embedder.encode( + passages, + progress_label=f"Embedding chunks (batch of {len(passages)})", + batch_size=chunk_embed_bs, + progress_done_summary=False, + ) + write_start = time.monotonic() + + if embed_producer: + # Chunk rowids increase across commits, including when a revision + # replaces old rows. The checkpoint also survives shard handoff. + sequence = max(max(cids, default=0), publication.checkpoint.get("segment_sequence", 0) + 1) + if revised_shard_papers: + # Only replay metadata for revisions produced since the last + # merge. A retained shard may be merged more than once. + conn.execute("CREATE TABLE IF NOT EXISTS producer_revisions " + "(paper_id INTEGER PRIMARY KEY, sequence INTEGER NOT NULL)") + conn.executemany("INSERT OR REPLACE INTO producer_revisions VALUES (?, ?)", + ((pid, sequence) for pid in revised_shard_papers)) + + def stage_segments(paper_dir, chunk_dir): + return ( + paper_seg_writer.stage(paper_dir, doc_ids=doc_ids, vecs=xp, sequence=sequence, texts=texts) + if pids else None, + chunk_seg_writer.stage(chunk_dir, paper_doc_ids=parents, ords=ords, vecs=xc, + sequence=sequence, texts=passages) if cids else None, + ) + + publication.publish(tar, members, stage_segments) + _eprint( + f"[cycle] docs={len(pids)} chunks={len(cids)} | " + f"embed={write_start - embed_start:.1f}s publish={time.monotonic() - write_start:.2f}s" + ) + elif faiss_writer: + touched_indexes = [] + + def stage_indexes(paper_dir, chunk_dir): + nonlocal paper_index, chunk_index, papers_added, chunks_added + if pids: + touched_indexes.append((supplied_indexes[0], paper_index, paper_index.ntotal)) + paper_index, paper_file, papers_added = _stage_index( + cur, + "papers", + paper_index, + paper_dir / paper_index_path.name, + pids, + xp, + replaced_papers, + rebuild=rebuild, + ) + if cids: + touched_indexes.append((supplied_indexes[1], chunk_index, chunk_index.ntotal)) + chunk_index, chunk_file, chunks_added = _stage_index( + cur, + "chunks", + chunk_index, + chunk_dir / chunk_index_path.name, + cids, + xc, + replaced_chunks, + rebuild=rebuild, + ) + return paper_file, chunk_file + + with FileLock(db_lock), FileLock(faiss_lock): + try: + publication.publish(tar, members, stage_indexes) + except BaseException: + # FAISS has no rollback for a partially modified HNSW or + # IVF index. Never accept those handles for another batch. + for supplied, working, count in touched_indexes: + if count == 0: + working.reset() + else: + supplied._litkit_failed_batch = True + raise + else: + commit_transaction(conn) + publication.checkpoint_tar(tar, members) + papers_added_total += papers_added + chunks_added_total += chunks_added + for buf in ( + paper_ids_buf, + paper_texts_buf, + paper_doc_ids_buf, + chunk_ids_buf, + chunk_texts_buf, + chunk_paper_doc_ids_buf, + chunk_ords_buf, + ): + buf.clear() + replaced_papers.clear() + replaced_chunks.clear() + revised_shard_papers.clear() + + def process_tar(tpath: Path) -> None: + rebuilding_tar = str(tpath) in rebuild_tars # Number of *persisted* members previously processed for this tar shard start_persisted = int(ckpt_stream.get(str(tpath), 0)) processed_count = start_persisted # increments after each successfully handled member persisted_count = start_persisted # last value safely fsynced via commit + checkpoint - + # Set LITKIT_TAR_PRESCAN=0 to skip counting members total_members = ( count_tar_xml_members(tpath) if os.environ.get("LITKIT_TAR_PRESCAN", "1") == "1" else None ) - + if total_members is not None: _eprint( f"[scan] shard {tpath} (resume=#{start_persisted}{'' if total_members is None else f', total≈{total_members}'})" ) - + # ---- compact single-line progress for large shards ---- start_ts = time.time() last_render = 0.0 render_every = TAR_RENDER_SEC render_pct_step = TAR_RENDER_PCT_STEP next_pct = 0.0 # next threshold to print (0, 1, 2, ... if step=1) - + # For instantaneous rate calculation last_render_count = start_persisted last_render_ts = start_ts - + def _render(force: bool = False): nonlocal last_render, next_pct, last_render_count, last_render_ts now = time.time() done = processed_count - + # time gate if not force and (now - last_render) < render_every: # allow percent gate to break the time gate if we crossed a threshold if not (render_pct_step > 0 and total_members): return - + # percent gate (optional) if (not force) and render_pct_step > 0 and total_members: cur_pct = 100.0 * done / max(1, total_members) @@ -272,10 +437,10 @@ def _render(force: bool = False): return while cur_pct + 1e-9 >= next_pct: next_pct += render_pct_step - + elapsed = max(1e-3, now - start_ts) avg_rate = done / elapsed - + # Instantaneous rate from delta since last render delta_time = now - last_render_ts delta_count = done - last_render_count @@ -283,7 +448,7 @@ def _render(force: bool = False): inst_rate = delta_count / delta_time else: inst_rate = avg_rate # Fall back if no meaningful delta - + total_str = str(total_members) if total_members is not None else "?" pct_str = f" ({100.0*done/total_members:.1f}%)" if total_members else "" msg = ( @@ -295,594 +460,323 @@ def _render(force: bool = False): _progress_newline(sys.stderr) _progress_write(msg, sys.stderr) _progress_newline(sys.stderr) - + # Update tracking for next instantaneous calculation last_render_count = done last_render_ts = now last_render = now - + # show initial 0/N state (or ? if unknown) _render(force=True) - + # Skip exactly 'start_persisted' members (they are guaranteed persisted) skipped = 0 - + # Use iter_tar_articles for parallel XML parsing (--parse-workers) - for m, meta in iter_tar_articles(tpath, parse_workers=parse_workers): - if skipped < start_persisted: - skipped += 1 - if skipped == start_persisted: - _render(force=True) # render resume point - continue - - f = f"tar://{tpath}!/{m.name}" - st = SimpleNamespace( - st_size=int(getattr(m, "size", 0)), - st_mtime=float(getattr(m, "mtime", 0.0) or 0.0), - ) - - # ═══════════════════════════════════════════════════════════════════ - # FAST PATH - No savepoint overhead for already-processed or unparsable - # ═══════════════════════════════════════════════════════════════════ - - # inline heartbeat/progress refresh - _render() - - # Fast path 1: already processed (vast majority in --update mode) - if not rebuild and db_already_processed(cur, str(f), st): - processed_count += 1 - continue - - # Fast path 2: unparsable XML (meta is None) - if meta is None: - processed_count += 1 - continue - - # ═══════════════════════════════════════════════════════════════════ - # SLOW PATH - Savepoint-protected writes - # ═══════════════════════════════════════════════════════════════════ - - handled_ok = False - - # Snapshot buffer lengths BEFORE processing so we can truncate on rollback - buf_snapshot = ( - len(paper_ids_buf), - len(paper_texts_buf), - len(paper_doc_ids_buf), - len(chunk_ids_buf), - len(chunk_texts_buf), - len(chunk_paper_doc_ids_buf), - len(chunk_ords_buf), - ) - - # Every member since the last commit shares one transaction (#13). A - # SAVEPOINT that opened the transaction would commit this member alone at - # its RELEASE, and no commit or rollback below could include or undo it. - if not conn.in_transaction: - conn.execute("BEGIN") - conn.execute("SAVEPOINT member_sp") - try: - # ---------- BEGIN INGEST BODY ---------- - pmcid = (meta["pmcid"] or "").strip() - pmid = (meta["pmid"] or "").strip() - - # Content-addressed doc_id: use DB's canonical doc_id when reusing - # an existing paper row. - existing_row = None - if pmcid: - existing_row = cur.execute( - "SELECT id, doc_id FROM papers WHERE pmcid=?", (pmcid,) - ).fetchone() - if (existing_row is None) and pmid: - existing_row = cur.execute( - "SELECT id, doc_id FROM papers WHERE pmid=?", (pmid,) - ).fetchone() - - if existing_row: - pid, existing_doc_id = existing_row - if existing_doc_id: - canon_doc_id = existing_doc_id + with batch_transaction(conn): + for m, meta in iter_tar_articles(tpath, parse_workers=parse_workers): + if skipped < start_persisted: + skipped += 1 + if skipped == start_persisted: + _render(force=True) # render resume point + continue + + f = f"tar://{tpath}!/{m.name}" + st = SimpleNamespace( + st_size=int(getattr(m, "size", 0)), + st_mtime=float(getattr(m, "mtime", 0.0) or 0.0), + ) + + # ═══════════════════════════════════════════════════════════════════ + # FAST PATH - No savepoint overhead for already-processed or unparsable + # ═══════════════════════════════════════════════════════════════════ + + # inline heartbeat/progress refresh + _render() + + # Fast path 1: already processed (vast majority in --update mode) + if not rebuilding_tar: + known = db_already_processed(cur, f, st) + if not known and merged is not None and db_already_processed(merged, f, st, require_indexed=True): + known = not cur.execute("SELECT 1 FROM files WHERE path=?", (f,)).fetchone() + if known: + processed_count += 1 + continue + + # Fast path 2: unparsable XML (meta is None) + if meta is None: + processed_count += 1 + continue + + # ═══════════════════════════════════════════════════════════════════ + # SLOW PATH - Savepoint-protected writes + # ═══════════════════════════════════════════════════════════════════ + + # Snapshot buffer lengths BEFORE processing so we can truncate on rollback + buf_snapshot = ( + len(paper_ids_buf), + len(paper_texts_buf), + len(paper_doc_ids_buf), + len(chunk_ids_buf), + len(chunk_texts_buf), + len(chunk_paper_doc_ids_buf), + len(chunk_ords_buf), + ) + + if embed_producer or faiss_writer: + publication.reserve() + if not conn.in_transaction: + conn.execute("BEGIN") + conn.execute("SAVEPOINT member_sp") + try: + # ---------- BEGIN INGEST BODY ---------- + pmcid = (meta["pmcid"] or "").strip() + pmid = (meta["pmid"] or "").strip() + + # Content-addressed doc_id: use DB's canonical doc_id when reusing + # an existing paper row. + existing_row = _find_paper(cur, pmcid, pmid, f) + canonical = None + if existing_row is None and merged is not None: + canonical = _find_paper(merged, pmcid, pmid, f, merged=True) + if canonical: + doc_id, known_pmid, known_pmcid = canonical + pmid, pmcid = known_pmid or pmid, known_pmcid or pmcid + existing_row = cur.execute( + "SELECT id, doc_id, embedding_text FROM papers WHERE doc_id=? AND doc_id<>''", + (doc_id,), + ).fetchone() + if existing_row is None: + # A retained shard can know this paper under another + # archive path and only one of its two citation IDs. + local = _find_paper(cur, known_pmcid, known_pmid, doc_id) + if local: + owner = _find_paper(merged, None, None, local[1], merged=True) + if owner is None or owner[0] == doc_id: + existing_row = local + + if existing_row: + pid, existing_doc_id, previous_text = existing_row + if existing_doc_id: + canon_doc_id = existing_doc_id + else: + canon_doc_id = str(f) + cur.execute( + "UPDATE papers SET doc_id = ? WHERE id = ?", + (canon_doc_id, pid) + ) else: - canon_doc_id = str(f) + canon_doc_id = canonical[0] if canonical and canonical[0] else f + shard_revision = embed_producer and (existing_row is not None or canonical is not None) + if shard_revision: + pmid, pmcid = available_citation_ids(canon_doc_id, pmid, pmcid, cur, merged) + if not existing_row: cur.execute( - "UPDATE papers SET doc_id = ? WHERE id = ?", - (canon_doc_id, pid) + "INSERT INTO papers(doc_id, pmid, pmcid, title, abstract, source_path) VALUES (?,?,?,?,?,?)", + (canon_doc_id, pmid, pmcid, meta["title"], meta["abstract"], meta.get("source_path")), ) - else: - # New paper: use current path as canonical doc_id - canon_doc_id = str(f) - cur.execute( - "INSERT INTO papers(doc_id, pmid, pmcid, title, abstract, source_path) VALUES (?,?,?,?,?,?)", - (canon_doc_id, pmid, pmcid, meta["title"], meta["abstract"], meta.get("source_path")), + pid = cur.lastrowid + + seen_this_path = ( + cur.execute("SELECT 1 FROM files WHERE path=?", (str(f),)).fetchone() + is not None ) - pid = cur.lastrowid - - seen_this_path = ( - cur.execute("SELECT 1 FROM files WHERE path=?", (str(f),)).fetchone() - is not None - ) - if seen_this_path: - if faiss_writer: - with FileLock(faiss_lock): - if not isinstance(paper_index, faiss.IndexIDMap2): - paper_index = faiss.IndexIDMap2(paper_index) - selp = make_id_selector([pid]) - safe_remove_ids(paper_index, selp) - faiss_save_force(paper_index, paper_index_path) - - old_ids = [ - row[0] - for row in cur.execute( - "SELECT id FROM chunks WHERE paper_id=?", (pid,) - ) - ] - if old_ids: - with FileLock(faiss_lock): - if not isinstance(chunk_index, faiss.IndexIDMap2): - chunk_index = faiss.IndexIDMap2(chunk_index) - selc = make_id_selector(old_ids) - safe_remove_ids(chunk_index, selc) - faiss_save_force(chunk_index, chunk_index_path) - with FileLock(db_lock): + old_ids = [] + if seen_this_path or (shard_revision and existing_row): + old_ids = [row[0] for row in cur.execute( + "SELECT id FROM chunks WHERE paper_id=?", (pid,) + )] cur.execute("DELETE FROM chunks WHERE paper_id=?", (pid,)) cur.execute("UPDATE papers SET in_index=0 WHERE id=?", (pid,)) - - db_register_file(cur, str(f), pid, st) - - ta = (meta["title"] or "").strip() - ab = (meta["abstract"] or "").strip() - ta_ab = (ta + " " + ab).strip() or ( - meta["paragraphs"][0][:800] if meta["paragraphs"] else "untitled" - ) - paper_ids_buf.append(pid) - paper_texts_buf.append(ta_ab) - paper_doc_ids_buf.append(canon_doc_id) - - body = pack_body(meta, chunk_target_chars, chunk_min_chars, chunk_overlap) - proposed_chunks = [(-1, ta_ab, None)] if ta_ab else [] - proposed_chunks.extend((i, text, page) for i, (text, page) in enumerate(body)) - - for ord_i, text_i, page in proposed_chunks: - cur.execute( - "INSERT INTO chunks(paper_id, ord, text, page) VALUES (?,?,?,?)", - (pid, ord_i, text_i, page), + + db_register_file(cur, str(f), pid, st) + + ta = (meta["title"] or "").strip() + ab = (meta["abstract"] or "").strip() + ta_ab = (ta + " " + ab).strip() or ( + meta["paragraphs"][0][:800] if meta["paragraphs"] else "untitled" ) - cid = cur.lastrowid - chunk_ids_buf.append(cid) - chunk_texts_buf.append(text_i) - chunk_paper_doc_ids_buf.append(canon_doc_id) - chunk_ords_buf.append(ord_i) - - # ---------- END INGEST BODY ---------- - - handled_ok = True - - # Track docs and chunks for cycle timing - cycle_docs += 1 - - # Release savepoint on success - conn.execute("RELEASE SAVEPOINT member_sp") - - except Exception as e: - _eprint(f"[ingest] ERROR tar://{tpath}!/{m.name}: {e.__class__.__name__}: {e}") - # Rollback ONLY this member's changes via savepoint - try: - conn.execute("ROLLBACK TO SAVEPOINT member_sp") - conn.execute("RELEASE SAVEPOINT member_sp") - except Exception: - pass - if not conn.in_transaction: - # SQLite rolled back the whole transaction (disk full, I/O error): - # the members before this one are gone but still in the buffers - raise - - # Truncate in-memory buffers back to pre-member state - (p_len, pt_len, pd_len, c_len, ct_len, cp_len, co_len) = buf_snapshot - del paper_ids_buf[p_len:] - del paper_texts_buf[pt_len:] - del paper_doc_ids_buf[pd_len:] - del chunk_ids_buf[c_len:] - del chunk_texts_buf[ct_len:] - del chunk_paper_doc_ids_buf[cp_len:] - del chunk_ords_buf[co_len:] - - if strict_ingest: - raise - - # Mark-and-skip: log failure and continue - try: - failure_log = sqlite_dir / "ingest_failures.jsonl" - failure_entry = { - "tar": str(tpath), - "member": m.name, - "error": f"{e.__class__.__name__}: {e}", - "ts": int(time.time()), - } - with open(failure_log, "a", encoding="utf-8") as ff: - ff.write(json.dumps(failure_entry) + "\n") - except Exception as log_err: - _eprint(f"[ingest] WARNING: could not log failure: {log_err}") - - _eprint(f"[ingest] SKIP: {m.name} (use --strict-ingest to fail fast)") - handled_ok = True - - # ═══════════════════════════════════════════════════════════════════ - # BATCH FLUSH - OUTSIDE SAVEPOINT REGION - # ═══════════════════════════════════════════════════════════════════ - - if handled_ok: - processed_count += 1 - - if handled_ok and len(paper_ids_buf) >= paper_batch: - u_ids, u_texts, u_doc_ids = dedupe_papers_with_doc_ids( - paper_ids_buf, paper_texts_buf, paper_doc_ids_buf - ) - - if paper_seg_writer is not None: - # Producer mode: embed and write segments - try: - Xp = paper_embedder.encode( - u_texts, - progress_label=f"Embedding papers (producer, {len(u_texts)})", - batch_size=paper_embed_bs, - progress_done_summary=False, - ) - paper_seg_writer.write(doc_ids=u_doc_ids, vecs=Xp) - papers_added_total += len(u_ids) - # No commit or checkpoint until the tar-boundary finalize(): this - # segment is pending, and cleanup_pending() deletes it if that - # fails, so its rows must roll back with it (#3, #13) - except Exception as e: - conn.rollback() - _eprint(f"[flush] FATAL: paper segment flush failed: {e.__class__.__name__}: {e}") - raise - - elif faiss_writer: - # Writer mode: embed and update FAISS - try: - Xp = paper_embedder.encode( - u_texts, - progress_label=f"Embedding papers (batch of {len(u_texts)})", - batch_size=paper_embed_bs, - progress_done_summary=False, - ) - # Commit the rows before a save can write their vectors: rolled - # back, they would get the same ids on the restart, and the HNSW - # paper index can't remove the first copy (#13) - conn.commit() - prior_ntotal = int(getattr(paper_index, "ntotal", 0) or 0) - with FileLock(faiss_lock): - # skip_dedup=rebuild: in rebuild mode, index starts empty, no dedup needed - added, ids_added = add_with_ids_dedup(paper_index, u_ids, Xp, skip_dedup=rebuild) - saved = False - if added: - if prior_ntotal == 0: - saved = faiss_save_force(paper_index, paper_index_path) - else: - saved = faiss_save(paper_index, paper_index_path) - if added: - if saved: - with FileLock(db_lock): - db_mark_in_index(cur, "papers", [int(i) for i in ids_added]) - db_flush_pending_marks(cur) - conn.commit() - papers_added_total += int(added) - except Exception as e: - conn.rollback() - _eprint(f"[flush] FATAL: paper FAISS flush failed: {e.__class__.__name__}: {e}") - raise - - else: - conn.commit() - papers_added_total += len(u_ids) - - paper_ids_buf.clear() - paper_texts_buf.clear() - paper_doc_ids_buf.clear() - - if handled_ok and len(chunk_ids_buf) >= chunk_batch: - # --- CYCLE TIMING: capture scan phase duration --- - t_scan = time.time() - cycle_scan_start - - u_ids, u_texts, u_paper_doc_ids, u_ords = dedupe_chunks_with_doc_ids( - chunk_ids_buf, chunk_texts_buf, chunk_paper_doc_ids_buf, chunk_ords_buf - ) - - if chunk_seg_writer is not None: - # Producer mode: embed and write segments - try: - t_embed_start = time.time() - Xc = chunk_embedder.encode( - u_texts, - progress_label=f"Embedding chunks (producer, {len(u_texts)})", - batch_size=chunk_embed_bs, - progress_done_summary=False, + # Rebuilds keep the first canonical paper embedding, including + # when an alias arrives after its original batch was published. + # Updates still embed revised text received under a new path. + reuse_embedding = False + if existing_row: + if previous_text is None and not seen_this_path: + prior = cur.execute( + "SELECT text FROM chunks WHERE paper_id=? AND ord=-1 ORDER BY id DESC LIMIT 1", + (pid,), + ).fetchone() + previous_text = prior[0] if prior else None + reuse_embedding = (not seen_this_path and previous_text is not None + and (rebuilding_tar or previous_text == ta_ab)) + cur.execute( + "UPDATE papers SET embedding_text=? WHERE id=?", + (previous_text if reuse_embedding else ta_ab, pid), ) - t_embed = time.time() - t_embed_start - - t_seg_start = time.time() - chunk_seg_writer.write( - paper_doc_ids=u_paper_doc_ids, ords=u_ords, vecs=Xc + # Another shard may have installed a different version + # since this retained shard last embedded the paper. + if not reuse_embedding or shard_revision: + paper_ids_buf.append(pid) + paper_texts_buf.append(previous_text if reuse_embedding else ta_ab) + paper_doc_ids_buf.append(canon_doc_id) + if shard_revision: + cur.execute( + "UPDATE papers SET title=?, abstract=?, source_path=?, embedding_text=?, " + "pmid=COALESCE(NULLIF(pmid,''),?), pmcid=COALESCE(NULLIF(pmcid,''),?) WHERE id=?", + (meta["title"], meta["abstract"], meta.get("source_path"), + previous_text if reuse_embedding else ta_ab, pmid, pmcid, pid), ) - t_seg = time.time() - t_seg_start - - chunks_added_total += len(u_ids) - # No commit or checkpoint until the tar-boundary finalize(): this - # segment is pending, and cleanup_pending() deletes it if that - # fails, so its rows must roll back with it (#3, #13) - - # --- CYCLE TIMING: emit summary --- - total_docs_for_avg += cycle_docs - total_chunks_for_avg += len(u_ids) - if total_docs_for_avg > 0: - avg_cpd = total_chunks_for_avg / total_docs_for_avg - else: - avg_cpd = 0.0 - _eprint( - f"[cycle] docs={cycle_docs} chunks={len(u_ids)} | " - f"scan={t_scan:.1f}s embed={t_embed:.1f}s " - f"seg={t_seg:.2f}s | " - f"chunks/doc={avg_cpd:.1f}" + + body = pack_body(meta, chunk_target_chars, chunk_min_chars, chunk_overlap) + proposed_chunks = [(-1, ta_ab, None)] if ta_ab else [] + proposed_chunks.extend((i, text, page) for i, (text, page) in enumerate(body)) + + for ord_i, text_i, page in proposed_chunks: + cur.execute( + "INSERT INTO chunks(paper_id, ord, text, page) VALUES (?,?,?,?)", + (pid, ord_i, text_i, page), ) - # Reset cycle tracking - cycle_scan_start = time.time() - cycle_docs = 0 - cycle_chunks = 0 - except Exception as e: - conn.rollback() - _eprint(f"[flush] FATAL: chunk segment flush failed: {e.__class__.__name__}: {e}") + cid = cur.lastrowid + chunk_ids_buf.append(cid) + chunk_texts_buf.append(text_i) + chunk_paper_doc_ids_buf.append(canon_doc_id) + chunk_ords_buf.append(ord_i) + + # ---------- END INGEST BODY ---------- + + conn.execute("RELEASE SAVEPOINT member_sp") + if existing_row and not reuse_embedding: + # A saved ID alone cannot distinguish two revisions after restart. + replaced_papers.add(pid) + replaced_chunks.update(old_ids) + if shard_revision: + revised_shard_papers.add(pid) + + except Exception as e: + _eprint(f"[ingest] ERROR tar://{tpath}!/{m.name}: {e.__class__.__name__}: {e}") + if not conn.in_transaction: + # SQLite rolled back the whole batch (disk full, I/O error): the + # members before this one are gone but still in the buffers (#13) raise - - elif faiss_writer: - # Writer mode: embed and update FAISS - try: - Xc = chunk_embedder.encode( - u_texts, - progress_label=f"Embedding chunks (batch of {len(u_texts)})", - batch_size=chunk_embed_bs, - progress_done_summary=False, - ) - # Commit the rows before a save can write their vectors, as for - # papers: every vector a save writes then has a committed row (#13) - conn.commit() - prior_ntotal = int(getattr(chunk_index, "ntotal", 0) or 0) - with FileLock(faiss_lock): - # skip_dedup=rebuild: in rebuild mode, index starts empty, no dedup needed - added, ids_added = add_with_ids_dedup(chunk_index, u_ids, Xc, skip_dedup=rebuild) - saved = False - if added: - if prior_ntotal == 0: - saved = faiss_save_force(chunk_index, chunk_index_path) - else: - saved = faiss_save(chunk_index, chunk_index_path) - if added: - if saved: - with FileLock(db_lock): - db_mark_in_index(cur, "chunks", [int(i) for i in ids_added]) - db_flush_pending_marks(cur) - conn.commit() - chunks_added_total += int(added) - except Exception as e: - conn.rollback() - _eprint(f"[flush] FATAL: chunk FAISS flush failed: {e.__class__.__name__}: {e}") + # Rollback ONLY this member's changes via savepoint + conn.execute("ROLLBACK TO SAVEPOINT member_sp") + conn.execute("RELEASE SAVEPOINT member_sp") + + # Truncate in-memory buffers back to pre-member state + (p_len, pt_len, pd_len, c_len, ct_len, cp_len, co_len) = buf_snapshot + del paper_ids_buf[p_len:] + del paper_texts_buf[pt_len:] + del paper_doc_ids_buf[pd_len:] + del chunk_ids_buf[c_len:] + del chunk_texts_buf[ct_len:] + del chunk_paper_doc_ids_buf[cp_len:] + del chunk_ords_buf[co_len:] + + if strict_ingest: raise - - else: - conn.commit() - chunks_added_total += len(u_ids) - - chunk_ids_buf.clear() - chunk_texts_buf.clear() - chunk_paper_doc_ids_buf.clear() - chunk_ords_buf.clear() - - # Update progress & checkpoint only after a successful handle - if handled_ok: - _render() - - # Persist every ckpt_every handled members - if (processed_count - persisted_count) >= ckpt_every: - if embed_producer: - pass # Producer checkpoints only after the tar-boundary finalize() - else: - conn.commit() - ckpt_stream[str(tpath)] = processed_count - ckpt["build_stream"] = ckpt_stream - seg_save_checkpoint(ckpt, ckpt_path, ckpt_lock, shard_id=ckpt_shard_id) - persisted_count = processed_count - _render(force=True) - - # End of this tar: force flush remainder buffers + checkpoint + + # Mark-and-skip: log failure and continue + try: + failure_log = sqlite_dir / "ingest_failures.jsonl" + failure_entry = { + "tar": str(tpath), + "member": m.name, + "error": f"{e.__class__.__name__}: {e}", + "ts": int(time.time()), + } + with open(failure_log, "a", encoding="utf-8") as ff: + ff.write(json.dumps(failure_entry) + "\n") + except Exception as log_err: + _eprint(f"[ingest] WARNING: could not log failure: {log_err}") + + _eprint(f"[ingest] SKIP: {m.name} (use --strict-ingest to fail fast)") + + processed_count += 1 + # Both kinds belong to the same articles and SQLite transaction. + if ( + len(paper_ids_buf) >= paper_batch + or len(chunk_ids_buf) >= chunk_batch + or (not embed_producer and processed_count - persisted_count >= ckpt_every) + ): + flush_batch(str(tpath), processed_count) + persisted_count = processed_count + _render(force=True) + + if processed_count != persisted_count or str(tpath) not in ckpt_stream: + flush_batch(str(tpath), processed_count) _render(force=True) _progress_newline(sys.stderr) - - # ═══════════════════════════════════════════════════════════════════ - # PRODUCER MODE: Two-phase durability for tar-boundary flush - # ═══════════════════════════════════════════════════════════════════ - if embed_producer: - try: - # Phase 1: Write all segments to .pending files - if paper_ids_buf: - u_ids, u_texts, u_doc_ids = dedupe_papers_with_doc_ids( - paper_ids_buf, paper_texts_buf, paper_doc_ids_buf - ) - Xp = paper_embedder.encode( - u_texts, - progress_label=f"Embedding papers (producer tar-boundary, {len(u_texts)})", - batch_size=paper_embed_bs, - progress_done_summary=False, - ) - paper_seg_writer.write(doc_ids=u_doc_ids, vecs=Xp) - papers_added_total += len(u_ids) - paper_ids_buf.clear() - paper_texts_buf.clear() - paper_doc_ids_buf.clear() - - if chunk_ids_buf: - u_ids, u_texts, u_paper_doc_ids, u_ords = dedupe_chunks_with_doc_ids( - chunk_ids_buf, chunk_texts_buf, chunk_paper_doc_ids_buf, chunk_ords_buf - ) - Xc = chunk_embedder.encode( - u_texts, - progress_label=f"Embedding chunks (producer tar-boundary, {len(u_texts)})", - batch_size=chunk_embed_bs, - progress_done_summary=False, - ) - chunk_seg_writer.write( - paper_doc_ids=u_paper_doc_ids, ords=u_ords, vecs=Xc - ) - chunks_added_total += len(u_ids) - chunk_ids_buf.clear() - chunk_texts_buf.clear() - chunk_paper_doc_ids_buf.clear() - chunk_ords_buf.clear() - - # Phase 2: Commit DB: this tar's rows, all in one transaction (#13) - conn.commit() - - # Phase 3: Finalize segments (atomic rename .pending → .npz) - paper_seg_writer.finalize() - chunk_seg_writer.finalize() - - persisted_count = processed_count - - except Exception as e: - # Compensating transaction: clean up any .pending files - paper_seg_writer.cleanup_pending() - chunk_seg_writer.cleanup_pending() - conn.rollback() - _eprint(f"[flush] FATAL: producer tar-boundary flush failed: {e.__class__.__name__}: {e}") - raise - else: - conn.commit() - - # Checkpoint: now safe for both modes + + # Different shards can run in parallel. Two starts of the same shard must + # serialize recovery, scanning, and publication against the same checkpoint. + owner_lock = ( + producer_shard_lock(sqlite_dir, ckpt_shard_id, FileLock, database_open=True) + if embed_producer and not _producer_locked else nullcontext() + ) + with owner_lock, ExitStack() as readers: + merged = None + ensure_paper_embedding_column(conn) + publication = BatchPublication( + conn, + ckpt_path, + ckpt_lock, + ckpt_shard_id, + paper_seg_writer.outdir if embed_producer else paper_index_path.parent, + chunk_seg_writer.outdir if embed_producer else chunk_index_path.parent, + ) if embed_producer: - ckpt_stream[str(tpath)] = persisted_count - else: - ckpt_stream[str(tpath)] = processed_count - ckpt["build_stream"] = ckpt_stream - seg_save_checkpoint(ckpt, ckpt_path, ckpt_lock, shard_id=ckpt_shard_id) - - # ═══════════════════════════════════════════════════════════════════════ - # FINAL BUFFER FLUSH - After all tars processed - # ═══════════════════════════════════════════════════════════════════════ - # Writer mode may have remaining items in buffers; producer mode - # should be empty after tar-boundary flush but handle for safety. - - if faiss_writer: - if paper_ids_buf: - u_ids, u_texts, _ = dedupe_papers_with_doc_ids( - paper_ids_buf, paper_texts_buf, paper_doc_ids_buf + main_path = Path(os.environ.get("LITKIT_MERGED_DB", sqlite_dir / "litkit.sqlite3")) + main_db = None + shard_path = conn.execute("PRAGMA database_list").fetchone()[2] + if main_path.is_file() and str(main_path.resolve()) != shard_path: + main_db = readers.enter_context(readable_database(main_path)) + has_files = main_db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='files'").fetchone() + if has_files and main_db.execute("SELECT 1 FROM files LIMIT 1").fetchone(): + merged = main_db.cursor() + producer_id = paper_seg_writer.shard_id + publication.bind_producer_outputs(merged_checkpoints(main_db, producer_id).get(producer_id)) + verify_legacy_shard( + conn, paper_seg_writer.shard_id, + paper_seg_writer.outdir, chunk_seg_writer.outdir, merged_db=main_db, ) - Xp = paper_embedder.encode( - u_texts, - progress_label=f"Embedding papers (batch of {len(u_texts)})", - batch_size=paper_embed_bs, - progress_done_summary=False, - ) - if not isinstance(paper_index, faiss.IndexIDMap2): - paper_index = faiss.IndexIDMap2(paper_index) - - with FileLock(db_lock), FileLock(faiss_lock): - prior_ntotal = int(getattr(paper_index, "ntotal", 0) or 0) - # skip_dedup=rebuild: in rebuild mode, index starts empty, no dedup needed - added, ids_added = add_with_ids_dedup(paper_index, u_ids, Xp, skip_dedup=rebuild) - if added: - if prior_ntotal == 0: - faiss_save_force(paper_index, paper_index_path) - db_mark_in_index(cur, "papers", [int(i) for i in ids_added]) - else: - if faiss_save(paper_index, paper_index_path): - db_mark_in_index(cur, "papers", [int(i) for i in ids_added]) - db_flush_pending_marks(cur) - conn.commit() - papers_added_total += int(added) - - paper_ids_buf.clear() - paper_texts_buf.clear() - - if chunk_ids_buf: - u_ids, u_texts, _, _ = dedupe_chunks_with_doc_ids( - chunk_ids_buf, chunk_texts_buf, chunk_paper_doc_ids_buf, chunk_ords_buf - ) - Xc = chunk_embedder.encode( - u_texts, - progress_label=f"Embedding chunks (batch of {len(u_texts)})", - batch_size=chunk_embed_bs, - progress_done_summary=False, - ) - if not isinstance(chunk_index, faiss.IndexIDMap2): - chunk_index = faiss.IndexIDMap2(chunk_index) - - with FileLock(db_lock), FileLock(faiss_lock): - prior_ntotal = int(getattr(chunk_index, "ntotal", 0) or 0) - # skip_dedup=rebuild: in rebuild mode, index starts empty, no dedup needed - added, ids_added = add_with_ids_dedup(chunk_index, u_ids, Xc, skip_dedup=rebuild) - if added: - if prior_ntotal == 0: - faiss_save_force(chunk_index, chunk_index_path) - db_mark_in_index(cur, "chunks", [int(i) for i in ids_added]) - else: - if faiss_save(chunk_index, chunk_index_path): - db_mark_in_index(cur, "chunks", [int(i) for i in ids_added]) - db_flush_pending_marks(cur) - conn.commit() - chunks_added_total += int(added) - - chunk_ids_buf.clear() - chunk_texts_buf.clear() - - elif embed_producer: - # Producer: final embed and write segment files (should be empty after tar-boundary) - if paper_ids_buf: - u_ids, u_texts, u_doc_ids = dedupe_papers_with_doc_ids( - paper_ids_buf, paper_texts_buf, paper_doc_ids_buf - ) - Xp = paper_embedder.encode( - u_texts, - progress_label=f"Embedding papers (producer, {len(u_texts)})", - batch_size=paper_embed_bs, - ) - paper_seg_writer.write(doc_ids=u_doc_ids, vecs=Xp) - conn.commit() - papers_added_total += len(u_ids) - paper_ids_buf.clear() - paper_texts_buf.clear() - paper_doc_ids_buf.clear() - - if chunk_ids_buf: - u_ids, u_texts, u_paper_doc_ids, u_ords = dedupe_chunks_with_doc_ids( - chunk_ids_buf, chunk_texts_buf, chunk_paper_doc_ids_buf, chunk_ords_buf - ) - Xc = chunk_embedder.encode( - u_texts, - progress_label=f"Embedding chunks (producer, {len(u_texts)})", - batch_size=chunk_embed_bs, - ) - chunk_seg_writer.write(paper_doc_ids=u_paper_doc_ids, ords=u_ords, vecs=Xc) - conn.commit() - chunks_added_total += len(u_ids) - chunk_ids_buf.clear() - chunk_texts_buf.clear() - chunk_paper_doc_ids_buf.clear() - chunk_ords_buf.clear() - - else: - # Plain reader: DB only - conn.commit() - papers_added_total += len(paper_ids_buf) - paper_ids_buf.clear() - paper_texts_buf.clear() - chunks_added_total += len(chunk_ids_buf) - chunk_ids_buf.clear() - chunk_texts_buf.clear() - - # Final commit - conn.commit() + # A legacy checkpoint can arrive without all of its shard rows. + # After a merge the checkpoint can also outlive its database. + # In both cases verify file records as the archives are replayed. + journal = read_publication(conn) + if (publication.checkpoint.get("build_stream") and not completed_checkpoint(conn) + and not (journal and journal.tar is not None)): + publication.checkpoint.pop("build_stream") + publication.save_checkpoint() + if embed_producer or faiss_writer: + with FileLock(faiss_lock) if faiss_writer else nullcontext(): + if publication.recover() and faiss_writer: + paper_index = faiss_load(paper_index_path) + chunk_index = faiss_load(chunk_index_path) + elif faiss_writer and any(getattr(index, "_litkit_failed_batch", False) + for index in supplied_indexes): + raise ValueError( + "A failed batch modified these FAISS handles. " + "Reopen the saved indexes before retrying, or resume with the writer CLI." + ) + ckpt_stream = publication.checkpoint.setdefault("build_stream", {}) + # A rebuild is resumed without the destructive --rebuild flag. Keep + # its revision policy for its unfinished archives, including later tars. + if rebuild and tar_paths: + publication.checkpoint["rebuild_tars"] = [str(path) for path in tar_paths] + publication.save_checkpoint() + rebuild_tars = publication.checkpoint.get("rebuild_tars", []) + + for tpath in tar_paths: + process_tar(tpath) + if str(tpath) in rebuild_tars: + rebuild_tars.remove(str(tpath)) + if not rebuild_tars: + del publication.checkpoint["rebuild_tars"] + publication.save_checkpoint() + if not embed_producer: conn.execute("PRAGMA cache_spill=ON") - + # Return indices and counts (indices may have been wrapped) return paper_index, chunk_index, papers_added_total, chunks_added_total diff --git a/src/litkit/build/publication.py b/src/litkit/build/publication.py new file mode 100644 index 0000000..8d740e7 --- /dev/null +++ b/src/litkit/build/publication.py @@ -0,0 +1,297 @@ +"""Publish a tar batch across SQLite and the filesystem, including after a restart.""" + +from __future__ import annotations + +import json +import os +import shutil +import sqlite3 +from collections.abc import Callable +from pathlib import Path +from uuid import UUID, uuid4 + +from litkit.build.helpers import maybe_fsync_dir +from litkit.db.connection import batch_transaction, commit_transaction, rollback_transaction +from litkit.db.handoff import output_markers, verify_checkpoint_revision, verify_output_markers +from litkit.db.publication import PublicationRecord, read_publication +from litkit.segments.checkpoint import load_checkpoint, save_checkpoint, shard_ckpt_path +from litkit.segments.discovery import segment_order +from litkit.segments.writer import finalized_name + + +def reset_publication(conn: sqlite3.Connection, sqlite_dir: Path, seg_dir: Path) -> None: + """Retire writer and detached shard progress while producer admission is held.""" + from litkit.db.sharding import shard_db_path + from litkit.db.handoff import completed_checkpoint, merged_checkpoints, readable_database + from litkit.segments.metadata import verify_legacy_shard + + if read_publication(conn): + conn.execute("UPDATE ingest_publication SET tar=NULL WHERE singleton=1") + for table in ("merged_paper_revisions", "obsolete_chunk_vectors"): + if conn.execute("SELECT 1 FROM sqlite_master WHERE name=?", (table,)).fetchone(): + conn.execute(f"DELETE FROM {table}") + if conn.execute("SELECT 1 FROM sqlite_master WHERE name='merged_shard_checkpoints'").fetchone(): + for (shard_id,) in conn.execute("SELECT shard_id FROM merged_shard_checkpoints").fetchall(): + checkpoint = shard_ckpt_path(sqlite_dir, shard_id) + source = shard_db_path(sqlite_dir, shard_id) + if source.exists(): + with readable_database(source) as shard: + verify_checkpoint_revision(shard, load_checkpoint(checkpoint), read_publication(shard), + merged_checkpoints(conn, shard_id).get(shard_id)) + verify_legacy_shard(shard, shard_id, seg_dir, seg_dir, before_rebuild=True) + if not completed_checkpoint(shard): + continue # Its external checkpoint can still depend on the merged receipt. + # The retained shard owns its checkpoint. Its rows will be merged + # into the new main database on the next consume. + else: + checkpoint.unlink(missing_ok=True) + # If the reset rolls back, the SQLite receipt can restore the JSON. + maybe_fsync_dir(checkpoint) + conn.execute("DELETE FROM merged_shard_checkpoints WHERE shard_id=?", (shard_id,)) + + +def _same_path(first, second): + first, second = Path(first), Path(second) + return first.resolve() == second.resolve() or (first.exists() and second.exists() and first.samefile(second)) + + +class BatchPublication: + """One reserved directory per active batch. Only its owning database cleans it.""" + + def __init__(self, conn, ckpt_path, ckpt_lock, shard_id, paper_dir, chunk_dir): + self.conn: sqlite3.Connection = conn + self.ckpt_path = ckpt_path + self.ckpt_lock = ckpt_lock + self.shard_id = shard_id + self.outputs = (Path(paper_dir).resolve(), Path(chunk_dir).resolve()) + self.checkpoint = load_checkpoint(ckpt_path, shard_id=shard_id) + self.token: str | None = None + self.producer = False + + def bind_producer_outputs(self, merged=None): + self.producer = True + record = read_publication(self.conn) + saved = verify_checkpoint_revision(self.conn, self.checkpoint, record, merged) + publishing = record.token if record and record.tar is not None else None + verify_output_markers(self.checkpoint or saved or {}, *self.outputs, publishing=publishing) + if saved and not self.checkpoint: + self.checkpoint = saved + self.save_checkpoint() + + def checkpoint_tar(self, tar: str, members: int) -> None: + if self.producer: + if "segment_output" not in self.checkpoint: + self.checkpoint["segment_output"] = self.token or uuid4().hex + if self.token is not None: + self.checkpoint["producer_revision"] = self.token + revision = self.checkpoint.get("producer_revision", "") + for marker in output_markers(self.checkpoint, *self.outputs): + if marker.is_file() and marker.read_text() == revision: + continue + marker.parent.mkdir(parents=True, exist_ok=True) + temporary = marker.with_name(marker.name + ".tmp") + with temporary.open("w") as stream: + stream.write(revision) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, marker) + maybe_fsync_dir(marker) + self.checkpoint.setdefault("build_stream", {})[tar] = members + self.checkpoint.pop("batch_reservation", None) + self.save_checkpoint() + + def save_checkpoint(self) -> None: + save_checkpoint(self.checkpoint, self.ckpt_path, self.ckpt_lock, shard_id=self.shard_id) + + def _database(self) -> str: + return self.conn.execute("PRAGMA database_list").fetchone()[2] + + def _directories(self, token: str, roots=None) -> tuple[Path, Path]: + if UUID(hex=token).hex != token: + raise ValueError("Invalid batch directory in SQLite") + paper, chunk = self.outputs if roots is None else roots + return paper / f".litkit-batch-{token}-papers", chunk / f".litkit-batch-{token}-chunks" + + def _recovery_directories(self, record, *, committed): + """Identify the private directories this connection can publish or remove.""" + roots = (Path(record.paper_root), Path(record.chunk_root)) + original = self._directories(record.token, roots) + if _same_path(self._database(), record.source_db): + if committed and not all(_same_path(a, b) for a, b in zip(self.outputs, roots, strict=True)): + raise RuntimeError("Resume this committed batch with its original paper and chunk output directories.") + return original + + independent = [] + for root, stage in zip(self.outputs, self._directories(record.token), strict=True): + shared = any(_same_path(root, other) for other in roots) or any( + _same_path(stage, other) for other in original + ) + if not shared: + independent.append(stage) + elif committed: + raise RuntimeError( + "This database copy shares staging with its original database. " + "Resume the original workspace, or use a matching copy of its segment directory." + ) + return independent + + def reserve(self) -> None: + """Record exactly which files recovery may reclaim before starting the article transaction.""" + if self.token is not None: + return + in_transaction = self.conn.in_transaction + self.conn.execute( + "CREATE TABLE IF NOT EXISTS ingest_publication (singleton INTEGER PRIMARY KEY " + "CHECK(singleton=1), token TEXT NOT NULL, source_db TEXT NOT NULL, " + "paper_root TEXT NOT NULL, chunk_root TEXT NOT NULL, " + "tar TEXT, members INTEGER, paper TEXT, chunk TEXT)" + ) + token = uuid4().hex + owner = (token, self._database(), *(str(root.resolve()) for root in self.outputs)) + if in_transaction: + # A rollback also erases the reservation inside a caller's existing + # transaction. Record ownership without advancing the member count. + self.checkpoint["batch_reservation"] = owner + self.save_checkpoint() + self.conn.execute( + "INSERT INTO ingest_publication(singleton, token, source_db, paper_root, chunk_root) " + "VALUES (1, ?, ?, ?, ?)", + owner, + ) + if self.producer and self.checkpoint.get("producer_revision"): + self.conn.execute("CREATE TABLE IF NOT EXISTS ingest_ancestors (revision TEXT PRIMARY KEY)") + self.conn.execute( + "INSERT OR IGNORE INTO ingest_ancestors VALUES (?)", (self.checkpoint["producer_revision"],) + ) + if not in_transaction: + commit_transaction(self.conn) + self.token = token + + def _retire(self): + self.conn.execute("DELETE FROM ingest_publication WHERE singleton=1") + commit_transaction(self.conn) + self.token = None + + def discard_uncommitted(self) -> None: + """Drop a reservation after an empty batch or after SQLite rolled back the articles.""" + journal = read_publication(self.conn) + record = journal + if record is None and "batch_reservation" in self.checkpoint: + record = PublicationRecord(*self.checkpoint["batch_reservation"], None, None, None, None) + if record is None: + self.token = None + return + if record.tar is not None: + raise RuntimeError("Cannot discard a committed batch awaiting publication") + # A database backup taken during ingest can contain the reservation. Its + # files may still belong to the live database in a shared --embed-outdir. + for directory in self._recovery_directories(record, committed=False): + if directory.exists(): + shutil.rmtree(directory) + if "batch_reservation" in self.checkpoint: + del self.checkpoint["batch_reservation"] + self.save_checkpoint() + if journal is not None: + self._retire() + else: + self.token = None + + def publish( + self, + tar: str, + members: int, + write: Callable[[Path, Path], tuple[Path | None, Path | None]], + ) -> None: + """Commit the rows and staged filenames together, then publish and checkpoint.""" + if self.token is None: + raise RuntimeError("Missing batch reservation") + directories = self._directories(self.token) + try: + for directory in directories: + directory.mkdir(parents=True) + maybe_fsync_dir(directory) + paper, chunk = write(*directories) + for staged in (paper, chunk): + if staged is not None: + maybe_fsync_dir(staged) + record = (tar, members, paper.name if paper else None, chunk.name if chunk else None) + self.conn.execute( + "UPDATE ingest_publication SET tar=?, members=?, paper=?, chunk=? WHERE token=?", + (*record, self.token), + ) + commit_transaction(self.conn) + except BaseException: + rollback_transaction(self.conn) + # A signal can arrive after SQLite made the commit durable. + row = read_publication(self.conn) + if row is None or row.tar is None: + self.discard_uncommitted() + raise + self._finish(directories, *record) + + def _finish(self, directories, tar, members, paper, chunk): + for directory in directories: + if not directory.is_dir(): + raise FileNotFoundError( + f"Cannot resume batch: missing staging directory {directory}" + ) + for directory, name in zip(directories, (paper, chunk), strict=True): + if name is None: + continue + if name != Path(name).name or name in (".", ".."): + raise ValueError("Invalid staged filename in SQLite") + pending = directory / name + target = directory.parent / ( + finalized_name(pending) if name.endswith("_pending.npz") else name + ) + # Only the atomic rename removes a committed file from this private + # directory. Its final name may already have been claimed by a consumer. + if pending.exists(): + pending.replace(target) + maybe_fsync_dir(target) + maybe_fsync_dir(pending) + sequenced, _, sequence, _ = segment_order(chunk or paper or "") + if sequenced: + self.checkpoint["segment_sequence"] = max(sequence, self.checkpoint.get("segment_sequence", 0)) + self.checkpoint_tar(tar, members) + # Keep the token across cleanup. An interrupted rmdir can then be + # retried without re-publishing or requiring both directories to exist. + with batch_transaction(self.conn): + if self.producer: + self.conn.execute( + "CREATE TABLE IF NOT EXISTS ingest_checkpoint (singleton INTEGER PRIMARY KEY " + "CHECK(singleton=1), checkpoint TEXT NOT NULL)" + ) + self.conn.execute( + "INSERT OR REPLACE INTO ingest_checkpoint(singleton, checkpoint) VALUES (1, ?)", + (json.dumps(self.checkpoint),), + ) + self.conn.execute("UPDATE ingest_publication SET tar=NULL WHERE singleton=1") + for directory in directories: + directory.rmdir() + self._retire() + + def recover(self) -> bool: + """Finish a committed batch or discard its rolled-back staging files.""" + record = read_publication(self.conn) + if record is None: + if "batch_reservation" in self.checkpoint: + self.discard_uncommitted() + return False + if record.tar is None: + self.discard_uncommitted() + return False + directories = self._recovery_directories(record, committed=True) + if not _same_path(self._database(), record.source_db): + # An independent copy can be incomplete even when it contains + # both private directories. Verify the files before publishing any. + for directory, name in zip(directories, (record.paper, record.chunk), strict=True): + if name is None: + continue + staged = directory / name + target = directory.parent / (finalized_name(staged) if name.endswith("_pending.npz") else name) + if not any(path.is_file() for path in (staged, target, target.with_name(target.name + ".ingesting"))): + raise FileNotFoundError(f"Cannot verify {name} in the copied staging directory {directory}.") + self.token = record.token + self._finish(directories, record.tar, record.members, record.paper, record.chunk) + return True diff --git a/src/litkit/cli.py b/src/litkit/cli.py index ef76eac..c87d088 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1039,6 +1039,15 @@ def iter_tar_articles( pass +def _recover_writer_batch(conn): + from litkit.build.publication import BatchPublication + + with FileLock(DB_LOCK), FileLock(FAISS_LOCK): + BatchPublication( + conn, CKPT_PATH, CKPT_LOCK, None, PAPER_INDEX_PATH.parent, CHUNK_INDEX_PATH.parent + ).recover() + + def build_or_update_indices(args): """Build or update indices & DB depending on flags. @@ -1055,6 +1064,26 @@ def build_or_update_indices(args): save indices. Other processes (possibly using --shard-id/--num-shards) only populate SQLite rows and commit; they do not mutate FAISS indices. """ + if args.embed_producer: + get_runtime() + from litkit.db.sharding import producer_shard_lock + + # Acquire ownership before opening the shard. A consumer holding this + # lock may commit the merge and unlink the previous database. + with producer_shard_lock(SQLITE_DIR, args.shard_id, FileLock): + return _build_or_update_indices(args) + if args.rebuild and not args.init_indices_only: + get_runtime() + from litkit.db.sharding import drained_producers + + # A producer consults the main database for previously merged files. + # Let it see either the previous build or the finished replacement. + with drained_producers(SQLITE_DIR, FileLock): + return _build_or_update_indices(args) + return _build_or_update_indices(args) + + +def _build_or_update_indices(args): # ═══════════════════════════════════════════════════════════════════════════ # FAST EARLY EXIT: explicit build-mode enumeration (maintainability fix) # ═══════════════════════════════════════════════════════════════════════════ @@ -1104,8 +1133,10 @@ def build_or_update_indices(args): build_mode = "multi" if is_multi_node else "single" seg_dir = args.embed_outdir or EMBED_SEGMENTS_DIR - # Always validate if segment directory exists with prior work - if d.seg_has_segment_files(seg_dir) or d.seg_read_build_meta(seg_dir) is not None: + # Bootstrap doesn't assign archives to producers or change the shard count. + if not args.init_indices_only and ( + d.seg_has_segment_files(seg_dir) or d.seg_read_build_meta(seg_dir) is not None + ): d.seg_validate_shard_consistency(seg_dir, args.num_shards, current_mode=build_mode) # Write build metadata if this is a fresh start @@ -1160,7 +1191,17 @@ def build_or_update_indices(args): conn = d.db_init_db(DB_PATH, args.sqlite_journal_mode, args.sqlite_busy_timeout_ms) cur = conn.cursor() + if args.faiss_writer and (not args.rebuild or args.init_indices_only): + _recover_writer_batch(conn) + if args.init_indices_only: + for table, path in (("papers", PAPER_INDEX_PATH), ("chunks", CHUNK_INDEX_PATH)): + if not path.exists() and conn.execute(f"SELECT 1 FROM {table} WHERE in_index=1 LIMIT 1").fetchone(): + conn.close() + raise SystemExit( + f"[bootstrap] {path} is missing but SQLite records indexed {table}. " + "Restore the index or run a writer update with the original archives to recover its vectors." + ) # Build a minimal config for the module function cfg = BuildConfig( faiss_writer=args.faiss_writer, @@ -1222,6 +1263,18 @@ def build_or_update_indices(args): if d.seg_has_segment_files(seg_dir): conflict_reasons.append(f"Segment directory {seg_dir} contains unconsumed segment files") + from litkit.db.publication import unpublished_shards + from litkit.db.sharding import list_shard_dbs + + pending = unpublished_shards(list_shard_dbs(SQLITE_DIR)) + if pending: + names = ", ".join(shard.name for shard in pending) + raise SystemExit( + f"[rebuild] BLOCKED: {names} has a committed batch awaiting publication. " + "Rerun the interrupted producer with its original workspace and segment directory, " + "then consume the completed shards before rebuilding." + ) + # Check for producer completion markers (indicates multi-node run) # Use shard count from build_meta.json (if exists) to correctly interpret markers. meta = d.seg_read_build_meta(seg_dir) @@ -1255,17 +1308,17 @@ def build_or_update_indices(args): _eprint( "[rebuild] hard reset: deleting FAISS indices, clearing DB tables, removing checkpoint" ) - for p in [PAPER_INDEX_PATH, CHUNK_INDEX_PATH, CHUNK_TRAINED_FLAG]: - if p.exists(): - p.unlink() - # also clear checkpoint - if CKPT_PATH.exists(): - CKPT_PATH.unlink() - # wipe tables (DELETE in transaction, VACUUM outside) - cur.executescript("DELETE FROM chunks; DELETE FROM papers; DELETE FROM files;") - conn.commit() - + from litkit.build.publication import reset_publication + + with conn: + conn.execute("BEGIN") + reset_publication(conn, SQLITE_DIR, seg_dir) + for table in ("chunks", "papers", "files"): + cur.execute(f"DELETE FROM {table}") + for path in (PAPER_INDEX_PATH, CHUNK_INDEX_PATH, CHUNK_TRAINED_FLAG, CKPT_PATH): + path.unlink(missing_ok=True) + # VACUUM must run outside any transaction (autocommit mode) # Without this, sqlite3.OperationalError: cannot VACUUM from within a transaction old_isolation = conn.isolation_level @@ -1409,6 +1462,7 @@ def build_or_update_indices(args): chunk_min_chars=int(getattr(args, "chunk_min_chars", BODY_MIN_CHARS)), chunk_overlap=int(getattr(args, "chunk_overlap", CHUNK_OVERLAP_CHARS)), ckpt_shard_id=ckpt_shard_id, + _producer_locked=args.embed_producer, parse_workers=args.parse_workers, ) @@ -1424,16 +1478,17 @@ def build_or_update_indices(args): if args.faiss_writer and not args.consume_only: seg_dir = args.embed_outdir or EMBED_SEGMENTS_DIR + segment_errors = [] if args.consume_segments and seg_dir and Path(seg_dir).exists(): # Ingest segments - functions handle IDMap2 wrapping and return the (possibly wrapped) index paper_index, p_added = d.seg_ingest_paper_segments( conn, paper_index, seg_dir, FAISS_LOCK, PAPER_INDEX_PATH, DB_LOCK, - FileLock=FileLock + FileLock=FileLock, errors=segment_errors ) chunk_index, c_added = d.seg_ingest_chunk_segments( conn, chunk_index, seg_dir, FAISS_LOCK, CHUNK_INDEX_PATH, DB_LOCK, - FileLock=FileLock + FileLock=FileLock, errors=segment_errors ) if c_added or p_added: _eprint( @@ -1489,6 +1544,10 @@ def build_or_update_indices(args): d.db_flush_pending_marks(conn.cursor()) conn.commit() + if segment_errors: + conn.close() + raise RuntimeError("Segment ingestion stopped before completion. " + " / ".join(segment_errors)) + try: k, _ = kind_and_core(paper_index) if k == "hnsw": @@ -1775,7 +1834,7 @@ def main(): ap.add_argument( "--init-indices-only", action="store_true", - help="Create empty FAISS indices and exit immediately (for multi-node bootstrap). " + help="Create missing FAISS indices and exit immediately (for multi-node bootstrap). " "Requires --faiss-writer. Does not process any documents.", ) ap.add_argument("--update", action="store_true", help="Append-only update (skip seen files)") @@ -2209,6 +2268,7 @@ def _pick(cands: list[Path]) -> Path | None: conn = d.db_connect_db(DB_PATH) try: + _recover_writer_batch(conn) try: paper_index = faiss_load(PAPER_INDEX_PATH) chunk_index = faiss_load(CHUNK_INDEX_PATH) diff --git a/src/litkit/concurrent/locking.py b/src/litkit/concurrent/locking.py index 4e8ff0c..fa98416 100644 --- a/src/litkit/concurrent/locking.py +++ b/src/litkit/concurrent/locking.py @@ -117,7 +117,7 @@ class FileLock: """ def __init__(self, path: Path, *, db_lock_path: Path | None = None, - faiss_lock_path: Path | None = None): + faiss_lock_path: Path | None = None, blocking: bool = True): """Initialize a file lock. Args: @@ -129,6 +129,7 @@ def __init__(self, path: Path, *, db_lock_path: Path | None = None, """ self.path = Path(path) self._fd = None + self.blocking = blocking self._faiss_depth_bumped = False self._db_depth_bumped = False # Store reference paths for depth tracking @@ -153,20 +154,24 @@ def __enter__(self): try: msvcrt.locking(self._fd.fileno(), msvcrt.LK_NBLCK, 1) break - except PermissionError: + except PermissionError as error: + if not self.blocking: + raise BlockingIOError(errno.EAGAIN, "File lock is held", str(self.path)) from error time.sleep(0.05) except BaseException: self._fd.close() raise elif FLOCK_AVAILABLE and fcntl is not None: try: - fcntl.flock(self._fd.fileno(), fcntl.LOCK_EX) + operation = fcntl.LOCK_EX if self.blocking else fcntl.LOCK_EX | fcntl.LOCK_NB + fcntl.flock(self._fd.fileno(), operation) except OSError as e: # Treat ENOTSUP/EOPNOTSUPP as "best-effort" (no advisory # locking), but continue as if acquired. enotsup = getattr(errno, "ENOTSUP", 95) eopnotsupp = getattr(errno, "EOPNOTSUPP", 95) if e.errno not in (enotsup, eopnotsupp): + self._fd.close() raise if not _DEGRADED_MODE_WARNED: _eprint( diff --git a/src/litkit/db/connection.py b/src/litkit/db/connection.py index 202914c..2d5822c 100644 --- a/src/litkit/db/connection.py +++ b/src/litkit/db/connection.py @@ -5,6 +5,7 @@ import os import sqlite3 +from contextlib import contextmanager from pathlib import Path from typing import TYPE_CHECKING @@ -33,6 +34,31 @@ def _get_busy_timeout() -> int: return int(os.environ.get("LITKIT_SQLITE_BUSY_TIMEOUT_MS", str(DEFAULT_BUSY_TIMEOUT_MS))) +def commit_transaction(conn: sqlite3.Connection) -> None: + """Finish an explicit BEGIN even if Python's commit() is disabled by autocommit.""" + if conn.autocommit is True and conn.in_transaction: + conn.execute("COMMIT") + else: + conn.commit() + + +def rollback_transaction(conn: sqlite3.Connection) -> None: + if conn.autocommit is True and conn.in_transaction: + conn.execute("ROLLBACK") + else: + conn.rollback() + + +@contextmanager +def batch_transaction(conn: sqlite3.Connection): + try: + yield + commit_transaction(conn) + except BaseException: + rollback_transaction(conn) + raise + + # --------------------------------------------------------------------------- # Connection Functions # --------------------------------------------------------------------------- diff --git a/src/litkit/db/handoff.py b/src/litkit/db/handoff.py new file mode 100644 index 0000000..2e3fac0 --- /dev/null +++ b/src/litkit/db/handoff.py @@ -0,0 +1,396 @@ +"""Publish a completed node-local shard on shared storage. The caller holds the shard lock. + +The cluster script also runs this module directly on hosts without LitKit installed. +""" + +import hashlib +import json +import os +import shutil +import sqlite3 +import sys +from contextlib import closing, contextmanager +from pathlib import Path +from uuid import UUID + + +@contextmanager +def readable_database(path): + """Open an existing database read-only, allowing SQLite to recover a hot journal first.""" + uri = path.resolve().as_uri() + with closing(sqlite3.connect(uri + "?mode=ro", uri=True)) as reader: + try: + reader.execute("PRAGMA schema_version").fetchone() + except sqlite3.OperationalError as error: + # Older cluster-host Pythons do not expose sqlite_errorcode. + code = getattr(error, "sqlite_errorcode", None) + read_only = "readonly" in str(error).lower() if code is None else (code & 0xff) == sqlite3.SQLITE_READONLY + if not read_only: + raise + else: + yield reader + return + with closing(sqlite3.connect(uri + "?mode=rw", uri=True)) as recovery: + recovery.execute("PRAGMA schema_version").fetchone() + with closing(sqlite3.connect(uri + "?mode=ro", uri=True)) as reader: + yield reader + + +def completed_checkpoint(db): + if db.execute("SELECT 1 FROM sqlite_master WHERE name='ingest_checkpoint'").fetchone(): + row = db.execute("SELECT checkpoint FROM ingest_checkpoint WHERE singleton=1").fetchone() + if row: + return json.loads(row[0]) + return None + + +def merged_checkpoints(db, shard_id=None): + if db is None or not db.execute("SELECT 1 FROM sqlite_master WHERE name='merged_shard_checkpoints'").fetchone(): + return {} + query = "SELECT shard_id, checkpoint FROM merged_shard_checkpoints" + rows = db.execute(query) if shard_id is None else db.execute(query + " WHERE shard_id=?", (shard_id,)) + return {i: json.loads(value) for i, value in rows} + + +def verify_checkpoint_revision(conn, checkpoint, record=None, merged=None): + """Return the last completed SQLite checkpoint and check any external revision.""" + local = completed_checkpoint(conn) + if local and merged and merged.get("producer_revision") not in (None, local.get("producer_revision")): + has_history = conn.execute("SELECT 1 FROM sqlite_master WHERE name='ingest_ancestors'").fetchone() + if not has_history or not conn.execute( + "SELECT 1 FROM ingest_ancestors WHERE revision=?", (merged["producer_revision"],) + ).fetchone(): + raise RuntimeError( + "The shard database does not descend from the batch already merged into the main database. " + "Resume from the latest matching shard and output directories." + ) + saved = local or merged + revisions = {saved.get("producer_revision")} if saved else {None} + if record and record.tar is not None: + # SQLite may have committed the next batch and published its checkpoint + # without yet retiring the journal and recording the completed revision. + revisions.add(record.token) + if checkpoint and checkpoint.get("producer_revision") not in revisions: + raise RuntimeError( + "The checkpoint and shard database describe different batches. " + "Resume with a matching copy of the database, checkpoint and segment directories." + ) + return saved + + +def output_markers(checkpoint, paper_dir, chunk_dir): + """Return the two directory identities carried with a producer's checkpoint.""" + token = checkpoint.get("segment_output") + if token is None: + return () + if UUID(hex=token).hex != token: + raise ValueError("Invalid segment output identity in checkpoint") + return (paper_dir / f".litkit-output-{token}-papers", chunk_dir / f".litkit-output-{token}-chunks") + + +def verify_output_markers(checkpoint, paper_dir, chunk_dir, *, publishing=None): + markers = output_markers(checkpoint, paper_dir, chunk_dir) + revisions = {checkpoint.get("producer_revision", "")} + if publishing is not None: + revisions.add(publishing) + for marker in markers: + if not marker.is_file(): + raise RuntimeError( + f"The checkpoint does not belong to the segment directory {marker.parent}. " + "Use the original paper and chunk output directories or their complete copies." + ) + if marker.read_text() not in revisions: + raise RuntimeError( + f"The checkpoint and segment directory {marker.parent} describe different batches. " + "Use a matching copy of the database, checkpoint and segment directories." + ) + return markers + + +def _staging(sqlite_dir, shard_id): + name = ".litkit-handoff-" + str(shard_id) + return sqlite_dir / name, sqlite_dir.parent / "emb_segments" / name + + +def staged_shards(sqlite_dir): + for path in sqlite_dir.glob(".litkit-handoff-*"): + suffix = path.name.rsplit("-", 1)[-1] + if suffix.isdecimal() and path.is_dir(): + yield int(suffix) + + +def _sync_dir(directory): + if os.name != "nt": + fd = os.open(str(directory), os.O_RDONLY) + try: + os.fsync(fd) + finally: + os.close(fd) + + +def _backup(source, target): + with readable_database(source) as db: + with closing(sqlite3.connect(str(target))) as backup: + db.backup(backup) + + +def _copy_file(source, target): + shutil.copyfile(source, target) + # Flush while the private copy is writable, before restoring its source permissions. + with target.open("r+b") as stream: + os.fsync(stream.fileno()) + shutil.copystat(source, target) + + +def _shared_version(sqlite_dir, shard_id): + """Identify the shared state a local job is allowed to replace under the shard lock.""" + checkpoint = sqlite_dir / f"build_checkpoint_shard_{shard_id:02d}.json" + receipt = sqlite_dir / f"producer_{shard_id}.transfer" + db = sqlite_dir / f"litkit_shard_{shard_id:02d}.sqlite3" + version = {} + for path in (checkpoint, receipt): + if path.is_file(): + version[path.name] = hashlib.sha256(path.read_bytes()).hexdigest() + # A direct shared-storage producer can have a live SQLite publication + # before its checkpoint advances. Include the database and recovery files. + for path in (db, db.with_name(db.name + "-journal"), db.with_name(db.name + "-wal")): + if path.is_file(): + stat = path.stat() + version[path.name] = [stat.st_size, stat.st_mtime_ns] + return version + + +def _remember_version(base, version): + temporary = base.with_suffix(".tmp") + with temporary.open("w") as stream: + json.dump(version, stream, sort_keys=True) + stream.flush() + os.fsync(stream.fileno()) + temporary.replace(base) + _sync_dir(base.parent) + + +def _transfer_checkpoint(database, progress, merged): + """Verify the snapshot before replacing any shared files or acknowledging a retry.""" + if database.is_file(): + with readable_database(database) as db: + journal = db.execute("SELECT 1 FROM sqlite_master WHERE name='ingest_publication'").fetchone() + if journal and db.execute("SELECT 1 FROM ingest_publication").fetchone(): + raise RuntimeError("Resume the producer to finish its pending publication before transferring the shard.") + saved = verify_checkpoint_revision(db, progress, merged=merged) + else: + saved = merged + if progress and progress.get("producer_revision") != (saved or {}).get("producer_revision"): + raise RuntimeError("The checkpoint and merged shard database describe different batches.") + return progress or saved or {} + + +def prepare_local_shard(local, workspace, shard_id): + """Seed an empty local workspace from shared progress before running the producer.""" + if not hasattr(sqlite3.Connection, "backup"): + # RHEL 8 hosts can run Python 3.6. The container handles shared + # storage directly when the host cannot take a consistent SQLite copy. + print("Host Python lacks SQLite backup support. Using shared storage.", file=sys.stderr) + return False + sqlite_dir = workspace / "sqlite" + finish_handoff(sqlite_dir, shard_id) + target = local / "sqlite" / f"litkit_shard_{shard_id:02d}.sqlite3" + source = sqlite_dir / target.name + checkpoint = sqlite_dir / f"build_checkpoint_shard_{shard_id:02d}.json" + saved = None + if source.is_file(): + with readable_database(source) as db: + if not db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='files'").fetchone(): + return False # The producer must finish interrupted schema initialization on shared storage. + legacy = not db.execute( + "SELECT 1 FROM sqlite_master WHERE name='ingest_publication'" + ).fetchone() + if not legacy and db.execute("SELECT 1 FROM ingest_publication").fetchone(): + return False # Recover private staging in its original workspace. + saved = completed_checkpoint(db) + if not saved and db.execute("SELECT 1 FROM files LIMIT 1").fetchone(): + return False # Verify inherited rows even if the first modern reservation rolled back. + if saved is None and not checkpoint.is_file() and (sqlite_dir / "litkit.sqlite3").is_file(): + with readable_database(sqlite_dir / "litkit.sqlite3") as main: + saved = merged_checkpoints(main, shard_id).get(shard_id) + if saved and not checkpoint.is_file(): + # Recover the JSON and verify the output revisions on shared storage + # before seeding a new node. This never substitutes an empty local dir. + return False + if checkpoint.is_file(): + try: + progress = json.loads(checkpoint.read_text()) + except (ValueError, OSError): + return False + if not isinstance(progress, dict) or "batch_reservation" in progress: + return False + shared_segments = workspace / "emb_segments" + markers = verify_output_markers(progress, shared_segments, shared_segments) + base = target.parent / f"producer_{shard_id}.base" + if target.is_file(): + # A requeued job can retain an older local directory after another + # node has published new work. Resume from shared storage in that case. + version = _shared_version(sqlite_dir, shard_id) + expected = json.loads(base.read_text()) if base.is_file() else {} + return expected == version + if any(target.parent.iterdir()) or any((local / "emb_segments").iterdir()): + # Cleanup of a completed job can remove its database before its old + # segments. A new local seed must start in empty directories. + return False + if source.is_file(): + _backup(source, target.with_suffix(".seed")) + if checkpoint.is_file(): + dest = target.parent / checkpoint.name + local_segments = local / "emb_segments" + for marker in markers: + _copy_file(marker, local_segments / marker.name) + _sync_dir(local_segments) + _copy_file(checkpoint, dest.with_suffix(".seed")) + dest.with_suffix(".seed").replace(dest) + _remember_version(base, _shared_version(sqlite_dir, shard_id)) + if source.is_file(): + target.with_suffix(".seed").replace(target) + _sync_dir(target.parent) + return True + + +def finish_handoff(sqlite_dir, shard_id, *, database_open=False): + """Finish all renames after a complete copy, or discard an interrupted private copy.""" + db_stage, seg_stage = _staging(sqlite_dir, shard_id) + if not db_stage.exists(): + return + ready = db_stage / "READY" + if ready.is_file(): + if database_open: + raise RuntimeError("Close the shard connection and resume the producer CLI to finish its staged transfer.") + done = seg_stage / f"producer_{shard_id}.done" + for stage in (seg_stage, db_stage): + if stage == db_stage: + # The staged SQLite backup is self-contained. Sidecars left by + # an older copy do not belong to this snapshot. + for suffix in ("-journal", "-wal", "-shm"): + sidecar = sqlite_dir / f"litkit_shard_{shard_id:02d}.sqlite3{suffix}" + if sidecar.exists(): + sidecar.unlink() + for source in stage.iterdir(): + if source != ready and source != done: + source.replace(stage.parent / source.name) + _sync_dir(stage.parent) + _sync_dir(stage) + if done.exists(): + done.replace(seg_stage.parent / done.name) + _sync_dir(seg_stage.parent) + _sync_dir(seg_stage) + ready.replace(sqlite_dir / f"producer_{shard_id}.transfer") + _sync_dir(sqlite_dir) + _sync_dir(db_stage) + # Keep the discoverable database-side directory until all cleanup succeeds. + if seg_stage.exists(): + shutil.rmtree(seg_stage) + _sync_dir(seg_stage.parent) + shutil.rmtree(db_stage) + _sync_dir(db_stage.parent) + + +def copy_handoff(source, workspace, shard_id): + """Receive both directories privately before publishing any checkpoint or segment.""" + if __package__: + from litkit.segments.discovery import iter_shard_segment_files + else: + from discovery import iter_shard_segment_files + sqlite_dir = workspace / "sqlite" + finish_handoff(sqlite_dir, shard_id) + db_stage, seg_stage = _staging(sqlite_dir, shard_id) + source_db = source / "sqlite" / f"litkit_shard_{shard_id:02d}.sqlite3" + checkpoint = source / "sqlite" / f"build_checkpoint_shard_{shard_id:02d}.json" + segment_dir = source / "emb_segments" + done = segment_dir / f"producer_{shard_id}.done" + segments = sorted( + path for kind in ("papers", "chunks") for path in iter_shard_segment_files(segment_dir, kind, shard_id) + ) + if not source_db.is_file() or not done.is_file(): + raise RuntimeError(f"Incomplete local producer output for shard {shard_id} in {source}") + checkpoint_bytes = checkpoint.read_bytes() if checkpoint.is_file() else None + if not checkpoint_bytes: + with readable_database(source_db) as db: + saved = completed_checkpoint(db) + if saved: + checkpoint_bytes = json.dumps(saved, indent=2).encode() + digest = hashlib.sha256(checkpoint_bytes or b"") + for path in segments: + digest.update(b"\0" + os.fsencode(path.name)) + receipt = sqlite_dir / f"producer_{shard_id}.transfer" + old_identity = digest.hexdigest() + # A fresh producer invocation can finish without producing a new batch. + # Its marker still belongs to a different run than an old transfer retry. + digest.update(b"\0done\0" + done.read_bytes()) + identity = digest.hexdigest() + shared_checkpoint = sqlite_dir / checkpoint.name + merged = None + if (sqlite_dir / "litkit.sqlite3").is_file(): + with readable_database(sqlite_dir / "litkit.sqlite3") as main: + merged = merged_checkpoints(main, shard_id).get(shard_id) + shared_progress = json.loads(shared_checkpoint.read_bytes()) if shared_checkpoint.is_file() else {} + shared_progress = _transfer_checkpoint(sqlite_dir / source_db.name, shared_progress, merged) + shared_segments = workspace / "emb_segments" + verify_output_markers(shared_progress, shared_segments, shared_segments) + progress = json.loads(checkpoint_bytes) if checkpoint_bytes else {} + # A previous transfer can match the public filenames while a newer + # committed batch is still private in the retained source database. + _transfer_checkpoint(source_db, progress, merged) + markers = verify_output_markers(progress, segment_dir, segment_dir) + same_checkpoint = progress == shared_progress + base = source_db.parent / f"producer_{shard_id}.base" + expected = json.loads(base.read_text()) if base.is_file() else {} + if same_checkpoint and receipt.is_file() and ( + (sqlite_dir / source_db.name).is_file() or (sqlite_dir / "litkit.sqlite3").is_file() + ): + recorded = receipt.read_text() + if recorded == identity or (recorded == old_identity and expected != _shared_version(sqlite_dir, shard_id)): + # The receipt was published after the marker. A successful consumer + # may have since removed the marker. A repeat transfer is a no-op. + return + if expected != _shared_version(sqlite_dir, shard_id): + raise RuntimeError( + f"Shared progress changed since local shard {shard_id} was prepared. " + "Resume the producer from shared storage before copying this shard." + ) + db_stage.mkdir(parents=True) + seg_stage.mkdir(parents=True) + _backup(source_db, db_stage / source_db.name) + for path in (checkpoint, source / "sqlite" / "ingest_failures.jsonl"): + if path.is_file(): + _copy_file(path, db_stage / path.name) + if checkpoint_bytes and not checkpoint.is_file(): + with (db_stage / checkpoint.name).open("wb") as stream: + stream.write(checkpoint_bytes) + stream.flush() + os.fsync(stream.fileno()) + meta = segment_dir / "build_meta.json" + for path in [*segments, *markers, done]: + _copy_file(path, seg_stage / path.name) + if meta.is_file(): + _copy_file(meta, seg_stage / meta.name) + for stage in (db_stage, seg_stage): + _sync_dir(stage) + _sync_dir(stage.parent) + # Publish the complete receipt atomically too. A crash during its write + # leaves an uncommitted copy which a new producer may safely discard. + temporary = db_stage / "READY.tmp" + with temporary.open("x") as ready: + ready.write(identity) + ready.flush() + os.fsync(ready.fileno()) + temporary.replace(db_stage / "READY") + _sync_dir(db_stage) + finish_handoff(sqlite_dir, shard_id) + + +if __name__ == "__main__": + if not __package__: + # The cluster host runs this file without an installed LitKit package. + sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "segments")) + operation, source, workspace, shard = sys.argv[1:] + result = {"prepare": prepare_local_shard, "copy": copy_handoff}[operation](Path(source), Path(workspace), int(shard)) + if operation == "prepare": + print("local" if result else "shared") diff --git a/src/litkit/db/publication.py b/src/litkit/db/publication.py new file mode 100644 index 0000000..8e35b26 --- /dev/null +++ b/src/litkit/db/publication.py @@ -0,0 +1,42 @@ +"""Read the SQLite journal for a producer or writer batch.""" + +from __future__ import annotations + +import sqlite3 +from pathlib import Path +from typing import NamedTuple + +from litkit.db.handoff import readable_database + + +class PublicationRecord(NamedTuple): + token: str + source_db: str + paper_root: str + chunk_root: str + tar: str | None + members: int | None + paper: str | None + chunk: str | None + + +def read_publication(conn: sqlite3.Connection) -> PublicationRecord | None: + if not conn.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='ingest_publication'" + ).fetchone(): + return None + row = conn.execute( + "SELECT token, source_db, paper_root, chunk_root, tar, members, paper, chunk FROM ingest_publication" + ).fetchone() + return PublicationRecord(*row) if row else None + + +def unpublished_shards(shards: list[Path], *, include_reservations: bool = False) -> list[Path]: + """Find committed publications and, before a merge, journals needed for staging cleanup.""" + pending = [] + for shard in shards: + with readable_database(shard) as conn: + row = read_publication(conn) + if row and (include_reservations or row.tar is not None): + pending.append(shard) + return pending diff --git a/src/litkit/db/queries.py b/src/litkit/db/queries.py index d44d9ba..1c31acc 100644 --- a/src/litkit/db/queries.py +++ b/src/litkit/db/queries.py @@ -5,6 +5,7 @@ import sqlite3 from typing import TYPE_CHECKING +from litkit.progress import eprint if TYPE_CHECKING: import os @@ -18,6 +19,8 @@ def already_processed( cur: sqlite3.Cursor, fpath: str, st, + *, + require_indexed: bool = False, ) -> bool: """Check if file at `fpath` with current stat `st` was already ingested. @@ -32,10 +35,16 @@ def already_processed( Returns: True if file was already processed with same size/mtime """ - cur.execute( - "SELECT size, mtime FROM files WHERE path = ?", - (fpath,) - ) + if require_indexed: + # A SQLite-only worker can register files without ever writing vectors. + cur.execute(""" + SELECT f.size, f.mtime FROM files f JOIN papers p ON p.id=f.paper_id + WHERE f.path=? AND p.in_index=1 + AND EXISTS (SELECT 1 FROM chunks c WHERE c.paper_id=p.id) + AND NOT EXISTS (SELECT 1 FROM chunks c WHERE c.paper_id=p.id AND c.in_index IS NOT 1) + """, (fpath,)) + else: + cur.execute("SELECT size, mtime FROM files WHERE path=?", (fpath,)) row = cur.fetchone() if row is None: return False @@ -64,6 +73,27 @@ def register_file( ) +def available_citation_ids(doc_id, pmid, pmcid, *readers): + """Keep an established identifier with its owner when an archive links two records.""" + def available(column, value): + if value: + for reader in readers: + if reader is None: + continue + owner = reader.execute( + f"SELECT doc_id FROM papers p WHERE {column}=? AND {column}<>'' AND doc_id IS NOT ? " + "AND NOT EXISTS (SELECT 1 FROM files f WHERE f.path=? AND f.paper_id=p.id)", + (value, doc_id, doc_id), + ).fetchone() + if owner: + eprint(f"[ingest] {column.upper()} {value} is already assigned to {owner[0]}. " + f"Keeping its existing association while updating {doc_id}.") + return "" + return value + + return available("pmid", pmid), available("pmcid", pmcid) + + # --------------------------------------------------------------------------- # Paper/Chunk ID Map Preloading # --------------------------------------------------------------------------- @@ -82,8 +112,13 @@ def preload_paper_id_map(conn: sqlite3.Connection) -> dict[str, int]: Dictionary mapping doc_id strings to paper_id integers """ cur = conn.cursor() - cur.execute("SELECT doc_id, id FROM papers") - return {row[0]: row[1] for row in cur.fetchall()} + # A producer's original doc_id may be an alternate archive path after two + # shards independently encounter the same PMID or PMCID. Canonical IDs win. + cur.execute(""" + SELECT f.path, f.paper_id FROM files f JOIN papers p ON p.id=f.paper_id WHERE f.path<>p.doc_id + UNION ALL SELECT doc_id, id FROM papers + """) + return dict(cur) def preload_chunk_id_map(conn: sqlite3.Connection) -> dict[tuple[int, int], int]: diff --git a/src/litkit/db/schema.py b/src/litkit/db/schema.py index 167cbab..bc9a83c 100644 --- a/src/litkit/db/schema.py +++ b/src/litkit/db/schema.py @@ -22,7 +22,10 @@ title TEXT, abstract TEXT, source_path TEXT, - in_index INTEGER DEFAULT 0 -- 0=not yet in FAISS, 1=added + -- 0=not yet in FAISS, 1=added + in_index INTEGER DEFAULT 0, + -- Paper vector input when multiple versions share an ID + embedding_text TEXT ); CREATE TABLE IF NOT EXISTS chunks ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -59,6 +62,18 @@ def citation_columns(conn: sqlite3.Connection, schema: str = "main") -> tuple[st "c.page" if "page" in chunk_cols else "NULL") +def paper_embedding_column(conn: sqlite3.Connection, schema: str = "main") -> str: + """Select the recorded paper input when reading a current or legacy database.""" + columns = {row[1] for row in conn.execute(f"PRAGMA {schema}.table_info(papers)")} + return "p.embedding_text" if "embedding_text" in columns else "NULL" + + +def ensure_paper_embedding_column(conn: sqlite3.Connection) -> None: + """Upgrade a writable connection opened on a database from an earlier release.""" + if paper_embedding_column(conn) == "NULL": + conn.execute("ALTER TABLE main.papers ADD COLUMN embedding_text TEXT") + + def ensure_in_index_columns(conn: sqlite3.Connection) -> None: """Add missing index, document identity and citation columns to writable databases. @@ -79,6 +94,7 @@ def ensure_in_index_columns(conn: sqlite3.Connection) -> None: # Ensure doc_id column exists on papers table (for multi-producer deduplication) papers_cols = {row[1] for row in cur.execute("PRAGMA table_info(papers)")} + ensure_paper_embedding_column(conn) if "doc_id" not in papers_cols: cur.execute("ALTER TABLE papers ADD COLUMN doc_id TEXT") # Create unique index for doc_id if it doesn't exist diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index 4e66b73..ac2b18a 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -3,13 +3,19 @@ from __future__ import annotations -import os +import json import sqlite3 import sys import time +from contextlib import ExitStack, contextmanager from pathlib import Path -from litkit.db.schema import citation_columns +from litkit.concurrent.locking import FileLock +from litkit.db.connection import commit_transaction, rollback_transaction +from litkit.db.handoff import finish_handoff, merged_checkpoints, readable_database, staged_shards, verify_checkpoint_revision, verify_output_markers +from litkit.db.publication import unpublished_shards +from litkit.db.queries import available_citation_ids +from litkit.db.schema import citation_columns, ensure_paper_embedding_column, paper_embedding_column # --------------------------------------------------------------------------- @@ -42,8 +48,11 @@ def list_shard_dbs(sqlite_dir: Path) -> list[Path]: if not sqlite_dir.exists(): return [] - shards = sorted(sqlite_dir.glob("litkit_shard_*.sqlite3")) - return shards + def shard_order(path): + suffix = path.stem.removeprefix("litkit_shard_") + return (int(suffix) if suffix.isdecimal() else -1, path.name) + + return sorted(sqlite_dir.glob("litkit_shard_*.sqlite3"), key=shard_order) # --------------------------------------------------------------------------- @@ -67,6 +76,8 @@ class ShardDetachError(sqlite3.OperationalError): def merge_shard_databases( main_conn: sqlite3.Connection, delete_after_merge: bool = True, + *, + segment_dir: Path | tuple[Path, Path] | None = None, ) -> dict[str, int]: """Merge all per-shard SQLite databases into the main database. @@ -80,22 +91,173 @@ def merge_shard_databases( Args: main_conn: Connection to the main litkit.sqlite3 database delete_after_merge: If True, delete shard DBs after successful merge + segment_dir: Combined output directory, or the separate (paper, chunk) directories Returns: Dict with merge statistics: {"papers": N, "chunks": M, "files": F, "shards": S} - - Raises: - ShardDetachError: A shard could not be detached after its merge. """ - # Derive sqlite_dir from main database path - # The main_conn is typically to sqlite_dir/litkit.sqlite3 + with merged_shard_databases(main_conn, delete_after_merge, segment_dir=segment_dir) as stats: + return stats + + +@contextmanager +def producer_shard_lock(sqlite_dir, shard_id, lock_factory=FileLock, *, database_open=False): + """Register the shard under the admission lock before opening its database.""" + # A duplicate producer waits outside admission so other shards can start. + with lock_factory(sqlite_dir / f"producer_{shard_id}.queue"), ExitStack() as owner: + with lock_factory(sqlite_dir / "producer-admission.lock"): + owner.enter_context(lock_factory(sqlite_dir / f"producer_{shard_id}.lock")) + finish_handoff(sqlite_dir, shard_id, database_open=database_open) + yield + + +@contextmanager +def merged_shard_databases( + main_conn: sqlite3.Connection, + delete_after_merge: bool = True, + *, + lock_factory=FileLock, + segment_dir: Path | tuple[Path, Path] | None = None, +): + """Hold producer ownership through the merge and the caller's segment ingestion.""" db_path = main_conn.execute("PRAGMA database_list").fetchone()[2] sqlite_dir = Path(db_path).parent if db_path else Path(".") - - shard_dbs = list_shard_dbs(sqlite_dir) + with drained_producers(sqlite_dir, lock_factory): + yield merge_drained_shards(main_conn, sqlite_dir, delete_after_merge, segment_dir) + + +@contextmanager +def drained_producers(sqlite_dir, lock_factory=FileLock): + """Exclude new producers and finish transfers once every active producer exits.""" + with lock_factory(sqlite_dir / "producer-admission.lock"): + # New producers cannot enter. Wait for each previously admitted + # producer before discovering the databases, one descriptor at a time. + for path in sqlite_dir.glob("producer_*.lock"): + with lock_factory(path): + pass + for shard_id in staged_shards(sqlite_dir): + finish_handoff(sqlite_dir, shard_id) + yield + + +def merge_drained_shards(main_conn, sqlite_dir, delete_after_merge, segment_dir): + """The caller holds producer admission until it has finished using the segments.""" + shards = list_shard_dbs(sqlite_dir) + pending = unpublished_shards(shards, include_reservations=True) + if pending: + names = ", ".join(shard.name for shard in pending) + raise RuntimeError( + f"Cannot merge: {names} has unfinished batch publication or cleanup. " + "Resume the interrupted producer in its original workspace and segment directory." + ) + from litkit.segments.checkpoint import load_checkpoint + from litkit.segments.metadata import verify_legacy_shard + + outputs = segment_dir + if segment_dir is not None and not isinstance(segment_dir, tuple): + outputs = (segment_dir, segment_dir) + default_segments = sqlite_dir.parent / "emb_segments" + legacy_outputs = outputs + if outputs is None and sqlite_dir.name == "sqlite" and ( + default_segments.is_dir() or any(sqlite_dir.glob("build_checkpoint_shard_*.json")) + ): + legacy_outputs = (default_segments, default_segments) + + receipts = merged_checkpoints(main_conn) + external = {} + for path in sqlite_dir.glob("build_checkpoint_shard_*.json"): + suffix = path.stem.removeprefix("build_checkpoint_shard_") + if suffix.isdecimal(): + external[int(suffix)] = load_checkpoint(path) + + to_record = {} + for shard in shards: + suffix = shard.stem.removeprefix("litkit_shard_") + if not suffix.isdecimal(): + continue + shard_id = int(suffix) + checkpoint = external.pop(shard_id, {}) + merged = receipts.pop(shard_id, None) + with readable_database(shard) as source: + saved = verify_checkpoint_revision(source, checkpoint, merged=merged) + if outputs: + verify_output_markers(saved or checkpoint, *outputs) + if legacy_outputs: + verify_legacy_shard(source, shard_id, *legacy_outputs, merged_db=main_conn) + if saved or checkpoint.get("segment_output"): + to_record[shard] = (shard_id, json.dumps(checkpoint or saved)) + + if outputs: + # A previous merge may already have deleted the source shard. Its + # durable receipt still identifies the required outputs without JSON. + for shard_id in receipts.keys() | external.keys(): + current = external.get(shard_id) + saved = receipts.get(shard_id) + if saved and current and saved.get("producer_revision") != current.get("producer_revision"): + raise RuntimeError("The checkpoint and merged shard database describe different batches.") + verify_output_markers(saved or current, *outputs) + return _merge_locked_shards(main_conn, shards, delete_after_merge, to_record) + + +def _merge_revised_papers(conn, shard, mapping, since): + """Refresh retrieval text only for articles revised since this shard's last merge.""" + has_revisions = conn.execute(f"SELECT 1 FROM {shard}.sqlite_master WHERE name='producer_revisions'").fetchone() + if not has_revisions and not conn.execute(f"SELECT 1 FROM {mapping} WHERE new_alias LIMIT 1").fetchone(): + return 0 + join = f"LEFT JOIN {shard}.producer_revisions r ON r.paper_id=p.id" if has_revisions else "" + sequence = "r.sequence" if has_revisions else "0" + inserted = 0 + revisions = conn.execute(f""" + SELECT m.main_pid, p.id, dest.doc_id, p.pmid, p.pmcid, p.title, p.abstract, p.source_path, + COALESCE(p.embedding_text, (SELECT c.text FROM {shard}.chunks c + WHERE c.paper_id=p.id AND c.ord=-1 ORDER BY c.id DESC LIMIT 1)) + FROM {shard}.papers p JOIN {mapping} m ON m.shard_pid=p.id + JOIN papers dest ON dest.id=m.main_pid {join} + WHERE m.new_alias OR {sequence} > ? + -- A later occurrence replaces its chunks even when its local paper_id + -- is older than another alias which resolves to the same main paper. + ORDER BY m.main_pid, (SELECT MAX(c.id) FROM {shard}.chunks c WHERE c.paper_id=p.id) + """, (since,)) + for main_id, local_id, doc_id, pmid, pmcid, title, abstract, source_path, embedding_text in revisions: + pmid, pmcid = available_citation_ids(doc_id, pmid, pmcid, conn) + conn.execute("INSERT OR IGNORE INTO merged_paper_revisions(paper_id) VALUES (?)", (main_id,)) + conn.execute(""" + UPDATE papers SET in_index=CASE WHEN COALESCE(embedding_text, + (SELECT text FROM chunks WHERE paper_id=:id AND ord=-1 ORDER BY id DESC LIMIT 1) + ) IS :input THEN in_index ELSE 0 END, + title=:title, abstract=:abstract, source_path=:source, embedding_text=:input, + pmid=COALESCE(NULLIF(pmid,''), :pmid), pmcid=COALESCE(NULLIF(pmcid,''), :pmcid) WHERE id=:id + """, {"title": title, "abstract": abstract, "source": source_path, "input": embedding_text, + "id": main_id, "pmid": pmid, "pmcid": pmcid}) + inserted += conn.execute(f""" + INSERT INTO chunks(paper_id, ord, text, page, in_index) + SELECT ?, c.ord, c.text, c.page, 0 FROM {shard}.chunks c WHERE c.paper_id=? + AND NOT EXISTS (SELECT 1 FROM chunks m WHERE m.paper_id=? AND m.ord=c.ord) + """, (main_id, local_id, main_id)).rowcount + source = conn.execute(f"SELECT text, page, ord FROM {shard}.chunks WHERE paper_id=?", (local_id,)) + conn.executemany("UPDATE chunks SET in_index=CASE WHEN text=? THEN in_index ELSE 0 END, " + "text=?, page=? WHERE paper_id=? AND ord=?", + ((text, text, page, main_id, ordinal) for text, page, ordinal in source)) + obsolete = conn.execute(f""" + SELECT id FROM chunks WHERE paper_id=? AND ( + ord NOT IN (SELECT ord FROM {shard}.chunks WHERE paper_id=?) + OR id NOT IN (SELECT MAX(id) FROM chunks WHERE paper_id=? GROUP BY ord) + ) + """, (main_id, local_id, main_id)).fetchall() + if obsolete: + # The FAISS writer can remove these IDs after this SQLite merge + # commits, including on a retry after the source shard was deleted. + conn.execute("CREATE TABLE IF NOT EXISTS obsolete_chunk_vectors (id INTEGER PRIMARY KEY)") + conn.executemany("INSERT OR IGNORE INTO obsolete_chunk_vectors VALUES (?)", obsolete) + conn.executemany("DELETE FROM chunks WHERE id=?", obsolete) + return inserted + + +def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge, to_record): if not shard_dbs: return {"papers": 0, "chunks": 0, "files": 0, "shards": 0} + ensure_paper_embedding_column(main_conn) _eprint( f"[merge] Found {len(shard_dbs)} shard database(s) to merge " @@ -121,26 +283,27 @@ def merge_shard_databases( ) try: + if not main_conn.in_transaction: + main_conn.execute("BEGIN") # Count rows before merge for statistics papers_before = main_cur.execute( "SELECT COUNT(*) FROM papers" ).fetchone()[0] - chunks_before = main_cur.execute( - "SELECT COUNT(*) FROM chunks" - ).fetchone()[0] files_before = main_cur.execute( "SELECT COUNT(*) FROM files" ).fetchone()[0] source_path, page = citation_columns(main_conn, shard_alias) + embedding_text = paper_embedding_column(main_conn, shard_alias) + # 1) BULK MERGE PAPERS # Insert papers that don't already exist (by doc_id) main_cur.execute(f""" INSERT OR IGNORE INTO papers( - doc_id, pmid, pmcid, title, abstract, source_path, in_index + doc_id, pmid, pmcid, title, abstract, source_path, embedding_text, in_index ) - SELECT p.doc_id, p.pmid, p.pmcid, p.title, p.abstract, {source_path}, 0 + SELECT p.doc_id, p.pmid, p.pmcid, p.title, p.abstract, {source_path}, {embedding_text}, 0 FROM {shard_alias}.papers p WHERE p.doc_id IS NOT NULL AND p.doc_id != '' @@ -153,24 +316,51 @@ def merge_shard_databases( # Create temp table to map shard paper_id -> main paper_id main_cur.execute(f"DROP TABLE IF EXISTS {temp_map_table}") main_cur.execute(f""" - CREATE TEMP TABLE {temp_map_table} AS - SELECT s.id AS shard_pid, m.id AS main_pid - FROM {shard_alias}.papers s - JOIN papers m ON m.doc_id = s.doc_id + CREATE TEMP TABLE {temp_map_table} ( + shard_pid INTEGER PRIMARY KEY, main_pid INTEGER NOT NULL, new_alias INTEGER DEFAULT 0 + ) + """) + main_cur.execute(f""" + INSERT INTO {temp_map_table}(shard_pid, main_pid) + SELECT s.id, m.id FROM {shard_alias}.papers s JOIN papers m ON m.doc_id=s.doc_id WHERE s.doc_id IS NOT NULL AND s.doc_id != '' """) - + # Independent producers can assign different archive paths to the + # same identifier before either has been merged into the main DB. + aliases = main_cur.execute(f""" + SELECT s.id, s.doc_id, COALESCE(pmc.id, pub.id) FROM {shard_alias}.papers s + LEFT JOIN papers pmc ON pmc.pmcid=s.pmcid AND pmc.pmcid<>'' + LEFT JOIN papers pub ON pub.pmid=s.pmid AND pub.pmid<>'' + WHERE s.doc_id<>'' AND s.id NOT IN (SELECT shard_pid FROM {temp_map_table}) + """).fetchall() + for local_id, path, main_id in aliases: + if main_id is None or shard_db not in to_record: + raise RuntimeError(f"Cannot verify overlapping article {path} in {shard_db.name}. " + "Rebuild this shard from the original archives before merging.") + known = main_cur.execute("SELECT 1 FROM files WHERE path=? AND paper_id=?", (path, main_id)).fetchone() + main_cur.execute(f"INSERT INTO {temp_map_table} VALUES (?, ?, ?)", (local_id, main_id, not known)) + # Insert chunks with remapped paper_id + main_cur.execute("CREATE TABLE IF NOT EXISTS merged_paper_revisions (paper_id INTEGER PRIMARY KEY)") main_cur.execute(f""" INSERT OR IGNORE INTO chunks(paper_id, ord, text, page, in_index) SELECT pm.main_pid, c.ord, c.text, {page}, 0 FROM {shard_alias}.chunks c JOIN {temp_map_table} pm ON pm.shard_pid = c.paper_id - WHERE NOT EXISTS ( + WHERE NOT pm.new_alias AND pm.main_pid NOT IN (SELECT paper_id FROM merged_paper_revisions) + AND NOT EXISTS ( SELECT 1 FROM chunks mc WHERE mc.paper_id = pm.main_pid AND mc.ord = c.ord ) """) + chunks_merged = main_cur.rowcount + + if shard_db in to_record: + shard_id = to_record[shard_db][0] + previous = merged_checkpoints(main_conn, shard_id).get(shard_id, {}) + chunks_merged += _merge_revised_papers( + main_conn, shard_alias, temp_map_table, previous.get("segment_sequence", 0) + ) # 3) BULK MERGE FILES # Insert/replace files with remapped paper_id @@ -184,23 +374,15 @@ def merge_shard_databases( # Drop temp table immediately after use main_cur.execute(f"DROP TABLE IF EXISTS {temp_map_table}") - # Commit this shard before DETACH: the INSERTs above opened a - # transaction, and DETACH fails while it holds the shard (#1). - main_conn.commit() - # Count rows after merge for statistics papers_after = main_cur.execute( "SELECT COUNT(*) FROM papers" ).fetchone()[0] - chunks_after = main_cur.execute( - "SELECT COUNT(*) FROM chunks" - ).fetchone()[0] files_after = main_cur.execute( "SELECT COUNT(*) FROM files" ).fetchone()[0] papers_merged = papers_after - papers_before - chunks_merged = chunks_after - chunks_before files_merged = files_after - files_before stats["papers"] += papers_merged @@ -215,18 +397,25 @@ def merge_shard_databases( f"({elapsed:.1f}s)" ) - except Exception: - # Merge a shard completely or not at all, and end the transaction - # so the shard can be detached. - main_conn.rollback() + if shard_db in to_record: + main_cur.execute( + "CREATE TABLE IF NOT EXISTS merged_shard_checkpoints (" + "shard_id INTEGER PRIMARY KEY, checkpoint TEXT NOT NULL)" + ) + main_cur.execute( + "INSERT OR REPLACE INTO merged_shard_checkpoints VALUES (?, ?)", to_record[shard_db] + ) + + # Commit this shard before detaching or deleting its only copy. + commit_transaction(main_conn) + except BaseException: + rollback_transaction(main_conn) raise finally: - # Always detach the shard database. A failure ends the merge: a - # shard left attached makes every ATTACH after the tenth fail (#1). try: main_cur.execute(f"DETACH DATABASE {shard_alias}") - except sqlite3.Error as e: - raise ShardDetachError(f"could not detach {shard_db.name}: {e}") from e + except sqlite3.Error as error: + raise ShardDetachError(f"could not detach {shard_db.name}: {error}") from error # Delete shard DB after successful merge if delete_after_merge: @@ -238,20 +427,13 @@ def merge_shard_databases( f"[merge] WARNING: could not delete {shard_db.name}: {e}" ) - except ShardDetachError: - raise except Exception as e: _eprint( f"[merge] ERROR processing {shard_db.name}: " f"{e.__class__.__name__}: {e}" ) - import traceback - traceback.print_exc() - # Continue with next shard - - # Commit all changes - main_conn.commit() - + raise + _eprint( f"[merge] Complete: {stats['papers']} papers, {stats['chunks']} chunks, " f"{stats['files']} files from {stats['shards']} shard(s)" diff --git a/src/litkit/index/ids.py b/src/litkit/index/ids.py index d12d8b3..506b9df 100644 --- a/src/litkit/index/ids.py +++ b/src/litkit/index/ids.py @@ -35,9 +35,84 @@ def make_id_selector(ids_like: list[int] | np.ndarray) -> Any: ids_like: List or array of integer IDs Returns: - FAISS IDSelectorBatch over a copy of the IDs + FAISS IDSelectorBatch over a copy of the IDs, which it also keeps as + ``_litkit_ids`` for _remove_mapped_ivf_ids """ - return faiss.IDSelectorBatch(np.asarray(ids_like, dtype="int64")) + ids_arr = np.array(ids_like, dtype="int64") + selector = faiss.IDSelectorBatch(ids_arr) + # A selector only answers is_member(). The IVF removal path needs the IDs + # themselves; without them it tests every stored ID in Python. + selector._litkit_ids = ids_arr + return selector + + +def _remove_mapped_ivf_ids(index, core, selector): + """Copy surviving compressed codes and compact their internal labels together.""" + external = faiss.vector_to_array(index.id_map) + requested = selector if isinstance(selector, np.ndarray) else getattr(selector, "_litkit_ids", None) + if requested is None: + removed = np.fromiter((selector.is_member(int(i)) for i in external), dtype=bool, count=len(external)) + else: + removed = np.isin(external, requested) + count = int(removed.sum()) + if not count: + return 0 + + # IndexIDMap2.remove_ids compacts id_map, but IVF keeps the old internal + # labels in its inverted lists. Assemble a complete replacement before + # touching the live index. Reusing PQ codes preserves survivor scores. + keep = ~removed + new_labels = np.cumsum(keep, dtype=np.int64) - 1 + lists = core.invlists + compact = faiss.ArrayInvertedLists(core.nlist, core.code_size) + seen = np.zeros(len(external), dtype=bool) + for number in range(core.nlist): + size = lists.list_size(number) + if not size: + continue + labels_ptr = lists.get_ids(number) + try: + labels = faiss.rev_swig_ptr(labels_ptr, size).copy() + finally: + lists.release_ids(number, labels_ptr) + if labels.min() < 0 or labels.max() >= len(external): + raise ValueError("IVF labels do not match the saved ID map. Rebuild the index from its source data.") + seen[labels] = True + surviving = keep[labels] + if surviving.any(): + ids = new_labels[labels[surviving]] + codes_ptr = lists.get_codes(number) + try: + codes = faiss.rev_swig_ptr(codes_ptr, size * core.code_size).reshape(size, core.code_size) + kept_codes = codes[surviving] + compact.add_entries(number, len(ids), faiss.swig_ptr(ids), faiss.swig_ptr(kept_codes)) + finally: + lists.release_codes(number, codes_ptr) + if not seen.all() or int(compact.compute_ntotal()) != len(external) - count: + raise ValueError("IVF labels do not match the saved ID map. Rebuild the index from its source data.") + + direct_map = core.direct_map.type + core.set_direct_map_type(faiss.DirectMap.NoMap) + core.replace_invlists(compact, True) + compact.thisown = False # The IVF index now owns the copied lists. + core.ntotal = index.ntotal = len(external) - count + faiss.copy_array_to_vector(external[keep], index.id_map) + index.construct_rev_map() + core.set_direct_map_type(direct_map) + return count + + +def copy_hnsw_without_ids(source, target, replacing): + """Rebuild a graph in the separate target index, omitting replaced nodes.""" + target.reset() + old_ids = faiss.vector_to_array(source.id_map) + core = faiss.downcast_index(source.index) + for start in range(0, len(old_ids), 4096): + batch = old_ids[start:start + 4096] + keep = np.array([i not in replacing for i in batch], dtype=bool) + if keep.any(): + vectors = core.reconstruct_n(start, len(batch)) + target.add_with_ids(vectors[keep], batch[keep]) def safe_remove_ids(index: faiss.Index, sel: Any) -> int: @@ -57,9 +132,11 @@ def safe_remove_ids(index: faiss.Index, sel: Any) -> int: from litkit.index.introspection import kind_and_core # Check index type - HNSW doesn't support removal, skip silently - kind, _ = kind_and_core(index) + kind, core = kind_and_core(index) if kind == INDEX_KIND_HNSW: return 0 # No-op, no warning - HNSW doesn't support ID removal + if isinstance(index, faiss.IndexIDMap2) and isinstance(core, faiss.IndexIVF): + return _remove_mapped_ivf_ids(index, core, sel) # Handle raw array fallback (when no IDSelector available) if isinstance(sel, np.ndarray): diff --git a/src/litkit/segments/constants.py b/src/litkit/segments/constants.py index 03ccd7c..0eba999 100644 --- a/src/litkit/segments/constants.py +++ b/src/litkit/segments/constants.py @@ -5,6 +5,13 @@ import os +from litkit.segments.discovery import ( + CHUNK_SEGMENT_PREFIX as CHUNK_SEGMENT_PREFIX, + PAPER_SEGMENT_PREFIX as PAPER_SEGMENT_PREFIX, + PENDING_SUFFIX as PENDING_SUFFIX, + SEGMENT_EXTENSION as SEGMENT_EXTENSION, +) + # --------------------------------------------------------------------------- # Segment File Configuration # --------------------------------------------------------------------------- @@ -25,11 +32,6 @@ # Segment File Naming # --------------------------------------------------------------------------- -# Segment file patterns -PAPER_SEGMENT_PREFIX = "paper_seg" -CHUNK_SEGMENT_PREFIX = "chunk_seg" -SEGMENT_EXTENSION = ".npz" - # Build metadata file BUILD_META_FILENAME = "build_meta.json" diff --git a/src/litkit/segments/discovery.py b/src/litkit/segments/discovery.py new file mode 100644 index 0000000..7670a68 --- /dev/null +++ b/src/litkit/segments/discovery.py @@ -0,0 +1,125 @@ +"""Discover consumer input. Also run directly on cluster hosts without LitKit installed.""" + +import argparse +import json +import re +import sys +from itertools import chain, islice +from pathlib import Path + +PAPER_SEGMENT_PREFIX = "paper_seg" +CHUNK_SEGMENT_PREFIX = "chunk_seg" +SEGMENT_EXTENSION = ".npz" +PENDING_SUFFIX = "_pending" + + +def segment_order(name): + """Sort older formats first, then by producer, numeric batch order, and filename.""" + match = re.match(r"^(?:paper|chunk)_seg_(-?\d+)_(b?)(\d+)_", name) + if match: + return bool(match[2]), int(match[1]), int(match[3]), name + return False, -1, -1, name + + +def is_pending_segment(name): + # Older NumPy writers appended .npz to a filename ending in .npz.pending. + if name.endswith(".ingesting"): + name = name[:-len(".ingesting")] + return name.endswith((PENDING_SUFFIX + SEGMENT_EXTENSION, ".npz.pending", ".npz.pending.npz")) + + +def segment_shard(name): + match = re.match(r"(?:paper|chunk)_seg_(-?\d+)_", name) or re.match( + r"(?:papers|chunks)(?:_|\.seg\.)sh(\d+)[_.]", name + ) + return int(match[1]) if match else None + + +def iter_segment_files(seg_dir, kind): + """Yield finalized segments and interrupted consumer claims, including legacy names.""" + prefix = PAPER_SEGMENT_PREFIX if kind == "papers" else CHUNK_SEGMENT_PREFIX + for pattern in (prefix + "_*", kind + "_*", kind + ".seg.*"): + for suffix in (SEGMENT_EXTENSION, SEGMENT_EXTENSION + ".ingesting"): + for path in seg_dir.glob(pattern + suffix): + if not is_pending_segment(path.name) and path.is_file(): + yield path + + +def iter_shard_segment_files(seg_dir, kind, shard_id): + """Include unnumbered legacy files and files explicitly owned by this shard.""" + for path in iter_segment_files(seg_dir, kind): + if segment_shard(path.name) in (None, shard_id): + yield path + + +def _shard_count(directory, segments, transfers=(), ids=()): + roots = chain((directory / path.name for path in transfers), [directory]) + for root in roots: + try: + count = json.loads((root / "build_meta.json").read_text())["num_shards"] + if type(count) is int and count > 0: + return count + except FileNotFoundError: + continue # A committed transfer may have just moved its metadata to the public directory. + except (ValueError, KeyError, TypeError): + pass + print( + "Cannot read shard count from build_meta.json. Checking producer files.", + file=sys.stderr, + ) + # Older builds may lack metadata. Completed producers include shards that + # emitted no segments or whose last segment has already been consumed. + ids = list(ids) + for marker in directory.glob("producer_*.done"): + match = re.fullmatch(r"producer_(\d+)\.done", marker.name) + if match: + ids.append(int(match[1])) + for path in segments: + shard_id = segment_shard(path.name) + if shard_id is not None and shard_id >= 0: + ids.append(shard_id) + return max(ids) + 1 if ids else 2 # historic resume-script default + + +def resume_shard_count(directory): + """Return zero when caught up, otherwise the shard count needed by the consumer.""" + sqlite_dir = directory.parent / "sqlite" + transfers = [] + ids = [] + for ready in sqlite_dir.glob(".litkit-handoff-*/READY"): + suffix = ready.parent.name.rsplit("-", 1)[-1] + if suffix.isdecimal() and ready.is_file(): + transfers.append(ready.parent) + ids.append(int(suffix)) + for db in sqlite_dir.glob("litkit_shard_*.sqlite3"): + suffix = db.stem.rsplit("_", 1)[-1] + if suffix.isdecimal(): + ids.append(int(suffix)) + segments = chain(iter_segment_files(directory, "papers"), iter_segment_files(directory, "chunks")) + first = next(segments, None) + if first is None and not ids: + return 0 + return _shard_count(directory, chain([first], segments) if first else (), transfers, ids) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("operation", choices=("count", "sample", "shards", "resume")) + parser.add_argument("directory", type=Path) + args = parser.parse_args() + files = chain( + iter_segment_files(args.directory, "papers"), iter_segment_files(args.directory, "chunks") + ) + if args.operation == "count": + print(sum(1 for _ in files)) + elif args.operation == "sample": + for path in islice(files, 5): + print(path) + elif args.operation == "resume": + print(resume_shard_count(args.directory)) + else: + print(_shard_count(args.directory, files)) + + +if __name__ == "__main__": + main() diff --git a/src/litkit/segments/ingest.py b/src/litkit/segments/ingest.py index 8c13d3a..dc163eb 100644 --- a/src/litkit/segments/ingest.py +++ b/src/litkit/segments/ingest.py @@ -14,21 +14,23 @@ import sqlite3 import sys import time +from contextlib import nullcontext from dataclasses import dataclass +from functools import partial from pathlib import Path from typing import TYPE_CHECKING import faiss import numpy as np +from litkit.db.indexing import mark_in_index from litkit.db.queries import preload_paper_id_map, preload_chunk_id_map +from litkit.segments.discovery import iter_segment_files, segment_order +from litkit.segments.writer import text_digest from litkit.index.dedup import add_with_ids_dedup from litkit.index.io import faiss_save, faiss_save_force -from litkit.index.constants import INDEX_KIND_HNSW -from litkit.index.ids import make_id_selector, safe_remove_ids -from litkit.index.introspection import kind_and_core -from litkit.segments.constants import SEGMENT_EXTENSION -from litkit.segments.writer import PENDING_SUFFIX +from litkit.index.ids import copy_hnsw_without_ids, make_id_selector, safe_remove_ids +from litkit.index.introspection import faiss_present_ids, kind_and_core if TYPE_CHECKING: from litkit.config.paths import WorkspacePaths @@ -61,70 +63,181 @@ def _glob_segment_files(outdir: Path, kind: str) -> list[Path]: kind: Either "papers" or "chunks" Returns: - Sorted list of segment file paths (including .ingesting files, excluding - pending ones that a producer has not finalized) + Sorted list of segment file paths (including .ingesting files) """ - cand = [] - - if kind == "papers": - # Current style: paper_seg_*.npz (matches PAPER_SEGMENT_PREFIX from constants.py) - cand.extend(outdir.glob("paper_seg_*.npz")) - # Legacy styles for backward compatibility - cand.extend(outdir.glob("papers_*.npz")) - cand.extend(outdir.glob("papers.seg.*.npz")) - # In-progress files from previous interrupted runs - cand.extend(outdir.glob("paper_seg_*.npz.ingesting")) - cand.extend(outdir.glob("papers_*.npz.ingesting")) - cand.extend(outdir.glob("papers.seg.*.npz.ingesting")) - else: # chunks - # Current style: chunk_seg_*.npz (matches CHUNK_SEGMENT_PREFIX from constants.py) - cand.extend(outdir.glob("chunk_seg_*.npz")) - # Legacy styles for backward compatibility - cand.extend(outdir.glob("chunks_*.npz")) - cand.extend(outdir.glob("chunks.seg.*.npz")) - # In-progress files from previous interrupted runs - cand.extend(outdir.glob("chunk_seg_*.npz.ingesting")) - cand.extend(outdir.glob("chunks_*.npz.ingesting")) - cand.extend(outdir.glob("chunks.seg.*.npz.ingesting")) - - # paper_seg_*.npz also matches unfinished *_pending.npz files; a segment is - # visible only after the producer's finalize() renames it (#4). - pending = f"{PENDING_SUFFIX}{SEGMENT_EXTENSION}" - return sorted(p for p in cand if not p.name.endswith(pending)) + # Finish earlier formats first. Current producer filenames contain a + # fixed-width sequence within each shard that survives process restarts. + return sorted(iter_segment_files(outdir, kind), key=lambda p: segment_order(p.name)) -def _drop_ids_already_indexed( - index: faiss.Index, ids: np.ndarray, X: np.ndarray -) -> tuple[np.ndarray, np.ndarray]: - """Drop the vectors whose IDs an HNSW index already holds. +def _report_segment_error(errors: list[str] | None, path: Path, error: Exception) -> None: + message = f"{path.name}: {type(error).__name__}: {error}" + _eprint(f"[segments] ERROR ingesting {message}") + if errors is not None: + errors.append(message) - For a claimed (.ingesting) file left by an earlier run, which may have been - killed after a save covered the file but before it deleted the file. HNSW - can't remove vectors, so adding them again would duplicate them (#2). Other - indexes replace them, as add_with_ids_dedup() does for any segment. - """ - if not isinstance(index, faiss.IndexIDMap2) or index.ntotal == 0: - return ids, X - if kind_and_core(index)[0] != INDEX_KIND_HNSW: - return ids, X - keep = ~np.isin(ids, faiss.vector_to_array(index.id_map)) - return ids[keep], X[keep] +def _revised_inputs(conn, kind): + """Only revised articles need a content check across producer shards.""" + if not conn.execute("SELECT 1 FROM sqlite_master WHERE name='merged_paper_revisions'").fetchone(): + return {}, {} + fields = "p.id, p.id, NULL, p.embedding_text" if kind == "papers" else "c.id, p.id, c.ord, c.text" + chunks = "" if kind == "papers" else "JOIN chunks c ON c.paper_id=p.id" + rows = conn.execute(f"SELECT {fields} FROM merged_paper_revisions r " + f"JOIN papers p ON p.id=r.paper_id {chunks}") + documents, numeric = {}, {} + for row_id, paper_id, ordinal, text in rows: + digest = text_digest(text) + documents.setdefault(paper_id, {})[ordinal] = digest + numeric[row_id] = digest + return documents, numeric -def _remove_saved_segments(paths: list[Path]) -> None: - """Delete consumed segment files once a successful save covers them (#2). - A file that can't be deleted stays claimed, and the next run skips the - vectors it already holds (see _drop_ids_already_indexed). - """ - for path in paths: +def _read_segment(conn, path, kind, papers, chunks, revisions, numeric_ids): + """Resolve IDs and accept vectors whose embedding input matches the current revision.""" + by_paper, by_id = revisions + with np.load(path, mmap_mode="r", allow_pickle=True) as segment: + fields = set(segment.files) + if "kind" in fields and str(segment["kind"].item()).strip() != kind: + raise ValueError(f"wrong segment kind for {kind} ingester") + if kind == "papers" and {"doc_ids", "vecs"} <= fields: + docs = [str(doc) for doc in segment["doc_ids"]] + ids = [papers.get(doc) for doc in docs] + expected = [by_paper[i].get(None, b"") if i in by_paper else None for i in ids] + elif kind == "chunks" and {"paper_doc_ids", "ords", "vecs"} <= fields: + keys = [(papers.get(str(doc)), int(ordinal)) for doc, ordinal in + zip(segment["paper_doc_ids"], segment["ords"], strict=True)] + ids = [chunks.get(key) for key in keys] + expected = [by_paper[i].get(ordinal, b"") if i in by_paper else None for i, ordinal in keys] + elif "ids" in fields and {"vecs", "emb"} & fields: + # Numeric legacy segments must still resolve to live main-database rows. + if not numeric_ids: + numeric_ids.update(row[0] for row in conn.execute(f"SELECT id FROM {kind}")) + raw = segment["ids"].astype(np.int64) + ids = [i if i in numeric_ids else None for i in raw] + expected = [by_id.get(i) for i in raw] + else: + raise ValueError(f"Segment missing required keys: {segment.files}") + vectors = np.ascontiguousarray(segment["vecs" if "vecs" in fields else "emb"], dtype=np.float32) + if "text_hashes" in fields: + hashes = segment["text_hashes"] + if hashes.dtype != np.dtype("V32") or hashes.shape != (len(ids),): + raise ValueError("Invalid embedding text hashes in segment") + else: + hashes = [None] * len(ids) + if vectors.ndim != 2 or len(vectors) != len(ids): + raise ValueError("Segment vector shape does not match its IDs") + resolved = {} + unresolved = unverified = 0 + for position, (row_id, current, digest) in enumerate(zip(ids, expected, hashes, strict=True)): + if current is not None and digest is None: + unverified += 1 + elif current is not None and current != bytes(digest): + pass # Authenticated embedding for an older revision, including a deleted ordinal. + elif row_id is None: + unresolved += 1 + else: + # Different producer document IDs can now name the same paper. + # Only the final matching vector for a given index ID is needed. + resolved[row_id] = position + if unresolved or unverified: + disposition = "unverified" if unverified else "unresolved" + _eprint(f"[segments] {path.name}: {unresolved} unresolved IDs, " + f"{unverified} vectors without evidence for the current text. Preserving the input file.") + else: + disposition = None + return np.fromiter(resolved, dtype=np.int64), vectors[list(resolved.values())], disposition + + +def _finish_segment(path, disposition): + if disposition: + path.replace(path.with_suffix(f".{disposition}.{time.time_ns()}")) + else: + os.remove(path) + + +def remove_obsolete_chunks(conn, index, path, faiss_lock, db_lock, lock_factory): + if not conn.execute("SELECT 1 FROM sqlite_master WHERE name='obsolete_chunk_vectors'").fetchone(): + return + ids = [row[0] for row in conn.execute("SELECT id FROM obsolete_chunk_vectors")] + if ids: + with lock_factory(faiss_lock): + safe_remove_ids(index, make_id_selector(ids)) + faiss_save_force(index, path) + with lock_factory(db_lock) if db_lock else nullcontext(), conn: + conn.executemany("DELETE FROM obsolete_chunk_vectors WHERE id=?", ((i,) for i in ids)) + + +def _ingest_segments(conn, index, kind, candidates, paper_map, chunk_map, index_path, + faiss_lock, db_lock, lock_factory, save_every, errors): + """Keep claims in batch order until their vectors and SQLite marks are durable.""" + revisions = _revised_inputs(conn, kind) + numeric_ids = set() + hnsw_ids = None + if kind_and_core(index)[0] == "hnsw": + hnsw_ids = faiss_present_ids(index) or set() + pending = [] + added_total = 0 + + def finish_saved(): + with lock_factory(db_lock) if db_lock else nullcontext(), conn: + cur = conn.cursor() + for _, _, ids in pending: + mark_in_index(cur, kind, ids.tolist()) + for path, disposition, _ in pending: + _finish_segment(path, disposition) + pending.clear() + + for count, path in enumerate(candidates, 1): + claimed = path if path.name.endswith(".ingesting") else path.with_suffix(".npz.ingesting") + if claimed != path: + try: + os.replace(path, claimed) + except FileNotFoundError: + continue + except OSError as error: + _report_segment_error(errors, path, error) + break try: - os.remove(path) - except FileNotFoundError: - pass - except OSError as e: - _eprint(f"[segments] WARNING: could not remove consumed segment {path.name}: {e}") - paths.clear() + ids, vectors, disposition = _read_segment(conn, claimed, kind, paper_map, chunk_map, + revisions, numeric_ids) + except Exception as error: + if claimed != path: + os.replace(claimed, path) + _report_segment_error(errors, path, error) + # A later segment may revise the same ID. Finish this prefix before retry. + break + if not ids.size: + _finish_segment(claimed, disposition) + continue + + with lock_factory(faiss_lock): + was_empty = index.ntotal == 0 + if not isinstance(index, faiss.IndexIDMap2): + index = faiss.IndexIDMap2(index) + if hnsw_ids is not None: + replacing = hnsw_ids.intersection(ids) + if replacing: + replacement = faiss.clone_index(index) + copy_hnsw_without_ids(index, replacement, replacing) + index = replacement + added, ids_added = add_with_ids_dedup(index, ids, vectors) + if hnsw_ids is not None: + hnsw_ids.update(ids_added) + pending.append((claimed, disposition, ids)) + added_total += added + save = faiss_save_force if was_empty else faiss_save + saved = save(index, index_path) + if not saved and count % max(1, int(save_every)) == 0: + saved = faiss_save(index, index_path) + if saved: + finish_saved() + + if pending: + with lock_factory(faiss_lock): + faiss_save_force(index, index_path) + finish_saved() + return index, added_total def ingest_paper_segments( @@ -137,211 +250,23 @@ def ingest_paper_segments( *, save_every: int = 2, paper_id_map: dict[str, int] | None = None, + errors: list[str] | None = None, FileLock: type | None = None, ) -> tuple[faiss.Index, int]: - """Ingest paper embedding segments from producer nodes. - - Segments contain doc_ids (globally unique file paths) and embeddings. - At ingestion time, we resolve doc_id → paper_id using the merged main DB. - - Uses atomic file claiming (.ingesting rename) to prevent race conditions - between multiple consumers. - - Args: - conn: SQLite connection to main database - paper_index: FAISS index for papers (may be wrapped in IndexIDMap2 if needed) - outdir: Directory containing segment files - faiss_lock_path: Path to FAISS lock file - paper_index_path: Path to save the paper index - db_lock_path: Path to DB lock file (optional, for commit locking) - save_every: Save index every N segment files - paper_id_map: Optional preloaded doc_id → paper_id mapping for O(1) lookups. - If None, will be loaded once at start. - FileLock: File lock class to use (pass from caller to avoid circular import) - - Returns: - (paper_index, added_count): The (possibly wrapped) index and number of vectors added. - Caller should rebind their index reference to the returned value. - """ - # Lazy import if not provided + """Save finalized paper vectors and return the index and number added.""" if FileLock is None: from litkit.concurrent.locking import FileLock as _FileLock - FileLock = _FileLock - - outdir = Path(outdir) - if not outdir.exists(): - return paper_index, 0 - - cand = _glob_segment_files(outdir, "papers") - if not cand: + FileLock = partial(_FileLock, db_lock_path=db_lock_path, faiss_lock_path=faiss_lock_path) + candidates = _glob_segment_files(Path(outdir), "papers") + if not candidates: return paper_index, 0 - - # Preload paper_id_map once if not provided (O(1) lookups vs O(N) queries) if paper_id_map is None: paper_id_map = preload_paper_id_map(conn) - _eprint(f"[segments] preloaded {len(paper_id_map)} paper ID mappings") - - # SAFETY CHECK: Refuse to ingest if DB has no paper mappings - # This catches the common error of running segment ingestion before shard DB merge if not paper_id_map: - _eprint("[segments] ERROR: paper_id_map is empty. " - "Have shard databases been merged? Aborting paper segment ingestion.") - _eprint("[segments] HINT: Run --consume-only to merge DBs before ingesting segments, " - "or ensure producers have completed and DB merge has run.") - return paper_index, 0 # Safe exit, no data loss - - cur = conn.cursor() - added_total = 0 - batch_counter = 0 - # Claimed files whose vectors are in the index but not yet in a saved copy of - # it. They are deleted only once a save covers them, so that a job killed - # before its next save can be rerun (#2). - unsaved: list[Path] = [] - - for p in cand: - is_ingesting = p.name.endswith(".npz.ingesting") - tmp = p if is_ingesting else p.with_suffix(p.suffix + ".ingesting") - - # Atomic claim: rename to .ingesting before reading - if not is_ingesting: - try: - os.replace(p, tmp) - except FileNotFoundError: - continue # Another process claimed it - except Exception: - continue - - try: - with np.load(tmp, mmap_mode="r", allow_pickle=True) as z: - # Reject wrong-kind files - if "kind" in z.files and str(z["kind"].item()).strip() != "papers": - raise ValueError("wrong segment kind for paper ingester") - - # New format: doc_ids + vecs (content-addressed) - if "doc_ids" in z.files and "vecs" in z.files: - doc_ids = z["doc_ids"] # object array of strings - X = np.ascontiguousarray(z["vecs"].astype(np.float32)) - - # Resolve doc_id → paper_id using preloaded map (O(1) lookups) - resolved_ids = [] - valid_mask = [] - for i, doc_id in enumerate(doc_ids): - doc_id_str = str(doc_id) - paper_id = paper_id_map.get(doc_id_str) - if paper_id is not None: - resolved_ids.append(paper_id) - valid_mask.append(True) - else: - valid_mask.append(False) - - # Log resolution failures for debugging canonicalization issues - missing = np.count_nonzero(~np.array(valid_mask, dtype=bool)) - if missing: - _eprint(f"[segments] WARNING: skipped {missing}/{len(doc_ids)} paper embeddings in {p.name} " - "(doc_id not found in main DB - check doc_id canonicalization)") - - if not resolved_ids: - # QUARANTINE instead of delete: prevents data loss if DB wasn't merged - quarantine_path = tmp.with_suffix(f".unresolved.{int(time.time())}") - try: - os.replace(tmp, quarantine_path) - _eprint(f"[segments] QUARANTINE: {p.name} → {quarantine_path.name} " - "(0 IDs resolved - run again after DB merge)") - except Exception: - pass # Leave .ingesting file for next attempt - continue - - # Filter to only valid entries - valid_mask = np.array(valid_mask, dtype=bool) - ids = np.array(resolved_ids, dtype=np.int64) - X = X[valid_mask] - - # Legacy format: ids + vecs (shard-local IDs, deprecated) - elif "ids" in z.files and ("vecs" in z.files or "emb" in z.files): - ids = np.ascontiguousarray(z["ids"].astype(np.int64)) - X = np.ascontiguousarray( - (z["vecs"] if "vecs" in z.files else z["emb"]).astype(np.float32) - ) - else: - raise ValueError(f"Segment missing doc_ids/vecs or ids/vecs in {p.name}") - - if ids.size == 0: - os.remove(tmp) - continue - - # Ensure IDMap2 wrapper for external ID tracking - if not isinstance(paper_index, faiss.IndexIDMap2): - paper_index = faiss.IndexIDMap2(paper_index) - - if is_ingesting: - ids, X = _drop_ids_already_indexed(paper_index, ids, X) - if ids.size == 0: - unsaved.append(tmp) # Already indexed; delete after the next save - continue - - prior_ntotal = int(getattr(paper_index, "ntotal", 0) or 0) - added, ids_added, saved = 0, [], False - - with FileLock(faiss_lock_path): - # add_with_ids_dedup handles removal internally - no explicit safe_remove_ids needed - added, ids_added = add_with_ids_dedup(paper_index, ids, X) - unsaved.append(tmp) - if added: - # Force save on first vectors, throttled save otherwise - saved = faiss_save_force(paper_index, paper_index_path) if prior_ntotal == 0 \ - else faiss_save(paper_index, paper_index_path) - - if added: - if saved: - from litkit.db.indexing import mark_in_index - if db_lock_path: - with FileLock(db_lock_path): - if len(ids_added) > 0: - mark_in_index(cur, "papers", [int(i) for i in ids_added]) - conn.commit() - else: - if len(ids_added) > 0: - mark_in_index(cur, "papers", [int(i) for i in ids_added]) - conn.commit() - # else: throttled; the file is kept until a later save covers it (#2) - - added_total += int(added or 0) - batch_counter += 1 - if saved: - _remove_saved_segments(unsaved) # This save covers every file so far - - # Periodic save - if (batch_counter % max(1, int(save_every))) == 0: - with FileLock(faiss_lock_path): - saved_now = faiss_save(paper_index, paper_index_path) - if saved_now: - _remove_saved_segments(unsaved) - from litkit.db.indexing import flush_pending_marks - if db_lock_path: - with FileLock(db_lock_path): - flush_pending_marks(cur) - conn.commit() - else: - flush_pending_marks(cur) - conn.commit() - - except Exception as e: - # On error, rename file back so it can be retried next run, unless its - # vectors are already in the index and it waits for a save - if not is_ingesting and tmp not in unsaved: - try: - os.replace(tmp, p) - except Exception: - pass - _eprint(f"[segments] ERROR ingesting {p.name}: {e.__class__.__name__}: {e}") - - # Save what the throttled saves skipped, then delete those files (#2) - if unsaved: - with FileLock(faiss_lock_path): - faiss_save_force(paper_index, paper_index_path) - _remove_saved_segments(unsaved) - - return paper_index, added_total + _eprint("[segments] No papers to resolve. Merge producer databases before ingestion.") + return paper_index, 0 + return _ingest_segments(conn, paper_index, "papers", candidates, paper_id_map, None, + paper_index_path, faiss_lock_path, db_lock_path, FileLock, save_every, errors) def ingest_chunk_segments( @@ -355,231 +280,28 @@ def ingest_chunk_segments( save_every: int = 2, paper_id_map: dict[str, int] | None = None, chunk_id_map: dict[tuple[int, int], int] | None = None, + errors: list[str] | None = None, FileLock: type | None = None, ) -> tuple[faiss.Index, int]: - """Ingest chunk embedding segments from producer nodes. - - Segments contain (paper_doc_id, ord) pairs and embeddings. - At ingestion time, we resolve (paper_doc_id, ord) → chunk_id using the merged main DB. - - Uses atomic file claiming (.ingesting rename) to prevent race conditions. - - Safe file-handling: - - rename ".npz" -> ".npz.ingesting" before reading (atomic) - - if already ".npz.ingesting", read in place, skipping IDs an HNSW index holds - - once a successful save covers its vectors, delete the .ingesting file - - on failure, rename back so it can be retried next run - - Args: - conn: SQLite connection to main database - chunk_index: FAISS index for chunks (may be wrapped in IndexIDMap2 if needed) - outdir: Directory containing segment files - faiss_lock_path: Path to FAISS lock file - chunk_index_path: Path to save the chunk index - db_lock_path: Path to DB lock file (optional, for commit locking) - save_every: Save index every N segment files - paper_id_map: Optional preloaded doc_id → paper_id mapping for O(1) lookups. - If None, will be loaded once at start. - chunk_id_map: Optional preloaded (paper_id, ord) → chunk_id mapping for O(1) lookups. - If None, will be loaded once at start. - FileLock: File lock class to use (pass from caller to avoid circular import) - - Returns: - (chunk_index, added_count): The (possibly wrapped) index and number of vectors added. - Caller should rebind their index reference to the returned value. - """ - # Lazy import if not provided + """Remove retired passages, save finalized chunk vectors and return the index and number added.""" if FileLock is None: from litkit.concurrent.locking import FileLock as _FileLock - FileLock = _FileLock - + FileLock = partial(_FileLock, db_lock_path=db_lock_path, faiss_lock_path=faiss_lock_path) outdir = Path(outdir) if not outdir.exists(): return chunk_index, 0 - - # Ensure external ID mapping is present for robust remove and add + remove_obsolete_chunks(conn, chunk_index, chunk_index_path, faiss_lock_path, db_lock_path, FileLock) if not isinstance(chunk_index, faiss.IndexIDMap2): chunk_index = faiss.IndexIDMap2(chunk_index) - - cand = _glob_segment_files(outdir, "chunks") - if not cand: + candidates = _glob_segment_files(outdir, "chunks") + if not candidates: return chunk_index, 0 - - # Preload ID maps once if not provided (O(1) lookups vs O(N) queries) if paper_id_map is None: paper_id_map = preload_paper_id_map(conn) - _eprint(f"[segments] preloaded {len(paper_id_map)} paper ID mappings") if chunk_id_map is None: chunk_id_map = preload_chunk_id_map(conn) - _eprint(f"[segments] preloaded {len(chunk_id_map)} chunk ID mappings") - - # SAFETY CHECK: Refuse to ingest if DB has no mappings - # This catches the common error of running segment ingestion before shard DB merge if not paper_id_map or not chunk_id_map: - _eprint("[segments] ERROR: paper_id_map or chunk_id_map is empty. " - "Have shard databases been merged? Aborting chunk segment ingestion.") - _eprint("[segments] HINT: Run --consume-only to merge DBs before ingesting segments, " - "or ensure producers have completed and DB merge has run.") - return chunk_index, 0 # Safe exit, no data loss - - cur = conn.cursor() - added_total = 0 - batch_counter = 0 - # Claimed files whose vectors are in the index but not yet in a saved copy of - # it. They are deleted only once a save covers them, so that a job killed - # before its next save can be rerun (#2). - unsaved: list[Path] = [] - - for p in cand: - # Normalize to a working path "tmp" that we always read from: - is_ingesting = p.name.endswith(".npz.ingesting") - tmp = p if is_ingesting else p.with_suffix(p.suffix + ".ingesting") - - if not is_ingesting: - try: - # Claim atomically; another writer may race us. - os.replace(p, tmp) - except FileNotFoundError: - continue - except Exception: - # Could not claim; skip - continue - - try: - with np.load(tmp, mmap_mode="r", allow_pickle=True) as z: - # Reject wrong-kind files (old .seg has 'kind') - if "kind" in z.files and str(z["kind"].item()).strip() != "chunks": - raise ValueError("wrong segment kind for chunk ingester") - - # New format: paper_doc_ids + ords + vecs (content-addressed) - if "paper_doc_ids" in z.files and "ords" in z.files and "vecs" in z.files: - paper_doc_ids = z["paper_doc_ids"] # object array of strings - ords = z["ords"] # int32 array - X = np.ascontiguousarray(z["vecs"].astype(np.float32)) - - # Resolve (paper_doc_id, ord) → chunk_id using preloaded maps (O(1) lookups) - resolved_ids = [] - valid_mask = [] - for i, (doc_id, ord_val) in enumerate(zip(paper_doc_ids, ords)): - doc_id_str = str(doc_id) - ord_int = int(ord_val) - - # Get paper_id from preloaded map - paper_id = paper_id_map.get(doc_id_str) - - if paper_id is not None: - # Get chunk_id from preloaded map - chunk_id = chunk_id_map.get((paper_id, ord_int)) - - if chunk_id is not None: - resolved_ids.append(chunk_id) - valid_mask.append(True) - else: - valid_mask.append(False) - else: - valid_mask.append(False) - - # Log resolution failures for debugging canonicalization issues - missing = np.count_nonzero(~np.array(valid_mask, dtype=bool)) - if missing: - _eprint(f"[segments] WARNING: skipped {missing}/{len(paper_doc_ids)} chunk embeddings in {p.name} " - "(doc_id/ord not found in main DB - check doc_id canonicalization)") - - if not resolved_ids: - # QUARANTINE instead of delete: prevents data loss if DB wasn't merged - quarantine_path = tmp.with_suffix(f".unresolved.{int(time.time())}") - try: - os.replace(tmp, quarantine_path) - _eprint(f"[segments] QUARANTINE: {p.name} → {quarantine_path.name} " - "(0 IDs resolved - run again after DB merge)") - except Exception: - pass # Leave .ingesting file for next attempt - continue - - # Filter to only valid entries - valid_mask = np.array(valid_mask, dtype=bool) - ids = np.array(resolved_ids, dtype=np.int64) - X = X[valid_mask] - - # Legacy format: ids + vecs (shard-local IDs, deprecated) - elif "ids" in z.files and "vecs" in z.files: - ids = np.ascontiguousarray(z["ids"].astype(np.int64)) - X = np.ascontiguousarray(z["vecs"].astype(np.float32)) - elif "ids" in z.files and "emb" in z.files: - ids = np.ascontiguousarray(z["ids"].astype(np.int64)) - X = np.ascontiguousarray(z["emb"].astype(np.float32)) - else: - raise ValueError(f"Segment missing required keys: {z.files}") - - if ids.size == 0: - os.remove(tmp) - continue - - if is_ingesting: - ids, X = _drop_ids_already_indexed(chunk_index, ids, X) - if ids.size == 0: - unsaved.append(tmp) # Already indexed; delete after the next save - continue - - prior_ntotal = int(getattr(chunk_index, "ntotal", 0) or 0) - added, ids_added, saved = 0, [], False - - with FileLock(faiss_lock_path): - # add_with_ids_dedup handles removal internally - no explicit safe_remove_ids needed - added, ids_added = add_with_ids_dedup(chunk_index, ids, X) - unsaved.append(tmp) - if added: - saved = faiss_save_force(chunk_index, chunk_index_path) if prior_ntotal == 0 \ - else faiss_save(chunk_index, chunk_index_path) - - if added: - if saved: - from litkit.db.indexing import mark_in_index - if db_lock_path: - with FileLock(db_lock_path): - if len(ids_added) > 0: - mark_in_index(cur, "chunks", [int(i) for i in ids_added]) - conn.commit() - else: - if len(ids_added) > 0: - mark_in_index(cur, "chunks", [int(i) for i in ids_added]) - conn.commit() - # else: throttled; the file is kept until a later save covers it (#2) - - added_total += int(added) - batch_counter += 1 - if saved: - _remove_saved_segments(unsaved) # This save covers every file so far - - # Periodic save - if (batch_counter % max(1, int(save_every))) == 0: - with FileLock(faiss_lock_path): - saved_now = faiss_save(chunk_index, chunk_index_path) - if saved_now: - _remove_saved_segments(unsaved) - from litkit.db.indexing import flush_pending_marks - if db_lock_path: - with FileLock(db_lock_path): - flush_pending_marks(cur) - conn.commit() - else: - flush_pending_marks(cur) - conn.commit() - - except Exception as e: - # If we claimed it, put it back so another run can retry, unless its - # vectors are already in the index and it waits for a save. - if not is_ingesting and tmp not in unsaved: - try: - os.replace(tmp, p) - except Exception: - pass - _eprint(f"[segments] ERROR ingesting {p.name}: {e.__class__.__name__}: {e}") - - # Save what the throttled saves skipped, then delete those files (#2) - if unsaved: - with FileLock(faiss_lock_path): - faiss_save_force(chunk_index, chunk_index_path) - _remove_saved_segments(unsaved) - - return chunk_index, added_total + _eprint("[segments] No passages to resolve. Merge producer databases before ingestion.") + return chunk_index, 0 + return _ingest_segments(conn, chunk_index, "chunks", candidates, paper_id_map, chunk_id_map, + chunk_index_path, faiss_lock_path, db_lock_path, FileLock, save_every, errors) diff --git a/src/litkit/segments/metadata.py b/src/litkit/segments/metadata.py index e79db8e..961c5bb 100644 --- a/src/litkit/segments/metadata.py +++ b/src/litkit/segments/metadata.py @@ -4,16 +4,16 @@ from __future__ import annotations import json +import sqlite3 import sys +from contextlib import nullcontext +from itertools import chain from pathlib import Path -from litkit.segments.constants import ( - BUILD_META_FILENAME, - PAPER_SEGMENT_PREFIX, - CHUNK_SEGMENT_PREFIX, - SEGMENT_EXTENSION, -) -from litkit.segments.writer import PENDING_SUFFIX +from litkit.db.handoff import completed_checkpoint, readable_database +from litkit.db.publication import read_publication +from litkit.segments.constants import BUILD_META_FILENAME +from litkit.segments.discovery import is_pending_segment, iter_segment_files, iter_shard_segment_files def _eprint(msg: str = "", *, end: str = "\n") -> None: @@ -26,26 +26,96 @@ def _eprint(msg: str = "", *, end: str = "\n") -> None: def has_segment_files(seg_dir: Path) -> bool: - """Check if directory contains any segment files. - - Args: - seg_dir: Directory to check - - Returns: - True if any finalized paper or chunk segment files exist - """ - seg_dir = Path(seg_dir) - if not seg_dir.exists(): - return False - - # Unfinished *_pending.npz files also match the globs, but aren't segments yet (#4) - pending = f"{PENDING_SUFFIX}{SEGMENT_EXTENSION}" - for prefix in (PAPER_SEGMENT_PREFIX, CHUNK_SEGMENT_PREFIX): - for p in seg_dir.glob(f"{prefix}_*{SEGMENT_EXTENSION}"): - if not p.name.endswith(pending): - return True - - return False + """Whether the consumer has any segments to ingest or finish.""" + return any(path for kind in ("papers", "chunks") for path in iter_segment_files(Path(seg_dir), kind)) + + +def verify_legacy_shard( + conn: sqlite3.Connection, shard_id: int, paper_dir: Path, chunk_dir: Path, + *, merged_db: sqlite3.Connection | None = None, before_rebuild: bool = False, +) -> None: + """Account for old producer rows, including rows committed before the first checkpoint.""" + if not before_rebuild and completed_checkpoint(conn): + return + if not conn.execute("SELECT 1 FROM files LIMIT 1").fetchone(): + return + journal = read_publication(conn) + if not before_rebuild and journal and journal.tar is not None: + # The first verified modern batch has committed but still needs its + # two staged outputs. Publication recovery checks their recorded roots. + return + + import numpy as np + + message = ( + f"Cannot verify the embeddings for legacy producer shard {shard_id}. " + "Use its original segment directory. If the producer was interrupted, " + "rebuild from the original archives in a fresh workspace." + ) + if before_rebuild: + message = ( + f"Retained shard {shard_id} still depends on vectors in the current indices. " + "Finish the previous --consume-only run to merge and detach it, or rebuild in a fresh workspace." + ) + # Old files carry only (doc_id, ord). They cannot identify which text was + # embedded after a replacement deleted chunk rows or an alias reused an ordinal. + replaced = conn.execute("SELECT MAX(id) > COUNT(*) FROM chunks").fetchone()[0] + different_texts = conn.execute( + "SELECT 1 FROM chunks GROUP BY paper_id, ord HAVING MIN(text) <> MAX(text) LIMIT 1" + ).fetchone() + for kind, directory, prefix, query in ( + ("papers", paper_dir, "paper_seg", "SELECT id, doc_id FROM papers WHERE in_index=0 OR ?"), + ("chunks", chunk_dir, "chunk_seg", "SELECT c.id, p.doc_id, c.ord FROM chunks c " + "JOIN papers p ON p.id=c.paper_id WHERE c.in_index=0 OR ?"), + ): + if any(is_pending_segment(path.name) and path.is_file() + for path in directory.glob(f"{prefix}_{shard_id}_*")): + raise RuntimeError(message) + # Healthy completed shards can be upgraded. The old checkpoint alone + # cannot distinguish a completed archive from a batch whose files were deleted. + ready_keys = set() + for path in iter_shard_segment_files(directory, kind, shard_id): + if replaced or different_texts: + if before_rebuild: + raise RuntimeError(message) + raise RuntimeError(f"Legacy segment files do not identify the stored revision. {message}") + with np.load(path, allow_pickle=True) as segment: + if "vecs" not in segment.files and "emb" not in segment.files: + continue + if kind == "papers" and "doc_ids" in segment.files: + ready_keys.update((str(doc),) for doc in segment["doc_ids"]) + elif kind == "chunks" and {"paper_doc_ids", "ords"} <= set(segment.files): + ready_keys.update(zip(segment["paper_doc_ids"], segment["ords"], strict=True)) + elif "ids" in segment.files: + # The consumer interprets these IDs in the main database. + # A shard-local integer can refer to a different main row. + raise RuntimeError(f"{path.name} has only numeric IDs and cannot verify a shard merge. {message}") + missing = (row for row in conn.execute(query, (before_rebuild,)) if tuple(row[1:]) not in ready_keys) + first = next(missing, None) + if first is None: + continue + if before_rebuild: + raise RuntimeError(message) + # A retained shard may have already been merged and its segments + # consumed. Verify the indexed content before accepting that history. + target = nullcontext(merged_db) + if merged_db is None: + source_path = Path(conn.execute("PRAGMA database_list").fetchone()[2]) + main_path = source_path.with_name("litkit.sqlite3") if source_path.name else None + if main_path is None or not main_path.is_file() or main_path == source_path: + raise RuntimeError(message) + target = readable_database(main_path) + with target as main: + for row in chain([first], missing): + if kind == "papers": + expected = conn.execute("SELECT title, abstract FROM papers WHERE id=?", (row[0],)).fetchone() + saved = main.execute("SELECT title, abstract FROM papers WHERE doc_id=? AND in_index=1", row[1:]) + else: + expected = conn.execute("SELECT text FROM chunks WHERE id=?", (row[0],)).fetchone() + saved = main.execute("SELECT c.text FROM chunks c JOIN papers p ON p.id=c.paper_id " + "WHERE p.doc_id=? AND c.ord=? AND c.in_index=1", row[1:]) + if tuple(expected) not in (tuple(values) for values in saved): + raise RuntimeError(message) def write_build_meta( diff --git a/src/litkit/segments/writer.py b/src/litkit/segments/writer.py index e8693c3..1e1a947 100644 --- a/src/litkit/segments/writer.py +++ b/src/litkit/segments/writer.py @@ -1,7 +1,7 @@ # litkit/segments/writer.py """Segment writers for embedding data in litkit. -Two-phase durability: segments are written to .npz.pending files first, +Two-phase durability: segments are written to _pending.npz files first, then atomically renamed to .npz on finalize(). This ensures: - If chunk write fails after paper write: cleanup_pending() removes orphans - Consumer only sees finalized (.npz) segments @@ -10,17 +10,19 @@ from __future__ import annotations +import hashlib import os import sys import uuid -from contextlib import suppress -from dataclasses import dataclass, field +from collections import deque +from dataclasses import dataclass from pathlib import Path from typing import Any import numpy as np from litkit.segments.constants import ( + PENDING_SUFFIX, DEFAULT_EMBED_SEGMENT_SIZE, DEFAULT_EMBED_SEGMENT_DTYPE, PAPER_SEGMENT_PREFIX, @@ -28,12 +30,6 @@ SEGMENT_EXTENSION, ) -# Suffix for pending (not-yet-finalized) segment files -# NOTE: This goes BEFORE .npz, not after, because np.savez_compressed -# auto-appends .npz if the filename doesn't already end with it. -PENDING_SUFFIX = "_pending" - - def _eprint(msg: str = "", *, end: str = "\n") -> None: """Print to stderr with flush.""" sys.stderr.write(msg + end) @@ -43,13 +39,53 @@ def _eprint(msg: str = "", *, end: str = "\n") -> None: pass -def _write_segment(path: Path, **arrays: np.ndarray) -> None: +def text_digest(text: str) -> bytes: + return hashlib.sha256(text.encode("utf-8")).digest() + + +def _write_segment(path: Path, *, texts=None, **arrays: np.ndarray) -> None: """Close the writable handle before the pending file can be renamed.""" - with path.open("wb") as segment: - np.savez_compressed(segment, **arrays) - segment.flush() - with suppress(OSError): # fsync is best effort on shared filesystems. + if texts is not None: + if len(texts) != len(arrays["vecs"]): + raise ValueError("Segment texts and vectors must have the same length") + arrays["text_hashes"] = np.array([text_digest(text) for text in texts], dtype="V32") + try: + with path.open("xb") as segment: + np.savez_compressed(segment, **arrays) + segment.flush() os.fsync(segment.fileno()) + except FileExistsError: + raise + except BaseException: + path.unlink(missing_ok=True) + raise + + +def finalized_name(pending: Path) -> str: + suffix = PENDING_SUFFIX + SEGMENT_EXTENSION + if not pending.name.endswith(suffix): + raise ValueError(f"Invalid pending segment name: {pending.name}") + return pending.name.removesuffix(suffix) + SEGMENT_EXTENSION + + +def _finalize_paths(paths: deque[Path]) -> int: + count = len(paths) + while paths: + path = paths[0] + target = path.with_name(finalized_name(path)) + if not path.exists(): + if target.is_file() or target.with_suffix(".npz.ingesting").is_file(): + paths.popleft() + continue + raise FileNotFoundError(path) + try: + path.replace(target) + finally: + # A signal or filesystem error can arrive after a successful rename. + # The consumer may already have claimed and removed the final file. + if not path.exists(): + paths.popleft() + return count def cleanup_orphan_pending_files(outdir: Path, kinds: list[str] | None = None) -> int: @@ -104,7 +140,7 @@ class SegmentWriter: Buffers embeddings and flushes to disk when segment_size is reached. Two-phase write protocol: - 1. write() -> flushes to .npz.pending files (not visible to consumer) + 1. write() -> flushes to _pending.npz files (not visible to consumer) 2. finalize() -> atomic rename .pending -> .npz (visible to consumer) If write fails, call cleanup_pending() to remove orphan .pending files. @@ -143,7 +179,7 @@ def __init__( self._segment_counter = 0 # Pending files awaiting finalization - self._pending_paths: list[Path] = [] + self._pending_paths: deque[Path] = deque() # Ensure output directory exists self.outdir.mkdir(parents=True, exist_ok=True) @@ -166,16 +202,15 @@ def add(self, doc_id: str, embedding: np.ndarray) -> None: doc_id: Unique document identifier embedding: Embedding vector """ - self._doc_ids.append(doc_id) - self._embeddings.append(embedding) - - if len(self._doc_ids) >= self.segment_size: - self.flush() - + if len(self._doc_ids) + 1 >= self.segment_size: + self.write(doc_ids=[doc_id], vecs=embedding.reshape(1, -1)) + else: + self._doc_ids.append(doc_id) + self._embeddings.append(embedding) + def write(self, *, doc_ids: list[str], vecs: np.ndarray) -> Path | None: """Batch write: add multiple embeddings and flush. - This is the primary interface for cli.py batch flushes. Writes to .pending file (call finalize() after commit to make visible). Args: @@ -185,16 +220,17 @@ def write(self, *, doc_ids: list[str], vecs: np.ndarray) -> Path | None: Returns: Path to the written .pending segment file, or None if empty """ + if len(doc_ids) != len(vecs): + raise ValueError("Segment identifiers and vectors must have the same length") if len(doc_ids) == 0: return None - # Add all to buffer and flush - for doc_id, vec in zip(doc_ids, vecs): - self._doc_ids.append(doc_id) - self._embeddings.append(vec.reshape(1, -1)) - - return self.flush() - + vecs = np.asarray(vecs).reshape(len(doc_ids), -1) + if self._doc_ids: + doc_ids = [*self._doc_ids, *doc_ids] + vecs = np.vstack([*self._embeddings, vecs]) + return self._write_batch(doc_ids, vecs) + def flush(self) -> Path | None: """Flush buffered embeddings to a .pending file. @@ -206,73 +242,43 @@ def flush(self) -> Path | None: if not self._doc_ids: return None - # Stack embeddings and convert dtype - X = np.vstack(self._embeddings) - if self.dtype == "fp16": - X = X.astype("float16") - else: - X = X.astype("float32") + return self._write_batch(self._doc_ids, np.vstack(self._embeddings)) + + def _write_batch(self, doc_ids, vecs) -> Path: + path = self.stage(self.outdir, doc_ids=doc_ids, vecs=vecs) + self._pending_paths.append(path) + + # Clear buffers + self._doc_ids.clear() + self._embeddings.clear() - # Generate unique filename with _pending suffix BEFORE .npz - # (np.savez_compressed auto-appends .npz if not present) - seg_id = f"{self.shard_id}_{self._segment_counter}_{uuid.uuid4().hex[:8]}" + return path + + def stage( + self, directory: Path, *, doc_ids: list[str], vecs: np.ndarray, sequence: int | None = None, + texts: list[str] | None = None, + ) -> Path: + """Write a complete batch to a pending file owned by the caller.""" + if len(doc_ids) != len(vecs): + raise ValueError("Segment identifiers and vectors must have the same length") prefix = PAPER_SEGMENT_PREFIX if self.kind == "papers" else self.kind - filename = f"{prefix}_{seg_id}{PENDING_SUFFIX}{SEGMENT_EXTENSION}" - path = self.outdir / filename - + order = self._segment_counter if sequence is None else f"b{sequence:020d}" + seg_id = f"{self.shard_id}_{order}_{uuid.uuid4().hex}" + path = directory / f"{prefix}_{seg_id}{PENDING_SUFFIX}{SEGMENT_EXTENSION}" _write_segment( path, - doc_ids=np.array(self._doc_ids, dtype=object), - vecs=X, # Use 'vecs' key for consistency with ingest.py + doc_ids=np.asarray(doc_ids, dtype=object), + texts=texts, + vecs=np.asarray(vecs, dtype="float16" if self.dtype == "fp16" else "float32"), kind=np.array(self.kind), ) - - n = len(self._doc_ids) - _eprint(f"[segment] Wrote {n} {self.kind} embeddings to {filename} (pending)") - - # Track pending path for finalization - self._pending_paths.append(path) - - # Clear buffers - self._doc_ids.clear() - self._embeddings.clear() self._segment_counter += 1 - return path - + def finalize(self) -> int: - """Atomically rename all _pending.npz files to final .npz names. - - Call this AFTER conn.commit() succeeds to make segments visible to consumers. - - Renames: paper_seg_0_0_abc_pending.npz -> paper_seg_0_0_abc.npz - - Returns: - Number of segments finalized - """ - finalized = 0 - for pending_path in self._pending_paths: - if not pending_path.exists(): - continue - - # Remove _pending from the stem (before .npz) - # e.g., paper_seg_0_0_abc_pending.npz -> paper_seg_0_0_abc.npz - final_path = pending_path.with_name( - pending_path.name.replace(f"{PENDING_SUFFIX}{SEGMENT_EXTENSION}", SEGMENT_EXTENSION) - ) - - try: - os.replace(pending_path, final_path) - finalized += 1 - except Exception as e: - _eprint(f"[segment] WARNING: failed to finalize {pending_path.name}: {e}") - - if finalized: - _eprint(f"[segment] Finalized {finalized} {self.kind} segment(s)") - - self._pending_paths.clear() - return finalized - + """Publish pending files. On failure the remaining paths can be retried.""" + return _finalize_paths(self._pending_paths) + def cleanup_pending(self) -> int: """Remove all pending files (for rollback scenarios). @@ -324,7 +330,7 @@ class ChunkSegmentWriter: Buffers embeddings and flushes to disk when segment_size is reached. Two-phase write protocol: - 1. write() -> flushes to .npz.pending files (not visible to consumer) + 1. write() -> flushes to _pending.npz files (not visible to consumer) 2. finalize() -> atomic rename .pending -> .npz (visible to consumer) If write fails, call cleanup_pending() to remove orphan .pending files. @@ -362,7 +368,7 @@ def __init__( self._segment_counter = 0 # Pending files awaiting finalization - self._pending_paths: list[Path] = [] + self._pending_paths: deque[Path] = deque() # Ensure output directory exists self.outdir.mkdir(parents=True, exist_ok=True) @@ -385,19 +391,18 @@ def add(self, doc_id: str, ord_: int, embedding: np.ndarray) -> None: ord_: Chunk ordinal within the document embedding: Embedding vector """ - self._doc_ids.append(doc_id) - self._ords.append(ord_) - self._embeddings.append(embedding) - - if len(self._doc_ids) >= self.segment_size: - self.flush() - + if len(self._doc_ids) + 1 >= self.segment_size: + self.write(paper_doc_ids=[doc_id], ords=[ord_], vecs=embedding.reshape(1, -1)) + else: + self._doc_ids.append(doc_id) + self._ords.append(ord_) + self._embeddings.append(embedding) + def write( self, *, paper_doc_ids: list[str], ords: list[int], vecs: np.ndarray ) -> Path | None: """Batch write: add multiple chunk embeddings and flush. - This is the primary interface for cli.py batch flushes. Writes to .pending file (call finalize() after commit to make visible). Args: @@ -408,17 +413,18 @@ def write( Returns: Path to the written .pending segment file, or None if empty """ + if len(paper_doc_ids) != len(vecs) or len(ords) != len(vecs): + raise ValueError("Segment identifiers and vectors must have the same length") if len(paper_doc_ids) == 0: return None - # Add all to buffer and flush - for doc_id, ord_, vec in zip(paper_doc_ids, ords, vecs): - self._doc_ids.append(doc_id) - self._ords.append(ord_) - self._embeddings.append(vec.reshape(1, -1)) - - return self.flush() - + vecs = np.asarray(vecs).reshape(len(paper_doc_ids), -1) + if self._doc_ids: + paper_doc_ids = [*self._doc_ids, *paper_doc_ids] + ords = [*self._ords, *ords] + vecs = np.vstack([*self._embeddings, vecs]) + return self._write_batch(paper_doc_ids, ords, vecs) + def flush(self) -> Path | None: """Flush buffered embeddings to a .pending file. @@ -430,74 +436,45 @@ def flush(self) -> Path | None: if not self._doc_ids: return None - # Stack embeddings and convert dtype - X = np.vstack(self._embeddings) - if self.dtype == "fp16": - X = X.astype("float16") - else: - X = X.astype("float32") - - # Generate unique filename with _pending suffix BEFORE .npz - # (np.savez_compressed auto-appends .npz if not present) - seg_id = f"{self.shard_id}_{self._segment_counter}_{uuid.uuid4().hex[:8]}" - filename = f"{CHUNK_SEGMENT_PREFIX}_{seg_id}{PENDING_SUFFIX}{SEGMENT_EXTENSION}" - path = self.outdir / filename - - _write_segment( - path, - paper_doc_ids=np.array(self._doc_ids, dtype=object), - ords=np.array(self._ords, dtype="int32"), - vecs=X, - kind=np.array("chunks"), - ) + return self._write_batch(self._doc_ids, self._ords, np.vstack(self._embeddings)) - n = len(self._doc_ids) - _eprint(f"[segment] Wrote {n} chunk embeddings to {filename} (pending)") - - # Track pending path for finalization + def _write_batch(self, paper_doc_ids, ords, vecs) -> Path: + path = self.stage(self.outdir, paper_doc_ids=paper_doc_ids, ords=ords, vecs=vecs) self._pending_paths.append(path) - + # Clear buffers self._doc_ids.clear() self._ords.clear() self._embeddings.clear() - self._segment_counter += 1 return path - + + def stage( + self, directory: Path, *, paper_doc_ids: list[str], ords: list[int], vecs: np.ndarray, + sequence: int | None = None, texts: list[str] | None = None, + ) -> Path: + """Write a complete batch to a pending file owned by the caller.""" + if len(paper_doc_ids) != len(vecs) or len(ords) != len(vecs): + raise ValueError("Segment identifiers and vectors must have the same length") + prefix = CHUNK_SEGMENT_PREFIX + order = self._segment_counter if sequence is None else f"b{sequence:020d}" + seg_id = f"{self.shard_id}_{order}_{uuid.uuid4().hex}" + path = directory / f"{prefix}_{seg_id}{PENDING_SUFFIX}{SEGMENT_EXTENSION}" + _write_segment( + path, + paper_doc_ids=np.asarray(paper_doc_ids, dtype=object), + texts=texts, + ords=np.asarray(ords, dtype="int32"), + vecs=np.asarray(vecs, dtype="float16" if self.dtype == "fp16" else "float32"), + kind=np.array("chunks"), + ) + self._segment_counter += 1 + return path + def finalize(self) -> int: - """Atomically rename all _pending.npz files to final .npz names. - - Call this AFTER conn.commit() succeeds to make segments visible to consumers. - - Renames: chunk_seg_0_0_abc_pending.npz -> chunk_seg_0_0_abc.npz - - Returns: - Number of segments finalized - """ - finalized = 0 - for pending_path in self._pending_paths: - if not pending_path.exists(): - continue - - # Remove _pending from the stem (before .npz) - # e.g., chunk_seg_0_0_abc_pending.npz -> chunk_seg_0_0_abc.npz - final_path = pending_path.with_name( - pending_path.name.replace(f"{PENDING_SUFFIX}{SEGMENT_EXTENSION}", SEGMENT_EXTENSION) - ) - - try: - os.replace(pending_path, final_path) - finalized += 1 - except Exception as e: - _eprint(f"[segment] WARNING: failed to finalize {pending_path.name}: {e}") - - if finalized: - _eprint(f"[segment] Finalized {finalized} chunk segment(s)") - - self._pending_paths.clear() - return finalized - + """Publish pending files. On failure the remaining paths can be retried.""" + return _finalize_paths(self._pending_paths) + def cleanup_pending(self) -> int: """Remove all pending files (for rollback scenarios). diff --git a/tests/conftest.py b/tests/conftest.py index e3e220a..fbeb80f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -210,10 +210,10 @@ def _para(topic, i): def write_tar(path, members): - """Write {member_name: text} into an uncompressed (or .tar.gz) tar at path.""" + """Write a mapping or ordered name/text pairs (including repeated names) to a tar.""" mode = "w:gz" if path.name.endswith(".tar.gz") else "w" with tarfile.open(path, mode) as tf: - for name, text in members.items(): + for name, text in members.items() if isinstance(members, dict) else members: data = text.encode("utf-8") info = tarfile.TarInfo(name) info.size = len(data) diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py new file mode 100644 index 0000000..2a04ee6 --- /dev/null +++ b/tests/integration/test_batch_resume.py @@ -0,0 +1,1467 @@ +"""Interrupted tar batches, from SQLite savepoints to the consumer's FAISS IDs.""" + +import os +import shutil +import sqlite3 +import subprocess +import sys +from concurrent.futures import ThreadPoolExecutor +from contextlib import closing, nullcontext +from functools import partial +from pathlib import Path +from threading import Event + +import faiss +import numpy as np +import pytest + +from conftest import FakeEmbedder, jats, write_tar +from litkit.build.ingest_loop import process_tar_files +from litkit.concurrent.locking import FileLock +from litkit.db import connect_db, init_db, init_shard_db, merge_shard_databases, shard_db_path +from litkit.index import faiss_load, flat_ip_index +from litkit.segments import ChunkSegmentWriter, SegmentWriter, load_checkpoint +from litkit.segments.ingest import _glob_segment_files, ingest_chunk_segments, ingest_paper_segments + + +@pytest.mark.parametrize("old_marker", [False, True]) +def test_consumer_timeout_while_producer_holds_handoff(tmp_path, old_marker): + from litkit.build.consume import run_consume_only_mode + from litkit.db.sharding import producer_shard_lock + + segments = tmp_path / "emb_segments" + segments.mkdir() + if old_marker: + (segments / "producer_0.done").touch() + index_path = tmp_path / "empty.faiss" + faiss.write_index(flat_ip_index(32), str(index_path)) + db_path = tmp_path / "litkit.sqlite3" + + def consume(): + with closing(init_db(db_path)) as db: + return run_consume_only_mode( + db, + seg_dir=segments, + num_shards=1, + paper_index_path=index_path, + chunk_index_path=index_path, + faiss_lock_path=segments / "faiss.lock", + db_lock_path=segments / "db.lock", + FileLock=FileLock, + timeout=0.1, + poll_interval=8, + ) + + with ThreadPoolExecutor() as workers, producer_shard_lock(tmp_path, 0): + stage = tmp_path / ".litkit-handoff-0" + stage.mkdir() + # On a regression the assertion releases the producer before joining the thread. + assert workers.submit(consume).result(timeout=3) is False + assert stage.is_dir() + + +@pytest.fixture +def archive(tmp_path): + tar = tmp_path / "articles.tar" + write_tar( + tar, + { + f"{i}.xml": jats(title=f"Article {i}", paragraphs=[f"Body of article {i}."]) + for i in range(3) + }, + ) + return tar + + +def test_producer_resolves_equivalent_output_directories(tmp_path, archive): + build = Build(tmp_path / "producer", archive) + build.segments.mkdir(parents=True) + alias = tmp_path / "segment-link" + try: + alias.symlink_to(build.segments, target_is_directory=True) + except OSError: + alias = build.segments / ".." / build.segments.name + assert build.run(chunk_seg_writer=ChunkSegmentWriter(alias))[2:] == (3, 6) + assert build.progress() == 3 + assert [len(ids) for ids, _ in build.consume()] == [3, 6] + assert not list(build.segments.glob(".litkit-batch-*")) + + +class Build: + def __init__(self, root, tar, *, producer=True, shard_id=0): + self.root = root + self.tar = tar + self.producer = producer + self.shard = shard_id if producer else None + self.segments = root / "segments" + self.db = shard_db_path(root, shard_id) if producer else root / "main.sqlite3" + self.checkpoint = root / "checkpoint.json" + self.db_lock = root / "db.lock" + self.index_lock = root / "faiss.lock" + self.lock = partial(FileLock, db_lock_path=self.db_lock, faiss_lock_path=self.index_lock) + self.paper_path = root / "papers.faiss" + self.chunk_path = root / "chunks.faiss" + + def run(self, *, conn=None, **overrides): + def open_index(path): + if self.producer: + return None + return faiss_load(path) if path.exists() else flat_ip_index(32) + + connection = ( + nullcontext(conn) + if conn is not None + else closing(init_shard_db(self.db, self.shard) if self.producer else init_db(self.db)) + ) + with connection as conn: + options = dict( + tar_paths=[self.tar], + conn=conn, + paper_embedder=FakeEmbedder(), + chunk_embedder=FakeEmbedder(), + paper_index=open_index(self.paper_path), + chunk_index=open_index(self.chunk_path), + paper_seg_writer=( + SegmentWriter(self.segments, shard_id=self.shard) if self.producer else None + ), + chunk_seg_writer=( + ChunkSegmentWriter(self.segments, shard_id=self.shard) + if self.producer + else None + ), + ckpt_path=self.checkpoint, + ckpt_lock=self.root / "ckpt.lock", + db_lock=self.db_lock, + faiss_lock=self.index_lock, + paper_index_path=self.paper_path, + chunk_index_path=self.chunk_path, + sqlite_dir=self.root, + FileLock=self.lock, + rebuild=False, + embed_producer=self.producer, + faiss_writer=not self.producer, + strict_ingest=True, + paper_batch=2, + chunk_batch=100, + ckpt_every=100, + paper_embed_bs=8, + chunk_embed_bs=8, + chunk_target_chars=1200, + chunk_min_chars=300, + chunk_overlap=0, + ckpt_shard_id=self.shard, + parse_workers=1, + ) + return process_tar_files(**(options | overrides)) + + def rows(self): + with closing(sqlite3.connect(self.db, timeout=1)) as conn: + return tuple( + conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0] + for table in ("papers", "chunks", "files") + ) + + def progress(self): + return ( + load_checkpoint(self.checkpoint, self.shard) + .get("build_stream", {}) + .get(str(self.tar), 0) + ) + + def consume(self): + with closing(init_db(self.root / "consumer.sqlite3")) as conn: + assert merge_shard_databases(conn, delete_after_merge=False)["shards"] == 1 + for table, ingest, path in ( + ("papers", ingest_paper_segments, self.paper_path), + ("chunks", ingest_chunk_segments, self.chunk_path), + ): + index, _ = ingest( + conn, + flat_ip_index(32), + self.segments, + self.index_lock, + path, + self.db_lock, + FileLock=self.lock, + ) + ids = sorted(faiss.vector_to_array(index.id_map).tolist()) + assert ids == [r[0] for r in conn.execute(f"SELECT id FROM {table} ORDER BY id")] + yield ids, np.stack([index.reconstruct(i) for i in ids]) + + def ingest_merged(self, conn): + """Run the writer on already-merged rows while retaining the test's source shards.""" + for ingest, path in ( + (ingest_paper_segments, self.paper_path), + (ingest_chunk_segments, self.chunk_path), + ): + index = faiss_load(path) if path.exists() else faiss.IndexIDMap2(flat_ip_index(32)) + ingest( + conn, index, self.segments, self.index_lock, path, self.db_lock, FileLock=self.lock + ) + + +class InjectedFailure(Exception): + pass + + +def test_retained_shard_restores_its_earlier_text_after_another_shards_revision(tmp_path): + embedder = FakeEmbedder() + a = Build(tmp_path, tmp_path / "a.tar", shard_id=0) + b = Build(tmp_path, tmp_path / "b.tar", shard_id=1) + with closing(init_db(tmp_path / "litkit.sqlite3")) as db: + for number, (build, title) in enumerate(((a, "Alpha"), (b, "Bravo"), (a, "Alpha"))): + tar = tmp_path / f"{number}.tar" + members = ( + {"first.xml": jats(pmcid="PMC42", title="Earlier paper")} if number == 0 else {} + ) + members["alias.xml"] = jats(pmcid="PMC42", title=title) + write_tar(tar, members) + build.run(tar_paths=[tar]) + merge_shard_databases(db, delete_after_merge=False, segment_dir=a.segments) + a.ingest_merged(db) + for table, path in (("papers", a.paper_path), ("chunks", a.chunk_path)): + index = faiss_load(path) + row = db.execute(f"SELECT id, in_index FROM {table}").fetchone() + assert row[1] == 1 and index.ntotal == 1 + np.testing.assert_allclose( + index.reconstruct(row[0]), embedder.encode([title])[0], atol=3e-4 + ) + + +@pytest.mark.parametrize("retain", [False, True]) +@pytest.mark.parametrize("field", ["pmcid", "pmid"]) +def test_independent_shards_resolve_the_same_citation_before_first_merge(tmp_path, retain, field): + first = Build(tmp_path, tmp_path / "a.tar", shard_id=0) + other = Build(tmp_path, tmp_path / "b.tar", shard_id=1) + identifier = {field: "PMC42" if field == "pmcid" else "42"} + for build, title in ((first, "First"), (other, "Second")): + write_tar(build.tar, {"paper.xml": jats(title=title, **identifier)}) + build.run() + with closing(init_db(tmp_path / "litkit.sqlite3")) as db: + for n, title in enumerate(["Second", "Second", "Third", "Fourth"]): + if n >= 2: + revision = first if n == 2 else other + tar = tmp_path / f"revision-{n}.tar" + write_tar(tar, {"new.xml": jats(title=title, **identifier)}) + revision.run(tar_paths=[tar]) + merge_shard_databases(db, delete_after_merge=not retain, segment_dir=first.segments) + first.ingest_merged(db) + assert db.execute("SELECT title, in_index FROM papers").fetchall() == [(title, 1)] + assert db.execute( + "SELECT COUNT(*), COUNT(DISTINCT paper_id) FROM files" + ).fetchone() == (max(2, n + 1), 1) + for table, path in (("papers", first.paper_path), ("chunks", first.chunk_path)): + index = faiss_load(path) + [(row_id, flagged)] = db.execute(f"SELECT id, in_index FROM {table}").fetchall() + assert flagged and faiss.vector_to_array(index.id_map).tolist() == [row_id] + np.testing.assert_allclose( + index.reconstruct(row_id), FakeEmbedder().encode([title])[0], atol=3e-4 + ) + assert not list(first.segments.glob("*.unresolved.*")) + + +@pytest.mark.parametrize("titles", [("Earlier", "Middle", "Last"), ("Same", "Same", "Same")]) +def test_parallel_citation_aliases_keep_the_last_input_and_one_vector(tmp_path, titles): + first = Build(tmp_path, tmp_path / "a.tar", shard_id=0) + second = Build(tmp_path, tmp_path / "b.tar", shard_id=1) + write_tar(first.tar, {"both.xml": jats(title="Initial", pmid="123", pmcid="PMC42")}) + write_tar( + second.tar, + [ + ("one.xml", jats(title=titles[0], pmid="123")), + ("two.xml", jats(title=titles[1], pmcid="PMC42")), + ("three.xml", jats(title=titles[2], pmid="123")), + ], + ) + first.run() + second.run(paper_batch=10) + with closing(init_db(tmp_path / "litkit.sqlite3")) as db: + merge_shard_databases(db, segment_dir=first.segments) + first.ingest_merged(db) + assert db.execute("SELECT title FROM papers").fetchall() == [(titles[-1],)] + assert db.execute("SELECT text FROM chunks").fetchall() == [(titles[-1],)] + for table, path in (("papers", first.paper_path), ("chunks", first.chunk_path)): + [(row_id,)] = db.execute(f"SELECT id FROM {table}").fetchall() + index = faiss_load(path) + assert faiss.vector_to_array(index.id_map).tolist() == [row_id] + np.testing.assert_allclose( + index.reconstruct(row_id), FakeEmbedder().encode([titles[-1]])[0], atol=3e-4 + ) + + +@pytest.mark.parametrize("retain", [False, True]) +def test_revision_under_linked_citation_reuses_a_shards_original_alias(tmp_path, retain): + first = Build(tmp_path, tmp_path / "a.tar", shard_id=0) + second = Build(tmp_path, tmp_path / "b.tar", shard_id=1) + write_tar(first.tar, {"a.xml": jats(title="First", pmid="123", pmcid="PMC42")}) + write_tar(second.tar, {"b.xml": jats(title="Second", pmid="123")}) + first.run() + second.run() + with closing(init_db(tmp_path / "litkit.sqlite3")) as db: + merge_shard_databases(db, delete_after_merge=not retain, segment_dir=first.segments) + first.ingest_merged(db) + tar = tmp_path / "both.tar" + write_tar( + tar, + [ + ("pmc.xml", jats(title="Third", pmcid="PMC42")), + ("pmid.xml", jats(title="Fourth", pmid="123")), + ], + ) + second.run(tar_paths=[tar]) + with closing(sqlite3.connect(second.db)) as shard: + assert shard.execute("SELECT COUNT(*) FROM papers").fetchone() == (1,) + merge_shard_databases(db, delete_after_merge=not retain, segment_dir=first.segments) + first.ingest_merged(db) + assert db.execute("SELECT title, pmid, pmcid FROM papers").fetchall() == [ + ("Fourth", "123", "PMC42") + ] + assert db.execute("SELECT text FROM chunks").fetchall() == [("Fourth",)] + assert db.execute("SELECT COUNT(*), COUNT(DISTINCT paper_id) FROM files").fetchone() == ( + 4, + 1, + ) + for table, path in (("papers", first.paper_path), ("chunks", first.chunk_path)): + [(row_id, flag)] = db.execute(f"SELECT id, in_index FROM {table}").fetchall() + index = faiss_load(path) + assert flag and faiss.vector_to_array(index.id_map).tolist() == [row_id] + np.testing.assert_allclose( + index.reconstruct(row_id), FakeEmbedder().encode(["Fourth"])[0], atol=3e-4 + ) + + +@pytest.mark.parametrize("retain", [False, True]) +@pytest.mark.parametrize("first_id", ["pmid", "pmcid"]) +def test_producer_enriches_citation_ids_and_replaces_duplicate_ordinal(tmp_path, retain, first_id): + build = Build(tmp_path, tmp_path / "original.tar") + both = {"pmid": "123", "pmcid": "PMC42"} + second_id = "pmcid" if first_id == "pmid" else "pmid" + with closing(init_db(tmp_path / "litkit.sqlite3")) as db: + for n, fields in enumerate( + ({first_id: both[first_id]}, both, {second_id: both[second_id]}) + ): + title = f"Version {n}" + tar = tmp_path / f"{n}.tar" + write_tar(tar, {"article.xml": jats(title=title, **fields)}) + build.run(tar_paths=[tar]) + merge_shard_databases(db, delete_after_merge=not retain, segment_dir=build.segments) + build.ingest_merged(db) + metadata = fields if n == 0 else both + papers = db.execute("SELECT id, pmid, pmcid, title, in_index FROM papers").fetchall() + assert papers == [(1, metadata.get("pmid", ""), metadata.get("pmcid", ""), title, 1)] + chunks = db.execute("SELECT id, ord, text, in_index FROM chunks").fetchall() + assert [(ordinal, text, indexed) for _, ordinal, text, indexed in chunks] == [ + (-1, title, 1) + ] + for path, row_id in ((build.paper_path, 1), (build.chunk_path, chunks[0][0])): + index = faiss_load(path) + assert faiss.vector_to_array(index.id_map).tolist() == [row_id] + np.testing.assert_allclose( + index.reconstruct(row_id), FakeEmbedder().encode([title])[0], atol=3e-4 + ) + if n == 0: + # Older builds could have two independently indexed rows for this ordinal. + duplicate = db.execute( + "INSERT INTO chunks(paper_id,ord,text,in_index) VALUES (1,-1,?,1)", (title,) + ).lastrowid + db.commit() + index = faiss_load(build.chunk_path) + index.add_with_ids( + index.reconstruct(chunks[0][0]).reshape(1, -1), + np.array([duplicate], dtype=np.int64), + ) + faiss.write_index(index, str(build.chunk_path)) + + +@pytest.mark.parametrize("retain", [False, True]) +def test_link_between_two_existing_papers_preserves_both_identifier_owners( + tmp_path, retain, capsys +): + build = Build(tmp_path, tmp_path / "a.tar") + with closing(init_db(tmp_path / "litkit.sqlite3")) as db: + for n, fields in enumerate( + ({"pmid": "123"}, {"pmcid": "PMC42"}, {"pmid": "123", "pmcid": "PMC42"}) + ): + tar = tmp_path / f"{n}.tar" + write_tar(tar, {"article.xml": jats(title=f"Edition {n}", **fields)}) + build.run(tar_paths=[tar]) + merge_shard_databases(db, delete_after_merge=not retain, segment_dir=build.segments) + build.ingest_merged(db) + assert "PMID 123 is already assigned" in capsys.readouterr().err + assert db.execute( + "SELECT pmid, pmcid, title, in_index FROM papers ORDER BY id" + ).fetchall() == [("123", "", "Edition 0", 1), ("", "PMC42", "Edition 2", 1)] + assert db.execute("SELECT COUNT(*) FROM files").fetchone() == (3,) + assert faiss_load(build.paper_path).ntotal == faiss_load(build.chunk_path).ntotal == 2 + + +def test_throttled_backfill_embeds_each_row_once_and_recovers_unsaved_batches( + tmp_path, monkeypatch +): + from litkit.build import backfill + from litkit.index import hnsw_index + + build = Build(tmp_path, tmp_path / "unused.tar", producer=False) + paper = faiss.IndexIDMap2(hnsw_index(32)) + chunk = faiss.IndexIDMap2(flat_ip_index(32)) + with closing(init_db(build.db)) as db: + for i in range(1, 5): + db.execute( + "INSERT INTO papers(id, doc_id, title, embedding_text, in_index) VALUES (?,?,?,?,?)", + (i, str(i), f"paper {i}", f"paper {i}", int(i == 1)), + ) + db.execute( + "INSERT INTO chunks(id, paper_id, ord, text, in_index) VALUES (?,?,?,?,?)", + (i, i, -1, f"chunk {i}", int(i == 1)), + ) + db.commit() + for index, path, text in ( + (paper, build.paper_path, "paper"), + (chunk, build.chunk_path, "chunk"), + ): + index.add_with_ids( + FakeEmbedder().encode([f"{text} 1", "obsolete"]), np.array([1, 2], dtype=np.int64) + ) + faiss.write_index(index, str(path)) + seen = [] + + class TrackingEmbedder(FakeEmbedder): + def encode(self, texts, **kwargs): + assert not set(texts).intersection(seen), "backfill repeated an unsaved batch" + seen.extend(texts) + return super().encode(texts, **kwargs) + + embedder = TrackingEmbedder() + run = partial( + backfill.backfill_unindexed_vectors, + db, + embedder, + embedder, + paper_index_path=build.paper_path, + chunk_index_path=build.chunk_path, + faiss_lock_path=build.index_lock, + db_lock_path=build.db_lock, + FileLock=build.lock, + batch=1, + ) + monkeypatch.setattr(backfill, "faiss_save", lambda *args: False) + force = backfill.faiss_save_force + + def fail_chunk(index, path): + if path == build.chunk_path: + raise InjectedFailure + return force(index, path) + + with monkeypatch.context() as fault: + fault.setattr(backfill, "faiss_save_force", fail_chunk) + with pytest.raises(InjectedFailure): + run(paper, chunk) + assert seen == ["paper 2", "paper 3", "paper 4", "chunk 2", "chunk 3", "chunk 4"] + assert db.execute("SELECT SUM(in_index) FROM chunks").fetchone() == (1,) + seen.clear() + run(faiss_load(build.paper_path), faiss_load(build.chunk_path)) + assert seen == ["chunk 2", "chunk 3", "chunk 4"] + for table, path in (("papers", build.paper_path), ("chunks", build.chunk_path)): + index = faiss_load(path) + assert sorted(faiss.vector_to_array(index.id_map)) == [1, 2, 3, 4] + assert db.execute(f"SELECT SUM(in_index) FROM {table}").fetchone() == (4,) + for i in range(1, 5): + np.testing.assert_allclose( + index.reconstruct(i), FakeEmbedder().encode([f"{table[:-1]} {i}"])[0], atol=1e-7 + ) + + +@pytest.mark.parametrize("retain, first_shard", [(True, 0), (True, 1), (False, 1)]) +def test_shard_remerge_and_late_segments_keep_current_revision(tmp_path, retain, first_shard): + from litkit.build.consume import run_consume_only_mode + + older = Build(tmp_path, tmp_path / "old.tar", shard_id=first_shard) + newer = Build(tmp_path, tmp_path / "new.tar", shard_id=1 - first_shard) + write_tar( + older.tar, + {"old.xml": jats(pmcid="PMC42", title="Original title", paragraphs=["Obsolete passage."])}, + ) + write_tar(newer.tar, {"new.xml": jats(pmcid="PMC42", title="Revised heading")}) + extra = tmp_path / "extra.tar" + write_tar(extra, {"extra.xml": jats(title="Unrelated paper")}) + with closing(init_db(tmp_path / "litkit.sqlite3")) as db: + older.run() + merge_shard_databases(db, not retain, segment_dir=older.segments) + # The first merge committed, but the older segments have yet to be ingested. + newer.run() + merge_shard_databases(db, not retain, segment_dir=older.segments) + assert db.execute("SELECT text FROM chunks").fetchall() == [("Revised heading",)] + older.run(tar_paths=[extra]) + merge_shard_databases(db, not retain, segment_dir=older.segments) + for shard in (0, 1): + (older.segments / f"producer_{shard}.done").touch() + for path in (older.paper_path, older.chunk_path): + faiss.write_index(faiss.IndexIDMap2(flat_ip_index(32)), str(path)) + assert run_consume_only_mode( + db, + seg_dir=older.segments, + num_shards=2, + paper_index_path=older.paper_path, + chunk_index_path=older.chunk_path, + db_lock_path=older.db_lock, + faiss_lock_path=older.index_lock, + FileLock=older.lock, + ) + for table, field, path in ( + ("papers", "title", older.paper_path), + ("chunks", "text", older.chunk_path), + ): + rows = db.execute(f"SELECT id, {field}, in_index FROM {table} ORDER BY id").fetchall() + assert [(text, flag) for _, text, flag in rows] == [ + ("Revised heading", 1), + ("Unrelated paper", 1), + ] + index = faiss_load(path) + assert sorted(faiss.vector_to_array(index.id_map)) == [i for i, _, _ in rows] + for i, text, _ in rows: + np.testing.assert_allclose( + index.reconstruct(i), FakeEmbedder().encode([text])[0], atol=3e-4 + ) + assert not list(older.segments.glob("*.unresolved.*")) + + +class FailOnRevisedText(FakeEmbedder): + def encode(self, texts, **kwargs): + if "Revised article title" in texts: + raise InjectedFailure + return super().encode(texts, **kwargs) + + +def test_resumed_producer_consumes_paper_and_chunk_revisions_in_commit_order(tmp_path): + archive = tmp_path / "revisions.tar" + members = [(f"{i}.xml", jats(title=f"Filler {i}")) for i in range(9)] + for title in ("Original", "Revised article title"): + members.append(("repeat.xml", jats(pmcid="PMC42", title=title))) + write_tar(archive, members) + interrupted = Build(tmp_path / "interrupted", archive) + reference = Build(tmp_path / "uninterrupted", archive) + with pytest.raises(InjectedFailure): + interrupted.run(paper_batch=1, paper_embedder=FailOnRevisedText()) + assert interrupted.progress() == 10 + interrupted.run(paper_batch=1) + reference.run(paper_batch=1) + expected = FakeEmbedder().encode(["Revised article title"])[0] + for (ids, vectors), (other_ids, other_vectors) in zip( + interrupted.consume(), reference.consume(), strict=True + ): + assert len(ids) == 10 + assert ids == other_ids + np.testing.assert_array_equal(vectors, other_vectors) + np.testing.assert_allclose(vectors[-1], expected, atol=3e-4) + + +@pytest.mark.parametrize("table,prefix", [("papers", "paper_seg_"), ("chunks", "chunk_seg_")]) +def test_consumer_read_error_preserves_revision_order_on_retry( + tmp_path, table, prefix, monkeypatch +): + from litkit.build.consume import run_consume_only_mode + from litkit.index import faiss_save_force + + archive = tmp_path / "revisions.tar" + write_tar( + archive, + [ + ("filler.xml", jats(title="Filler")), + ("same.xml", jats(pmcid="PMC42", title="Original")), + ("same.xml", jats(pmcid="PMC42", title="Revised article title")), + ], + ) + build = Build(tmp_path / "producer", archive) + build.run(paper_batch=1) + (build.segments / "producer_0.done").touch() + with build.lock(build.index_lock): + for path in [build.paper_path, build.chunk_path]: + faiss_save_force(flat_ip_index(32), path) + load = np.load + first_revision = _glob_segment_files(build.segments, table)[1] + + def fail_read(path, *args, **kwargs): + if Path(path).name == first_revision.name + ".ingesting": + raise OSError("interrupted read") + return load(path, *args, **kwargs) + + with closing(init_db(build.root / "consumer.sqlite3")) as conn: + consume = partial( + run_consume_only_mode, + conn, + seg_dir=build.segments, + num_shards=1, + paper_index_path=build.paper_path, + chunk_index_path=build.chunk_path, + faiss_lock_path=build.index_lock, + db_lock_path=build.db_lock, + FileLock=build.lock, + ) + with monkeypatch.context() as fault: + fault.setattr(np, "load", fail_read) + with pytest.raises(RuntimeError, match="stopped before completion"): + consume() + assert len(list(build.segments.glob(prefix + "*.npz"))) == 2 + assert consume() + expected = FakeEmbedder().encode(["Revised article title"])[0] + for path in (build.paper_path, build.chunk_path): + saved = faiss_load(path) + assert saved.ntotal == 2 + np.testing.assert_allclose(saved.reconstruct(2), expected, atol=3e-4) + + +@pytest.mark.parametrize("same_tar", [True, False]) +def test_resumed_writer_keeps_the_rebuild_revision_policy(tmp_path, same_tar): + first = tmp_path / "a.tar" + first_member = ("original.xml", jats(pmcid="PMC42", title="Original")) + revision = ("revision.xml", jats(pmcid="PMC42", title="Revised article title")) + paths = [first] + if same_tar: + write_tar(first, [first_member, revision]) + else: + paths.append(tmp_path / "b.tar") + write_tar(first, [first_member]) + write_tar(paths[1], [revision]) + build = Build(tmp_path / "writer", first, producer=False) + with pytest.raises(InjectedFailure): + build.run(tar_paths=paths, rebuild=True, paper_batch=1, chunk_embedder=FailOnRevisedText()) + assert build.progress() == 1 + paper, _, added, _ = build.run(tar_paths=paths, paper_batch=1) + assert added == 0 + np.testing.assert_allclose( + paper.reconstruct(1), FakeEmbedder().encode(["Original"])[0], atol=1e-7 + ) + assert "rebuild_tars" not in load_checkpoint(build.checkpoint) + + +def test_resumed_rebuild_reads_later_member_with_identical_file_metadata(tmp_path): + archive = tmp_path / "revisions.tar" + titles = ["Initial article title", "Revised article title"] + members = [("same.xml", jats(pmcid="PMC42", title=title)) for title in titles] + assert len(members[0][1]) == len(members[1][1]) + write_tar(archive, members) + build = Build(tmp_path / "writer", archive, producer=False) + with pytest.raises(InjectedFailure): + build.run(rebuild=True, paper_batch=1, paper_embedder=FailOnRevisedText()) + assert build.progress() == 1 + papers, chunks, _, _ = build.run(paper_batch=1) + with closing(connect_db(build.db)) as db: + [(cid, text)] = db.execute("SELECT id, text FROM chunks") + assert text == titles[1] + expected = FakeEmbedder().encode([text])[0] + np.testing.assert_allclose(papers.reconstruct(1), expected, atol=1e-7) + np.testing.assert_allclose(chunks.reconstruct(cid), expected, atol=1e-7) + + +@pytest.mark.parametrize("autocommit", [sqlite3.LEGACY_TRANSACTION_CONTROL, False, True]) +def test_ingest_and_merge_through_existing_pre_embedding_text_connections(tmp_path, autocommit): + archive = tmp_path / "revisions.tar" + write_tar( + archive, + { + "original.xml": jats(pmcid="PMC42", title="Original"), + "revised.xml": jats(pmcid="PMC42", title="Revised"), + }, + ) + build = Build(tmp_path / "workspace", archive) + main_db = build.root / "main.sqlite3" + for path in (build.db, main_db): + with closing(init_db(path)) as conn: + conn.execute("ALTER TABLE papers DROP COLUMN embedding_text") + with closing(connect_db(build.db)) as producer: + producer.autocommit = autocommit + # Both aliases are in the same batch, so only the final chunk is published. + assert build.run(conn=producer)[2:] == (1, 1) + assert producer.execute("SELECT embedding_text FROM papers").fetchall() == [("Revised",)] + with closing(connect_db(main_db)) as main: + main.autocommit = autocommit + stats = merge_shard_databases(main) + assert stats["papers"] == 1 + assert main.execute("SELECT embedding_text FROM papers").fetchall() == [("Revised",)] + with closing(connect_db(main_db)) as reopened: + assert reopened.execute("SELECT embedding_text FROM papers").fetchall() == [("Revised",)] + + +@pytest.mark.parametrize( + "legacy_files", ["ready", "pending", "missing", "stale_revision", "changed_alias"] +) +@pytest.mark.parametrize("has_checkpoint", [True, False]) +def test_upgrade_verifies_old_producer_checkpoint_before_resume_or_merge( + tmp_path, archive, legacy_files, has_checkpoint, monkeypatch +): + from litkit.segments import save_checkpoint, shard_ckpt_path + + build = Build(tmp_path / "producer", archive) + build.run(paper_batch=1) + with closing(connect_db(build.db)) as old: + old.execute("DROP TABLE ingest_publication") + old.execute("DROP TABLE ingest_checkpoint") + old.execute("ALTER TABLE papers DROP COLUMN embedding_text") + if legacy_files in {"stale_revision", "changed_alias"}: + if legacy_files == "stale_revision": + old.execute("DELETE FROM chunks WHERE paper_id=1 AND ord=-1") + old.execute( + "INSERT INTO chunks(paper_id, ord, text) VALUES (1, -1, 'Changed after the save')" + ) + old.commit() + if has_checkpoint: + save_checkpoint( + {"build_stream": {str(archive): 3}}, build.checkpoint, build.root / "ckpt.lock", 0 + ) + else: + shard_ckpt_path(build.root, 0).unlink() + for kind, prefix in [("papers", "paper_seg"), ("chunks", "chunk_seg")]: + for i, current in enumerate(_glob_segment_files(build.segments, kind)): + old = current.rename(build.segments / f"{prefix}_0_{i}_legacy.npz") + if i == 2 and legacy_files == "pending": + old.rename(old.with_name(old.stem + "_pending.npz")) + elif i == 2 and legacy_files == "missing" and kind == "chunks": + old.unlink() + # Older done markers can survive a later interrupted run. + (build.segments / "producer_0.done").touch() + with closing(init_db(build.root / "litkit.sqlite3")) as main: + if legacy_files == "ready": + assert build.run()[2:] == (0, 0) + assert merge_shard_databases(main, False, segment_dir=build.segments)["papers"] == 3 + monkeypatch.setattr("litkit.index.io._SAVE_MIN_SEC", 0) + for ingest, target in [ + (ingest_paper_segments, build.paper_path), + (ingest_chunk_segments, build.chunk_path), + ]: + ingest( + main, + flat_ip_index(32), + build.segments, + build.index_lock, + target, + build.db_lock, + FileLock=build.lock, + ) + assert build.run()[2:] == (0, 0) + assert merge_shard_databases(main, segment_dir=build.segments)["papers"] == 0 + else: + with pytest.raises(RuntimeError, match="fresh workspace"): + build.run() + with pytest.raises(RuntimeError, match="fresh workspace"): + merge_shard_databases(main, segment_dir=build.segments) + assert build.db.is_file() + assert build.progress() == (3 if has_checkpoint else 0) + assert main.execute("SELECT COUNT(*) FROM papers").fetchone() == (0,) + + +@pytest.mark.parametrize("process_exit", [False, True]) +def test_caller_transaction_rollback_reclaims_staged_files(tmp_path, archive, process_exit): + build = Build(tmp_path / "producer", archive) + # Exit after writing the paper segment while SQLite still holds the + # caller's transaction. On restart the reservation row itself is gone. + script = """ +import os, sys +from pathlib import Path +from unittest.mock import patch +from test_batch_resume import Build +from litkit.db import init_db +from litkit.segments import ChunkSegmentWriter +root, tar, failure = sys.argv[1:] +build = Build(Path(root), Path(tar)) +conn = init_db(build.db) +conn.execute("INSERT INTO papers(title) VALUES ('caller')") +def interrupt(*args, **kwargs): + if failure == "exit": + os._exit(86) + raise OSError("disk full") +with patch.object(ChunkSegmentWriter, "stage", interrupt): + try: + build.run(conn=conn) + except OSError as error: + assert str(error) == "disk full" + sys.exit(87) +""" + test_paths = [Path(__file__).parent, Path(__file__).parents[1]] + env = dict(os.environ, PYTHONPATH=os.pathsep.join(map(str, test_paths))) + proc = subprocess.run( + [ + sys.executable, + "-c", + script, + str(build.root), + str(archive), + "exit" if process_exit else "raise", + ], + env=env, + timeout=30, + ) + assert proc.returncode == (86 if process_exit else 87) + assert build.rows() == (0, 0, 0) + assert build.progress() == 0 + assert bool(list(build.segments.glob(".litkit-batch-*"))) == process_exit + assert build.run()[2:] == (3, 6) + assert not list(build.segments.glob(".litkit-batch-*")) + assert "batch_reservation" not in load_checkpoint(build.checkpoint, build.shard) + assert [len(ids) for ids, _ in build.consume()] == [3, 6] + + +@pytest.mark.parametrize("paper_batch,chunk_batch", [(2, 100), (100, 4)]) +def test_failed_batch_resumes_through_consumption(tmp_path, archive, paper_batch, chunk_batch): + build = Build(tmp_path / "interrupted", archive) + limits = dict(paper_batch=paper_batch, chunk_batch=chunk_batch) + observations = [] + + class FailOnFinalChunkBatch(FakeEmbedder): + def encode(self, texts, **kwargs): + observations.append((build.rows(), build.progress())) + if any("Article 2" in text for text in texts): + raise InjectedFailure + return super().encode(texts, **kwargs) + + with pytest.raises(InjectedFailure): + build.run(chunk_embedder=FailOnFinalChunkBatch(), **limits) + assert observations == [((0, 0, 0), 0), ((2, 4, 2), 2)] + assert build.rows() == (2, 4, 2) + assert build.progress() == 2 + assert build.run(**limits)[2:] == (1, 2) + assert build.rows() == (3, 6, 3) + assert build.progress() == 3 + + reference = Build(tmp_path / "uninterrupted", archive) + reference.run(**limits) + for (ids, vectors), (expected_ids, expected_vectors) in zip( + build.consume(), reference.consume(), strict=True + ): + assert ids == expected_ids + np.testing.assert_array_equal(vectors, expected_vectors) + + +@pytest.mark.parametrize("producer", [True, False], ids=["producer", "writer"]) +@pytest.mark.parametrize("failure", ["rename", "checkpoint"]) +def test_resume_finishes_committed_publication(tmp_path, archive, monkeypatch, producer, failure): + # Inspect the persisted snapshots after every writer batch in this test. + monkeypatch.setattr("litkit.index.io._SAVE_MIN_SEC", 0) + build = Build(tmp_path / "build", archive, producer=producer) + with monkeypatch.context() as fault: + if failure == "rename": + replace = Path.replace + + def fail_chunk_rename(path, target): + if path.name.startswith("chunk"): + raise InjectedFailure + return replace(path, target) + + fault.setattr(Path, "replace", fail_chunk_rename) + else: + from litkit.build import publication + + def fail_checkpoint(*args, **kwargs): + raise InjectedFailure + + fault.setattr(publication, "save_checkpoint", fail_checkpoint) + with pytest.raises(InjectedFailure): + build.run() + assert build.rows() == (2, 4, 2) + assert build.progress() == 0 + if producer: + assert len(_glob_segment_files(build.segments, "papers")) == 1 + assert len(_glob_segment_files(build.segments, "chunks")) == int(failure == "checkpoint") + with closing(init_db(build.root / "consumer.sqlite3")) as main: + with pytest.raises(RuntimeError, match="unfinished batch publication or cleanup"): + merge_shard_databases(main) + assert main.execute("SELECT COUNT(*) FROM papers").fetchone() == (0,) + assert build.db.is_file() + assert build.run()[2:] == (1, 2) + assert build.progress() == 3 + if producer: + assert [len(ids) for ids, _ in build.consume()] == [3, 6] + else: + for path, n in [(build.paper_path, 3), (build.chunk_path, 6)]: + index = faiss_load(path) + assert sorted(faiss.vector_to_array(index.id_map)) == list(range(1, n + 1)) + + +def test_two_starts_of_the_same_shard_serialize_publication(tmp_path, archive, monkeypatch): + from litkit.db.sharding import producer_shard_lock + + build = Build(tmp_path / "producer", archive) + staged = Event() + second_attempt = Event() + independent_shard = Event() + write = SegmentWriter.stage + + def wait_for_second_start(writer, *args, **kwargs): + path = write(writer, *args, **kwargs) + staged.set() + assert independent_shard.wait(10), "a queued producer blocked an independent shard" + return path + + class SecondLock(FileLock): + def __enter__(self): + if self.path.name == "producer_0.queue": + second_attempt.set() + return super().__enter__() + + def start_independent_shard(): + with producer_shard_lock(build.root, 1): + independent_shard.set() + + monkeypatch.setattr(SegmentWriter, "stage", wait_for_second_start) + with ThreadPoolExecutor(max_workers=3) as workers: + first = workers.submit(build.run) + assert staged.wait(10), "first producer did not stage its batch" + second = workers.submit(build.run, FileLock=SecondLock) + assert second_attempt.wait(10), "duplicate producer did not reach its shard queue" + workers.submit(start_independent_shard).result(timeout=10) + assert first.result(timeout=15)[2:] == (3, 6) + assert second.result(timeout=15)[2:] == (0, 0) + assert [len(ids) for ids, _ in build.consume()] == [3, 6] + + +def test_workspace_copy_cannot_discard_another_producers_committed_segments( + tmp_path, archive, monkeypatch +): + first = Build(tmp_path / "first", archive) + second = Build(tmp_path / "second", archive) + first.run(tar_paths=[]) + second.root.mkdir() + shutil.copy(first.db, second.db) + second.segments = first.segments + with monkeypatch.context() as fault: + + def fail_rename(*args): + raise InjectedFailure + + fault.setattr(Path, "replace", fail_rename) + with pytest.raises(InjectedFailure): + first.run() + + # A fresh database for the same shard can share --embed-outdir. + second.run(tar_paths=[]) + assert first.run()[2:] == (1, 2) + assert [len(ids) for ids, _ in first.consume()] == [3, 6] + + +@pytest.mark.parametrize("strict", [True, False]) +def test_member_savepoint_preserves_only_successful_members(tmp_path, archive, monkeypatch, strict): + from litkit.build import ingest_loop + + real_pack = ingest_loop.pack_body + + def fail_middle(meta, *args): + if meta["title"] == "Article 1": + raise InjectedFailure + return real_pack(meta, *args) + + build = Build(tmp_path / "producer", archive) + with monkeypatch.context() as fault: + fault.setattr(ingest_loop, "pack_body", fail_middle) + if strict: + with pytest.raises(InjectedFailure): + build.run() + assert build.rows() == (0, 0, 0) + assert build.progress() == 0 + else: + assert build.run(strict_ingest=False)[2:] == (2, 4) + assert build.rows() == (2, 4, 2) + assert build.progress() == 3 + with closing(sqlite3.connect(build.db)) as conn: + assert conn.execute("SELECT title FROM papers ORDER BY id").fetchall() == [ + ("Article 0",), + ("Article 2",), + ] + assert [len(ids) for ids, _ in build.consume()] == [2, 4] + if strict: + assert build.run()[2:] == (3, 6) + + +def test_failed_writer_save_rolls_back_both_indexes_and_rows(tmp_path, archive, monkeypatch): + from litkit.build import ingest_loop + + build = Build(tmp_path / "writer", archive, producer=False) + save = ingest_loop.faiss_save_force + + def fail_chunk_save(index, path): + assert build.rows() == (0, 0, 0) + if path.name.startswith("chunks"): + raise InjectedFailure + return save(index, path) + + with monkeypatch.context() as fault: + fault.setattr(ingest_loop, "faiss_save_force", fail_chunk_save) + with pytest.raises(InjectedFailure): + build.run() + assert build.rows() == (0, 0, 0) + assert build.progress() == 0 + assert not build.paper_path.exists() + assert not build.chunk_path.exists() + assert build.run()[2:] == (3, 6) + + +@pytest.mark.parametrize("existing", [False, True]) +def test_failed_writer_handles_cannot_duplicate_a_new_hnsw_id(tmp_path, monkeypatch, existing): + from litkit.build import ingest_loop + + monkeypatch.setattr("litkit.index.io._SAVE_MIN_SEC", 0) + archive = tmp_path / "new.tar" + write_tar(archive, {"new.xml": jats(title="New paper")}) + build = Build(tmp_path / "writer", archive, producer=False) + handles = dict( + paper_index=faiss.IndexIDMap2(faiss.IndexHNSWFlat(32, 8)), + chunk_index=faiss.IndexIDMap2(flat_ip_index(32)), + ) + if existing: + first = tmp_path / "first.tar" + write_tar(first, {"first.xml": jats(title="First paper")}) + build.run(tar_paths=[first], **handles) + save = ingest_loop.faiss_save_force + + def fail_chunk(index, path): + if path.name.startswith("chunks"): + raise OSError("disk full") + return save(index, path) + + with monkeypatch.context() as fault: + fault.setattr(ingest_loop, "faiss_save_force", fail_chunk) + fault.setattr(ingest_loop, "faiss_save", fail_chunk) + with pytest.raises(OSError, match="disk full"): + build.run(**handles) + assert build.progress() == 0 + if existing: + with pytest.raises(ValueError, match="Reopen the saved indexes"): + build.run(**handles) + build.run() + else: + assert all(index.ntotal == 0 for index in handles.values()) + build.run(**handles) + for path in (build.paper_path, build.chunk_path): + index = faiss_load(path) + assert sorted(faiss.vector_to_array(index.id_map)) == ([1, 2] if existing else [1]) + + +@pytest.mark.parametrize("entry", ["rebuild", "producer", "node-local"]) +def test_readers_recover_hot_rollback_journals(tmp_path, archive, entry): + from litkit.db.handoff import prepare_local_shard + from litkit.db.publication import unpublished_shards + + shared = tmp_path / "shared" + build = Build(shared / "sqlite", archive) + db = build.db if entry == "rebuild" else build.root / "litkit.sqlite3" + init_db(db).close() + script = """ +import os, sqlite3, sys +conn = sqlite3.connect(sys.argv[1]) +conn.execute("PRAGMA cache_size=4") +conn.executemany("INSERT INTO papers(title) VALUES (?)", [("x" * 12288,)] * 200) +os._exit(86) +""" + proc = subprocess.run([sys.executable, "-c", script, str(db)], timeout=30) + assert proc.returncode == 86 + assert db.with_name(db.name + "-journal").stat().st_size > 0 + if entry == "rebuild": + assert unpublished_shards([db]) == [] + elif entry == "producer": + assert build.run()[2:] == (3, 6) + else: + local = tmp_path / "fresh-node" + (local / "sqlite").mkdir(parents=True) + (local / "emb_segments").mkdir() + assert prepare_local_shard(local, shared, 0) + with closing(sqlite3.connect(db.resolve().as_uri() + "?mode=ro", uri=True)) as conn: + assert conn.execute("SELECT COUNT(*) FROM papers").fetchone() == (0,) + + +@pytest.mark.parametrize("interrupted", ["main", "shard"]) +def test_producer_resumes_after_interrupted_schema_initialization(tmp_path, archive, interrupted): + from litkit.db.handoff import prepare_local_shard + + shared = tmp_path / "shared" + build = Build(shared / "sqlite", archive) + db = build.db if interrupted == "shard" else build.root / "litkit.sqlite3" + script = """ +import os, sqlite3, sys +from pathlib import Path +from litkit.db import init_db, init_shard_db +connect = sqlite3.connect +def stop_before_files(*args, **kwargs): + db = connect(*args, **kwargs) + def authorize(action, name, *unused): + if action == sqlite3.SQLITE_CREATE_TABLE and name == "files": + os._exit(86) + return sqlite3.SQLITE_OK + db.set_authorizer(authorize) + return db +sqlite3.connect = stop_before_files +path = Path(sys.argv[1]) +init_shard_db(path, 0) if sys.argv[2] == "shard" else init_db(path) +""" + result = subprocess.run([sys.executable, "-c", script, str(db), interrupted], timeout=30) + assert result.returncode == 86 + with closing(sqlite3.connect(db)) as partial_db: + tables = { + r[0] for r in partial_db.execute("SELECT name FROM sqlite_master WHERE type='table'") + } + assert "papers" in tables and "files" not in tables + if interrupted == "shard": + local = tmp_path / "next-node" + (local / "sqlite").mkdir(parents=True) + (local / "emb_segments").mkdir() + assert not prepare_local_shard(local, shared, 0) + assert build.run()[2:] == (3, 6) + assert build.rows() == (3, 6, 3) + + +@pytest.mark.parametrize("staging", ["shared", "complete", "incomplete"]) +def test_committed_database_copy_requires_independent_staging( + tmp_path, archive, monkeypatch, staging +): + first = Build(tmp_path / "original", archive) + copy = Build(tmp_path / "copy", archive) + with monkeypatch.context() as fault: + + def fail_rename(*args): + raise InjectedFailure + + fault.setattr(Path, "replace", fail_rename) + with pytest.raises(InjectedFailure): + first.run() + copy.root.mkdir() + with closing(sqlite3.connect(first.db)) as source, closing(sqlite3.connect(copy.db)) as target: + source.backup(target) + if staging == "shared": + copy.segments = first.segments + with pytest.raises(RuntimeError, match="matching copy"): + copy.run() + else: + shutil.copytree(first.segments, copy.segments) + if staging == "incomplete": + next(copy.segments.glob(".litkit-batch-*-chunks/*.npz")).unlink() + with pytest.raises(FileNotFoundError, match="copied staging directory"): + copy.run() + assert copy.progress() == 0 + assert not _glob_segment_files(copy.segments, "papers") + else: + assert copy.run()[2:] == (1, 2) + assert [len(ids) for ids, _ in copy.consume()] == [3, 6] + assert first.run()[2:] == (1, 2) + assert [len(ids) for ids, _ in first.consume()] == [3, 6] + + +@pytest.mark.parametrize("location", ["original", "shared", "copy"]) +def test_swapped_output_roots_preserve_committed_files(tmp_path, archive, monkeypatch, location): + production = Build(tmp_path / "original", archive) + paper_root = production.segments + chunk_root = production.root / "chunks" + + def run(build, paper, chunk): + return build.run( + paper_seg_writer=SegmentWriter(paper), chunk_seg_writer=ChunkSegmentWriter(chunk) + ) + + def crash(*args): + raise InjectedFailure + + with monkeypatch.context() as fault: + fault.setattr(Path, "replace", crash) + with pytest.raises(InjectedFailure): + run(production, paper_root, chunk_root) + + candidate = production + papers, chunks = paper_root, chunk_root + if location != "original": + candidate = Build(tmp_path / "backup", archive) + candidate.root.mkdir() + with ( + closing(sqlite3.connect(production.db)) as src, + closing(sqlite3.connect(candidate.db)) as dst, + ): + src.backup(dst) + if location == "copy": + papers = shutil.copytree(paper_root, candidate.segments) + chunks = shutil.copytree(chunk_root, candidate.root / "chunks") + for _ in range(2): + with pytest.raises((RuntimeError, FileNotFoundError), match="original|staging directory"): + run(candidate, chunks, papers) + assert candidate.progress() == 0 + assert len(list(papers.glob(".litkit-batch-*/*.npz"))) == 1 + assert len(list(chunks.glob(".litkit-batch-*/*.npz"))) == 1 + assert run(production, paper_root, chunk_root)[2:] == (1, 2) + for directory, kind, count in [(paper_root, "papers", 3), (chunk_root, "chunks", 6)]: + vectors = [] + for path in _glob_segment_files(directory, kind): + with np.load(path) as segment: + vectors.extend(segment["vecs"]) + assert len(vectors) == count + + +def test_checkpoint_requires_matching_output_after_interruption_or_move( + tmp_path, archive, monkeypatch +): + build = Build(tmp_path / "original", archive) + stage = ChunkSegmentWriter.stage + calls = 0 + + def crash_on_second(writer, *args, **kwargs): + nonlocal calls + calls += 1 + if calls == 2: + raise InjectedFailure + return stage(writer, *args, **kwargs) + + with monkeypatch.context() as fault: + fault.setattr(ChunkSegmentWriter, "stage", crash_on_second) + with pytest.raises(InjectedFailure): + build.run(paper_batch=1) + assert build.progress() == 1 + wrong = tmp_path / "new-output" + with pytest.raises(RuntimeError, match="original paper and chunk output"): + build.run(paper_seg_writer=SegmentWriter(wrong), chunk_seg_writer=ChunkSegmentWriter(wrong)) + with closing(init_db(build.root / "litkit.sqlite3")) as main: + with pytest.raises(RuntimeError, match="original paper and chunk output"): + merge_shard_databases(main, segment_dir=wrong) + assert build.db.is_file() and build.progress() == 1 + moved = Build(tmp_path / "moved", archive) + build.root.rename(moved.root) + assert moved.run()[2:] == (2, 4) + assert [len(ids) for ids, _ in moved.consume()] == [3, 6] + + +@pytest.mark.parametrize("legacy", [False, True]) +def test_merge_only_supports_separate_segment_directories(tmp_path, archive, legacy): + build = Build(tmp_path / "sqlite", archive) + papers, chunks = tmp_path / "paper-output", tmp_path / "chunk-output" + build.run(paper_seg_writer=SegmentWriter(papers), chunk_seg_writer=ChunkSegmentWriter(chunks)) + if legacy: + from litkit.segments import save_checkpoint + + with closing(connect_db(build.db)) as old: + old.execute("DROP TABLE ingest_checkpoint") + old.execute("DROP TABLE ingest_publication") + old.commit() + save_checkpoint( + {"build_stream": {str(archive): 3}}, build.checkpoint, build.root / "ckpt.lock", 0 + ) + with closing(init_db(build.root / "litkit.sqlite3")) as main: + assert ( + merge_shard_databases(main, segment_dir=(papers, chunks) if legacy else None)["papers"] + == 3 + ) + for source, ingest, path, total in [ + (papers, ingest_paper_segments, build.paper_path, 3), + (chunks, ingest_chunk_segments, build.chunk_path, 6), + ]: + index, added = ingest( + main, + flat_ip_index(32), + source, + build.index_lock, + path, + build.db_lock, + FileLock=build.lock, + ) + assert added == index.ntotal == total + + +def test_first_failed_batch_backup_cannot_claim_completed_rows(tmp_path, archive, monkeypatch): + build = Build(tmp_path / "producer", archive) + + def crash(*args, **kwargs): + raise InjectedFailure + + with monkeypatch.context() as fault: + fault.setattr(ChunkSegmentWriter, "stage", crash) + with pytest.raises(InjectedFailure): + build.run() + backup = tmp_path / "rolled-back.sqlite3" + with closing(sqlite3.connect(build.db)) as src, closing(sqlite3.connect(backup)) as dst: + src.backup(dst) + assert build.run()[2:] == (3, 6) + backup.replace(build.db) + with pytest.raises(RuntimeError, match="different batches"): + build.run() + with closing(init_db(build.root / "litkit.sqlite3")) as main: + with pytest.raises(RuntimeError, match="different batches"): + merge_shard_databases(main, segment_dir=build.segments) + assert build.db.is_file() + assert build.rows() == (0, 0, 0) + + +def test_a_complete_old_shard_cannot_revert_its_merged_successor(tmp_path): + from litkit.segments import shard_ckpt_path + + a, b = tmp_path / "a.tar", tmp_path / "b.tar" + write_tar(a, {"a.xml": jats(title="A")}) + write_tar(b, {"b.xml": jats(title="B")}) + build = Build(tmp_path / "source", a) + build.run() + old = tmp_path / "older" + shutil.copytree(build.root, old) + main_path = build.root / "litkit.sqlite3" + # A retained shard may legitimately advance beyond the last merged batch. + with closing(init_db(main_path)) as main: + assert merge_shard_databases(main, False, segment_dir=build.segments)["papers"] == 1 + build.run(tar_paths=[a, b]) + with closing(init_db(main_path)) as main: + assert merge_shard_databases(main, segment_dir=build.segments)["papers"] == 1 + shutil.copyfile(old / build.db.name, build.db) + shutil.rmtree(build.segments) + shutil.copytree(old / build.segments.name, build.segments) + shard_ckpt_path(build.root, 0).unlink() + with pytest.raises(RuntimeError, match="does not descend"): + build.run(tar_paths=[a, b]) + with closing(init_db(main_path)) as main: + with pytest.raises(RuntimeError, match="does not descend"): + merge_shard_databases(main, segment_dir=build.segments) + assert main.execute("SELECT title FROM papers ORDER BY title").fetchall() == [ + ("A",), + ("B",), + ] + assert build.db.is_file() + + +def test_failed_legacy_upgrade_checks_inherited_rows_again(tmp_path, monkeypatch): + from litkit.segments import save_checkpoint + + a, b = tmp_path / "a.tar", tmp_path / "b.tar" + write_tar(a, {"a.xml": jats(title="Legacy")}) + write_tar(b, {"b.xml": jats(title="New")}) + build = Build(tmp_path / "sqlite", a) + build.run() + with closing(connect_db(build.db)) as old: + old.execute("DROP TABLE ingest_checkpoint") + old.execute("DROP TABLE ingest_publication") + old.commit() + save_checkpoint({"build_stream": {str(a): 1}}, build.checkpoint, build.root / "ckpt.lock", 0) + + def crash(*args, **kwargs): + raise InjectedFailure + + with monkeypatch.context() as fault: + fault.setattr(ChunkSegmentWriter, "stage", crash) + with pytest.raises(InjectedFailure): + build.run(tar_paths=[b]) + wrong = tmp_path / "empty" + with pytest.raises(RuntimeError, match="fresh workspace"): + build.run( + tar_paths=[a, b], + paper_seg_writer=SegmentWriter(wrong), + chunk_seg_writer=ChunkSegmentWriter(wrong), + ) + with closing(init_db(build.root / "litkit.sqlite3")) as main: + with pytest.raises(RuntimeError, match="fresh workspace"): + merge_shard_databases(main, segment_dir=wrong) + assert build.run(tar_paths=[a, b])[2:] == (1, 1) + assert [len(ids) for ids, _ in build.consume()] == [2, 2] + + +def test_restart_finishes_an_interrupted_output_revision(tmp_path, archive, monkeypatch): + build = Build(tmp_path / "producer", archive) + replace = os.replace + revisions = [] + + def interrupt(src, dst): + path = Path(dst) + if path.name.startswith(".litkit-output-") and path.name.endswith("-chunks"): + revisions.append(Path(src).read_text()) + if len(revisions) == 2: + raise InjectedFailure + return replace(src, dst) + + with monkeypatch.context() as fault: + fault.setattr(os, "replace", interrupt) + with pytest.raises(InjectedFailure): + build.run(paper_batch=1) + assert build.progress() == 1 and revisions[0] != revisions[1] + assert build.run(paper_batch=1)[2:] == (1, 2) + assert [len(ids) for ids, _ in build.consume()] == [3, 6] + + +def test_writer_backfill_uses_the_original_body_only_paper_text(tmp_path): + from litkit.build.backfill import backfill_unindexed_vectors + + archive = tmp_path / "body.tar" + text = "Keep the inlet covered and record the pressure before opening the outlet. " * 15 + write_tar(archive, {"body.xml": jats(paragraphs=[text])}) + build = Build(tmp_path / "writer", archive, producer=False) + paper_idx, chunk_idx, papers, _ = build.run() + assert papers == 1 + original = paper_idx.reconstruct(1) + with closing(init_db(build.db)) as conn: + conn.execute("UPDATE papers SET in_index=0") + conn.commit() + reopened = faiss.IndexIDMap2(flat_ip_index(32)) + embedder = FakeEmbedder() + backfill_unindexed_vectors( + conn, + embedder, + FakeEmbedder(), + reopened, + chunk_idx, + paper_index_path=build.paper_path, + chunk_index_path=build.chunk_path, + faiss_lock_path=build.index_lock, + db_lock_path=build.db_lock, + FileLock=build.lock, + ) + assert conn.execute("SELECT in_index FROM papers").fetchone() == (1,) + np.testing.assert_array_equal(reopened.reconstruct(1), original) + + +def test_update_aliases_follow_the_last_embedded_text(tmp_path, monkeypatch): + monkeypatch.setattr("litkit.index.io._SAVE_MIN_SEC", 0) + embedder = FakeEmbedder() + build = Build(tmp_path / "writer", tmp_path / "a.tar", producer=False) + for i, title in enumerate(["First revision", "Second revision", "First revision"]): + archive = tmp_path / f"{i}.tar" + write_tar(archive, {"paper.xml": jats(pmcid="PMC1001", title=title)}) + paper, _, papers_added, _ = build.run(tar_paths=[archive]) + assert papers_added == 1 + assert paper.ntotal == 1 + np.testing.assert_allclose(paper.reconstruct(1), embedder.encode([title])[0], atol=1e-7) + if i == 1: + # A writer restart after throttling must reproduce the second version. + from litkit.build.backfill import backfill_unindexed_vectors + + with closing(init_db(build.db)) as conn: + conn.execute("UPDATE papers SET in_index=0") + conn.commit() + reopened = faiss.IndexIDMap2(flat_ip_index(32)) + backfill_unindexed_vectors( + conn, + embedder, + FakeEmbedder(), + reopened, + faiss_load(build.chunk_path), + paper_index_path=build.paper_path, + chunk_index_path=build.chunk_path, + faiss_lock_path=build.index_lock, + db_lock_path=build.db_lock, + FileLock=build.lock, + ) + np.testing.assert_array_equal(reopened.reconstruct(1), paper.reconstruct(1)) + + +def test_revision_persists_before_restarting_with_an_identical_alias(tmp_path, monkeypatch): + monkeypatch.setattr("litkit.index.io._SAVE_MIN_SEC", 3600) + build = Build(tmp_path / "writer", tmp_path / "first.tar", producer=False) + for i, (title, expected_added) in enumerate([("A", 1), ("B", 1), ("B", 0)]): + archive = tmp_path / f"{i}.tar" + write_tar(archive, {"paper.xml": jats(pmcid="PMC1001", title=title)}) + _, _, papers_added, _ = build.run(tar_paths=[archive]) + assert papers_added == expected_added + saved = faiss_load(build.paper_path) + assert saved.ntotal == 1 + np.testing.assert_allclose( + saved.reconstruct(1), FakeEmbedder().encode([title])[0], atol=1e-7 + ) + + +def test_resume_retries_interrupted_staging_cleanup(tmp_path, archive, monkeypatch): + build = Build(tmp_path / "producer", archive) + with monkeypatch.context() as fault: + + def fail_cleanup(path): + raise OSError("cleanup interrupted") + + fault.setattr(Path, "rmdir", fail_cleanup) + with pytest.raises(OSError, match="cleanup interrupted"): + build.run() + assert build.progress() == 2 + assert build.run()[2:] == (1, 2) + assert not list(build.segments.glob(".litkit-batch-*")) + assert [len(ids) for ids, _ in build.consume()] == [3, 6] diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index e4fd4d5..f028b44 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -5,7 +5,9 @@ run_litkit_fake.py, so no model, GPU or network is needed. """ +import json import os +import shutil import sqlite3 import subprocess import sys @@ -568,3 +570,847 @@ def test_rebuild_without_yes_refuses_noninteractively(isolated_env, corpus_dir): ) assert proc.returncode == 2 assert "Refusing to proceed non-interactively" in proc.stderr + + +def test_writer_consume_segments_reports_partial_pass_and_retries_in_order(isolated_env, corpus_dir): + import numpy as np + + from litkit.segments import SegmentWriter + from litkit.segments.ingest import _glob_segment_files + + ws = isolated_env + args = ["--build-only", "--faiss-writer", "--tar-dir", str(corpus_dir), *FLAT] + _ok(litkit(ws, *args, "--rebuild")) + with _db(ws) as db: + pid, doc = db.execute("SELECT id, doc_id FROM papers ORDER BY id LIMIT 1").fetchone() + path = ws / "indices" / "papers.faiss" + vectors = np.eye(3, faiss_load(path).d, dtype=np.float32) + segments = ws / "emb_segments" + writer = SegmentWriter(segments, dtype="fp32") + for vector in vectors: + writer.write(doc_ids=[doc], vecs=vector.reshape(1, -1)) + writer.finalize() + first, damaged, last = _glob_segment_files(segments, "papers") + payload = damaged.read_bytes() + damaged.write_bytes(b"incomplete") + failed = litkit(ws, *args, "--consume-segments") + assert failed.returncode != 0 + assert "Segment ingestion stopped before completion" in failed.stderr + assert damaged.name in failed.stderr + assert not first.exists() and last.exists() + np.testing.assert_array_equal(faiss_load(path).reconstruct(pid), vectors[0]) + damaged.write_bytes(payload) + _ok(litkit(ws, *args, "--consume-segments")) + np.testing.assert_array_equal(faiss_load(path).reconstruct(pid), vectors[2]) + + +@pytest.mark.parametrize("interruption", ["copy", "ready", "publish"]) +def test_local_shard_transfer_survives_interruption(isolated_env, corpus_dir, monkeypatch, interruption): + from litkit.db import handoff + from litkit.segments import discovery + + shared = isolated_env + local = shared.parent / "node-local" + monkeypatch.setenv("FAKE_EMBED_DIM", "768") + _ok(litkit(shared, "--init-indices-only", "--faiss-writer", *FLAT)) + produce = ["--build-only", "--embed-producer", "--tar-dir", str(corpus_dir)] + consume = ["--build-only", "--consume-only", "--faiss-writer"] + _ok(litkit(local, *produce)) + + copy = handoff._copy_file + rename = Path.replace + with monkeypatch.context() as fault: + def fail_copy(path, dest): + if path.suffix == ".npz": + raise OSError("transfer interrupted") + return copy(path, dest) + + def fail_publish(path, dest): + if interruption == "ready" and dest.name == "READY": + rename(path, dest) + raise OSError("transfer interrupted") + if interruption == "publish" and path.suffix == ".done": + raise OSError("transfer interrupted") + return rename(path, dest) + + if interruption == "copy": + fault.setattr(handoff, "_copy_file", fail_copy) + else: + fault.setattr(Path, "replace", fail_publish) + with pytest.raises(OSError, match="transfer interrupted"): + handoff.copy_handoff(local, shared, 0) + + assert not (shared / "emb_segments" / "producer_0.done").exists() + if interruption == "ready": + assert not list((shared / "emb_segments").glob("*.npz")) + result = subprocess.check_output( + [sys.executable, "-I", discovery.__file__, "resume", str(shared / "emb_segments")], text=True + ) + assert result.strip() == "1" + if interruption == "copy": + assert not (shared / "sqlite" / "litkit_shard_00.sqlite3").exists() + assert not list((shared / "emb_segments").glob("*.npz")) + _ok(litkit(shared, *produce)) # Supported fallback to direct shared storage + _ok(litkit(shared, *consume)) + assert not list(shared.glob("*/.litkit-handoff-*")) + with _db(shared) as db: + for table in ("papers", "chunks"): + rows = db.execute(f"SELECT id, in_index FROM {table} ORDER BY id").fetchall() + assert rows and all(flag == 1 for _, flag in rows) + index = faiss_load(shared / "indices" / f"{table}.faiss") + assert sorted(faiss.vector_to_array(index.id_map)) == [pid for pid, _ in rows] + if interruption == "publish": + assert not (shared / "emb_segments" / "producer_0.done").exists() + handoff.copy_handoff(local, shared, 0) # Retrying the same transfer after consumption is harmless. + assert not (shared / "emb_segments" / "producer_0.done").exists() + assert not list((shared / "emb_segments").glob("*.npz")) + fresh = shared.parent / "next-node" + (fresh / "sqlite").mkdir(parents=True) + (fresh / "emb_segments").mkdir() + assert handoff.prepare_local_shard(fresh, shared, 0) + monkeypatch.setenv("LITKIT_MERGED_DB", str(shared / "sqlite" / "litkit.sqlite3")) + _ok(litkit(fresh, *produce)) + assert not list((fresh / "emb_segments").glob("*.npz")) + handoff.copy_handoff(fresh, shared, 0) + assert (shared / "emb_segments" / "producer_0.done").is_file() + _ok(litkit(shared, *consume)) + assert not (shared / "emb_segments" / "producer_0.done").exists() + + +@pytest.mark.parametrize("node_local", [False, True]) +@pytest.mark.parametrize("paper_index", ["flat", "hnsw"]) +def test_detached_checkpoint_and_incremental_alias(isolated_env, tmp_path, monkeypatch, node_local, paper_index): + import numpy as np + + from conftest import FakeEmbedder + from litkit.db import handoff + + shared = isolated_env + tars = tmp_path / "archives" + tars.mkdir() + original = tars / "a.tar" + write_tar(original, { + "original.xml": jats(title="Original", pmcid="PMC42", paragraphs=["Original body."]), + "control.xml": jats(title="Unchanged", pmcid="PMC43"), + }) + monkeypatch.setenv("FAKE_EMBED_DIM", "768") + _ok(litkit(shared, "--init-indices-only", "--faiss-writer", *_index_args(paper_index))) + # Older rsync jobs could install this checkpoint before installing the shard. + checkpoint = shared / "sqlite" / "build_checkpoint_shard_00.json" + checkpoint.write_text(json.dumps({"build_stream": {str(original): 1}})) + monkeypatch.setenv("LITKIT_MERGED_DB", str(shared / "sqlite" / "litkit.sqlite3")) + + for run, title in enumerate(("Original", "Revision", "Title only")): + if run == 1: + revision = jats(title="Revision", pmcid="PMC42", paragraphs=["New body."]).replace( + "", 'revised.pdf' + ).replace("", '') + write_tar(tars / "b.tar", {"alias.xml": revision}) + if run == 2: + write_tar(tars / "c.tar", {"short.xml": jats(title="Title only", pmcid="PMC42")}) + workspace = tmp_path / f"job-{run}" if node_local else shared + if node_local: + (workspace / "sqlite").mkdir(parents=True) + (workspace / "emb_segments").mkdir() + assert handoff.prepare_local_shard(workspace, shared, 0) + _ok(litkit(workspace, "--build-only", "--embed-producer", "--tar-dir", str(tars))) + if node_local: + handoff.copy_handoff(workspace, shared, 0) + _ok(litkit(shared, "--consume-only", "--faiss-writer")) + with _db(shared) as db: + assert db.execute("SELECT doc_id FROM papers WHERE pmcid='PMC42' AND in_index=1").fetchall() == [ + (f"tar://{original}!/original.xml",) + ] + assert db.execute("SELECT count(*) FROM files").fetchone() == (run + 2,) + expected = [[title, "Original body."], [title, "New body."], [title]][run] + assert db.execute("SELECT title, source_path FROM papers WHERE pmcid='PMC42'").fetchone() == ( + title, "revised.pdf" if run == 1 else None + ) + assert db.execute("SELECT c.page FROM chunks c JOIN papers p ON p.id=c.paper_id " + "WHERE p.pmcid='PMC42' AND c.ord=0").fetchall() == [[(None,)], [(6,)], []][run] + paper = faiss_load(shared / "indices" / "papers.faiss") + papers = db.execute("SELECT id, COALESCE(embedding_text, title) FROM papers WHERE in_index=1 ORDER BY id").fetchall() + assert sorted(faiss.vector_to_array(paper.id_map)) == [pid for pid, _ in papers] + assert len(papers) == 2 + for pid, text in papers: + np.testing.assert_allclose(paper.reconstruct(pid), FakeEmbedder(768).encode([text])[0], atol=3e-4) + rows = db.execute("SELECT c.id, c.text, c.in_index FROM chunks c JOIN papers p ON p.id=c.paper_id " + "ORDER BY p.pmcid, c.ord").fetchall() + assert [text for _, text, flag in rows if flag] == [*expected, "Unchanged"] + index = faiss_load(shared / "indices" / "chunks.faiss") + assert sorted(faiss.vector_to_array(index.id_map)) == sorted(cid for cid, _, _ in rows) + for cid, text, _ in rows: + np.testing.assert_allclose(index.reconstruct(cid), FakeEmbedder(768).encode([text])[0], atol=3e-4) + assert not list((shared / "emb_segments").glob("*.unresolved.*")) + + +@pytest.mark.parametrize("paper_index,numeric", [("flat", False), ("hnsw", True)]) +def test_reconcile_and_hashless_segments_preserve_revised_vectors( + isolated_env, tmp_path, monkeypatch, paper_index, numeric +): + from contextlib import closing + + import numpy as np + + from conftest import FakeEmbedder + from litkit.db import merge_shard_databases + from litkit.segments import ChunkSegmentWriter, SegmentWriter + + ws = isolated_env + tars = tmp_path / "tars" + tars.mkdir() + monkeypatch.setenv("FAKE_EMBED_DIM", "768") + _ok(litkit(ws, "--init-indices-only", "--faiss-writer", *_index_args(paper_index))) + produce = ["--build-only", "--embed-producer", "--tar-dir", str(tars)] + consume = ["--consume-only", "--faiss-writer"] + write_tar(tars / "a.tar", { + "a.xml": jats(pmcid="PMC1", title="Original", paragraphs=["Removed passage."]), + "b.xml": jats(pmcid="PMC2", title="Control"), + }) + _ok(litkit(ws, *produce)) + _ok(litkit(ws, *consume)) + with closing(_db(ws)) as db: + removed = db.execute("SELECT id FROM chunks WHERE ord=0").fetchone()[0] + write_tar(tars / "b.tar", {"alias.xml": jats(pmcid="PMC1", title="Revision")}) + _ok(litkit(ws, *produce)) + segments = ws / "emb_segments" + with closing(_db(ws)) as db: + merge_shard_databases(db, segment_dir=segments) + assert db.execute("SELECT in_index FROM papers WHERE pmcid='PMC1'").fetchone() == (0,) + + embedder = FakeEmbedder(768) + for step in ("reconcile", "consume", "legacy"): + if step == "reconcile": + _ok(litkit(ws, "--reconcile-only")) + else: + _ok(litkit(ws, *consume)) + with closing(_db(ws)) as db: + papers = db.execute("SELECT id, doc_id, title, in_index FROM papers ORDER BY pmcid").fetchall() + chunks = db.execute("SELECT c.id, p.doc_id, c.text, c.in_index FROM chunks c JOIN papers p " + "ON c.paper_id=p.id ORDER BY p.pmcid").fetchall() + for table, rows in (("papers", papers), ("chunks", chunks)): + assert [(text, indexed) for _, _, text, indexed in rows] == [("Revision", 1), ("Control", 1)] + index = faiss_load(ws / "indices" / f"{table}.faiss") + assert sorted(faiss.vector_to_array(index.id_map)) == sorted(i for i, _, _, _ in rows) + for i, _, text, _ in rows: + np.testing.assert_allclose(index.reconstruct(i), embedder.encode([text])[0], atol=3e-4) + if step == "consume": + docs = [doc for _, doc, _, _ in papers] + vectors = embedder.encode(["Original", "Control"]) + if numeric: + np.savez(segments / "papers_old.npz", ids=[r[0] for r in papers], vecs=vectors) + np.savez(segments / "chunks_old.npz", ids=[r[0] for r in chunks] + [removed], + emb=np.vstack([vectors, vectors[0]])) + else: + pw = SegmentWriter(segments) + pw.write(doc_ids=docs, vecs=vectors) + pw.finalize() + cw = ChunkSegmentWriter(segments) + cw.write(paper_doc_ids=docs, ords=[-1, -1], vecs=vectors) + cw.finalize() + (segments / "producer_0.done").touch() # The simulated legacy producer has finished. + assert len(list(segments.glob("*.unverified.*"))) == 2 + + +@pytest.mark.parametrize("newer_local", [True, False]) +def test_retained_local_shard_cannot_replace_newer_progress(isolated_env, tmp_path, monkeypatch, newer_local): + from litkit.db import handoff + from litkit.db.sharding import producer_shard_lock + + shared = isolated_env + sql = shared / "sqlite" + tars = tmp_path / "archives" + tars.mkdir() + write_tar(tars / "a.tar", {"a.xml": jats(title="A")}) + produce = ["--build-only", "--embed-producer", "--tar-dir", str(tars)] + monkeypatch.setenv("FAKE_EMBED_DIM", "768") + monkeypatch.setenv("LITKIT_MERGED_DB", str(sql / "litkit.sqlite3")) + _ok(litkit(shared, "--init-indices-only", "--faiss-writer", *FLAT)) + + def run_local(name): + local = tmp_path / name + (local / "sqlite").mkdir(parents=True) + (local / "emb_segments").mkdir() + with producer_shard_lock(sql, 0): + assert handoff.prepare_local_shard(local, shared, 0) + _ok(litkit(local, *produce)) + handoff.copy_handoff(local, shared, 0) + return local + + retained = run_local("first-node") + write_tar(tars / "b.tar", {"b.xml": jats(title="B")}) + if newer_local: + run_local("second-node") + else: + _ok(litkit(shared, *produce)) + with producer_shard_lock(sql, 0): + assert not handoff.prepare_local_shard(retained, shared, 0) + with pytest.raises(RuntimeError, match="Shared progress changed"): + handoff.copy_handoff(retained, shared, 0) + _ok(litkit(shared, *produce)) # The cluster script falls back to shared storage. + _ok(litkit(shared, "--consume-only", "--faiss-writer")) + with _db(shared) as db: + assert db.execute("SELECT title FROM papers WHERE in_index=1 ORDER BY title").fetchall() == [("A",), ("B",)] + assert _ntotal(shared, "papers.faiss") == 2 + assert not list((shared / "emb_segments").glob("*.unresolved.*")) + # A requeue can land on a node whose cleanup removed only the database. + (retained / "sqlite" / "litkit_shard_00.sqlite3").unlink() + assert list((retained / "emb_segments").glob("*.npz")) + with producer_shard_lock(sql, 0): + assert not handoff.prepare_local_shard(retained, shared, 0) + assert not list((shared / "emb_segments").glob("*.npz")) + + +@pytest.mark.parametrize("stale", ["segments", "sqlite", "checkpoint", "merged_segments"]) +def test_producer_and_consumer_reject_mixed_batch_snapshots(isolated_env, tmp_path, monkeypatch, stale): + from litkit.db import merge_shard_databases + from litkit.db.handoff import prepare_local_shard + + ws = isolated_env + tars = tmp_path / "tars" + tars.mkdir() + monkeypatch.setenv("FAKE_EMBED_DIM", "768") + _ok(litkit(ws, "--init-indices-only", "--faiss-writer", *FLAT)) + produce = ["--build-only", "--embed-producer", "--tar-dir", str(tars)] + consume = ["--consume-only", "--faiss-writer"] + write_tar(tars / "a.tar", {"a.xml": jats(title="First")}) + _ok(litkit(ws, *produce)) + paths = {"sqlite": ws / "sqlite" / "litkit_shard_00.sqlite3", + "checkpoint": ws / "sqlite" / "build_checkpoint_shard_00.json", + "segments": ws / "emb_segments"} + current = paths["segments" if stale == "merged_segments" else stale] + old = tmp_path / "old" + if current.is_dir(): + shutil.copytree(current, old) + else: + shutil.copyfile(current, old) + write_tar(tars / "b.tar", {"b.xml": jats(title="Second")}) + _ok(litkit(ws, *produce)) + if stale == "merged_segments": + paths["checkpoint"].unlink() + with _db(ws) as db: + assert merge_shard_databases(db)["papers"] == 2 + latest = current.rename(tmp_path / "latest") + old.rename(current) + for mode in (consume, produce): # Starting a producer clears its old completion marker. + failed = litkit(ws, *mode) + assert failed.returncode != 0 and "different batches" in failed.stderr + if stale != "merged_segments": + assert paths["sqlite"].is_file() + assert _count(ws, "SELECT COUNT(*) FROM papers WHERE in_index=1") == 0 + current.rename(old) + latest.rename(current) + # The matching shard can also restore a missing JSON checkpoint from SQLite. + if stale != "merged_segments": + paths["checkpoint"].unlink() + fresh = tmp_path / "new-node" + (fresh / "sqlite").mkdir(parents=True) + (fresh / "emb_segments").mkdir() + assert not prepare_local_shard(fresh, ws, 0) + _ok(litkit(ws, *produce)) + assert len(json.loads(paths["checkpoint"].read_text())["build_stream"]) == 2 + _ok(litkit(ws, *consume)) + assert _ntotal(ws, "papers.faiss") == _count(ws, "SELECT COUNT(*) FROM papers WHERE in_index=1") == 2 + + +@pytest.mark.parametrize("already_copied", [False, True]) +def test_requeued_handoff_checks_shared_segment_revision(isolated_env, tmp_path, monkeypatch, already_copied): + from litkit.db.handoff import copy_handoff, prepare_local_shard + + shared = isolated_env + segments = shared / "emb_segments" + tars = tmp_path / "archives" + tars.mkdir() + produce = ["--build-only", "--embed-producer", "--tar-dir", str(tars)] + monkeypatch.setenv("FAKE_EMBED_DIM", "768") + _ok(litkit(shared, "--init-indices-only", "--faiss-writer", *FLAT)) + for title in ("A", "B"): + write_tar(tars / f"{title}.tar", {f"{title}.xml": jats(title=title)}) + _ok(litkit(shared, *produce)) + if title == "A": + old = shutil.copytree(segments, tmp_path / "old-segments") + local = tmp_path / "local" + (local / "sqlite").mkdir(parents=True) + (local / "emb_segments").mkdir() + assert prepare_local_shard(local, shared, 0) + write_tar(tars / "C.tar", {"C.xml": jats(title="C")}) + _ok(litkit(local, *produce)) + if already_copied: + copy_handoff(local, shared, 0) + + matching = segments.rename(tmp_path / "matching-segments") + old.rename(segments) + with pytest.raises(RuntimeError, match="different batches"): + prepare_local_shard(local, shared, 0) + with pytest.raises(RuntimeError, match="different batches"): + copy_handoff(local, shared, 0) + segments.rename(old) + matching.rename(segments) + copy_handoff(local, shared, 0) + _ok(litkit(shared, "--faiss-writer", "--consume-only")) + assert _count(shared, "SELECT COUNT(*) FROM papers WHERE in_index=1") == _ntotal(shared, "papers.faiss") == 3 + + +@pytest.mark.parametrize("invalid_source", ["pending", "stale-marker"]) +def test_matching_transfer_receipt_checks_retained_source(isolated_env, tmp_path, monkeypatch, invalid_source): + from litkit.db.handoff import copy_handoff + + shared = isolated_env + local, tars = tmp_path / "local", tmp_path / "archives" + tars.mkdir() + write_tar(tars / "a.tar", {"a.xml": jats(title="A")}) + monkeypatch.setenv("FAKE_EMBED_DIM", "768") + _ok(litkit(shared, "--init-indices-only", "--faiss-writer", *FLAT)) + produce = ["--build-only", "--embed-producer", "--tar-dir", str(tars)] + _ok(litkit(local, *produce)) + copy_handoff(local, shared, 0) + final_done = shared / "emb_segments" / "producer_0.done" + old_marker = final_done.read_bytes() + final_done.unlink() + if invalid_source == "pending": + write_tar(tars / "b.tar", {"b.xml": jats(title="B")}) + interrupt = """ +import os, runpy, sys +from pathlib import Path +replace = Path.replace +def stop(src, dst): + if src.name.startswith("paper_seg_"): + os._exit(86) + return replace(src, dst) +Path.replace = stop +sys.argv = sys.argv[1:] +runpy.run_path(sys.argv[0], run_name="__main__") +""" + failed = subprocess.run([sys.executable, "-c", interrupt, str(RUNNER), *produce], + env=dict(os.environ, LITKIT_WORKSPACE=str(local)), timeout=30) + assert failed.returncode == 86 + # Even if an old marker is copied back alongside the interrupted shard, + # its matching transfer receipt cannot acknowledge unpublished new work. + (local / "emb_segments" / final_done.name).write_bytes(old_marker) + message = "pending publication" + else: + next((local / "emb_segments").glob(".litkit-output-*-chunks")).write_text("stale") + message = "different batches" + with pytest.raises(RuntimeError, match=message): + copy_handoff(local, shared, 0) + assert not final_done.exists() + assert (local / "sqlite" / "litkit_shard_00.sqlite3").is_file() + + +def test_node_local_transfer_includes_verified_legacy_files_and_claims(isolated_env, tmp_path, monkeypatch): + from contextlib import closing + + from litkit.db import handoff + + shared, local = isolated_env, tmp_path / "node" + archives = tmp_path / "archives" + archives.mkdir() + first = archives / "a.tar" + write_tar(first, {"a.xml": jats(title="Historical")}) + monkeypatch.setenv("FAKE_EMBED_DIM", "768") + _ok(litkit(shared, "--init-indices-only", "--faiss-writer", *FLAT)) + produce = ["--build-only", "--embed-producer", "--tar-dir", str(archives)] + _ok(litkit(local, *produce)) + with closing(sqlite3.connect(local / "sqlite" / "litkit_shard_00.sqlite3")) as old: + old.execute("DROP TABLE ingest_publication") + old.execute("DROP TABLE ingest_checkpoint") + old.commit() + checkpoint = local / "sqlite" / "build_checkpoint_shard_00.json" + checkpoint.write_text(json.dumps({"build_stream": {str(first): 1}})) + source = local / "emb_segments" + for marker in source.glob(".litkit-output-*"): + marker.unlink() + paper = next(source.glob("paper_seg_*.npz")).rename(source / "papers_sh00_1700000000_00000.npz") + claim = next(source.glob("chunk_seg_*.npz")).rename(source / "chunks_sh00_1700000000_00000.npz.ingesting") + other = source / "papers_sh01_1700000000_00000.npz" + other.write_bytes(b"owned by another shard") + assert handoff.prepare_local_shard(local, shared, 0) + write_tar(archives / "b.tar", {"b.xml": jats(title="Current")}) + _ok(litkit(local, *produce)) + pending = source / "paper_seg_0_5_unsaved_pending.npz" + pending.touch() + transfer = [sys.executable, "-I", handoff.__file__, "copy", str(local), str(shared), "0"] + _ok(subprocess.run(transfer, capture_output=True, text=True, timeout=30)) + dest = shared / "emb_segments" + assert (dest / paper.name).is_file() and (dest / claim.name).is_file() + assert not (dest / other.name).exists() and not (dest / pending.name).exists() + _ok(litkit(shared, "--consume-only", "--faiss-writer")) + for table in ("papers", "chunks"): + indexed = _count(shared, f"SELECT COUNT(*) FROM {table} WHERE in_index=1") + assert indexed == _ntotal(shared, f"{table}.faiss") == 2 + _ok(subprocess.run(transfer, capture_output=True, text=True, timeout=30)) + assert not (dest / paper.name).exists() and not (dest / claim.name).exists() + + +def test_cluster_host_without_sqlite_backup_selects_shared_storage(isolated_env, corpus_dir, tmp_path, monkeypatch): + from litkit.db import handoff + + shared = isolated_env + local = tmp_path / "old-host" + monkeypatch.setenv("FAKE_EMBED_DIM", "768") + _ok(litkit(shared, "--init-indices-only", "--faiss-writer", *FLAT)) + script = """ +import runpy, sqlite3, sys +sqlite3.Connection = type("LegacyConnection", (), {}) +sys.argv = sys.argv[1:] +runpy.run_path(sys.argv[0], run_name="__main__") +""" + prep = subprocess.run([sys.executable, "-I", "-c", script, handoff.__file__, "prepare", + str(local), str(shared), "0"], capture_output=True, text=True, timeout=30) + assert _ok(prep).stdout.strip() == "shared" + assert "SQLite backup" in prep.stderr and not local.exists() + _ok(litkit(shared, "--build-only", "--embed-producer", "--tar-dir", str(corpus_dir))) + _ok(litkit(shared, "--consume-only", "--faiss-writer")) + assert _ntotal(shared, "papers.faiss") == EXPECTED_PAPERS + + +@pytest.mark.parametrize("num_shards", [1, 2]) +def test_cluster_bootstrap_preserves_existing_indices(isolated_env, corpus_dir, monkeypatch, num_shards): + ws = isolated_env + monkeypatch.setenv("FAKE_EMBED_DIM", "768") + bootstrap = ["--init-indices-only", "--faiss-writer", *FLAT] + _ok(litkit(ws, *bootstrap)) + paper = ws / "indices" / "papers.faiss" + chunk = ws / "indices" / "chunks.faiss" + chunk.unlink() # A bootstrap interrupted between its two saves can resume. + _ok(litkit(ws, *bootstrap)) + assert _ntotal(ws, "chunks.faiss") == 0 + + shards = ["--num-shards", str(num_shards)] + for shard in range(num_shards): + _ok(litkit(ws, "--build-only", "--embed-producer", "--tar-dir", str(corpus_dir), + "--shard-id", str(shard), *shards)) + _ok(litkit(ws, "--consume-only", "--faiss-writer", *shards)) + assert _ntotal(ws, "papers.faiss") == EXPECTED_PAPERS + assert _ntotal(ws, "chunks.faiss") == EXPECTED_CHUNKS + meta = ws / "emb_segments" / "build_meta.json" + expected = [path.read_bytes() for path in (paper, chunk, meta)] + _ok(litkit(ws, *bootstrap)) # The cluster script omits shard flags on resubmission. + assert [path.read_bytes() for path in (paper, chunk, meta)] == expected + + chunk.unlink() + failed = litkit(ws, *bootstrap) + assert failed.returncode != 0 and "SQLite records indexed chunks" in failed.stderr + assert paper.read_bytes() == expected[0] and not chunk.exists() + + +@pytest.mark.parametrize("already_indexed", [None, "papers", "chunks"]) +def test_producer_repairs_sqlite_only_worker_rows(isolated_env, corpus_dir, monkeypatch, already_indexed): + from contextlib import closing + + import numpy as np + + from conftest import FakeEmbedder + + ws = isolated_env + monkeypatch.setenv("FAKE_EMBED_DIM", "768") + _ok(litkit(ws, "--init-indices-only", "--faiss-writer", *FLAT)) + build = ["--build-only", "--tar-dir", str(corpus_dir)] + _ok(litkit(ws, *build)) # Documented non-writer worker populates SQLite only. + if already_indexed: + table = already_indexed + column = "title || ' ' || abstract" if table == "papers" else "text" + with closing(_db(ws)) as db: + rows = db.execute(f"SELECT id, {column} FROM {table} ORDER BY id").fetchall() + path = ws / "indices" / f"{table}.faiss" + index = faiss_load(path) + index.add_with_ids(FakeEmbedder(768).encode([text for _, text in rows]), + np.array([i for i, _ in rows], dtype=np.int64)) + faiss.write_index(index, str(path)) + db.execute(f"UPDATE {table} SET in_index=1") + db.commit() + _ok(litkit(ws, *build, "--embed-producer")) + _ok(litkit(ws, "--consume-only", "--faiss-writer")) + with closing(_db(ws)) as db: + for table, count in (("papers", EXPECTED_PAPERS), ("chunks", EXPECTED_CHUNKS)): + ids = [row[0] for row in db.execute(f"SELECT id FROM {table} WHERE in_index=1 ORDER BY id")] + assert len(ids) == count + index = faiss_load(ws / "indices" / f"{table}.faiss") + assert sorted(faiss.vector_to_array(index.id_map)) == ids + + +def test_rebuild_preserves_only_indexed_copy_of_retained_shard(isolated_env, corpus_dir, monkeypatch): + from contextlib import closing + + from litkit.db import merge_shard_databases + + ws = isolated_env + write_tar(corpus_dir / "b.tar", {"b.xml": jats(title="Second archive")}) + monkeypatch.setenv("FAKE_EMBED_DIM", "768") + shards = ["--num-shards", "2"] + build = ["--build-only", "--tar-dir", str(corpus_dir), *shards, *FLAT] + _ok(litkit(ws, "--init-indices-only", "--faiss-writer", *shards, *FLAT)) + for shard in ("0", "1"): + _ok(litkit(ws, *build, "--embed-producer", "--shard-id", shard)) + with closing(_db(ws)) as db: + merge_shard_databases(db, delete_after_merge=False, segment_dir=ws / "emb_segments") + _ok(litkit(ws, *build, "--faiss-writer", "--consume-segments")) + before = [(ws / "indices" / name).read_bytes() for name in ("papers.faiss", "chunks.faiss")] + rebuild = [*build, "--faiss-writer", "--rebuild", "--force-rebuild"] + failed = litkit(ws, *rebuild) + assert failed.returncode != 0 and "depends on vectors in the current indices" in failed.stderr + assert [(ws / "indices" / name).read_bytes() for name in ("papers.faiss", "chunks.faiss")] == before + _ok(litkit(ws, "--consume-only", "--faiss-writer", *shards)) + _ok(litkit(ws, *rebuild)) + for shard in ("0", "1"): + _ok(litkit(ws, *build, "--embed-producer", "--shard-id", shard)) + _ok(litkit(ws, "--consume-only", "--faiss-writer", *shards)) + assert _ntotal(ws, "papers.faiss") == EXPECTED_PAPERS + 1 + assert _ntotal(ws, "chunks.faiss") == EXPECTED_CHUNKS + 1 + + +def test_incremental_producers_after_forced_writer_rebuild(isolated_env, corpus_dir, monkeypatch): + from contextlib import closing + + ws = isolated_env + monkeypatch.setenv("FAKE_EMBED_DIM", "768") + shard_args = ["--num-shards", "2"] + writer = ["--faiss-writer", *shard_args, *FLAT] + produce = ["--build-only", "--embed-producer", "--tar-dir", str(corpus_dir), *shard_args] + consume = ["--consume-only", *writer] + rebuild = ["--build-only", "--rebuild", "--force-rebuild", "--tar-dir", str(corpus_dir), *writer] + _ok(litkit(ws, "--init-indices-only", *writer)) + for shard in ("0", "1"): + _ok(litkit(ws, *produce, "--shard-id", shard)) + _ok(litkit(ws, *consume)) + checkpoint = ws / "sqlite" / "build_checkpoint_shard_00.json" + before = json.loads(checkpoint.read_bytes()) + with closing(_db(ws)) as db: + db.execute("CREATE TRIGGER stop_reset BEFORE DELETE ON merged_shard_checkpoints " + "BEGIN SELECT RAISE(ABORT, 'interrupted reset'); END") + failed = litkit(ws, *rebuild) + assert failed.returncode != 0 and "interrupted reset" in failed.stderr + assert not checkpoint.exists() + with closing(_db(ws)) as db: + restored = db.execute("SELECT checkpoint FROM merged_shard_checkpoints WHERE shard_id=0").fetchone() + assert json.loads(restored[0]) == before + db.execute("DROP TRIGGER stop_reset") + for shard in ("0", "1"): + _ok(litkit(ws, *produce, "--shard-id", shard)) + assert json.loads(checkpoint.read_bytes())["producer_revision"] == before["producer_revision"] + _ok(litkit(ws, *consume)) + assert _ntotal(ws, "papers.faiss") == EXPECTED_PAPERS + _ok(litkit(ws, *rebuild)) + assert not checkpoint.exists() + assert _count(ws, "SELECT COUNT(*) FROM merged_shard_checkpoints") == 0 + + write_tar(corpus_dir / "b.tar", {"new.xml": jats(title="Incremental paper")}) + for shard in ("0", "1"): + _ok(litkit(ws, *produce, "--shard-id", shard)) + _ok(litkit(ws, *consume)) + with closing(_db(ws)) as db: + for table, expected in (("papers", EXPECTED_PAPERS + 1), ("chunks", EXPECTED_CHUNKS + 1)): + rows = db.execute(f"SELECT id, in_index FROM {table} ORDER BY id").fetchall() + assert len(rows) == expected and all(flag for _, flag in rows) + index = faiss_load(ws / "indices" / f"{table}.faiss") + assert sorted(faiss.vector_to_array(index.id_map)) == [row[0] for row in rows] + + +@pytest.mark.parametrize("interruption", ["before-commit", "before-publish", "after-commit"]) +def test_two_producers_resume_after_process_exit( + isolated_env, corpus_dir, monkeypatch, interruption +): + from litkit.segments.checkpoint import load_checkpoint + from litkit.segments.metadata import has_segment_files + + ws = isolated_env + write_tar(corpus_dir / "b.tar", {"notes.xml": jats(title="Instrument notes")}) + # --init-indices-only creates 768-dimensional indices. + monkeypatch.setenv("FAKE_EMBED_DIM", "768") + _ok(litkit(ws, "--init-indices-only", "--faiss-writer", "--num-shards", "2", *FLAT)) + args = [ + "--build-only", + "--embed-producer", + "--tar-dir", + str(corpus_dir), + "--num-shards", + "2", + "--paper-batch", + "1", + ] + # os._exit bypasses Python cleanup and SQLite context managers. + crash = """ +import os, runpy, sys +from pathlib import Path +from litkit.segments.writer import SegmentWriter +runner, point = sys.argv[1:3] +sys.argv = [runner, *sys.argv[3:]] +if point == "before-commit": + stage = SegmentWriter.stage + def stop_after_write(self, *args, **kwargs): + stage(self, *args, **kwargs) + os._exit(86) + SegmentWriter.stage = stop_after_write +else: + replace = Path.replace + def stop_after_rename(self, target): + if point == "before-publish" and self.name.startswith("paper_seg_"): + os._exit(86) + result = replace(self, target) + if self.name.startswith("paper_seg_"): + os._exit(86) + return result + Path.replace = stop_after_rename +runpy.run_path(runner, run_name="__main__") +""" + proc = subprocess.run( + [sys.executable, "-c", crash, str(RUNNER), interruption, *args, "--shard-id", "0"], + env=dict(os.environ, LITKIT_WORKSPACE=str(ws)), + capture_output=True, + text=True, + timeout=120, + ) + assert proc.returncode == 86, proc.stderr + seg_dir = ws / "emb_segments" + checkpoint = ws / "sqlite" / "build_checkpoint.json" + assert has_segment_files(seg_dir) == (interruption == "after-commit") + assert load_checkpoint(checkpoint, 0) == {} + assert not (seg_dir / "producer_0.done").exists() + + if interruption == "before-commit": + from contextlib import closing + + from litkit.db import merge_shard_databases + + with closing(_db(ws)) as main: + with pytest.raises(RuntimeError, match="unfinished batch publication or cleanup"): + merge_shard_databases(main) + assert (ws / "sqlite" / "litkit_shard_00.sqlite3").is_file() + + if interruption == "before-publish": + blocked = litkit( + ws, + "--build-only", + "--faiss-writer", + "--rebuild", + "--num-shards", + "2", + "--tar-dir", + str(corpus_dir), + *FLAT, + ) + assert blocked.returncode != 0 + assert "committed batch awaiting publication" in blocked.stderr + assert "Rerun the interrupted producer" in blocked.stderr + # Stale completion markers must not let the consumer delete the journal. + markers = [seg_dir / f"producer_{shard}.done" for shard in (0, 1)] + for marker in markers: + marker.touch() + consume = litkit( + ws, "--build-only", "--consume-only", "--faiss-writer", "--num-shards", "2" + ) + assert consume.returncode != 0 + assert "unfinished batch publication or cleanup" in consume.stderr + for marker in markers: + marker.unlink() + + _ok(litkit(ws, *args, "--shard-id", "1")) + _ok(litkit(ws, *args, "--shard-id", "0")) + assert not list(seg_dir.glob(".litkit-batch-*")) + _ok(litkit(ws, "--build-only", "--consume-only", "--faiss-writer", "--num-shards", "2")) + assert not has_segment_files(seg_dir) + with _db(ws) as conn: + for table, expected in [("papers", 4), ("chunks", 7)]: + ids = [r[0] for r in conn.execute(f"SELECT id FROM {table} ORDER BY id")] + assert len(ids) == expected + assert conn.execute(f"SELECT SUM(in_index) FROM {table}").fetchone() == (expected,) + index = faiss_load(ws / "indices" / f"{table}.faiss") + assert sorted(faiss.vector_to_array(index.id_map)) == ids + + +@pytest.mark.parametrize("paper_index", ["flat", "hnsw"]) +def test_rebuild_keeps_one_vector_for_a_paper_alias_across_tars( + isolated_env, tiny_corpus, paper_index +): + _ok( + litkit( + isolated_env, + "--build-only", + "--faiss-writer", + "--rebuild", + "--tar-dir", + str(tiny_corpus), + *_index_args(paper_index), + ) + ) + with _db(isolated_env) as conn: + ids = [row[0] for row in conn.execute("SELECT id FROM papers ORDER BY id")] + index = faiss_load(isolated_env / "indices" / "papers.faiss") + assert sorted(faiss.vector_to_array(index.id_map)) == ids + + +def test_consumer_finishes_merge_before_next_producer_opens_shard(isolated_env, tmp_path, monkeypatch): + import time + + ws = isolated_env + tars = tmp_path / "tars" + tars.mkdir() + write_tar(tars / "a.tar", {"a.xml": jats(title="First paper")}) + monkeypatch.setenv("FAKE_EMBED_DIM", "768") + _ok(litkit(ws, "--init-indices-only", "--faiss-writer", *FLAT)) + produce = ["--build-only", "--embed-producer", "--tar-dir", str(tars)] + consume = ["--build-only", "--consume-only", "--faiss-writer"] + _ok(litkit(ws, *produce)) + write_tar(tars / "b.tar", {"b.xml": jats(title="Second paper")}) + + # Rendezvous at the preflight/merge boundary and at the next producer's + # first lock attempt. Both processes use the ordinary CLI and real SQLite. + hook = """ +import os, runpy, sys, time +from pathlib import Path +from litkit import cli +from litkit.db import sharding +runner, root, role = sys.argv[1:4] +root = Path(root) +sys.argv = [runner, *sys.argv[4:]] +if role == "consumer": + inspect = sharding.unpublished_shards + def pause_after_check(shards, **options): + result = inspect(shards, **options) + (root / "checked").touch() + deadline = time.monotonic() + 20 + while not (root / "contending").exists(): + if time.monotonic() >= deadline: + raise RuntimeError("producer did not reach the lock") + time.sleep(0.02) + return result + sharding.unpublished_shards = pause_after_check +else: + class ContendingLock(cli.FileLock): + def __enter__(self): + if self.path.name == "producer-admission.lock": + (root / "contending").touch() + return super().__enter__() + cli.FileLock = ContendingLock +runpy.run_path(runner, run_name="__main__") +""" + args = [sys.executable, "-c", hook, str(RUNNER), str(tmp_path)] + env = dict(os.environ, LITKIT_WORKSPACE=str(ws)) + with subprocess.Popen( + args + ["consumer", *consume], + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) as consumer: + deadline = time.monotonic() + 20 + while not (tmp_path / "checked").exists(): + if consumer.poll() is not None or time.monotonic() >= deadline: + consumer.kill() + pytest.fail(f"consumer preflight failed: {consumer.communicate()[1]}") + time.sleep(0.02) + next_producer = subprocess.run( + args + ["producer", *produce], env=env, capture_output=True, text=True, timeout=40 + ) + _, errors = consumer.communicate(timeout=30) + assert consumer.returncode == 0, errors + _ok(next_producer) + + assert _ntotal(ws, "papers.faiss") == 1 + _ok(litkit(ws, *consume)) + with _db(ws) as conn: + rows = conn.execute("SELECT id, title FROM papers ORDER BY id").fetchall() + assert [title for _, title in rows] == ["First paper", "Second paper"] + index = faiss_load(ws / "indices" / "papers.faiss") + assert sorted(faiss.vector_to_array(index.id_map)) == [pid for pid, _ in rows] diff --git a/tests/integration/test_multi_node.py b/tests/integration/test_multi_node.py index cab4272..20e06e8 100644 --- a/tests/integration/test_multi_node.py +++ b/tests/integration/test_multi_node.py @@ -83,7 +83,14 @@ def test_multi_node_build_indexes_every_shard_and_removes_markers(isolated_env, assert faiss.read_index(str(ws / "indices" / "papers.faiss")).ntotal == n_papers assert faiss.read_index(str(ws / "indices" / "chunks.faiss")).ntotal == 2 * n_papers # Every segment and marker is consumed (#5), and the shard databases are merged. - assert sorted(p.name for p in seg_dir.iterdir()) == ["build_meta.json"] + from litkit.db.handoff import output_markers + from litkit.segments.checkpoint import load_checkpoint + + remaining = {seg_dir / "build_meta.json"} + for shard in range(NUM_SHARDS): + checkpoint = load_checkpoint(ws / "sqlite" / "build_checkpoint.json", shard_id=shard) + remaining.update(output_markers(checkpoint, seg_dir, seg_dir)) + assert set(seg_dir.iterdir()) == remaining assert list((ws / "sqlite").glob("litkit_shard_*.sqlite3")) == [] # Leftover markers blocked this as "Prior multi-node run (not consumed)" (#5). @@ -126,18 +133,20 @@ def test_multi_node_script_clears_markers_before_starting_producers(): assert clear and clear[0] < start -@pytest.mark.skipif(os.name == "nt", reason="runs the script's POSIX find command") -def test_resume_script_counts_claimed_segments(tmp_path): - """#2: a consumer stopped before a save keeps the segments it claimed as - *.npz.ingesting. The resume script must count them, or it exits with "Nothing to do".""" - (line,) = [s for s in _script_lines("vector_resume_consumer.sbatch") if s.startswith("n_segs=")] - for name in ("paper_seg_0_0_aaaa.npz", "chunk_seg_0_0_bbbb.npz.ingesting"): - (tmp_path / name).touch() +@pytest.mark.skipif(os.name == "nt", reason="runs the resume script's shell commands") +def test_resume_script_detects_claimed_segments(tmp_path): + """#2: a claimed segment alone must still cause the script to start the consumer.""" + lines = _script_lines("vector_resume_consumer.sbatch") + commands = [ + next(line for line in lines if line.startswith(prefix)) + for prefix in ("discovery=", "n_shards=") + ] + (tmp_path / "chunk_seg_3_0_bbbb.npz.ingesting").touch() count = subprocess.run( - ["bash", "-c", f'{line}\necho "$n_segs"'], - env=dict(os.environ, SEG_DIR=str(tmp_path)), + ["bash", "-c", "\n".join([*commands, 'echo "$n_shards"'])], + env=dict(os.environ, SEG_DIR=str(tmp_path), LITKIT_REPO=str(REPO)), capture_output=True, text=True, check=True, ) - assert int(count.stdout) == 2 + assert int(count.stdout) == 4 diff --git a/tests/test_db.py b/tests/test_db.py index 3d27f5b..e1d5c7e 100644 --- a/tests/test_db.py +++ b/tests/test_db.py @@ -201,6 +201,119 @@ def test_merge_and_retrieve_chunk_citation(tmp_path, legacy): migrated.close() +def test_merge_commits_and_detaches_each_shard_before_removal(tmp_path): + from contextlib import closing + + from litkit.db import init_shard_db, merge_shard_databases, shard_db_path + + for i in range(12): + with closing(init_shard_db(shard_db_path(tmp_path, i), i)) as shard, shard: + pid = shard.execute( + "INSERT INTO papers(doc_id, embedding_text) VALUES (?, ?)", + (f"doc-{i}", f"version {i}"), + ).lastrowid + shard.execute("INSERT INTO chunks(paper_id, ord, text) VALUES (?, -1, 'text')", (pid,)) + with closing(init_db(tmp_path / "main.sqlite3")) as main: + stats = merge_shard_databases(main) + assert (stats["shards"], stats["papers"], stats["chunks"]) == (12, 12, 12) + assert main.execute( + "SELECT COUNT(*) FROM papers WHERE embedding_text IS NOT NULL" + ).fetchone() == (12,) + assert {r[1] for r in main.execute("PRAGMA database_list")} <= {"main", "temp"} + assert not list(tmp_path.glob("litkit_shard_*.sqlite3")) + + +def test_merge_failure_preserves_source_shard_and_rolls_back_its_rows(tmp_path): + from contextlib import closing + + from litkit.db import init_shard_db, merge_shard_databases, shard_db_path + + path = shard_db_path(tmp_path, 0) + with closing(init_shard_db(path, 0)) as shard, shard: + shard.execute("INSERT INTO papers(doc_id) VALUES ('doc')") + shard.execute("DROP TABLE files") + with closing(init_db(tmp_path / "main.sqlite3")) as main: + with pytest.raises(sqlite3.OperationalError, match="files"): + merge_shard_databases(main) + assert main.execute("SELECT COUNT(*) FROM papers").fetchone() == (0,) + assert {r[1] for r in main.execute("PRAGMA database_list")} <= {"main", "temp"} + assert path.is_file() + + +def test_merge_drains_producers_one_at_a_time_and_accepts_unpadded_shards(tmp_path): + from contextlib import closing, contextmanager + + from litkit.concurrent.locking import FileLock + from litkit.db.sharding import merged_shard_databases, producer_shard_lock + + names = ["litkit_shard_0.sqlite3", *(f"litkit_shard_{i:02}.sqlite3" for i in range(12))] + for name in names: + shard_id = int(name.removeprefix("litkit_shard_").split(".")[0]) + with producer_shard_lock(tmp_path, shard_id): + with closing(init_db(tmp_path / name)) as shard, shard: + shard.execute("INSERT INTO papers(doc_id) VALUES (?)", (name,)) + acquired = set() + held = set() + + @contextmanager + def track_descriptors(path): + assert path not in held, "a second flock on the same path would deadlock" + held.add(path) + acquired.add(path.name) + assert len(held) <= 2 + with FileLock(path): + yield + held.remove(path) + + with closing(init_db(tmp_path / "main.sqlite3")) as main: + with merged_shard_databases(main, lock_factory=track_descriptors) as stats: + assert stats["papers"] == stats["shards"] == len(names) + assert held == {tmp_path / "producer-admission.lock"} + assert acquired == {"producer-admission.lock", *(f"producer_{i}.lock" for i in range(12))} + + +def test_merge_rejects_unverified_shard_local_numeric_segment_ids(tmp_path): + from contextlib import closing + + import numpy as np + + from litkit.db import merge_shard_databases, shard_db_path + + segments = tmp_path / "segments" + segments.mkdir() + for i in range(2): + with closing(init_db(shard_db_path(tmp_path, i))) as shard, shard: + shard.execute("INSERT INTO papers(id, doc_id) VALUES (1, ?)", (f"doc-{i}",)) + shard.execute("INSERT INTO chunks(id, paper_id, ord, text) VALUES (1, 1, -1, ?)", (f"text-{i}",)) + shard.execute("INSERT INTO files(path, paper_id) VALUES ('paper.xml', 1)") + for table in ("papers", "chunks"): + np.savez(segments / f"{table}_sh0_001.npz", ids=[1], vecs=[[1., 0.]]) + with closing(init_db(tmp_path / "main.sqlite3")) as main: + with pytest.raises(RuntimeError, match="numeric IDs"): + merge_shard_databases(main, segment_dir=segments) + assert main.execute("SELECT COUNT(*) FROM papers").fetchone() == (0,) + assert all(shard_db_path(tmp_path, i).is_file() for i in range(2)) + + +def test_unverified_legacy_shard_keeps_its_source_when_an_identifier_overlaps(tmp_path): + from contextlib import closing + + from litkit.db import init_shard_db, merge_shard_databases, shard_db_path + + source = shard_db_path(tmp_path, 0) + with closing(init_shard_db(source, 0)) as shard, shard: + shard.execute("INSERT INTO papers(doc_id, pmcid) VALUES ('second.xml', 'PMC42')") + shard.execute("INSERT INTO files(path, paper_id) VALUES ('second.xml', 1)") + with closing(init_db(tmp_path / "main.sqlite3")) as main: + with main: + main.execute("INSERT INTO papers(doc_id, pmcid) VALUES ('first.xml', 'PMC42')") + with pytest.raises(RuntimeError, match="Cannot verify overlapping article second.xml"): + merge_shard_databases(main) + assert main.execute("SELECT doc_id FROM papers").fetchall() == [("first.xml",)] + with closing(sqlite3.connect(source)) as shard: + assert shard.execute("SELECT path FROM files").fetchall() == [("second.xml",)] + + def test_merge_shard_databases_merges_more_shards_than_sqlite_can_attach(tmp_path): """#1: SQLite attaches at most 10 databases at once, so each shard must be detached before the next is attached. Twelve shards check that rows from all of them arrive.""" diff --git a/tests/test_index.py b/tests/test_index.py index 3fd36bf..9ab5e28 100644 --- a/tests/test_index.py +++ b/tests/test_index.py @@ -117,6 +117,51 @@ def test_safe_remove_ids(unit_vectors, capsys): assert capsys.readouterr().err == "" # and silent +def test_ivfpq_removal_and_replacement_preserve_surviving_search_results(tmp_path, unit_vectors): + import sqlite3 + from contextlib import closing + + from litkit.segments.ingest import ingest_chunk_segments + + core = ivfpq_index(DIM, nlist=4, m=4, bits=4) + core.train(unit_vectors(960, DIM)) + core.nprobe = core.nlist + index = faiss.IndexIDMap2(core) + vectors = unit_vectors(8, DIM) + ids = [101, 202, 303, 404, 505, 606, 707] + index.add_with_ids(vectors[:7], np.array(ids, dtype=np.int64)) + scores, matches = index.search(vectors, len(ids)) + path = tmp_path / "chunks.faiss" + with closing(sqlite3.connect(":memory:")) as db: + db.execute("CREATE TABLE obsolete_chunk_vectors(id INTEGER PRIMARY KEY)") + db.executemany("INSERT INTO obsolete_chunk_vectors VALUES (?)", [(202,), (404,)]) + ingest_chunk_segments(db, index, tmp_path, tmp_path / "faiss.lock", path) + assert db.execute("SELECT COUNT(*) FROM obsolete_chunk_vectors").fetchone() == (0,) + saved = faiss.read_index(str(path)) + keep = ~np.isin(matches, [202, 404]) + after_scores, after_matches = saved.search(vectors, 5) + np.testing.assert_array_equal(after_matches, matches[keep].reshape(-1, 5)) + np.testing.assert_array_equal(after_scores, scores[keep].reshape(-1, 5)) + + add_with_ids_dedup(saved, [303], vectors[7:]) + expected = faiss.clone_index(index) + expected.reset() + expected.add_with_ids( + vectors[[0, 4, 5, 6, 7]], np.array([101, 505, 606, 707, 303], dtype=np.int64) + ) + faiss.write_index(saved, str(path)) + for actual, reference in zip( + faiss.read_index(str(path)).search(vectors, 5), expected.search(vectors, 5), strict=True + ): + np.testing.assert_array_equal(actual, reference) + + # An index saved after the historical native removal has already lost + # part of its label mapping. Detect that damage before publishing a change. + saved.remove_ids(np.array([505], dtype=np.int64)) + with pytest.raises(ValueError, match="IVF labels do not match"): + safe_remove_ids(saved, make_id_selector([101])) + + @pytest.mark.parametrize("kind", ["flat", "ivfpq"]) @pytest.mark.parametrize( "remove", @@ -138,6 +183,22 @@ def test_make_id_selector_removes_exactly_the_given_ids(unit_vectors, make_index assert faiss_present_ids(index) == expected +def test_ivf_removal_reads_the_ids_instead_of_testing_each_stored_id(unit_vectors, make_index): + """IVF removal compacts the inverted lists itself, so it needs the IDs, not only a + selector. Given only is_member(), it calls it from Python for every stored ID: 0.11 s + per dedup at 1M vectors, even when nothing is removed.""" + ids = np.arange(400, dtype="int64") + index = make_index("ivfpq", unit_vectors(len(ids), DIM), ids) + selector = make_id_selector([3, 5]) + + def per_stored_id(i): + raise AssertionError("tested a stored ID in Python") + + selector.is_member = per_stored_id + assert safe_remove_ids(index, selector) == 2 + assert faiss_present_ids(index) == set(ids.tolist()) - {3, 5} + + def test_removing_many_ids_costs_about_as_much_as_removing_few(rng): """#14: remove_ids() tests every stored ID against the selector. IDSelectorArray scans its whole ID list for each test, so removing k IDs from N vectors cost diff --git a/tests/test_segments.py b/tests/test_segments.py index 3e5e67e..2c9c3b8 100644 --- a/tests/test_segments.py +++ b/tests/test_segments.py @@ -18,6 +18,7 @@ from conftest import CORPUS, FakeEmbedder, jats, write_tar from litkit.build.consume import run_consume_only_mode from litkit.build.ingest_loop import process_tar_files +from litkit.build.publication import BatchPublication from litkit.concurrent.locking import FileLock from litkit.db import init_db, init_shard_db, shard_db_path from litkit.index import faiss_load, faiss_save_force, flat_ip_index, hnsw_index, kind_and_core @@ -95,6 +96,24 @@ def test_add_flushes_every_segment_size(seg_dir): assert sorted(counts) == [1, 3, 3] +@pytest.mark.parametrize("kind", ["papers", "chunks"]) +def test_consumer_reads_double_digit_writer_counters_in_order(seg_dir, kind): + w = ( + SegmentWriter(seg_dir, dtype="fp32") + if kind == "papers" + else ChunkSegmentWriter(seg_dir, dtype="fp32") + ) + keys = {"doc_ids": ["d"]} if kind == "papers" else {"paper_doc_ids": ["d"], "ords": [0]} + for revision in range(12): + w.write(**keys, vecs=np.array([[revision]], dtype=np.float32)) + assert w.finalize() == 12 + revisions = [] + for path in _glob_segment_files(seg_dir, kind): + with np.load(path) as segment: + revisions.append(segment["vecs"].item()) + assert revisions == list(range(12)) + + def test_empty_write_writes_nothing(seg_dir): w = ChunkSegmentWriter(seg_dir) assert w.write(paper_doc_ids=[], ords=[], vecs=np.zeros((0, 4))) is None @@ -124,6 +143,127 @@ def test_cleanup_orphan_pending_files(seg_dir, unit_vectors): assert cleanup_orphan_pending_files(seg_dir / "missing") == 0 +@pytest.mark.parametrize("kind", ["papers", "chunks"]) +def test_segment_writer_keeps_failed_rename_for_retry(seg_dir, unit_vectors, monkeypatch, kind): + from pathlib import Path + + writer = _write_one(kind, seg_dir, unit_vectors(1, 4)) + with monkeypatch.context() as fault: + + def fail_replace(*args): + raise OSError("rename failed") + + fault.setattr(Path, "replace", fail_replace) + with pytest.raises(OSError, match="rename failed"): + writer.finalize() + assert writer.pending_count == 1 + assert not has_segment_files(seg_dir) + assert writer.finalize() == 1 + + +@pytest.mark.parametrize("kind", ["papers", "chunks"]) +def test_segment_writer_rejects_incomplete_embedding_batch(seg_dir, unit_vectors, kind): + if kind == "papers": + writer = SegmentWriter(seg_dir) + keys = dict(doc_ids=["a", "b"]) + else: + writer = ChunkSegmentWriter(seg_dir) + keys = dict(paper_doc_ids=["a", "b"], ords=[0, 1]) + with pytest.raises(ValueError, match="same length"): + writer.write(**keys, vecs=unit_vectors(1, 4)) + assert writer.flush() is None + assert list(seg_dir.iterdir()) == [] + + +@pytest.mark.parametrize("kind", ["papers", "chunks"]) +def test_retry_after_disk_error_keeps_buffered_vectors_once( + seg_dir, unit_vectors, monkeypatch, kind +): + vectors = unit_vectors(2, 4) + if kind == "papers": + writer = SegmentWriter(seg_dir, segment_size=2) + writer.add("first", vectors[0]) + args = ("second", vectors[1]) + key = "doc_ids" + else: + writer = ChunkSegmentWriter(seg_dir, segment_size=2) + writer.add("first", 0, vectors[0]) + args = ("second", 1, vectors[1]) + key = "paper_doc_ids" + + def full_disk(*args, **kwargs): + raise OSError("disk full") + + with monkeypatch.context() as fault: + fault.setattr(np, "savez_compressed", full_disk) + with pytest.raises(OSError, match="disk full"): + writer.add(*args) + assert list(seg_dir.iterdir()) == [] + writer.add(*args) + assert writer.finalize() == 1 + with np.load(next(seg_dir.iterdir()), allow_pickle=True) as segment: + assert segment[key].tolist() == ["first", "second"] + np.testing.assert_array_equal(segment["vecs"], vectors.astype("float16")) + + +@pytest.mark.parametrize("kind", ["papers", "chunks"]) +def test_retry_finishes_other_segments_after_successful_rename_raises( + seg_dir, unit_vectors, monkeypatch, kind +): + from pathlib import Path + + vectors = unit_vectors(2, 4) + w = _write_one(kind, seg_dir, vectors[:1]) + if kind == "papers": + w.write(doc_ids=["d"], vecs=vectors[1:]) + else: + w.write(paper_doc_ids=["d"], ords=[0], vecs=vectors[1:]) + replace = Path.replace + with monkeypatch.context() as fault: + + def exit_after_rename(path, target): + replace(path, target) + raise KeyboardInterrupt + + fault.setattr(Path, "replace", exit_after_rename) + with pytest.raises(KeyboardInterrupt): + w.finalize() + [first] = _glob_segment_files(seg_dir, kind) + with np.load(first) as segment: + np.testing.assert_array_equal(segment["vecs"], vectors[:1]) + first.unlink() # A consumer can finish the first segment before retry. + assert w.finalize() == 1 + [second] = _glob_segment_files(seg_dir, kind) + with np.load(second) as segment: + np.testing.assert_array_equal(segment["vecs"], vectors[1:]) + + +def test_cluster_segment_commands_use_consumer_discovery(seg_dir): + import subprocess + import sys + + from litkit.segments import discovery + + def run(command): + return subprocess.check_output( + [sys.executable, "-I", discovery.__file__, command, str(seg_dir)], text=True + ).strip() + + stage = seg_dir / ".litkit-batch-hidden" + stage.mkdir() + (stage / "paper_seg_0_0_x.npz").touch() + (seg_dir / "paper_seg_0_0_x_pending.npz").touch() + (seg_dir / "unrelated.npz").touch() + assert run("count") == "0" + claim = seg_dir / "chunk_seg_3_0_x.npz.ingesting" + claim.touch() + assert run("count") == "1" + assert run("sample") == str(claim) + assert run("shards") == "4" + (seg_dir / "build_meta.json").write_text('{"num_shards": 8}') + assert run("shards") == "8" + + def _write_one(kind, seg_dir, vec): if kind == "papers": w = SegmentWriter(seg_dir, dtype="fp32") @@ -137,6 +277,9 @@ def _write_one(kind, seg_dir, vec): @pytest.mark.parametrize("kind", ["papers", "chunks"]) def test_consumer_does_not_see_pending_segments(seg_dir, unit_vectors, kind): _write_one(kind, seg_dir, unit_vectors(1, 4)) # pending, not finalized + prefix = "paper_seg" if kind == "papers" else "chunk_seg" + for suffix in (".npz.pending", ".npz.pending.npz", ".npz.pending.npz.ingesting"): + (seg_dir / f"{prefix}_0_0_legacy{suffix}").touch() assert _glob_segment_files(seg_dir, kind) == [] assert has_segment_files(seg_dir) is False @@ -149,6 +292,17 @@ def test_consumer_sees_finalized_segments(seg_dir, unit_vectors, kind): assert has_segment_files(seg_dir) is True +@pytest.mark.parametrize("kind,prefix", [("papers", "papers.seg."), ("chunks", "chunks_")]) +def test_legacy_segments_and_interrupted_claims_remain_discoverable(seg_dir, kind, prefix): + ready = seg_dir / f"{prefix}old.npz.ingesting" + pending = seg_dir / f"{prefix}new_pending.npz.ingesting" + pending.touch() + assert not has_segment_files(seg_dir) + ready.touch() + assert _glob_segment_files(seg_dir, kind) == [ready] + assert has_segment_files(seg_dir) + + # -------------------------------------------------------------- consumer ingest DIM = 16 @@ -400,6 +554,92 @@ def test_clear_shard_checkpoints_removes_stale_higher_shards(sqlite_dir): class OutOfMemoryOnce(FakeEmbedder): + """Fail the final chunk embedding after one completed batch.""" + + def __init__(self): + super().__init__(DIM) + self.failed = False + + def encode(self, texts, **kwargs): + if self.calls and not self.failed: + self.failed = True + raise RuntimeError("CUDA out of memory") + return super().encode(texts, **kwargs) + + +def _produce(tmp_path, tar, conn, paper_embedder, chunk_embedder, *, rebuild=False): + """Run producer shard 0 with unequal paper and chunk batch thresholds.""" + sqlite_dir = tmp_path / "sqlite" + seg_dir = tmp_path / "emb_segments" + return process_tar_files( + tar_paths=[tar], + conn=conn, + paper_embedder=paper_embedder, + chunk_embedder=chunk_embedder, + paper_index=None, + chunk_index=None, + paper_seg_writer=SegmentWriter(seg_dir, dtype="fp32"), + chunk_seg_writer=ChunkSegmentWriter(seg_dir, dtype="fp32"), + ckpt_path=sqlite_dir / "build_checkpoint.json", + ckpt_lock=sqlite_dir / "ckpt.writer.lock", + faiss_lock=sqlite_dir / "faiss.writer.lock", + db_lock=sqlite_dir / "db.writer.lock", + paper_index_path=tmp_path / "indices" / "papers.faiss", + chunk_index_path=tmp_path / "indices" / "chunks.faiss", + sqlite_dir=sqlite_dir, + FileLock=FileLock, + rebuild=rebuild, + embed_producer=True, + faiss_writer=False, + strict_ingest=True, + paper_batch=2, + chunk_batch=10_000, + ckpt_every=1, + paper_embed_bs=8, + chunk_embed_bs=8, + chunk_target_chars=1200, + chunk_min_chars=0, + chunk_overlap=0, + ckpt_shard_id=0, + parse_workers=1, + ) + + +def test_producer_checkpoint_counts_no_article_whose_segment_is_deleted(tmp_path, seg_dir): + """#3: a failing tar-boundary flush preserves both segments of the checkpointed batch.""" + tar = write_tar(tmp_path / "a.tar", {f"{v['pmcid']}.nxml": jats(**v) for v in CORPUS.values()}) + doc_ids = {f"tar://{tar}!/{v['pmcid']}.nxml" for v in CORPUS.values()} + ckpt = tmp_path / "sqlite" / "build_checkpoint.json" + conn = init_shard_db(shard_db_path(tmp_path / "sqlite", 0), 0) + try: + papers = FakeEmbedder(DIM) + with pytest.raises(RuntimeError, match="out of memory"): + _produce(tmp_path, tar, conn, papers, OutOfMemoryOnce()) + assert [len(batch) for batch in papers.calls] == [2, 1] # one mid-tar flush + assert load_checkpoint(ckpt, shard_id=0)["build_stream"][str(tar)] == 2 + stored = {row[0] for row in conn.execute("SELECT doc_id FROM papers")} + assert len(stored) == 2 + for kind, key in [("papers", "doc_ids"), ("chunks", "paper_doc_ids")]: + [path] = _glob_segment_files(seg_dir, kind) + with np.load(path, allow_pickle=True) as segment: + assert set(segment[key]) == stored + + # The normal incremental restart must recover even with the file table enabled. + _produce(tmp_path, tar, conn, FakeEmbedder(DIM), FakeEmbedder(DIM)) + finally: + conn.close() + produced = set() + for path in seg_dir.glob("paper_seg_*.npz"): + with np.load(path, allow_pickle=True) as z: + produced.update(str(d) for d in z["doc_ids"]) + assert produced == doc_ids + assert load_checkpoint(ckpt, shard_id=0)["build_stream"][str(tar)] == len(CORPUS) + + +# Batch transactions (#13), from #44. + + +class OutOfMemoryFirst(FakeEmbedder): """Fails its first batch, as a CUDA out-of-memory error would.""" def __init__(self): @@ -416,12 +656,11 @@ def encode(self, texts, **kwargs): def _build( tmp_path, tar, conn, paper_embedder, chunk_embedder, *, writer=False, rebuild=False, strict=True ): - """Run one build over one tar, flushing papers every 2 articles. Chunks are flushed only - at the tar boundary by the producer (shard 0, writing segments), and only after the tar - loop by the writer, which adds to the indices it saved before, if any, as a restart - does. The producer is asked to checkpoint after every article, which it must not do - before the tar boundary (#3); the writer isn't asked to checkpoint before the tar - boundary, so it commits only at its flushes and there.""" + """Run one build over one tar as shard 0's producer (writing segments) or as the writer, + which adds to the indices it saved before, if any, as a restart does. Every 2 articles, + and at the tar boundary, a batch's papers and chunks are embedded and published with + its rows. The producer is asked to checkpoint after every article, which it must not do + mid-batch (#3); the writer isn't asked to checkpoint before the tar boundary.""" sqlite_dir = tmp_path / "sqlite" seg_dir = tmp_path / "emb_segments" indices = tmp_path / "indices" @@ -481,40 +720,6 @@ def _row_counts(conn): return {t: conn.execute(f"SELECT count(*) FROM {t}").fetchone()[0] for t in tables} -@pytest.mark.parametrize("rebuild", [True, False], ids=["rebuild", "update"]) -def test_producer_checkpoint_counts_no_article_whose_segment_is_deleted(tmp_path, seg_dir, rebuild): - """#3: a mid-tar flush leaves its segment pending until the tar boundary, and - cleanup_pending() deletes it if the tar-boundary flush fails. A checkpoint that - counted those articles made the restart skip them: no vectors, ever. - - #13: so did the files table, on a restart without --rebuild, when each article was - committed on its own. The producer commits only at the tar boundary, before finalize(), - so the failed flush rolls back every article whose segment cleanup_pending() deletes.""" - tar = _corpus_tar(tmp_path) - doc_ids = {f"tar://{tar}!/{v['pmcid']}.nxml" for v in CORPUS.values()} - ckpt = tmp_path / "sqlite" / "build_checkpoint.json" - conn = _open_db(tmp_path, writer=False) - try: - papers = FakeEmbedder(DIM) - with pytest.raises(RuntimeError, match="out of memory"): - _build(tmp_path, tar, conn, papers, OutOfMemoryOnce()) - assert [len(batch) for batch in papers.calls] == [2, 1] # one mid-tar flush - assert _names(seg_dir) == [] # cleanup_pending() deleted the mid-tar segment too - assert load_checkpoint(ckpt, shard_id=0).get("build_stream", {}).get(str(tar), 0) == 0 - assert _row_counts(conn) == {"papers": 0, "chunks": 0, "files": 0} - - _build(tmp_path, tar, conn, FakeEmbedder(DIM), FakeEmbedder(DIM), rebuild=rebuild) - finally: - conn.close() - for kind, key in (("paper", "doc_ids"), ("chunk", "paper_doc_ids")): - produced = set() - for path in seg_dir.glob(f"{kind}_seg_*.npz"): - with np.load(path, allow_pickle=True) as z: - produced.update(str(d) for d in z[key]) - assert produced == doc_ids, kind - assert load_checkpoint(ckpt, shard_id=0)["build_stream"][str(tar)] == len(CORPUS) - - def test_writer_restart_indexes_every_article_after_a_failed_flush(tmp_path, monkeypatch): """#13: a failed embedding rolls back every row since the last commit. When each article was committed on its own, the rows stayed at in_index=0 with no vectors, and a @@ -525,7 +730,7 @@ def test_writer_restart_indexes_every_article_after_a_failed_flush(tmp_path, mon conn = _open_db(tmp_path, writer=True) try: with pytest.raises(RuntimeError, match="out of memory"): - _build(tmp_path, tar, conn, OutOfMemoryOnce(), FakeEmbedder(DIM), writer=True) + _build(tmp_path, tar, conn, OutOfMemoryFirst(), FakeEmbedder(DIM), writer=True) assert _row_counts(conn) == {"papers": 0, "chunks": 0, "files": 0} _build(tmp_path, tar, conn, FakeEmbedder(DIM), FakeEmbedder(DIM), writer=True) @@ -539,35 +744,42 @@ def test_writer_restart_indexes_every_article_after_a_failed_flush(tmp_path, mon conn.close() -def test_writer_restart_after_a_failure_past_the_save_adds_no_second_vector(tmp_path, monkeypatch): - """#13: a writer commits a batch's rows once they are embedded, before a save can write - their vectors. Rolled back after the save, by an error or SIGTERM before the commit, - the rows would come back on the restart under the same ids, and the HNSW paper index, - which can't remove vectors, would hold two of each.""" +@pytest.mark.parametrize( + "killed_in", ["_finish", "checkpoint_tar"], ids=["before the move", "after the move"] +) +def test_writer_restart_after_a_failure_past_the_commit_finishes_the_batch( + tmp_path, monkeypatch, killed_in +): + """#13: a writer commits a batch's rows, marked in_index, with the names of its staged + index files, then moves the files into place and checkpoints. Killed in between, by an + error or SIGTERM, the restart must finish that batch: its rows would otherwise have no + vectors, or be added again, and the HNSW paper index can't remove the extra vectors.""" monkeypatch.setattr(index_io, "_SAVE_MIN_SEC", 0) # no throttle - flush_marks = ingest_loop.db_flush_pending_marks + original = getattr(BatchPublication, killed_in) failed = [] - def fail_after_the_first_save(cur): + def fail_once(publication, *args): if not failed: failed.append(True) - raise RuntimeError("killed after the save") - return flush_marks(cur) + raise RuntimeError("killed after the commit") + return original(publication, *args) - monkeypatch.setattr(ingest_loop, "db_flush_pending_marks", fail_after_the_first_save) + monkeypatch.setattr(BatchPublication, killed_in, fail_once) tar = _corpus_tar(tmp_path) + saved = tmp_path / "indices" / "papers.faiss" conn = _open_db(tmp_path, writer=True) try: - with pytest.raises(RuntimeError, match="after the save"): + with pytest.raises(RuntimeError, match="after the commit"): _build(tmp_path, tar, conn, FakeEmbedder(DIM), FakeEmbedder(DIM), writer=True) - assert _saved_ids(faiss_load(tmp_path / "indices" / "papers.faiss")) == [1, 2] + moved = _saved_ids(faiss_load(saved)) if saved.exists() else [] + assert moved == ([] if killed_in == "_finish" else [1, 2]) _build(tmp_path, tar, conn, FakeEmbedder(DIM), FakeEmbedder(DIM), writer=True) ids = [r[0] for r in conn.execute("SELECT id FROM papers ORDER BY id")] finally: conn.close() assert ids == [1, 2, 3] - assert _saved_ids(faiss_load(tmp_path / "indices" / "papers.faiss")) == ids + assert _saved_ids(faiss_load(saved)) == ids class Peeking(FakeEmbedder): @@ -587,27 +799,14 @@ def encode(self, texts, **kwargs): return super().encode(texts, **kwargs) -@pytest.mark.parametrize( - "writer, seen", - [ - # Papers mid-tar after articles 2, 4 and 6, then the 7th paper and all the chunks - # at the tar boundary: all before the tar boundary's commit. - (False, [0, 0, 0, 0, 0]), - # Papers after articles 2, 4 and 6, each flush committing its batch once it is - # embedded, then the 7th paper and all the chunks after the tar boundary's commit. - # Only the first save runs (it is forced): the commits don't wait for a save. - (True, [0, 2, 4, 7, 7]), - ], - ids=["producer", "writer"], -) -def test_other_connections_see_no_article_before_its_batch_commits( - tmp_path, monkeypatch, writer, seen -): +@pytest.mark.parametrize("writer", [False, True], ids=["producer", "writer"]) +def test_other_connections_see_no_article_before_its_batch_commits(tmp_path, monkeypatch, writer): """#13: each article's SAVEPOINT was the outermost transaction, so its RELEASE committed it; the articles of a batch now share one transaction. Searches still read the database while the writer embeds a batch: its page cache is tiny here, so the batch outgrows it, as a large batch outgrows the default 2 MB, and must not spill to the file and lock them out. Producers may spill: no one else reads their shard databases.""" + # Only the first save runs (it is forced): the batches don't wait for a save to commit. monkeypatch.setattr(ingest_loop, "faiss_save", lambda index, path: False) # throttled tar = write_tar( tmp_path / "a.tar", @@ -630,7 +829,9 @@ def test_other_connections_see_no_article_before_its_batch_commits( _build(tmp_path, tar, conn, papers, chunks, writer=writer) finally: conn.close() - assert papers.seen + chunks.seen == seen + # Papers and chunks are embedded after articles 2, 4 and 6 and at the tar boundary, + # each time with only the batches before committed. + assert papers.seen == chunks.seen == [0, 2, 4, 6] def test_error_that_ends_the_batch_transaction_stops_the_build(tmp_path, monkeypatch): diff --git a/validate_build.sh b/validate_build.sh index d77bc9f..419e1be 100755 --- a/validate_build.sh +++ b/validate_build.sh @@ -37,7 +37,7 @@ while [[ $# -gt 0 ]]; do echo " workspace_path Path to workspace (default: /path/to/litkit/workspace)" echo "" echo "Checks performed:" - echo " 1. Segment files consumed (emb_segments/ empty)" + echo " 1. Finalized segment files consumed" echo " 2. FAISS indices exist and have reasonable size" echo " 3. SQLite papers and chunks fully indexed" exit 0 @@ -69,13 +69,17 @@ if [[ ! -d "$EMB_DIR" ]]; then echo " ⚠️ Segment directory not found: $EMB_DIR" echo " (This is OK for single-node builds)" else - SEGMENT_COUNT=$(find "$EMB_DIR" -name "*.npz" -type f 2>/dev/null | wc -l | tr -d ' ') - if [[ "$SEGMENT_COUNT" -eq 0 ]]; then - echo " ✅ All segments consumed (directory empty)" + discovery="$(dirname "${BASH_SOURCE[0]}")/src/litkit/segments/discovery.py" + SEGMENT_COUNT=$(python3 "$discovery" count "$EMB_DIR") + if [[ "$SEGMENT_COUNT" -eq 0 && "$(python3 "$discovery" resume "$EMB_DIR")" -ne 0 ]]; then + echo " ❌ Shard databases or committed transfers are awaiting consumption" + ERRORS=$((ERRORS + 1)) + elif [[ "$SEGMENT_COUNT" -eq 0 ]]; then + echo " ✅ No segments awaiting consumption" else echo " ❌ Found $SEGMENT_COUNT unconsumed segment files" echo " These should have been processed by the consumer:" - find "$EMB_DIR" -name "*.npz" -type f | head -5 + python3 "$discovery" sample "$EMB_DIR" ERRORS=$((ERRORS + 1)) fi fi diff --git a/vector_build_multi.sbatch b/vector_build_multi.sbatch index 45ed1be..47ea138 100644 --- a/vector_build_multi.sbatch +++ b/vector_build_multi.sbatch @@ -136,7 +136,7 @@ echo "Chunks index: flat (no IVF-PQ training)" echo "======================================" # Function to run producer in Charliecloud container -# If USE_LOCAL_STAGING=1, writes to node-local SSD then rsyncs to NFS +# If USE_LOCAL_STAGING=1, writes to node-local SSD then publishes the completed shard on NFS # # Key design principles: # - Race-safe: no shared global exports; everything passed via srun --export=... @@ -227,6 +227,23 @@ run_producer() { echo "[Producer ${PRODUCER_NODE_ID}] [staging] Using node-local SSD: ${PRODUCER_LOCAL_STAGE_HOST}" mkdir -p "${PRODUCER_LOCAL_STAGE_HOST}/sqlite" "${PRODUCER_LOCAL_STAGE_HOST}/emb_segments" rm -f "${PRODUCER_LOCAL_STAGE_HOST}/sqlite/faiss_writer.guard" 2>/dev/null || true + # Hold ownership from the shared checkpoint read through the final handoff. + exec 7>>"${LITKIT_WORKSPACE}/sqlite/producer_${PRODUCER_NODE_ID}.queue" + exec 8>>"${LITKIT_WORKSPACE}/sqlite/producer-admission.lock" + exec 9>>"${LITKIT_WORKSPACE}/sqlite/producer_${PRODUCER_NODE_ID}.lock" + flock -x 7 + flock -x 8 + flock -x 9 + flock -u 8 + handoff="${LITKIT_REPO}/src/litkit/db/handoff.py" + location=$(python3 "${handoff}" prepare "${PRODUCER_LOCAL_STAGE_HOST}" "${LITKIT_WORKSPACE}" "${PRODUCER_NODE_ID}") + if [[ "${location}" == "shared" ]]; then + echo "[Producer ${PRODUCER_NODE_ID}] Using NFS directly" + ACTUAL_USE_LOCAL_STAGING=0 + CONTAINER_WS="${CONTAINER_NFS_WS}" + EMBED_OUTDIR="${CONTAINER_WS}/emb_segments" + exec 9>&- 8>&- 7>&- + fi else echo "[Producer ${PRODUCER_NODE_ID}] [staging] Using NFS directly (no local staging)" fi @@ -254,6 +271,7 @@ run_producer() { --set-env="LD_LIBRARY_PATH=${CUDA_LIBA}:${CUDA_LIBB}" --set-env="PATH=/root/.local/share/uv/tools/litkit/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" --set-env="LITKIT_WORKSPACE=${CONTAINER_WS}" + --set-env="LITKIT_MERGED_DB=${CONTAINER_NFS_WS}/sqlite/litkit.sqlite3" --set-env="HF_HOME=/app/hf_cache" --set-env="TRANSFORMERS_USE_SAFE_TENSORS=1" --set-env="LITKIT_SQLITE_BUSY_TIMEOUT_MS=${LITKIT_SQLITE_BUSY_TIMEOUT_MS}" @@ -305,15 +323,11 @@ EOF if [[ "${rc}" -eq 0 ]]; then echo "[Producer ${PRODUCER_NODE_ID}] [staging] Syncing local outputs -> NFS (flat)" mkdir -p "${LITKIT_WORKSPACE}/sqlite" "${LITKIT_WORKSPACE}/emb_segments" - # Use absolute path to rsync for deterministic behavior across nodes - rsync_ver="$(/usr/bin/rsync --version 2>/dev/null | head -1 || true)" - echo "[Producer ${PRODUCER_NODE_ID}] [staging] rsync version: ${rsync_ver:-unknown}" - /usr/bin/rsync -a --delay-updates "${PRODUCER_LOCAL_STAGE_HOST}/sqlite/" "${LITKIT_WORKSPACE}/sqlite/" - /usr/bin/rsync -a --delay-updates "${PRODUCER_LOCAL_STAGE_HOST}/emb_segments/" "${LITKIT_WORKSPACE}/emb_segments/" + python3 "${handoff}" copy "${PRODUCER_LOCAL_STAGE_HOST}" "${LITKIT_WORKSPACE}" "${PRODUCER_NODE_ID}" echo "[Producer ${PRODUCER_NODE_ID}] [staging] Cleanup local staging dir" rm -rf "${PRODUCER_LOCAL_STAGE_HOST}" else - echo "[Producer ${PRODUCER_NODE_ID}] [staging] Not rsyncing (litkit failed). Preserving: ${PRODUCER_LOCAL_STAGE_HOST}" >&2 + echo "[Producer ${PRODUCER_NODE_ID}] [staging] Preserving failed producer output: ${PRODUCER_LOCAL_STAGE_HOST}" >&2 fi fi @@ -378,7 +392,7 @@ srun -N1 -n1 -w "$CONSUMER_NODE" \ --chunks-index flat ' -echo "=== Bootstrap Complete (empty indices created) ===" +echo "=== Bootstrap Complete (indices ready) ===" echo "" # Wait for filesystem sync diff --git a/vector_resume_consumer.sbatch b/vector_resume_consumer.sbatch index 152d406..dabe38a 100644 --- a/vector_resume_consumer.sbatch +++ b/vector_resume_consumer.sbatch @@ -20,9 +20,8 @@ # - validate_build.sh shows "unconsumed segment files" # # This script: -# 1. Creates fake producer completion markers -# 2. Runs the consumer in consume-only mode -# 3. Ingests all remaining .npz segment files +# 1. Reads the producer shard count and checks for remaining segments +# 2. Runs the consumer using the producers' completion markers # ============================================================================ set -euo pipefail @@ -63,22 +62,17 @@ SEG_DIR="${LITKIT_WORKSPACE}/emb_segments" # Debug mode for parallelism verification (set to 0 for quiet production runs) export LITKIT_DEBUG="${LITKIT_DEBUG:-1}" -# Count remaining segment files, including *.npz.ingesting ones that a stopped -# consumer claimed and kept because no save covered them yet (#2) -n_segs=$(find "$SEG_DIR" \( -name '*.npz' -o -name '*.npz.ingesting' \) 2>/dev/null | wc -l) -echo "[resume] Found $n_segs segment files to ingest" +# Include committed transfers that the consumer can finish publishing under lock. +discovery="${LITKIT_REPO}/src/litkit/segments/discovery.py" +n_shards=$(python3 "$discovery" resume "$SEG_DIR") -if [[ "$n_segs" -eq 0 ]]; then - echo "[resume] No segment files found. Nothing to do." +if [[ "$n_shards" -eq 0 ]]; then + echo "[resume] No shard databases, committed transfers or finalized segments to consume." echo "[resume] Run ./validate_build.sh to check status." exit 0 fi -# Detect how many shards were used (from segment filenames) -n_shards=$(find "$SEG_DIR" -name '*.npz' -exec basename {} \; 2>/dev/null \ - | sed -n 's/.*_sh\([0-9]\+\)_.*/\1/p' | sort -u | wc -l) -[[ "$n_shards" -ge 1 ]] || n_shards=2 -echo "[resume] Detected $n_shards shard(s) from segment filenames" +echo "[resume] Resuming $n_shards producer shard(s)" ### ----- CLEAN STALE WRITER GUARD (SLURM RESTART SAFE) ------------------------ # If a prior job crashed on a different node, the guard file may persist. @@ -89,21 +83,8 @@ echo "[resume] Detected $n_shards shard(s) from segment filenames" # WARNING: Do NOT add this mid-job or if running concurrent writers. rm -f "${LITKIT_WORKSPACE}/sqlite/faiss_writer.guard" 2>/dev/null || true -# Create fake completion markers so consume-only doesn't wait -echo "[resume] Creating producer completion markers..." -for ((i=0; i "$marker" - echo "[resume] Created $marker" - else - echo "[resume] Marker already exists: $marker" - fi -done - echo "" echo "=== Resume Consumer Starting ===" -echo "Segments to ingest: $n_segs" echo "Shards: $n_shards" echo "Workspace: $LITKIT_WORKSPACE" echo "================================"