From 5d57740149724c71ea61cd2ceef41d9777981227 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 20:35:50 -0700 Subject: [PATCH 1/3] Commit each batch of articles in one transaction process_tar_files() wrapped each member in SAVEPOINT member_sp with no transaction open, so the savepoint was the outermost one and its RELEASE committed the article on its own. The batch-level commit and rollback calls did nothing: a failed embedding, FAISS or segment flush left the articles committed with no vectors, and a restart without --rebuild skipped them through the files table. Open a transaction before the first member after each commit, so the member savepoints nest inside it. Producers no longer commit after mid-tar flushes, whose segments stay pending until the tar boundary: each tar's rows commit only there, before finalize(), and roll back with cleanup_pending() if the flush fails. Writers also commit after a flush whose FAISS save was throttled, so a later save never writes vectors for rows a rollback could remove. An error after which SQLite rolls back the whole transaction now stops the build, since the buffers still hold the members it removed. Fixes #13 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 1 + src/litkit/build/ingest_loop.py | 34 ++++-- tests/test_segments.py | 199 +++++++++++++++++++++++++++----- 3 files changed, 192 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea53e10..124b424 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, so a failed embedding, FAISS, or segment flush rolls back the batch's rows and a restart without `--rebuild` processes those articles again instead of skipping them with no vectors. Producers commit each tar's rows only at the tar boundary, together with its segments. (#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..da290d5 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -348,6 +348,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 +464,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 +521,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}") @@ -546,6 +555,9 @@ def _render(force: bool = False): db_mark_in_index(cur, "papers", [int(i) for i in ids_added]) db_flush_pending_marks(cur) conn.commit() + # Also when the save was throttled: the next save writes these + # vectors, so a rollback must not remove their rows (#13) + conn.commit() papers_added_total += int(added) except Exception as e: conn.rollback() @@ -586,13 +598,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 +613,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 @@ -641,6 +650,9 @@ def _render(force: bool = False): db_mark_in_index(cur, "chunks", [int(i) for i in ids_added]) db_flush_pending_marks(cur) conn.commit() + # Also when the save was throttled: the next save writes these + # vectors, so a rollback must not remove their rows (#13) + conn.commit() chunks_added_total += int(added) except Exception as e: conn.rollback() @@ -717,7 +729,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) diff --git a/tests/test_segments.py b/tests/test_segments.py index 2aa2a6c..2f4d970 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,205 @@ 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 (adding to flat indices). The producer is asked to checkpoint after + every article, which it must not do before the tar boundary (#3); the writer checkpoints, + and so commits, only at the tar boundary.""" 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=faiss.IndexIDMap2(flat_ip_index(DIM)) if writer else None, + chunk_index=faiss.IndexIDMap2(flat_ip_index(DIM)) 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 _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 or FAISS flush 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.""" + 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() + + +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) + 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, then the 7th + # paper and all the chunks after the tar boundary's commit. The first save is + # forced and the others throttled: the batch commits all the same, before the + # next save writes its vectors. + (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.""" + 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) + 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() From d30ed1e1584669246c0350c424ea205187c79d4c Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 20:57:41 -0700 Subject: [PATCH 2/3] Keep searches reading while a writer embeds a batch With one transaction per batch, a writer's batch that outgrows the page cache spills to the database file and holds an EXCLUSIVE lock until the commit, through the embedding and the FAISS save. Searches, with a 30 s busy timeout, failed with "database is locked". Writer and plain runs now turn cache_spill off for the tar loop; a batch stays in memory until the next flush or checkpoint commits it. Producers keep spilling into their own shard databases, which no one else reads. Also scope the CHANGELOG entry to what a writer's rollback covers (the rows since its last commit), note in the --strict-ingest help that an error after which SQLite rolls back the batch stops the build, and fix two test docstrings. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 2 +- src/litkit/build/ingest_loop.py | 13 +++++++++++-- src/litkit/cli.py | 5 ++++- tests/test_segments.py | 16 +++++++++++----- 4 files changed, 27 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 124b424..83a42d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +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, so a failed embedding, FAISS, or segment flush rolls back the batch's rows and a restart without `--rebuild` processes those articles again instead of skipping them with no vectors. Producers commit each tar's rows only at the tar boundary, together with its segments. (#13) +- Builds commit articles in batches instead of one at a time. A producer commits each tar's articles only when it finalizes the tar's segments, so after a failed flush or a killed job, a restart without `--rebuild` processes them again instead of skipping them with no vectors. A writer's failed flush rolls back the articles since its last commit. (#13) ## [0.3.36] - 2026-11-30 diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index da290d5..c22c5c8 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -194,7 +194,14 @@ def process_tar_files( Indices may be wrapped in IDMap2 during processing. """ 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 and + # the FAISS save. Keep it in memory until the next flush or checkpoint 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", {}) @@ -872,7 +879,9 @@ 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 2f4d970..4839a7c 100644 --- a/tests/test_segments.py +++ b/tests/test_segments.py @@ -419,8 +419,8 @@ def _build( """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 (adding to flat indices). The producer is asked to checkpoint after - every article, which it must not do before the tar boundary (#3); the writer checkpoints, - and so commits, only at the tar boundary.""" + 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 after its flushes and there.""" sqlite_dir = tmp_path / "sqlite" seg_dir = tmp_path / "emb_segments" indices = tmp_path / "indices" @@ -513,7 +513,8 @@ def test_producer_checkpoint_counts_no_article_whose_segment_is_deleted(tmp_path def test_writer_restart_indexes_every_article_after_a_failed_flush(tmp_path, monkeypatch): """#13: a failed embedding or FAISS flush 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.""" + 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) @@ -542,7 +543,7 @@ def __init__(self, db_path): self.seen = [] def encode(self, texts, **kwargs): - other = sqlite3.connect(self.db_path) + 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: @@ -568,7 +569,10 @@ 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.""" + 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", @@ -583,6 +587,8 @@ def test_other_connections_see_no_article_before_its_batch_commits( }, ) 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: From 91b073143991daeb06e350b98333c0be7ef8fc39 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 21:17:39 -0700 Subject: [PATCH 3/3] Commit a writer's batch before its vectors reach FAISS The writer committed a batch's rows only after the FAISS save. If anything failed, or SIGTERM arrived, between the save and the commit, the rollback removed rows whose vectors were already on disk; the restart added the same articles again under the same ids, since the AUTOINCREMENT counter rolls back too, and the HNSW paper index, which can't remove vectors, kept both copies. Commit the rows at each flush once the batch is embedded, before it is added to the index. A failed embedding still rolls back the rows since the last commit (a flush, a checkpoint at least every --ckpt-every articles, or a tar boundary); a failed FAISS add or save leaves the rows at in_index=0, which the writer's reconcile and backfill after the tar loop repair, as before. This also makes the commit after a throttled save unnecessary, and a writer's open transaction now spans the embedding but not the save. The writer tests now use an HNSW paper index and load the indices a failed run saved, as a restart does. The CHANGELOG says how much of a batch a writer's rollback covers and that an error after which SQLite rolls back the batch stops the build. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 2 +- src/litkit/build/ingest_loop.py | 23 +++++++------ tests/test_segments.py | 61 ++++++++++++++++++++++++++------- 3 files changed, 61 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 83a42d6..b268fb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +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 each tar's articles only when it finalizes the tar's segments, so after a failed flush or a killed job, a restart without `--rebuild` processes them again instead of skipping them with no vectors. A writer's failed flush rolls back the articles since its last commit. (#13) +- 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 c22c5c8..ae39b55 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -194,11 +194,11 @@ def process_tar_files( Indices may be wrapped in IDMap2 during processing. """ 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 and - # the FAISS save. Keep it in memory until the next flush or checkpoint commits it - # (#13). A producer's tar can be large, and no one else reads its shard database. + # 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") @@ -546,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 @@ -562,9 +566,6 @@ def _render(force: bool = False): db_mark_in_index(cur, "papers", [int(i) for i in ids_added]) db_flush_pending_marks(cur) conn.commit() - # Also when the save was throttled: the next save writes these - # vectors, so a rollback must not remove their rows (#13) - conn.commit() papers_added_total += int(added) except Exception as e: conn.rollback() @@ -641,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 @@ -657,9 +661,6 @@ def _render(force: bool = False): db_mark_in_index(cur, "chunks", [int(i) for i in ids_added]) db_flush_pending_marks(cur) conn.commit() - # Also when the save was throttled: the next save writes these - # vectors, so a rollback must not remove their rows (#13) - conn.commit() chunks_added_total += int(added) except Exception as e: conn.rollback() @@ -881,7 +882,7 @@ def _render(force: bool = False): 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/tests/test_segments.py b/tests/test_segments.py index 4839a7c..3e5e67e 100644 --- a/tests/test_segments.py +++ b/tests/test_segments.py @@ -418,9 +418,10 @@ def _build( ): """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 (adding to flat indices). 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 after its flushes and there.""" + 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" @@ -431,8 +432,8 @@ def _build( conn=conn, paper_embedder=paper_embedder, chunk_embedder=chunk_embedder, - paper_index=faiss.IndexIDMap2(flat_ip_index(DIM)) if writer else None, - chunk_index=faiss.IndexIDMap2(flat_ip_index(DIM)) if writer else None, + 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", @@ -460,6 +461,10 @@ def _build( ) +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()}) @@ -511,10 +516,10 @@ def test_producer_checkpoint_counts_no_article_whose_segment_is_deleted(tmp_path def test_writer_restart_indexes_every_article_after_a_failed_flush(tmp_path, monkeypatch): - """#13: a failed embedding or FAISS flush 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.""" + """#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) @@ -534,6 +539,37 @@ def test_writer_restart_indexes_every_article_after_a_failed_flush(tmp_path, mon conn.close() +def test_writer_restart_after_a_failure_past_the_save_adds_no_second_vector(tmp_path, monkeypatch): + """#13: a writer commits a batch's rows once they are embedded, before a save can write + their vectors. Rolled back after the save, by an error or SIGTERM before the commit, + the rows would come back on the restart under the same ids, and the HNSW paper index, + which can't remove vectors, would hold two of each.""" + 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.""" @@ -557,10 +593,9 @@ def encode(self, texts, **kwargs): # 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, then the 7th - # paper and all the chunks after the tar boundary's commit. The first save is - # forced and the others throttled: the batch commits all the same, before the - # next save writes its vectors. + # 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"],