From d66f3f49fad09e02a19ac459540b07104720f50f Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 16:11:37 -0700 Subject: [PATCH 01/31] Commit tar members and publish their embeddings in recoverable batches Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 1 + src/litkit/build/ingest_loop.py | 916 ++++++++-------------- src/litkit/build/publication.py | 121 +++ src/litkit/cli.py | 22 +- src/litkit/segments/constants.py | 1 + src/litkit/segments/ingest.py | 26 +- src/litkit/segments/metadata.py | 36 +- src/litkit/segments/writer.py | 214 ++--- tests/integration/test_batch_resume.py | 253 ++++++ tests/integration/test_build_and_query.py | 72 ++ tests/test_segments.py | 44 +- 11 files changed, 931 insertions(+), 775 deletions(-) create mode 100644 src/litkit/build/publication.py create mode 100644 tests/integration/test_batch_resume.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c4d398..9d7f48d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ internal versions are summarized under 0.3.33. ## [Unreleased] ### Fixed +- Tar builds commit articles in batches. Interrupted producers resume with complete paper and chunk segments, and consumers ignore unfinished files. For a producer already interrupted on an older release, 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) diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index 0d8be76..d6a9dad 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -10,12 +10,12 @@ import os import sys import time +from contextlib import 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 +35,7 @@ make_id_selector, safe_remove_ids, add_with_ids_dedup, + faiss_load, faiss_save, faiss_save_force, ) @@ -44,10 +45,7 @@ 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.build.helpers import ( pack_body, dedupe_papers_with_doc_ids, @@ -82,9 +80,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 +108,21 @@ def iter_tar_articles( pass +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 isinstance(index, faiss.IndexIDMap2): + index = faiss.IndexIDMap2(index) + force = not index.ntotal or bool(removed) + if removed: + safe_remove_ids(index, make_id_selector(sorted(removed))) + added, ids_added = add_with_ids_dedup(index, ids, vectors, skip_dedup=rebuild) + 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], @@ -154,9 +167,9 @@ def process_tar_files( parse_workers: int, ) -> 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,17 +201,30 @@ 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. """ cur = conn.cursor() - - # 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") + 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 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) + ckpt_stream = publication.checkpoint.setdefault("build_stream", {}) + # Buffers for batch processing paper_ids_buf: list[int] = [] paper_texts_buf: list[str] = [] @@ -207,57 +233,150 @@ 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) - + + replaced_papers: set[int] = set() + replaced_chunks: 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: + conn.commit() + 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 + ) + 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, + ) + 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: + + def stage_segments(paper_dir, chunk_dir): + return ( + paper_seg_writer.stage(paper_dir, doc_ids=doc_ids, vecs=xp), + chunk_seg_writer.stage(chunk_dir, paper_doc_ids=parents, ords=ords, vecs=xc), + ) + + 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: + + def stage_indexes(paper_dir, chunk_dir): + nonlocal paper_index, chunk_index, papers_added, chunks_added + paper_index, paper_file, papers_added = _stage_index( + cur, + "papers", + paper_index, + paper_dir / paper_index_path.name, + pids, + xp, + replaced_papers, + rebuild=rebuild, + ) + 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): + publication.publish(tar, members, stage_indexes) + else: + conn.commit() + 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() + for tpath in tar_paths: # 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) @@ -265,10 +384,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 @@ -276,7 +395,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 = ( @@ -288,585 +407,200 @@ 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), - ) - - 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 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 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 + # ═══════════════════════════════════════════════════════════════════ + + # 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 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 + else: + canon_doc_id = str(f) + cur.execute( + "UPDATE papers SET doc_id = ? WHERE id = ?", + (canon_doc_id, pid) + ) else: + # New paper: use current path as canonical doc_id canon_doc_id = str(f) 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: + 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: + 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), + ) + 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 seen_this_path: + replaced_papers.add(pid) + replaced_chunks.update(old_ids) + + except Exception as e: + _eprint(f"[ingest] ERROR tar://{tpath}!/{m.name}: {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") - except Exception: - pass - - # 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) - conn.commit() - papers_added_total += len(u_ids) - - 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 - 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, - ) - 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, - ) - 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 - ) - t_seg = time.time() - t_seg_start - - t_db_start = time.time() - conn.commit() - t_db = time.time() - t_db_start - - chunks_added_total += len(u_ids) - - 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 - - # --- 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 db={t_db:.2f}s | " - f"chunks/doc={avg_cpd:.1f}" - ) - # 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}") + + # 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 - - elif faiss_writer: - # Writer mode: embed and update FAISS + + # Mark-and-skip: log failure and continue 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, - ) - 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}") - 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 segment flush - 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 + 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 (rows now durable) - 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 - 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 - ) - 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() - + # 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..b61c414 --- /dev/null +++ b/src/litkit/build/publication.py @@ -0,0 +1,121 @@ +"""Publish a tar batch across SQLite and the filesystem, including after a restart.""" + +from __future__ import annotations + +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.segments.checkpoint import load_checkpoint, save_checkpoint +from litkit.segments.writer import finalized_name + + +class BatchPublication: + """A single writer owns each database and its private staging directories.""" + + 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), Path(chunk_dir)) + self.prefix = f".litkit-batch-{'writer' if shard_id is None else shard_id}-" + self.checkpoint = load_checkpoint(ckpt_path, shard_id=shard_id) + + def checkpoint_tar(self, tar: str, members: int) -> None: + self.checkpoint.setdefault("build_stream", {})[tar] = members + save_checkpoint(self.checkpoint, self.ckpt_path, self.ckpt_lock, shard_id=self.shard_id) + + def _stage_name(self, token: str) -> str: + if UUID(hex=token).hex != token: + raise ValueError("Invalid batch directory in SQLite") + return self.prefix + token + + def publish( + self, + tar: str, + members: int, + write: Callable[[Path, Path], tuple[Path | None, Path | None]], + ) -> None: + """Keep staged files on a post-commit error so recovery can finish publishing.""" + token = uuid4().hex + stage = self._stage_name(token) + directories = [root / stage for root in dict.fromkeys(self.outputs)] + try: + for directory in directories: + directory.mkdir(parents=True) + maybe_fsync_dir(directory) + paper, chunk = write(*(root / stage for root in self.outputs)) + for staged in (paper, chunk): + if staged is not None: + maybe_fsync_dir(staged) + self.conn.execute( + "CREATE TABLE IF NOT EXISTS ingest_publication (" + "singleton INTEGER PRIMARY KEY CHECK(singleton=1), tar TEXT, members INTEGER, " + "token TEXT, paper TEXT, chunk TEXT)" + ) + self.conn.execute( + "INSERT INTO ingest_publication VALUES (1, ?, ?, ?, ?, ?)", + (tar, members, token, paper.name if paper else None, chunk.name if chunk else None), + ) + self.conn.commit() + except BaseException: + self.conn.rollback() + # A signal can arrive just after SQLite made the commit durable. + if self._record() is None: + for directory in directories: + shutil.rmtree(directory, ignore_errors=True) + raise + self._finish( + tar, members, token, paper.name if paper else None, chunk.name if chunk else None + ) + + def _record(self): + if not self.conn.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='ingest_publication'" + ).fetchone(): + return None + return self.conn.execute( + "SELECT tar, members, token, paper, chunk FROM ingest_publication WHERE singleton=1" + ).fetchone() + + def _finish(self, tar, members, token, paper, chunk): + stage = self._stage_name(token) + for root, name in zip(self.outputs, (paper, chunk), strict=True): + directory = root / stage + if not directory.is_dir(): + raise FileNotFoundError( + f"Cannot resume batch: missing staging directory {directory}" + ) + if name is None: + continue + if name != Path(name).name or name in (".", ".."): + raise ValueError("Invalid staged filename in SQLite") + pending = directory / name + target = root / (finalized_name(pending) if name.endswith("_pending.npz") else name) + # In this committed, private directory, only the atomic rename removes + # a staged file. A consumer may already have claimed or deleted its target. + if pending.exists(): + pending.replace(target) + maybe_fsync_dir(target) + maybe_fsync_dir(pending) + self.checkpoint_tar(tar, members) + self.conn.execute("DELETE FROM ingest_publication WHERE singleton=1") + self.conn.commit() + for root in dict.fromkeys(self.outputs): + (root / stage).rmdir() + + def recover(self) -> bool: + """Complete a committed batch, then discard this writer's uncommitted staging.""" + record = self._record() + if record: + self._finish(*record) + for root in dict.fromkeys(self.outputs): + for directory in root.glob(self.prefix + "?" * 32): + token = directory.name.removeprefix(self.prefix) + if all(ch in "0123456789abcdef" for ch in token) and directory.is_dir(): + shutil.rmtree(directory) + return record is not None diff --git a/src/litkit/cli.py b/src/litkit/cli.py index 3e75200..ac5dad2 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1038,6 +1038,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. @@ -1154,6 +1163,9 @@ 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: + _recover_writer_batch(conn) + if args.init_indices_only: # Build a minimal config for the module function cfg = BuildConfig( @@ -1257,9 +1269,12 @@ def build_or_update_indices(args): CKPT_PATH.unlink() # wipe tables (DELETE in transaction, VACUUM outside) - cur.executescript("DELETE FROM chunks; DELETE FROM papers; DELETE FROM files;") - conn.commit() - + with conn: + conn.execute("BEGIN") + for table in ("chunks", "papers", "files"): + cur.execute(f"DELETE FROM {table}") + cur.execute("DROP TABLE IF EXISTS ingest_publication") + # VACUUM must run outside any transaction (autocommit mode) # Without this, sqlite3.OperationalError: cannot VACUUM from within a transaction old_isolation = conn.isolation_level @@ -2200,6 +2215,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/segments/constants.py b/src/litkit/segments/constants.py index 03ccd7c..783e5e0 100644 --- a/src/litkit/segments/constants.py +++ b/src/litkit/segments/constants.py @@ -29,6 +29,7 @@ PAPER_SEGMENT_PREFIX = "paper_seg" CHUNK_SEGMENT_PREFIX = "chunk_seg" SEGMENT_EXTENSION = ".npz" +PENDING_SUFFIX = "_pending" # Build metadata file BUILD_META_FILENAME = "build_meta.json" diff --git a/src/litkit/segments/ingest.py b/src/litkit/segments/ingest.py index eae3adc..4b61bdd 100644 --- a/src/litkit/segments/ingest.py +++ b/src/litkit/segments/ingest.py @@ -22,6 +22,7 @@ import numpy as np from litkit.db.queries import preload_paper_id_map, preload_chunk_id_map +from litkit.segments.metadata import iter_segment_files from litkit.index.dedup import add_with_ids_dedup from litkit.index.io import faiss_save, faiss_save_force from litkit.index.ids import make_id_selector, safe_remove_ids @@ -59,30 +60,7 @@ def _glob_segment_files(outdir: Path, kind: str) -> list[Path]: Returns: 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")) - - return sorted(cand) + return sorted(iter_segment_files(outdir, kind)) def ingest_paper_segments( diff --git a/src/litkit/segments/metadata.py b/src/litkit/segments/metadata.py index a5f95f0..d3663cd 100644 --- a/src/litkit/segments/metadata.py +++ b/src/litkit/segments/metadata.py @@ -5,10 +5,12 @@ import json import sys +from collections.abc import Iterator from pathlib import Path from litkit.segments.constants import ( BUILD_META_FILENAME, + PENDING_SUFFIX, PAPER_SEGMENT_PREFIX, CHUNK_SEGMENT_PREFIX, SEGMENT_EXTENSION, @@ -24,28 +26,20 @@ def _eprint(msg: str = "", *, end: str = "\n") -> None: pass +def iter_segment_files(seg_dir: Path, kind: str) -> Iterator[Path]: + """Yield finalized segments and interrupted consumer claims, including legacy names.""" + prefix = PAPER_SEGMENT_PREFIX if kind == "papers" else CHUNK_SEGMENT_PREFIX + for pattern in (f"{prefix}_*", f"{kind}_*", f"{kind}.seg.*"): + for claim in ("", ".ingesting"): + suffix = SEGMENT_EXTENSION + claim + for path in seg_dir.glob(pattern + suffix): + if not path.name.endswith(PENDING_SUFFIX + suffix): + yield path + + 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 paper or chunk segment files exist - """ - seg_dir = Path(seg_dir) - if not seg_dir.exists(): - return False - - # Check for paper segments - if list(seg_dir.glob(f"{PAPER_SEGMENT_PREFIX}_*{SEGMENT_EXTENSION}")): - return True - - # Check for chunk segments - if list(seg_dir.glob(f"{CHUNK_SEGMENT_PREFIX}_*{SEGMENT_EXTENSION}")): - 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 write_build_meta( diff --git a/src/litkit/segments/writer.py b/src/litkit/segments/writer.py index e8693c3..f2070c0 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 @@ -13,14 +13,14 @@ import os import sys import uuid -from contextlib import suppress -from dataclasses import dataclass, field +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 +28,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) @@ -45,11 +39,32 @@ def _eprint(msg: str = "", *, end: str = "\n") -> None: def _write_segment(path: Path, **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. + 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: list[Path]) -> int: + count = len(paths) + while paths: + path = paths[-1] + path.replace(path.with_name(finalized_name(path))) + paths.pop() + return count def cleanup_orphan_pending_files(outdir: Path, kinds: list[str] | None = None) -> int: @@ -104,7 +119,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. @@ -185,11 +200,13 @@ 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): + for doc_id, vec in zip(doc_ids, vecs, strict=True): self._doc_ids.append(doc_id) self._embeddings.append(vec.reshape(1, -1)) @@ -206,73 +223,35 @@ 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") + path = self.stage(self.outdir, doc_ids=self._doc_ids, vecs=np.vstack(self._embeddings)) + 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) -> 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 - + seg_id = f"{self.shard_id}_{self._segment_counter}_{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), + 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 +303,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. @@ -408,11 +387,13 @@ 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): + for doc_id, ord_, vec in zip(paper_doc_ids, ords, vecs, strict=True): self._doc_ids.append(doc_id) self._ords.append(ord_) self._embeddings.append(vec.reshape(1, -1)) @@ -430,74 +411,37 @@ 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"), - ) - - n = len(self._doc_ids) - _eprint(f"[segment] Wrote {n} chunk embeddings to {filename} (pending)") - - # Track pending path for finalization + path = self.stage(self.outdir, paper_doc_ids=self._doc_ids, ords=self._ords, vecs=np.vstack(self._embeddings)) 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) -> 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 + seg_id = f"{self.shard_id}_{self._segment_counter}_{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), + 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/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py new file mode 100644 index 0000000..db5fdef --- /dev/null +++ b/tests/integration/test_batch_resume.py @@ -0,0 +1,253 @@ +"""Interrupted tar batches, from SQLite savepoints to the consumer's FAISS IDs.""" + +import sqlite3 +from contextlib import closing +from functools import partial +from pathlib import Path + +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 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.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 + + +class Build: + def __init__(self, root, tar, *, producer=True): + self.root = root + self.tar = tar + self.producer = producer + self.shard = 0 if producer else None + self.segments = root / "segments" + self.db = shard_db_path(root, 0) 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, **overrides): + def open_index(path): + if self.producer: + return None + return faiss_load(path) if path.exists() else flat_ip_index(32) + + conn = init_shard_db(self.db, 0) if self.producer else init_db(self.db) + with closing(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) if self.producer else None, + chunk_seg_writer=ChunkSegmentWriter(self.segments) 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]) + + +class InjectedFailure(Exception): + pass + + +@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") + 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)]: + assert sorted(faiss.vector_to_array(faiss_load(path).id_map)) == list(range(1, n + 1)) + + +@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) diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index e4fd4d5..5560c84 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -568,3 +568,75 @@ def test_rebuild_without_yes_refuses_noninteractively(isolated_env, corpus_dir): ) assert proc.returncode == 2 assert "Refusing to proceed non-interactively" in proc.stderr + + +@pytest.mark.parametrize("interruption", ["before-commit", "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): + 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() + + _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 + index = faiss_load(ws / "indices" / f"{table}.faiss") + assert sorted(faiss.vector_to_array(index.id_map)) == ids diff --git a/tests/test_segments.py b/tests/test_segments.py index 02fff79..25d574b 100644 --- a/tests/test_segments.py +++ b/tests/test_segments.py @@ -107,6 +107,38 @@ 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()) == [] + + def _write_one(kind, seg_dir, vec): if kind == "papers": w = SegmentWriter(seg_dir, dtype="fp32") @@ -117,7 +149,6 @@ def _write_one(kind, seg_dir, vec): return w -@pytest.mark.xfail(strict=True, raises=AssertionError, reason="#4: glob matches pending") @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 @@ -133,6 +164,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) + + # ------------------------------------------------------------------ checkpoints From 6eed0e95df17dc2cc2d38da9d4dbf231e56ceb3a Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 16:19:12 -0700 Subject: [PATCH 02/31] Isolate producer recovery and protect committed work from overlapping starts Signed-off-by: Bill Hlavacek --- src/litkit/build/ingest_loop.py | 65 ++++++++---- src/litkit/build/publication.py | 120 ++++++++++++++++------ src/litkit/cli.py | 8 +- tests/integration/test_batch_resume.py | 51 +++++++++ tests/integration/test_build_and_query.py | 40 +++++++- 5 files changed, 230 insertions(+), 54 deletions(-) diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index d6a9dad..dd02109 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -110,6 +110,8 @@ def iter_tar_articles( 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) @@ -210,21 +212,6 @@ def process_tar_files( 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") - 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 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) - ckpt_stream = publication.checkpoint.setdefault("build_stream", {}) - # Buffers for batch processing paper_ids_buf: list[int] = [] paper_texts_buf: list[str] = [] @@ -242,7 +229,7 @@ def process_tar_files( def flush_batch(tar: str, members: int) -> None: nonlocal paper_index, chunk_index, papers_added_total, chunks_added_total - if not paper_ids_buf: + if not (paper_ids_buf or chunk_ids_buf): conn.commit() publication.checkpoint_tar(tar, members) return @@ -269,7 +256,7 @@ def flush_batch(tar: str, members: int) -> None: 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)})", @@ -282,7 +269,7 @@ def flush_batch(tar: str, members: int) -> None: def stage_segments(paper_dir, chunk_dir): return ( - paper_seg_writer.stage(paper_dir, doc_ids=doc_ids, vecs=xp), + paper_seg_writer.stage(paper_dir, doc_ids=doc_ids, vecs=xp) if pids else None, chunk_seg_writer.stage(chunk_dir, paper_doc_ids=parents, ords=ords, vecs=xc), ) @@ -337,7 +324,7 @@ def stage_indexes(paper_dir, chunk_dir): replaced_papers.clear() replaced_chunks.clear() - for tpath in tar_paths: + def process_tar(tpath: Path) -> None: # 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 @@ -524,9 +511,19 @@ def _render(force: bool = False): 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) + # 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 and not seen_this_path: + reuse_embedding = rebuild or cur.execute( + "SELECT text FROM chunks WHERE paper_id=? AND ord=-1 ORDER BY id LIMIT 1", + (pid,), + ).fetchone() == (ta_ab,) + if not reuse_embedding: + 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 [] @@ -601,6 +598,30 @@ def _render(force: bool = False): _render(force=True) _progress_newline(sys.stderr) + # Different shards can run in parallel. Two starts of the same shard must + # serialize recovery, scanning, and publication against the same checkpoint. + owner_lock = ( + FileLock(sqlite_dir / f"producer_{ckpt_shard_id}.lock") if embed_producer else nullcontext() + ) + with owner_lock: + 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 or faiss_writer: + with FileLock(faiss_lock) if faiss_writer else nullcontext(): + if publication.recover(initialize=True) and faiss_writer: + paper_index = faiss_load(paper_index_path) + chunk_index = faiss_load(chunk_index_path) + ckpt_stream = publication.checkpoint.setdefault("build_stream", {}) + + for tpath in tar_paths: + process_tar(tpath) + # 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 index b61c414..0622f12 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -5,14 +5,52 @@ import shutil import sqlite3 from collections.abc import Callable +from contextlib import closing from pathlib import Path from uuid import UUID, uuid4 from litkit.build.helpers import maybe_fsync_dir +from litkit.db.sharding import list_shard_dbs from litkit.segments.checkpoint import load_checkpoint, save_checkpoint from litkit.segments.writer import finalized_name +def _has_journal(conn: sqlite3.Connection) -> bool: + return ( + conn.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='ingest_publication'" + ).fetchone() + is not None + ) + + +def has_unpublished_batch(conn: sqlite3.Connection) -> bool: + return ( + _has_journal(conn) + and conn.execute("SELECT 1 FROM ingest_publication WHERE tar IS NOT NULL").fetchone() + is not None + ) + + +def unpublished_shards(sqlite_dir: Path) -> list[Path]: + """Find committed producer work whose segment publication has not finished.""" + pending = [] + for shard in list_shard_dbs(sqlite_dir): + uri = shard.resolve().as_uri() + "?mode=ro" + with closing(sqlite3.connect(uri, uri=True)) as conn: + if has_unpublished_batch(conn): + pending.append(shard) + return pending + + +def clear_publication(conn: sqlite3.Connection) -> None: + """Retain the workspace identity so a reset can reclaim its staging files.""" + if _has_journal(conn): + conn.execute( + "UPDATE ingest_publication SET tar=NULL, members=NULL, token=NULL, paper=NULL, chunk=NULL" + ) + + class BatchPublication: """A single writer owns each database and its private staging directories.""" @@ -22,13 +60,19 @@ def __init__(self, conn, ckpt_path, ckpt_lock, shard_id, paper_dir, chunk_dir): self.ckpt_lock = ckpt_lock self.shard_id = shard_id self.outputs = (Path(paper_dir), Path(chunk_dir)) - self.prefix = f".litkit-batch-{'writer' if shard_id is None else shard_id}-" + self.owner: str | None = None self.checkpoint = load_checkpoint(ckpt_path, shard_id=shard_id) def checkpoint_tar(self, tar: str, members: int) -> None: self.checkpoint.setdefault("build_stream", {})[tar] = members save_checkpoint(self.checkpoint, self.ckpt_path, self.ckpt_lock, shard_id=self.shard_id) + @property + def prefix(self) -> str: + if self.owner is None or UUID(hex=self.owner).hex != self.owner: + raise ValueError("Invalid publication owner in SQLite") + return f".litkit-batch-{self.owner}-" + def _stage_name(self, token: str) -> str: if UUID(hex=token).hex != token: raise ValueError("Invalid batch directory in SQLite") @@ -52,35 +96,29 @@ def publish( for staged in (paper, chunk): if staged is not None: maybe_fsync_dir(staged) - self.conn.execute( - "CREATE TABLE IF NOT EXISTS ingest_publication (" - "singleton INTEGER PRIMARY KEY CHECK(singleton=1), tar TEXT, members INTEGER, " - "token TEXT, paper TEXT, chunk TEXT)" + record = ( + tar, + members, + token, + paper.name if paper else None, + chunk.name if chunk else None, ) - self.conn.execute( - "INSERT INTO ingest_publication VALUES (1, ?, ?, ?, ?, ?)", - (tar, members, token, paper.name if paper else None, chunk.name if chunk else None), + updated = self.conn.execute( + "UPDATE ingest_publication SET tar=?, members=?, token=?, paper=?, chunk=? " + "WHERE owner=? AND tar IS NULL", + (*record, self.owner), ) + if updated.rowcount != 1: + raise RuntimeError("Another batch is awaiting publication") self.conn.commit() except BaseException: self.conn.rollback() # A signal can arrive just after SQLite made the commit durable. - if self._record() is None: + if not has_unpublished_batch(self.conn): for directory in directories: shutil.rmtree(directory, ignore_errors=True) raise - self._finish( - tar, members, token, paper.name if paper else None, chunk.name if chunk else None - ) - - def _record(self): - if not self.conn.execute( - "SELECT 1 FROM sqlite_master WHERE type='table' AND name='ingest_publication'" - ).fetchone(): - return None - return self.conn.execute( - "SELECT tar, members, token, paper, chunk FROM ingest_publication WHERE singleton=1" - ).fetchone() + self._finish(*record) def _finish(self, tar, members, token, paper, chunk): stage = self._stage_name(token) @@ -103,19 +141,41 @@ def _finish(self, tar, members, token, paper, chunk): maybe_fsync_dir(target) maybe_fsync_dir(pending) self.checkpoint_tar(tar, members) - self.conn.execute("DELETE FROM ingest_publication WHERE singleton=1") + clear_publication(self.conn) self.conn.commit() for root in dict.fromkeys(self.outputs): (root / stage).rmdir() - def recover(self) -> bool: - """Complete a committed batch, then discard this writer's uncommitted staging.""" - record = self._record() - if record: - self._finish(*record) + def recover(self, *, initialize: bool = False) -> bool: + """Finish any committed batch and reclaim only this database's private staging.""" + if initialize and not _has_journal(self.conn): + self.conn.execute( + "CREATE TABLE ingest_publication (singleton INTEGER PRIMARY KEY CHECK(singleton=1), " + "owner TEXT NOT NULL, tar TEXT, members INTEGER, token TEXT, paper TEXT, chunk TEXT)" + ) + if not _has_journal(self.conn): + return False + row = self.conn.execute( + "SELECT owner, tar, members, token, paper, chunk FROM ingest_publication WHERE singleton=1" + ).fetchone() + if row is None: + if not initialize: + return False + self.owner = uuid4().hex + self.conn.execute( + "INSERT INTO ingest_publication(singleton, owner) VALUES (1, ?)", (self.owner,) + ) + self.conn.commit() + return False + self.owner, tar, members, token, paper, chunk = row + if tar is not None: + self._finish(tar, members, token, paper, chunk) + # Another workspace can use the same --embed-outdir and shard number. + # The SQLite identity survives relocation and never names that workspace's files. + prefix = self.prefix for root in dict.fromkeys(self.outputs): - for directory in root.glob(self.prefix + "?" * 32): - token = directory.name.removeprefix(self.prefix) + for directory in root.glob(prefix + "?" * 32): + token = directory.name.removeprefix(prefix) if all(ch in "0123456789abcdef" for ch in token) and directory.is_dir(): shutil.rmtree(directory) - return record is not None + return tar is not None diff --git a/src/litkit/cli.py b/src/litkit/cli.py index ac5dad2..da4b0eb 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1228,6 +1228,11 @@ 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.build.publication import unpublished_shards + + for shard in unpublished_shards(SQLITE_DIR): + conflict_reasons.append(f"Producer shard {shard.name} has a committed batch awaiting publication") + # 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) @@ -1273,7 +1278,8 @@ def build_or_update_indices(args): conn.execute("BEGIN") for table in ("chunks", "papers", "files"): cur.execute(f"DELETE FROM {table}") - cur.execute("DROP TABLE IF EXISTS ingest_publication") + from litkit.build.publication import clear_publication + clear_publication(conn) # VACUUM must run outside any transaction (autocommit mode) # Without this, sqlite3.OperationalError: cannot VACUUM from within a transaction diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index db5fdef..5a388f1 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -1,6 +1,8 @@ """Interrupted tar batches, from SQLite savepoints to the consumer's FAISS IDs.""" import sqlite3 +from concurrent.futures import ThreadPoolExecutor +from threading import Event from contextlib import closing from functools import partial from pathlib import Path @@ -197,6 +199,55 @@ def fail_checkpoint(*args, **kwargs): assert sorted(faiss.vector_to_array(faiss_load(path).id_map)) == list(range(1, n + 1)) +def test_two_starts_of_the_same_shard_serialize_publication(tmp_path, archive, monkeypatch): + build = Build(tmp_path / "producer", archive) + staged = Event() + second_attempt = Event() + write = SegmentWriter.stage + + def wait_for_second_start(writer, *args, **kwargs): + path = write(writer, *args, **kwargs) + staged.set() + assert second_attempt.wait(10), "second producer did not reach the shard lock" + return path + + class SecondLock(FileLock): + def __enter__(self): + if self.path.name == "producer_0.lock": + second_attempt.set() + return super().__enter__() + + monkeypatch.setattr(SegmentWriter, "stage", wait_for_second_start) + with ThreadPoolExecutor(max_workers=2) 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 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_new_workspace_cannot_discard_another_producers_committed_segments( + tmp_path, archive, monkeypatch +): + first = Build(tmp_path / "first", archive) + second = Build(tmp_path / "second", archive) + 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 diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index 5560c84..9d2b13d 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -570,7 +570,7 @@ def test_rebuild_without_yes_refuses_noninteractively(isolated_env, corpus_dir): assert "Refusing to proceed non-interactively" in proc.stderr -@pytest.mark.parametrize("interruption", ["before-commit", "after-commit"]) +@pytest.mark.parametrize("interruption", ["before-commit", "before-publish", "after-commit"]) def test_two_producers_resume_after_process_exit( isolated_env, corpus_dir, monkeypatch, interruption ): @@ -608,6 +608,8 @@ def stop_after_write(self, *args, **kwargs): 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) @@ -629,6 +631,21 @@ def stop_after_rename(self, target): assert load_checkpoint(checkpoint, 0) == {} assert not (seg_dir / "producer_0.done").exists() + 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 + _ok(litkit(ws, *args, "--shard-id", "1")) _ok(litkit(ws, *args, "--shard-id", "0")) assert not list(seg_dir.glob(".litkit-batch-*")) @@ -640,3 +657,24 @@ def stop_after_rename(self, target): assert len(ids) == 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 From 484ff856cef98c5764c1fdc38b32bb0d851b4922 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 16:28:15 -0700 Subject: [PATCH 03/31] Reserve each staging directory and share consumer discovery with cluster scripts Signed-off-by: Bill Hlavacek --- src/litkit/build/consume.py | 13 ++ src/litkit/build/ingest_loop.py | 6 +- src/litkit/build/publication.py | 217 ++++++++++++---------- src/litkit/cli.py | 15 +- src/litkit/segments/constants.py | 13 +- src/litkit/segments/discovery.py | 73 ++++++++ src/litkit/segments/ingest.py | 2 +- src/litkit/segments/metadata.py | 21 +-- src/litkit/segments/writer.py | 66 +++---- tests/integration/test_batch_resume.py | 30 ++- tests/integration/test_build_and_query.py | 12 ++ tests/test_segments.py | 54 ++++++ validate_build.sh | 9 +- vector_resume_consumer.sbatch | 27 +-- 14 files changed, 368 insertions(+), 190 deletions(-) create mode 100644 src/litkit/segments/discovery.py diff --git a/src/litkit/build/consume.py b/src/litkit/build/consume.py index 28d76b7..ccf7ec5 100644 --- a/src/litkit/build/consume.py +++ b/src/litkit/build/consume.py @@ -96,6 +96,19 @@ def default_progress(complete: int, total: int) -> None: eprint("[consumer] All producers have completed") + # An old completion marker can outlive an interrupted producer. Merging + # and deleting that shard would discard its record of unpublished files. + from litkit.build.publication import unpublished_shards + + sqlite_dir = Path(conn.execute("PRAGMA database_list").fetchone()[2]).parent + pending = unpublished_shards(sqlite_dir) + if pending: + names = ", ".join(shard.name for shard in pending) + raise RuntimeError( + f"Cannot consume: {names} has a committed batch awaiting publication. " + "Resume the interrupted producer in its original workspace and segment directory." + ) + # Merge shard databases FIRST (before segment ingestion) # This populates the main DB so doc_id → paper_id resolution works eprint("[consumer] Merging shard databases...") diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index dd02109..c6e12f8 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -230,6 +230,8 @@ def process_tar_files( 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() conn.commit() publication.checkpoint_tar(tar, members) return @@ -453,6 +455,8 @@ def _render(force: bool = False): 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") @@ -614,7 +618,7 @@ def _render(force: bool = False): ) if embed_producer or faiss_writer: with FileLock(faiss_lock) if faiss_writer else nullcontext(): - if publication.recover(initialize=True) and faiss_writer: + if publication.recover() and faiss_writer: paper_index = faiss_load(paper_index_path) chunk_index = faiss_load(chunk_index_path) ckpt_stream = publication.checkpoint.setdefault("build_stream", {}) diff --git a/src/litkit/build/publication.py b/src/litkit/build/publication.py index 0622f12..92b40e9 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -7,6 +7,7 @@ from collections.abc import Callable from contextlib import closing from pathlib import Path +from typing import NamedTuple from uuid import UUID, uuid4 from litkit.build.helpers import maybe_fsync_dir @@ -15,44 +16,53 @@ from litkit.segments.writer import finalized_name -def _has_journal(conn: sqlite3.Connection) -> bool: - return ( - conn.execute( - "SELECT 1 FROM sqlite_master WHERE type='table' AND name='ingest_publication'" - ).fetchone() - is not None - ) +class _Publication(NamedTuple): + token: str + source_db: str + tar: str | None + members: int | None + paper: str | None + chunk: str | None -def has_unpublished_batch(conn: sqlite3.Connection) -> bool: - return ( - _has_journal(conn) - and conn.execute("SELECT 1 FROM ingest_publication WHERE tar IS NOT NULL").fetchone() - is not None - ) +def _record(conn: sqlite3.Connection) -> _Publication | 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, tar, members, paper, chunk FROM ingest_publication" + ).fetchone() + return _Publication(*row) if row else None def unpublished_shards(sqlite_dir: Path) -> list[Path]: - """Find committed producer work whose segment publication has not finished.""" + """Find producers that committed rows and still have files to publish.""" pending = [] for shard in list_shard_dbs(sqlite_dir): - uri = shard.resolve().as_uri() + "?mode=ro" - with closing(sqlite3.connect(uri, uri=True)) as conn: - if has_unpublished_batch(conn): - pending.append(shard) + uri = shard.resolve().as_uri() + try: + with closing(sqlite3.connect(uri + "?mode=ro", uri=True)) as conn: + row = _record(conn) + except sqlite3.OperationalError as error: + if error.sqlite_errorcode & 0xFF != sqlite3.SQLITE_READONLY: + raise + # Inspecting a hot rollback journal requires SQLite to undo uncommitted pages. + with closing(sqlite3.connect(uri + "?mode=rw", uri=True)) as conn: + row = _record(conn) + if row and row.tar is not None: + pending.append(shard) return pending -def clear_publication(conn: sqlite3.Connection) -> None: - """Retain the workspace identity so a reset can reclaim its staging files.""" - if _has_journal(conn): - conn.execute( - "UPDATE ingest_publication SET tar=NULL, members=NULL, token=NULL, paper=NULL, chunk=NULL" - ) +def reset_publication(conn: sqlite3.Connection) -> None: + """Invalidate the active batch in the same transaction as an explicit rebuild.""" + if _record(conn): + conn.execute("UPDATE ingest_publication SET tar=NULL WHERE singleton=1") class BatchPublication: - """A single writer owns each database and its private staging directories.""" + """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 @@ -60,23 +70,62 @@ def __init__(self, conn, ckpt_path, ckpt_lock, shard_id, paper_dir, chunk_dir): self.ckpt_lock = ckpt_lock self.shard_id = shard_id self.outputs = (Path(paper_dir), Path(chunk_dir)) - self.owner: str | None = None self.checkpoint = load_checkpoint(ckpt_path, shard_id=shard_id) + self.token: str | None = None def checkpoint_tar(self, tar: str, members: int) -> None: self.checkpoint.setdefault("build_stream", {})[tar] = members save_checkpoint(self.checkpoint, self.ckpt_path, self.ckpt_lock, shard_id=self.shard_id) - @property - def prefix(self) -> str: - if self.owner is None or UUID(hex=self.owner).hex != self.owner: - raise ValueError("Invalid publication owner in SQLite") - return f".litkit-batch-{self.owner}-" + def _database(self) -> str: + return self.conn.execute("PRAGMA database_list").fetchone()[2] - def _stage_name(self, token: str) -> str: + def _directories(self, token: str) -> tuple[Path, Path]: if UUID(hex=token).hex != token: raise ValueError("Invalid batch directory in SQLite") - return self.prefix + token + name = ".litkit-batch-" + token + return self.outputs[0] / name, self.outputs[1] / name + + 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, " + "tar TEXT, members INTEGER, paper TEXT, chunk TEXT)" + ) + token = uuid4().hex + self.conn.execute( + "INSERT INTO ingest_publication(singleton, token, source_db) VALUES (1, ?, ?)", + (token, self._database()), + ) + if not in_transaction: + self.conn.commit() + self.token = token + + def _retire(self): + self.conn.execute("DELETE FROM ingest_publication WHERE singleton=1") + self.conn.commit() + self.token = None + + def discard_uncommitted(self) -> None: + """Drop a reservation after an empty batch or after SQLite rolled back the articles.""" + record = _record(self.conn) + if record is None: + self.token = None + return + token, source_db, tar, *_ = record + if 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. + if source_db == self._database(): + for directory in set(self._directories(token)): + if directory.exists(): + shutil.rmtree(directory) + self._retire() def publish( self, @@ -84,46 +133,35 @@ def publish( members: int, write: Callable[[Path, Path], tuple[Path | None, Path | None]], ) -> None: - """Keep staged files on a post-commit error so recovery can finish publishing.""" - token = uuid4().hex - stage = self._stage_name(token) - directories = [root / stage for root in dict.fromkeys(self.outputs)] + """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: + for directory in set(directories): directory.mkdir(parents=True) maybe_fsync_dir(directory) - paper, chunk = write(*(root / stage for root in self.outputs)) + paper, chunk = write(*directories) for staged in (paper, chunk): if staged is not None: maybe_fsync_dir(staged) - record = ( - tar, - members, - token, - paper.name if paper else None, - chunk.name if chunk else None, - ) - updated = self.conn.execute( - "UPDATE ingest_publication SET tar=?, members=?, token=?, paper=?, chunk=? " - "WHERE owner=? AND tar IS NULL", - (*record, self.owner), + 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), ) - if updated.rowcount != 1: - raise RuntimeError("Another batch is awaiting publication") self.conn.commit() except BaseException: self.conn.rollback() - # A signal can arrive just after SQLite made the commit durable. - if not has_unpublished_batch(self.conn): - for directory in directories: - shutil.rmtree(directory, ignore_errors=True) + # A signal can arrive after SQLite made the commit durable. + row = _record(self.conn) + if row is None or row.tar is None: + self.discard_uncommitted() raise - self._finish(*record) + self._finish(directories, *record) - def _finish(self, tar, members, token, paper, chunk): - stage = self._stage_name(token) - for root, name in zip(self.outputs, (paper, chunk), strict=True): - directory = root / stage + def _finish(self, directories, tar, members, paper, chunk): + for directory, name in zip(directories, (paper, chunk), strict=True): if not directory.is_dir(): raise FileNotFoundError( f"Cannot resume batch: missing staging directory {directory}" @@ -133,49 +171,28 @@ def _finish(self, tar, members, token, paper, chunk): if name != Path(name).name or name in (".", ".."): raise ValueError("Invalid staged filename in SQLite") pending = directory / name - target = root / (finalized_name(pending) if name.endswith("_pending.npz") else name) - # In this committed, private directory, only the atomic rename removes - # a staged file. A consumer may already have claimed or deleted its target. + 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) self.checkpoint_tar(tar, members) - clear_publication(self.conn) - self.conn.commit() - for root in dict.fromkeys(self.outputs): - (root / stage).rmdir() - - def recover(self, *, initialize: bool = False) -> bool: - """Finish any committed batch and reclaim only this database's private staging.""" - if initialize and not _has_journal(self.conn): - self.conn.execute( - "CREATE TABLE ingest_publication (singleton INTEGER PRIMARY KEY CHECK(singleton=1), " - "owner TEXT NOT NULL, tar TEXT, members INTEGER, token TEXT, paper TEXT, chunk TEXT)" - ) - if not _has_journal(self.conn): + self._retire() + for directory in set(directories): + directory.rmdir() + + def recover(self) -> bool: + """Finish a committed batch or discard its rolled-back staging files.""" + record = _record(self.conn) + if record is None: return False - row = self.conn.execute( - "SELECT owner, tar, members, token, paper, chunk FROM ingest_publication WHERE singleton=1" - ).fetchone() - if row is None: - if not initialize: - return False - self.owner = uuid4().hex - self.conn.execute( - "INSERT INTO ingest_publication(singleton, owner) VALUES (1, ?)", (self.owner,) - ) - self.conn.commit() + token, _, tar, members, paper, chunk = record + if tar is None: + self.discard_uncommitted() return False - self.owner, tar, members, token, paper, chunk = row - if tar is not None: - self._finish(tar, members, token, paper, chunk) - # Another workspace can use the same --embed-outdir and shard number. - # The SQLite identity survives relocation and never names that workspace's files. - prefix = self.prefix - for root in dict.fromkeys(self.outputs): - for directory in root.glob(prefix + "?" * 32): - token = directory.name.removeprefix(prefix) - if all(ch in "0123456789abcdef" for ch in token) and directory.is_dir(): - shutil.rmtree(directory) - return tar is not None + self._finish(self._directories(token), tar, members, paper, chunk) + return True diff --git a/src/litkit/cli.py b/src/litkit/cli.py index da4b0eb..801dc98 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1230,8 +1230,14 @@ def build_or_update_indices(args): from litkit.build.publication import unpublished_shards - for shard in unpublished_shards(SQLITE_DIR): - conflict_reasons.append(f"Producer shard {shard.name} has a committed batch awaiting publication") + pending = unpublished_shards(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. @@ -1274,12 +1280,13 @@ def build_or_update_indices(args): CKPT_PATH.unlink() # wipe tables (DELETE in transaction, VACUUM outside) + from litkit.build.publication import reset_publication + with conn: conn.execute("BEGIN") for table in ("chunks", "papers", "files"): cur.execute(f"DELETE FROM {table}") - from litkit.build.publication import clear_publication - clear_publication(conn) + reset_publication(conn) # VACUUM must run outside any transaction (autocommit mode) # Without this, sqlite3.OperationalError: cannot VACUUM from within a transaction diff --git a/src/litkit/segments/constants.py b/src/litkit/segments/constants.py index 783e5e0..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,12 +32,6 @@ # Segment File Naming # --------------------------------------------------------------------------- -# Segment file patterns -PAPER_SEGMENT_PREFIX = "paper_seg" -CHUNK_SEGMENT_PREFIX = "chunk_seg" -SEGMENT_EXTENSION = ".npz" -PENDING_SUFFIX = "_pending" - # 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..3fb850a --- /dev/null +++ b/src/litkit/segments/discovery.py @@ -0,0 +1,73 @@ +"""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 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 path.name.endswith(PENDING_SUFFIX + suffix) and path.is_file(): + yield path + + +def _shard_count(directory, segments): + meta = directory / "build_meta.json" + if meta.exists(): + try: + count = json.loads(meta.read_text())["num_shards"] + if type(count) is int and count > 0: + return count + 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 = [] + 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: + match = re.match(r"(?:paper|chunk)_seg_(\d+)_", path.name) or re.search( + r"_sh(\d+)_", path.name + ) + if match: + ids.append(int(match[1])) + return max(ids) + 1 if ids else 2 # historic resume-script default + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("operation", choices=("count", "sample", "shards")) + 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) + 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 4b61bdd..2602be7 100644 --- a/src/litkit/segments/ingest.py +++ b/src/litkit/segments/ingest.py @@ -22,7 +22,7 @@ import numpy as np from litkit.db.queries import preload_paper_id_map, preload_chunk_id_map -from litkit.segments.metadata import iter_segment_files +from litkit.segments.discovery import iter_segment_files from litkit.index.dedup import add_with_ids_dedup from litkit.index.io import faiss_save, faiss_save_force from litkit.index.ids import make_id_selector, safe_remove_ids diff --git a/src/litkit/segments/metadata.py b/src/litkit/segments/metadata.py index d3663cd..12e2a16 100644 --- a/src/litkit/segments/metadata.py +++ b/src/litkit/segments/metadata.py @@ -5,16 +5,10 @@ import json import sys -from collections.abc import Iterator from pathlib import Path -from litkit.segments.constants import ( - BUILD_META_FILENAME, - PENDING_SUFFIX, - PAPER_SEGMENT_PREFIX, - CHUNK_SEGMENT_PREFIX, - SEGMENT_EXTENSION, -) +from litkit.segments.constants import BUILD_META_FILENAME +from litkit.segments.discovery import iter_segment_files def _eprint(msg: str = "", *, end: str = "\n") -> None: @@ -26,17 +20,6 @@ def _eprint(msg: str = "", *, end: str = "\n") -> None: pass -def iter_segment_files(seg_dir: Path, kind: str) -> Iterator[Path]: - """Yield finalized segments and interrupted consumer claims, including legacy names.""" - prefix = PAPER_SEGMENT_PREFIX if kind == "papers" else CHUNK_SEGMENT_PREFIX - for pattern in (f"{prefix}_*", f"{kind}_*", f"{kind}.seg.*"): - for claim in ("", ".ingesting"): - suffix = SEGMENT_EXTENSION + claim - for path in seg_dir.glob(pattern + suffix): - if not path.name.endswith(PENDING_SUFFIX + suffix): - yield path - - def has_segment_files(seg_dir: Path) -> bool: """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)) diff --git a/src/litkit/segments/writer.py b/src/litkit/segments/writer.py index f2070c0..bc6f6d0 100644 --- a/src/litkit/segments/writer.py +++ b/src/litkit/segments/writer.py @@ -181,16 +181,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: @@ -205,13 +204,12 @@ def write(self, *, doc_ids: list[str], vecs: np.ndarray) -> Path | None: if len(doc_ids) == 0: return None - # Add all to buffer and flush - for doc_id, vec in zip(doc_ids, vecs, strict=True): - 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. @@ -223,7 +221,10 @@ def flush(self) -> Path | None: if not self._doc_ids: return None - path = self.stage(self.outdir, doc_ids=self._doc_ids, vecs=np.vstack(self._embeddings)) + 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 @@ -364,19 +365,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: @@ -392,14 +392,13 @@ def write( 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, strict=True): - 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. @@ -411,7 +410,10 @@ def flush(self) -> Path | None: if not self._doc_ids: return None - path = self.stage(self.outdir, paper_doc_ids=self._doc_ids, ords=self._ords, vecs=np.vstack(self._embeddings)) + return self._write_batch(self._doc_ids, self._ords, np.vstack(self._embeddings)) + + 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 diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 5a388f1..bee1950 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -1,11 +1,14 @@ """Interrupted tar batches, from SQLite savepoints to the consumer's FAISS IDs.""" +import shutil import sqlite3 +import subprocess +import sys from concurrent.futures import ThreadPoolExecutor -from threading import Event from contextlib import closing from functools import partial from pathlib import Path +from threading import Event import faiss import numpy as np @@ -227,11 +230,14 @@ def __enter__(self): assert [len(ids) for ids, _ in build.consume()] == [3, 6] -def test_new_workspace_cannot_discard_another_producers_committed_segments( +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: @@ -302,3 +308,23 @@ def fail_chunk_save(index, path): assert not build.paper_path.exists() assert not build.chunk_path.exists() assert build.run()[2:] == (3, 6) + + +def test_rebuild_can_inspect_a_shard_with_a_hot_rollback_journal(tmp_path): + from litkit.build.publication import unpublished_shards + + db = shard_db_path(tmp_path, 0) + init_shard_db(db, 0).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 + assert unpublished_shards(tmp_path) == [] + with closing(sqlite3.connect(db)) as conn: + assert conn.execute("SELECT COUNT(*) FROM papers").fetchone() == (0,) diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index 9d2b13d..417b39d 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -645,6 +645,18 @@ def stop_after_rename(self, target): ) 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 "committed batch awaiting publication" in consume.stderr + for marker in markers: + marker.unlink() _ok(litkit(ws, *args, "--shard-id", "1")) _ok(litkit(ws, *args, "--shard-id", "0")) diff --git a/tests/test_segments.py b/tests/test_segments.py index 25d574b..d73fe14 100644 --- a/tests/test_segments.py +++ b/tests/test_segments.py @@ -139,6 +139,60 @@ def test_segment_writer_rejects_incomplete_embedding_batch(seg_dir, unit_vectors 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")) + + +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") diff --git a/validate_build.sh b/validate_build.sh index d77bc9f..21d2125 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,14 @@ 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 ' ') + discovery="$(dirname "${BASH_SOURCE[0]}")/src/litkit/segments/discovery.py" + SEGMENT_COUNT=$(python3 "$discovery" count "$EMB_DIR") if [[ "$SEGMENT_COUNT" -eq 0 ]]; then - echo " ✅ All segments consumed (directory empty)" + 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_resume_consumer.sbatch b/vector_resume_consumer.sbatch index 12bb1db..70cc474 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 @@ -64,7 +63,8 @@ SEG_DIR="${LITKIT_WORKSPACE}/emb_segments" export LITKIT_DEBUG="${LITKIT_DEBUG:-1}" # Count remaining segment files -n_segs=$(find "$SEG_DIR" -name '*.npz' 2>/dev/null | wc -l) +discovery="${LITKIT_REPO}/src/litkit/segments/discovery.py" +n_segs=$(python3 "$discovery" count "$SEG_DIR") echo "[resume] Found $n_segs segment files to ingest" if [[ "$n_segs" -eq 0 ]]; then @@ -73,11 +73,8 @@ if [[ "$n_segs" -eq 0 ]]; then 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" +n_shards=$(python3 "$discovery" shards "$SEG_DIR") +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. @@ -88,18 +85,6 @@ 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}/.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" From dabd78efc06295ec6e15de1cd48eed66e765cc73 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 16:35:08 -0700 Subject: [PATCH 04/31] Preserve published work across retries and mark every saved consumer vector Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 1 + src/litkit/build/backfill.py | 6 +- src/litkit/build/consume.py | 9 ++- src/litkit/build/publication.py | 44 ++++++++++---- src/litkit/segments/ingest.py | 73 ++++++++++------------- src/litkit/segments/writer.py | 15 ++++- tests/integration/test_batch_resume.py | 60 +++++++++++++++++++ tests/integration/test_build_and_query.py | 1 + tests/test_segments.py | 22 +++++++ 9 files changed, 174 insertions(+), 57 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d7f48d..6a67ce3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ internal versions are summarized under 0.3.33. ## [Unreleased] ### Fixed +- Completed consumers now mark every saved paper and chunk as indexed when FAISS saves are throttled. - Tar builds commit articles in batches. Interrupted producers resume with complete paper and chunk segments, and consumers ignore unfinished files. For a producer already interrupted on an older release, 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) diff --git a/src/litkit/build/backfill.py b/src/litkit/build/backfill.py index d03dfe3..d516b57 100644 --- a/src/litkit/build/backfill.py +++ b/src/litkit/build/backfill.py @@ -70,8 +70,10 @@ def backfill_unindexed_vectors( # Papers while True: rows = cur.execute( - "SELECT id, (COALESCE(title,'') || ' ' || COALESCE(abstract,'')) " - "AS txt FROM papers WHERE in_index=0 LIMIT ?", + "SELECT p.id, COALESCE((" + " SELECT c.text FROM chunks c WHERE c.paper_id=p.id AND c.ord=-1 ORDER BY c.id LIMIT 1" + "), TRIM(COALESCE(p.title,'') || ' ' || COALESCE(p.abstract,''))) " + "FROM papers p WHERE p.in_index=0 LIMIT ?", (batch,), ).fetchall() if not rows: diff --git a/src/litkit/build/consume.py b/src/litkit/build/consume.py index ccf7ec5..801e78f 100644 --- a/src/litkit/build/consume.py +++ b/src/litkit/build/consume.py @@ -24,6 +24,7 @@ ingest_paper_segments, ingest_chunk_segments, ) +from litkit.segments.ingest import mark_saved_segments from litkit.progress import eprint if TYPE_CHECKING: @@ -122,13 +123,14 @@ def default_progress(complete: int, total: int) -> None: # NOW ingest segments - main DB has all data for doc_id resolution eprint("[consumer] Ingesting embedding segments...") + pending_papers, pending_chunks = [], [] paper_index, p_added = ingest_paper_segments( conn, paper_index, seg_dir, faiss_lock_path, paper_index_path, db_lock_path, - FileLock=FileLock + FileLock=FileLock, unsaved_ids=pending_papers, ) chunk_index, c_added = ingest_chunk_segments( conn, chunk_index, seg_dir, faiss_lock_path, chunk_index_path, db_lock_path, - FileLock=FileLock + FileLock=FileLock, unsaved_ids=pending_chunks, ) eprint(f"[consumer] Ingested {p_added} paper vectors and {c_added} chunk vectors") @@ -139,7 +141,8 @@ def default_progress(complete: int, total: int) -> None: with FileLock(db_lock_path): flush_pending_marks(conn.cursor()) - conn.commit() + mark_saved_segments(conn, "papers", pending_papers) + mark_saved_segments(conn, "chunks", pending_chunks) eprint("[consumer] Consume-only mode completed") return True diff --git a/src/litkit/build/publication.py b/src/litkit/build/publication.py index 92b40e9..0307a85 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -2,6 +2,7 @@ from __future__ import annotations +import os import shutil import sqlite3 from collections.abc import Callable @@ -19,6 +20,8 @@ class _Publication(NamedTuple): token: str source_db: str + paper_root: str + chunk_root: str tar: str | None members: int | None paper: str | None @@ -31,7 +34,7 @@ def _record(conn: sqlite3.Connection) -> _Publication | None: ).fetchone(): return None row = conn.execute( - "SELECT token, source_db, tar, members, paper, chunk FROM ingest_publication" + "SELECT token, source_db, paper_root, chunk_root, tar, members, paper, chunk FROM ingest_publication" ).fetchone() return _Publication(*row) if row else None @@ -80,6 +83,20 @@ def checkpoint_tar(self, tar: str, members: int) -> None: def _database(self) -> str: return self.conn.execute("PRAGMA database_list").fetchone()[2] + def _shares_source_staging(self, record: _Publication) -> bool: + """A backup may publish its own copy of staging, or resume the original DB in place.""" + current = self._database() + if current == record.source_db or ( + Path(record.source_db).exists() and os.path.samefile(current, record.source_db) + ): + return False + for root, source in zip(self.outputs, (record.paper_root, record.chunk_root), strict=True): + if root.resolve() == Path(source) or ( + root.exists() and Path(source).exists() and root.samefile(source) + ): + return True + return False + def _directories(self, token: str) -> tuple[Path, Path]: if UUID(hex=token).hex != token: raise ValueError("Invalid batch directory in SQLite") @@ -94,12 +111,14 @@ def reserve(self) -> None: 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 self.conn.execute( - "INSERT INTO ingest_publication(singleton, token, source_db) VALUES (1, ?, ?)", - (token, self._database()), + "INSERT INTO ingest_publication(singleton, token, source_db, paper_root, chunk_root) " + "VALUES (1, ?, ?, ?, ?)", + (token, self._database(), *(str(root.resolve()) for root in self.outputs)), ) if not in_transaction: self.conn.commit() @@ -116,13 +135,12 @@ def discard_uncommitted(self) -> None: if record is None: self.token = None return - token, source_db, tar, *_ = record - if tar is not None: + 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. - if source_db == self._database(): - for directory in set(self._directories(token)): + if not self._shares_source_staging(record): + for directory in set(self._directories(record.token)): if directory.exists(): shutil.rmtree(directory) self._retire() @@ -190,9 +208,15 @@ def recover(self) -> bool: record = _record(self.conn) if record is None: return False - token, _, tar, members, paper, chunk = record - if tar is None: + if record.tar is None: self.discard_uncommitted() return False - self._finish(self._directories(token), tar, members, paper, chunk) + if self._shares_source_staging(record): + raise RuntimeError( + "This database copy shares staging with its original database. " + "Resume the original workspace, or use a matching copy of its segment directory." + ) + self._finish( + self._directories(record.token), record.tar, record.members, record.paper, record.chunk + ) return True diff --git a/src/litkit/segments/ingest.py b/src/litkit/segments/ingest.py index 2602be7..263ab5b 100644 --- a/src/litkit/segments/ingest.py +++ b/src/litkit/segments/ingest.py @@ -14,6 +14,7 @@ import sqlite3 import sys import time +from contextlib import nullcontext from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING @@ -21,6 +22,7 @@ import faiss import numpy as np +from litkit.db.indexing import flush_pending_marks, mark_in_index from litkit.db.queries import preload_paper_id_map, preload_chunk_id_map from litkit.segments.discovery import iter_segment_files from litkit.index.dedup import add_with_ids_dedup @@ -63,6 +65,15 @@ def _glob_segment_files(outdir: Path, kind: str) -> list[Path]: return sorted(iter_segment_files(outdir, kind)) +def mark_saved_segments(conn: sqlite3.Connection, table: str, batches: list[np.ndarray]) -> None: + """Mark IDs from this index's throttled batches once a save covers them.""" + with conn: + cur = conn.cursor() + for ids in batches: + mark_in_index(cur, table, ids.tolist()) + batches.clear() + + def ingest_paper_segments( conn: sqlite3.Connection, paper_index: faiss.Index, @@ -73,6 +84,7 @@ def ingest_paper_segments( *, save_every: int = 2, paper_id_map: dict[str, int] | None = None, + unsaved_ids: list[np.ndarray] | None = None, FileLock: type | None = None, ) -> tuple[faiss.Index, int]: """Ingest paper embedding segments from producer nodes. @@ -93,6 +105,7 @@ def ingest_paper_segments( 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. + unsaved_ids: Receives ID batches still awaiting the caller's final forced save. FileLock: File lock class to use (pass from caller to avoid circular import) Returns: @@ -126,6 +139,8 @@ def ingest_paper_segments( "or ensure producers have completed and DB merge has run.") return paper_index, 0 # Safe exit, no data loss + if unsaved_ids is None: + unsaved_ids = [] cur = conn.cursor() added_total = 0 batch_counter = 0 @@ -217,19 +232,11 @@ def ingest_paper_segments( else faiss_save(paper_index, paper_index_path) if added: + unsaved_ids.append(ids_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: save failed, reconcile+backfill will repair - + with FileLock(db_lock_path) if db_lock_path else nullcontext(): + mark_saved_segments(conn, "papers", unsaved_ids) + added_total += int(added or 0) batch_counter += 1 os.remove(tmp) @@ -239,15 +246,10 @@ def ingest_paper_segments( with FileLock(faiss_lock_path): saved_now = faiss_save(paper_index, paper_index_path) if saved_now: - from litkit.db.indexing import flush_pending_marks - if db_lock_path: - with FileLock(db_lock_path): - flush_pending_marks(cur) - conn.commit() - else: + with FileLock(db_lock_path) if db_lock_path else nullcontext(): flush_pending_marks(cur) - conn.commit() - + mark_saved_segments(conn, "papers", unsaved_ids) + except Exception as e: # On error, rename file back so it can be retried next run if not is_ingesting: @@ -271,6 +273,7 @@ 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, + unsaved_ids: list[np.ndarray] | None = None, FileLock: type | None = None, ) -> tuple[faiss.Index, int]: """Ingest chunk embedding segments from producer nodes. @@ -298,6 +301,7 @@ def ingest_chunk_segments( 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. + unsaved_ids: Receives ID batches still awaiting the caller's final forced save. FileLock: File lock class to use (pass from caller to avoid circular import) Returns: @@ -338,6 +342,8 @@ def ingest_chunk_segments( "or ensure producers have completed and DB merge has run.") return chunk_index, 0 # Safe exit, no data loss + if unsaved_ids is None: + unsaved_ids = [] cur = conn.cursor() added_total = 0 batch_counter = 0 @@ -438,19 +444,11 @@ def ingest_chunk_segments( else faiss_save(chunk_index, chunk_index_path) if added: + unsaved_ids.append(ids_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: save failed, reconcile+backfill will repair - + with FileLock(db_lock_path) if db_lock_path else nullcontext(): + mark_saved_segments(conn, "chunks", unsaved_ids) + added_total += int(added) batch_counter += 1 os.remove(tmp) @@ -460,15 +458,10 @@ def ingest_chunk_segments( with FileLock(faiss_lock_path): saved_now = faiss_save(chunk_index, chunk_index_path) if saved_now: - from litkit.db.indexing import flush_pending_marks - if db_lock_path: - with FileLock(db_lock_path): - flush_pending_marks(cur) - conn.commit() - else: + with FileLock(db_lock_path) if db_lock_path else nullcontext(): flush_pending_marks(cur) - conn.commit() - + mark_saved_segments(conn, "chunks", unsaved_ids) + except Exception as e: # If we claimed it, put it back so another run can retry. if not is_ingesting: diff --git a/src/litkit/segments/writer.py b/src/litkit/segments/writer.py index bc6f6d0..a626c17 100644 --- a/src/litkit/segments/writer.py +++ b/src/litkit/segments/writer.py @@ -62,8 +62,19 @@ def _finalize_paths(paths: list[Path]) -> int: count = len(paths) while paths: path = paths[-1] - path.replace(path.with_name(finalized_name(path))) - paths.pop() + target = path.with_name(finalized_name(path)) + if not path.exists(): + if target.is_file() or target.with_suffix(".npz.ingesting").is_file(): + paths.pop() + 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.pop() return count diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index bee1950..22312ee 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -328,3 +328,63 @@ def test_rebuild_can_inspect_a_shard_with_a_hot_rollback_journal(tmp_path): assert unpublished_shards(tmp_path) == [] with closing(sqlite3.connect(db)) as conn: assert conn.execute("SELECT COUNT(*) FROM papers").fetchone() == (0,) + + +@pytest.mark.parametrize("share_segments", [True, False]) +def test_committed_database_copy_requires_independent_staging( + tmp_path, archive, monkeypatch, share_segments +): + 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 share_segments: + copy.segments = first.segments + with pytest.raises(RuntimeError, match="matching copy"): + copy.run() + else: + shutil.copytree(first.segments, copy.segments) + 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] + + +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) diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index 417b39d..0174ddf 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -667,6 +667,7 @@ def stop_after_rename(self, target): 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 diff --git a/tests/test_segments.py b/tests/test_segments.py index d73fe14..8737e4c 100644 --- a/tests/test_segments.py +++ b/tests/test_segments.py @@ -168,6 +168,28 @@ def full_disk(*args, **kwargs): 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 + + vec = unit_vectors(1, 4) + w = _write_one(kind, seg_dir, vec) + if kind == "papers": + w.write(doc_ids=["second"], vecs=vec) + else: + w.write(paper_doc_ids=["second"], ords=[0], vecs=vec) + 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() + assert w.finalize() == 1 + assert len(_glob_segment_files(seg_dir, kind)) == 2 + + def test_cluster_segment_commands_use_consumer_discovery(seg_dir): import subprocess import sys From b20159619db99d1f4d7986af44d280d47be54e9c Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 16:46:01 -0700 Subject: [PATCH 05/31] Serialize shard handoff and retain the paper text used for each revision Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 1 + src/litkit/build/backfill.py | 6 +- src/litkit/build/consume.py | 94 +++++++++++++---------- src/litkit/build/helpers.py | 21 ++--- src/litkit/build/ingest_loop.py | 30 +++++--- src/litkit/build/publication.py | 11 ++- src/litkit/cli.py | 14 +++- src/litkit/db/schema.py | 9 +++ src/litkit/db/sharding.py | 38 +++++---- tests/integration/test_batch_resume.py | 52 ++++++++++++- tests/integration/test_build_and_query.py | 77 +++++++++++++++++++ tests/test_db.py | 37 +++++++++ vector_build_multi.sbatch | 10 ++- 13 files changed, 307 insertions(+), 93 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a67ce3..d7a76da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ internal versions are summarized under 0.3.33. ## [Unreleased] ### Fixed +- Shard merges commit and detach each database before deleting it. Builds with more than ten producer shards can now merge every shard. (#1) - Completed consumers now mark every saved paper and chunk as indexed when FAISS saves are throttled. - Tar builds commit articles in batches. Interrupted producers resume with complete paper and chunk segments, and consumers ignore unfinished files. For a producer already interrupted on an older release, 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) diff --git a/src/litkit/build/backfill.py b/src/litkit/build/backfill.py index d516b57..63ffc10 100644 --- a/src/litkit/build/backfill.py +++ b/src/litkit/build/backfill.py @@ -25,6 +25,7 @@ safe_remove_ids, ) 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: @@ -68,10 +69,11 @@ def backfill_unindexed_vectors( cur = conn.cursor() # Papers + recorded_text = paper_embedding_column(conn) while True: rows = cur.execute( - "SELECT p.id, COALESCE((" - " SELECT c.text FROM chunks c WHERE c.paper_id=p.id AND c.ord=-1 ORDER BY c.id LIMIT 1" + 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 WHERE p.in_index=0 LIMIT ?", (batch,), diff --git a/src/litkit/build/consume.py b/src/litkit/build/consume.py index 801e78f..63b348a 100644 --- a/src/litkit/build/consume.py +++ b/src/litkit/build/consume.py @@ -10,6 +10,7 @@ from __future__ import annotations +from contextlib import ExitStack from pathlib import Path from sqlite3 import Connection from typing import TYPE_CHECKING, Callable @@ -18,6 +19,7 @@ merge_shard_databases, flush_pending_marks, ) +from litkit.db.sharding import list_shard_dbs, shard_db_path from litkit.index import faiss_load, faiss_save_force from litkit.segments import ( ConsumerCoordinator, @@ -102,47 +104,55 @@ def default_progress(complete: int, total: int) -> None: from litkit.build.publication import unpublished_shards sqlite_dir = Path(conn.execute("PRAGMA database_list").fetchone()[2]).parent - pending = unpublished_shards(sqlite_dir) - if pending: - names = ", ".join(shard.name for shard in pending) - raise RuntimeError( - f"Cannot consume: {names} has a committed batch awaiting publication. " - "Resume the interrupted producer in its original workspace and segment directory." - ) + candidates = sorted(set(list_shard_dbs(sqlite_dir)) | + {shard_db_path(sqlite_dir, i) for i in range(num_shards)}) + with ExitStack() as locks: + for shard in candidates: + suffix = shard.stem.removeprefix("litkit_shard_") + shard_id = int(suffix) if suffix.isdecimal() else suffix + locks.enter_context(FileLock(sqlite_dir / f"producer_{shard_id}.lock")) + shards = [shard for shard in candidates if shard.is_file()] + pending = unpublished_shards(shards) + if pending: + names = ", ".join(shard.name for shard in pending) + raise RuntimeError( + f"Cannot consume: {names} has a committed batch awaiting publication. " + "Resume the interrupted producer in its original workspace and segment directory." + ) + + # 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, shard_dbs=shards) + 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" + ) - # 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" + # NOW ingest segments - main DB has all data for doc_id resolution + eprint("[consumer] Ingesting embedding segments...") + pending_papers, pending_chunks = [], [] + paper_index, p_added = ingest_paper_segments( + conn, paper_index, seg_dir, faiss_lock_path, paper_index_path, db_lock_path, + FileLock=FileLock, unsaved_ids=pending_papers, ) - - # NOW ingest segments - main DB has all data for doc_id resolution - eprint("[consumer] Ingesting embedding segments...") - pending_papers, pending_chunks = [], [] - paper_index, p_added = ingest_paper_segments( - conn, paper_index, seg_dir, faiss_lock_path, paper_index_path, db_lock_path, - FileLock=FileLock, unsaved_ids=pending_papers, - ) - chunk_index, c_added = ingest_chunk_segments( - conn, chunk_index, seg_dir, faiss_lock_path, chunk_index_path, db_lock_path, - FileLock=FileLock, unsaved_ids=pending_chunks, - ) - eprint(f"[consumer] Ingested {p_added} paper vectors and {c_added} chunk vectors") - - # Force save indices after ingestion - with FileLock(faiss_lock_path): - faiss_save_force(paper_index, paper_index_path) - faiss_save_force(chunk_index, chunk_index_path) - - with FileLock(db_lock_path): - flush_pending_marks(conn.cursor()) - mark_saved_segments(conn, "papers", pending_papers) - mark_saved_segments(conn, "chunks", pending_chunks) - - eprint("[consumer] Consume-only mode completed") - return True + chunk_index, c_added = ingest_chunk_segments( + conn, chunk_index, seg_dir, faiss_lock_path, chunk_index_path, db_lock_path, + FileLock=FileLock, unsaved_ids=pending_chunks, + ) + eprint(f"[consumer] Ingested {p_added} paper vectors and {c_added} chunk vectors") + + # Force save indices after ingestion + with FileLock(faiss_lock_path): + faiss_save_force(paper_index, paper_index_path) + faiss_save_force(chunk_index, chunk_index_path) + + with FileLock(db_lock_path): + flush_pending_marks(conn.cursor()) + mark_saved_segments(conn, "papers", pending_papers) + mark_saved_segments(conn, "chunks", pending_chunks) + + 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/ingest_loop.py b/src/litkit/build/ingest_loop.py index c6e12f8..db66ef4 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -167,6 +167,7 @@ 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. @@ -237,7 +238,7 @@ def flush_batch(tar: str, members: int) -> None: return pids, texts, doc_ids = dedupe_papers_with_doc_ids( - paper_ids_buf, paper_texts_buf, paper_doc_ids_buf + 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 @@ -470,15 +471,15 @@ def _render(force: bool = False): existing_row = None if pmcid: existing_row = cur.execute( - "SELECT id, doc_id FROM papers WHERE pmcid=?", (pmcid,) + "SELECT id, doc_id, embedding_text 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,) + "SELECT id, doc_id, embedding_text FROM papers WHERE pmid=?", (pmid,) ).fetchone() if existing_row: - pid, existing_doc_id = existing_row + pid, existing_doc_id, previous_text = existing_row if existing_doc_id: canon_doc_id = existing_doc_id else: @@ -519,11 +520,19 @@ def _render(force: bool = False): # 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 and not seen_this_path: - reuse_embedding = rebuild or cur.execute( - "SELECT text FROM chunks WHERE paper_id=? AND ord=-1 ORDER BY id LIMIT 1", - (pid,), - ).fetchone() == (ta_ab,) + 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 (rebuild or previous_text == ta_ab)) + cur.execute( + "UPDATE papers SET embedding_text=? WHERE id=?", + (previous_text if reuse_embedding else ta_ab, pid), + ) if not reuse_embedding: paper_ids_buf.append(pid) paper_texts_buf.append(ta_ab) @@ -605,7 +614,8 @@ def _render(force: bool = False): # Different shards can run in parallel. Two starts of the same shard must # serialize recovery, scanning, and publication against the same checkpoint. owner_lock = ( - FileLock(sqlite_dir / f"producer_{ckpt_shard_id}.lock") if embed_producer else nullcontext() + FileLock(sqlite_dir / f"producer_{ckpt_shard_id}.lock") + if embed_producer and not _producer_locked else nullcontext() ) with owner_lock: publication = BatchPublication( diff --git a/src/litkit/build/publication.py b/src/litkit/build/publication.py index 0307a85..f7d6fa5 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -12,7 +12,6 @@ from uuid import UUID, uuid4 from litkit.build.helpers import maybe_fsync_dir -from litkit.db.sharding import list_shard_dbs from litkit.segments.checkpoint import load_checkpoint, save_checkpoint from litkit.segments.writer import finalized_name @@ -39,10 +38,10 @@ def _record(conn: sqlite3.Connection) -> _Publication | None: return _Publication(*row) if row else None -def unpublished_shards(sqlite_dir: Path) -> list[Path]: +def unpublished_shards(shards: list[Path]) -> list[Path]: """Find producers that committed rows and still have files to publish.""" pending = [] - for shard in list_shard_dbs(sqlite_dir): + for shard in shards: uri = shard.resolve().as_uri() try: with closing(sqlite3.connect(uri + "?mode=ro", uri=True)) as conn: @@ -199,9 +198,13 @@ def _finish(self, directories, tar, members, paper, chunk): maybe_fsync_dir(target) maybe_fsync_dir(pending) self.checkpoint_tar(tar, members) - self._retire() + # Keep the token across cleanup. An interrupted rmdir can then be + # retried without re-publishing or requiring both directories to exist. + with self.conn: + self.conn.execute("UPDATE ingest_publication SET tar=NULL WHERE singleton=1") for directory in set(directories): directory.rmdir() + self._retire() def recover(self) -> bool: """Finish a committed batch or discard its rolled-back staging files.""" diff --git a/src/litkit/cli.py b/src/litkit/cli.py index 801dc98..c762586 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1063,6 +1063,16 @@ 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() + # Acquire ownership before opening the shard. A consumer holding this + # lock may commit the merge and unlink the previous database. + with FileLock(SQLITE_DIR / f"producer_{args.shard_id}.lock"): + 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) # ═══════════════════════════════════════════════════════════════════════════ @@ -1229,8 +1239,9 @@ def build_or_update_indices(args): conflict_reasons.append(f"Segment directory {seg_dir} contains unconsumed segment files") from litkit.build.publication import unpublished_shards + from litkit.db.sharding import list_shard_dbs - pending = unpublished_shards(SQLITE_DIR) + pending = unpublished_shards(list_shard_dbs(SQLITE_DIR)) if pending: names = ", ".join(shard.name for shard in pending) raise SystemExit( @@ -1431,6 +1442,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, ) diff --git a/src/litkit/db/schema.py b/src/litkit/db/schema.py index 167cbab..4c785fb 100644 --- a/src/litkit/db/schema.py +++ b/src/litkit/db/schema.py @@ -21,6 +21,7 @@ pmcid TEXT, title TEXT, abstract TEXT, + embedding_text TEXT, -- paper vector input when multiple versions share an ID source_path TEXT, in_index INTEGER DEFAULT 0 -- 0=not yet in FAISS, 1=added ); @@ -59,6 +60,12 @@ 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_in_index_columns(conn: sqlite3.Connection) -> None: """Add missing index, document identity and citation columns to writable databases. @@ -79,6 +86,8 @@ 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)")} + if "embedding_text" not in papers_cols: + cur.execute("ALTER TABLE papers ADD COLUMN embedding_text TEXT") 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 480ed69..fd6cc84 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -9,7 +9,7 @@ import time from pathlib import Path -from litkit.db.schema import citation_columns +from litkit.db.schema import citation_columns, paper_embedding_column # --------------------------------------------------------------------------- @@ -63,6 +63,8 @@ def _eprint(msg: str = "", *, end: str = "\n") -> None: def merge_shard_databases( main_conn: sqlite3.Connection, delete_after_merge: bool = True, + *, + shard_dbs: list[Path] | None = None, ) -> dict[str, int]: """Merge all per-shard SQLite databases into the main database. @@ -76,6 +78,7 @@ 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 + shard_dbs: Optional snapshot of databases already locked by the consumer Returns: Dict with merge statistics: {"papers": N, "chunks": M, "files": F, @@ -86,7 +89,8 @@ def merge_shard_databases( 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) + if shard_dbs is None: + shard_dbs = list_shard_dbs(sqlite_dir) if not shard_dbs: return {"papers": 0, "chunks": 0, "files": 0, "shards": 0} @@ -114,6 +118,8 @@ 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" @@ -127,13 +133,15 @@ def merge_shard_databases( 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 != '' @@ -204,13 +212,14 @@ def merge_shard_databases( f"({elapsed:.1f}s)" ) + # Commit this shard before detaching or deleting its only copy. + main_conn.commit() + except BaseException: + main_conn.rollback() + raise finally: - # Always detach the shard database - try: - main_cur.execute(f"DETACH DATABASE {shard_alias}") - except Exception: - pass - + main_cur.execute(f"DETACH DATABASE {shard_alias}") + # Delete shard DB after successful merge if delete_after_merge: try: @@ -226,13 +235,8 @@ def merge_shard_databases( 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/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 22312ee..682fb57 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -325,7 +325,7 @@ def test_rebuild_can_inspect_a_shard_with_a_hot_rollback_journal(tmp_path): 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 - assert unpublished_shards(tmp_path) == [] + assert unpublished_shards([db]) == [] with closing(sqlite3.connect(db)) as conn: assert conn.execute("SELECT COUNT(*) FROM papers").fetchone() == (0,) @@ -388,3 +388,53 @@ def test_writer_backfill_uses_the_original_body_only_paper_text(tmp_path): ) 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_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 0174ddf..a35612c 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -691,3 +691,80 @@ def test_rebuild_keeps_one_vector_for_a_paper_alias_across_tars( 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.build import publication +runner, root, role = sys.argv[1:4] +root = Path(root) +sys.argv = [runner, *sys.argv[4:]] +if role == "consumer": + inspect = publication.unpublished_shards + def pause_after_check(shards): + result = inspect(shards) + (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 + publication.unpublished_shards = pause_after_check +else: + class ContendingLock(cli.FileLock): + def __enter__(self): + if self.path.name == "producer_0.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"] + assert sorted(faiss.vector_to_array(faiss_load(ws / "indices" / "papers.faiss").id_map)) == [ + pid for pid, _ in rows + ] diff --git a/tests/test_db.py b/tests/test_db.py index 4132f90..415d737 100644 --- a/tests/test_db.py +++ b/tests/test_db.py @@ -199,3 +199,40 @@ def test_merge_and_retrieve_chunk_citation(tmp_path, legacy): migrated.execute("UPDATE papers SET source_path='new.pdf'") finally: 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() diff --git a/vector_build_multi.sbatch b/vector_build_multi.sbatch index bd52c3a..110d1a9 100644 --- a/vector_build_multi.sbatch +++ b/vector_build_multi.sbatch @@ -302,8 +302,14 @@ EOF # 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/" + # Publish into the shared workspace under the same shard lock as the + # consumer. The local lock inode stays local. The done marker travels last. + ( + flock -x 9 + /usr/bin/rsync -a --delay-updates --exclude="producer_*.lock" "${PRODUCER_LOCAL_STAGE_HOST}/sqlite/" "${LITKIT_WORKSPACE}/sqlite/" + /usr/bin/rsync -a --delay-updates --exclude="producer_*.done" "${PRODUCER_LOCAL_STAGE_HOST}/emb_segments/" "${LITKIT_WORKSPACE}/emb_segments/" + /usr/bin/rsync -a "${PRODUCER_LOCAL_STAGE_HOST}/emb_segments/producer_${PRODUCER_NODE_ID}.done" "${LITKIT_WORKSPACE}/emb_segments/" + ) 9>>"${LITKIT_WORKSPACE}/sqlite/producer_${PRODUCER_NODE_ID}.lock" echo "[Producer ${PRODUCER_NODE_ID}] [staging] Cleanup local staging dir" rm -rf "${PRODUCER_LOCAL_STAGE_HOST}" else From 381c488b4ebcd7c3a3d14f9ef87f1585f86ff2c0 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 16:51:51 -0700 Subject: [PATCH 06/31] Guard direct shard merges and persist paper revisions before checkpointing Signed-off-by: Bill Hlavacek --- src/litkit/build/consume.py | 35 ++------------- src/litkit/build/ingest_loop.py | 11 +++-- src/litkit/build/publication.py | 54 +++-------------------- src/litkit/cli.py | 2 +- src/litkit/db/publication.py | 49 ++++++++++++++++++++ src/litkit/db/schema.py | 15 +++++-- src/litkit/db/sharding.py | 50 ++++++++++++++++----- tests/integration/test_batch_resume.py | 54 ++++++++++++++++++++--- tests/integration/test_build_and_query.py | 6 +-- tests/test_db.py | 23 ++++++++++ 10 files changed, 193 insertions(+), 106 deletions(-) create mode 100644 src/litkit/db/publication.py diff --git a/src/litkit/build/consume.py b/src/litkit/build/consume.py index 63b348a..0c9af87 100644 --- a/src/litkit/build/consume.py +++ b/src/litkit/build/consume.py @@ -10,16 +10,12 @@ from __future__ import annotations -from contextlib import ExitStack 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.sharding import list_shard_dbs, shard_db_path +from litkit.db import flush_pending_marks +from litkit.db.sharding import merged_shard_databases from litkit.index import faiss_load, faiss_save_force from litkit.segments import ( ConsumerCoordinator, @@ -99,31 +95,8 @@ def default_progress(complete: int, total: int) -> None: eprint("[consumer] All producers have completed") - # An old completion marker can outlive an interrupted producer. Merging - # and deleting that shard would discard its record of unpublished files. - from litkit.build.publication import unpublished_shards - - sqlite_dir = Path(conn.execute("PRAGMA database_list").fetchone()[2]).parent - candidates = sorted(set(list_shard_dbs(sqlite_dir)) | - {shard_db_path(sqlite_dir, i) for i in range(num_shards)}) - with ExitStack() as locks: - for shard in candidates: - suffix = shard.stem.removeprefix("litkit_shard_") - shard_id = int(suffix) if suffix.isdecimal() else suffix - locks.enter_context(FileLock(sqlite_dir / f"producer_{shard_id}.lock")) - shards = [shard for shard in candidates if shard.is_file()] - pending = unpublished_shards(shards) - if pending: - names = ", ".join(shard.name for shard in pending) - raise RuntimeError( - f"Cannot consume: {names} has a committed batch awaiting publication. " - "Resume the interrupted producer in its original workspace and segment directory." - ) - - # 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, shard_dbs=shards) + eprint("[consumer] Merging shard databases...") + with merged_shard_databases(conn, expected_shards=num_shards, lock_factory=FileLock) as merge_stats: if merge_stats["shards"] > 0: eprint( f"[consumer] Merged {merge_stats['shards']} shard DB(s): " diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index db66ef4..ffb7ee6 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -46,6 +46,7 @@ flush_pending_marks as db_flush_pending_marks, ) from litkit.build.publication import BatchPublication +from litkit.db.schema import ensure_paper_embedding_column from litkit.build.helpers import ( pack_body, dedupe_papers_with_doc_ids, @@ -116,8 +117,9 @@ def _stage_index(cur, table, index, path, ids, vectors, removed, *, rebuild): index = faiss.IndexIDMap2(index) force = not index.ntotal or bool(removed) if removed: - safe_remove_ids(index, make_id_selector(sorted(removed))) - added, ids_added = add_with_ids_dedup(index, ids, vectors, skip_dedup=rebuild) + 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]) @@ -556,8 +558,10 @@ def _render(force: bool = False): # ---------- END INGEST BODY ---------- conn.execute("RELEASE SAVEPOINT member_sp") - if seen_this_path: + if existing_row and not reuse_embedding: + # A saved ID alone cannot distinguish two revisions after restart. replaced_papers.add(pid) + if seen_this_path: replaced_chunks.update(old_ids) except Exception as e: @@ -618,6 +622,7 @@ def _render(force: bool = False): if embed_producer and not _producer_locked else nullcontext() ) with owner_lock: + ensure_paper_embedding_column(conn) publication = BatchPublication( conn, ckpt_path, diff --git a/src/litkit/build/publication.py b/src/litkit/build/publication.py index f7d6fa5..c21ab26 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -6,60 +6,18 @@ import shutil import sqlite3 from collections.abc import Callable -from contextlib import closing from pathlib import Path -from typing import NamedTuple from uuid import UUID, uuid4 from litkit.build.helpers import maybe_fsync_dir +from litkit.db.publication import PublicationRecord, read_publication from litkit.segments.checkpoint import load_checkpoint, save_checkpoint from litkit.segments.writer import finalized_name -class _Publication(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 _record(conn: sqlite3.Connection) -> _Publication | 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 _Publication(*row) if row else None - - -def unpublished_shards(shards: list[Path]) -> list[Path]: - """Find producers that committed rows and still have files to publish.""" - pending = [] - for shard in shards: - uri = shard.resolve().as_uri() - try: - with closing(sqlite3.connect(uri + "?mode=ro", uri=True)) as conn: - row = _record(conn) - except sqlite3.OperationalError as error: - if error.sqlite_errorcode & 0xFF != sqlite3.SQLITE_READONLY: - raise - # Inspecting a hot rollback journal requires SQLite to undo uncommitted pages. - with closing(sqlite3.connect(uri + "?mode=rw", uri=True)) as conn: - row = _record(conn) - if row and row.tar is not None: - pending.append(shard) - return pending - - def reset_publication(conn: sqlite3.Connection) -> None: """Invalidate the active batch in the same transaction as an explicit rebuild.""" - if _record(conn): + if read_publication(conn): conn.execute("UPDATE ingest_publication SET tar=NULL WHERE singleton=1") @@ -82,7 +40,7 @@ def checkpoint_tar(self, tar: str, members: int) -> None: def _database(self) -> str: return self.conn.execute("PRAGMA database_list").fetchone()[2] - def _shares_source_staging(self, record: _Publication) -> bool: + def _shares_source_staging(self, record: PublicationRecord) -> bool: """A backup may publish its own copy of staging, or resume the original DB in place.""" current = self._database() if current == record.source_db or ( @@ -130,7 +88,7 @@ def _retire(self): def discard_uncommitted(self) -> None: """Drop a reservation after an empty batch or after SQLite rolled back the articles.""" - record = _record(self.conn) + record = read_publication(self.conn) if record is None: self.token = None return @@ -171,7 +129,7 @@ def publish( except BaseException: self.conn.rollback() # A signal can arrive after SQLite made the commit durable. - row = _record(self.conn) + row = read_publication(self.conn) if row is None or row.tar is None: self.discard_uncommitted() raise @@ -208,7 +166,7 @@ def _finish(self, directories, tar, members, paper, chunk): def recover(self) -> bool: """Finish a committed batch or discard its rolled-back staging files.""" - record = _record(self.conn) + record = read_publication(self.conn) if record is None: return False if record.tar is None: diff --git a/src/litkit/cli.py b/src/litkit/cli.py index c762586..97c9203 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1238,7 +1238,7 @@ 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.build.publication import unpublished_shards + from litkit.db.publication import unpublished_shards from litkit.db.sharding import list_shard_dbs pending = unpublished_shards(list_shard_dbs(SQLITE_DIR)) diff --git a/src/litkit/db/publication.py b/src/litkit/db/publication.py new file mode 100644 index 0000000..4cd109e --- /dev/null +++ b/src/litkit/db/publication.py @@ -0,0 +1,49 @@ +"""Read the SQLite journal for a producer or writer batch.""" + +from __future__ import annotations + +import sqlite3 +from contextlib import closing +from pathlib import Path +from typing import NamedTuple + + +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]) -> list[Path]: + """Find producers that committed rows and still have files to publish.""" + pending = [] + for shard in shards: + uri = shard.resolve().as_uri() + try: + with closing(sqlite3.connect(uri + "?mode=ro", uri=True)) as conn: + row = read_publication(conn) + except sqlite3.OperationalError as error: + if error.sqlite_errorcode & 0xFF != sqlite3.SQLITE_READONLY: + raise + # Inspecting a hot rollback journal requires SQLite to undo uncommitted pages. + with closing(sqlite3.connect(uri + "?mode=rw", uri=True)) as conn: + row = read_publication(conn) + if row and row.tar is not None: + pending.append(shard) + return pending diff --git a/src/litkit/db/schema.py b/src/litkit/db/schema.py index 4c785fb..bc9a83c 100644 --- a/src/litkit/db/schema.py +++ b/src/litkit/db/schema.py @@ -21,9 +21,11 @@ pmcid TEXT, title TEXT, abstract TEXT, - embedding_text TEXT, -- paper vector input when multiple versions share an ID 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, @@ -66,6 +68,12 @@ def paper_embedding_column(conn: sqlite3.Connection, schema: str = "main") -> st 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. @@ -86,8 +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)")} - if "embedding_text" not in papers_cols: - cur.execute("ALTER TABLE papers ADD COLUMN embedding_text TEXT") + 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 fd6cc84..d5c740b 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -3,13 +3,15 @@ from __future__ import annotations -import os import sqlite3 import sys import time +from contextlib import ExitStack, contextmanager from pathlib import Path -from litkit.db.schema import citation_columns, paper_embedding_column +from litkit.concurrent.locking import FileLock +from litkit.db.publication import unpublished_shards +from litkit.db.schema import citation_columns, ensure_paper_embedding_column, paper_embedding_column # --------------------------------------------------------------------------- @@ -63,8 +65,6 @@ def _eprint(msg: str = "", *, end: str = "\n") -> None: def merge_shard_databases( main_conn: sqlite3.Connection, delete_after_merge: bool = True, - *, - shard_dbs: list[Path] | None = None, ) -> dict[str, int]: """Merge all per-shard SQLite databases into the main database. @@ -78,21 +78,51 @@ 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 - shard_dbs: Optional snapshot of databases already locked by the consumer Returns: Dict with merge statistics: {"papers": N, "chunks": M, "files": F, "shards": S} """ - # 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) as stats: + return stats + + +@contextmanager +def merged_shard_databases( + main_conn: sqlite3.Connection, + delete_after_merge: bool = True, + *, + expected_shards: int = 0, + lock_factory=FileLock, +): + """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(".") - - if shard_dbs is None: - shard_dbs = list_shard_dbs(sqlite_dir) + candidates = set(list_shard_dbs(sqlite_dir)) + candidates.update(shard_db_path(sqlite_dir, i) for i in range(expected_shards)) + lock_paths = set() + for shard in candidates: + suffix = shard.stem.removeprefix("litkit_shard_") + shard_id = int(suffix) if suffix.isdecimal() else suffix + lock_paths.add(sqlite_dir / f"producer_{shard_id}.lock") + with ExitStack() as locks: + for path in sorted(lock_paths): + locks.enter_context(lock_factory(path)) + shards = sorted(shard for shard in candidates if shard.is_file()) + pending = unpublished_shards(shards) + if pending: + names = ", ".join(shard.name for shard in pending) + raise RuntimeError( + f"Cannot merge: {names} has a committed batch awaiting publication. " + "Resume the interrupted producer in its original workspace and segment directory." + ) + yield _merge_locked_shards(main_conn, shards, delete_after_merge) + + +def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge): 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 " diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 682fb57..2026971 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -5,7 +5,7 @@ import subprocess import sys from concurrent.futures import ThreadPoolExecutor -from contextlib import closing +from contextlib import closing, nullcontext from functools import partial from pathlib import Path from threading import Event @@ -17,7 +17,7 @@ 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 init_db, init_shard_db, merge_shard_databases, shard_db_path +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 @@ -51,14 +51,16 @@ def __init__(self, root, tar, *, producer=True): self.paper_path = root / "papers.faiss" self.chunk_path = root / "chunks.faiss" - def run(self, **overrides): + 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) - conn = init_shard_db(self.db, 0) if self.producer else init_db(self.db) - with closing(conn): + connection = nullcontext(conn) if conn is not None else closing( + init_shard_db(self.db, 0) if self.producer else init_db(self.db) + ) + with connection as conn: options = dict( tar_paths=[self.tar], conn=conn, @@ -132,6 +134,26 @@ class InjectedFailure(Exception): pass +def test_ingest_and_merge_through_existing_pre_embedding_text_connections(tmp_path): + 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: + assert build.run(conn=producer)[2:] == (1, 2) + assert producer.execute("SELECT embedding_text FROM papers").fetchall() == [("Revised",)] + with closing(connect_db(main_db)) as main: + stats = merge_shard_databases(main) + assert stats["papers"] == 1 + assert main.execute("SELECT embedding_text FROM papers").fetchall() == [("Revised",)] + + @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) @@ -193,6 +215,11 @@ def fail_checkpoint(*args, **kwargs): 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="committed batch awaiting publication"): + 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: @@ -311,7 +338,7 @@ def fail_chunk_save(index, path): def test_rebuild_can_inspect_a_shard_with_a_hot_rollback_journal(tmp_path): - from litkit.build.publication import unpublished_shards + from litkit.db.publication import unpublished_shards db = shard_db_path(tmp_path, 0) init_shard_db(db, 0).close() @@ -424,6 +451,21 @@ def test_update_aliases_follow_the_last_embedded_text(tmp_path, monkeypatch): 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: diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index a35612c..754c5c2 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -713,12 +713,12 @@ def test_consumer_finishes_merge_before_next_producer_opens_shard(isolated_env, import os, runpy, sys, time from pathlib import Path from litkit import cli -from litkit.build import publication +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 = publication.unpublished_shards + inspect = sharding.unpublished_shards def pause_after_check(shards): result = inspect(shards) (root / "checked").touch() @@ -728,7 +728,7 @@ def pause_after_check(shards): raise RuntimeError("producer did not reach the lock") time.sleep(0.02) return result - publication.unpublished_shards = pause_after_check + sharding.unpublished_shards = pause_after_check else: class ContendingLock(cli.FileLock): def __enter__(self): diff --git a/tests/test_db.py b/tests/test_db.py index 415d737..d5a3502 100644 --- a/tests/test_db.py +++ b/tests/test_db.py @@ -236,3 +236,26 @@ def test_merge_failure_preserves_source_shard_and_rolls_back_its_rows(tmp_path): 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_accepts_padded_and_unpadded_paths_for_the_same_producer(tmp_path): + from contextlib import closing, contextmanager + from litkit.concurrent.locking import FileLock + from litkit.db.sharding import merged_shard_databases + + for name in ("litkit_shard_0.sqlite3", "litkit_shard_00.sqlite3"): + with closing(init_db(tmp_path / name)) as shard, shard: + shard.execute("INSERT INTO papers(doc_id) VALUES (?)", (name,)) + acquired = [] + + @contextmanager + def lock_once(path): + assert path not in acquired, "a second flock on the same path would deadlock" + acquired.append(path) + with FileLock(path): + yield + + with closing(init_db(tmp_path / "main.sqlite3")) as main: + with merged_shard_databases(main, expected_shards=1, lock_factory=lock_once) as stats: + assert stats["papers"] == stats["shards"] == 2 + assert acquired == [tmp_path / "producer_0.lock"] From 7668d27106432f5646dab01ca7224979ff1e6dd5 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 16:59:07 -0700 Subject: [PATCH 07/31] Recover caller-owned transactions and bound file descriptors during shard handoff Signed-off-by: Bill Hlavacek --- src/litkit/build/consume.py | 2 +- src/litkit/build/ingest_loop.py | 10 +++-- src/litkit/build/publication.py | 38 +++++++++++++---- src/litkit/cli.py | 4 +- src/litkit/db/connection.py | 26 ++++++++++++ src/litkit/db/sharding.py | 33 ++++++++------- tests/integration/test_batch_resume.py | 51 ++++++++++++++++++++++- tests/integration/test_build_and_query.py | 2 +- tests/test_db.py | 32 ++++++++------ vector_build_multi.sbatch | 6 ++- 10 files changed, 160 insertions(+), 44 deletions(-) diff --git a/src/litkit/build/consume.py b/src/litkit/build/consume.py index 0c9af87..ce75c1e 100644 --- a/src/litkit/build/consume.py +++ b/src/litkit/build/consume.py @@ -96,7 +96,7 @@ def default_progress(complete: int, total: int) -> None: eprint("[consumer] All producers have completed") eprint("[consumer] Merging shard databases...") - with merged_shard_databases(conn, expected_shards=num_shards, lock_factory=FileLock) as merge_stats: + with merged_shard_databases(conn, lock_factory=FileLock) as merge_stats: if merge_stats["shards"] > 0: eprint( f"[consumer] Merged {merge_stats['shards']} shard DB(s): " diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index ffb7ee6..239dcca 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -46,7 +46,9 @@ flush_pending_marks as db_flush_pending_marks, ) from litkit.build.publication import BatchPublication +from litkit.db.connection import batch_transaction, commit_transaction from litkit.db.schema import ensure_paper_embedding_column +from litkit.db.sharding import producer_shard_lock from litkit.build.helpers import ( pack_body, dedupe_papers_with_doc_ids, @@ -235,7 +237,7 @@ def flush_batch(tar: str, members: int) -> None: if not (paper_ids_buf or chunk_ids_buf): if publication.token is not None: publication.discard_uncommitted() - conn.commit() + commit_transaction(conn) publication.checkpoint_tar(tar, members) return @@ -312,7 +314,7 @@ def stage_indexes(paper_dir, chunk_dir): with FileLock(db_lock), FileLock(faiss_lock): publication.publish(tar, members, stage_indexes) else: - conn.commit() + commit_transaction(conn) publication.checkpoint_tar(tar, members) papers_added_total += papers_added chunks_added_total += chunks_added @@ -412,7 +414,7 @@ def _render(force: bool = False): skipped = 0 # Use iter_tar_articles for parallel XML parsing (--parse-workers) - with conn: + with batch_transaction(conn): for m, meta in iter_tar_articles(tpath, parse_workers=parse_workers): if skipped < start_persisted: skipped += 1 @@ -618,7 +620,7 @@ def _render(force: bool = False): # Different shards can run in parallel. Two starts of the same shard must # serialize recovery, scanning, and publication against the same checkpoint. owner_lock = ( - FileLock(sqlite_dir / f"producer_{ckpt_shard_id}.lock") + producer_shard_lock(sqlite_dir, ckpt_shard_id, FileLock) if embed_producer and not _producer_locked else nullcontext() ) with owner_lock: diff --git a/src/litkit/build/publication.py b/src/litkit/build/publication.py index c21ab26..a5f2680 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -10,6 +10,7 @@ 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.publication import PublicationRecord, read_publication from litkit.segments.checkpoint import load_checkpoint, save_checkpoint from litkit.segments.writer import finalized_name @@ -35,6 +36,10 @@ def __init__(self, conn, ckpt_path, ckpt_lock, shard_id, paper_dir, chunk_dir): def checkpoint_tar(self, tar: str, members: int) -> None: 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: @@ -72,23 +77,32 @@ def reserve(self) -> None: "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, ?, ?, ?, ?)", - (token, self._database(), *(str(root.resolve()) for root in self.outputs)), + owner, ) if not in_transaction: - self.conn.commit() + commit_transaction(self.conn) self.token = token def _retire(self): self.conn.execute("DELETE FROM ingest_publication WHERE singleton=1") - self.conn.commit() + 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.""" - record = read_publication(self.conn) + 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 @@ -100,7 +114,13 @@ def discard_uncommitted(self) -> None: for directory in set(self._directories(record.token)): if directory.exists(): shutil.rmtree(directory) - self._retire() + 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, @@ -125,9 +145,9 @@ def publish( "UPDATE ingest_publication SET tar=?, members=?, paper=?, chunk=? WHERE token=?", (*record, self.token), ) - self.conn.commit() + commit_transaction(self.conn) except BaseException: - self.conn.rollback() + 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: @@ -158,7 +178,7 @@ def _finish(self, directories, tar, members, paper, chunk): 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 self.conn: + with batch_transaction(self.conn): self.conn.execute("UPDATE ingest_publication SET tar=NULL WHERE singleton=1") for directory in set(directories): directory.rmdir() @@ -168,6 +188,8 @@ 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() diff --git a/src/litkit/cli.py b/src/litkit/cli.py index 97c9203..d786085 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1065,9 +1065,11 @@ def build_or_update_indices(args): """ 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 FileLock(SQLITE_DIR / f"producer_{args.shard_id}.lock"): + with producer_shard_lock(SQLITE_DIR, args.shard_id, FileLock): return _build_or_update_indices(args) return _build_or_update_indices(args) 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/sharding.py b/src/litkit/db/sharding.py index d5c740b..945a287 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -10,6 +10,7 @@ from pathlib import Path from litkit.concurrent.locking import FileLock +from litkit.db.connection import commit_transaction, rollback_transaction from litkit.db.publication import unpublished_shards from litkit.db.schema import citation_columns, ensure_paper_embedding_column, paper_embedding_column @@ -87,28 +88,32 @@ def merge_shard_databases( return stats +@contextmanager +def producer_shard_lock(sqlite_dir, shard_id, lock_factory=FileLock): + """Register the shard under the admission lock before opening its database.""" + with ExitStack() as owner: + with lock_factory(sqlite_dir / "producer-admission.lock"): + owner.enter_context(lock_factory(sqlite_dir / f"producer_{shard_id}.lock")) + yield + + @contextmanager def merged_shard_databases( main_conn: sqlite3.Connection, delete_after_merge: bool = True, *, - expected_shards: int = 0, lock_factory=FileLock, ): """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(".") - candidates = set(list_shard_dbs(sqlite_dir)) - candidates.update(shard_db_path(sqlite_dir, i) for i in range(expected_shards)) - lock_paths = set() - for shard in candidates: - suffix = shard.stem.removeprefix("litkit_shard_") - shard_id = int(suffix) if suffix.isdecimal() else suffix - lock_paths.add(sqlite_dir / f"producer_{shard_id}.lock") - with ExitStack() as locks: - for path in sorted(lock_paths): - locks.enter_context(lock_factory(path)) - shards = sorted(shard for shard in candidates if shard.is_file()) + 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 + shards = list_shard_dbs(sqlite_dir) pending = unpublished_shards(shards) if pending: names = ", ".join(shard.name for shard in pending) @@ -243,9 +248,9 @@ def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge): ) # Commit this shard before detaching or deleting its only copy. - main_conn.commit() + commit_transaction(main_conn) except BaseException: - main_conn.rollback() + rollback_transaction(main_conn) raise finally: main_cur.execute(f"DETACH DATABASE {shard_alias}") diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 2026971..fd4dd92 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -1,5 +1,6 @@ """Interrupted tar batches, from SQLite savepoints to the consumer's FAISS IDs.""" +import os import shutil import sqlite3 import subprocess @@ -134,7 +135,8 @@ class InjectedFailure(Exception): pass -def test_ingest_and_merge_through_existing_pre_embedding_text_connections(tmp_path): +@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"), @@ -146,12 +148,59 @@ def test_ingest_and_merge_through_existing_pre_embedding_text_connections(tmp_pa 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 assert build.run(conn=producer)[2:] == (1, 2) 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("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)]) diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index 754c5c2..7c0a010 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -732,7 +732,7 @@ def pause_after_check(shards): else: class ContendingLock(cli.FileLock): def __enter__(self): - if self.path.name == "producer_0.lock": + if self.path.name == "producer-admission.lock": (root / "contending").touch() return super().__enter__() cli.FileLock = ContendingLock diff --git a/tests/test_db.py b/tests/test_db.py index d5a3502..1b0ce48 100644 --- a/tests/test_db.py +++ b/tests/test_db.py @@ -238,24 +238,32 @@ def test_merge_failure_preserves_source_shard_and_rolls_back_its_rows(tmp_path): assert path.is_file() -def test_merge_accepts_padded_and_unpadded_paths_for_the_same_producer(tmp_path): +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 + from litkit.db.sharding import merged_shard_databases, producer_shard_lock - for name in ("litkit_shard_0.sqlite3", "litkit_shard_00.sqlite3"): - with closing(init_db(tmp_path / name)) as shard, shard: - shard.execute("INSERT INTO papers(doc_id) VALUES (?)", (name,)) - acquired = [] + 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 lock_once(path): - assert path not in acquired, "a second flock on the same path would deadlock" - acquired.append(path) + 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, expected_shards=1, lock_factory=lock_once) as stats: - assert stats["papers"] == stats["shards"] == 2 - assert acquired == [tmp_path / "producer_0.lock"] + 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))} diff --git a/vector_build_multi.sbatch b/vector_build_multi.sbatch index 110d1a9..71a504e 100644 --- a/vector_build_multi.sbatch +++ b/vector_build_multi.sbatch @@ -305,11 +305,13 @@ EOF # Publish into the shared workspace under the same shard lock as the # consumer. The local lock inode stays local. The done marker travels last. ( + flock -x 8 flock -x 9 - /usr/bin/rsync -a --delay-updates --exclude="producer_*.lock" "${PRODUCER_LOCAL_STAGE_HOST}/sqlite/" "${LITKIT_WORKSPACE}/sqlite/" + flock -u 8 + /usr/bin/rsync -a --delay-updates --exclude="producer-admission.lock" --exclude="producer_*.lock" "${PRODUCER_LOCAL_STAGE_HOST}/sqlite/" "${LITKIT_WORKSPACE}/sqlite/" /usr/bin/rsync -a --delay-updates --exclude="producer_*.done" "${PRODUCER_LOCAL_STAGE_HOST}/emb_segments/" "${LITKIT_WORKSPACE}/emb_segments/" /usr/bin/rsync -a "${PRODUCER_LOCAL_STAGE_HOST}/emb_segments/producer_${PRODUCER_NODE_ID}.done" "${LITKIT_WORKSPACE}/emb_segments/" - ) 9>>"${LITKIT_WORKSPACE}/sqlite/producer_${PRODUCER_NODE_ID}.lock" + ) 8>>"${LITKIT_WORKSPACE}/sqlite/producer-admission.lock" 9>>"${LITKIT_WORKSPACE}/sqlite/producer_${PRODUCER_NODE_ID}.lock" echo "[Producer ${PRODUCER_NODE_ID}] [staging] Cleanup local staging dir" rm -rf "${PRODUCER_LOCAL_STAGE_HOST}" else From 614174a79e04ab5492d71c819903ed44643b1740 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 17:08:23 -0700 Subject: [PATCH 08/31] Preserve revision order and rebuild semantics across interrupted batches Signed-off-by: Bill Hlavacek --- src/litkit/build/ingest_loop.py | 23 +++++++- src/litkit/build/publication.py | 13 +++-- src/litkit/db/publication.py | 6 +- src/litkit/db/sharding.py | 7 ++- src/litkit/segments/ingest.py | 5 +- src/litkit/segments/writer.py | 22 ++++++-- tests/conftest.py | 4 +- tests/integration/test_batch_resume.py | 69 +++++++++++++++++++++-- tests/integration/test_build_and_query.py | 15 ++++- vector_build_multi.sbatch | 5 +- 10 files changed, 139 insertions(+), 30 deletions(-) diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index 239dcca..d95afd8 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -273,11 +273,16 @@ def flush_batch(tar: str, members: int) -> None: 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) def stage_segments(paper_dir, chunk_dir): return ( - paper_seg_writer.stage(paper_dir, doc_ids=doc_ids, vecs=xp) if pids else None, - chunk_seg_writer.stage(chunk_dir, paper_doc_ids=parents, ords=ords, vecs=xc), + paper_seg_writer.stage(paper_dir, doc_ids=doc_ids, vecs=xp, sequence=sequence) + if pids else None, + chunk_seg_writer.stage(chunk_dir, paper_doc_ids=parents, ords=ords, vecs=xc, + sequence=sequence) if cids else None, ) publication.publish(tar, members, stage_segments) @@ -332,6 +337,7 @@ def stage_indexes(paper_dir, chunk_dir): replaced_chunks.clear() def process_tar(tpath: Path) -> None: + keep_first_revision = 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 @@ -532,7 +538,7 @@ def _render(force: bool = False): ).fetchone() previous_text = prior[0] if prior else None reuse_embedding = (not seen_this_path and previous_text is not None - and (rebuild or previous_text == ta_ab)) + and (keep_first_revision or previous_text == ta_ab)) cur.execute( "UPDATE papers SET embedding_text=? WHERE id=?", (previous_text if reuse_embedding else ta_ab, pid), @@ -639,9 +645,20 @@ def _render(force: bool = False): paper_index = faiss_load(paper_index_path) chunk_index = faiss_load(chunk_index_path) 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() # 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 index a5f2680..0f0279b 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -13,7 +13,7 @@ from litkit.db.connection import batch_transaction, commit_transaction, rollback_transaction from litkit.db.publication import PublicationRecord, read_publication from litkit.segments.checkpoint import load_checkpoint, save_checkpoint -from litkit.segments.writer import finalized_name +from litkit.segments.writer import finalized_name, segment_sequence def reset_publication(conn: sqlite3.Connection) -> None: @@ -37,9 +37,9 @@ def __init__(self, conn, ckpt_path, ckpt_lock, shard_id, paper_dir, chunk_dir): def checkpoint_tar(self, tar: str, members: int) -> None: self.checkpoint.setdefault("build_stream", {})[tar] = members self.checkpoint.pop("batch_reservation", None) - self._save_checkpoint() + self.save_checkpoint() - def _save_checkpoint(self) -> None: + def save_checkpoint(self) -> None: save_checkpoint(self.checkpoint, self.ckpt_path, self.ckpt_lock, shard_id=self.shard_id) def _database(self) -> str: @@ -82,7 +82,7 @@ def reserve(self) -> None: # 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.save_checkpoint() self.conn.execute( "INSERT INTO ingest_publication(singleton, token, source_db, paper_root, chunk_root) " "VALUES (1, ?, ?, ?, ?)", @@ -116,7 +116,7 @@ def discard_uncommitted(self) -> None: shutil.rmtree(directory) if "batch_reservation" in self.checkpoint: del self.checkpoint["batch_reservation"] - self._save_checkpoint() + self.save_checkpoint() if journal is not None: self._retire() else: @@ -175,6 +175,9 @@ def _finish(self, directories, tar, members, paper, chunk): pending.replace(target) maybe_fsync_dir(target) maybe_fsync_dir(pending) + sequence = segment_sequence(chunk or paper or "") + if sequence is not None: + 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. diff --git a/src/litkit/db/publication.py b/src/litkit/db/publication.py index 4cd109e..ca1633b 100644 --- a/src/litkit/db/publication.py +++ b/src/litkit/db/publication.py @@ -30,8 +30,8 @@ def read_publication(conn: sqlite3.Connection) -> PublicationRecord | None: return PublicationRecord(*row) if row else None -def unpublished_shards(shards: list[Path]) -> list[Path]: - """Find producers that committed rows and still have files to publish.""" +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: uri = shard.resolve().as_uri() @@ -44,6 +44,6 @@ def unpublished_shards(shards: list[Path]) -> list[Path]: # Inspecting a hot rollback journal requires SQLite to undo uncommitted pages. with closing(sqlite3.connect(uri + "?mode=rw", uri=True)) as conn: row = read_publication(conn) - if row and row.tar is not None: + if row and (include_reservations or row.tar is not None): pending.append(shard) return pending diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index 945a287..0478cea 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -91,7 +91,8 @@ def merge_shard_databases( @contextmanager def producer_shard_lock(sqlite_dir, shard_id, lock_factory=FileLock): """Register the shard under the admission lock before opening its database.""" - with ExitStack() as owner: + # 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")) yield @@ -114,11 +115,11 @@ def merged_shard_databases( with lock_factory(path): pass shards = list_shard_dbs(sqlite_dir) - pending = unpublished_shards(shards) + pending = unpublished_shards(shards, include_reservations=True) if pending: names = ", ".join(shard.name for shard in pending) raise RuntimeError( - f"Cannot merge: {names} has a committed batch awaiting publication. " + f"Cannot merge: {names} has unfinished batch publication or cleanup. " "Resume the interrupted producer in its original workspace and segment directory." ) yield _merge_locked_shards(main_conn, shards, delete_after_merge) diff --git a/src/litkit/segments/ingest.py b/src/litkit/segments/ingest.py index 263ab5b..f696050 100644 --- a/src/litkit/segments/ingest.py +++ b/src/litkit/segments/ingest.py @@ -25,6 +25,7 @@ from litkit.db.indexing import flush_pending_marks, mark_in_index from litkit.db.queries import preload_paper_id_map, preload_chunk_id_map from litkit.segments.discovery import iter_segment_files +from litkit.segments.writer import segment_sequence from litkit.index.dedup import add_with_ids_dedup from litkit.index.io import faiss_save, faiss_save_force from litkit.index.ids import make_id_selector, safe_remove_ids @@ -62,7 +63,9 @@ def _glob_segment_files(outdir: Path, kind: str) -> list[Path]: Returns: Sorted list of segment file paths (including .ingesting files) """ - return sorted(iter_segment_files(outdir, kind)) + # 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_sequence(p.name) is not None, p)) def mark_saved_segments(conn: sqlite3.Connection, table: str, batches: list[np.ndarray]) -> None: diff --git a/src/litkit/segments/writer.py b/src/litkit/segments/writer.py index a626c17..7a83c5d 100644 --- a/src/litkit/segments/writer.py +++ b/src/litkit/segments/writer.py @@ -11,6 +11,7 @@ from __future__ import annotations import os +import re import sys import uuid from dataclasses import dataclass @@ -58,6 +59,12 @@ def finalized_name(pending: Path) -> str: return pending.name.removesuffix(suffix) + SEGMENT_EXTENSION +def segment_sequence(name: str) -> int | None: + """Read the durable producer batch order, when present in the segment name.""" + match = re.match(r"^(?:paper|chunk)_seg_-?\d+_b(\d+)_", name) + return int(match[1]) if match else None + + def _finalize_paths(paths: list[Path]) -> int: count = len(paths) while paths: @@ -244,12 +251,15 @@ def _write_batch(self, doc_ids, vecs) -> Path: return path - def stage(self, directory: Path, *, doc_ids: list[str], vecs: np.ndarray) -> Path: + def stage( + self, directory: Path, *, doc_ids: list[str], vecs: np.ndarray, sequence: int | 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 - seg_id = f"{self.shard_id}_{self._segment_counter}_{uuid.uuid4().hex}" + 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, @@ -434,12 +444,16 @@ def _write_batch(self, paper_doc_ids, ords, vecs) -> Path: return path - def stage(self, directory: Path, *, paper_doc_ids: list[str], ords: list[int], vecs: np.ndarray) -> Path: + def stage( + self, directory: Path, *, paper_doc_ids: list[str], ords: list[int], vecs: np.ndarray, + sequence: int | 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 - seg_id = f"{self.shard_id}_{self._segment_counter}_{uuid.uuid4().hex}" + 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, 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 index fd4dd92..8e13c12 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -135,6 +135,58 @@ class InjectedFailure(Exception): pass +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("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) + + @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" @@ -265,7 +317,7 @@ def fail_checkpoint(*args, **kwargs): 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="committed batch awaiting publication"): + 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() @@ -279,28 +331,37 @@ def fail_checkpoint(*args, **kwargs): 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 second_attempt.wait(10), "second producer did not reach the shard lock" + 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.lock": + 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=2) as workers: + 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] diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index 7c0a010..d6175fd 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -631,6 +631,15 @@ def stop_after_rename(self, target): 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, @@ -654,7 +663,7 @@ def stop_after_rename(self, target): ws, "--build-only", "--consume-only", "--faiss-writer", "--num-shards", "2" ) assert consume.returncode != 0 - assert "committed batch awaiting publication" in consume.stderr + assert "unfinished batch publication or cleanup" in consume.stderr for marker in markers: marker.unlink() @@ -719,8 +728,8 @@ def test_consumer_finishes_merge_before_next_producer_opens_shard(isolated_env, sys.argv = [runner, *sys.argv[4:]] if role == "consumer": inspect = sharding.unpublished_shards - def pause_after_check(shards): - result = inspect(shards) + def pause_after_check(shards, **options): + result = inspect(shards, **options) (root / "checked").touch() deadline = time.monotonic() + 20 while not (root / "contending").exists(): diff --git a/vector_build_multi.sbatch b/vector_build_multi.sbatch index 71a504e..5a8e4a7 100644 --- a/vector_build_multi.sbatch +++ b/vector_build_multi.sbatch @@ -305,13 +305,14 @@ EOF # Publish into the shared workspace under the same shard lock as the # consumer. The local lock inode stays local. The done marker travels last. ( + flock -x 7 flock -x 8 flock -x 9 flock -u 8 - /usr/bin/rsync -a --delay-updates --exclude="producer-admission.lock" --exclude="producer_*.lock" "${PRODUCER_LOCAL_STAGE_HOST}/sqlite/" "${LITKIT_WORKSPACE}/sqlite/" + /usr/bin/rsync -a --delay-updates --exclude="producer-admission.lock" --exclude="producer_*.lock" --exclude="producer_*.queue" "${PRODUCER_LOCAL_STAGE_HOST}/sqlite/" "${LITKIT_WORKSPACE}/sqlite/" /usr/bin/rsync -a --delay-updates --exclude="producer_*.done" "${PRODUCER_LOCAL_STAGE_HOST}/emb_segments/" "${LITKIT_WORKSPACE}/emb_segments/" /usr/bin/rsync -a "${PRODUCER_LOCAL_STAGE_HOST}/emb_segments/producer_${PRODUCER_NODE_ID}.done" "${LITKIT_WORKSPACE}/emb_segments/" - ) 8>>"${LITKIT_WORKSPACE}/sqlite/producer-admission.lock" 9>>"${LITKIT_WORKSPACE}/sqlite/producer_${PRODUCER_NODE_ID}.lock" + ) 7>>"${LITKIT_WORKSPACE}/sqlite/producer_${PRODUCER_NODE_ID}.queue" 8>>"${LITKIT_WORKSPACE}/sqlite/producer-admission.lock" 9>>"${LITKIT_WORKSPACE}/sqlite/producer_${PRODUCER_NODE_ID}.lock" echo "[Producer ${PRODUCER_NODE_ID}] [staging] Cleanup local staging dir" rm -rf "${PRODUCER_LOCAL_STAGE_HOST}" else From 8dc1170f9b7537704d0cb92bd23ecb31f2254161 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 17:18:20 -0700 Subject: [PATCH 09/31] Preserve revision order after interrupted reads and failed writer saves Signed-off-by: Bill Hlavacek --- src/litkit/build/consume.py | 3 + src/litkit/build/ingest_loop.py | 34 +++++++- src/litkit/segments/ingest.py | 15 ++-- tests/integration/test_batch_resume.py | 103 +++++++++++++++++++++++++ 4 files changed, 146 insertions(+), 9 deletions(-) diff --git a/src/litkit/build/consume.py b/src/litkit/build/consume.py index ce75c1e..5c49aa8 100644 --- a/src/litkit/build/consume.py +++ b/src/litkit/build/consume.py @@ -23,6 +23,7 @@ ingest_chunk_segments, ) from litkit.segments.ingest import mark_saved_segments +from litkit.segments.metadata import has_segment_files from litkit.progress import eprint if TYPE_CHECKING: @@ -127,5 +128,7 @@ def default_progress(complete: int, total: int) -> None: mark_saved_segments(conn, "papers", pending_papers) mark_saved_segments(conn, "chunks", pending_chunks) + if has_segment_files(seg_dir): + raise RuntimeError("Segment ingestion stopped before completion. Retry the remaining segments.") eprint("[consumer] Consume-only mode completed") return True diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index d95afd8..da17e6d 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -212,8 +212,13 @@ def process_tar_files( 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) 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") @@ -291,9 +296,12 @@ def stage_segments(paper_dir, chunk_dir): 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", @@ -304,6 +312,8 @@ def stage_indexes(paper_dir, chunk_dir): 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", @@ -317,7 +327,17 @@ def stage_indexes(paper_dir, chunk_dir): return paper_file, chunk_file with FileLock(db_lock), FileLock(faiss_lock): - publication.publish(tar, members, stage_indexes) + 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) @@ -337,7 +357,7 @@ def stage_indexes(paper_dir, chunk_dir): replaced_chunks.clear() def process_tar(tpath: Path) -> None: - keep_first_revision = str(tpath) in rebuild_tars + 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 @@ -442,7 +462,7 @@ def _render(force: bool = False): _render() # Fast path 1: already processed (vast majority in --update mode) - if not rebuild and db_already_processed(cur, str(f), st): + if not rebuilding_tar and db_already_processed(cur, str(f), st): processed_count += 1 continue @@ -538,7 +558,7 @@ def _render(force: bool = False): ).fetchone() previous_text = prior[0] if prior else None reuse_embedding = (not seen_this_path and previous_text is not None - and (keep_first_revision or previous_text == ta_ab)) + 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), @@ -644,6 +664,12 @@ def _render(force: bool = False): 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. diff --git a/src/litkit/segments/ingest.py b/src/litkit/segments/ingest.py index f696050..da7f68d 100644 --- a/src/litkit/segments/ingest.py +++ b/src/litkit/segments/ingest.py @@ -158,8 +158,9 @@ def ingest_paper_segments( os.replace(p, tmp) except FileNotFoundError: continue # Another process claimed it - except Exception: - continue + except OSError as e: + _eprint(f"[segments] Could not claim {p.name}: {e}") + break try: with np.load(tmp, mmap_mode="r", allow_pickle=True) as z: @@ -261,6 +262,9 @@ def ingest_paper_segments( except Exception: pass _eprint(f"[segments] ERROR ingesting {p.name}: {e.__class__.__name__}: {e}") + # A later segment may revise these same IDs. Preserve their order + # for retry and let the caller save any successful prefix. + break return paper_index, added_total @@ -362,9 +366,9 @@ def ingest_chunk_segments( os.replace(p, tmp) except FileNotFoundError: continue - except Exception: - # Could not claim; skip - continue + except OSError as e: + _eprint(f"[segments] Could not claim {p.name}: {e}") + break try: with np.load(tmp, mmap_mode="r", allow_pickle=True) as z: @@ -473,5 +477,6 @@ def ingest_chunk_segments( except Exception: pass _eprint(f"[segments] ERROR ingesting {p.name}: {e.__class__.__name__}: {e}") + break return chunk_index, added_total diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 8e13c12..7f35dc6 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -165,6 +165,50 @@ def test_resumed_producer_consumes_paper_and_chunk_revisions_in_commit_order(tmp 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" @@ -187,6 +231,25 @@ def test_resumed_writer_keeps_the_rebuild_revision_policy(tmp_path, same_tar): 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" @@ -447,6 +510,46 @@ def fail_chunk_save(index, path): 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): + assert sorted(faiss.vector_to_array(faiss_load(path).id_map)) == ([1, 2] if existing else [1]) + + def test_rebuild_can_inspect_a_shard_with_a_hot_rollback_journal(tmp_path): from litkit.db.publication import unpublished_shards From 1fa9de20df2a86569ed06d00fb9a733c07606f3d Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 17:32:13 -0700 Subject: [PATCH 10/31] Verify legacy producer progress and preserve public segment write order Signed-off-by: Bill Hlavacek --- src/litkit/build/consume.py | 2 +- src/litkit/build/ingest_loop.py | 6 ++ src/litkit/build/publication.py | 7 ++- src/litkit/cli.py | 9 ++- src/litkit/db/sharding.py | 25 +++++++- src/litkit/segments/discovery.py | 17 ++++- src/litkit/segments/ingest.py | 24 +++++--- src/litkit/segments/metadata.py | 75 ++++++++++++++++++++++- src/litkit/segments/writer.py | 20 +++--- tests/integration/test_batch_resume.py | 41 +++++++++++++ tests/integration/test_build_and_query.py | 31 ++++++++++ tests/test_segments.py | 33 ++++++++-- 12 files changed, 255 insertions(+), 35 deletions(-) diff --git a/src/litkit/build/consume.py b/src/litkit/build/consume.py index 5c49aa8..f9ded2b 100644 --- a/src/litkit/build/consume.py +++ b/src/litkit/build/consume.py @@ -97,7 +97,7 @@ def default_progress(complete: int, total: int) -> None: eprint("[consumer] All producers have completed") eprint("[consumer] Merging shard databases...") - with merged_shard_databases(conn, lock_factory=FileLock) as merge_stats: + with merged_shard_databases(conn, lock_factory=FileLock, segment_dir=seg_dir) as merge_stats: if merge_stats["shards"] > 0: eprint( f"[consumer] Merged {merge_stats['shards']} shard DB(s): " diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index da17e6d..a4b9a96 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -49,6 +49,7 @@ from litkit.db.connection import batch_transaction, commit_transaction from litkit.db.schema import ensure_paper_embedding_column from litkit.db.sharding import producer_shard_lock +from litkit.segments.metadata import verify_legacy_checkpoint from litkit.build.helpers import ( pack_body, dedupe_papers_with_doc_ids, @@ -659,6 +660,11 @@ def _render(force: bool = False): 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: + verify_legacy_checkpoint( + conn, publication.checkpoint, paper_seg_writer.shard_id, + paper_seg_writer.outdir, chunk_seg_writer.outdir, + ) if embed_producer or faiss_writer: with FileLock(faiss_lock) if faiss_writer else nullcontext(): if publication.recover() and faiss_writer: diff --git a/src/litkit/build/publication.py b/src/litkit/build/publication.py index 0f0279b..fe09f8d 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -13,7 +13,8 @@ from litkit.db.connection import batch_transaction, commit_transaction, rollback_transaction from litkit.db.publication import PublicationRecord, read_publication from litkit.segments.checkpoint import load_checkpoint, save_checkpoint -from litkit.segments.writer import finalized_name, segment_sequence +from litkit.segments.discovery import segment_order +from litkit.segments.writer import finalized_name def reset_publication(conn: sqlite3.Connection) -> None: @@ -175,8 +176,8 @@ def _finish(self, directories, tar, members, paper, chunk): pending.replace(target) maybe_fsync_dir(target) maybe_fsync_dir(pending) - sequence = segment_sequence(chunk or paper or "") - if sequence is not None: + 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 diff --git a/src/litkit/cli.py b/src/litkit/cli.py index d786085..7b96c98 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1460,16 +1460,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( @@ -1525,6 +1526,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": diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index 0478cea..496202b 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -6,7 +6,7 @@ import sqlite3 import sys import time -from contextlib import ExitStack, contextmanager +from contextlib import ExitStack, closing, contextmanager from pathlib import Path from litkit.concurrent.locking import FileLock @@ -66,6 +66,8 @@ def _eprint(msg: str = "", *, end: str = "\n") -> None: def merge_shard_databases( main_conn: sqlite3.Connection, delete_after_merge: bool = True, + *, + segment_dir: Path | None = None, ) -> dict[str, int]: """Merge all per-shard SQLite databases into the main database. @@ -79,12 +81,13 @@ 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: Output directory for checking producer checkpoints from older releases Returns: Dict with merge statistics: {"papers": N, "chunks": M, "files": F, "shards": S} """ - with merged_shard_databases(main_conn, delete_after_merge) as stats: + with merged_shard_databases(main_conn, delete_after_merge, segment_dir=segment_dir) as stats: return stats @@ -104,6 +107,7 @@ def merged_shard_databases( delete_after_merge: bool = True, *, lock_factory=FileLock, + segment_dir: 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] @@ -122,6 +126,23 @@ def merged_shard_databases( f"Cannot merge: {names} has unfinished batch publication or cleanup. " "Resume the interrupted producer in its original workspace and segment directory." ) + if segment_dir is None and sqlite_dir.name == "sqlite": + segment_dir = sqlite_dir.parent / "emb_segments" + if segment_dir is not None: + from litkit.segments.checkpoint import load_checkpoint + from litkit.segments.metadata import verify_legacy_checkpoint + + for shard in shards: + suffix = shard.stem.removeprefix("litkit_shard_") + if not suffix.isdecimal(): + continue + shard_id = int(suffix) + checkpoint = load_checkpoint(sqlite_dir / "build_checkpoint.json", shard_id) + if checkpoint: + uri = shard.resolve().as_uri() + "?mode=ro" + with closing(sqlite3.connect(uri, uri=True)) as source: + verify_legacy_checkpoint(source, checkpoint, shard_id, segment_dir, segment_dir, + merged_db=main_conn) yield _merge_locked_shards(main_conn, shards, delete_after_merge) diff --git a/src/litkit/segments/discovery.py b/src/litkit/segments/discovery.py index 3fb850a..001877f 100644 --- a/src/litkit/segments/discovery.py +++ b/src/litkit/segments/discovery.py @@ -13,13 +13,28 @@ 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 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 path.name.endswith(PENDING_SUFFIX + suffix) and path.is_file(): + if not is_pending_segment(path.name) and path.is_file(): yield path diff --git a/src/litkit/segments/ingest.py b/src/litkit/segments/ingest.py index da7f68d..dc3e11e 100644 --- a/src/litkit/segments/ingest.py +++ b/src/litkit/segments/ingest.py @@ -24,8 +24,7 @@ from litkit.db.indexing import flush_pending_marks, mark_in_index from litkit.db.queries import preload_paper_id_map, preload_chunk_id_map -from litkit.segments.discovery import iter_segment_files -from litkit.segments.writer import segment_sequence +from litkit.segments.discovery import iter_segment_files, segment_order from litkit.index.dedup import add_with_ids_dedup from litkit.index.io import faiss_save, faiss_save_force from litkit.index.ids import make_id_selector, safe_remove_ids @@ -65,7 +64,7 @@ def _glob_segment_files(outdir: Path, kind: str) -> list[Path]: """ # 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_sequence(p.name) is not None, p)) + return sorted(iter_segment_files(outdir, kind), key=lambda p: segment_order(p.name)) def mark_saved_segments(conn: sqlite3.Connection, table: str, batches: list[np.ndarray]) -> None: @@ -77,6 +76,13 @@ def mark_saved_segments(conn: sqlite3.Connection, table: str, batches: list[np.n batches.clear() +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) + + def ingest_paper_segments( conn: sqlite3.Connection, paper_index: faiss.Index, @@ -88,6 +94,7 @@ def ingest_paper_segments( save_every: int = 2, paper_id_map: dict[str, int] | None = None, unsaved_ids: list[np.ndarray] | None = None, + errors: list[str] | None = None, FileLock: type | None = None, ) -> tuple[faiss.Index, int]: """Ingest paper embedding segments from producer nodes. @@ -109,6 +116,7 @@ def ingest_paper_segments( paper_id_map: Optional preloaded doc_id → paper_id mapping for O(1) lookups. If None, will be loaded once at start. unsaved_ids: Receives ID batches still awaiting the caller's final forced save. + errors: Receives failures that stopped this pass, so callers can save the prefix before exiting. FileLock: File lock class to use (pass from caller to avoid circular import) Returns: @@ -159,7 +167,7 @@ def ingest_paper_segments( except FileNotFoundError: continue # Another process claimed it except OSError as e: - _eprint(f"[segments] Could not claim {p.name}: {e}") + _report_segment_error(errors, p, e) break try: @@ -261,7 +269,7 @@ def ingest_paper_segments( os.replace(tmp, p) except Exception: pass - _eprint(f"[segments] ERROR ingesting {p.name}: {e.__class__.__name__}: {e}") + _report_segment_error(errors, p, e) # A later segment may revise these same IDs. Preserve their order # for retry and let the caller save any successful prefix. break @@ -281,6 +289,7 @@ def ingest_chunk_segments( paper_id_map: dict[str, int] | None = None, chunk_id_map: dict[tuple[int, int], int] | None = None, unsaved_ids: list[np.ndarray] | None = None, + errors: list[str] | None = None, FileLock: type | None = None, ) -> tuple[faiss.Index, int]: """Ingest chunk embedding segments from producer nodes. @@ -309,6 +318,7 @@ def ingest_chunk_segments( chunk_id_map: Optional preloaded (paper_id, ord) → chunk_id mapping for O(1) lookups. If None, will be loaded once at start. unsaved_ids: Receives ID batches still awaiting the caller's final forced save. + errors: Receives failures that stopped this pass, so callers can save the prefix before exiting. FileLock: File lock class to use (pass from caller to avoid circular import) Returns: @@ -367,7 +377,7 @@ def ingest_chunk_segments( except FileNotFoundError: continue except OSError as e: - _eprint(f"[segments] Could not claim {p.name}: {e}") + _report_segment_error(errors, p, e) break try: @@ -476,7 +486,7 @@ def ingest_chunk_segments( os.replace(tmp, p) except Exception: pass - _eprint(f"[segments] ERROR ingesting {p.name}: {e.__class__.__name__}: {e}") + _report_segment_error(errors, p, e) break return chunk_index, added_total diff --git a/src/litkit/segments/metadata.py b/src/litkit/segments/metadata.py index 12e2a16..68e7039 100644 --- a/src/litkit/segments/metadata.py +++ b/src/litkit/segments/metadata.py @@ -4,11 +4,14 @@ from __future__ import annotations import json +import sqlite3 import sys +from contextlib import closing, nullcontext +from itertools import chain from pathlib import Path from litkit.segments.constants import BUILD_META_FILENAME -from litkit.segments.discovery import iter_segment_files +from litkit.segments.discovery import is_pending_segment, iter_segment_files def _eprint(msg: str = "", *, end: str = "\n") -> None: @@ -25,6 +28,76 @@ def has_segment_files(seg_dir: Path) -> bool: return any(path for kind in ("papers", "chunks") for path in iter_segment_files(Path(seg_dir), kind)) +def verify_legacy_checkpoint( + conn: sqlite3.Connection, checkpoint: dict, shard_id: int, paper_dir: Path, chunk_dir: Path, + *, merged_db: sqlite3.Connection | None = None, +) -> None: + """Before trusting an old producer checkpoint, account for its unindexed rows.""" + if not any(checkpoint.get("build_stream", {}).values()): + return + if conn.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='ingest_publication'" + ).fetchone() or not conn.execute("SELECT 1 FROM files LIMIT 1").fetchone(): + return + + import numpy as np + + message = ( + f"Cannot verify the checkpoint 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." + ) + for kind, directory, prefix, query in ( + ("papers", paper_dir, "paper_seg", "SELECT id, doc_id FROM papers WHERE in_index=0"), + ("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"), + ): + 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() + numeric_ids = set() + for path in iter_segment_files(directory, kind): + if path.name.startswith(prefix + "_") and not path.name.startswith(f"{prefix}_{shard_id}_"): + continue + 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: + numeric_ids.update(segment["ids"]) + missing = (row for row in conn.execute(query) + if row[0] not in numeric_ids and tuple(row[1:]) not in ready_keys) + first = next(missing, None) + if first is None: + continue + # 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 = closing(sqlite3.connect(main_path.resolve().as_uri() + "?mode=ro", uri=True)) + 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( seg_dir: Path, num_shards: int, diff --git a/src/litkit/segments/writer.py b/src/litkit/segments/writer.py index 7a83c5d..f4b8b63 100644 --- a/src/litkit/segments/writer.py +++ b/src/litkit/segments/writer.py @@ -11,9 +11,9 @@ from __future__ import annotations import os -import re import sys import uuid +from collections import deque from dataclasses import dataclass from pathlib import Path from typing import Any @@ -59,20 +59,14 @@ def finalized_name(pending: Path) -> str: return pending.name.removesuffix(suffix) + SEGMENT_EXTENSION -def segment_sequence(name: str) -> int | None: - """Read the durable producer batch order, when present in the segment name.""" - match = re.match(r"^(?:paper|chunk)_seg_-?\d+_b(\d+)_", name) - return int(match[1]) if match else None - - -def _finalize_paths(paths: list[Path]) -> int: +def _finalize_paths(paths: deque[Path]) -> int: count = len(paths) while paths: - path = paths[-1] + 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.pop() + paths.popleft() continue raise FileNotFoundError(path) try: @@ -81,7 +75,7 @@ def _finalize_paths(paths: list[Path]) -> int: # 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.pop() + paths.popleft() return count @@ -176,7 +170,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) @@ -363,7 +357,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) diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 7f35dc6..80bae05 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -275,6 +275,47 @@ def test_ingest_and_merge_through_existing_pre_embedding_text_connections(tmp_pa assert reopened.execute("SELECT embedding_text FROM papers").fetchall() == [("Revised",)] +@pytest.mark.parametrize("legacy_files", ["ready", "pending", "missing"]) +def test_upgrade_verifies_old_producer_checkpoint_before_resume_or_merge( + tmp_path, archive, legacy_files, monkeypatch +): + from litkit.segments import save_checkpoint + + 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("ALTER TABLE papers DROP COLUMN embedding_text") + save_checkpoint({"build_stream": {str(archive): 3}}, build.checkpoint, build.root / "ckpt.lock", 0) + 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 + 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) diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index d6175fd..f7d0e64 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -570,6 +570,37 @@ def test_rebuild_without_yes_refuses_noninteractively(isolated_env, corpus_dir): 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", ["before-commit", "before-publish", "after-commit"]) def test_two_producers_resume_after_process_exit( isolated_env, corpus_dir, monkeypatch, interruption diff --git a/tests/test_segments.py b/tests/test_segments.py index 8737e4c..cc4f340 100644 --- a/tests/test_segments.py +++ b/tests/test_segments.py @@ -78,6 +78,20 @@ 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 @@ -172,12 +186,12 @@ def full_disk(*args, **kwargs): def test_retry_finishes_other_segments_after_successful_rename_raises(seg_dir, unit_vectors, monkeypatch, kind): from pathlib import Path - vec = unit_vectors(1, 4) - w = _write_one(kind, seg_dir, vec) + vectors = unit_vectors(2, 4) + w = _write_one(kind, seg_dir, vectors[:1]) if kind == "papers": - w.write(doc_ids=["second"], vecs=vec) + w.write(doc_ids=["d"], vecs=vectors[1:]) else: - w.write(paper_doc_ids=["second"], ords=[0], vecs=vec) + 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): @@ -186,8 +200,14 @@ def exit_after_rename(path, target): 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 - assert len(_glob_segment_files(seg_dir, kind)) == 2 + [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): @@ -228,6 +248,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 From e57fa748f78803a8a95b99f796f5f567ad82b77b Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 17:38:11 -0700 Subject: [PATCH 11/31] Check legacy shard rows before the first checkpoint and reject ambiguous revisions Signed-off-by: Bill Hlavacek --- src/litkit/build/ingest_loop.py | 6 +++--- src/litkit/db/sharding.py | 19 +++++++++---------- src/litkit/segments/metadata.py | 18 ++++++++++++------ tests/integration/test_batch_resume.py | 19 ++++++++++++++----- 4 files changed, 38 insertions(+), 24 deletions(-) diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index a4b9a96..1b551a7 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -49,7 +49,7 @@ from litkit.db.connection import batch_transaction, commit_transaction from litkit.db.schema import ensure_paper_embedding_column from litkit.db.sharding import producer_shard_lock -from litkit.segments.metadata import verify_legacy_checkpoint +from litkit.segments.metadata import verify_legacy_shard from litkit.build.helpers import ( pack_body, dedupe_papers_with_doc_ids, @@ -661,8 +661,8 @@ def _render(force: bool = False): chunk_seg_writer.outdir if embed_producer else chunk_index_path.parent, ) if embed_producer: - verify_legacy_checkpoint( - conn, publication.checkpoint, paper_seg_writer.shard_id, + verify_legacy_shard( + conn, paper_seg_writer.shard_id, paper_seg_writer.outdir, chunk_seg_writer.outdir, ) if embed_producer or faiss_writer: diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index 496202b..ae44bb4 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -126,23 +126,22 @@ def merged_shard_databases( f"Cannot merge: {names} has unfinished batch publication or cleanup. " "Resume the interrupted producer in its original workspace and segment directory." ) - if segment_dir is None and sqlite_dir.name == "sqlite": - segment_dir = sqlite_dir.parent / "emb_segments" + default_segments = sqlite_dir.parent / "emb_segments" + if segment_dir is None and sqlite_dir.name == "sqlite" and ( + default_segments.is_dir() or any(sqlite_dir.glob("build_checkpoint_shard_*.json")) + ): + segment_dir = default_segments if segment_dir is not None: - from litkit.segments.checkpoint import load_checkpoint - from litkit.segments.metadata import verify_legacy_checkpoint + from litkit.segments.metadata import verify_legacy_shard for shard in shards: suffix = shard.stem.removeprefix("litkit_shard_") if not suffix.isdecimal(): continue shard_id = int(suffix) - checkpoint = load_checkpoint(sqlite_dir / "build_checkpoint.json", shard_id) - if checkpoint: - uri = shard.resolve().as_uri() + "?mode=ro" - with closing(sqlite3.connect(uri, uri=True)) as source: - verify_legacy_checkpoint(source, checkpoint, shard_id, segment_dir, segment_dir, - merged_db=main_conn) + uri = shard.resolve().as_uri() + "?mode=ro" + with closing(sqlite3.connect(uri, uri=True)) as source: + verify_legacy_shard(source, shard_id, segment_dir, segment_dir, merged_db=main_conn) yield _merge_locked_shards(main_conn, shards, delete_after_merge) diff --git a/src/litkit/segments/metadata.py b/src/litkit/segments/metadata.py index 68e7039..627bdae 100644 --- a/src/litkit/segments/metadata.py +++ b/src/litkit/segments/metadata.py @@ -28,13 +28,11 @@ def has_segment_files(seg_dir: Path) -> bool: return any(path for kind in ("papers", "chunks") for path in iter_segment_files(Path(seg_dir), kind)) -def verify_legacy_checkpoint( - conn: sqlite3.Connection, checkpoint: dict, shard_id: int, paper_dir: Path, chunk_dir: Path, +def verify_legacy_shard( + conn: sqlite3.Connection, shard_id: int, paper_dir: Path, chunk_dir: Path, *, merged_db: sqlite3.Connection | None = None, ) -> None: - """Before trusting an old producer checkpoint, account for its unindexed rows.""" - if not any(checkpoint.get("build_stream", {}).values()): - return + """Account for old producer rows, including rows committed before the first checkpoint.""" if conn.execute( "SELECT 1 FROM sqlite_master WHERE type='table' AND name='ingest_publication'" ).fetchone() or not conn.execute("SELECT 1 FROM files LIMIT 1").fetchone(): @@ -43,10 +41,16 @@ def verify_legacy_checkpoint( import numpy as np message = ( - f"Cannot verify the checkpoint for legacy producer shard {shard_id}. " + 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." ) + # 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"), ("chunks", chunk_dir, "chunk_seg", "SELECT c.id, p.doc_id, c.ord FROM chunks c " @@ -62,6 +66,8 @@ def verify_legacy_checkpoint( for path in iter_segment_files(directory, kind): if path.name.startswith(prefix + "_") and not path.name.startswith(f"{prefix}_{shard_id}_"): continue + if replaced or different_texts: + 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 diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 80bae05..16f9160 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -275,18 +275,27 @@ def test_ingest_and_merge_through_existing_pre_embedding_text_connections(tmp_pa assert reopened.execute("SELECT embedding_text FROM papers").fetchall() == [("Revised",)] -@pytest.mark.parametrize("legacy_files", ["ready", "pending", "missing"]) +@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, monkeypatch + tmp_path, archive, legacy_files, has_checkpoint, monkeypatch ): - from litkit.segments import save_checkpoint + 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("ALTER TABLE papers DROP COLUMN embedding_text") - save_checkpoint({"build_stream": {str(archive): 3}}, build.checkpoint, build.root / "ckpt.lock", 0) + 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") @@ -312,7 +321,7 @@ def test_upgrade_verifies_old_producer_checkpoint_before_resume_or_merge( with pytest.raises(RuntimeError, match="fresh workspace"): merge_shard_databases(main, segment_dir=build.segments) assert build.db.is_file() - assert build.progress() == 3 + assert build.progress() == (3 if has_checkpoint else 0) assert main.execute("SELECT COUNT(*) FROM papers").fetchone() == (0,) From 765f924d159af5210a47f34494dc6d5aacc40c15 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 17:51:27 -0700 Subject: [PATCH 12/31] Publish node-local shard copies recoverably before exposing their checkpoints Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 2 +- src/litkit/build/consume.py | 11 +- src/litkit/build/ingest_loop.py | 2 +- src/litkit/cli.py | 3 + src/litkit/db/handoff.py | 183 ++++++++++++++++++++++ src/litkit/db/sharding.py | 13 +- src/litkit/segments/metadata.py | 8 +- tests/integration/test_build_and_query.py | 59 +++++++ tests/test_db.py | 21 +++ vector_build_multi.sbatch | 36 +++-- 10 files changed, 313 insertions(+), 25 deletions(-) create mode 100644 src/litkit/db/handoff.py diff --git a/CHANGELOG.md b/CHANGELOG.md index d7a76da..9271a51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ internal versions are summarized under 0.3.33. ## [Unreleased] ### Fixed -- Shard merges commit and detach each database before deleting it. Builds with more than ten producer shards can now merge every shard. (#1) +- Shard merges commit and detach each database before deleting it. Builds with more than ten producer shards can now merge every shard. Node-local transfers publish the checkpoint, database, segments and completion marker from a recoverable copy on shared storage. (#1) - Completed consumers now mark every saved paper and chunk as indexed when FAISS saves are throttled. - Tar builds commit articles in batches. Interrupted producers resume with complete paper and chunk segments, and consumers ignore unfinished files. For a producer already interrupted on an older release, 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) diff --git a/src/litkit/build/consume.py b/src/litkit/build/consume.py index f9ded2b..67bbc8a 100644 --- a/src/litkit/build/consume.py +++ b/src/litkit/build/consume.py @@ -15,7 +15,7 @@ from typing import TYPE_CHECKING, Callable from litkit.db import flush_pending_marks -from litkit.db.sharding import merged_shard_databases +from litkit.db.sharding import merged_shard_databases, recover_staged_shards from litkit.index import faiss_load, faiss_save_force from litkit.segments import ( ConsumerCoordinator, @@ -72,6 +72,12 @@ 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 + + def poll_progress(complete: int, total: int) -> None: + if complete < total: + recover_staged_shards(sqlite_dir, FileLock) + cb(complete, total) eprint("[consumer] Starting consume-only mode") @@ -84,10 +90,11 @@ def default_progress(complete: int, total: int) -> None: eprint("[consumer] Waiting for producers to complete...") + recover_staged_shards(sqlite_dir, FileLock) completed = consumer_coordinator.wait_for_completion( poll_interval=poll_interval, timeout=timeout, - progress_callback=cb, + progress_callback=poll_progress, ) if not completed: diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index 1b551a7..600103f 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -647,7 +647,7 @@ def _render(force: bool = False): # 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) + producer_shard_lock(sqlite_dir, ckpt_shard_id, FileLock, database_open=True) if embed_producer and not _producer_locked else nullcontext() ) with owner_lock: diff --git a/src/litkit/cli.py b/src/litkit/cli.py index 7b96c98..fdc5617 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1233,6 +1233,9 @@ def _build_or_update_indices(args): # Guard: --rebuild with unconsumed segments or active producers can corrupt data # This check is here (not in main()) because it requires heavy deps for segment functions if not getattr(args, "force_rebuild", False): + from litkit.db.sharding import recover_staged_shards + + recover_staged_shards(SQLITE_DIR, FileLock) seg_dir = args.embed_outdir or EMBED_SEGMENTS_DIR conflict_reasons = [] diff --git a/src/litkit/db/handoff.py b/src/litkit/db/handoff.py new file mode 100644 index 0000000..912626e --- /dev/null +++ b/src/litkit/db/handoff.py @@ -0,0 +1,183 @@ +"""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 +from pathlib import Path + + +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 closing(sqlite3.connect(source.resolve().as_uri() + "?mode=ro", uri=True)) 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 prepare_local_shard(local, workspace, shard_id): + """Seed an empty local workspace from shared progress before running the producer.""" + 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" + if source.is_file(): + with closing(sqlite3.connect(source.resolve().as_uri() + "?mode=rw", uri=True)) as db: + legacy = not db.execute( + "SELECT 1 FROM sqlite_master WHERE name='ingest_publication'" + ).fetchone() + if legacy and db.execute("SELECT 1 FROM files LIMIT 1").fetchone(): + return False # Verify old segments and any already-consumed rows on shared storage. + if not legacy and db.execute("SELECT 1 FROM ingest_publication").fetchone(): + return False # Recover private staging in its original workspace. + 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 + if target.is_file(): + return True # This job may have progressed beyond the shared checkpoint. + if source.is_file(): + _backup(source, target.with_suffix(".seed")) + if checkpoint.is_file(): + dest = target.parent / checkpoint.name + _copy_file(checkpoint, dest.with_suffix(".seed")) + dest.with_suffix(".seed").replace(dest) + 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.""" + 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(segment_dir.glob(f"*_seg_{shard_id}_*.npz")) + if not source_db.is_file() or not done.is_file(): + raise RuntimeError(f"Incomplete local producer output for shard {shard_id} in {source}") + digest = hashlib.sha256(checkpoint.read_bytes() if checkpoint.is_file() else b"") + for path in segments: + digest.update(b"\0" + os.fsencode(path.name)) + receipt = sqlite_dir / f"producer_{shard_id}.transfer" + identity = digest.hexdigest() + if receipt.is_file() and receipt.read_text() == identity and ( + (sqlite_dir / source_db.name).is_file() or (sqlite_dir / "litkit.sqlite3").is_file() + ): + final_done = workspace / "emb_segments" / done.name + if not final_done.is_file(): + temporary = final_done.with_suffix(".done.tmp") + _copy_file(done, temporary) + temporary.replace(final_done) + _sync_dir(final_done.parent) + return + 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) + meta = segment_dir / "build_meta.json" + for path in [*segments, 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__": + 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/sharding.py b/src/litkit/db/sharding.py index ae44bb4..2a332f5 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -11,6 +11,7 @@ from litkit.concurrent.locking import FileLock from litkit.db.connection import commit_transaction, rollback_transaction +from litkit.db.handoff import finish_handoff, staged_shards from litkit.db.publication import unpublished_shards from litkit.db.schema import citation_columns, ensure_paper_embedding_column, paper_embedding_column @@ -92,15 +93,23 @@ def merge_shard_databases( @contextmanager -def producer_shard_lock(sqlite_dir, shard_id, lock_factory=FileLock): +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 +def recover_staged_shards(sqlite_dir, lock_factory=FileLock): + """Complete interrupted transfers before checking the producers' completion markers.""" + for shard_id in staged_shards(sqlite_dir): + with producer_shard_lock(sqlite_dir, shard_id, lock_factory): + pass + + @contextmanager def merged_shard_databases( main_conn: sqlite3.Connection, @@ -118,6 +127,8 @@ def merged_shard_databases( 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) shards = list_shard_dbs(sqlite_dir) pending = unpublished_shards(shards, include_reservations=True) if pending: diff --git a/src/litkit/segments/metadata.py b/src/litkit/segments/metadata.py index 627bdae..767eb27 100644 --- a/src/litkit/segments/metadata.py +++ b/src/litkit/segments/metadata.py @@ -62,7 +62,6 @@ def verify_legacy_shard( # 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() - numeric_ids = set() for path in iter_segment_files(directory, kind): if path.name.startswith(prefix + "_") and not path.name.startswith(f"{prefix}_{shard_id}_"): continue @@ -76,9 +75,10 @@ def verify_legacy_shard( 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: - numeric_ids.update(segment["ids"]) - missing = (row for row in conn.execute(query) - if row[0] not in numeric_ids and tuple(row[1:]) not in ready_keys) + # 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) if tuple(row[1:]) not in ready_keys) first = next(missing, None) if first is None: continue diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index f7d0e64..caaf551 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -601,6 +601,65 @@ def test_writer_consume_segments_reports_partial_pass_and_retries_in_order(isola np.testing.assert_array_equal(faiss_load(path).reconstruct(pid), vectors[2]) +@pytest.mark.parametrize("interruption", ["copy", "publish"]) +def test_local_shard_transfer_survives_interruption(isolated_env, corpus_dir, monkeypatch, interruption): + from litkit.db import handoff + + 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 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 == "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) + assert sorted(faiss.vector_to_array(faiss_load(shared / "indices" / f"{table}.faiss").id_map)) == [ + pid for pid, _ in rows + ] + if interruption == "publish": + (shared / "emb_segments" / "producer_0.done").unlink() + handoff.copy_handoff(local, shared, 0) # Retrying the same transfer after consumption is harmless. + assert (shared / "emb_segments" / "producer_0.done").is_file() + 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) + _ok(litkit(fresh, *produce)) + assert not list((fresh / "emb_segments").glob("*.npz")) + + @pytest.mark.parametrize("interruption", ["before-commit", "before-publish", "after-commit"]) def test_two_producers_resume_after_process_exit( isolated_env, corpus_dir, monkeypatch, interruption diff --git a/tests/test_db.py b/tests/test_db.py index 1b0ce48..74fa85e 100644 --- a/tests/test_db.py +++ b/tests/test_db.py @@ -267,3 +267,24 @@ def track_descriptors(path): 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)) diff --git a/vector_build_multi.sbatch b/vector_build_multi.sbatch index 5a8e4a7..bb1b0d9 100644 --- a/vector_build_multi.sbatch +++ b/vector_build_multi.sbatch @@ -130,7 +130,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=... @@ -221,6 +221,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}/.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}] Resuming an interrupted batch on NFS" + 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 @@ -299,24 +316,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}" - # Publish into the shared workspace under the same shard lock as the - # consumer. The local lock inode stays local. The done marker travels last. - ( - flock -x 7 - flock -x 8 - flock -x 9 - flock -u 8 - /usr/bin/rsync -a --delay-updates --exclude="producer-admission.lock" --exclude="producer_*.lock" --exclude="producer_*.queue" "${PRODUCER_LOCAL_STAGE_HOST}/sqlite/" "${LITKIT_WORKSPACE}/sqlite/" - /usr/bin/rsync -a --delay-updates --exclude="producer_*.done" "${PRODUCER_LOCAL_STAGE_HOST}/emb_segments/" "${LITKIT_WORKSPACE}/emb_segments/" - /usr/bin/rsync -a "${PRODUCER_LOCAL_STAGE_HOST}/emb_segments/producer_${PRODUCER_NODE_ID}.done" "${LITKIT_WORKSPACE}/emb_segments/" - ) 7>>"${LITKIT_WORKSPACE}/sqlite/producer_${PRODUCER_NODE_ID}.queue" 8>>"${LITKIT_WORKSPACE}/sqlite/producer-admission.lock" 9>>"${LITKIT_WORKSPACE}/sqlite/producer_${PRODUCER_NODE_ID}.lock" + 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 From 772cc61da0c02e2bf244e8095b7b097e58035886 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 18:05:42 -0700 Subject: [PATCH 13/31] Recover detached checkpoints and honor producer timeouts during cluster resume Signed-off-by: Bill Hlavacek --- src/litkit/build/consume.py | 53 +++++++++++-------- src/litkit/build/ingest_loop.py | 49 ++++++++++++++---- src/litkit/concurrent/locking.py | 11 ++-- src/litkit/db/sharding.py | 62 ++++++++++++++--------- src/litkit/segments/discovery.py | 37 +++++++++++--- tests/integration/test_batch_resume.py | 29 +++++++++++ tests/integration/test_build_and_query.py | 54 +++++++++++++++++++- validate_build.sh | 5 +- vector_build_multi.sbatch | 1 + vector_resume_consumer.sbatch | 11 ++-- 10 files changed, 238 insertions(+), 74 deletions(-) diff --git a/src/litkit/build/consume.py b/src/litkit/build/consume.py index 67bbc8a..63e9182 100644 --- a/src/litkit/build/consume.py +++ b/src/litkit/build/consume.py @@ -10,12 +10,16 @@ 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 flush_pending_marks -from litkit.db.sharding import merged_shard_databases, recover_staged_shards +from litkit.concurrent.locking import FileLock as ProducerFileLock +from litkit.db.sharding import drained_producers, merge_drained_shards from litkit.index import faiss_load, faiss_save_force from litkit.segments import ( ConsumerCoordinator, @@ -74,11 +78,6 @@ def default_progress(complete: int, total: int) -> None: cb = progress_callback or default_progress sqlite_dir = Path(conn.execute("PRAGMA database_list").fetchone()[2]).parent - def poll_progress(complete: int, total: int) -> None: - if complete < total: - recover_staged_shards(sqlite_dir, FileLock) - cb(complete, total) - eprint("[consumer] Starting consume-only mode") # Load existing indices @@ -90,21 +89,33 @@ def poll_progress(complete: int, total: int) -> None: eprint("[consumer] Waiting for producers to complete...") - recover_staged_shards(sqlite_dir, FileLock) - completed = consumer_coordinator.wait_for_completion( - poll_interval=poll_interval, - timeout=timeout, - progress_callback=poll_progress, - ) - - if not completed: - eprint("[consumer] TIMEOUT waiting for producers; aborting consume-only run.") - return False - - eprint("[consumer] All producers have completed") - - eprint("[consumer] Merging shard databases...") - with merged_shard_databases(conn, lock_factory=FileLock, segment_dir=seg_dir) as merge_stats: + 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): " diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index 600103f..1a35fc6 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -8,9 +8,10 @@ import json import os +import sqlite3 import sys import time -from contextlib import nullcontext +from contextlib import ExitStack, closing, nullcontext from pathlib import Path from types import SimpleNamespace from typing import TYPE_CHECKING, Iterator, Sequence @@ -57,7 +58,6 @@ ) if TYPE_CHECKING: - import sqlite3 from litkit.embeddings.base import Embedder from litkit.segments import SegmentWriter, ChunkSegmentWriter @@ -463,9 +463,13 @@ def _render(force: bool = False): _render() # Fast path 1: already processed (vast majority in --update mode) - if not rebuilding_tar and db_already_processed(cur, str(f), st): - processed_count += 1 - continue + 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): + 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: @@ -520,8 +524,18 @@ def _render(force: bool = False): (canon_doc_id, pid) ) else: - # New paper: use current path as canonical doc_id - canon_doc_id = str(f) + # A previous consume may have removed the shard that + # assigned this paper its canonical document ID. + canonical = None + if merged is not None and pmcid: + canonical = merged.execute( + "SELECT doc_id FROM papers WHERE pmcid=?", (pmcid,) + ).fetchone() + if merged is not None and not canonical and pmid: + canonical = merged.execute( + "SELECT doc_id FROM papers WHERE pmid=?", (pmid,) + ).fetchone() + canon_doc_id = canonical[0] if canonical and canonical[0] else 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")), @@ -650,7 +664,8 @@ def _render(force: bool = False): producer_shard_lock(sqlite_dir, ckpt_shard_id, FileLock, database_open=True) if embed_producer and not _producer_locked else nullcontext() ) - with owner_lock: + with owner_lock, ExitStack() as readers: + merged = None ensure_paper_embedding_column(conn) publication = BatchPublication( conn, @@ -661,10 +676,26 @@ def _render(force: bool = False): chunk_seg_writer.outdir if embed_producer else chunk_index_path.parent, ) if embed_producer: + 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_uri = main_path.resolve().as_uri() + "?mode=ro" + main_db = readers.enter_context(closing(sqlite3.connect(main_uri, uri=True))) + if main_db.execute("SELECT 1 FROM files LIMIT 1").fetchone(): + merged = main_db.cursor() verify_legacy_shard( conn, paper_seg_writer.shard_id, - paper_seg_writer.outdir, chunk_seg_writer.outdir, + paper_seg_writer.outdir, chunk_seg_writer.outdir, merged_db=main_db, ) + # 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. + if publication.checkpoint.get("build_stream") and not conn.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='ingest_publication'" + ).fetchone(): + 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: 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/sharding.py b/src/litkit/db/sharding.py index 2a332f5..23ad00c 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -121,6 +121,13 @@ def merged_shard_databases( """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(".") + 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. @@ -129,31 +136,36 @@ def merged_shard_databases( pass for shard_id in staged_shards(sqlite_dir): finish_handoff(sqlite_dir, shard_id) - 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." - ) - default_segments = sqlite_dir.parent / "emb_segments" - if segment_dir is None and sqlite_dir.name == "sqlite" and ( - default_segments.is_dir() or any(sqlite_dir.glob("build_checkpoint_shard_*.json")) - ): - segment_dir = default_segments - if segment_dir is not None: - from litkit.segments.metadata import verify_legacy_shard - - for shard in shards: - suffix = shard.stem.removeprefix("litkit_shard_") - if not suffix.isdecimal(): - continue - shard_id = int(suffix) - uri = shard.resolve().as_uri() + "?mode=ro" - with closing(sqlite3.connect(uri, uri=True)) as source: - verify_legacy_shard(source, shard_id, segment_dir, segment_dir, merged_db=main_conn) - yield _merge_locked_shards(main_conn, shards, delete_after_merge) + 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." + ) + default_segments = sqlite_dir.parent / "emb_segments" + if segment_dir is None and sqlite_dir.name == "sqlite" and ( + default_segments.is_dir() or any(sqlite_dir.glob("build_checkpoint_shard_*.json")) + ): + segment_dir = default_segments + if segment_dir is not None: + from litkit.segments.metadata import verify_legacy_shard + + for shard in shards: + suffix = shard.stem.removeprefix("litkit_shard_") + if not suffix.isdecimal(): + continue + shard_id = int(suffix) + uri = shard.resolve().as_uri() + "?mode=ro" + with closing(sqlite3.connect(uri, uri=True)) as source: + verify_legacy_shard(source, shard_id, segment_dir, segment_dir, merged_db=main_conn) + return _merge_locked_shards(main_conn, shards, delete_after_merge) def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge): diff --git a/src/litkit/segments/discovery.py b/src/litkit/segments/discovery.py index 001877f..86409da 100644 --- a/src/litkit/segments/discovery.py +++ b/src/litkit/segments/discovery.py @@ -38,13 +38,15 @@ def iter_segment_files(seg_dir, kind): yield path -def _shard_count(directory, segments): - meta = directory / "build_meta.json" - if meta.exists(): +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(meta.read_text())["num_shards"] + 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( @@ -53,7 +55,7 @@ def _shard_count(directory, segments): ) # Older builds may lack metadata. Completed producers include shards that # emitted no segments or whose last segment has already been consumed. - ids = [] + ids = list(ids) for marker in directory.glob("producer_*.done"): match = re.fullmatch(r"producer_(\d+)\.done", marker.name) if match: @@ -67,9 +69,30 @@ def _shard_count(directory, segments): 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")) + parser.add_argument("operation", choices=("count", "sample", "shards", "resume")) parser.add_argument("directory", type=Path) args = parser.parse_args() files = chain( @@ -80,6 +103,8 @@ def main(): 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)) diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 16f9160..0e33d5e 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -24,6 +24,35 @@ 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" diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index caaf551..99ab8bf 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -5,6 +5,7 @@ run_litkit_fake.py, so no model, GPU or network is needed. """ +import json import os import sqlite3 import subprocess @@ -601,9 +602,10 @@ def test_writer_consume_segments_reports_partial_pass_and_retries_in_order(isola np.testing.assert_array_equal(faiss_load(path).reconstruct(pid), vectors[2]) -@pytest.mark.parametrize("interruption", ["copy", "publish"]) +@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" @@ -622,7 +624,10 @@ def fail_copy(path, dest): return copy(path, dest) def fail_publish(path, dest): - if path.suffix == ".done": + 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) @@ -634,6 +639,12 @@ def fail_publish(path, dest): 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")) @@ -656,10 +667,49 @@ def fail_publish(path, dest): (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")) +@pytest.mark.parametrize("node_local", [False, True]) +def test_detached_checkpoint_and_incremental_alias(isolated_env, tmp_path, monkeypatch, node_local): + 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=[])}) + monkeypatch.setenv("FAKE_EMBED_DIM", "768") + _ok(litkit(shared, "--init-indices-only", "--faiss-writer", *FLAT)) + # 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 in range(2): + if run: + write_tar(tars / "b.tar", {"alias.xml": jats(title="Revision", pmcid="PMC42", paragraphs=["New body."])}) + 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 in_index=1").fetchall() == [ + (f"tar://{original}!/original.xml",) + ] + assert db.execute("SELECT count(*) FROM files").fetchone() == (run + 1,) + assert db.execute("SELECT count(*) FROM chunks WHERE in_index=1").fetchone() == (run + 1,) + assert _ntotal(shared, "chunks.faiss") == run + 1 + assert not list((shared / "emb_segments").glob("*.unresolved.*")) + + @pytest.mark.parametrize("interruption", ["before-commit", "before-publish", "after-commit"]) def test_two_producers_resume_after_process_exit( isolated_env, corpus_dir, monkeypatch, interruption diff --git a/validate_build.sh b/validate_build.sh index 21d2125..419e1be 100755 --- a/validate_build.sh +++ b/validate_build.sh @@ -71,7 +71,10 @@ if [[ ! -d "$EMB_DIR" ]]; then else discovery="$(dirname "${BASH_SOURCE[0]}")/src/litkit/segments/discovery.py" SEGMENT_COUNT=$(python3 "$discovery" count "$EMB_DIR") - if [[ "$SEGMENT_COUNT" -eq 0 ]]; then + 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" diff --git a/vector_build_multi.sbatch b/vector_build_multi.sbatch index bb1b0d9..9615a5d 100644 --- a/vector_build_multi.sbatch +++ b/vector_build_multi.sbatch @@ -265,6 +265,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}" diff --git a/vector_resume_consumer.sbatch b/vector_resume_consumer.sbatch index 70cc474..b606917 100644 --- a/vector_resume_consumer.sbatch +++ b/vector_resume_consumer.sbatch @@ -62,18 +62,16 @@ 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 +# Include committed transfers that the consumer can finish publishing under lock. discovery="${LITKIT_REPO}/src/litkit/segments/discovery.py" -n_segs=$(python3 "$discovery" count "$SEG_DIR") -echo "[resume] Found $n_segs segment files to ingest" +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 -n_shards=$(python3 "$discovery" shards "$SEG_DIR") echo "[resume] Resuming $n_shards producer shard(s)" ### ----- CLEAN STALE WRITER GUARD (SLURM RESTART SAFE) ------------------------ @@ -87,7 +85,6 @@ rm -f "${LITKIT_WORKSPACE}/.writer_guard" 2>/dev/null || true echo "" echo "=== Resume Consumer Starting ===" -echo "Segments to ingest: $n_segs" echo "Shards: $n_shards" echo "Workspace: $LITKIT_WORKSPACE" echo "================================" From 4bbe808362eef47d65804956204d917180db73e0 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 18:08:07 -0700 Subject: [PATCH 14/31] Keep reopened FAISS indexes alive while checking native ID maps Signed-off-by: Bill Hlavacek --- tests/integration/test_batch_resume.py | 6 ++++-- tests/integration/test_build_and_query.py | 10 ++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 0e33d5e..3032d24 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -469,7 +469,8 @@ def fail_checkpoint(*args, **kwargs): assert [len(ids) for ids, _ in build.consume()] == [3, 6] else: for path, n in [(build.paper_path, 3), (build.chunk_path, 6)]: - assert sorted(faiss.vector_to_array(faiss_load(path).id_map)) == list(range(1, n + 1)) + 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): @@ -626,7 +627,8 @@ def fail_chunk(index, path): assert all(index.ntotal == 0 for index in handles.values()) build.run(**handles) for path in (build.paper_path, build.chunk_path): - assert sorted(faiss.vector_to_array(faiss_load(path).id_map)) == ([1, 2] if existing else [1]) + index = faiss_load(path) + assert sorted(faiss.vector_to_array(index.id_map)) == ([1, 2] if existing else [1]) def test_rebuild_can_inspect_a_shard_with_a_hot_rollback_journal(tmp_path): diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index 99ab8bf..3ecac97 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -655,9 +655,8 @@ def fail_publish(path, dest): 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) - assert sorted(faiss.vector_to_array(faiss_load(shared / "indices" / f"{table}.faiss").id_map)) == [ - pid for pid, _ 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": (shared / "emb_segments" / "producer_0.done").unlink() handoff.copy_handoff(local, shared, 0) # Retrying the same transfer after consumption is harmless. @@ -914,6 +913,5 @@ def __enter__(self): 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"] - assert sorted(faiss.vector_to_array(faiss_load(ws / "indices" / "papers.faiss").id_map)) == [ - pid for pid, _ in rows - ] + index = faiss_load(ws / "indices" / "papers.faiss") + assert sorted(faiss.vector_to_array(index.id_map)) == [pid for pid, _ in rows] From 7df48caa20871c9e2d48aa8f9feebe4810bfe16a Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 18:13:35 -0700 Subject: [PATCH 15/31] Reject stale node-local transfers and share staging across equivalent paths Signed-off-by: Bill Hlavacek --- src/litkit/build/publication.py | 9 +++- src/litkit/db/handoff.py | 52 +++++++++++++++++++++-- tests/integration/test_batch_resume.py | 14 ++++++ tests/integration/test_build_and_query.py | 43 +++++++++++++++++++ 4 files changed, 114 insertions(+), 4 deletions(-) diff --git a/src/litkit/build/publication.py b/src/litkit/build/publication.py index fe09f8d..a1927e5 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -31,12 +31,18 @@ def __init__(self, conn, ckpt_path, ckpt_lock, shard_id, paper_dir, chunk_dir): self.ckpt_path = ckpt_path self.ckpt_lock = ckpt_lock self.shard_id = shard_id - self.outputs = (Path(paper_dir), Path(chunk_dir)) + paper_root, chunk_root = Path(paper_dir).resolve(), Path(chunk_dir).resolve() + if (paper_root != chunk_root and paper_root.exists() and chunk_root.exists() + and paper_root.samefile(chunk_root)): + chunk_root = paper_root + self.outputs = paper_root, chunk_root self.checkpoint = load_checkpoint(ckpt_path, shard_id=shard_id) self.token: str | None = None def checkpoint_tar(self, tar: str, members: int) -> None: self.checkpoint.setdefault("build_stream", {})[tar] = members + if self.shard_id is not None and self.token is not None: + self.checkpoint["producer_revision"] = self.token self.checkpoint.pop("batch_reservation", None) self.save_checkpoint() @@ -203,6 +209,7 @@ def recover(self) -> bool: "This database copy shares staging with its original database. " "Resume the original workspace, or use a matching copy of its segment directory." ) + self.token = record.token self._finish( self._directories(record.token), record.tar, record.members, record.paper, record.chunk ) diff --git a/src/litkit/db/handoff.py b/src/litkit/db/handoff.py index 912626e..56961a4 100644 --- a/src/litkit/db/handoff.py +++ b/src/litkit/db/handoff.py @@ -48,6 +48,34 @@ def _copy_file(source, target): 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 prepare_local_shard(local, workspace, shard_id): """Seed an empty local workspace from shared progress before running the producer.""" sqlite_dir = workspace / "sqlite" @@ -71,14 +99,20 @@ def prepare_local_shard(local, workspace, shard_id): return False if not isinstance(progress, dict) or "batch_reservation" in progress: return False + base = target.parent / f"producer_{shard_id}.base" if target.is_file(): - return True # This job may have progressed beyond the shared checkpoint. + # 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 source.is_file(): _backup(source, target.with_suffix(".seed")) if checkpoint.is_file(): dest = target.parent / checkpoint.name _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) @@ -135,12 +169,17 @@ def copy_handoff(source, workspace, shard_id): segments = sorted(segment_dir.glob(f"*_seg_{shard_id}_*.npz")) if not source_db.is_file() or not done.is_file(): raise RuntimeError(f"Incomplete local producer output for shard {shard_id} in {source}") - digest = hashlib.sha256(checkpoint.read_bytes() if checkpoint.is_file() else b"") + checkpoint_bytes = checkpoint.read_bytes() if checkpoint.is_file() else None + 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" identity = digest.hexdigest() - if receipt.is_file() and receipt.read_text() == identity and ( + shared_checkpoint = sqlite_dir / checkpoint.name + same_checkpoint = checkpoint_bytes == ( + shared_checkpoint.read_bytes() if shared_checkpoint.is_file() else None + ) + if same_checkpoint and receipt.is_file() and receipt.read_text() == identity and ( (sqlite_dir / source_db.name).is_file() or (sqlite_dir / "litkit.sqlite3").is_file() ): final_done = workspace / "emb_segments" / done.name @@ -150,6 +189,13 @@ def copy_handoff(source, workspace, shard_id): temporary.replace(final_done) _sync_dir(final_done.parent) return + base = source_db.parent / f"producer_{shard_id}.base" + expected = json.loads(base.read_text()) if base.is_file() else {} + 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) diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 3032d24..75be636 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -66,6 +66,20 @@ def archive(tmp_path): 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): self.root = root diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index 3ecac97..8f09551 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -709,6 +709,49 @@ def test_detached_checkpoint_and_incremental_alias(isolated_env, tmp_path, monke assert not list((shared / "emb_segments").glob("*.unresolved.*")) +@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.*")) + + @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 f221550afd87734425c85facba53e024ff152ec3 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 18:22:07 -0700 Subject: [PATCH 16/31] Verify checkpoint output directories before publishing or reclaiming a batch Signed-off-by: Bill Hlavacek --- src/litkit/build/ingest_loop.py | 1 + src/litkit/build/publication.py | 101 +++++++++++++++---------- src/litkit/db/handoff.py | 30 +++++++- src/litkit/db/sharding.py | 5 +- tests/integration/test_batch_resume.py | 89 ++++++++++++++++++++-- 5 files changed, 181 insertions(+), 45 deletions(-) diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index 1a35fc6..7af8a30 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -676,6 +676,7 @@ def _render(force: bool = False): chunk_seg_writer.outdir if embed_producer else chunk_index_path.parent, ) if embed_producer: + publication.bind_producer_outputs() 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] diff --git a/src/litkit/build/publication.py b/src/litkit/build/publication.py index a1927e5..3642b8b 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -2,7 +2,6 @@ from __future__ import annotations -import os import shutil import sqlite3 from collections.abc import Callable @@ -11,6 +10,7 @@ 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_output_markers from litkit.db.publication import PublicationRecord, read_publication from litkit.segments.checkpoint import load_checkpoint, save_checkpoint from litkit.segments.discovery import segment_order @@ -23,6 +23,11 @@ def reset_publication(conn: sqlite3.Connection) -> None: conn.execute("UPDATE ingest_publication SET tar=NULL WHERE singleton=1") +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.""" @@ -31,15 +36,22 @@ def __init__(self, conn, ckpt_path, ckpt_lock, shard_id, paper_dir, chunk_dir): self.ckpt_path = ckpt_path self.ckpt_lock = ckpt_lock self.shard_id = shard_id - paper_root, chunk_root = Path(paper_dir).resolve(), Path(chunk_dir).resolve() - if (paper_root != chunk_root and paper_root.exists() and chunk_root.exists() - and paper_root.samefile(chunk_root)): - chunk_root = paper_root - self.outputs = paper_root, chunk_root + 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): + self.producer = True + verify_output_markers(self.checkpoint, *self.outputs) def checkpoint_tar(self, tar: str, members: int) -> None: + if self.producer and "segment_output" not in self.checkpoint: + self.checkpoint["segment_output"] = uuid4().hex + for marker in output_markers(self.checkpoint, *self.outputs): + marker.parent.mkdir(parents=True, exist_ok=True) + marker.touch() + maybe_fsync_dir(marker) self.checkpoint.setdefault("build_stream", {})[tar] = members if self.shard_id is not None and self.token is not None: self.checkpoint["producer_revision"] = self.token @@ -52,25 +64,34 @@ def save_checkpoint(self) -> None: def _database(self) -> str: return self.conn.execute("PRAGMA database_list").fetchone()[2] - def _shares_source_staging(self, record: PublicationRecord) -> bool: - """A backup may publish its own copy of staging, or resume the original DB in place.""" - current = self._database() - if current == record.source_db or ( - Path(record.source_db).exists() and os.path.samefile(current, record.source_db) - ): - return False - for root, source in zip(self.outputs, (record.paper_root, record.chunk_root), strict=True): - if root.resolve() == Path(source) or ( - root.exists() and Path(source).exists() and root.samefile(source) - ): - return True - return False - - def _directories(self, token: str) -> tuple[Path, Path]: + def _directories(self, token: str, roots=None) -> tuple[Path, Path]: if UUID(hex=token).hex != token: raise ValueError("Invalid batch directory in SQLite") - name = ".litkit-batch-" + token - return self.outputs[0] / name, self.outputs[1] / name + 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.""" @@ -117,10 +138,9 @@ def discard_uncommitted(self) -> 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. - if not self._shares_source_staging(record): - for directory in set(self._directories(record.token)): - if directory.exists(): - shutil.rmtree(directory) + 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() @@ -140,7 +160,7 @@ def publish( raise RuntimeError("Missing batch reservation") directories = self._directories(self.token) try: - for directory in set(directories): + for directory in directories: directory.mkdir(parents=True) maybe_fsync_dir(directory) paper, chunk = write(*directories) @@ -163,11 +183,12 @@ def publish( self._finish(directories, *record) def _finish(self, directories, tar, members, paper, chunk): - for directory, name in zip(directories, (paper, chunk), strict=True): + 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 (".", ".."): @@ -190,7 +211,7 @@ def _finish(self, directories, tar, members, paper, chunk): # retried without re-publishing or requiring both directories to exist. with batch_transaction(self.conn): self.conn.execute("UPDATE ingest_publication SET tar=NULL WHERE singleton=1") - for directory in set(directories): + for directory in directories: directory.rmdir() self._retire() @@ -204,13 +225,17 @@ def recover(self) -> bool: if record.tar is None: self.discard_uncommitted() return False - if self._shares_source_staging(record): - raise RuntimeError( - "This database copy shares staging with its original database. " - "Resume the original workspace, or use a matching copy of its segment directory." - ) + 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( - self._directories(record.token), record.tar, record.members, record.paper, record.chunk - ) + self._finish(directories, record.tar, record.members, record.paper, record.chunk) return True diff --git a/src/litkit/db/handoff.py b/src/litkit/db/handoff.py index 56961a4..5c6471c 100644 --- a/src/litkit/db/handoff.py +++ b/src/litkit/db/handoff.py @@ -11,6 +11,28 @@ import sys from contextlib import closing from pathlib import Path +from uuid import UUID + + +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): + markers = output_markers(checkpoint, paper_dir, chunk_dir) + 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." + ) + return markers def _staging(sqlite_dir, shard_id): @@ -110,6 +132,11 @@ def prepare_local_shard(local, workspace, shard_id): _backup(source, target.with_suffix(".seed")) if checkpoint.is_file(): dest = target.parent / checkpoint.name + shared_segments = workspace / "emb_segments" + local_segments = local / "emb_segments" + for marker in verify_output_markers(progress, shared_segments, shared_segments): + _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)) @@ -203,7 +230,8 @@ def copy_handoff(source, workspace, shard_id): if path.is_file(): _copy_file(path, db_stage / path.name) meta = segment_dir / "build_meta.json" - for path in [*segments, done]: + markers = verify_output_markers(json.loads(checkpoint_bytes), segment_dir, segment_dir) if checkpoint_bytes else () + for path in [*segments, *markers, done]: _copy_file(path, seg_stage / path.name) if meta.is_file(): _copy_file(meta, seg_stage / meta.name) diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index 23ad00c..9600e54 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -11,7 +11,7 @@ from litkit.concurrent.locking import FileLock from litkit.db.connection import commit_transaction, rollback_transaction -from litkit.db.handoff import finish_handoff, staged_shards +from litkit.db.handoff import finish_handoff, staged_shards, verify_output_markers from litkit.db.publication import unpublished_shards from litkit.db.schema import citation_columns, ensure_paper_embedding_column, paper_embedding_column @@ -155,6 +155,7 @@ def merge_drained_shards(main_conn, sqlite_dir, delete_after_merge, segment_dir) ): segment_dir = default_segments if segment_dir is not None: + from litkit.segments.checkpoint import load_checkpoint from litkit.segments.metadata import verify_legacy_shard for shard in shards: @@ -162,6 +163,8 @@ def merge_drained_shards(main_conn, sqlite_dir, delete_after_merge, segment_dir) if not suffix.isdecimal(): continue shard_id = int(suffix) + checkpoint = load_checkpoint(sqlite_dir / "build_checkpoint.json", shard_id) + verify_output_markers(checkpoint, segment_dir, segment_dir) uri = shard.resolve().as_uri() + "?mode=ro" with closing(sqlite3.connect(uri, uri=True)) as source: verify_legacy_shard(source, shard_id, segment_dir, segment_dir, merged_db=main_conn) diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 75be636..ffd1687 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -665,9 +665,9 @@ def test_rebuild_can_inspect_a_shard_with_a_hot_rollback_journal(tmp_path): assert conn.execute("SELECT COUNT(*) FROM papers").fetchone() == (0,) -@pytest.mark.parametrize("share_segments", [True, False]) +@pytest.mark.parametrize("staging", ["shared", "complete", "incomplete"]) def test_committed_database_copy_requires_independent_staging( - tmp_path, archive, monkeypatch, share_segments + tmp_path, archive, monkeypatch, staging ): first = Build(tmp_path / "original", archive) copy = Build(tmp_path / "copy", archive) @@ -682,18 +682,97 @@ def fail_rename(*args): copy.root.mkdir() with closing(sqlite3.connect(first.db)) as source, closing(sqlite3.connect(copy.db)) as target: source.backup(target) - if share_segments: + if staging == "shared": copy.segments = first.segments with pytest.raises(RuntimeError, match="matching copy"): copy.run() else: shutil.copytree(first.segments, copy.segments) - assert copy.run()[2:] == (1, 2) - assert [len(ids) for ids, _ in copy.consume()] == [3, 6] + 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] + + def test_writer_backfill_uses_the_original_body_only_paper_text(tmp_path): from litkit.build.backfill import backfill_unindexed_vectors From 9418cc0287072b654a6df47a3c3509bfdc005aa7 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 18:24:30 -0700 Subject: [PATCH 17/31] Allow merge-only callers to consume separate segment directories Signed-off-by: Bill Hlavacek --- src/litkit/db/sharding.py | 14 +++++++++----- tests/integration/test_batch_resume.py | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index 9600e54..e6882e9 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -150,11 +150,12 @@ def merge_drained_shards(main_conn, sqlite_dir, delete_after_merge, segment_dir) "Resume the interrupted producer in its original workspace and segment directory." ) default_segments = sqlite_dir.parent / "emb_segments" + legacy_segment_dir = segment_dir if segment_dir is None and sqlite_dir.name == "sqlite" and ( default_segments.is_dir() or any(sqlite_dir.glob("build_checkpoint_shard_*.json")) ): - segment_dir = default_segments - if segment_dir is not None: + legacy_segment_dir = default_segments + if legacy_segment_dir is not None: from litkit.segments.checkpoint import load_checkpoint from litkit.segments.metadata import verify_legacy_shard @@ -163,11 +164,14 @@ def merge_drained_shards(main_conn, sqlite_dir, delete_after_merge, segment_dir) if not suffix.isdecimal(): continue shard_id = int(suffix) - checkpoint = load_checkpoint(sqlite_dir / "build_checkpoint.json", shard_id) - verify_output_markers(checkpoint, segment_dir, segment_dir) + # A merge-only caller can ingest papers and chunks separately. + # The consumer supplies the directory it will actually read. + if segment_dir is not None: + checkpoint = load_checkpoint(sqlite_dir / "build_checkpoint.json", shard_id) + verify_output_markers(checkpoint, segment_dir, segment_dir) uri = shard.resolve().as_uri() + "?mode=ro" with closing(sqlite3.connect(uri, uri=True)) as source: - verify_legacy_shard(source, shard_id, segment_dir, segment_dir, merged_db=main_conn) + verify_legacy_shard(source, shard_id, legacy_segment_dir, legacy_segment_dir, merged_db=main_conn) return _merge_locked_shards(main_conn, shards, delete_after_merge) diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index ffd1687..06bf867 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -773,6 +773,21 @@ def crash_on_second(writer, *args, **kwargs): assert [len(ids) for ids, _ in moved.consume()] == [3, 6] +def test_merge_only_supports_separate_segment_directories(tmp_path, archive): + 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)) + with closing(init_db(build.root / "litkit.sqlite3")) as main: + assert merge_shard_databases(main)["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_writer_backfill_uses_the_original_body_only_paper_text(tmp_path): from litkit.build.backfill import backfill_unindexed_vectors From 8979b7539a4cf1599c6eb932d7bb971ab5733d06 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 18:32:08 -0700 Subject: [PATCH 18/31] Match completed batch revisions across SQLite, checkpoints and segment copies Signed-off-by: Bill Hlavacek --- src/litkit/build/publication.py | 40 +++++++++++++++---- src/litkit/db/handoff.py | 10 ++++- src/litkit/db/publication.py | 22 +++++++++++ src/litkit/db/sharding.py | 38 ++++++++++-------- tests/integration/test_batch_resume.py | 23 +++++++++++ tests/integration/test_build_and_query.py | 47 +++++++++++++++++++++++ 6 files changed, 157 insertions(+), 23 deletions(-) diff --git a/src/litkit/build/publication.py b/src/litkit/build/publication.py index 3642b8b..6489d6b 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -2,6 +2,8 @@ from __future__ import annotations +import json +import os import shutil import sqlite3 from collections.abc import Callable @@ -11,7 +13,7 @@ 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_output_markers -from litkit.db.publication import PublicationRecord, read_publication +from litkit.db.publication import PublicationRecord, read_publication, verify_checkpoint_revision from litkit.segments.checkpoint import load_checkpoint, save_checkpoint from litkit.segments.discovery import segment_order from litkit.segments.writer import finalized_name @@ -43,18 +45,33 @@ def __init__(self, conn, ckpt_path, ckpt_lock, shard_id, paper_dir, chunk_dir): def bind_producer_outputs(self): self.producer = True - verify_output_markers(self.checkpoint, *self.outputs) + record = read_publication(self.conn) + saved = verify_checkpoint_revision(self.conn, self.checkpoint, record) + 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 and "segment_output" not in self.checkpoint: - self.checkpoint["segment_output"] = uuid4().hex + 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) - marker.touch() + 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 - if self.shard_id is not None and self.token is not None: - self.checkpoint["producer_revision"] = self.token self.checkpoint.pop("batch_reservation", None) self.save_checkpoint() @@ -210,6 +227,15 @@ def _finish(self, directories, tar, members, paper, chunk): # 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() diff --git a/src/litkit/db/handoff.py b/src/litkit/db/handoff.py index 5c6471c..f312278 100644 --- a/src/litkit/db/handoff.py +++ b/src/litkit/db/handoff.py @@ -24,14 +24,22 @@ def output_markers(checkpoint, paper_dir, chunk_dir): return (paper_dir / f".litkit-output-{token}-papers", chunk_dir / f".litkit-output-{token}-chunks") -def verify_output_markers(checkpoint, paper_dir, chunk_dir): +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 diff --git a/src/litkit/db/publication.py b/src/litkit/db/publication.py index ca1633b..39c6583 100644 --- a/src/litkit/db/publication.py +++ b/src/litkit/db/publication.py @@ -2,6 +2,7 @@ from __future__ import annotations +import json import sqlite3 from contextlib import closing from pathlib import Path @@ -30,6 +31,27 @@ def read_publication(conn: sqlite3.Connection) -> PublicationRecord | None: return PublicationRecord(*row) if row else None +def verify_checkpoint_revision(conn, checkpoint, record=None): + """Return the last completed SQLite checkpoint and check any external revision.""" + if not conn.execute("SELECT 1 FROM sqlite_master WHERE name='ingest_checkpoint'").fetchone(): + return + row = conn.execute("SELECT checkpoint FROM ingest_checkpoint WHERE singleton=1").fetchone() + if row is None: + return + saved = json.loads(row[0]) + revisions = {saved["producer_revision"]} + 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 unpublished_shards(shards: list[Path], *, include_reservations: bool = False) -> list[Path]: """Find committed publications and, before a merge, journals needed for staging cleanup.""" pending = [] diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index e6882e9..883cb2e 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -12,7 +12,7 @@ from litkit.concurrent.locking import FileLock from litkit.db.connection import commit_transaction, rollback_transaction from litkit.db.handoff import finish_handoff, staged_shards, verify_output_markers -from litkit.db.publication import unpublished_shards +from litkit.db.publication import unpublished_shards, verify_checkpoint_revision from litkit.db.schema import citation_columns, ensure_paper_embedding_column, paper_embedding_column @@ -155,22 +155,30 @@ def merge_drained_shards(main_conn, sqlite_dir, delete_after_merge, segment_dir) default_segments.is_dir() or any(sqlite_dir.glob("build_checkpoint_shard_*.json")) ): legacy_segment_dir = default_segments - if legacy_segment_dir is not None: - from litkit.segments.checkpoint import load_checkpoint - from litkit.segments.metadata import verify_legacy_shard - - for shard in shards: - suffix = shard.stem.removeprefix("litkit_shard_") - if not suffix.isdecimal(): - continue - shard_id = int(suffix) + from litkit.segments.checkpoint import load_checkpoint + from litkit.segments.metadata import verify_legacy_shard + + if segment_dir is not None: + # The databases can already be merged when a consumer resumes. The + # surviving per-shard checkpoints still identify the segment revisions. + for path in sqlite_dir.glob("build_checkpoint_shard_*.json"): + suffix = path.stem.removeprefix("build_checkpoint_shard_") + if not (sqlite_dir / f"litkit_shard_{suffix}.sqlite3").is_file(): + verify_output_markers(load_checkpoint(path), segment_dir, segment_dir) + + for shard in shards: + suffix = shard.stem.removeprefix("litkit_shard_") + if not suffix.isdecimal(): + continue + shard_id = int(suffix) + checkpoint = load_checkpoint(sqlite_dir / "build_checkpoint.json", shard_id) + uri = shard.resolve().as_uri() + "?mode=ro" + with closing(sqlite3.connect(uri, uri=True)) as source: + saved = verify_checkpoint_revision(source, checkpoint) # A merge-only caller can ingest papers and chunks separately. - # The consumer supplies the directory it will actually read. if segment_dir is not None: - checkpoint = load_checkpoint(sqlite_dir / "build_checkpoint.json", shard_id) - verify_output_markers(checkpoint, segment_dir, segment_dir) - uri = shard.resolve().as_uri() + "?mode=ro" - with closing(sqlite3.connect(uri, uri=True)) as source: + verify_output_markers(saved or checkpoint, segment_dir, segment_dir) + if legacy_segment_dir is not None: verify_legacy_shard(source, shard_id, legacy_segment_dir, legacy_segment_dir, merged_db=main_conn) return _merge_locked_shards(main_conn, shards, delete_after_merge) diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 06bf867..476d9b4 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -329,6 +329,7 @@ def test_upgrade_verifies_old_producer_checkpoint_before_resume_or_merge( 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": @@ -788,6 +789,28 @@ def test_merge_only_supports_separate_segment_directories(tmp_path, archive): assert added == index.ntotal == total +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 diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index 8f09551..c8fb159 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -7,6 +7,7 @@ import json import os +import shutil import sqlite3 import subprocess import sys @@ -752,6 +753,52 @@ def run_local(name): assert not list((shared / "emb_segments").glob("*.unresolved.*")) +@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 + + 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": + with _db(ws) as db: + assert merge_shard_databases(db)["papers"] == 2 + latest = current.rename(tmp_path / "latest") + old.rename(current) + for mode in (produce, consume): + 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() + _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("interruption", ["before-commit", "before-publish", "after-commit"]) def test_two_producers_resume_after_process_exit( isolated_env, corpus_dir, monkeypatch, interruption From f27ffddba347f7944b685e5a117842062a949277 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 18:39:13 -0700 Subject: [PATCH 19/31] Preserve verified producer revisions through shard removal and fresh-node recovery Signed-off-by: Bill Hlavacek --- src/litkit/build/ingest_loop.py | 4 +- src/litkit/build/publication.py | 6 +- src/litkit/db/handoff.py | 36 ++++++++++ src/litkit/db/publication.py | 14 ++-- src/litkit/db/sharding.py | 80 +++++++++++++++-------- tests/integration/test_batch_resume.py | 34 +++++++++- tests/integration/test_build_and_query.py | 8 ++- 7 files changed, 140 insertions(+), 42 deletions(-) diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index 7af8a30..5871294 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -48,6 +48,7 @@ ) from litkit.build.publication import BatchPublication from litkit.db.connection import batch_transaction, commit_transaction +from litkit.db.handoff import merged_checkpoints 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 @@ -676,7 +677,6 @@ def _render(force: bool = False): chunk_seg_writer.outdir if embed_producer else chunk_index_path.parent, ) if embed_producer: - publication.bind_producer_outputs() 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] @@ -685,6 +685,8 @@ def _render(force: bool = False): main_db = readers.enter_context(closing(sqlite3.connect(main_uri, uri=True))) if 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, diff --git a/src/litkit/build/publication.py b/src/litkit/build/publication.py index 6489d6b..cf9baf4 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -23,6 +23,8 @@ def reset_publication(conn: sqlite3.Connection) -> None: """Invalidate the active batch in the same transaction as an explicit rebuild.""" if read_publication(conn): conn.execute("UPDATE ingest_publication SET tar=NULL WHERE singleton=1") + if conn.execute("SELECT 1 FROM sqlite_master WHERE name='merged_shard_checkpoints'").fetchone(): + conn.execute("DELETE FROM merged_shard_checkpoints") def _same_path(first, second): @@ -43,10 +45,10 @@ def __init__(self, conn, ckpt_path, ckpt_lock, shard_id, paper_dir, chunk_dir): self.token: str | None = None self.producer = False - def bind_producer_outputs(self): + def bind_producer_outputs(self, merged=None): self.producer = True record = read_publication(self.conn) - saved = verify_checkpoint_revision(self.conn, self.checkpoint, record) + 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: diff --git a/src/litkit/db/handoff.py b/src/litkit/db/handoff.py index f312278..3bfa771 100644 --- a/src/litkit/db/handoff.py +++ b/src/litkit/db/handoff.py @@ -14,6 +14,22 @@ from uuid import UUID +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 output_markers(checkpoint, paper_dir, chunk_dir): """Return the two directory identities carried with a producer's checkpoint.""" token = checkpoint.get("segment_output") @@ -113,6 +129,7 @@ def prepare_local_shard(local, workspace, 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 closing(sqlite3.connect(source.resolve().as_uri() + "?mode=rw", uri=True)) as db: legacy = not db.execute( @@ -122,6 +139,15 @@ def prepare_local_shard(local, workspace, shard_id): return False # Verify old segments and any already-consumed rows on shared storage. 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 saved is None and not checkpoint.is_file() and (sqlite_dir / "litkit.sqlite3").is_file(): + uri = (sqlite_dir / "litkit.sqlite3").resolve().as_uri() + "?mode=ro" + with closing(sqlite3.connect(uri, uri=True)) 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()) @@ -205,6 +231,11 @@ def copy_handoff(source, workspace, 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 closing(sqlite3.connect(source_db.resolve().as_uri() + "?mode=ro", uri=True)) 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)) @@ -237,6 +268,11 @@ def copy_handoff(source, workspace, shard_id): 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" markers = verify_output_markers(json.loads(checkpoint_bytes), segment_dir, segment_dir) if checkpoint_bytes else () for path in [*segments, *markers, done]: diff --git a/src/litkit/db/publication.py b/src/litkit/db/publication.py index 39c6583..bb860bc 100644 --- a/src/litkit/db/publication.py +++ b/src/litkit/db/publication.py @@ -2,12 +2,13 @@ from __future__ import annotations -import json import sqlite3 from contextlib import closing from pathlib import Path from typing import NamedTuple +from litkit.db.handoff import completed_checkpoint + class PublicationRecord(NamedTuple): token: str @@ -31,15 +32,10 @@ def read_publication(conn: sqlite3.Connection) -> PublicationRecord | None: return PublicationRecord(*row) if row else None -def verify_checkpoint_revision(conn, checkpoint, record=None): +def verify_checkpoint_revision(conn, checkpoint, record=None, merged=None): """Return the last completed SQLite checkpoint and check any external revision.""" - if not conn.execute("SELECT 1 FROM sqlite_master WHERE name='ingest_checkpoint'").fetchone(): - return - row = conn.execute("SELECT checkpoint FROM ingest_checkpoint WHERE singleton=1").fetchone() - if row is None: - return - saved = json.loads(row[0]) - revisions = {saved["producer_revision"]} + saved = completed_checkpoint(conn) 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. diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index 883cb2e..b142d37 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -3,6 +3,7 @@ from __future__ import annotations +import json import sqlite3 import sys import time @@ -11,7 +12,7 @@ from litkit.concurrent.locking import FileLock from litkit.db.connection import commit_transaction, rollback_transaction -from litkit.db.handoff import finish_handoff, staged_shards, verify_output_markers +from litkit.db.handoff import finish_handoff, merged_checkpoints, staged_shards, verify_output_markers from litkit.db.publication import unpublished_shards, verify_checkpoint_revision from litkit.db.schema import citation_columns, ensure_paper_embedding_column, paper_embedding_column @@ -68,7 +69,7 @@ def merge_shard_databases( main_conn: sqlite3.Connection, delete_after_merge: bool = True, *, - segment_dir: Path | None = None, + segment_dir: Path | tuple[Path, Path] | None = None, ) -> dict[str, int]: """Merge all per-shard SQLite databases into the main database. @@ -82,7 +83,7 @@ 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: Output directory for checking producer checkpoints from older releases + segment_dir: Combined output directory, or the separate (paper, chunk) directories Returns: Dict with merge statistics: {"papers": N, "chunks": M, "files": F, @@ -116,7 +117,7 @@ def merged_shard_databases( delete_after_merge: bool = True, *, lock_factory=FileLock, - segment_dir: Path | None = None, + 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] @@ -149,41 +150,57 @@ def merge_drained_shards(main_conn, sqlite_dir, delete_after_merge, segment_dir) 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_segment_dir = segment_dir - if segment_dir is None and sqlite_dir.name == "sqlite" and ( + 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_segment_dir = default_segments - from litkit.segments.checkpoint import load_checkpoint - from litkit.segments.metadata import verify_legacy_shard + legacy_outputs = (default_segments, default_segments) - if segment_dir is not None: - # The databases can already be merged when a consumer resumes. The - # surviving per-shard checkpoints still identify the segment revisions. - for path in sqlite_dir.glob("build_checkpoint_shard_*.json"): - suffix = path.stem.removeprefix("build_checkpoint_shard_") - if not (sqlite_dir / f"litkit_shard_{suffix}.sqlite3").is_file(): - verify_output_markers(load_checkpoint(path), segment_dir, segment_dir) + 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 = load_checkpoint(sqlite_dir / "build_checkpoint.json", shard_id) + checkpoint = external.pop(shard_id, {}) + merged = receipts.pop(shard_id, None) uri = shard.resolve().as_uri() + "?mode=ro" with closing(sqlite3.connect(uri, uri=True)) as source: - saved = verify_checkpoint_revision(source, checkpoint) - # A merge-only caller can ingest papers and chunks separately. - if segment_dir is not None: - verify_output_markers(saved or checkpoint, segment_dir, segment_dir) - if legacy_segment_dir is not None: - verify_legacy_shard(source, shard_id, legacy_segment_dir, legacy_segment_dir, merged_db=main_conn) - return _merge_locked_shards(main_conn, shards, delete_after_merge) - - -def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge): + 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_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) @@ -306,6 +323,15 @@ def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge): f"({elapsed:.1f}s)" ) + 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: diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 476d9b4..08d3a50 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -774,12 +774,20 @@ def crash_on_second(writer, *args, **kwargs): assert [len(ids) for ids, _ in moved.consume()] == [3, 6] -def test_merge_only_supports_separate_segment_directories(tmp_path, archive): +@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)["papers"] == 3 + 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), @@ -789,6 +797,28 @@ def test_merge_only_supports_separate_segment_directories(tmp_path, archive): 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_restart_finishes_an_interrupted_output_revision(tmp_path, archive, monkeypatch): build = Build(tmp_path / "producer", archive) replace = os.replace diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index c8fb159..8f31f3e 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -756,6 +756,7 @@ def run_local(name): @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" @@ -778,6 +779,7 @@ def test_producer_and_consumer_reject_mixed_batch_snapshots(isolated_env, tmp_pa 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") @@ -793,7 +795,11 @@ def test_producer_and_consumer_reject_mixed_batch_snapshots(isolated_env, tmp_pa # The matching shard can also restore a missing JSON checkpoint from SQLite. if stale != "merged_segments": paths["checkpoint"].unlink() - _ok(litkit(ws, *produce)) + 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 From 37d0b7b9d933bd050632bcf148f90a3f6e0b6707 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 18:45:20 -0700 Subject: [PATCH 20/31] Reject obsolete shard histories and reverify interrupted legacy migrations Signed-off-by: Bill Hlavacek --- src/litkit/build/ingest_loop.py | 9 ++-- src/litkit/build/publication.py | 5 ++ src/litkit/db/handoff.py | 8 ++- src/litkit/db/publication.py | 12 ++++- src/litkit/segments/metadata.py | 11 +++-- tests/integration/test_batch_resume.py | 59 +++++++++++++++++++++++ tests/integration/test_build_and_query.py | 6 +++ 7 files changed, 100 insertions(+), 10 deletions(-) diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index 5871294..5e62329 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -48,7 +48,8 @@ ) from litkit.build.publication import BatchPublication from litkit.db.connection import batch_transaction, commit_transaction -from litkit.db.handoff import merged_checkpoints +from litkit.db.handoff import completed_checkpoint, merged_checkpoints +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 @@ -694,9 +695,9 @@ def _render(force: bool = False): # 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. - if publication.checkpoint.get("build_stream") and not conn.execute( - "SELECT 1 FROM sqlite_master WHERE type='table' AND name='ingest_publication'" - ).fetchone(): + 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: diff --git a/src/litkit/build/publication.py b/src/litkit/build/publication.py index cf9baf4..61a2e83 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -135,6 +135,11 @@ def reserve(self) -> None: "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 diff --git a/src/litkit/db/handoff.py b/src/litkit/db/handoff.py index 3bfa771..0e1b3f8 100644 --- a/src/litkit/db/handoff.py +++ b/src/litkit/db/handoff.py @@ -135,11 +135,11 @@ def prepare_local_shard(local, workspace, shard_id): legacy = not db.execute( "SELECT 1 FROM sqlite_master WHERE name='ingest_publication'" ).fetchone() - if legacy and db.execute("SELECT 1 FROM files LIMIT 1").fetchone(): - return False # Verify old segments and any already-consumed rows on shared storage. 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(): uri = (sqlite_dir / "litkit.sqlite3").resolve().as_uri() + "?mode=ro" with closing(sqlite3.connect(uri, uri=True)) as main: @@ -162,6 +162,10 @@ def prepare_local_shard(local, workspace, shard_id): 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(): diff --git a/src/litkit/db/publication.py b/src/litkit/db/publication.py index bb860bc..aca0690 100644 --- a/src/litkit/db/publication.py +++ b/src/litkit/db/publication.py @@ -34,7 +34,17 @@ def read_publication(conn: sqlite3.Connection) -> PublicationRecord | None: def verify_checkpoint_revision(conn, checkpoint, record=None, merged=None): """Return the last completed SQLite checkpoint and check any external revision.""" - saved = completed_checkpoint(conn) or merged + 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 diff --git a/src/litkit/segments/metadata.py b/src/litkit/segments/metadata.py index 767eb27..e1650b6 100644 --- a/src/litkit/segments/metadata.py +++ b/src/litkit/segments/metadata.py @@ -10,6 +10,8 @@ from itertools import chain from pathlib import Path +from litkit.db.handoff import completed_checkpoint +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 @@ -33,9 +35,12 @@ def verify_legacy_shard( *, merged_db: sqlite3.Connection | None = None, ) -> None: """Account for old producer rows, including rows committed before the first checkpoint.""" - if conn.execute( - "SELECT 1 FROM sqlite_master WHERE type='table' AND name='ingest_publication'" - ).fetchone() or not conn.execute("SELECT 1 FROM files LIMIT 1").fetchone(): + if completed_checkpoint(conn) or not conn.execute("SELECT 1 FROM files LIMIT 1").fetchone(): + return + journal = read_publication(conn) + if 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 diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 08d3a50..cfa399d 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -819,6 +819,65 @@ def crash(*args, **kwargs): 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 diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index 8f31f3e..12a2651 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -751,6 +751,12 @@ def run_local(name): 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"]) From f802fe4dbf09a32d1e56cb32ac647ddd58d4b669 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 18:50:48 -0700 Subject: [PATCH 21/31] Recover hot SQLite journals before read-only inspection and shard copies Signed-off-by: Bill Hlavacek --- src/litkit/build/ingest_loop.py | 7 +++--- src/litkit/db/handoff.py | 33 +++++++++++++++++++++----- src/litkit/db/publication.py | 15 +++--------- src/litkit/db/sharding.py | 7 +++--- src/litkit/segments/metadata.py | 6 ++--- tests/integration/test_batch_resume.py | 22 +++++++++++++---- 6 files changed, 56 insertions(+), 34 deletions(-) diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index 5e62329..f7b4801 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -11,7 +11,7 @@ import sqlite3 import sys import time -from contextlib import ExitStack, closing, nullcontext +from contextlib import ExitStack, nullcontext from pathlib import Path from types import SimpleNamespace from typing import TYPE_CHECKING, Iterator, Sequence @@ -48,7 +48,7 @@ ) from litkit.build.publication import BatchPublication from litkit.db.connection import batch_transaction, commit_transaction -from litkit.db.handoff import completed_checkpoint, merged_checkpoints +from litkit.db.handoff import completed_checkpoint, merged_checkpoints, readable_database from litkit.db.publication import read_publication from litkit.db.schema import ensure_paper_embedding_column from litkit.db.sharding import producer_shard_lock @@ -682,8 +682,7 @@ def _render(force: bool = False): 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_uri = main_path.resolve().as_uri() + "?mode=ro" - main_db = readers.enter_context(closing(sqlite3.connect(main_uri, uri=True))) + main_db = readers.enter_context(readable_database(main_path)) if main_db.execute("SELECT 1 FROM files LIMIT 1").fetchone(): merged = main_db.cursor() producer_id = paper_seg_writer.shard_id diff --git a/src/litkit/db/handoff.py b/src/litkit/db/handoff.py index 0e1b3f8..c302247 100644 --- a/src/litkit/db/handoff.py +++ b/src/litkit/db/handoff.py @@ -9,11 +9,33 @@ import shutil import sqlite3 import sys -from contextlib import closing +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() @@ -81,7 +103,7 @@ def _sync_dir(directory): def _backup(source, target): - with closing(sqlite3.connect(source.resolve().as_uri() + "?mode=ro", uri=True)) as db: + with readable_database(source) as db: with closing(sqlite3.connect(str(target))) as backup: db.backup(backup) @@ -131,7 +153,7 @@ def prepare_local_shard(local, workspace, shard_id): checkpoint = sqlite_dir / f"build_checkpoint_shard_{shard_id:02d}.json" saved = None if source.is_file(): - with closing(sqlite3.connect(source.resolve().as_uri() + "?mode=rw", uri=True)) as db: + with readable_database(source) as db: legacy = not db.execute( "SELECT 1 FROM sqlite_master WHERE name='ingest_publication'" ).fetchone() @@ -141,8 +163,7 @@ def prepare_local_shard(local, workspace, shard_id): 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(): - uri = (sqlite_dir / "litkit.sqlite3").resolve().as_uri() + "?mode=ro" - with closing(sqlite3.connect(uri, uri=True)) as main: + 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 @@ -236,7 +257,7 @@ def copy_handoff(source, workspace, shard_id): 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 closing(sqlite3.connect(source_db.resolve().as_uri() + "?mode=ro", uri=True)) as db: + with readable_database(source_db) as db: saved = completed_checkpoint(db) if saved: checkpoint_bytes = json.dumps(saved, indent=2).encode() diff --git a/src/litkit/db/publication.py b/src/litkit/db/publication.py index aca0690..f4ae69d 100644 --- a/src/litkit/db/publication.py +++ b/src/litkit/db/publication.py @@ -3,11 +3,10 @@ from __future__ import annotations import sqlite3 -from contextlib import closing from pathlib import Path from typing import NamedTuple -from litkit.db.handoff import completed_checkpoint +from litkit.db.handoff import completed_checkpoint, readable_database class PublicationRecord(NamedTuple): @@ -62,16 +61,8 @@ def unpublished_shards(shards: list[Path], *, include_reservations: bool = False """Find committed publications and, before a merge, journals needed for staging cleanup.""" pending = [] for shard in shards: - uri = shard.resolve().as_uri() - try: - with closing(sqlite3.connect(uri + "?mode=ro", uri=True)) as conn: - row = read_publication(conn) - except sqlite3.OperationalError as error: - if error.sqlite_errorcode & 0xFF != sqlite3.SQLITE_READONLY: - raise - # Inspecting a hot rollback journal requires SQLite to undo uncommitted pages. - with closing(sqlite3.connect(uri + "?mode=rw", uri=True)) as conn: - row = read_publication(conn) + 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/sharding.py b/src/litkit/db/sharding.py index b142d37..6ab7897 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -7,12 +7,12 @@ import sqlite3 import sys import time -from contextlib import ExitStack, closing, contextmanager +from contextlib import ExitStack, contextmanager from pathlib import Path from litkit.concurrent.locking import FileLock from litkit.db.connection import commit_transaction, rollback_transaction -from litkit.db.handoff import finish_handoff, merged_checkpoints, staged_shards, verify_output_markers +from litkit.db.handoff import finish_handoff, merged_checkpoints, readable_database, staged_shards, verify_output_markers from litkit.db.publication import unpublished_shards, verify_checkpoint_revision from litkit.db.schema import citation_columns, ensure_paper_embedding_column, paper_embedding_column @@ -178,8 +178,7 @@ def merge_drained_shards(main_conn, sqlite_dir, delete_after_merge, segment_dir) shard_id = int(suffix) checkpoint = external.pop(shard_id, {}) merged = receipts.pop(shard_id, None) - uri = shard.resolve().as_uri() + "?mode=ro" - with closing(sqlite3.connect(uri, uri=True)) as source: + with readable_database(shard) as source: saved = verify_checkpoint_revision(source, checkpoint, merged=merged) if outputs: verify_output_markers(saved or checkpoint, *outputs) diff --git a/src/litkit/segments/metadata.py b/src/litkit/segments/metadata.py index e1650b6..4343362 100644 --- a/src/litkit/segments/metadata.py +++ b/src/litkit/segments/metadata.py @@ -6,11 +6,11 @@ import json import sqlite3 import sys -from contextlib import closing, nullcontext +from contextlib import nullcontext from itertools import chain from pathlib import Path -from litkit.db.handoff import completed_checkpoint +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 @@ -95,7 +95,7 @@ def verify_legacy_shard( 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 = closing(sqlite3.connect(main_path.resolve().as_uri() + "?mode=ro", uri=True)) + target = readable_database(main_path) with target as main: for row in chain([first], missing): if kind == "papers": diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index cfa399d..e15e8ce 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -646,11 +646,15 @@ def fail_chunk(index, path): assert sorted(faiss.vector_to_array(index.id_map)) == ([1, 2] if existing else [1]) -def test_rebuild_can_inspect_a_shard_with_a_hot_rollback_journal(tmp_path): +@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 - db = shard_db_path(tmp_path, 0) - init_shard_db(db, 0).close() + 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]) @@ -661,8 +665,16 @@ def test_rebuild_can_inspect_a_shard_with_a_hot_rollback_journal(tmp_path): 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 - assert unpublished_shards([db]) == [] - with closing(sqlite3.connect(db)) as conn: + 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,) From 77b373c4d7dd84256574dabdc23715579ca0179a Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 18:57:45 -0700 Subject: [PATCH 22/31] Validate both ends of shard transfers and retry incomplete schema creation Signed-off-by: Bill Hlavacek --- src/litkit/build/ingest_loop.py | 3 +- src/litkit/build/publication.py | 4 +- src/litkit/db/handoff.py | 64 ++++++++++++++++++++--- src/litkit/db/publication.py | 28 +--------- src/litkit/db/sharding.py | 4 +- tests/integration/test_batch_resume.py | 38 ++++++++++++++ tests/integration/test_build_and_query.py | 38 ++++++++++++++ 7 files changed, 141 insertions(+), 38 deletions(-) diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index f7b4801..8bf445e 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -683,7 +683,8 @@ def _render(force: bool = False): 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)) - if main_db.execute("SELECT 1 FROM files LIMIT 1").fetchone(): + 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)) diff --git a/src/litkit/build/publication.py b/src/litkit/build/publication.py index 61a2e83..9874bcf 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -12,8 +12,8 @@ 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_output_markers -from litkit.db.publication import PublicationRecord, read_publication, verify_checkpoint_revision +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 from litkit.segments.discovery import segment_order from litkit.segments.writer import finalized_name diff --git a/src/litkit/db/handoff.py b/src/litkit/db/handoff.py index c302247..b2f40e5 100644 --- a/src/litkit/db/handoff.py +++ b/src/litkit/db/handoff.py @@ -52,6 +52,32 @@ def merged_checkpoints(db, shard_id=None): 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") @@ -144,6 +170,21 @@ def _remember_version(base, version): _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.""" sqlite_dir = workspace / "sqlite" @@ -154,6 +195,8 @@ def prepare_local_shard(local, workspace, shard_id): 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() @@ -176,6 +219,8 @@ def prepare_local_shard(local, workspace, shard_id): 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 @@ -191,9 +236,8 @@ def prepare_local_shard(local, workspace, shard_id): _backup(source, target.with_suffix(".seed")) if checkpoint.is_file(): dest = target.parent / checkpoint.name - shared_segments = workspace / "emb_segments" local_segments = local / "emb_segments" - for marker in verify_output_markers(progress, shared_segments, shared_segments): + for marker in markers: _copy_file(marker, local_segments / marker.name) _sync_dir(local_segments) _copy_file(checkpoint, dest.with_suffix(".seed")) @@ -267,9 +311,16 @@ def copy_handoff(source, workspace, shard_id): receipt = sqlite_dir / f"producer_{shard_id}.transfer" identity = digest.hexdigest() shared_checkpoint = sqlite_dir / checkpoint.name - same_checkpoint = checkpoint_bytes == ( - shared_checkpoint.read_bytes() if shared_checkpoint.is_file() else None - ) + 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 {} + same_checkpoint = progress == shared_progress if same_checkpoint and receipt.is_file() and receipt.read_text() == identity and ( (sqlite_dir / source_db.name).is_file() or (sqlite_dir / "litkit.sqlite3").is_file() ): @@ -287,6 +338,8 @@ def copy_handoff(source, workspace, shard_id): f"Shared progress changed since local shard {shard_id} was prepared. " "Resume the producer from shared storage before copying this shard." ) + _transfer_checkpoint(source_db, progress, merged) + markers = verify_output_markers(progress, segment_dir, segment_dir) db_stage.mkdir(parents=True) seg_stage.mkdir(parents=True) _backup(source_db, db_stage / source_db.name) @@ -299,7 +352,6 @@ def copy_handoff(source, workspace, shard_id): stream.flush() os.fsync(stream.fileno()) meta = segment_dir / "build_meta.json" - markers = verify_output_markers(json.loads(checkpoint_bytes), segment_dir, segment_dir) if checkpoint_bytes else () for path in [*segments, *markers, done]: _copy_file(path, seg_stage / path.name) if meta.is_file(): diff --git a/src/litkit/db/publication.py b/src/litkit/db/publication.py index f4ae69d..8e35b26 100644 --- a/src/litkit/db/publication.py +++ b/src/litkit/db/publication.py @@ -6,7 +6,7 @@ from pathlib import Path from typing import NamedTuple -from litkit.db.handoff import completed_checkpoint, readable_database +from litkit.db.handoff import readable_database class PublicationRecord(NamedTuple): @@ -31,32 +31,6 @@ def read_publication(conn: sqlite3.Connection) -> PublicationRecord | None: return PublicationRecord(*row) if row else None -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 unpublished_shards(shards: list[Path], *, include_reservations: bool = False) -> list[Path]: """Find committed publications and, before a merge, journals needed for staging cleanup.""" pending = [] diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index 6ab7897..18caba4 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -12,8 +12,8 @@ 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_output_markers -from litkit.db.publication import unpublished_shards, verify_checkpoint_revision +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.schema import citation_columns, ensure_paper_embedding_column, paper_embedding_column diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index e15e8ce..c0b6624 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -678,6 +678,44 @@ def test_readers_recover_hot_rollback_journals(tmp_path, archive, entry): 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 diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index 12a2651..b8525f6 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -811,6 +811,44 @@ def test_producer_and_consumer_reject_mixed_batch_snapshots(isolated_env, tmp_pa 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("interruption", ["before-commit", "before-publish", "after-commit"]) def test_two_producers_resume_after_process_exit( isolated_env, corpus_dir, monkeypatch, interruption From f4104a8d9fa8f30cf4260b2e57e89e5699cb5d60 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 19:06:39 -0700 Subject: [PATCH 23/31] Check retained producer state before acknowledging a previous transfer Signed-off-by: Bill Hlavacek --- src/litkit/db/handoff.py | 6 ++-- tests/integration/test_build_and_query.py | 42 +++++++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/src/litkit/db/handoff.py b/src/litkit/db/handoff.py index b2f40e5..9163316 100644 --- a/src/litkit/db/handoff.py +++ b/src/litkit/db/handoff.py @@ -320,6 +320,10 @@ def copy_handoff(source, workspace, shard_id): 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 if same_checkpoint and receipt.is_file() and receipt.read_text() == identity and ( (sqlite_dir / source_db.name).is_file() or (sqlite_dir / "litkit.sqlite3").is_file() @@ -338,8 +342,6 @@ def copy_handoff(source, workspace, shard_id): f"Shared progress changed since local shard {shard_id} was prepared. " "Resume the producer from shared storage before copying this shard." ) - _transfer_checkpoint(source_db, progress, merged) - markers = verify_output_markers(progress, segment_dir, segment_dir) db_stage.mkdir(parents=True) seg_stage.mkdir(parents=True) _backup(source_db, db_stage / source_db.name) diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index b8525f6..52c9628 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -849,6 +849,48 @@ def test_requeued_handoff_checks_shared_segment_revision(isolated_env, tmp_path, 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" + 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 + 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() + + @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 62f81c1b6c3cebed4b333dfd43cd8efe77d5dcbb Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 19:15:17 -0700 Subject: [PATCH 24/31] Transfer historical content-addressed segments and interrupted claims Signed-off-by: Bill Hlavacek --- src/litkit/db/handoff.py | 11 +++++- src/litkit/segments/discovery.py | 22 +++++++++--- src/litkit/segments/metadata.py | 6 ++-- tests/integration/test_build_and_query.py | 44 +++++++++++++++++++++++ 4 files changed, 73 insertions(+), 10 deletions(-) diff --git a/src/litkit/db/handoff.py b/src/litkit/db/handoff.py index 9163316..952fe93 100644 --- a/src/litkit/db/handoff.py +++ b/src/litkit/db/handoff.py @@ -289,6 +289,10 @@ def finish_handoff(sqlite_dir, shard_id, *, database_open=False): 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) @@ -296,7 +300,9 @@ def copy_handoff(source, workspace, shard_id): 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(segment_dir.glob(f"*_seg_{shard_id}_*.npz")) + 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 @@ -374,6 +380,9 @@ def copy_handoff(source, workspace, 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": diff --git a/src/litkit/segments/discovery.py b/src/litkit/segments/discovery.py index 86409da..7670a68 100644 --- a/src/litkit/segments/discovery.py +++ b/src/litkit/segments/discovery.py @@ -28,6 +28,13 @@ def is_pending_segment(name): 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 @@ -38,6 +45,13 @@ def iter_segment_files(seg_dir, kind): 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: @@ -61,11 +75,9 @@ def _shard_count(directory, segments, transfers=(), ids=()): if match: ids.append(int(match[1])) for path in segments: - match = re.match(r"(?:paper|chunk)_seg_(\d+)_", path.name) or re.search( - r"_sh(\d+)_", path.name - ) - if match: - ids.append(int(match[1])) + 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 diff --git a/src/litkit/segments/metadata.py b/src/litkit/segments/metadata.py index 4343362..9f920a1 100644 --- a/src/litkit/segments/metadata.py +++ b/src/litkit/segments/metadata.py @@ -13,7 +13,7 @@ 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 +from litkit.segments.discovery import is_pending_segment, iter_segment_files, iter_shard_segment_files def _eprint(msg: str = "", *, end: str = "\n") -> None: @@ -67,9 +67,7 @@ def verify_legacy_shard( # 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_segment_files(directory, kind): - if path.name.startswith(prefix + "_") and not path.name.startswith(f"{prefix}_{shard_id}_"): - continue + for path in iter_shard_segment_files(directory, kind, shard_id): if replaced or different_texts: raise RuntimeError(f"Legacy segment files do not identify the stored revision. {message}") with np.load(path, allow_pickle=True) as segment: diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index 52c9628..0ebbd5b 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -891,6 +891,50 @@ def stop(src, dst): 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() + + @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 4c707af22b4e9178ec2c8440e486b09c2ae78ebb Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 19:27:19 -0700 Subject: [PATCH 25/31] Preserve index and checkpoint consistency across cluster resubmissions and rebuilds Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 1 + src/litkit/build/indices.py | 51 +++++------- src/litkit/build/publication.py | 17 +++- src/litkit/cli.py | 39 +++++---- src/litkit/db/handoff.py | 5 ++ src/litkit/db/sharding.py | 7 -- tests/integration/test_build_and_query.py | 98 +++++++++++++++++++++++ vector_build_multi.sbatch | 4 +- 8 files changed, 163 insertions(+), 59 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9271a51..df28efd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ internal versions are summarized under 0.3.33. ## [Unreleased] ### Fixed +- Resubmitting a cluster build preserves populated FAISS indexes. A writer rebuild also retires detached shard checkpoints so producers can add new archives afterward. - Shard merges commit and detach each database before deleting it. Builds with more than ten producer shards can now merge every shard. Node-local transfers publish the checkpoint, database, segments and completion marker from a recoverable copy on shared storage. (#1) - Completed consumers now mark every saved paper and chunk as indexed when FAISS saves are throttled. - Tar builds commit articles in batches. Interrupted producers resume with complete paper and chunk segments, and consumers ignore unfinished files. For a producer already interrupted on an older release, rebuild from the original archives in a fresh workspace. (#13, #3, #4) 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/publication.py b/src/litkit/build/publication.py index 9874bcf..c2bb790 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -14,17 +14,26 @@ 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 +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) -> None: - """Invalidate the active batch in the same transaction as an explicit rebuild.""" +def reset_publication(conn: sqlite3.Connection, sqlite_dir: Path) -> None: + """Retire writer and detached shard progress while producer admission is held.""" + from litkit.db.sharding import shard_db_path + if read_publication(conn): conn.execute("UPDATE ingest_publication SET tar=NULL WHERE singleton=1") if conn.execute("SELECT 1 FROM sqlite_master WHERE name='merged_shard_checkpoints'").fetchone(): - conn.execute("DELETE FROM merged_shard_checkpoints") + for (shard_id,) in conn.execute("SELECT shard_id FROM merged_shard_checkpoints").fetchall(): + if shard_db_path(sqlite_dir, shard_id).exists(): + continue # A retained shard can still depend on its last merged revision. + checkpoint = shard_ckpt_path(sqlite_dir, shard_id) + 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): diff --git a/src/litkit/cli.py b/src/litkit/cli.py index fdc5617..7caff87 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1071,6 +1071,14 @@ def build_or_update_indices(args): # 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) @@ -1124,8 +1132,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 @@ -1175,10 +1185,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: + 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, @@ -1233,9 +1250,6 @@ def _build_or_update_indices(args): # Guard: --rebuild with unconsumed segments or active producers can corrupt data # This check is here (not in main()) because it requires heavy deps for segment functions if not getattr(args, "force_rebuild", False): - from litkit.db.sharding import recover_staged_shards - - recover_staged_shards(SQLITE_DIR, FileLock) seg_dir = args.embed_outdir or EMBED_SEGMENTS_DIR conflict_reasons = [] @@ -1288,21 +1302,16 @@ 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) from litkit.build.publication import reset_publication with conn: conn.execute("BEGIN") + reset_publication(conn, SQLITE_DIR) for table in ("chunks", "papers", "files"): cur.execute(f"DELETE FROM {table}") - reset_publication(conn) + 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 @@ -1819,7 +1828,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)") diff --git a/src/litkit/db/handoff.py b/src/litkit/db/handoff.py index 952fe93..e43d893 100644 --- a/src/litkit/db/handoff.py +++ b/src/litkit/db/handoff.py @@ -187,6 +187,11 @@ def _transfer_checkpoint(database, progress, merged): 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" diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index 18caba4..0faab2e 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -104,13 +104,6 @@ def producer_shard_lock(sqlite_dir, shard_id, lock_factory=FileLock, *, database yield -def recover_staged_shards(sqlite_dir, lock_factory=FileLock): - """Complete interrupted transfers before checking the producers' completion markers.""" - for shard_id in staged_shards(sqlite_dir): - with producer_shard_lock(sqlite_dir, shard_id, lock_factory): - pass - - @contextmanager def merged_shard_databases( main_conn: sqlite3.Connection, diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index 0ebbd5b..81ca327 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -935,6 +935,104 @@ def test_node_local_transfer_includes_verified_legacy_files_and_claims(isolated_ 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() + + +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") + _ok(litkit(ws, *produce, "--shard-id", "0")) + 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 diff --git a/vector_build_multi.sbatch b/vector_build_multi.sbatch index 9615a5d..fec0290 100644 --- a/vector_build_multi.sbatch +++ b/vector_build_multi.sbatch @@ -232,7 +232,7 @@ run_producer() { 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}] Resuming an interrupted batch on NFS" + echo "[Producer ${PRODUCER_NODE_ID}] Using NFS directly" ACTUAL_USE_LOCAL_STAGING=0 CONTAINER_WS="${CONTAINER_NFS_WS}" EMBED_OUTDIR="${CONTAINER_WS}/emb_segments" @@ -386,7 +386,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 From ad2a9c78e4a6f381237fa2604596ea7692cad461 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 19:45:36 -0700 Subject: [PATCH 26/31] Verify indexed worker rows and consume revised paper text, citations and vectors together Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 4 +- src/litkit/build/ingest_loop.py | 44 +++++++-- src/litkit/build/publication.py | 9 +- src/litkit/cli.py | 2 +- src/litkit/db/queries.py | 16 +++- src/litkit/db/sharding.py | 52 ++++++++-- src/litkit/segments/ingest.py | 47 ++++++++- src/litkit/segments/metadata.py | 23 +++-- tests/integration/test_batch_resume.py | 3 +- tests/integration/test_build_and_query.py | 111 ++++++++++++++++++++-- 10 files changed, 264 insertions(+), 47 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df28efd..bebf1f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,8 @@ internal versions are summarized under 0.3.33. ### Fixed - Resubmitting a cluster build preserves populated FAISS indexes. A writer rebuild also retires detached shard checkpoints so producers can add new archives afterward. - Shard merges commit and detach each database before deleting it. Builds with more than ten producer shards can now merge every shard. Node-local transfers publish the checkpoint, database, segments and completion marker from a recoverable copy on shared storage. (#1) -- Completed consumers now mark every saved paper and chunk as indexed when FAISS saves are throttled. -- Tar builds commit articles in batches. Interrupted producers resume with complete paper and chunk segments, and consumers ignore unfinished files. For a producer already interrupted on an older release, rebuild from the original archives in a fresh workspace. (#13, #3, #4) +- 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. Interrupted producers resume with complete paper and chunk segments, and consumers ignore unfinished files. 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) diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index 8bf445e..71eba80 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -239,6 +239,7 @@ def process_tar_files( 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 @@ -284,6 +285,13 @@ def flush_batch(tar: str, members: int) -> None: # 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 ( @@ -358,6 +366,7 @@ def stage_indexes(paper_dir, chunk_dir): 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 @@ -467,7 +476,7 @@ def _render(force: bool = False): # 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): + 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 @@ -506,13 +515,19 @@ def _render(force: bool = False): # Content-addressed doc_id: use DB's canonical doc_id when reusing # an existing paper row. existing_row = None + canonical = None if pmcid: existing_row = cur.execute( - "SELECT id, doc_id, embedding_text FROM papers WHERE pmcid=?", (pmcid,) + "SELECT id, doc_id, embedding_text FROM papers WHERE pmcid=? AND pmcid<>''", (pmcid,) ).fetchone() if (existing_row is None) and pmid: existing_row = cur.execute( - "SELECT id, doc_id, embedding_text FROM papers WHERE pmid=?", (pmid,) + "SELECT id, doc_id, embedding_text FROM papers WHERE pmid=? AND pmid<>''", (pmid,) + ).fetchone() + if existing_row is None: + existing_row = cur.execute( + "SELECT p.id, p.doc_id, p.embedding_text FROM files f JOIN papers p ON p.id=f.paper_id " + "WHERE f.path=?", (f,) ).fetchone() if existing_row: @@ -528,14 +543,17 @@ def _render(force: bool = False): else: # A previous consume may have removed the shard that # assigned this paper its canonical document ID. - canonical = None if merged is not None and pmcid: canonical = merged.execute( - "SELECT doc_id FROM papers WHERE pmcid=?", (pmcid,) + "SELECT doc_id FROM papers WHERE pmcid=? AND pmcid<>''", (pmcid,) ).fetchone() if merged is not None and not canonical and pmid: canonical = merged.execute( - "SELECT doc_id FROM papers WHERE pmid=?", (pmid,) + "SELECT doc_id FROM papers WHERE pmid=? AND pmid<>''", (pmid,) + ).fetchone() + if merged is not None and not canonical: + canonical = merged.execute( + "SELECT p.doc_id FROM files f JOIN papers p ON p.id=f.paper_id WHERE f.path=?", (f,) ).fetchone() canon_doc_id = canonical[0] if canonical and canonical[0] else f cur.execute( @@ -549,7 +567,8 @@ def _render(force: bool = False): is not None ) old_ids = [] - if seen_this_path: + shard_revision = embed_producer and (existing_row is not None or canonical is not None) + 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,) )] @@ -584,6 +603,12 @@ def _render(force: bool = False): paper_ids_buf.append(pid) paper_texts_buf.append(ta_ab) paper_doc_ids_buf.append(canon_doc_id) + if shard_revision: + cur.execute( + "UPDATE papers SET title=?, abstract=?, source_path=?, embedding_text=? WHERE id=?", + (meta["title"], meta["abstract"], meta.get("source_path"), + previous_text if reuse_embedding else ta_ab, pid), + ) body = pack_body(meta, chunk_target_chars, chunk_min_chars, chunk_overlap) proposed_chunks = [(-1, ta_ab, None)] if ta_ab else [] @@ -606,8 +631,9 @@ def _render(force: bool = False): if existing_row and not reuse_embedding: # A saved ID alone cannot distinguish two revisions after restart. replaced_papers.add(pid) - if seen_this_path: - replaced_chunks.update(old_ids) + 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}") diff --git a/src/litkit/build/publication.py b/src/litkit/build/publication.py index c2bb790..4f5c13e 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -19,15 +19,20 @@ from litkit.segments.writer import finalized_name -def reset_publication(conn: sqlite3.Connection, sqlite_dir: Path) -> None: +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 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") 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(): - if shard_db_path(sqlite_dir, shard_id).exists(): + source = shard_db_path(sqlite_dir, shard_id) + if source.exists(): + with readable_database(source) as shard: + verify_legacy_shard(shard, shard_id, seg_dir, seg_dir, before_rebuild=True) continue # A retained shard can still depend on its last merged revision. checkpoint = shard_ckpt_path(sqlite_dir, shard_id) checkpoint.unlink(missing_ok=True) diff --git a/src/litkit/cli.py b/src/litkit/cli.py index 7caff87..3be5a58 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1307,7 +1307,7 @@ def _build_or_update_indices(args): with conn: conn.execute("BEGIN") - reset_publication(conn, SQLITE_DIR) + 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): diff --git a/src/litkit/db/queries.py b/src/litkit/db/queries.py index d44d9ba..0b549b9 100644 --- a/src/litkit/db/queries.py +++ b/src/litkit/db/queries.py @@ -18,6 +18,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 +34,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 diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index 0faab2e..9dfec16 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -47,8 +47,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) # --------------------------------------------------------------------------- @@ -192,6 +195,38 @@ def merge_drained_shards(main_conn, sqlite_dir, delete_after_merge, segment_dir) 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.""" + if not conn.execute(f"SELECT 1 FROM {shard}.sqlite_master WHERE name='producer_revisions'").fetchone(): + return + revisions = conn.execute(f""" + SELECT m.main_pid, p.id, p.title, p.abstract, p.source_path, p.embedding_text + FROM {shard}.producer_revisions r JOIN {shard}.papers p ON p.id=r.paper_id + JOIN {mapping} m ON m.shard_pid=p.id WHERE r.sequence > ? + """, (since,)) + for main_id, local_id, title, abstract, source_path, embedding_text in revisions: + 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 WHERE id=:id + """, {"title": title, "abstract": abstract, "source": source_path, "input": embedding_text, "id": main_id}) + 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=?) + """, (main_id, local_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) + + 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} @@ -227,9 +262,6 @@ def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge, to_record): 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] @@ -275,6 +307,12 @@ def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge, to_record): 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, {}) + _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 @@ -292,15 +330,11 @@ def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge, to_record): 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 diff --git a/src/litkit/segments/ingest.py b/src/litkit/segments/ingest.py index dc3e11e..844d5ab 100644 --- a/src/litkit/segments/ingest.py +++ b/src/litkit/segments/ingest.py @@ -28,6 +28,7 @@ from litkit.index.dedup import add_with_ids_dedup from litkit.index.io import faiss_save, faiss_save_force from litkit.index.ids import 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 @@ -83,6 +84,33 @@ def _report_segment_error(errors: list[str] | None, path: Path, error: Exception errors.append(message) +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): + index.remove_ids(np.asarray(ids, dtype=np.int64)) + 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 _hnsw_without_ids(index, replacing): + """Rebuild a graph without the old revisions. HNSW cannot remove individual nodes.""" + replacement = faiss.clone_index(index) + replacement.reset() + old_ids = faiss.vector_to_array(index.id_map) + core = faiss.downcast_index(index.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)) + replacement.add_with_ids(vectors[keep], batch[keep]) + return replacement + + def ingest_paper_segments( conn: sqlite3.Connection, paper_index: faiss.Index, @@ -152,6 +180,9 @@ def ingest_paper_segments( if unsaved_ids is None: unsaved_ids = [] + hnsw_ids = None + if kind_and_core(paper_index)[0] == "hnsw": + hnsw_ids = faiss_present_ids(paper_index) or set() cur = conn.cursor() added_total = 0 batch_counter = 0 @@ -236,12 +267,20 @@ def ingest_paper_segments( added, ids_added, saved = 0, [], False with FileLock(faiss_lock_path): + target = paper_index + if hnsw_ids is not None: + replacing = hnsw_ids.intersection(ids) + if replacing: + target = _hnsw_without_ids(paper_index, replacing) # add_with_ids_dedup handles removal internally - no explicit safe_remove_ids needed - added, ids_added = add_with_ids_dedup(paper_index, ids, X) + added, ids_added = add_with_ids_dedup(target, ids, X) 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) + saved = faiss_save_force(target, paper_index_path) if prior_ntotal == 0 \ + else faiss_save(target, paper_index_path) + paper_index = target + if hnsw_ids is not None: + hnsw_ids.update(ids_added) if added: unsaved_ids.append(ids_added) @@ -333,6 +372,8 @@ def ingest_chunk_segments( outdir = Path(outdir) if not outdir.exists(): return chunk_index, 0 + + _remove_obsolete_chunks(conn, chunk_index, chunk_index_path, faiss_lock_path, db_lock_path, FileLock) # Ensure external ID mapping is present for robust remove and add if not isinstance(chunk_index, faiss.IndexIDMap2): diff --git a/src/litkit/segments/metadata.py b/src/litkit/segments/metadata.py index 9f920a1..961c5bb 100644 --- a/src/litkit/segments/metadata.py +++ b/src/litkit/segments/metadata.py @@ -32,13 +32,15 @@ def has_segment_files(seg_dir: Path) -> bool: def verify_legacy_shard( conn: sqlite3.Connection, shard_id: int, paper_dir: Path, chunk_dir: Path, - *, merged_db: sqlite3.Connection | None = None, + *, merged_db: sqlite3.Connection | None = None, before_rebuild: bool = False, ) -> None: """Account for old producer rows, including rows committed before the first checkpoint.""" - if completed_checkpoint(conn) or not conn.execute("SELECT 1 FROM files LIMIT 1").fetchone(): + 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 journal and journal.tar is not None: + 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 @@ -50,6 +52,11 @@ def verify_legacy_shard( "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] @@ -57,9 +64,9 @@ def verify_legacy_shard( "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"), + ("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"), + "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}_*")): @@ -69,6 +76,8 @@ def verify_legacy_shard( 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: @@ -81,10 +90,12 @@ def verify_legacy_shard( # 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) if tuple(row[1:]) not in ready_keys) + 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) diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index c0b6624..95c3c68 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -307,7 +307,8 @@ def test_ingest_and_merge_through_existing_pre_embedding_text_connections(tmp_pa conn.execute("ALTER TABLE papers DROP COLUMN embedding_text") with closing(connect_db(build.db)) as producer: producer.autocommit = autocommit - assert build.run(conn=producer)[2:] == (1, 2) + # 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 diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index 81ca327..df10369 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -673,24 +673,36 @@ def fail_publish(path, dest): @pytest.mark.parametrize("node_local", [False, True]) -def test_detached_checkpoint_and_incremental_alias(isolated_env, tmp_path, monkeypatch, node_local): +@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=[])}) + 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", *FLAT)) + _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 in range(2): - if run: - write_tar(tars / "b.tar", {"alias.xml": jats(title="Revision", pmcid="PMC42", paragraphs=["New body."])}) + 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) @@ -701,12 +713,29 @@ def test_detached_checkpoint_and_incremental_alias(isolated_env, tmp_path, monke 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 in_index=1").fetchall() == [ + 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 + 1,) - assert db.execute("SELECT count(*) FROM chunks WHERE in_index=1").fetchone() == (run + 1,) - assert _ntotal(shared, "chunks.faiss") == run + 1 + 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.*")) @@ -987,6 +1016,68 @@ def test_cluster_bootstrap_preserves_existing_indices(isolated_env, corpus_dir, 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): + import numpy as np + from contextlib import closing + 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 From 69ac54d2ad2f7da9105a59aa9be7d599e6d75b29 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 19:57:46 -0700 Subject: [PATCH 27/31] Keep delayed shard segments and IVF labels consistent with the current passages Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 1 + src/litkit/build/ingest_loop.py | 4 +- src/litkit/build/publication.py | 21 ++++++--- src/litkit/db/sharding.py | 18 ++++++-- src/litkit/index/ids.py | 64 +++++++++++++++++++++++++- src/litkit/segments/ingest.py | 41 +++++++++++++++-- src/litkit/segments/writer.py | 16 ++++++- tests/integration/test_batch_resume.py | 50 +++++++++++++++++--- tests/test_index.py | 41 +++++++++++++++++ 9 files changed, 230 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bebf1f8..bbcb0a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ internal versions are summarized under 0.3.33. ## [Unreleased] ### Fixed +- 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. - Shard merges commit and detach each database before deleting it. Builds with more than ten producer shards can now merge every shard. Node-local transfers publish the checkpoint, database, segments and completion marker from a recoverable copy on shared storage. (#1) - 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. diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index 71eba80..5c6eefb 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -295,10 +295,10 @@ def flush_batch(tar: str, members: int) -> None: def stage_segments(paper_dir, chunk_dir): return ( - paper_seg_writer.stage(paper_dir, doc_ids=doc_ids, vecs=xp, sequence=sequence) + 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) if cids else None, + sequence=sequence, texts=passages) if cids else None, ) publication.publish(tar, members, stage_segments) diff --git a/src/litkit/build/publication.py b/src/litkit/build/publication.py index 4f5c13e..8d740e7 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -22,22 +22,31 @@ 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 readable_database + 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) - continue # A retained shard can still depend on its last merged revision. - checkpoint = shard_ckpt_path(sqlite_dir, shard_id) - checkpoint.unlink(missing_ok=True) - # If the reset rolls back, the SQLite receipt can restore the JSON. - maybe_fsync_dir(checkpoint) + 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,)) diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index 9dfec16..cddc109 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -198,19 +198,26 @@ def merge_drained_shards(main_conn, sqlite_dir, delete_after_merge, segment_dir) def _merge_revised_papers(conn, shard, mapping, since): """Refresh retrieval text only for articles revised since this shard's last merge.""" if not conn.execute(f"SELECT 1 FROM {shard}.sqlite_master WHERE name='producer_revisions'").fetchone(): - return + return 0 + inserted = 0 revisions = conn.execute(f""" SELECT m.main_pid, p.id, p.title, p.abstract, p.source_path, p.embedding_text FROM {shard}.producer_revisions r JOIN {shard}.papers p ON p.id=r.paper_id JOIN {mapping} m ON m.shard_pid=p.id WHERE r.sequence > ? """, (since,)) for main_id, local_id, title, abstract, source_path, embedding_text in revisions: + 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 WHERE id=:id """, {"title": title, "abstract": abstract, "source": source_path, "input": embedding_text, "id": main_id}) + 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=?", @@ -225,6 +232,7 @@ def _merge_revised_papers(conn, shard, mapping, since): 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): @@ -297,12 +305,14 @@ def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge, to_record): """) # 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 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 ) @@ -312,7 +322,9 @@ def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge, to_record): if shard_db in to_record: shard_id = to_record[shard_db][0] previous = merged_checkpoints(main_conn, shard_id).get(shard_id, {}) - _merge_revised_papers(main_conn, shard_alias, temp_map_table, previous.get("segment_sequence", 0)) + 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 diff --git a/src/litkit/index/ids.py b/src/litkit/index/ids.py index 7d7d0c9..fcced68 100644 --- a/src/litkit/index/ids.py +++ b/src/litkit/index/ids.py @@ -42,12 +42,70 @@ def make_id_selector(ids_like: list[int] | np.ndarray) -> Any: Sel = getattr(faiss, "IDSelectorBatch", None) if Sel is not None: - return Sel(ids_arr) + selector = Sel(ids_arr) + selector._litkit_ids = ids_arr + return selector # Fallback: return raw array (caller must handle differently) return ids_arr +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 safe_remove_ids(index: faiss.Index, sel: Any) -> int: """Best-effort removal of IDs from a FAISS index. @@ -65,9 +123,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/ingest.py b/src/litkit/segments/ingest.py index 844d5ab..686d8d1 100644 --- a/src/litkit/segments/ingest.py +++ b/src/litkit/segments/ingest.py @@ -16,6 +16,7 @@ import time from contextlib import nullcontext from dataclasses import dataclass +from functools import partial from pathlib import Path from typing import TYPE_CHECKING @@ -25,6 +26,7 @@ from litkit.db.indexing import flush_pending_marks, 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.ids import make_id_selector, safe_remove_ids @@ -84,13 +86,36 @@ def _report_segment_error(errors: list[str] | None, path: Path, error: Exception errors.append(message) +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.doc_id, NULL, p.embedding_text" if kind == "papers" else "p.doc_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}") + revised = {} + for doc, ordinal, text in rows: + revised.setdefault(doc, {})[ordinal] = text_digest(text) + return revised + + +def _current_segment_rows(segment, revised, documents, ordinals): + if not revised or "text_hashes" not in segment.files: + return slice(None) + return np.array([ + doc not in revised or revised[doc].get(ordinal) == bytes(digest) + for doc, ordinal, digest in zip(documents, ordinals, segment["text_hashes"], strict=True) + ], dtype=bool) + + 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): - index.remove_ids(np.asarray(ids, dtype=np.int64)) + 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)) @@ -154,7 +179,7 @@ def ingest_paper_segments( # Lazy import if not provided 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(): @@ -180,6 +205,7 @@ def ingest_paper_segments( if unsaved_ids is None: unsaved_ids = [] + revised = _revised_inputs(conn, "papers") hnsw_ids = None if kind_and_core(paper_index)[0] == "hnsw": hnsw_ids = faiss_present_ids(paper_index) or set() @@ -211,6 +237,8 @@ def ingest_paper_segments( 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)) + current = _current_segment_rows(z, revised, doc_ids, [None] * len(doc_ids)) + doc_ids, X = doc_ids[current], X[current] # Resolve doc_id → paper_id using preloaded map (O(1) lookups) resolved_ids = [] @@ -230,7 +258,7 @@ def ingest_paper_segments( _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: + if len(doc_ids) and 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: @@ -367,7 +395,7 @@ def ingest_chunk_segments( # Lazy import if not provided 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(): @@ -402,6 +430,7 @@ def ingest_chunk_segments( if unsaved_ids is None: unsaved_ids = [] + revised = _revised_inputs(conn, "chunks") cur = conn.cursor() added_total = 0 batch_counter = 0 @@ -432,6 +461,8 @@ def ingest_chunk_segments( paper_doc_ids = z["paper_doc_ids"] # object array of strings ords = z["ords"] # int32 array X = np.ascontiguousarray(z["vecs"].astype(np.float32)) + current = _current_segment_rows(z, revised, paper_doc_ids, ords) + paper_doc_ids, ords, X = paper_doc_ids[current], ords[current], X[current] # Resolve (paper_doc_id, ord) → chunk_id using preloaded maps (O(1) lookups) resolved_ids = [] @@ -461,7 +492,7 @@ def ingest_chunk_segments( _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: + if len(paper_doc_ids) and 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: diff --git a/src/litkit/segments/writer.py b/src/litkit/segments/writer.py index f4b8b63..1e1a947 100644 --- a/src/litkit/segments/writer.py +++ b/src/litkit/segments/writer.py @@ -10,6 +10,7 @@ from __future__ import annotations +import hashlib import os import sys import uuid @@ -38,8 +39,16 @@ 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.""" + 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) @@ -247,6 +256,7 @@ def _write_batch(self, doc_ids, vecs) -> 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): @@ -258,6 +268,7 @@ def stage( _write_segment( path, 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), ) @@ -440,7 +451,7 @@ def _write_batch(self, paper_doc_ids, ords, vecs) -> Path: def stage( self, directory: Path, *, paper_doc_ids: list[str], ords: list[int], vecs: np.ndarray, - sequence: int | None = None, + 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): @@ -452,6 +463,7 @@ def stage( _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"), diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 95c3c68..bac0ea5 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -81,13 +81,13 @@ def test_producer_resolves_equivalent_output_directories(tmp_path, archive): class Build: - def __init__(self, root, tar, *, producer=True): + def __init__(self, root, tar, *, producer=True, shard_id=0): self.root = root self.tar = tar self.producer = producer - self.shard = 0 if producer else None + self.shard = shard_id if producer else None self.segments = root / "segments" - self.db = shard_db_path(root, 0) if producer else root / "main.sqlite3" + 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" @@ -102,7 +102,7 @@ def open_index(path): 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, 0) if self.producer else init_db(self.db) + init_shard_db(self.db, self.shard) if self.producer else init_db(self.db) ) with connection as conn: options = dict( @@ -112,8 +112,8 @@ def open_index(path): chunk_embedder=FakeEmbedder(), paper_index=open_index(self.paper_path), chunk_index=open_index(self.chunk_path), - paper_seg_writer=SegmentWriter(self.segments) if self.producer else None, - chunk_seg_writer=ChunkSegmentWriter(self.segments) if self.producer else None, + 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, @@ -178,6 +178,44 @@ class InjectedFailure(Exception): pass +@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: diff --git a/tests/test_index.py b/tests/test_index.py index 89c1b5f..7295418 100644 --- a/tests/test_index.py +++ b/tests/test_index.py @@ -116,6 +116,47 @@ 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])) + + # ------------------------------------------------------------- approximate From 3377110034eedb7fe436da60b21596f15f67b6d9 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 20:08:53 -0700 Subject: [PATCH 28/31] Reconcile current article revisions and backfill throttled batches once Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 1 + src/litkit/build/backfill.py | 209 +++++++------------ src/litkit/build/ingest_loop.py | 6 +- src/litkit/index/ids.py | 13 ++ src/litkit/segments/ingest.py | 241 ++++++++-------------- tests/integration/test_batch_resume.py | 82 ++++++++ tests/integration/test_build_and_query.py | 65 ++++++ 7 files changed, 318 insertions(+), 299 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bbcb0a6..3f927a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ 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. - Shard merges commit and detach each database before deleting it. Builds with more than ten producer shards can now merge every shard. Node-local transfers publish the checkpoint, database, segments and completion marker from a recoverable copy on shared storage. (#1) diff --git a/src/litkit/build/backfill.py b/src/litkit/build/backfill.py index 63ffc10..3c9217c 100644 --- a/src/litkit/build/backfill.py +++ b/src/litkit/build/backfill.py @@ -20,10 +20,11 @@ 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 @@ -67,88 +68,57 @@ def backfill_unindexed_vectors( chunk_bs: Batch size for chunk embedding """ cur = conn.cursor() - - # Papers recorded_text = paper_embedding_column(conn) - while True: - rows = cur.execute( - 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 WHERE p.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() + 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( @@ -162,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/ingest_loop.py b/src/litkit/build/ingest_loop.py index 5c6eefb..3cd8d51 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -599,9 +599,11 @@ def _render(force: bool = False): "UPDATE papers SET embedding_text=? WHERE id=?", (previous_text if reuse_embedding else ta_ab, pid), ) - if not reuse_embedding: + # 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(ta_ab) + 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( diff --git a/src/litkit/index/ids.py b/src/litkit/index/ids.py index fcced68..83ccc22 100644 --- a/src/litkit/index/ids.py +++ b/src/litkit/index/ids.py @@ -106,6 +106,19 @@ def _remove_mapped_ivf_ids(index, core, selector): 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: """Best-effort removal of IDs from a FAISS index. diff --git a/src/litkit/segments/ingest.py b/src/litkit/segments/ingest.py index 686d8d1..a0a80c6 100644 --- a/src/litkit/segments/ingest.py +++ b/src/litkit/segments/ingest.py @@ -29,7 +29,7 @@ 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.ids import make_id_selector, safe_remove_ids +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: @@ -89,27 +89,82 @@ def _report_segment_error(errors: list[str] | None, path: Path, error: Exception 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.doc_id, NULL, p.embedding_text" if kind == "papers" else "p.doc_id, c.ord, c.text" + return {}, {} + fields = "p.id, p.doc_id, NULL, p.embedding_text" if kind == "papers" else "c.id, p.doc_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}") - revised = {} - for doc, ordinal, text in rows: - revised.setdefault(doc, {})[ordinal] = text_digest(text) - return revised + documents, numeric = {}, {} + for row_id, doc, ordinal, text in rows: + digest = text_digest(text) + documents.setdefault(doc, {})[ordinal] = digest + numeric[row_id] = digest + return documents, numeric + + +def _read_segment(conn, path, kind, papers, chunks, revisions, numeric_ids): + """Resolve IDs and accept vectors whose embedding input matches the current revision.""" + by_doc, 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_doc[doc].get(None, b"") if doc in by_doc else None for doc in docs] + elif kind == "chunks" and {"paper_doc_ids", "ords", "vecs"} <= fields: + keys = [(str(doc), int(ordinal)) for doc, ordinal in + zip(segment["paper_doc_ids"], segment["ords"], strict=True)] + ids = [chunks.get((papers.get(doc), ordinal)) for doc, ordinal in keys] + expected = [by_doc[doc].get(ordinal, b"") if doc in by_doc else None for doc, 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) + keep, resolved = [], [] + unresolved = unverified = 0 + for row_id, current, digest in 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: + resolved.append(row_id) + keep.append(True) + continue + keep.append(False) + 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.asarray(resolved, dtype=np.int64), vectors[np.asarray(keep, dtype=bool)], disposition -def _current_segment_rows(segment, revised, documents, ordinals): - if not revised or "text_hashes" not in segment.files: - return slice(None) - return np.array([ - doc not in revised or revised[doc].get(ordinal) == bytes(digest) - for doc, ordinal, digest in zip(documents, ordinals, segment["text_hashes"], strict=True) - ], dtype=bool) +def _finish_segment(path, disposition): + if disposition: + path.replace(path.with_suffix(f".{disposition}.{time.time_ns()}")) + else: + path.unlink() -def _remove_obsolete_chunks(conn, index, path, faiss_lock, db_lock, lock_factory): +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")] @@ -121,21 +176,6 @@ def _remove_obsolete_chunks(conn, index, path, faiss_lock, db_lock, lock_factory conn.executemany("DELETE FROM obsolete_chunk_vectors WHERE id=?", ((i,) for i in ids)) -def _hnsw_without_ids(index, replacing): - """Rebuild a graph without the old revisions. HNSW cannot remove individual nodes.""" - replacement = faiss.clone_index(index) - replacement.reset() - old_ids = faiss.vector_to_array(index.id_map) - core = faiss.downcast_index(index.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)) - replacement.add_with_ids(vectors[keep], batch[keep]) - return replacement - - def ingest_paper_segments( conn: sqlite3.Connection, paper_index: faiss.Index, @@ -206,6 +246,7 @@ def ingest_paper_segments( if unsaved_ids is None: unsaved_ids = [] revised = _revised_inputs(conn, "papers") + numeric_ids = set() hnsw_ids = None if kind_and_core(paper_index)[0] == "hnsw": hnsw_ids = faiss_present_ids(paper_index) or set() @@ -228,63 +269,10 @@ def ingest_paper_segments( break 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)) - current = _current_segment_rows(z, revised, doc_ids, [None] * len(doc_ids)) - doc_ids, X = doc_ids[current], X[current] - - # 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 len(doc_ids) and 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}") - + ids, X, disposition = _read_segment(conn, tmp, "papers", paper_id_map, None, revised, numeric_ids) + if ids.size == 0: - os.remove(tmp) + _finish_segment(tmp, disposition) continue # Ensure IDMap2 wrapper for external ID tracking @@ -299,7 +287,8 @@ def ingest_paper_segments( if hnsw_ids is not None: replacing = hnsw_ids.intersection(ids) if replacing: - target = _hnsw_without_ids(paper_index, replacing) + target = faiss.clone_index(paper_index) + copy_hnsw_without_ids(paper_index, target, replacing) # add_with_ids_dedup handles removal internally - no explicit safe_remove_ids needed added, ids_added = add_with_ids_dedup(target, ids, X) if added: @@ -318,7 +307,7 @@ def ingest_paper_segments( added_total += int(added or 0) batch_counter += 1 - os.remove(tmp) + _finish_segment(tmp, disposition) # Periodic save if (batch_counter % max(1, int(save_every))) == 0: @@ -401,7 +390,7 @@ def ingest_chunk_segments( if not outdir.exists(): return chunk_index, 0 - _remove_obsolete_chunks(conn, chunk_index, chunk_index_path, faiss_lock_path, db_lock_path, FileLock) + remove_obsolete_chunks(conn, chunk_index, chunk_index_path, faiss_lock_path, db_lock_path, FileLock) # Ensure external ID mapping is present for robust remove and add if not isinstance(chunk_index, faiss.IndexIDMap2): @@ -431,6 +420,7 @@ def ingest_chunk_segments( if unsaved_ids is None: unsaved_ids = [] revised = _revised_inputs(conn, "chunks") + numeric_ids = set() cur = conn.cursor() added_total = 0 batch_counter = 0 @@ -451,75 +441,10 @@ def ingest_chunk_segments( break 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)) - current = _current_segment_rows(z, revised, paper_doc_ids, ords) - paper_doc_ids, ords, X = paper_doc_ids[current], ords[current], X[current] - - # 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 len(paper_doc_ids) and 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}") - + ids, X, disposition = _read_segment(conn, tmp, "chunks", paper_id_map, chunk_id_map, revised, numeric_ids) + if ids.size == 0: - os.remove(tmp) + _finish_segment(tmp, disposition) continue prior_ntotal = int(getattr(chunk_index, "ntotal", 0) or 0) @@ -540,7 +465,7 @@ def ingest_chunk_segments( added_total += int(added) batch_counter += 1 - os.remove(tmp) + _finish_segment(tmp, disposition) # Periodic save if (batch_counter % max(1, int(save_every))) == 0: diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index bac0ea5..82f0f36 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -178,6 +178,88 @@ class InjectedFailure(Exception): pass +def test_retained_shard_restores_its_earlier_text_after_another_shards_revision(tmp_path): + from litkit.index import faiss_save_force + from litkit.segments.ingest import mark_saved_segments + + 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) + for table, ingest, path in (("papers", ingest_paper_segments, a.paper_path), + ("chunks", ingest_chunk_segments, a.chunk_path)): + index = faiss_load(path) if path.exists() else faiss.IndexIDMap2(flat_ip_index(32)) + pending = [] + index, _ = ingest(db, index, a.segments, a.index_lock, path, a.db_lock, + FileLock=a.lock, unsaved_ids=pending) + with a.lock(a.index_lock): + faiss_save_force(index, path) + mark_saved_segments(db, table, pending) + row = db.execute(f"SELECT id, in_index FROM {table}").fetchone() + assert row[1] == 1 and index.ntotal == 1 + np.testing.assert_allclose(faiss_load(path).reconstruct(row[0]), embedder.encode([title])[0], atol=3e-4) + + +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 diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index df10369..3a024b5 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -739,6 +739,71 @@ def test_detached_checkpoint_and_incremental_alias(isolated_env, tmp_path, monke 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 +): + import numpy as np + from contextlib import closing + 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() + 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 203225cceac5f090363139c047b59a6fe56ac02e Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 20:17:04 -0700 Subject: [PATCH 29/31] Preserve citation identifiers and retire duplicate passage IDs on revision Signed-off-by: Bill Hlavacek --- src/litkit/build/ingest_loop.py | 62 +++++++++---------- src/litkit/db/queries.py | 21 +++++++ src/litkit/db/sharding.py | 20 ++++--- tests/integration/test_batch_resume.py | 83 ++++++++++++++++++++++---- 4 files changed, 135 insertions(+), 51 deletions(-) diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index 3cd8d51..e43fe17 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -49,6 +49,7 @@ 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 @@ -114,6 +115,19 @@ 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: @@ -514,21 +528,17 @@ def _render(force: bool = False): # Content-addressed doc_id: use DB's canonical doc_id when reusing # an existing paper row. - existing_row = None + existing_row = _find_paper(cur, pmcid, pmid, f) canonical = None - if pmcid: - existing_row = cur.execute( - "SELECT id, doc_id, embedding_text FROM papers WHERE pmcid=? AND pmcid<>''", (pmcid,) - ).fetchone() - if (existing_row is None) and pmid: - existing_row = cur.execute( - "SELECT id, doc_id, embedding_text FROM papers WHERE pmid=? AND pmid<>''", (pmid,) - ).fetchone() - if existing_row is None: - existing_row = cur.execute( - "SELECT p.id, p.doc_id, p.embedding_text FROM files f JOIN papers p ON p.id=f.paper_id " - "WHERE f.path=?", (f,) - ).fetchone() + 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: pid, existing_doc_id, previous_text = existing_row @@ -541,21 +551,11 @@ def _render(force: bool = False): (canon_doc_id, pid) ) else: - # A previous consume may have removed the shard that - # assigned this paper its canonical document ID. - if merged is not None and pmcid: - canonical = merged.execute( - "SELECT doc_id FROM papers WHERE pmcid=? AND pmcid<>''", (pmcid,) - ).fetchone() - if merged is not None and not canonical and pmid: - canonical = merged.execute( - "SELECT doc_id FROM papers WHERE pmid=? AND pmid<>''", (pmid,) - ).fetchone() - if merged is not None and not canonical: - canonical = merged.execute( - "SELECT p.doc_id FROM files f JOIN papers p ON p.id=f.paper_id WHERE f.path=?", (f,) - ).fetchone() 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( "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")), @@ -567,7 +567,6 @@ def _render(force: bool = False): is not None ) old_ids = [] - shard_revision = embed_producer and (existing_row is not None or canonical is not None) 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,) @@ -607,9 +606,10 @@ def _render(force: bool = False): paper_doc_ids_buf.append(canon_doc_id) if shard_revision: cur.execute( - "UPDATE papers SET title=?, abstract=?, source_path=?, embedding_text=? WHERE id=?", + "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, pid), + previous_text if reuse_embedding else ta_ab, pmid, pmcid, pid), ) body = pack_body(meta, chunk_target_chars, chunk_min_chars, chunk_overlap) diff --git a/src/litkit/db/queries.py b/src/litkit/db/queries.py index 0b549b9..c43f365 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 @@ -72,6 +73,26 @@ 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 WHERE {column}=? AND {column}<>'' AND doc_id IS NOT ?", + (value, 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 # --------------------------------------------------------------------------- diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index cddc109..d6219b3 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -14,6 +14,7 @@ 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 @@ -201,18 +202,21 @@ def _merge_revised_papers(conn, shard, mapping, since): return 0 inserted = 0 revisions = conn.execute(f""" - SELECT m.main_pid, p.id, p.title, p.abstract, p.source_path, p.embedding_text + SELECT m.main_pid, p.id, p.doc_id, p.pmid, p.pmcid, p.title, p.abstract, p.source_path, p.embedding_text FROM {shard}.producer_revisions r JOIN {shard}.papers p ON p.id=r.paper_id JOIN {mapping} m ON m.shard_pid=p.id WHERE r.sequence > ? """, (since,)) - for main_id, local_id, title, abstract, source_path, embedding_text in revisions: + 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 WHERE id=:id - """, {"title": title, "abstract": abstract, "source": source_path, "input": embedding_text, "id": main_id}) + 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=? @@ -223,9 +227,11 @@ def _merge_revised_papers(conn, shard, mapping, since): "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=?) - """, (main_id, local_id)).fetchall() + 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. diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 82f0f36..3f3e7c3 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -173,15 +173,27 @@ def consume(self): 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.""" + from litkit.index import faiss_save_force + from litkit.segments.ingest import mark_saved_segments + + for table, ingest, path in (("papers", ingest_paper_segments, self.paper_path), + ("chunks", ingest_chunk_segments, self.chunk_path)): + index = faiss_load(path) if path.exists() else faiss.IndexIDMap2(flat_ip_index(32)) + pending = [] + index, _ = ingest(conn, index, self.segments, self.index_lock, path, self.db_lock, + FileLock=self.lock, unsaved_ids=pending) + with self.lock(self.index_lock): + faiss_save_force(index, path) + mark_saved_segments(conn, table, pending) + class InjectedFailure(Exception): pass def test_retained_shard_restores_its_earlier_text_after_another_shards_revision(tmp_path): - from litkit.index import faiss_save_force - from litkit.segments.ingest import mark_saved_segments - embedder = FakeEmbedder() a = Build(tmp_path, tmp_path / "a.tar", shard_id=0) b = Build(tmp_path, tmp_path / "b.tar", shard_id=1) @@ -193,18 +205,63 @@ def test_retained_shard_restores_its_earlier_text_after_another_shards_revision( write_tar(tar, members) build.run(tar_paths=[tar]) merge_shard_databases(db, delete_after_merge=False, segment_dir=a.segments) - for table, ingest, path in (("papers", ingest_paper_segments, a.paper_path), - ("chunks", ingest_chunk_segments, a.chunk_path)): - index = faiss_load(path) if path.exists() else faiss.IndexIDMap2(flat_ip_index(32)) - pending = [] - index, _ = ingest(db, index, a.segments, a.index_lock, path, a.db_lock, - FileLock=a.lock, unsaved_ids=pending) - with a.lock(a.index_lock): - faiss_save_force(index, path) - mark_saved_segments(db, table, pending) + 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(faiss_load(path).reconstruct(row[0]), embedder.encode([title])[0], atol=3e-4) + np.testing.assert_allclose(index.reconstruct(row[0]), embedder.encode([title])[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 08fc972bff786f54357caca6b9d18f51178eda76 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 20:28:20 -0700 Subject: [PATCH 30/31] Keep consumed transfers complete and resolve citations across independent shards Signed-off-by: Bill Hlavacek --- src/litkit/db/handoff.py | 22 ++++++------ src/litkit/db/queries.py | 14 +++++--- src/litkit/db/sharding.py | 43 +++++++++++++++++------ src/litkit/segments/ingest.py | 16 ++++----- tests/integration/test_batch_resume.py | 28 +++++++++++++++ tests/integration/test_build_and_query.py | 10 +++++- tests/test_db.py | 18 ++++++++++ 7 files changed, 118 insertions(+), 33 deletions(-) diff --git a/src/litkit/db/handoff.py b/src/litkit/db/handoff.py index e43d893..2e3fac0 100644 --- a/src/litkit/db/handoff.py +++ b/src/litkit/db/handoff.py @@ -320,6 +320,10 @@ def copy_handoff(source, workspace, shard_id): 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 @@ -336,18 +340,16 @@ def copy_handoff(source, workspace, shard_id): _transfer_checkpoint(source_db, progress, merged) markers = verify_output_markers(progress, segment_dir, segment_dir) same_checkpoint = progress == shared_progress - if same_checkpoint and receipt.is_file() and receipt.read_text() == identity and ( - (sqlite_dir / source_db.name).is_file() or (sqlite_dir / "litkit.sqlite3").is_file() - ): - final_done = workspace / "emb_segments" / done.name - if not final_done.is_file(): - temporary = final_done.with_suffix(".done.tmp") - _copy_file(done, temporary) - temporary.replace(final_done) - _sync_dir(final_done.parent) - return 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. " diff --git a/src/litkit/db/queries.py b/src/litkit/db/queries.py index c43f365..1c31acc 100644 --- a/src/litkit/db/queries.py +++ b/src/litkit/db/queries.py @@ -81,8 +81,9 @@ def available(column, value): if reader is None: continue owner = reader.execute( - f"SELECT doc_id FROM papers WHERE {column}=? AND {column}<>'' AND doc_id IS NOT ?", - (value, doc_id), + 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]}. " @@ -111,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/sharding.py b/src/litkit/db/sharding.py index e1011fa..b80118b 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -202,13 +202,19 @@ def merge_drained_shards(main_conn, sqlite_dir, delete_after_merge, segment_dir) def _merge_revised_papers(conn, shard, mapping, since): """Refresh retrieval text only for articles revised since this shard's last merge.""" - if not conn.execute(f"SELECT 1 FROM {shard}.sqlite_master WHERE name='producer_revisions'").fetchone(): + 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, p.doc_id, p.pmid, p.pmcid, p.title, p.abstract, p.source_path, p.embedding_text - FROM {shard}.producer_revisions r JOIN {shard}.papers p ON p.id=r.paper_id - JOIN {mapping} m ON m.shard_pid=p.id WHERE r.sequence > ? + 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} > ? """, (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) @@ -307,13 +313,30 @@ def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge, to_record): # 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""" @@ -321,7 +344,7 @@ def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge, to_record): 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 pm.main_pid NOT IN (SELECT paper_id FROM merged_paper_revisions) + 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 diff --git a/src/litkit/segments/ingest.py b/src/litkit/segments/ingest.py index 4ae07d8..8041c0a 100644 --- a/src/litkit/segments/ingest.py +++ b/src/litkit/segments/ingest.py @@ -81,21 +81,21 @@ 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.doc_id, NULL, p.embedding_text" if kind == "papers" else "c.id, p.doc_id, c.ord, c.text" + 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, doc, ordinal, text in rows: + for row_id, paper_id, ordinal, text in rows: digest = text_digest(text) - documents.setdefault(doc, {})[ordinal] = digest + documents.setdefault(paper_id, {})[ordinal] = digest numeric[row_id] = digest return documents, numeric def _read_segment(conn, path, kind, papers, chunks, revisions, numeric_ids): """Resolve IDs and accept vectors whose embedding input matches the current revision.""" - by_doc, by_id = revisions + 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: @@ -103,12 +103,12 @@ def _read_segment(conn, path, kind, papers, chunks, revisions, numeric_ids): 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_doc[doc].get(None, b"") if doc in by_doc else None 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 = [(str(doc), int(ordinal)) for doc, ordinal in + keys = [(papers.get(str(doc)), int(ordinal)) for doc, ordinal in zip(segment["paper_doc_ids"], segment["ords"], strict=True)] - ids = [chunks.get((papers.get(doc), ordinal)) for doc, ordinal in keys] - expected = [by_doc[doc].get(ordinal, b"") if doc in by_doc else None for doc, ordinal in keys] + 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: diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index f9129a0..71bbc14 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -205,6 +205,34 @@ def test_retained_shard_restores_its_earlier_text_after_another_shards_revision( 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("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): diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index 95a66e4..51848a8 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -661,7 +661,7 @@ def fail_publish(path, dest): 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 (shared / "emb_segments" / "producer_0.done").is_file() + 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) @@ -670,6 +670,10 @@ def fail_publish(path, dest): 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]) @@ -958,6 +962,7 @@ def test_matching_transfer_receipt_checks_retained_source(isolated_env, tmp_path _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")}) @@ -976,6 +981,9 @@ def stop(src, dst): 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") diff --git a/tests/test_db.py b/tests/test_db.py index 0b2bd0d..66560f3 100644 --- a/tests/test_db.py +++ b/tests/test_db.py @@ -290,6 +290,24 @@ def test_merge_rejects_unverified_shard_local_numeric_segment_ids(tmp_path): 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.""" From 06db22faf02782caafc9ac094a4c648fabfe5388 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 20:31:34 -0700 Subject: [PATCH 31/31] Preserve archive order when retained and independent citation aliases converge Signed-off-by: Bill Hlavacek --- src/litkit/build/ingest_loop.py | 8 ++++ src/litkit/db/sharding.py | 3 ++ src/litkit/segments/ingest.py | 15 ++++---- tests/integration/test_batch_resume.py | 53 ++++++++++++++++++++++++++ 4 files changed, 72 insertions(+), 7 deletions(-) diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index e43fe17..64d188f 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -539,6 +539,14 @@ def _render(force: bool = False): "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 diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index b80118b..ac2b18a 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -215,6 +215,9 @@ def _merge_revised_papers(conn, shard, mapping, since): 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) diff --git a/src/litkit/segments/ingest.py b/src/litkit/segments/ingest.py index 8041c0a..dc163eb 100644 --- a/src/litkit/segments/ingest.py +++ b/src/litkit/segments/ingest.py @@ -125,9 +125,11 @@ def _read_segment(conn, path, kind, papers, chunks, revisions, numeric_ids): raise ValueError("Invalid embedding text hashes in segment") else: hashes = [None] * len(ids) - keep, resolved = [], [] + if vectors.ndim != 2 or len(vectors) != len(ids): + raise ValueError("Segment vector shape does not match its IDs") + resolved = {} unresolved = unverified = 0 - for row_id, current, digest in zip(ids, expected, hashes, strict=True): + 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): @@ -135,17 +137,16 @@ def _read_segment(conn, path, kind, papers, chunks, revisions, numeric_ids): elif row_id is None: unresolved += 1 else: - resolved.append(row_id) - keep.append(True) - continue - keep.append(False) + # 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.asarray(resolved, dtype=np.int64), vectors[np.asarray(keep, dtype=bool)], disposition + return np.fromiter(resolved, dtype=np.int64), vectors[list(resolved.values())], disposition def _finish_segment(path, disposition): diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 71bbc14..c3ad856 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -233,6 +233,59 @@ def test_independent_shards_resolve_the_same_citation_before_first_merge(tmp_pat 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):