diff --git a/CHANGELOG.md b/CHANGELOG.md index ea53e10..b268fb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ internal versions are summarized under 0.3.33. - The consumer and `--rebuild` ignore unfinished `*_pending.npz` segments. (#4) - A successful `--consume-only` run removes the producers' `producer_N.done` markers, and `vector_build_multi.sbatch` and each producer remove old ones when they start, so the next multi-node job waits for its producers and `--rebuild` is no longer blocked. (#5) - The batch scripts and the cluster guide remove the writer guard litkit creates, `workspace/sqlite/faiss_writer.guard`, instead of `workspace/.writer_guard`. (#15) +- Builds commit articles in batches instead of one at a time. A producer commits a tar's articles only at the tar boundary, just before it finalizes the tar's segments, so after a failed flush or a job killed mid-tar, a restart without `--rebuild` processes them again instead of skipping them with no vectors. A writer commits at each flush, once the batch is embedded, at each checkpoint and at each tar boundary, so a failed embedding rolls back only the articles since the last of those; earlier rows of the batch still wait for the backfill. Without `--strict-ingest`, an error after which SQLite has rolled back the batch, such as a full disk, now stops the build instead of skipping the article. (#13) ## [0.3.36] - 2026-11-30 diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index a19e9ae..ae39b55 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -195,6 +195,13 @@ def process_tar_files( """ cur = conn.cursor() + # A batch that spilled from the page cache to the database file would hold an + # EXCLUSIVE lock until its commit, locking searches out through the embedding. Keep + # it in memory until the next flush, checkpoint or tar boundary commits it (#13). A + # producer's tar can be large, and no one else reads its shard database. + if not embed_producer: + conn.execute("PRAGMA cache_spill=OFF") + # Load checkpoint ckpt = seg_load_checkpoint(ckpt_path, shard_id=ckpt_shard_id) ckpt_stream = ckpt.get("build_stream", {}) @@ -348,6 +355,11 @@ def _render(force: bool = False): len(chunk_ords_buf), ) + # Every member since the last commit shares one transaction (#13). A + # SAVEPOINT that opened the transaction would commit this member alone at + # its RELEASE, and no commit or rollback below could include or undo it. + if not conn.in_transaction: + conn.execute("BEGIN") conn.execute("SAVEPOINT member_sp") try: # ---------- BEGIN INGEST BODY ---------- @@ -459,6 +471,10 @@ def _render(force: bool = False): conn.execute("RELEASE SAVEPOINT member_sp") except Exception: pass + if not conn.in_transaction: + # SQLite rolled back the whole transaction (disk full, I/O error): + # the members before this one are gone but still in the buffers + raise # Truncate in-memory buffers back to pre-member state (p_len, pt_len, pd_len, c_len, ct_len, cp_len, co_len) = buf_snapshot @@ -512,10 +528,10 @@ def _render(force: bool = False): progress_done_summary=False, ) paper_seg_writer.write(doc_ids=u_doc_ids, vecs=Xp) - conn.commit() papers_added_total += len(u_ids) - # No checkpoint until the tar-boundary finalize(): this segment - # is pending, and cleanup_pending() deletes it if that fails (#3) + # No commit or checkpoint until the tar-boundary finalize(): this + # segment is pending, and cleanup_pending() deletes it if that + # fails, so its rows must roll back with it (#3, #13) except Exception as e: conn.rollback() _eprint(f"[flush] FATAL: paper segment flush failed: {e.__class__.__name__}: {e}") @@ -530,6 +546,10 @@ def _render(force: bool = False): batch_size=paper_embed_bs, progress_done_summary=False, ) + # Commit the rows before a save can write their vectors: rolled + # back, they would get the same ids on the restart, and the HNSW + # paper index can't remove the first copy (#13) + conn.commit() prior_ntotal = int(getattr(paper_index, "ntotal", 0) or 0) with FileLock(faiss_lock): # skip_dedup=rebuild: in rebuild mode, index starts empty, no dedup needed @@ -586,13 +606,10 @@ def _render(force: bool = False): ) 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) - # No checkpoint until the tar-boundary finalize(): this segment - # is pending, and cleanup_pending() deletes it if that fails (#3) + # No commit or checkpoint until the tar-boundary finalize(): this + # segment is pending, and cleanup_pending() deletes it if that + # fails, so its rows must roll back with it (#3, #13) # --- CYCLE TIMING: emit summary --- total_docs_for_avg += cycle_docs @@ -604,7 +621,7 @@ def _render(force: bool = False): _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"seg={t_seg:.2f}s | " f"chunks/doc={avg_cpd:.1f}" ) # Reset cycle tracking @@ -625,6 +642,9 @@ def _render(force: bool = False): batch_size=chunk_embed_bs, progress_done_summary=False, ) + # Commit the rows before a save can write their vectors, as for + # papers: every vector a save writes then has a committed row (#13) + conn.commit() prior_ntotal = int(getattr(chunk_index, "ntotal", 0) or 0) with FileLock(faiss_lock): # skip_dedup=rebuild: in rebuild mode, index starts empty, no dedup needed @@ -717,7 +737,7 @@ def _render(force: bool = False): chunk_paper_doc_ids_buf.clear() chunk_ords_buf.clear() - # Phase 2: Commit DB (rows now durable) + # Phase 2: Commit DB: this tar's rows, all in one transaction (#13) conn.commit() # Phase 3: Finalize segments (atomic rename .pending → .npz) @@ -860,6 +880,8 @@ def _render(force: bool = False): # Final commit conn.commit() + if not embed_producer: + conn.execute("PRAGMA cache_spill=ON") # Return indices and counts (indices may have been wrapped) return paper_index, chunk_index, papers_added_total, chunks_added_total diff --git a/src/litkit/cli.py b/src/litkit/cli.py index e4c63cc..ef76eac 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1802,7 +1802,10 @@ def main(): ap.add_argument( "--strict-ingest", action="store_true", - help="Fail fast on ingest errors instead of mark-and-skip (default: skip failed members and continue)", + help=( + "Fail fast on ingest errors instead of mark-and-skip (default: skip failed members " + "and continue, unless SQLite rolled back the batch, e.g. when the disk is full)" + ), ) # index types / params diff --git a/tests/test_segments.py b/tests/test_segments.py index 2aa2a6c..3e5e67e 100644 --- a/tests/test_segments.py +++ b/tests/test_segments.py @@ -4,6 +4,7 @@ import json import os +import sqlite3 from functools import partial from types import SimpleNamespace @@ -11,6 +12,7 @@ import numpy as np import pytest +import litkit.build.ingest_loop as ingest_loop import litkit.index.io as index_io import litkit.segments.ingest as ingest_mod from conftest import CORPUS, FakeEmbedder, jats, write_tar @@ -411,70 +413,246 @@ def encode(self, texts, **kwargs): return super().encode(texts, **kwargs) -def _produce(tmp_path, tar, conn, paper_embedder, chunk_embedder, *, rebuild=False): - """Run producer shard 0 over one tar, flushing papers every 2 articles. Chunks are - flushed only at the tar boundary.""" +def _build( + tmp_path, tar, conn, paper_embedder, chunk_embedder, *, writer=False, rebuild=False, strict=True +): + """Run one build over one tar, flushing papers every 2 articles. Chunks are flushed only + at the tar boundary by the producer (shard 0, writing segments), and only after the tar + loop by the writer, which adds to the indices it saved before, if any, as a restart + does. The producer is asked to checkpoint after every article, which it must not do + before the tar boundary (#3); the writer isn't asked to checkpoint before the tar + boundary, so it commits only at its flushes and there.""" sqlite_dir = tmp_path / "sqlite" seg_dir = tmp_path / "emb_segments" + indices = tmp_path / "indices" + indices.mkdir(exist_ok=True) + faiss_lock, db_lock = sqlite_dir / "faiss.writer.lock", sqlite_dir / "db.writer.lock" return process_tar_files( tar_paths=[tar], conn=conn, paper_embedder=paper_embedder, chunk_embedder=chunk_embedder, - paper_index=None, - chunk_index=None, - paper_seg_writer=SegmentWriter(seg_dir, dtype="fp32"), - chunk_seg_writer=ChunkSegmentWriter(seg_dir, dtype="fp32"), + paper_index=_saved_or_empty(indices / "papers.faiss", "papers") if writer else None, + chunk_index=_saved_or_empty(indices / "chunks.faiss", "chunks") if writer else None, + paper_seg_writer=None if writer else SegmentWriter(seg_dir, dtype="fp32"), + chunk_seg_writer=None if writer else ChunkSegmentWriter(seg_dir, dtype="fp32"), ckpt_path=sqlite_dir / "build_checkpoint.json", ckpt_lock=sqlite_dir / "ckpt.writer.lock", - faiss_lock=sqlite_dir / "faiss.writer.lock", - db_lock=sqlite_dir / "db.writer.lock", - paper_index_path=tmp_path / "indices" / "papers.faiss", - chunk_index_path=tmp_path / "indices" / "chunks.faiss", + faiss_lock=faiss_lock, + db_lock=db_lock, + paper_index_path=indices / "papers.faiss", + chunk_index_path=indices / "chunks.faiss", sqlite_dir=sqlite_dir, - FileLock=FileLock, + FileLock=partial(FileLock, db_lock_path=db_lock, faiss_lock_path=faiss_lock), rebuild=rebuild, - embed_producer=True, - faiss_writer=False, - strict_ingest=True, + embed_producer=not writer, + faiss_writer=writer, + strict_ingest=strict, paper_batch=2, chunk_batch=10_000, - ckpt_every=1, + ckpt_every=1000 if writer else 1, paper_embed_bs=8, chunk_embed_bs=8, chunk_target_chars=1200, chunk_min_chars=0, chunk_overlap=0, - ckpt_shard_id=0, + ckpt_shard_id=None if writer else 0, parse_workers=1, ) -def test_producer_checkpoint_counts_no_article_whose_segment_is_deleted(tmp_path, seg_dir): +def _saved_or_empty(path, kind): + return faiss_load(path) if path.exists() else _empty_index(kind) + + +def _corpus_tar(tmp_path): + return write_tar(tmp_path / "a.tar", {f"{v['pmcid']}.nxml": jats(**v) for v in CORPUS.values()}) + + +def _open_db(tmp_path, *, writer): + sqlite_dir = tmp_path / "sqlite" + if writer: + return init_db(sqlite_dir / "litkit.sqlite3") + return init_shard_db(shard_db_path(sqlite_dir, 0), 0) + + +def _row_counts(conn): + tables = ("papers", "chunks", "files") + return {t: conn.execute(f"SELECT count(*) FROM {t}").fetchone()[0] for t in tables} + + +@pytest.mark.parametrize("rebuild", [True, False], ids=["rebuild", "update"]) +def test_producer_checkpoint_counts_no_article_whose_segment_is_deleted(tmp_path, seg_dir, rebuild): """#3: a mid-tar flush leaves its segment pending until the tar boundary, and cleanup_pending() deletes it if the tar-boundary flush fails. A checkpoint that - counted those articles made the restart skip them: no vectors, ever.""" - tar = write_tar(tmp_path / "a.tar", {f"{v['pmcid']}.nxml": jats(**v) for v in CORPUS.values()}) + counted those articles made the restart skip them: no vectors, ever. + + #13: so did the files table, on a restart without --rebuild, when each article was + committed on its own. The producer commits only at the tar boundary, before finalize(), + so the failed flush rolls back every article whose segment cleanup_pending() deletes.""" + tar = _corpus_tar(tmp_path) doc_ids = {f"tar://{tar}!/{v['pmcid']}.nxml" for v in CORPUS.values()} ckpt = tmp_path / "sqlite" / "build_checkpoint.json" - conn = init_shard_db(shard_db_path(tmp_path / "sqlite", 0), 0) + conn = _open_db(tmp_path, writer=False) try: papers = FakeEmbedder(DIM) with pytest.raises(RuntimeError, match="out of memory"): - _produce(tmp_path, tar, conn, papers, OutOfMemoryOnce()) + _build(tmp_path, tar, conn, papers, OutOfMemoryOnce()) assert [len(batch) for batch in papers.calls] == [2, 1] # one mid-tar flush assert _names(seg_dir) == [] # cleanup_pending() deleted the mid-tar segment too assert load_checkpoint(ckpt, shard_id=0).get("build_stream", {}).get(str(tar), 0) == 0 + assert _row_counts(conn) == {"papers": 0, "chunks": 0, "files": 0} - # The restart produces every article. It uses --rebuild, which skips the - # files-table check: each article is committed on its own (#13), so the files - # table would skip them too, whatever the checkpoint says. - _produce(tmp_path, tar, conn, FakeEmbedder(DIM), FakeEmbedder(DIM), rebuild=True) + _build(tmp_path, tar, conn, FakeEmbedder(DIM), FakeEmbedder(DIM), rebuild=rebuild) finally: conn.close() - produced = set() - for path in seg_dir.glob("paper_seg_*.npz"): - with np.load(path, allow_pickle=True) as z: - produced.update(str(d) for d in z["doc_ids"]) - assert produced == doc_ids + for kind, key in (("paper", "doc_ids"), ("chunk", "paper_doc_ids")): + produced = set() + for path in seg_dir.glob(f"{kind}_seg_*.npz"): + with np.load(path, allow_pickle=True) as z: + produced.update(str(d) for d in z[key]) + assert produced == doc_ids, kind assert load_checkpoint(ckpt, shard_id=0)["build_stream"][str(tar)] == len(CORPUS) + + +def test_writer_restart_indexes_every_article_after_a_failed_flush(tmp_path, monkeypatch): + """#13: a failed embedding rolls back every row since the last commit. When each + article was committed on its own, the rows stayed at in_index=0 with no vectors, and a + restart without --rebuild skipped them through the files table, leaving them to the + backfill the CLI runs after the tar loop.""" + monkeypatch.setattr(index_io, "_SAVE_MIN_SEC", 0) # no throttle: each flush marks its rows + tar = _corpus_tar(tmp_path) + conn = _open_db(tmp_path, writer=True) + try: + with pytest.raises(RuntimeError, match="out of memory"): + _build(tmp_path, tar, conn, OutOfMemoryOnce(), FakeEmbedder(DIM), writer=True) + assert _row_counts(conn) == {"papers": 0, "chunks": 0, "files": 0} + + _build(tmp_path, tar, conn, FakeEmbedder(DIM), FakeEmbedder(DIM), writer=True) + assert _row_counts(conn)["papers"] == len(CORPUS) + for table in ("papers", "chunks"): + rows = conn.execute(f"SELECT id, in_index FROM {table} ORDER BY id").fetchall() + assert {in_index for _, in_index in rows} == {1}, table + saved = faiss_load(tmp_path / "indices" / f"{table}.faiss") + assert _saved_ids(saved) == [i for i, _ in rows], table + finally: + conn.close() + + +def test_writer_restart_after_a_failure_past_the_save_adds_no_second_vector(tmp_path, monkeypatch): + """#13: a writer commits a batch's rows once they are embedded, before a save can write + their vectors. Rolled back after the save, by an error or SIGTERM before the commit, + the rows would come back on the restart under the same ids, and the HNSW paper index, + which can't remove vectors, would hold two of each.""" + monkeypatch.setattr(index_io, "_SAVE_MIN_SEC", 0) # no throttle + flush_marks = ingest_loop.db_flush_pending_marks + failed = [] + + def fail_after_the_first_save(cur): + if not failed: + failed.append(True) + raise RuntimeError("killed after the save") + return flush_marks(cur) + + monkeypatch.setattr(ingest_loop, "db_flush_pending_marks", fail_after_the_first_save) + tar = _corpus_tar(tmp_path) + conn = _open_db(tmp_path, writer=True) + try: + with pytest.raises(RuntimeError, match="after the save"): + _build(tmp_path, tar, conn, FakeEmbedder(DIM), FakeEmbedder(DIM), writer=True) + assert _saved_ids(faiss_load(tmp_path / "indices" / "papers.faiss")) == [1, 2] + + _build(tmp_path, tar, conn, FakeEmbedder(DIM), FakeEmbedder(DIM), writer=True) + ids = [r[0] for r in conn.execute("SELECT id FROM papers ORDER BY id")] + finally: + conn.close() + assert ids == [1, 2, 3] + assert _saved_ids(faiss_load(tmp_path / "indices" / "papers.faiss")) == ids + + +class Peeking(FakeEmbedder): + """Records, at each call, how many papers a second connection to the database sees.""" + + def __init__(self, db_path): + super().__init__(DIM) + self.db_path = db_path + self.seen = [] + + def encode(self, texts, **kwargs): + other = sqlite3.connect(self.db_path, timeout=0) # a locked database fails the test + try: + self.seen.append(other.execute("SELECT count(*) FROM papers").fetchone()[0]) + finally: + other.close() + return super().encode(texts, **kwargs) + + +@pytest.mark.parametrize( + "writer, seen", + [ + # Papers mid-tar after articles 2, 4 and 6, then the 7th paper and all the chunks + # at the tar boundary: all before the tar boundary's commit. + (False, [0, 0, 0, 0, 0]), + # Papers after articles 2, 4 and 6, each flush committing its batch once it is + # embedded, then the 7th paper and all the chunks after the tar boundary's commit. + # Only the first save runs (it is forced): the commits don't wait for a save. + (True, [0, 2, 4, 7, 7]), + ], + ids=["producer", "writer"], +) +def test_other_connections_see_no_article_before_its_batch_commits( + tmp_path, monkeypatch, writer, seen +): + """#13: each article's SAVEPOINT was the outermost transaction, so its RELEASE + committed it; the articles of a batch now share one transaction. Searches still read + the database while the writer embeds a batch: its page cache is tiny here, so the batch + outgrows it, as a large batch outgrows the default 2 MB, and must not spill to the file + and lock them out. Producers may spill: no one else reads their shard databases.""" + monkeypatch.setattr(ingest_loop, "faiss_save", lambda index, path: False) # throttled + tar = write_tar( + tmp_path / "a.tar", + { + f"PMC2000{i}.nxml": jats( + pmcid=f"PMC2000{i}", + title=f"Article {i}", + abstract=f"Abstract of article {i}.", + paragraphs=[f"Body of article {i}."], + ) + for i in range(7) + }, + ) + conn = _open_db(tmp_path, writer=writer) + if writer: + conn.execute("PRAGMA cache_size=10") # pages + db_path = conn.execute("PRAGMA database_list").fetchone()[2] + papers, chunks = Peeking(db_path), Peeking(db_path) + try: + _build(tmp_path, tar, conn, papers, chunks, writer=writer) + finally: + conn.close() + assert papers.seen + chunks.seen == seen + + +def test_error_that_ends_the_batch_transaction_stops_the_build(tmp_path, monkeypatch): + """After some errors (disk full, I/O error) SQLite rolls back the whole transaction, + which now holds every article since the last commit. Those are still in the embedding + buffers, so the build stops instead of skipping the article, as it does for other + errors without --strict-ingest; a restart redoes them.""" + tar = _corpus_tar(tmp_path) + conn = _open_db(tmp_path, writer=True) + register_file = ingest_loop.db_register_file + + def disk_full_at_second_article(cur, path, paper_id, st): + if path.endswith(f"{CORPUS['egfr']['pmcid']}.nxml"): + cur.execute("ROLLBACK") # what SQLite does on SQLITE_FULL + raise sqlite3.OperationalError("database or disk is full") + return register_file(cur, path, paper_id, st) + + monkeypatch.setattr(ingest_loop, "db_register_file", disk_full_at_second_article) + try: + with pytest.raises(sqlite3.OperationalError, match="disk is full"): + embedders = FakeEmbedder(DIM), FakeEmbedder(DIM) + _build(tmp_path, tar, conn, *embedders, writer=True, strict=False) + assert _row_counts(conn) == {"papers": 0, "chunks": 0, "files": 0} + finally: + conn.close()