From 727c7103f4036950402bfc43a7c98d493f0bbeea Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 12:22:43 -0700 Subject: [PATCH 1/3] Stream corpus shards in order and persist training fallbacks Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 3 + src/litkit/build/indices.py | 15 +- src/litkit/build/training.py | 93 ++++---- src/litkit/cli.py | 5 +- src/litkit/ingest/ingest.py | 264 +++++++--------------- tests/integration/test_build_and_query.py | 47 ++++ tests/test_index.py | 128 +++++++++++ tests/test_ingest.py | 96 +++++++- 8 files changed, 393 insertions(+), 258 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5db106e..569d190 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,9 @@ internal versions are summarized under 0.3.33. ## [Unreleased] ### Fixed +- Corpus manifests accept dotted shard names without a tar extension. The CLI reports entries it cannot resolve. (#19) +- 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) ## [0.3.36] - 2026-11-30 diff --git a/src/litkit/build/indices.py b/src/litkit/build/indices.py index 23a9607..20963c6 100644 --- a/src/litkit/build/indices.py +++ b/src/litkit/build/indices.py @@ -21,7 +21,6 @@ faiss_load, unwrap_core_and_kind, kind_and_core, - extract_ivf, ) from litkit.build.helpers import ensure_parent from litkit.progress import eprint as _eprint @@ -238,7 +237,7 @@ def load_or_create_chunk_index( if chunk_index_path.exists(): chunk_index = faiss_load(chunk_index_path) - _, core = kind_and_core(chunk_index) + kind, core = kind_and_core(chunk_index) mt = getattr(core, "metric_type", faiss.METRIC_INNER_PRODUCT) if mt != faiss.METRIC_INNER_PRODUCT: @@ -254,24 +253,22 @@ def load_or_create_chunk_index( faiss_save(chunk_index, chunk_index_path) # Check if IVF-PQ needs training - ivf = extract_ivf(chunk_index) - if isinstance(ivf, faiss.IndexIVFPQ) and not getattr(ivf, "is_trained", False): + # FAISS can expose the inner IVFPQ as its IndexIVF base class. + if kind == "ivf" and not core.is_trained: _eprint( "[train] WARNING: chunks index is IVFPQ but untrained; " "ignoring stale trained flag and retraining." ) - _clear_trained_flag(chunk_trained_flag) needs_training = True else: if chunks_index == "flat": base = flat_ip_index(chunk_dim) chunk_index = faiss.IndexIDMap2(base) - _clear_trained_flag(chunk_trained_flag) - ensure_parent(chunk_index_path) - if is_faiss_writer: with FileLock(db_lock_path), FileLock(faiss_lock_path): - faiss_save(chunk_index, chunk_index_path) + ensure_parent(chunk_index_path) + faiss_save_force(chunk_index, chunk_index_path) + _clear_trained_flag(chunk_trained_flag) else: raise RuntimeError( "CHUNK index does not exist. Start a writer with --faiss-writer " diff --git a/src/litkit/build/training.py b/src/litkit/build/training.py index 94036c7..feb2840 100644 --- a/src/litkit/build/training.py +++ b/src/litkit/build/training.py @@ -20,7 +20,7 @@ flat_ip_index, ivfpq_index, safe_pq_m, - faiss_save, + faiss_save_force, auto_set_nprobe, PQ_BITS, ) @@ -245,17 +245,20 @@ def _flush_train(buf: list[str]) -> np.ndarray: texts_buf.clear() samples_prog.finish() - - # Handle no training data case + + def flat_fallback() -> faiss.Index: + index = faiss.IndexIDMap2(flat_ip_index(chunk_dim)) + if is_faiss_writer: + with FileLock(db_lock_path), FileLock(faiss_lock_path): + ensure_parent(chunk_index_path) + faiss_save_force(index, chunk_index_path) + _clear_trained_flag(chunk_trained_flag) + return index + if not X_train_list: _eprint("[train] WARNING: no chunk texts found for training; falling back to FLAT index") - base = flat_ip_index(chunk_dim) - chunk_index = faiss.IndexIDMap2(base) - _clear_trained_flag(chunk_trained_flag) - if is_faiss_writer: - faiss_save(chunk_index, chunk_index_path) - return chunk_index - + return flat_fallback() + # Prepare training data X_train = np.vstack(X_train_list) if X_train.shape[0] > train_samples: @@ -263,8 +266,7 @@ def _flush_train(buf: list[str]) -> np.ndarray: n_train = int(X_train.shape[0]) _eprint(f"[train] chunk training samples: target={train_samples} collected={n_train}") - ensure_parent(chunk_index_path) - + # Training decision tree pq_bits = PQ_BITS k = 1 << pq_bits @@ -275,14 +277,8 @@ def _flush_train(buf: list[str]) -> np.ndarray: # Check if we have enough data for IVF-PQ if n_train < max(min_for_micro, min_for_pq, 100 * m_candidate): _eprint(f"[train] not enough samples for IVF-PQ (n={n_train}); using FLAT IP") - base = flat_ip_index(chunk_dim) - chunk_index = faiss.IndexIDMap2(base) - if is_faiss_writer: - with FileLock(db_lock_path), FileLock(faiss_lock_path): - faiss_save(chunk_index, chunk_index_path) - _clear_trained_flag(chunk_trained_flag) - return chunk_index - + return flat_fallback() + # Choose nlist with data-aware caps eff_nlist = _effective_nlist(n_train, ivf_nlist, user_forced=ivf_nlist_forced) max_by_samples = max(1, n_train // 40) @@ -293,14 +289,8 @@ def _flush_train(buf: list[str]) -> np.ndarray: # Re-check adequacy with final nlist if eff_nlist < 8 or n_train < max(min_for_pq, 50 * eff_nlist, 100 * m_candidate): _eprint(f"[train] nlist/m under-sampled (n={n_train}, nlist={eff_nlist}, m={m_candidate}); using FLAT IP") - base = flat_ip_index(chunk_dim) - chunk_index = faiss.IndexIDMap2(base) - if is_faiss_writer: - with FileLock(db_lock_path), FileLock(faiss_lock_path): - faiss_save(chunk_index, chunk_index_path) - _clear_trained_flag(chunk_trained_flag) - return chunk_index - + return flat_fallback() + # Train IVF-PQ m = m_candidate if m != pq_m: @@ -337,32 +327,29 @@ def _flush_train(buf: list[str]) -> np.ndarray: # Set nprobe auto_set_nprobe(new_chunk_index, nprobe) chunk_index = faiss.IndexIDMap2(new_chunk_index) - - # Save and write trained flag - if is_faiss_writer: - with FileLock(db_lock_path), FileLock(faiss_lock_path): - faiss_save(chunk_index, chunk_index_path) - - _tf_tmp = chunk_trained_flag.with_suffix(".tmp") - with open(_tf_tmp, "w") as fh: - fh.write(json.dumps({ + + except Exception as e: + _eprint(f"[train] WARNING: IVF-PQ training failed ({e}); falling back to FLAT") + return flat_fallback() + + if is_faiss_writer: + with FileLock(db_lock_path), FileLock(faiss_lock_path): + ensure_parent(chunk_index_path) + faiss_save_force(chunk_index, chunk_index_path) + flag_tmp = chunk_trained_flag.with_suffix(".tmp") + with open(flag_tmp, "w") as fh: + json.dump( + { "trained_on": int(time.time()), "n": n_train, "nlist": eff_nlist, "m": m, - }, indent=2)) - fh.flush() - os.fsync(fh.fileno()) - os.replace(_tf_tmp, chunk_trained_flag) - maybe_fsync_dir(chunk_trained_flag) - - return chunk_index - - except Exception as e: - _eprint(f"[train] WARNING: IVF-PQ training failed ({e}); falling back to FLAT") - chunk_index = faiss.IndexIDMap2(flat_ip_index(chunk_dim)) - if is_faiss_writer: - with FileLock(db_lock_path), FileLock(faiss_lock_path): - faiss_save(chunk_index, chunk_index_path) - _clear_trained_flag(chunk_trained_flag) - return chunk_index + }, + fh, + indent=2, + ) + fh.flush() + os.fsync(fh.fileno()) + os.replace(flag_tmp, chunk_trained_flag) + maybe_fsync_dir(chunk_trained_flag) + return chunk_index diff --git a/src/litkit/cli.py b/src/litkit/cli.py index d91a7c6..263cb6b 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -55,6 +55,7 @@ def _version_banner() -> str: # Only imports needed BEFORE argparse runs (for --help/--version) are at module level. # Other stdlib imports are deferred to their use sites to minimize import-time side effects. import argparse +import logging import threading from pathlib import Path from typing import Any, Iterator @@ -270,9 +271,6 @@ def _load_heavy_deps() -> None: -# logging.basicConfig(level=logging.WARNING, format="%(levelname)s %(name)s: %(message)s") - - def deps() -> SimpleNamespace: """Load heavy dependencies (idempotent) and return the deps namespace. @@ -1598,6 +1596,7 @@ def get_chunks(conn, ids: list[int]) -> list[dict[str, Any]]: # -------------------- Main -------------------- def main(): """CLI entry point.""" + logging.basicConfig(format="%(levelname)s %(name)s: %(message)s") # Windows pipes default to the ANSI code page, which can lose scientific text. if ( os.name == "nt" diff --git a/src/litkit/ingest/ingest.py b/src/litkit/ingest/ingest.py index 6c0a2e9..42e626e 100644 --- a/src/litkit/ingest/ingest.py +++ b/src/litkit/ingest/ingest.py @@ -46,8 +46,8 @@ import tarfile import threading from collections.abc import Iterable, Iterator -from concurrent.futures import ThreadPoolExecutor, as_completed -from contextlib import ExitStack, contextmanager +from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait +from contextlib import closing, contextmanager from pathlib import Path, PureWindowsPath from typing import IO, Any, NotRequired, TypedDict @@ -97,7 +97,7 @@ def _open_tar_safely(tar_path: str | Path): """Open a tar (any compression). Yields None if unreadable and then logs a warning.""" try: tf = tarfile.open(str(tar_path), mode="r:*") - except (tarfile.TarError, OSError) as e: + except (tarfile.TarError, OSError, EOFError) as e: logger.warning("[tar] skipping unreadable shard %s: %s", tar_path, e) yield None return @@ -273,7 +273,9 @@ def parse_xml_fileobj(fobj: IO[bytes], member_name: str = "") -> ArticleMeta | N def _parse_tree(tree: etree._ElementTree, member_name: str) -> ArticleMeta | None: root = tree.getroot() - rootname = etree.QName(root).localname.lower() if root is not None else "" + if root is None: + return None + rootname = etree.QName(root).localname.lower() meta = parse_jats(tree, member_name) if rootname == "article" else parse_pubmed(tree) # Fallback: sometimes PubMed-ish roots still contain JATS sections if not (meta["title"] or meta["abstract"]): @@ -384,24 +386,15 @@ def iter_tar_paths( """ def _resolve_token(tok: str, base: Path) -> Path | None: - tok = tok.strip() - if not tok: - return None - p = Path(tok) - if p.is_absolute(): - return p if p.exists() and _is_tar_path(p) else None candidate = base / tok - if candidate.exists() and _is_tar_path(candidate): - return candidate - # If no suffix was provided, try common tar compressions. - if candidate.suffix == "": - for ext in _TAR_EXTS: - c3 = Path(str(candidate) + ext) - if c3.exists() and _is_tar_path(c3): - return c3 + if _is_tar_path(candidate): + return candidate if candidate.is_file() else None + for ext in _TAR_EXTS: + archive = Path(f"{candidate}{ext}") + if archive.is_file(): + return archive return None - if manifest is not None: mf = Path(manifest) base = Path(tar_dir) if tar_dir is not None else mf.parent @@ -433,93 +426,55 @@ def _resolve_token(tok: str, base: Path) -> Path | None: yield p +def _iter_xml_members(tf: tarfile.TarFile, exts: Iterable[str]) -> Iterator[tarfile.TarInfo]: + suffixes = tuple(ext.lower() for ext in exts) + while True: + try: + member = tf.next() + except (tarfile.TarError, OSError, EOFError) as e: + logger.warning("[tar] error iterating %s: %s", tf.name, e) + return + if member is None: + return + # Python 3.12 caches every header even with next(). We only extract + # regular files by TarInfo, so later members need no name lookup. + tf.members.clear() + if member.isfile() and member.name.lower().endswith(suffixes): + yield member + + def iter_tar_xml_member_names( tar_path: str | Path, exts: Iterable[str] = _XML_EXTS, ) -> Iterator[str]: """Iterate member names inside a tar that look like XML, streaming safely.""" - lower_exts = tuple(e.lower() for e in exts) - stack = ExitStack() - try: - tf = stack.enter_context(_open_tar_safely(tar_path)) - if tf is None: - return # unreadable: yield nothing - - # Stream through the archive without loading all headers into memory. - # TarFile.next() returns the next TarInfo or None at EOF. - while True: - try: - m = tf.next() # type: ignore[attr-defined] - except (tarfile.TarError, OSError) as e: - logger.warning("[tar] error iterating %s: %s", tar_path, e) - break - if m is None: - break - if m.isfile() and m.name.lower().endswith(lower_exts): - yield m.name - finally: - stack.close() + with _open_tar_safely(tar_path) as tf: + if tf is not None: + for member in _iter_xml_members(tf, exts): + yield member.name def count_tar_xml_members(tar_path: str | Path, exts: Iterable[str] = _XML_EXTS) -> int: """Count XML/NXML members in a tar/tgz.""" - lower_exts = tuple(e.lower() for e in exts) - stack = ExitStack() - try: - tf = stack.enter_context(_open_tar_safely(tar_path)) - if tf is None: - return 0 - count = 0 - while True: - try: - m = tf.next() # stream headers without loading full table - except (tarfile.TarError, OSError): - break - if m is None: - break - if m.isfile() and m.name.lower().endswith(lower_exts): - count += 1 - return count - finally: - stack.close() + return sum(1 for _ in iter_tar_xml_member_names(tar_path, exts)) def iter_tar_xml_streams( tar_path: str | Path, exts: Iterable[str] = _XML_EXTS, ) -> Iterator[tuple[tarfile.TarInfo, IO[bytes]]]: - lower_exts = tuple(e.lower() for e in exts) - stack = ExitStack() - try: - tf = stack.enter_context(_open_tar_safely(tar_path)) + with _open_tar_safely(tar_path) as tf: if tf is None: return - while True: - try: - m = tf.next() - except (tarfile.TarError, OSError) as e: - logger.warning("[tar] error iterating %s: %s", tar_path, e) - break - if m is None: - break - if not (m.isfile() and m.name.lower().endswith(lower_exts)): - continue + for member in _iter_xml_members(tf, exts): try: - f = tf.extractfile(m) - except (tarfile.TarError, OSError) as e: - logger.warning("[tar] cannot extract %s from %s: %s", m.name, tar_path, e) + stream = tf.extractfile(member) + except (tarfile.TarError, OSError, EOFError) as e: + logger.warning("[tar] cannot extract %s from %s: %s", member.name, tar_path, e) continue - if f is None: - continue - try: - yield m, f - finally: - try: - f.close() - except Exception: - pass - finally: - stack.close() + if stream is not None: + with stream: + yield member, stream # ------------------------------- @@ -616,107 +571,44 @@ def parallel_iter_tar_articles( - Uncompressed .tar files allow faster I/O since no decompression is needed. - XML parsing (lxml) releases the GIL during C operations, so threading provides real parallelism. - - With yield_in_order=True, uses a reorder buffer to preserve tar order. - Memory usage is bounded: O(workers * 4) results buffered at most. """ - import heapq - - lower_exts = tuple(e.lower() for e in exts) - - with _open_tar_safely(tar_path) as tf: - if tf is None: - return - - with ThreadPoolExecutor(max_workers=workers) as pool: - futures = {} # future -> (sequence, meta) - pending_count = 0 - max_pending = workers * 4 # limit memory: ~4 XMLs per worker in flight - - # For in-order yielding - sequence = 0 # monotonically increasing submission order (tar order) - next_yield_seq = 0 # next sequence number to yield - result_heap: list[tuple[int, TarMemberMeta, ArticleMeta]] = [] # (seq, meta, article) - eof_reached = False - - while True: - # Submit new work while under the limit and not at EOF - while not eof_reached and pending_count < max_pending: - try: - m = tf.next() - except (tarfile.TarError, OSError) as e: - logger.warning("[tar] error iterating %s: %s", tar_path, e) - m = None - if m is None: - eof_reached = True - break - if not (m.isfile() and m.name.lower().endswith(lower_exts)): - continue - try: - f = tf.extractfile(m) - if f is None: - continue - data = f.read() - f.close() - except (tarfile.TarError, OSError) as e: - logger.warning("[tar] cannot extract %s: %s", m.name, e) - continue - - meta = TarMemberMeta( - name=m.name, - size=int(getattr(m, "size", 0)), - mtime=float(getattr(m, "mtime", 0.0) or 0.0), - ) - fut = pool.submit(_parse_xml_bytes, data, m.name) - futures[fut] = (sequence, meta) - sequence += 1 - pending_count += 1 - - if not futures: - # Drain any remaining buffered results (in-order mode) - if yield_in_order: - while result_heap: - _, meta, article = heapq.heappop(result_heap) - yield (meta, article) - break # no more work - - # Collect completed results - done_futures = [f for f in futures if f.done()] - if not done_futures: - # Wait for at least one to complete - import concurrent.futures - done, _ = concurrent.futures.wait( - futures.keys(), - return_when=concurrent.futures.FIRST_COMPLETED - ) - done_futures = list(done) - - for fut in done_futures: - seq, meta = futures.pop(fut) - pending_count -= 1 - try: - result, _tid = fut.result() - if result is not None: - if yield_in_order: - # Buffer for in-order yielding - heapq.heappush(result_heap, (seq, meta, result)) - else: - # Original behavior: yield immediately - yield (meta, result) - except Exception as e: - logger.warning("[parse] error parsing %s: %s", meta.name, e) - if yield_in_order: - # Must track failed parses to not block the sequence - # We increment next_yield_seq when we would have yielded this - # Since result is None, we skip it but advance the sequence - heapq.heappush(result_heap, (seq, meta, None)) # type: ignore - - # Yield buffered results in order - if yield_in_order: - while result_heap and result_heap[0][0] == next_yield_seq: - _, meta, article = heapq.heappop(result_heap) - next_yield_seq += 1 - if article is not None: - yield (meta, article) + max_pending = workers * 4 + with ( + closing(iter_tar_xml_streams(tar_path, exts)) as streams, + ThreadPoolExecutor(max_workers=workers) as pool, + ): + pending = {} # Insertion order is tar order, including unsuccessful parses. + while True: + while len(pending) < max_pending: + item = next(streams, None) + if item is None: + break + member, stream = item + try: + data = stream.read() + except (tarfile.TarError, OSError, EOFError) as e: + logger.warning("[tar] cannot read %s from %s: %s", member.name, tar_path, e) + continue + future = pool.submit(_parse_xml_bytes, data, member.name) + pending[future] = TarMemberMeta(member.name, member.size, member.mtime) + + if not pending: + return + if yield_in_order: + # Waiting on the oldest also bounds completed results behind a slow member. + ready = (next(iter(pending)),) + else: + ready, _ = wait(pending, return_when=FIRST_COMPLETED) + for future in ready: + meta = pending.pop(future) + try: + article, _ = future.result() + except Exception as e: + logger.warning("[parse] error parsing %s: %s", meta.name, e) + continue + if article is not None: + yield meta, article # Public API diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index 147f557..8017135 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -15,6 +15,7 @@ import pytest from conftest import CORPUS, jats, write_tar +from litkit.index import faiss_load, kind_and_core RUNNER = Path(__file__).with_name("run_litkit_fake.py") FLAT = ["--chunks-index", "flat", "--papers-index", "flat"] @@ -466,6 +467,52 @@ def test_compressed_tar_builds_the_same_as_uncompressed(isolated_env, tmp_path, _assert_db_matches_indexes(ws_gz) +def test_manifest_build_continues_past_rootless_xml(isolated_env, tmp_path): + archive = write_tar( + tmp_path / "baseline.2025-06-26.tar.gz", + { + "first.xml": jats(**CORPUS["egfr"]), + "bad.nxml": "not an article", + "last.xml": jats(**CORPUS["malaria"]), + }, + ) + manifest = tmp_path / "corpus.manifest" + manifest.write_text(f"absent.tar\n{archive.name.removesuffix('.tar.gz')}\n") + build = ["--build-only", "--faiss-writer", "--tar-manifest", str(manifest), *FLAT] + proc = _ok(litkit(isolated_env, "--rebuild", *build)) + assert "absent.tar" in proc.stderr + with _db(isolated_env) as conn: + pmcids = set(conn.execute("SELECT pmcid FROM papers")) + assert pmcids == {(CORPUS["egfr"]["pmcid"],), (CORPUS["malaria"]["pmcid"],)} + before = _chunk_rows(isolated_env) + assert len(before) == 4 + _ok(litkit(isolated_env, "--update", *build)) + assert _chunk_rows(isolated_env) == before + _assert_db_matches_indexes(isolated_env) + + +@pytest.mark.parametrize("bootstrap", [False, True], ids=["new", "reopen-untrained"]) +def test_ivfpq_fallback_indexes_title_only_archive(isolated_env, tmp_path, monkeypatch, bootstrap): + archive = write_tar( + tmp_path / "titles.tar.gz", {"only.xml": jats(pmcid="PMC99", title="Title only")} + ) + manifest = tmp_path / "corpus.manifest" + manifest.write_text(archive.name) + args = ["--build-only", "--faiss-writer", "--chunks-index", "ivfpq", "--ivf-nlist", "16"] + if bootstrap: + monkeypatch.setenv("FAKE_EMBED_DIM", "768") # Dimensions of the bootstrapped indexes. + _ok(litkit(isolated_env, "--init-indices-only", *args)) + (isolated_env / "indices" / "chunks.trained.json").write_text("stale") + mode = "--update" if bootstrap else "--rebuild" + proc = _ok(litkit(isolated_env, mode, *args, "--tar-manifest", str(manifest))) + assert "no chunk texts found for training" in proc.stderr + index = faiss_load(isolated_env / "indices" / "chunks.faiss") + assert kind_and_core(index)[0] == "flat" + assert index.ntotal == 1 + assert _count(isolated_env, "SELECT COUNT(*) FROM chunks WHERE in_index=1") == 1 + assert not (isolated_env / "indices" / "chunks.trained.json").exists() + + def test_edge_case_members_are_skipped(isolated_env, tiny_corpus): """Empty
, no abstract, PubMed record and a non-XML member, in a .tar.""" tar_dir = tiny_corpus.parent / "only_a" diff --git a/tests/test_index.py b/tests/test_index.py index 605198b..89c1b5f 100644 --- a/tests/test_index.py +++ b/tests/test_index.py @@ -1,12 +1,17 @@ """Tests for litkit.index: exact search, ID replacement, approximate recall, index-type detection, and saving and loading.""" +import json import os +from functools import partial import faiss import numpy as np import pytest +from conftest import jats, write_tar +from litkit.build import training +from litkit.build.indices import load_or_create_chunk_index from litkit.concurrent.locking import FileLock from litkit.index import io as index_io from litkit.index.dedup import add_with_ids_dedup @@ -187,6 +192,129 @@ def test_faiss_save_requires_lock(tmp_path, fresh_throttle): index_io.faiss_save(flat_ip_index(DIM), tmp_path / "papers.faiss") +@pytest.fixture +def chunk_index_paths(tmp_path): + db_lock = tmp_path / "db.lock" + faiss_lock = tmp_path / "faiss.lock" + return dict( + chunk_index_path=tmp_path / "chunks.faiss", + chunk_trained_flag=tmp_path / "chunks.trained.json", + db_lock_path=db_lock, + faiss_lock_path=faiss_lock, + FileLock=partial(FileLock, db_lock_path=db_lock, faiss_lock_path=faiss_lock), + ) + + +@pytest.mark.parametrize("writer", [True, False], ids=["writer", "nonwriter"]) +def test_creating_missing_flat_index_with_stale_marker( + tmp_path, fresh_throttle, chunk_index_paths, writer +): + paths = chunk_index_paths + path = paths["chunk_index_path"] + flag = paths["chunk_trained_flag"] + flag.write_text("stale") + with paths["FileLock"](paths["faiss_lock_path"]): + index_io.faiss_save_force(flat_ip_index(DIM), tmp_path / "previous.faiss") + + def open_index(): + return load_or_create_chunk_index( + **paths, chunk_dim=DIM, chunks_index="flat", ivf_nlist=4, pq_m=8, is_faiss_writer=writer + ) + + if writer: + _, needs_training = open_index() + assert not needs_training + assert kind_and_core(index_io.faiss_load(path))[0] == "flat" + assert not flag.exists() + else: + with pytest.raises(RuntimeError, match="CHUNK index does not exist"): + open_index() + assert not path.exists() + assert flag.read_text() == "stale" + + +@pytest.mark.parametrize("writer", [True, False], ids=["writer", "nonwriter"]) +@pytest.mark.parametrize("body", [(), ("Some training text.",)], ids=["empty", "undersized"]) +def test_flat_training_fallback_persists_only_for_writer( + tmp_path, fake_embedder, fresh_throttle, chunk_index_paths, writer, body +): + archive = tmp_path / "sample.tar" + write_tar(archive, {"paper.xml": jats(title="Title only", paragraphs=body)}) + paths = chunk_index_paths + path = paths["chunk_index_path"] + flag = paths["chunk_trained_flag"] + flag.write_text("previous training") + with paths["FileLock"](paths["faiss_lock_path"]): + index_io.faiss_save_force(ivfpq_index(DIM, nlist=4, m=8), path) + + index = training.train_ivfpq_index( + chunk_dim=DIM, + chunk_embedder=fake_embedder, + tar_dir=tmp_path, + tar_manifest=None, + ivf_nlist=4, + pq_m=8, + nprobe=None, + is_faiss_writer=writer, + **paths, + ) + assert kind_and_core(index)[0] == "flat" + assert kind_and_core(index_io.faiss_load(path))[0] == ("flat" if writer else "ivf") + if writer: + assert not flag.exists() + else: + assert flag.read_text() == "previous training" + + +@pytest.mark.parametrize("write_error", [False, True], ids=["saved", "disk-full"]) +def test_ivfpq_training_publishes_flag_only_after_index_is_saved( + tmp_path, fake_embedder, fresh_throttle, chunk_index_paths, monkeypatch, write_error +): + # A two-bit codebook keeps real FAISS training small enough for the default suite. + monkeypatch.setattr(training, "PQ_BITS", 2) + monkeypatch.setenv("LITKIT_TRAIN_PER_PAPER", "800") + paragraphs = [f"sample {i}" for i in range(800)] + write_tar(tmp_path / "sample.tar", {"paper.xml": jats(title="Samples", paragraphs=paragraphs)}) + paths = chunk_index_paths + path = paths["chunk_index_path"] + flag = paths["chunk_trained_flag"] + with paths["FileLock"](paths["faiss_lock_path"]): + index_io.faiss_save_force(flat_ip_index(DIM), path) + + def train(): + return training.train_ivfpq_index( + chunk_dim=DIM, + chunk_embedder=fake_embedder, + tar_dir=tmp_path, + tar_manifest=None, + ivf_nlist=16, + pq_m=1, + nprobe=1, + train_samples=800, + chunk_target_chars=1, + chunk_min_chars=0, + chunk_overlap=0, + **paths, + ) + + if write_error: + + def disk_full(index, path): + raise OSError("disk full") + + monkeypatch.setattr(index_io, "_write_index_atomically", disk_full) + with pytest.raises(OSError, match="disk full"): + train() + assert kind_and_core(index_io.faiss_load(path))[0] == "flat" + assert not flag.exists() + else: + train() + saved = index_io.faiss_load(path) + assert kind_and_core(saved)[0] == "ivf" + assert saved.is_trained + assert json.loads(flag.read_text())["n"] == 800 + + def test_faiss_save_is_throttled_per_label(tmp_path, faiss_lock, fresh_throttle, unit_vectors): index = flat_ip_index(DIM) with faiss_lock(): diff --git a/tests/test_ingest.py b/tests/test_ingest.py index 6f31186..3f1986a 100644 --- a/tests/test_ingest.py +++ b/tests/test_ingest.py @@ -2,6 +2,8 @@ import io import tarfile +from contextlib import closing +from threading import Event import pytest @@ -91,8 +93,7 @@ def test_parse_returns_none_for_unusable_input(data): assert parse_xml_fileobj(io.BytesIO(data)) is None -@pytest.mark.xfail(strict=True, raises=AssertionError, reason="#24: raises instead of None") -@pytest.mark.parametrize("data", [b" \n", b"not xml at all"]) +@pytest.mark.parametrize("data", [b" \n", b"not xml at all", b'']) def test_parse_returns_none_for_text_without_a_root(data): assert parse_xml_fileobj(io.BytesIO(data)) is None @@ -175,6 +176,21 @@ def test_count_and_stream_only_xml_members(tiny_corpus): assert count_tar_xml_members(tar) == 6 +def test_tar_prescan_releases_headers_as_it_goes(tmp_path, monkeypatch): + tar = write_tar(tmp_path / "many.tar", {f"{i}.xml": "" for i in range(64)}) + cached = [] + next_header = tarfile.TarFile.next + + def track_headers(tf): + member = next_header(tf) + cached.append(len(tf.members)) + return member + + monkeypatch.setattr(tarfile.TarFile, "next", track_headers) + assert count_tar_xml_members(tar) == 64 + assert max(cached) <= 1 + + def test_extension_match_is_case_insensitive(tmp_path): tar = write_tar(tmp_path / "x.tar", {"A.NXML": jats(pmcid="PMC1", title="T")}) assert count_tar_xml_members(tar) == 1 @@ -187,6 +203,14 @@ def test_unreadable_tar_yields_nothing(tmp_path): assert list(iter_tar_xml_streams(bad)) == [] +def test_truncated_gzip_header_is_skipped(tmp_path, caplog): + archive = write_tar(tmp_path / "incomplete.tar.gz", {"a.xml": jats(title="A")}) + archive.write_bytes(archive.read_bytes()[:10]) + assert count_tar_xml_members(archive) == 0 + assert list(iter_tar_xml_streams(archive)) == [] + assert archive.name in caplog.text + + def test_parallel_parse_matches_sequential_parse(tiny_corpus): """Two implementations of the same job: they must agree, in tar order.""" tar = tiny_corpus / "corpus_a.tar" @@ -210,6 +234,54 @@ def test_parallel_member_meta_has_size_and_mtime(tiny_corpus): assert m.mtime == 1_700_000_000 +def test_ordered_parser_resumes_streaming_after_empty_member(tmp_path, monkeypatch): + good = {f"{i}.xml": jats(title=f"Article {i}") for i in range(30)} + tar = write_tar(tmp_path / "mixed.tar", {"empty.xml": "
", **good}) + reads = [] + extractfile = tarfile.TarFile.extractfile + + def track_read(tf, member): + reads.append(member.name) + return extractfile(tf, member) + + monkeypatch.setattr(tarfile.TarFile, "extractfile", track_read) + with closing(parallel_iter_tar_articles(tar, workers=2)) as articles: + for consumed, expected in enumerate(good, start=2): + member, article = next(articles) + assert member.name == expected + assert article["title"] == f"Article {consumed - 2}" + assert len(reads) - consumed < 2 * 4 + assert next(articles, None) is None + + +def test_unordered_parser_can_yield_while_first_parse_is_blocked(tmp_path, monkeypatch): + from litkit.ingest import ingest + + tar = write_tar( + tmp_path / "mixed.tar", + { + "slow.xml": jats(title="Slow"), + "empty.xml": "
", + "ready.xml": jats(title="Ready"), + }, + ) + release = Event() + parse = ingest._parse_xml_bytes + + def parse_member(data, name): + if name == "slow.xml" and not release.wait(timeout=10): + raise RuntimeError("first parse was never released") + return parse(data, name) + + monkeypatch.setattr(ingest, "_parse_xml_bytes", parse_member) + with closing(parallel_iter_tar_articles(tar, workers=2, yield_in_order=False)) as articles: + try: + assert next(articles)[0].name == "ready.xml" + finally: + release.set() + assert [m.name for m, _ in articles] == ["slow.xml"] + + @pytest.mark.parametrize( ("name", "expected"), [ @@ -272,12 +344,22 @@ def test_manifest_relative_entries_use_tar_dir_when_given(tar_dir, tmp_path): assert list(iter_tar_paths(None, manifest)) == [] # resolved next to the manifest -@pytest.mark.xfail(strict=True, raises=AssertionError, reason="#19: dotted name, no extension") -def test_manifest_dotted_name_without_extension(tmp_path): - (tmp_path / "oa_comm_xml.PMC000xxxxxx.baseline.2025-06-26.tar.gz").write_bytes(b"") +@pytest.mark.parametrize("absolute", [False, True], ids=["relative", "absolute"]) +def test_manifest_dotted_name_without_extension(tmp_path, absolute): + stem = "oa_comm_xml.PMC000xxxxxx.baseline.2025-06-26" + archive = tmp_path / f"{stem}.tar.gz" + archive.touch() + manifest = tmp_path / "m.manifest" + manifest.write_text(f"{tmp_path / stem if absolute else stem}\n") + assert list(iter_tar_paths(None, manifest)) == [archive.resolve()] + + +def test_manifest_requires_a_file_and_respects_explicit_tar_suffix(tmp_path): + (tmp_path / "dir.tar").mkdir() + (tmp_path / "missing.tgz.tar").touch() manifest = tmp_path / "m.manifest" - manifest.write_text("oa_comm_xml.PMC000xxxxxx.baseline.2025-06-26\n") - assert len(list(iter_tar_paths(None, manifest))) == 1 + manifest.write_text("dir\ndir.tar\nmissing.tgz\n") + assert list(iter_tar_paths(None, manifest)) == [] def test_no_dir_and_no_manifest_is_an_error(): From 3510fa39965e5bae8097272334d12945f4f6c026 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 12:25:55 -0700 Subject: [PATCH 2/3] Continue checking tar suffixes when a candidate name is too long Signed-off-by: Bill Hlavacek --- src/litkit/ingest/ingest.py | 15 ++++++++++----- tests/test_ingest.py | 21 +++++++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src/litkit/ingest/ingest.py b/src/litkit/ingest/ingest.py index 42e626e..ec8889d 100644 --- a/src/litkit/ingest/ingest.py +++ b/src/litkit/ingest/ingest.py @@ -40,6 +40,7 @@ from __future__ import annotations +import errno import io import logging import re @@ -387,12 +388,16 @@ def iter_tar_paths( def _resolve_token(tok: str, base: Path) -> Path | None: candidate = base / tok - if _is_tar_path(candidate): - return candidate if candidate.is_file() else None - for ext in _TAR_EXTS: + extensions = ("",) if _is_tar_path(candidate) else _TAR_EXTS + for ext in extensions: archive = Path(f"{candidate}{ext}") - if archive.is_file(): - return archive + try: + if archive.is_file(): + return archive + except OSError as e: + # A longer suffix may exceed the filesystem's filename limit. + if e.errno != errno.ENAMETOOLONG: + raise return None if manifest is not None: diff --git a/tests/test_ingest.py b/tests/test_ingest.py index 3f1986a..df681ea 100644 --- a/tests/test_ingest.py +++ b/tests/test_ingest.py @@ -1,8 +1,10 @@ """Tests for litkit.ingest: JATS/PubMed parsing, chunk packing, tar and manifest handling.""" +import errno import io import tarfile from contextlib import closing +from pathlib import Path from threading import Event import pytest @@ -362,6 +364,25 @@ def test_manifest_requires_a_file_and_respects_explicit_tar_suffix(tmp_path): assert list(iter_tar_paths(None, manifest)) == [] +def test_manifest_tries_shorter_suffix_after_overlong_candidate(tmp_path, monkeypatch, caplog): + stem = "baseline.2025" + archive = tmp_path / f"{stem}.tgz" + archive.touch() + manifest = tmp_path / "m.manifest" + manifest.write_text(f"missing.tar\n{stem}\n") + is_file = Path.is_file + + def check_path(path): + # Filesystem name limits vary. Model a stem for which .tgz fits but .tar.gz does not. + if path.name in {"missing.tar", f"{stem}.tar.gz"}: + raise OSError(errno.ENAMETOOLONG, "File name too long") + return is_file(path) + + monkeypatch.setattr(Path, "is_file", check_path) + assert list(iter_tar_paths(None, manifest)) == [archive.resolve()] + assert "missing.tar" in caplog.text + + def test_no_dir_and_no_manifest_is_an_error(): with pytest.raises(ValueError, match="--tar-dir or --tar-manifest"): list(iter_tar_paths(None)) From 07a7320d9ddd0b29c1bdf25f632caa10d0012ae6 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 12:29:26 -0700 Subject: [PATCH 3/3] Skip inaccessible manifest entries and report their filesystem error Signed-off-by: Bill Hlavacek --- src/litkit/ingest/ingest.py | 22 ++++++++-------------- tests/test_ingest.py | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/src/litkit/ingest/ingest.py b/src/litkit/ingest/ingest.py index ec8889d..dc8fddf 100644 --- a/src/litkit/ingest/ingest.py +++ b/src/litkit/ingest/ingest.py @@ -40,7 +40,6 @@ from __future__ import annotations -import errno import io import logging import re @@ -389,15 +388,16 @@ def iter_tar_paths( def _resolve_token(tok: str, base: Path) -> Path | None: candidate = base / tok extensions = ("",) if _is_tar_path(candidate) else _TAR_EXTS + error_detail = "" for ext in extensions: archive = Path(f"{candidate}{ext}") try: if archive.is_file(): - return archive + return archive.resolve() except OSError as e: - # A longer suffix may exceed the filesystem's filename limit. - if e.errno != errno.ENAMETOOLONG: - raise + # Another suffix may be readable or short enough for this filesystem. + error_detail = f": {e}" + logger.warning("[manifest] skipping unresolved entry %r (base=%s)%s", tok, base, error_detail) return None if manifest is not None: @@ -409,15 +409,9 @@ def _resolve_token(tok: str, base: Path) -> Path | None: if not raw: continue p = _resolve_token(raw, base) - if p: - rp = p.resolve(strict=False) # normalize for de-duplication - if rp not in seen: - seen.add(rp) - yield rp # preserve manifest order - else: - logger.warning( - "[manifest] skipping unresolved entry %r (base=%s)", raw, base - ) + if p is not None and p not in seen: + seen.add(p) + yield p return diff --git a/tests/test_ingest.py b/tests/test_ingest.py index df681ea..aad567c 100644 --- a/tests/test_ingest.py +++ b/tests/test_ingest.py @@ -383,6 +383,24 @@ def check_path(path): assert "missing.tar" in caplog.text +def test_manifest_continues_after_inaccessible_entries_and_suffixes(tmp_path, monkeypatch, caplog): + archive = tmp_path / "baseline.2025.tgz" + archive.touch() + manifest = tmp_path / "m.manifest" + manifest.write_text("locked/shard.tar\nbaseline.2025\n") + is_file = Path.is_file + + def check_path(path): + if path.name in {"shard.tar", "baseline.2025.tar"}: + raise PermissionError(errno.EACCES, "Permission denied", str(path)) + return is_file(path) + + monkeypatch.setattr(Path, "is_file", check_path) + assert list(iter_tar_paths(None, manifest)) == [archive.resolve()] + assert "locked/shard.tar" in caplog.text + assert "Permission denied" in caplog.text + + def test_no_dir_and_no_manifest_is_an_error(): with pytest.raises(ValueError, match="--tar-dir or --tar-manifest"): list(iter_tar_paths(None))