diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c4d398..ea53e10 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,12 @@ internal versions are summarized under 0.3.33. - Archive scans release processed headers. Parallel parsing keeps a bounded window and continues in order after empty articles. Compressed archives can contain rootless XML members without stopping the build. (#12, #24) - IVF-PQ training saves a flat chunk index when the corpus has no training text. Builds also recognize untrained indexes created by `--init-indices-only` and persist the training result before updating its marker. (#11) - `query_terms()`, `find_rare_terms()`, and Stage-2 lexical front-loading now retain 3–4 character all-uppercase acronyms (such as `HIV`, `EGFR`, and `ALL`, plus plurals like `TLRs`) with word-boundary matching that still accepts plural, numbered, and inhibitor forms (`RNAs`, `TLR4`, `ACEi`), prioritize digit/hyphen and long-term matches ahead of acronyms, and normalize SQLite-compatible dashes and subscripts before tokenizing. All-caps prose such as `WHAT IS THE ROLE OF RNA` does not turn ordinary words into acronyms, while all-caps keyword queries such as `EGFR NSCLC` keep theirs. (#9) +- Multi-node consumers merge every producer's shard database. The merge stopped after 10 shards, losing the rows of producers 10 and up while reporting success; a shard that can't be detached now stops the merge with an error. (#1) +- `--consume-only` deletes a segment file only after a saved index covers its vectors, so a job killed between throttled saves can be rerun, also with `vector_resume_consumer.sbatch`, without losing vectors or adding duplicates to the HNSW paper index. (#2) +- A producer's checkpoint advances only after the tar's segments are finalized. It used to count articles whose segments were still pending, which a failed tar-boundary flush deletes. (#3) +- 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) ## [0.3.36] - 2026-11-30 diff --git a/LITKIT_CLUSTER_GUIDE.md b/LITKIT_CLUSTER_GUIDE.md index b41155e..6068521 100644 --- a/LITKIT_CLUSTER_GUIDE.md +++ b/LITKIT_CLUSTER_GUIDE.md @@ -628,7 +628,7 @@ Check producer logs for errors. If a producer crashes: If a previous job crashed without cleanup: ```bash -rm workspace/.writer_guard +rm workspace/sqlite/faiss_writer.guard ``` The batch script does this automatically at job start. diff --git a/src/litkit/build/consume.py b/src/litkit/build/consume.py index 28d76b7..908bb62 100644 --- a/src/litkit/build/consume.py +++ b/src/litkit/build/consume.py @@ -18,7 +18,7 @@ merge_shard_databases, flush_pending_marks, ) -from litkit.index import faiss_load, faiss_save_force +from litkit.index import faiss_load from litkit.segments import ( ConsumerCoordinator, ingest_paper_segments, @@ -119,14 +119,16 @@ def default_progress(complete: int, total: int) -> None: ) 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) + # No save here: each ingest function saves what it added before it returns, + # and the segment files it consumed are deleted only after that save (#2). with FileLock(db_lock_path): flush_pending_marks(conn.cursor()) conn.commit() + # The next multi-node job in this workspace must wait for its own producers, + # and --rebuild refuses to run while these markers exist (#5). + consumer_coordinator.cleanup_done_files() + 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 0d8be76..a19e9ae 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -514,11 +514,8 @@ def _render(force: bool = 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 + # No checkpoint until the tar-boundary finalize(): this segment + # is pending, and cleanup_pending() deletes it if that fails (#3) except Exception as e: conn.rollback() _eprint(f"[flush] FATAL: paper segment flush failed: {e.__class__.__name__}: {e}") @@ -594,11 +591,8 @@ def _render(force: bool = False): 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 + # No checkpoint until the tar-boundary finalize(): this segment + # is pending, and cleanup_pending() deletes it if that fails (#3) # --- CYCLE TIMING: emit summary --- total_docs_for_avg += cycle_docs @@ -669,7 +663,7 @@ def _render(force: bool = False): # Persist every ckpt_every handled members if (processed_count - persisted_count) >= ckpt_every: if embed_producer: - pass # Producer checkpoints only after segment flush + pass # Producer checkpoints only after the tar-boundary finalize() else: conn.commit() ckpt_stream[str(tpath)] = processed_count diff --git a/src/litkit/cli.py b/src/litkit/cli.py index 3e75200..e4c63cc 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -367,11 +367,12 @@ def _create_writer_guard_or_exit(*, ttl_sec: int | None = None): 1. Cross-host guard handling: - On same host: we check PID liveness via os.kill(pid, 0) before evicting - On different host: we REFUSE to auto-evict (cannot verify PID liveness) - * Exit with instructions to manually remove the guard: rm .writer_guard + * Exit with instructions to manually remove the guard: + rm $WORKSPACE/sqlite/faiss_writer.guard * This prevents data corruption from evicting a legitimately running build - TTL only applies to same-host scenarios where we can verify PID is dead - Mitigations for stale cross-host guards: - * SLURM scripts should include `rm -f $WORKSPACE/.writer_guard` at job start + * SLURM scripts include `rm -f $WORKSPACE/sqlite/faiss_writer.guard` at job start * Users can manually remove stale guards if certain the other job is dead - Rationale: false eviction is catastrophic; manual intervention is safer @@ -540,7 +541,7 @@ def _signal_exit_handler(signum, frame): is_live = True # Unknown error, be conservative # Different host: NEVER auto-evict. We cannot verify PID liveness, # so auto-eviction could corrupt data if a build is still running. - # User must manually remove the guard: rm .writer_guard + # User must manually remove the guard: rm $WORKSPACE/sqlite/faiss_writer.guard if guard_host != socket.gethostname(): sys.stderr.write( f"[writer] Guard held by DIFFERENT HOST ({guard_host}); cannot verify if process is alive.\n" @@ -1123,6 +1124,11 @@ def build_or_update_indices(args): manifest_path = str(args.tar_manifest) if args.tar_manifest else None d.seg_write_build_meta(seg_dir, args.num_shards, manifest_path, mode="single") + # A producer's done marker from an earlier run would tell the consumer that this + # shard is finished while it is still running (#5). + if args.embed_producer: + d.SegProducerCoordinator(seg_dir, args.shard_id, args.num_shards).clear_stale_marker() + # ═══════════════════════════════════════════════════════════════════════════ # DATABASE CONCURRENCY CONTRACT # ═══════════════════════════════════════════════════════════════════════════ diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index 480ed69..4e66b73 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -60,6 +60,10 @@ def _eprint(msg: str = "", *, end: str = "\n") -> None: pass +class ShardDetachError(sqlite3.OperationalError): + """A merged shard database could not be detached from the main connection.""" + + def merge_shard_databases( main_conn: sqlite3.Connection, delete_after_merge: bool = True, @@ -80,6 +84,9 @@ def merge_shard_databases( Returns: Dict with merge statistics: {"papers": N, "chunks": M, "files": F, "shards": S} + + Raises: + ShardDetachError: A shard could not be detached after its merge. """ # Derive sqlite_dir from main database path # The main_conn is typically to sqlite_dir/litkit.sqlite3 @@ -176,7 +183,11 @@ def merge_shard_databases( # Drop temp table immediately after use main_cur.execute(f"DROP TABLE IF EXISTS {temp_map_table}") - + + # Commit this shard before DETACH: the INSERTs above opened a + # transaction, and DETACH fails while it holds the shard (#1). + main_conn.commit() + # Count rows after merge for statistics papers_after = main_cur.execute( "SELECT COUNT(*) FROM papers" @@ -203,14 +214,20 @@ def merge_shard_databases( f"+{chunks_merged} chunks, +{files_merged} files " f"({elapsed:.1f}s)" ) - + + except Exception: + # Merge a shard completely or not at all, and end the transaction + # so the shard can be detached. + main_conn.rollback() + raise finally: - # Always detach the shard database + # Always detach the shard database. A failure ends the merge: a + # shard left attached makes every ATTACH after the tenth fail (#1). try: main_cur.execute(f"DETACH DATABASE {shard_alias}") - except Exception: - pass - + except sqlite3.Error as e: + raise ShardDetachError(f"could not detach {shard_db.name}: {e}") from e + # Delete shard DB after successful merge if delete_after_merge: try: @@ -220,7 +237,9 @@ def merge_shard_databases( _eprint( f"[merge] WARNING: could not delete {shard_db.name}: {e}" ) - + + except ShardDetachError: + raise except Exception as e: _eprint( f"[merge] ERROR processing {shard_db.name}: " diff --git a/src/litkit/segments/coordination.py b/src/litkit/segments/coordination.py index 12b1d4b..d0978c5 100644 --- a/src/litkit/segments/coordination.py +++ b/src/litkit/segments/coordination.py @@ -54,6 +54,22 @@ def mark_complete(self) -> None: _eprint(f"[producer] Shard {self.shard_id} marked complete") + def clear_stale_marker(self) -> bool: + """Remove this shard's done file left by an earlier run. + + Call when the producer starts: until it finishes, an old done file + would tell the consumer that this shard is already complete (#5). + + Returns: + True if a done file was removed + """ + try: + self._done_file.unlink() + except FileNotFoundError: + return False + _eprint(f"[producer] Removed stale {self._done_file.name} from an earlier run") + return True + def is_complete(self) -> bool: """Check if this producer has marked completion.""" return self._done_file.exists() diff --git a/src/litkit/segments/ingest.py b/src/litkit/segments/ingest.py index eae3adc..8c13d3a 100644 --- a/src/litkit/segments/ingest.py +++ b/src/litkit/segments/ingest.py @@ -24,7 +24,11 @@ from litkit.db.queries import preload_paper_id_map, preload_chunk_id_map from litkit.index.dedup import add_with_ids_dedup from litkit.index.io import faiss_save, faiss_save_force +from litkit.index.constants import INDEX_KIND_HNSW from litkit.index.ids import make_id_selector, safe_remove_ids +from litkit.index.introspection import kind_and_core +from litkit.segments.constants import SEGMENT_EXTENSION +from litkit.segments.writer import PENDING_SUFFIX if TYPE_CHECKING: from litkit.config.paths import WorkspacePaths @@ -57,7 +61,8 @@ def _glob_segment_files(outdir: Path, kind: str) -> list[Path]: kind: Either "papers" or "chunks" Returns: - Sorted list of segment file paths (including .ingesting files) + Sorted list of segment file paths (including .ingesting files, excluding + pending ones that a producer has not finalized) """ cand = [] @@ -82,7 +87,44 @@ def _glob_segment_files(outdir: Path, kind: str) -> list[Path]: cand.extend(outdir.glob("chunks_*.npz.ingesting")) cand.extend(outdir.glob("chunks.seg.*.npz.ingesting")) - return sorted(cand) + # paper_seg_*.npz also matches unfinished *_pending.npz files; a segment is + # visible only after the producer's finalize() renames it (#4). + pending = f"{PENDING_SUFFIX}{SEGMENT_EXTENSION}" + return sorted(p for p in cand if not p.name.endswith(pending)) + + +def _drop_ids_already_indexed( + index: faiss.Index, ids: np.ndarray, X: np.ndarray +) -> tuple[np.ndarray, np.ndarray]: + """Drop the vectors whose IDs an HNSW index already holds. + + For a claimed (.ingesting) file left by an earlier run, which may have been + killed after a save covered the file but before it deleted the file. HNSW + can't remove vectors, so adding them again would duplicate them (#2). Other + indexes replace them, as add_with_ids_dedup() does for any segment. + """ + if not isinstance(index, faiss.IndexIDMap2) or index.ntotal == 0: + return ids, X + if kind_and_core(index)[0] != INDEX_KIND_HNSW: + return ids, X + keep = ~np.isin(ids, faiss.vector_to_array(index.id_map)) + return ids[keep], X[keep] + + +def _remove_saved_segments(paths: list[Path]) -> None: + """Delete consumed segment files once a successful save covers them (#2). + + A file that can't be deleted stays claimed, and the next run skips the + vectors it already holds (see _drop_ids_already_indexed). + """ + for path in paths: + try: + os.remove(path) + except FileNotFoundError: + pass + except OSError as e: + _eprint(f"[segments] WARNING: could not remove consumed segment {path.name}: {e}") + paths.clear() def ingest_paper_segments( @@ -151,6 +193,10 @@ def ingest_paper_segments( cur = conn.cursor() added_total = 0 batch_counter = 0 + # Claimed files whose vectors are in the index but not yet in a saved copy of + # it. They are deleted only once a save covers them, so that a job killed + # before its next save can be rerun (#2). + unsaved: list[Path] = [] for p in cand: is_ingesting = p.name.endswith(".npz.ingesting") @@ -227,12 +273,19 @@ def ingest_paper_segments( if not isinstance(paper_index, faiss.IndexIDMap2): paper_index = faiss.IndexIDMap2(paper_index) + if is_ingesting: + ids, X = _drop_ids_already_indexed(paper_index, ids, X) + if ids.size == 0: + unsaved.append(tmp) # Already indexed; delete after the next save + continue + prior_ntotal = int(getattr(paper_index, "ntotal", 0) or 0) added, ids_added, saved = 0, [], False with FileLock(faiss_lock_path): # add_with_ids_dedup handles removal internally - no explicit safe_remove_ids needed added, ids_added = add_with_ids_dedup(paper_index, ids, X) + unsaved.append(tmp) if added: # Force save on first vectors, throttled save otherwise saved = faiss_save_force(paper_index, paper_index_path) if prior_ntotal == 0 \ @@ -250,17 +303,19 @@ def ingest_paper_segments( 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 + # else: throttled; the file is kept until a later save covers it (#2) added_total += int(added or 0) batch_counter += 1 - os.remove(tmp) + if saved: + _remove_saved_segments(unsaved) # This save covers every file so far # Periodic save if (batch_counter % max(1, int(save_every))) == 0: with FileLock(faiss_lock_path): saved_now = faiss_save(paper_index, paper_index_path) if saved_now: + _remove_saved_segments(unsaved) from litkit.db.indexing import flush_pending_marks if db_lock_path: with FileLock(db_lock_path): @@ -271,14 +326,21 @@ def ingest_paper_segments( conn.commit() except Exception as e: - # On error, rename file back so it can be retried next run - if not is_ingesting: + # On error, rename file back so it can be retried next run, unless its + # vectors are already in the index and it waits for a save + if not is_ingesting and tmp not in unsaved: try: os.replace(tmp, p) except Exception: pass _eprint(f"[segments] ERROR ingesting {p.name}: {e.__class__.__name__}: {e}") + # Save what the throttled saves skipped, then delete those files (#2) + if unsaved: + with FileLock(faiss_lock_path): + faiss_save_force(paper_index, paper_index_path) + _remove_saved_segments(unsaved) + return paper_index, added_total @@ -304,8 +366,8 @@ def ingest_chunk_segments( Safe file-handling: - rename ".npz" -> ".npz.ingesting" before reading (atomic) - - if already ".npz.ingesting", read in place - - on success, delete the .ingesting file + - if already ".npz.ingesting", read in place, skipping IDs an HNSW index holds + - once a successful save covers its vectors, delete the .ingesting file - on failure, rename back so it can be retried next run Args: @@ -363,6 +425,10 @@ def ingest_chunk_segments( cur = conn.cursor() added_total = 0 batch_counter = 0 + # Claimed files whose vectors are in the index but not yet in a saved copy of + # it. They are deleted only once a save covers them, so that a job killed + # before its next save can be rerun (#2). + unsaved: list[Path] = [] for p in cand: # Normalize to a working path "tmp" that we always read from: @@ -449,12 +515,19 @@ def ingest_chunk_segments( os.remove(tmp) continue + if is_ingesting: + ids, X = _drop_ids_already_indexed(chunk_index, ids, X) + if ids.size == 0: + unsaved.append(tmp) # Already indexed; delete after the next save + continue + prior_ntotal = int(getattr(chunk_index, "ntotal", 0) or 0) added, ids_added, saved = 0, [], False with FileLock(faiss_lock_path): # add_with_ids_dedup handles removal internally - no explicit safe_remove_ids needed added, ids_added = add_with_ids_dedup(chunk_index, ids, X) + unsaved.append(tmp) if added: saved = faiss_save_force(chunk_index, chunk_index_path) if prior_ntotal == 0 \ else faiss_save(chunk_index, chunk_index_path) @@ -471,17 +544,19 @@ def ingest_chunk_segments( 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 + # else: throttled; the file is kept until a later save covers it (#2) added_total += int(added) batch_counter += 1 - os.remove(tmp) + if saved: + _remove_saved_segments(unsaved) # This save covers every file so far # Periodic save if (batch_counter % max(1, int(save_every))) == 0: with FileLock(faiss_lock_path): saved_now = faiss_save(chunk_index, chunk_index_path) if saved_now: + _remove_saved_segments(unsaved) from litkit.db.indexing import flush_pending_marks if db_lock_path: with FileLock(db_lock_path): @@ -492,12 +567,19 @@ def ingest_chunk_segments( conn.commit() except Exception as e: - # If we claimed it, put it back so another run can retry. - if not is_ingesting: + # If we claimed it, put it back so another run can retry, unless its + # vectors are already in the index and it waits for a save. + if not is_ingesting and tmp not in unsaved: try: os.replace(tmp, p) except Exception: pass _eprint(f"[segments] ERROR ingesting {p.name}: {e.__class__.__name__}: {e}") + # Save what the throttled saves skipped, then delete those files (#2) + if unsaved: + with FileLock(faiss_lock_path): + faiss_save_force(chunk_index, chunk_index_path) + _remove_saved_segments(unsaved) + return chunk_index, added_total diff --git a/src/litkit/segments/metadata.py b/src/litkit/segments/metadata.py index a5f95f0..e79db8e 100644 --- a/src/litkit/segments/metadata.py +++ b/src/litkit/segments/metadata.py @@ -13,6 +13,7 @@ CHUNK_SEGMENT_PREFIX, SEGMENT_EXTENSION, ) +from litkit.segments.writer import PENDING_SUFFIX def _eprint(msg: str = "", *, end: str = "\n") -> None: @@ -31,19 +32,18 @@ def has_segment_files(seg_dir: Path) -> bool: seg_dir: Directory to check Returns: - True if any paper or chunk segment files exist + True if any finalized 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 + # Unfinished *_pending.npz files also match the globs, but aren't segments yet (#4) + pending = f"{PENDING_SUFFIX}{SEGMENT_EXTENSION}" + for prefix in (PAPER_SEGMENT_PREFIX, CHUNK_SEGMENT_PREFIX): + for p in seg_dir.glob(f"{prefix}_*{SEGMENT_EXTENSION}"): + if not p.name.endswith(pending): + return True return False diff --git a/tests/integration/test_multi_node.py b/tests/integration/test_multi_node.py new file mode 100644 index 0000000..cab4272 --- /dev/null +++ b/tests/integration/test_multi_node.py @@ -0,0 +1,143 @@ +"""Multi-node builds end to end: producers write shard databases and embedding +segments, then a consumer merges and indexes them. + +Runs the real CLI in subprocesses with the fake embedders of run_litkit_fake.py. +""" + +import os +import subprocess +import sys +from pathlib import Path + +import faiss +import pytest + +from conftest import CORPUS, jats, write_tar + +RUNNER = Path(__file__).with_name("run_litkit_fake.py") +REPO = Path(__file__).resolve().parents[2] +# --init-indices-only creates 768-dimensional indices, the real models' size. +FAKE_DIM = "768" +INDEXES = ["--chunks-index", "flat", "--papers-index", "hnsw"] +NUM_SHARDS = 2 + + +def litkit(workspace, *args): + env = dict(os.environ, LITKIT_WORKSPACE=str(workspace), FAKE_EMBED_DIM=FAKE_DIM) + return subprocess.run( + [sys.executable, str(RUNNER), *args], + env=env, + capture_output=True, + text=True, + timeout=120, + ) + + +def _ok(proc): + assert proc.returncode == 0, proc.stderr[-2000:] + return proc + + +@pytest.fixture +def tars(tmp_path): + """Two tars, so that each of the two producers gets one.""" + d = tmp_path / "tars" + d.mkdir() + members = [(f"{k}/{v['pmcid']}.nxml", jats(**v)) for k, v in CORPUS.items()] + write_tar(d / "a.tar", dict(members[:2])) + write_tar(d / "b.tar", dict(members[2:])) + return d + + +def _producer(ws, tars, shard_id): + return litkit( + ws, + "--embed-producer", + "--build-only", + "--shard-id", + str(shard_id), + "--num-shards", + str(NUM_SHARDS), + "--embed-outdir", + str(ws / "emb_segments"), + "--tar-dir", + str(tars), + ) + + +def _markers(seg_dir): + return sorted(p.name for p in seg_dir.glob("producer_*.done")) + + +def test_multi_node_build_indexes_every_shard_and_removes_markers(isolated_env, tars): + ws = isolated_env + seg_dir = ws / "emb_segments" + _ok(litkit(ws, "--faiss-writer", "--init-indices-only", *INDEXES)) + for shard_id in range(NUM_SHARDS): + _ok(_producer(ws, tars, shard_id)) + assert _markers(seg_dir) == ["producer_0.done", "producer_1.done"] + + consumer = ["--faiss-writer", "--num-shards", str(NUM_SHARDS), "--embed-outdir", str(seg_dir)] + _ok(litkit(ws, *consumer, "--consume-only", *INDEXES)) + n_papers = len(CORPUS) + assert faiss.read_index(str(ws / "indices" / "papers.faiss")).ntotal == n_papers + assert faiss.read_index(str(ws / "indices" / "chunks.faiss")).ntotal == 2 * n_papers + # Every segment and marker is consumed (#5), and the shard databases are merged. + assert sorted(p.name for p in seg_dir.iterdir()) == ["build_meta.json"] + assert list((ws / "sqlite").glob("litkit_shard_*.sqlite3")) == [] + + # Leftover markers blocked this as "Prior multi-node run (not consumed)" (#5). + rebuild = ["--build-only", "--rebuild", "--tar-dir", str(tars), *INDEXES] + _ok(litkit(ws, *consumer, *rebuild)) + + +def test_producer_removes_its_stale_marker_when_it_starts(isolated_env, tars): + """#5: a marker left by an earlier run tells the consumer that this shard is finished + while it is still running. Even a producer that then fails must not leave it.""" + ws = isolated_env + seg_dir = ws / "emb_segments" + seg_dir.mkdir() + for shard_id in range(NUM_SHARDS): + (seg_dir / f"producer_{shard_id}.done").write_text("stale\n") + # Make producer 0 fail right after it starts: its shard database can't be opened. + (ws / "sqlite" / "litkit_shard_00.sqlite3").mkdir(parents=True) + + proc = _producer(ws, tars, 0) + assert proc.returncode != 0 + assert "unable to open database file" in proc.stderr + assert _markers(seg_dir) == ["producer_1.done"] # another producer's marker stays + + +def _script_lines(name): + return (REPO / name).read_text(encoding="utf-8").splitlines() + + +def test_multi_node_script_clears_markers_before_starting_producers(): + """#5: with local staging, the default, producers write their markers locally and + rsync them to the shared emb_segments/ at the end, so they can't remove an old one + there. The script removes them before it starts any producer.""" + lines = _script_lines("vector_build_multi.sbatch") + clear = [ + i + for i, line in enumerate(lines) + if line.startswith("rm -f") and '/emb_segments"/producer_*.done' in line + ] + start = lines.index("PRODUCER_PIDS=()") + assert clear and clear[0] < start + + +@pytest.mark.skipif(os.name == "nt", reason="runs the script's POSIX find command") +def test_resume_script_counts_claimed_segments(tmp_path): + """#2: a consumer stopped before a save keeps the segments it claimed as + *.npz.ingesting. The resume script must count them, or it exits with "Nothing to do".""" + (line,) = [s for s in _script_lines("vector_resume_consumer.sbatch") if s.startswith("n_segs=")] + for name in ("paper_seg_0_0_aaaa.npz", "chunk_seg_0_0_bbbb.npz.ingesting"): + (tmp_path / name).touch() + count = subprocess.run( + ["bash", "-c", f'{line}\necho "$n_segs"'], + env=dict(os.environ, SEG_DIR=str(tmp_path)), + capture_output=True, + text=True, + check=True, + ) + assert int(count.stdout) == 2 diff --git a/tests/integration/test_writer_locking.py b/tests/integration/test_writer_locking.py index dd15a4c..0adf54b 100644 --- a/tests/integration/test_writer_locking.py +++ b/tests/integration/test_writer_locking.py @@ -1,13 +1,16 @@ """Exercise writer ownership across independent processes using the same workspace.""" import os +import re import subprocess import sys import time +from pathlib import Path import pytest from litkit.concurrent import FileLock +from litkit.config.paths import WorkspacePaths GUARD_OWNER = """ import sys @@ -102,3 +105,40 @@ def test_file_lock_serializes_processes(tmp_path): finally: if waiter.poll() is None: waiter.kill() + + +REPO = Path(__file__).resolve().parents[2] +# Batch scripts and docs that ship in the repository (the PDF is built from the guides). +# CHANGELOG.md is history: its #15 entry names the old path. +SCRIPTS = sorted(REPO.glob("*.sbatch")) +DOCS = [p for p in sorted(REPO.glob("*.md")) if p.name != "CHANGELOG.md"] +DOCS += sorted(REPO.glob("*.sh")) + [REPO / "justfile"] +# ".writer_guard" not preceded by a name, so attributes such as paths.writer_guard don't count +WRONG_GUARD = re.compile(r"(?/dev/null || true +rm -f "${LITKIT_WORKSPACE}/sqlite/faiss_writer.guard" 2>/dev/null || true + +### ----- CLEAR PRODUCER MARKERS FROM AN EARLIER RUN ---------------------------- +# The consumer reads producer_N.done in the shared emb_segments/ as "shard N is +# finished". With local staging, producers write theirs locally and rsync them +# here at the end, so they can't remove an old one themselves (#5). +rm -f "${LITKIT_WORKSPACE}/emb_segments"/producer_*.done 2>/dev/null || true echo "=== Multi-Node Litkit Build Starting ===" echo "Job ID: $SLURM_JOB_ID" @@ -220,7 +226,7 @@ run_producer() { if [[ "${ACTUAL_USE_LOCAL_STAGING}" == "1" ]]; then 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 + rm -f "${PRODUCER_LOCAL_STAGE_HOST}/sqlite/faiss_writer.guard" 2>/dev/null || true else echo "[Producer ${PRODUCER_NODE_ID}] [staging] Using NFS directly (no local staging)" fi diff --git a/vector_build_single.sbatch b/vector_build_single.sbatch index 3adfe72..3d01c2e 100644 --- a/vector_build_single.sbatch +++ b/vector_build_single.sbatch @@ -460,7 +460,7 @@ fi # 1. This runs at job START (no concurrent writer for this workspace) # 2. Any prior writer is dead (SLURM guarantees our allocation is exclusive) # WARNING: Do NOT add this mid-job or if running concurrent writers. -rm -f "${WORKSPACE:-$LITKIT_WORKSPACE}/.writer_guard" 2>/dev/null || true +rm -f "${WORKSPACE:-$LITKIT_WORKSPACE}/sqlite/faiss_writer.guard" 2>/dev/null || true ### ----- RUN BUILD ------------------------------------------------------------ echo "[info] Starting build in Charliecloud..." diff --git a/vector_resume_consumer.sbatch b/vector_resume_consumer.sbatch index 12bb1db..152d406 100644 --- a/vector_resume_consumer.sbatch +++ b/vector_resume_consumer.sbatch @@ -63,8 +63,9 @@ 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 -n_segs=$(find "$SEG_DIR" -name '*.npz' 2>/dev/null | wc -l) +# Count remaining segment files, including *.npz.ingesting ones that a stopped +# consumer claimed and kept because no save covered them yet (#2) +n_segs=$(find "$SEG_DIR" \( -name '*.npz' -o -name '*.npz.ingesting' \) 2>/dev/null | wc -l) echo "[resume] Found $n_segs segment files to ingest" if [[ "$n_segs" -eq 0 ]]; then @@ -86,7 +87,7 @@ echo "[resume] Detected $n_shards shard(s) from segment filenames" # 1. This runs at job START (no concurrent writer for this workspace) # 2. Any prior writer is dead (SLURM guarantees our allocation is exclusive) # WARNING: Do NOT add this mid-job or if running concurrent writers. -rm -f "${LITKIT_WORKSPACE}/.writer_guard" 2>/dev/null || true +rm -f "${LITKIT_WORKSPACE}/sqlite/faiss_writer.guard" 2>/dev/null || true # Create fake completion markers so consume-only doesn't wait echo "[resume] Creating producer completion markers..."