Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion LITKIT_CLUSTER_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 7 additions & 5 deletions src/litkit/build/consume.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
16 changes: 5 additions & 11 deletions src/litkit/build/ingest_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
12 changes: 9 additions & 3 deletions src/litkit/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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
# ═══════════════════════════════════════════════════════════════════════════
Expand Down
33 changes: 26 additions & 7 deletions src/litkit/db/sharding.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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"
Expand All @@ -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:
Expand All @@ -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}: "
Expand Down
16 changes: 16 additions & 0 deletions src/litkit/segments/coordination.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading
Loading