Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
d66f3f4
Commit tar members and publish their embeddings in recoverable batches
wshlavacek Dec 1, 2026
6eed0e9
Isolate producer recovery and protect committed work from overlapping…
wshlavacek Dec 1, 2026
484ff85
Reserve each staging directory and share consumer discovery with clus…
wshlavacek Dec 1, 2026
dabd78e
Preserve published work across retries and mark every saved consumer …
wshlavacek Dec 1, 2026
b201596
Serialize shard handoff and retain the paper text used for each revision
wshlavacek Dec 1, 2026
381c488
Guard direct shard merges and persist paper revisions before checkpoi…
wshlavacek Dec 1, 2026
7668d27
Recover caller-owned transactions and bound file descriptors during s…
wshlavacek Dec 1, 2026
614174a
Preserve revision order and rebuild semantics across interrupted batches
wshlavacek Dec 2, 2026
8dc1170
Preserve revision order after interrupted reads and failed writer saves
wshlavacek Dec 2, 2026
1fa9de2
Verify legacy producer progress and preserve public segment write order
wshlavacek Dec 2, 2026
e57fa74
Check legacy shard rows before the first checkpoint and reject ambigu…
wshlavacek Dec 2, 2026
765f924
Publish node-local shard copies recoverably before exposing their che…
wshlavacek Dec 2, 2026
772cc61
Recover detached checkpoints and honor producer timeouts during clust…
wshlavacek Dec 2, 2026
4bbe808
Keep reopened FAISS indexes alive while checking native ID maps
wshlavacek Dec 2, 2026
7df48ca
Reject stale node-local transfers and share staging across equivalent…
wshlavacek Dec 2, 2026
f221550
Verify checkpoint output directories before publishing or reclaiming …
wshlavacek Dec 2, 2026
9418cc0
Allow merge-only callers to consume separate segment directories
wshlavacek Dec 2, 2026
8979b75
Match completed batch revisions across SQLite, checkpoints and segmen…
wshlavacek Dec 2, 2026
f27ffdd
Preserve verified producer revisions through shard removal and fresh-…
wshlavacek Dec 2, 2026
37d0b7b
Reject obsolete shard histories and reverify interrupted legacy migra…
wshlavacek Dec 2, 2026
f802fe4
Recover hot SQLite journals before read-only inspection and shard copies
wshlavacek Dec 2, 2026
77b373c
Validate both ends of shard transfers and retry incomplete schema cre…
wshlavacek Dec 2, 2026
f4104a8
Check retained producer state before acknowledging a previous transfer
wshlavacek Dec 2, 2026
62f81c1
Transfer historical content-addressed segments and interrupted claims
wshlavacek Dec 2, 2026
4c707af
Preserve index and checkpoint consistency across cluster resubmission…
wshlavacek Dec 2, 2026
ad2a9c7
Verify indexed worker rows and consume revised paper text, citations …
wshlavacek Dec 2, 2026
69ac54d
Keep delayed shard segments and IVF labels consistent with the curren…
wshlavacek Dec 2, 2026
3377110
Reconcile current article revisions and backfill throttled batches once
wshlavacek Dec 2, 2026
203225c
Preserve citation identifiers and retire duplicate passage IDs on rev…
wshlavacek Dec 2, 2026
5448020
Integrate durable segment consumption and producer marker cleanup fro…
wshlavacek Dec 2, 2026
08fc972
Keep consumed transfers complete and resolve citations across indepen…
wshlavacek Dec 2, 2026
06db22f
Preserve archive order when retained and independent citation aliases…
wshlavacek Dec 2, 2026
08b01fb
Merge main (#44) into the resumable producer batches
wshlavacek Dec 2, 2026
16de41c
Merge main (#14) into the resumable producer batches
wshlavacek Dec 2, 2026
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
9 changes: 7 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ internal versions are summarized under 0.3.33.
## [Unreleased]

### Fixed
- Backfill embeds each missing paper and passage once per pass when index saves are throttled. Reconciliation checks revised vectors before marking them indexed. (#6)
- Removing or replacing chunks in an IVF-PQ index preserves search IDs and scores for the remaining passages.
- Resubmitting a cluster build preserves populated FAISS indexes. A writer rebuild also retires detached shard checkpoints so producers can add new archives afterward.
- Node-local transfers publish the checkpoint, database, segments and completion marker from a recoverable copy on shared storage.
- Completed consumers now mark every saved paper and chunk as indexed when FAISS saves are throttled. Incremental producers embed files recorded by SQLite-only workers and keep revised documents, passages and vectors together after a shard merge.
- Tar builds commit articles in batches. An interrupted producer resumes from the last batch for which it published both paper and chunk segments. 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. If a shard interrupted on an older release has unverifiable or missing embeddings, rebuild from the original archives in a fresh workspace. (#13, #3, #4)
- Keyword search now matches Unicode forms such as `fibrosis`, `CD4`, and `marker²` in existing indexes. Applications executing `sqlite_norm_expr()` on their own SQLite connections can call `litkit.retrieval.register_search_normalizer(conn)` once. LitKit handles registration for its own searches. (#20)
- Capped Stage-2 searches keep newly fetched chunks inside the paper shortlist. Sparse-shortlist fallback and explicit global lexical searches can still return other papers. (#25)
- Corpus manifests accept dotted shard names without a tar extension. The CLI reports entries it cannot resolve. (#19)
Expand All @@ -15,11 +21,10 @@ internal versions are summarized under 0.3.33.
- `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)
- A producer's checkpoint advances only after both paper and passage segments for its batch 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)
- 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)
- Removing vectors from a FAISS index before re-adding them (`--update`, backfill, segment ingestion) takes time proportional to the index size instead of index size times IDs removed. Removing 20,000 IDs from 1M vectors took 10.3 s and now takes 0.03 s. (#14)

## [0.3.36] - 2026-11-30
Expand Down
209 changes: 72 additions & 137 deletions src/litkit/build/backfill.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,13 @@
faiss_present_ids,
faiss_save,
faiss_save_force,
make_id_selector,
kind_and_core,
report_faiss_index,
safe_remove_ids,
)
from litkit.index.ids import copy_hnsw_without_ids
from litkit.segments.ingest import remove_obsolete_chunks
from litkit.db import mark_in_index, flush_pending_marks
from litkit.db.schema import paper_embedding_column
from litkit.progress import eprint

if TYPE_CHECKING:
Expand Down Expand Up @@ -66,85 +68,57 @@ def backfill_unindexed_vectors(
chunk_bs: Batch size for chunk embedding
"""
cur = conn.cursor()

# Papers
while True:
rows = cur.execute(
"SELECT id, (COALESCE(title,'') || ' ' || COALESCE(abstract,'')) "
"AS txt FROM papers WHERE in_index=0 LIMIT ?",
(batch,),
).fetchall()
if not rows:
break
ids = [r[0] for r in rows]
texts = [(r[1] or "untitled").strip() for r in rows]
Xp = paper_embedder.encode(
texts,
progress_label=f"Embedding papers (backfill, {len(texts)})",
batch_size=paper_bs,
progress_done_summary=False,
)

if not isinstance(paper_index, faiss.IndexIDMap2):
paper_index = faiss.IndexIDMap2(paper_index)

prior_ntotal = int(getattr(paper_index, "ntotal", 0) or 0)
with FileLock(faiss_lock_path):
# add_with_ids_dedup handles removal internally - no explicit safe_remove_ids needed
added, ids_added = add_with_ids_dedup(paper_index, ids, Xp)
saved = False
if added:
if prior_ntotal == 0:
saved = faiss_save_force(paper_index, paper_index_path)
else:
saved = faiss_save(paper_index, paper_index_path)
if added and saved:
with FileLock(db_lock_path):
mark_in_index(cur, "papers", [int(i) for i in ids_added])
flush_pending_marks(cur)
conn.commit()
else:
# Save failed - vectors are in FAISS but not marked in DB.
# reconcile_sqlite_flags_with_faiss() will fix this on next run.
conn.commit()

# Chunks
while True:
rows = cur.execute(
"SELECT id, text FROM chunks WHERE in_index=0 LIMIT ?", (batch,)
).fetchall()
recorded_text = paper_embedding_column(conn)
paper_rows = (
f"SELECT p.id, COALESCE({recorded_text}, ("
"SELECT c.text FROM chunks c WHERE c.paper_id=p.id AND c.ord=-1 ORDER BY c.id DESC LIMIT 1"
"), TRIM(COALESCE(p.title,'') || ' ' || COALESCE(p.abstract,''))) FROM papers p"
)
remove_obsolete_chunks(conn, chunk_index, chunk_index_path, faiss_lock_path, db_lock_path, FileLock)
for table, select, index, path, embedder, bs in (
("papers", paper_rows, paper_index, paper_index_path, paper_embedder, paper_bs),
("chunks", "SELECT id, text FROM chunks", chunk_index, chunk_index_path, chunk_embedder, chunk_bs),
):
query = f"{select} WHERE in_index=0"
rows = cur.execute(query + " ORDER BY id LIMIT ?", (batch,)).fetchall()
if not rows:
break
ids = [r[0] for r in rows]
texts = [r[1] for r in rows]
Xc = chunk_embedder.encode(
texts,
progress_label=f"Embedding chunks (backfill, {len(texts)})",
batch_size=chunk_bs,
progress_done_summary=False,
)
if not isinstance(chunk_index, faiss.IndexIDMap2):
chunk_index = faiss.IndexIDMap2(chunk_index)

prior_ntotal = int(getattr(chunk_index, "ntotal", 0) or 0)
with FileLock(faiss_lock_path):
# add_with_ids_dedup handles removal internally - no explicit safe_remove_ids needed
added, ids_added = add_with_ids_dedup(chunk_index, ids, Xc)
saved = False
if added:
if prior_ntotal == 0:
saved = faiss_save_force(chunk_index, chunk_index_path)
else:
saved = faiss_save(chunk_index, chunk_index_path)
if added and saved:
with FileLock(db_lock_path):
mark_in_index(cur, "chunks", [int(i) for i in ids_added])
flush_pending_marks(cur)
conn.commit()
else:
# Save failed - vectors are in FAISS but not marked in DB.
# reconcile_sqlite_flags_with_faiss() will fix this on next run.
conn.commit()
continue
if not isinstance(index, faiss.IndexIDMap2):
index = faiss.IndexIDMap2(index)
if kind_and_core(index)[0] == "hnsw" and index.ntotal:
present = faiss_present_ids(index) or set()
replacing = present.intersection(row[0] for row in cur.execute(f"SELECT id FROM {table} WHERE in_index=0"))
if replacing:
with FileLock(faiss_lock_path):
copy_hnsw_without_ids(faiss.clone_index(index), index, replacing)
pending = []
while rows:
ids = [row[0] for row in rows]
texts = [row[1] for row in rows]
if table == "papers":
texts = [(text or "untitled").strip() for text in texts]
vectors = embedder.encode(texts, batch_size=bs,
progress_label=f"Embedding {table} (backfill, {len(texts)})")
with FileLock(faiss_lock_path):
first = not index.ntotal
added, ids_added = add_with_ids_dedup(index, ids, vectors)
if added != len(ids):
raise RuntimeError(f"Unable to replace every {table} vector in this backfill batch.")
pending.extend(int(i) for i in ids_added)
saved = faiss_save_force(index, path) if first else faiss_save(index, path)
# Advance past unsaved IDs. They stay at zero in SQLite until a
# durable snapshot includes them, so a restart can repeat the work.
rows = cur.execute(query + " AND id>? ORDER BY id LIMIT ?", (ids[-1], batch)).fetchall()
if not rows and not saved:
with FileLock(faiss_lock_path):
faiss_save_force(index, path)
saved = True
if saved:
with FileLock(db_lock_path):
mark_in_index(cur, table, pending)
flush_pending_marks(cur)
conn.commit()
pending.clear()


def reconcile_sqlite_flags_with_faiss(
Expand All @@ -158,64 +132,25 @@ def reconcile_sqlite_flags_with_faiss(
Tuple of (papers_reset, chunks_reset)
"""
cur = conn.cursor()
reset_p = reset_c = 0

# Papers
ids_present = faiss_present_ids(paper_index)
if ids_present is not None:
cur.execute("SELECT id, in_index FROM papers")
bad = [
row[0]
for row in cur.fetchall()
if row[0] not in ids_present and row[1] == 1
]
good_missing_flag = [
row[0]
for row in cur.execute(
"SELECT id FROM papers WHERE in_index=0"
).fetchall()
if row[0] in ids_present
]
if bad:
cur.executemany(
"UPDATE papers SET in_index=0 WHERE id=?", [(i,) for i in bad]
)
reset_p = len(bad)
if good_missing_flag:
cur.executemany(
"UPDATE papers SET in_index=1 WHERE id=?",
[(i,) for i in good_missing_flag],
)

# Chunks
ids_present = faiss_present_ids(chunk_index)
if ids_present is not None:
cur.execute("SELECT id, in_index FROM chunks")
bad = [
row[0]
for row in cur.fetchall()
if row[0] not in ids_present and row[1] == 1
]
good_missing_flag = [
row[0]
for row in cur.execute(
"SELECT id FROM chunks WHERE in_index=0"
).fetchall()
if row[0] in ids_present
]
if bad:
cur.executemany(
"UPDATE chunks SET in_index=0 WHERE id=?", [(i,) for i in bad]
)
reset_c = len(bad)
if good_missing_flag:
cur.executemany(
"UPDATE chunks SET in_index=1 WHERE id=?",
[(i,) for i in good_missing_flag],
)

revised = conn.execute("SELECT 1 FROM sqlite_master WHERE name='merged_paper_revisions'").fetchone()
resets = []
for table, index, paper_key in (("papers", paper_index, "id"), ("chunks", chunk_index, "paper_id")):
present = faiss_present_ids(index)
if present is None:
resets.append(0)
continue
missing = [i for i, in cur.execute(f"SELECT id FROM {table} WHERE in_index=1") if i not in present]
# After merging a revision, the numeric ID can still refer to the
# previous vector. Only a saved replacement may mark these rows.
query = f"SELECT id FROM {table} WHERE in_index=0"
if revised:
query += f" AND {paper_key} NOT IN (SELECT paper_id FROM merged_paper_revisions)"
saved = [i for i, in cur.execute(query) if i in present]
cur.executemany(f"UPDATE {table} SET in_index=0 WHERE id=?", ((i,) for i in missing))
cur.executemany(f"UPDATE {table} SET in_index=1 WHERE id=?", ((i,) for i in saved))
resets.append(len(missing))
conn.commit()
return reset_p, reset_c
return resets[0], resets[1]


def post_build_sanity_check(
Expand Down
Loading
Loading