From 8b19c48c8aa012eae9b3f19fb8d52ebb8261667f Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Fri, 4 Dec 2026 14:50:59 -0700 Subject: [PATCH 1/5] Restore vector releases on CPU and verify fetched passages on demand Signed-off-by: Bill Hlavacek --- README.md | 18 ++ src/litkit/cli.py | 4 +- src/litkit/embeddings/factory.py | 30 +- src/litkit/embeddings/hf_local.py | 9 +- src/litkit/embeddings/sbert_mpnet.py | 6 +- src/litkit/embeddings/specter2.py | 3 +- src/litkit/portable/articles.py | 94 ++++++ src/litkit/portable/cli.py | 48 ++- src/litkit/portable/restore.py | 360 +++++++++++++++++++++ src/litkit/portable/search.py | 167 ++++++++++ src/litkit/retrieval/cli_commands.py | 8 +- tests/integration/run_litkit_fake.py | 4 +- tests/integration/test_cpu_install.py | 20 ++ tests/integration/test_portable_restore.py | 174 ++++++++++ 14 files changed, 927 insertions(+), 18 deletions(-) create mode 100644 src/litkit/portable/articles.py create mode 100644 src/litkit/portable/restore.py create mode 100644 src/litkit/portable/search.py create mode 100644 tests/integration/test_portable_restore.py diff --git a/README.md b/README.md index 9fc5a4b..ae069ce 100644 --- a/README.md +++ b/README.md @@ -237,3 +237,21 @@ the fields below. Substitute the actual model revisions and build options. "paper_model":{"name":"allenai/specter2_base","revision":"PAPER_COMMIT"}, "chunk_model":{"name":"sentence-transformers/all-mpnet-base-v2","revision":"CHUNK_COMMIT"}} ``` + +Restore the normal searchable workspace on CPU with +`litkit rebuild-from-vectors RELEASE --sources ARCHIVE_DIR --workspace NEW_WORKSPACE`. +Use the relative archive names in the manifest. The JSON report lists changed, +new and missing sources, papers and chunk IDs. Matching text retains its +original vector. When all rows match, the FAISS files are copied unchanged +and no embedding model is loaded. Re-embedding changed or new inputs uses the +recorded model snapshots in the Hugging Face cache (`--hf-home`). + +To retrieve passages before downloading the bulk archives, run +`litkit search-vectors RELEASE "query" --mode semantic --limit 10 --cache DIR`. +LitKit searches the chunk index, fetches the matching PMC articles from Europe +PMC, and returns only passages matching their recorded text hashes. The JSON +output includes identifiers and titles for unavailable or changed passages. +Hybrid mode reranks the fetched candidates using lexical and semantic ranks. +Queries require the recorded chunk embedding model. Subsequent queries reuse +the cached XML. Pass the same `--cache DIR` to a rebuild to recover verified +articles that are missing from the bulk sources. diff --git a/src/litkit/cli.py b/src/litkit/cli.py index 8f1d21a..4dfbc13 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1844,7 +1844,7 @@ def main(): sys.stderr.write("[env] Python >= 3.10 required.\n") sys.exit(2) - if sys.argv[1:2] == ["export-vectors"]: + if sys.argv[1:2] and sys.argv[1] in {"export-vectors", "rebuild-from-vectors", "search-vectors"}: from litkit.portable.cli import main as portable_main portable_main(sys.argv[1:]) return @@ -1882,6 +1882,8 @@ def main(): description="An air-gapped HPC two-stage RAG pipeline for the PMC-OA corpus", epilog=( " litkit export-vectors DIR Export vectors and a text-free passage mapping\n" + " litkit rebuild-from-vectors Restore a workspace from a vector release\n" + " litkit search-vectors Fetch verified passages from a vector release\n" "Progressive retrieval subcommands (all support --json, --limit, --max-chars):\n" " litkit search-papers [query] Stage-1 / metadata search with filters\n" " litkit search-passages Hybrid, semantic, or exact lexical/FTS5 search\n" diff --git a/src/litkit/embeddings/factory.py b/src/litkit/embeddings/factory.py index 47c6c2b..1c587f4 100644 --- a/src/litkit/embeddings/factory.py +++ b/src/litkit/embeddings/factory.py @@ -2,6 +2,8 @@ from __future__ import annotations +import json +from pathlib import Path from typing import Any from .base import Embedder # protocol for type hints @@ -10,7 +12,24 @@ from .specter2 import SPECTER2_ID, PaperEmbedderSpecter2 -def make_paper_embedder() -> tuple[Embedder, dict[str, Any]]: +def _workspace_model(db_path, kind): + """A restored index must continue to use its release's embedding space.""" + from litkit.config.paths import WorkspacePaths + from litkit.db.handoff import readable_database + from litkit.db.schema import get_workspace_meta + + path = db_path if db_path is not None else WorkspacePaths.from_env_or_default().db_path + if not path.is_file(): + return {} + with readable_database(path) as db: + record = get_workspace_meta(db, "vector_release_models") + if not record: + return {} + model = json.loads(record).get(kind) + return {"model_id": model["name"], "revision": model["revision"]} if model else {} + + +def make_paper_embedder(*, db_path: Path | None = None) -> tuple[Embedder, dict[str, Any]]: """ Instantiate the paper-level embedder (SPECTER2). @@ -20,12 +39,12 @@ def make_paper_embedder() -> tuple[Embedder, dict[str, Any]]: embedder : object implementing Embedder.encode(list[str]) -> np.ndarray cfg : dict with metadata (model id, dim, device info if available) """ - e = PaperEmbedderSpecter2() # Paper embedder handles its own device selection + e = PaperEmbedderSpecter2(**_workspace_model(db_path, "papers")) dim = getattr(e, "dim", 768) cfg = { "type": "paper", "impl": "PaperEmbedderSpecter2", - "model_id": SPECTER2_ID, # informational only + "model_id": getattr(e, "model_id", SPECTER2_ID), "dim": int(dim), "device": getattr(e, "device", detect_device()), } @@ -37,6 +56,7 @@ def make_chunk_embedder( *, workers: int = 1, force_devices: bool = False, + db_path: Path | None = None, ) -> tuple[Embedder, dict[str, Any]]: """ Instantiate the chunk-level embedder (SBERT all-mpnet-base-v2). @@ -59,12 +79,12 @@ def make_chunk_embedder( spec = ",".join(devices) if isinstance(devices, list) else (devices or "auto") dev_list = resolve_embed_devices(spec, force=force_devices) - e = ChunkEmbedderSBERT(devices=dev_list, workers=workers) + e = ChunkEmbedderSBERT(devices=dev_list, workers=workers, **_workspace_model(db_path, "chunks")) dim = getattr(e, "dim", 768) cfg = { "type": "chunk", "impl": "ChunkEmbedderSBERT", - "model_id": SBERT_ID, + "model_id": getattr(e, "model_id", SBERT_ID), "dim": int(dim), "devices": list(dev_list), "workers": int(workers), diff --git a/src/litkit/embeddings/hf_local.py b/src/litkit/embeddings/hf_local.py index 7035267..0e0d78d 100644 --- a/src/litkit/embeddings/hf_local.py +++ b/src/litkit/embeddings/hf_local.py @@ -51,7 +51,7 @@ def repo_root(repo_id: str, hf_home: str | Path | None = None) -> Path: def local_snapshot_dir( - repo_id: str, branch: str = "main", hf_home: str | Path | None = None + repo_id: str, branch: str = "main", hf_home: str | Path | None = None, *, revision: str | None = None ) -> Path: """Resolve a usable local snapshot directory for `repo_id`. @@ -62,6 +62,13 @@ def local_snapshot_dir( """ root = repo_root(repo_id, hf_home=hf_home) snaps = root / "snapshots" + if revision is not None: + if revision in {"", ".", ".."} or Path(revision).name != revision: + raise ValueError(f"Invalid snapshot revision {revision!r}") + snapshot = snaps / revision + if not snapshot.is_dir(): + raise FileNotFoundError(f"Missing pinned snapshot {repo_id}@{revision} under {snaps}") + return snapshot ref = root / "refs" / branch if ref.exists(): commit = ref.read_text().strip() diff --git a/src/litkit/embeddings/sbert_mpnet.py b/src/litkit/embeddings/sbert_mpnet.py index 72cf7f2..64992af 100644 --- a/src/litkit/embeddings/sbert_mpnet.py +++ b/src/litkit/embeddings/sbert_mpnet.py @@ -40,7 +40,7 @@ class ChunkEmbedderSBERT: - If multiple CUDA devices requested, a background EmbeddingPool is used. """ - def __init__(self, devices: list[str] | None = None, workers: int = 1): + def __init__(self, devices: list[str] | None = None, workers: int = 1, *, model_id: str = SBERT_ID, revision: str | None = None): from sentence_transformers import SentenceTransformer # import lazily self.devices = list(devices) if devices else [detect_device()] @@ -50,8 +50,8 @@ def __init__(self, devices: list[str] | None = None, workers: int = 1): if self.workers > 0 and len(self.devices) > self.workers: self.devices = self.devices[: self.workers] - self.model_id = SBERT_ID - model_path = local_snapshot_dir(SBERT_ID) # must exist for offline runs + self.model_id = model_id + model_path = local_snapshot_dir(model_id, revision=revision) if revision else local_snapshot_dir(model_id) self.revision = model_path.name diff --git a/src/litkit/embeddings/specter2.py b/src/litkit/embeddings/specter2.py index 09c5052..ab70f78 100644 --- a/src/litkit/embeddings/specter2.py +++ b/src/litkit/embeddings/specter2.py @@ -32,6 +32,7 @@ def __init__( self, model_id: str = SPECTER2_ID, device: str | None = None, + *, revision: str | None = None, ) -> None: # torch is imported here, not at module level, so that importing litkit # (retrieval, build, the CLI) doesn't load torch until a model is built. @@ -39,7 +40,7 @@ def __init__( self.model_id = model_id self.device = device or detect_device() - local_path = local_snapshot_dir(self.model_id) + local_path = local_snapshot_dir(model_id, revision=revision) if revision else local_snapshot_dir(model_id) self.revision = local_path.name self.tok, self.model = load_auto_or_fallback(local_path, device=self.device) self.model.eval() diff --git a/src/litkit/portable/articles.py b/src/litkit/portable/articles.py new file mode 100644 index 0000000..c9400c1 --- /dev/null +++ b/src/litkit/portable/articles.py @@ -0,0 +1,94 @@ +"""Read and verify article inputs for local rebuilds and on-demand passage search.""" + +from __future__ import annotations + +import io +import os +import re +import tempfile +from pathlib import Path + +from litkit.build.helpers import article_passages, paper_input +from litkit.ingest.ingest import parse_xml_fileobj +from litkit.portable.release import digest + + +def passages(meta, settings): + return article_passages( + meta, + paper_input(meta), + settings["chunk_target_chars"], + settings["chunk_min_chars"], + settings["chunk_overlap"], + ) + + +def parser_options(settings): + return {key: settings[key] for key in ("include_tables", "max_table_chars")} + + +def license_allowed(meta, manifest): + return not manifest["licenses"] or (meta.get("license") or "unknown") in manifest["licenses"] + + +def settings_for_article(mapping, paper_id, sources): + rows = mapping.execute( + """SELECT DISTINCT f.source FROM files f JOIN articles a ON a.id=f.paper_id + WHERE a.id=? AND (a.current_file IS NULL OR a.current_file=f.original)""", + (paper_id,), + ) + options = [sources[name] for (name,) in rows] + if not options or any(config != options[0] for config in options[1:]): + raise ValueError(f"Cannot determine unique build settings for paper {paper_id}") + return options[0] + + +def model_settings(manifest, kind): + key = "paper_model" if kind == "papers" else "chunk_model" + models = [s["settings"][key] for s in manifest["sources"]] + if not models or any(m != models[0] for m in models[1:]): + raise ValueError(f"Cannot search or extend {kind} with mixed or missing model revisions") + return models[0] + + +def load_model(kind, mode, model): + """Instantiate only the exact local snapshot needed for a query or changed inputs.""" + from litkit.embeddings.sbert_mpnet import ChunkEmbedderSBERT + from litkit.embeddings.specter2 import PaperEmbedderSpecter2 + + options = dict(model_id=model["name"], revision=model["revision"]) + if kind == "papers" and mode == "specter2": + return PaperEmbedderSpecter2(device="cpu", **options) + return ChunkEmbedderSBERT(devices=["cpu"], **options) + + +def cache_path(root, manifest, pid): + return Path(root) / manifest["checksums"]["mapping.sqlite3"] / f"{pid}.xml" + + +def parse_cached(raw, metadata, settings): + meta = parse_xml_fileobj(io.BytesIO(raw), **parser_options(settings)) + pmcid = metadata.get("pmcid") + if not re.fullmatch(r"PMC[0-9]+", pmcid or ""): + raise ValueError("No fetchable PMCID") + if meta is None or meta.get("pmcid") != pmcid: + raise ValueError(f"Fetched article identity differs from {pmcid}") + return meta + + +def write_cache(path, raw): + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as handle: + temporary = Path(handle.name) + try: + temporary.write_bytes(raw) + os.replace(temporary, path) + finally: + temporary.unlink(missing_ok=True) + + +def verified_article(mapping, pid, meta, settings): + expected = dict(mapping.execute("SELECT ord,digest FROM passages WHERE paper_id=?", (pid,))) + actual = {ordinal: digest(text) for ordinal, text, *_ in passages(meta, settings)} + paper_hash = mapping.execute("SELECT digest FROM articles WHERE id=?", (pid,)).fetchone()[0] + return paper_hash == digest(paper_input(meta)) and expected == actual diff --git a/src/litkit/portable/cli.py b/src/litkit/portable/cli.py index 3350a63..2fc77a3 100644 --- a/src/litkit/portable/cli.py +++ b/src/litkit/portable/cli.py @@ -9,9 +9,55 @@ def main(argv): + parser = argparse.ArgumentParser(prog="litkit " + argv[0]) + if argv[0] != "export-vectors": + parser.add_argument("release", type=Path) + parser.add_argument( + "--cache", type=Path, default=Path.home() / ".cache" / "litkit" / "articles" + ) + parser.add_argument( + "--hf-home", type=Path, help="Hugging Face cache with the recorded model snapshot" + ) + if argv[0] == "rebuild-from-vectors": + parser.add_argument( + "--sources", + type=Path, + required=True, + help="Directory of downloaded source archives", + ) + parser.add_argument( + "--workspace", type=Path, required=True, help="New workspace to create" + ) + else: + parser.add_argument("query") + parser.add_argument("--mode", choices=("semantic", "hybrid"), default="semantic") + parser.add_argument("--limit", type=int, default=10) + args = parser.parse_args(argv[1:]) + try: + import os + + if args.hf_home: + os.environ["HF_HOME"] = str(args.hf_home.expanduser().resolve()) + else: + WorkspacePaths.from_env_or_default().setup_environment() + if argv[0] == "search-vectors": + from litkit.portable.search import search_vectors + + result = search_vectors( + args.release, args.query, cache=args.cache, limit=args.limit, mode=args.mode + ) + else: + from litkit.portable.restore import rebuild_from_vectors + + result = rebuild_from_vectors( + args.release, args.sources, args.workspace, cache=args.cache + ) + print(json.dumps(result, ensure_ascii=False)) + except (OSError, sqlite3.Error, ValueError, RuntimeError, KeyError) as error: + parser.exit(1, f"{parser.prog}: {error}\n") + return from litkit.portable.release import export_vectors - parser = argparse.ArgumentParser(prog="litkit " + argv[0]) parser.add_argument("output", type=Path, help="New directory for the release") parser.add_argument("--workspace", type=Path, help="Completed LitKit workspace") parser.add_argument( diff --git a/src/litkit/portable/restore.py b/src/litkit/portable/restore.py new file mode 100644 index 0000000..0fc3462 --- /dev/null +++ b/src/litkit/portable/restore.py @@ -0,0 +1,360 @@ +"""Reconstruct a searchable workspace from a portable release and local source archives.""" + +from __future__ import annotations + +import json +import shutil +import sqlite3 +from contextlib import closing +from pathlib import Path + +import faiss +import numpy as np + +from litkit.build.helpers import paper_input +from litkit.build.ingest_loop import iter_tar_articles +from litkit.config.paths import WorkspacePaths +from litkit.db.handoff import readable_database +from litkit.db.schema import init_db, set_stage1_mode, set_workspace_meta +from litkit.ingest.ingest import _is_tar_path +from litkit.portable import articles +from litkit.portable.record import SOURCE_SCHEMA, file_hash +from litkit.portable.release import digest, new_directory, read_manifest, remove_labels, safe_path + + +class Rebuild: + """Stage rows in SQLite before reconciling their FAISS labels. Memory scales by article.""" + + def __init__(self, db, mapping, manifest): + self.db = db + self.mapping = mapping + self.manifest = manifest + self.settings = {s["name"]: s["settings"] for s in manifest["sources"]} + self.next_paper = mapping.execute("SELECT COALESCE(MAX(id),0)+1 FROM articles").fetchone()[ + 0 + ] + self.next_chunk = mapping.execute("SELECT COALESCE(MAX(id),0)+1 FROM passages").fetchone()[ + 0 + ] + self.report = { + k: [] + for k in ( + "changed_sources", + "missing_sources", + "new_sources", + "changed_papers", + "missing_papers", + "new_papers", + "changed_chunks", + "missing_chunks", + "new_chunks", + "cached_papers", + ) + } + db.executescript( + """ + CREATE TEMP TABLE owners(pmid TEXT, pmcid TEXT, pid INTEGER PRIMARY KEY); + CREATE UNIQUE INDEX temp.owner_pmid ON owners(pmid) WHERE pmid IS NOT NULL; + CREATE UNIQUE INDEX temp.owner_pmcid ON owners(pmcid) WHERE pmcid IS NOT NULL; + CREATE TEMP TABLE picked(pid INTEGER PRIMARY KEY, priority INTEGER, name TEXT); + """ + ) + db.executemany( + "INSERT INTO owners VALUES(?,?,?)", + ( + (meta.get("pmid") or None, meta.get("pmcid") or None, pid) + for pid, meta in ( + (pid, json.loads(value)) + for pid, value in mapping.execute("SELECT id,metadata FROM articles") + ) + ), + ) + db.execute(SOURCE_SCHEMA) + + def resolve(self, name, member, meta): + """A citation ID follows a renamed member; a reused filename cannot steal another ID.""" + match = self.mapping.execute( + """SELECT a.id,a.current_file,f.original FROM files f JOIN articles a ON a.id=f.paper_id + WHERE source=? AND member=?""", + (name, member), + ).fetchone() + pmid, pmcid = meta.get("pmid") or None, meta.get("pmcid") or None + owners = self.db.execute( + "SELECT pid,pmid,pmcid FROM owners WHERE pmid=? OR pmcid=?", (pmid, pmcid) + ).fetchall() + if len(owners) > 1: + raise ValueError(f"Conflicting citation owners for {name}!/{member}") + owner = owners[0] if owners else None + if match and not owner: + candidate = self.db.execute( + "SELECT pid,pmid,pmcid FROM owners WHERE pid=?", (match[0],) + ).fetchone() + if not any( + a and b and a != b for a, b in zip((pmid, pmcid), candidate[1:], strict=True) + ): + owner = candidate + if owner: + if any(a and b and a != b for a, b in zip((pmid, pmcid), owner[1:], strict=True)): + raise ValueError(f"Inconsistent citation identifiers for {name}!/{member}") + pid = owner[0] + self.db.execute( + "UPDATE owners SET pmid=COALESCE(pmid,?), pmcid=COALESCE(pmcid,?) WHERE pid=?", + (pmid, pmcid, pid), + ) + else: + pid = self.next_paper + self.next_paper += 1 + self.db.execute("INSERT INTO owners VALUES(?,?,?)", (pmid, pmcid, pid)) + if match and match[0] == pid: + return pid, 3 if match[1] == match[2] else 2 if not match[1] else 0 + return pid, 1 + + def ingest(self, name, member, uri, size, mtime, meta, settings, *, cached_pid=None): + if cached_pid is None: + pid, priority = self.resolve(name, member, meta) + else: + pid, priority = cached_pid, 3 + self.db.execute("INSERT OR REPLACE INTO files VALUES(?,?,?,?)", (uri, size, mtime, pid)) + previous = self.db.execute("SELECT priority FROM picked WHERE pid=?", (pid,)).fetchone() + if priority == 0 or (previous and previous[0] > priority): + return + old = self.mapping.execute( + "SELECT doc_id,metadata,digest FROM articles WHERE id=?", (pid,) + ).fetchone() + # Legacy archives can have aliases and no current-member marker. Prefer a digest-verified edition. + if priority == 2 and old and articles.verified_article(self.mapping, pid, meta, settings): + priority = 3 + if previous and previous[0] == priority: + if old and articles.verified_article(self.mapping, pid, meta, settings): + return + raise ValueError(f"Ambiguous source editions for paper {pid}: {uri}") + self.db.execute("INSERT OR REPLACE INTO picked VALUES(?,?,?)", (pid, priority, name)) + if previous: + self.db.execute("DELETE FROM chunks WHERE paper_id=?", (pid,)) + self.db.execute("DELETE FROM papers WHERE id=?", (pid,)) + if not articles.license_allowed(meta, self.manifest): + return + prior = json.loads(old[1]) if old else {} + doc_id = old[0] if old else uri + if ( + not old + and self.mapping.execute("SELECT 1 FROM articles WHERE doc_id=?", (uri,)).fetchone() + ): + doc_id = f"portable:{pid}:{uri}" + paper_text = paper_input(meta) + metadata = { + k: meta.get(k) or prior.get(k) + for k in ("pmid", "pmcid", "doi", "authors", "journal", "year") + } + metadata.update( + {k: meta.get(k) for k in ("title", "abstract", "source_path", "license", "license_url")} + ) + references = meta.get("references") + metadata.update( + id=pid, + doc_id=doc_id, + build_member=uri, + embedding_text=paper_text, + references_json=( + json.dumps(references, ensure_ascii=False) if references is not None else None + ), + in_index=int( + bool( + old and old[2] == digest(paper_text) and self.manifest["stage1_mode"] != "none" + ) + ), + ) + cols = ",".join(metadata) + self.db.execute( + f"INSERT INTO papers({cols}) VALUES({','.join('?' for _ in metadata)})", + tuple(metadata.values()), + ) + expected = { + o: (i, h) + for i, o, h in self.mapping.execute( + "SELECT id,ord,digest FROM passages WHERE paper_id=?", (pid,) + ) + } + for ordinal, text, page, section, refs in articles.passages(meta, settings): + if ordinal in expected: + cid, original_hash = expected[ordinal] + else: + cid, original_hash = self.next_chunk, None + self.next_chunk += 1 + self.db.execute( + """INSERT INTO chunks(id,paper_id,ord,text,page,section,cited_refs,in_index) + VALUES(?,?,?,?,?,?,?,?)""", + ( + cid, + pid, + ordinal, + text, + page, + section, + json.dumps(refs) if refs else None, + int(original_hash == digest(text)), + ), + ) + + def read_sources(self, root): + records = {s["name"]: s for s in self.manifest["sources"]} + present = { + p.relative_to(root).as_posix() + for p in root.rglob("*") + if p.is_file() and _is_tar_path(p) + } + self.report["missing_sources"] = sorted(records.keys() - present) + if self.manifest["licenses"]: + present.intersection_update(records) + for name in sorted(present): + path = safe_path(root, name) + record = records.get(name) + if record is None: + configs = list(self.settings.values()) + if not configs or any(c != configs[0] for c in configs[1:]): + raise ValueError(f"Cannot infer build settings for new source {name}") + self.report["new_sources"].append(name) + config = configs[0] + else: + config = record["settings"] + checksum = file_hash(path) + if record and checksum != record["sha256"]: + self.report["changed_sources"].append(name) + size = path.stat().st_size + self.db.execute( + "INSERT INTO build_sources VALUES(?,?,?,?)", + (str(path), checksum, size, json.dumps(config, sort_keys=True)), + ) + for member, meta in iter_tar_articles( + path, parse_workers=1, **articles.parser_options(config) + ): + self.ingest( + name, + member.name, + f"tar://{path}!/{member.name}", + member.size, + member.mtime, + meta, + config, + ) + + def read_cache(self, cache, root): + for pid, value in self.mapping.execute("SELECT id,metadata FROM articles"): + if self.db.execute("SELECT 1 FROM picked WHERE pid=?", (pid,)).fetchone(): + continue + path = articles.cache_path(cache, self.manifest, pid) + if not path.is_file(): + continue + config = articles.settings_for_article(self.mapping, pid, self.settings) + meta = articles.parse_cached(path.read_bytes(), json.loads(value), config) + if not articles.verified_article( + self.mapping, pid, meta, config + ) or not articles.license_allowed(meta, self.manifest): + continue + name, member = self.mapping.execute( + """SELECT f.source,f.member FROM files f JOIN articles a ON a.id=f.paper_id + WHERE a.id=? ORDER BY (f.original=a.current_file) DESC,f.original LIMIT 1""", + (pid,), + ).fetchone() + uri = f"tar://{safe_path(root,name)}!/{member}" + self.ingest(name, member, uri, 0, 0, meta, config, cached_pid=pid) + self.report["cached_papers"].append(pid) + record = next(s for s in self.manifest["sources"] if s["name"] == name) + self.db.execute( + "INSERT OR IGNORE INTO build_sources VALUES(?,?,?,?)", + ( + str(safe_path(root, name)), + record["sha256"], + record["size"], + json.dumps(config, sort_keys=True), + ), + ) + + def finish(self, release, paths): + self.db.execute("DELETE FROM files WHERE paper_id NOT IN (SELECT id FROM papers)") + for table, original in (("papers", "articles"), ("chunks", "passages")): + # Compare sorted streams in SQLite; no corpus-sized Python dictionaries. + missing = self.report["missing_" + table] + missing.extend( + r[0] + for r in self.db.execute( + f"SELECT id FROM shipped.{original} EXCEPT SELECT id FROM {table}" + ) + ) + new = self.report["new_" + table] + new.extend( + r[0] + for r in self.db.execute( + f"SELECT id FROM {table} EXCEPT SELECT id FROM shipped.{original}" + ) + ) + changed = self.report["changed_" + table] + if table == "papers": + changed.extend( + pid + for pid, text, h in self.db.execute( + "SELECT p.id,p.embedding_text,a.digest FROM papers p JOIN shipped.articles a ON a.id=p.id" + ) + if digest(text) != h + ) + else: + changed.extend( + r[0] + for r in self.db.execute( + "SELECT c.id FROM chunks c JOIN shipped.passages v ON v.id=c.id WHERE c.in_index=0" + ) + ) + if table not in self.manifest["indices"]: + continue + source, target = release / f"{table}.faiss", paths.indices_dir / f"{table}.faiss" + if not (missing or changed or new): + shutil.copyfile(source, target) + continue + index = faiss.read_index(str(source)) + discard = missing + changed + remove_labels(index, discard) + if index.ntotal != self.manifest["indices"][table]["count"] - len(discard): + raise ValueError(f"Could not remove obsolete {table} vectors") + if changed or new: + model = articles.load_model( + table, + self.manifest["stage1_mode"], + articles.model_settings(self.manifest, table), + ) + field = "embedding_text" if table == "papers" else "text" + cursor = self.db.execute( + f"SELECT id,{field} FROM {table} WHERE in_index=0 ORDER BY id" + ) + while rows := cursor.fetchmany(64): + ids, texts = zip(*rows, strict=True) + vectors = np.ascontiguousarray(model.encode(list(texts)), dtype=np.float32) + if vectors.shape != (len(rows), index.d) or not np.isfinite(vectors).all(): + raise ValueError(f"Invalid {table} embedding shape or values") + faiss.normalize_L2(vectors) + index.add_with_ids(vectors, np.asarray(ids, dtype=np.int64)) + self.db.execute(f"UPDATE {table} SET in_index=1 WHERE in_index=0") + faiss.write_index(index, str(target)) + + +def rebuild_from_vectors(release, sources, workspace, *, cache=None): + release, root = Path(release).resolve(), Path(sources).resolve() + if not root.is_dir(): + raise FileNotFoundError(f"Source directory does not exist: {root}") + manifest = read_manifest(release) + mapping_path = release / "mapping.sqlite3" + with new_directory(workspace) as stage, readable_database(mapping_path) as mapping: + paths = WorkspacePaths.from_env_or_default(workspace_override=stage) + paths.ensure_directories(quiet=True) + with closing(init_db(paths.db_path)) as db: + db.execute("ATTACH DATABASE ? AS shipped", (str(mapping_path),)) + restore = Rebuild(db, mapping, manifest) + set_stage1_mode(db, manifest["stage1_mode"]) + if manifest["sources"]: + models = {k: articles.model_settings(manifest, k) for k in manifest["indices"]} + set_workspace_meta(db, "vector_release_models", json.dumps(models)) + restore.read_sources(root) + if cache is not None: + restore.read_cache(cache, root) + restore.finish(release, paths) + db.commit() + return restore.report diff --git a/src/litkit/portable/search.py b/src/litkit/portable/search.py new file mode 100644 index 0000000..6dcc5b5 --- /dev/null +++ b/src/litkit/portable/search.py @@ -0,0 +1,167 @@ +"""Fetch and verify only the articles selected by a vector query.""" + +from __future__ import annotations + +import json +import re +import time +from pathlib import Path +from urllib.error import URLError +from urllib.request import Request, urlopen + +from litkit.db.handoff import readable_database +from litkit.portable import articles +from litkit.portable.release import digest, read_manifest +from litkit.portable.record import file_hash +from litkit.retrieval.progressive import _score_exact_text, extract_exact_terms +from litkit.retrieval.search import faiss_search + + +def fetch_pmc(pmcid): + if not re.fullmatch(r"PMC[0-9]+", pmcid or ""): + raise ValueError("No fetchable PMCID") + url = f"https://www.ebi.ac.uk/europepmc/webservices/rest/{pmcid}/fullTextXML" + request = Request(url, headers={"User-Agent": "LitKit (https://github.com/lanl/litkit)"}) + with urlopen(request, timeout=30) as response: + return response.read() + + +def verified_manifest(release, cache): + """Reuse file verification across CLI calls while file identity and timestamps match.""" + manifest = read_manifest(release, verify=False) + record = Path(cache) / "releases" / (digest(str(release.resolve())) + ".json") + try: + prior = json.loads(record.read_text(encoding="utf-8")) + except (FileNotFoundError, ValueError): + prior = {} + checked = {} + for name, expected in manifest["checksums"].items(): + path = release / name + stat = path.stat() + identity = [ + expected, + stat.st_dev, + stat.st_ino, + stat.st_size, + stat.st_mtime_ns, + stat.st_ctime_ns, + ] + if prior.get(name) != identity and file_hash(path) != expected: + raise ValueError(f"Release checksum mismatch for {name}") + checked[name] = identity + if checked != prior: + articles.write_cache(record, json.dumps(checked).encode()) + return manifest + + +def search_vectors(release, query, *, cache, limit=10, mode="semantic", fetch=None): + if not query.strip() or limit < 1 or mode not in ("semantic", "hybrid"): + raise ValueError("Supply a query, positive limit and semantic or hybrid mode") + release = Path(release) + manifest = verified_manifest(release, cache) + count = manifest["indices"]["chunks"]["count"] + result = {"passages": [], "unavailable": []} + if not count: + return result + model = articles.load_model( + "chunks", manifest["stage1_mode"], articles.model_settings(manifest, "chunks") + ) + ids, scores, _ = faiss_search( + release / "chunks.faiss", + model.encode([query]), + min(count, limit * (3 if mode == "hybrid" else 1)), + ) + configs = {s["name"]: s["settings"] for s in manifest["sources"]} + by_paper = {} + with readable_database(release / "mapping.sqlite3") as mapping: + for rank, (cid, score) in enumerate(zip(ids, scores, strict=True)): + row = mapping.execute( + """SELECT p.paper_id,p.ord,p.digest,a.metadata FROM passages p + JOIN articles a ON a.id=p.paper_id WHERE p.id=?""", + (cid,), + ).fetchone() + if row is None: + raise ValueError(f"Unmapped chunk vector {cid}") + pid, ordinal, checksum, metadata = row + hits = by_paper.setdefault(pid, []) + hits.append((rank, cid, ordinal, checksum, score, metadata)) + available = [] + retry_after = 0.0 + for pid, hits in by_paper.items(): + metadata = json.loads(hits[0][-1]) + settings = articles.settings_for_article(mapping, pid, configs) + path = articles.cache_path(cache, manifest, pid) + try: + if path.is_file(): + raw = path.read_bytes() + else: + if fetch is None: + time.sleep(max(0, retry_after - time.monotonic())) + retry_after = time.monotonic() + 0.35 + raw = (fetch or fetch_pmc)(metadata.get("pmcid")) + meta = articles.parse_cached(raw, metadata, settings) + if not articles.license_allowed(meta, manifest): + raise ValueError("Article license differs from the selected release licenses") + if not path.exists(): + articles.write_cache(path, raw) + by_ord = { + o: (text, page, section) + for o, text, page, section, _ in articles.passages(meta, settings) + } + except (OSError, URLError, ValueError) as error: + result["unavailable"].append( + { + "paper_id": pid, + "pmcid": metadata.get("pmcid"), + "title": metadata.get("title"), + "reason": str(error), + } + ) + continue + for rank, cid, ordinal, expected, score, _ in hits: + passage = by_ord.get(ordinal) + if not passage or digest(passage[0]) != expected: + result["unavailable"].append( + { + "paper_id": pid, + "chunk_id": cid, + "ord": ordinal, + "pmcid": metadata.get("pmcid"), + "title": metadata.get("title"), + "reason": "Passage text hash differs from the release", + } + ) + continue + text, page, section = passage + available.append( + ( + rank, + dict( + paper_id=pid, + chunk_id=cid, + ord=ordinal, + text=text, + page=page, + section=section, + score=score, + **metadata, + ), + ) + ) + available.sort(key=lambda item: item[0]) + ranked = [hit for _, hit in available] + if mode == "hybrid": + terms = extract_exact_terms(query) + lexical = [ + (i, _score_exact_text(hit["text"], terms, title=hit.get("title") or "")) + for i, hit in enumerate(ranked) + ] + lexical.sort(key=lambda pair: pair[1], reverse=True) + for rank, hit in enumerate(ranked, start=1): + hit["score"] = 1 / (60 + rank) + for rank, (i, (matches, _)) in enumerate(lexical, start=1): + if matches: + ranked[i]["score"] += 1 / (60 + rank) + ranked.sort(key=lambda hit: hit["score"], reverse=True) + result["passages"] = ranked[:limit] + return result diff --git a/src/litkit/retrieval/cli_commands.py b/src/litkit/retrieval/cli_commands.py index 58ec453..a8d109d 100644 --- a/src/litkit/retrieval/cli_commands.py +++ b/src/litkit/retrieval/cli_commands.py @@ -250,10 +250,10 @@ def _run_search_papers(argv: list[str]) -> int: paper_embedder, _ = make_chunk_embedder( devices=args.embed_devices, workers=args.embed_workers, - force_devices=args.force_embed_devices, + force_devices=args.force_embed_devices, db_path=paths.db_path, ) else: - paper_embedder, _ = make_paper_embedder() + paper_embedder, _ = make_paper_embedder(db_path=paths.db_path) try: results = search_papers( @@ -390,7 +390,7 @@ def _run_search_passages(argv: list[str]) -> int: chunk_embedder, _ = make_chunk_embedder( devices=args.embed_devices, workers=args.embed_workers, - force_devices=args.force_embed_devices, + force_devices=args.force_embed_devices, db_path=paths.db_path, ) if stage1_mode != "none" and paths.paper_index_path.is_file(): paper_index_path = paths.paper_index_path @@ -398,7 +398,7 @@ def _run_search_passages(argv: list[str]) -> int: if stage1_mode == "mpnet": paper_embedder = chunk_embedder else: - paper_embedder, _ = make_paper_embedder() + paper_embedder, _ = make_paper_embedder(db_path=paths.db_path) try: results = search_passages( diff --git a/tests/integration/run_litkit_fake.py b/tests/integration/run_litkit_fake.py index d88ce48..2215208 100644 --- a/tests/integration/run_litkit_fake.py +++ b/tests/integration/run_litkit_fake.py @@ -18,13 +18,13 @@ DIM = int(os.environ.get("FAKE_EMBED_DIM", "32")) -def _make_paper_embedder(): +def _make_paper_embedder(*, db_path=None): if os.environ.get("FAKE_FORBID_PAPER_EMBEDDER") == "1": raise AssertionError("make_paper_embedder() was called when forbidden") return FakeEmbedder(DIM), {"type": "paper", "impl": "fake", "dim": DIM} -def _make_chunk_embedder(devices="auto", *, workers=1, force_devices=False): +def _make_chunk_embedder(devices="auto", *, workers=1, force_devices=False, db_path=None): if os.environ.get("FAKE_FORBID_CHUNK_EMBEDDER") == "1": raise AssertionError("make_chunk_embedder() was called when forbidden") return FakeEmbedder(DIM), {"type": "chunk", "impl": "fake", "dim": DIM} diff --git a/tests/integration/test_cpu_install.py b/tests/integration/test_cpu_install.py index 9bd82a4..4f4b892 100644 --- a/tests/integration/test_cpu_install.py +++ b/tests/integration/test_cpu_install.py @@ -104,3 +104,23 @@ def run(*args): assert b"[faiss] chunks: FLAT" in build.stderr output = run("--no-llm", "lunar rock basalt").stdout.decode("utf-8") assert "PMC101" in output and passage in output + + # Reopen the exported vectors on CPU with a new workspace and a relocated corpus. + # Moving the model refs afterwards proves normal search uses the released revisions. + release, restored = tmp_path / "release", tmp_path / "receiver" / "workspace" + original_queries = [ + run("search-passages", q, "--mode", "semantic", "--json").stdout + for q in ("lunar rock", "basalt") + ] + run("export-vectors", str(release)) + moved = tmp_path / "receiver" / "archives" + moved.parent.mkdir() + corpus.rename(moved) + run("rebuild-from-vectors", str(release), "--sources", str(moved), "--workspace", str(restored)) + for repo in (tmp_path / "hf" / "hub").iterdir(): + if (repo / "snapshots").is_dir(): + (repo / "refs").mkdir(exist_ok=True) + (repo / "refs" / "main").write_text("unavailable-revision") + for q, original in zip(("lunar rock", "basalt"), original_queries, strict=True): + assert run("search-passages", q, "--mode", "semantic", "--json", + "--workspace", str(restored)).stdout == original diff --git a/tests/integration/test_portable_restore.py b/tests/integration/test_portable_restore.py new file mode 100644 index 0000000..348fece --- /dev/null +++ b/tests/integration/test_portable_restore.py @@ -0,0 +1,174 @@ +"""CPU rebuild, source drift and on-demand retrieval from a portable release.""" + +import json +import sqlite3 +from contextlib import closing + +import faiss +import pytest + +from conftest import write_tar +from litkit.portable.record import file_hash +from litkit.portable.release import export_vectors +from test_portable_vectors import MODELS, licensed_article, portable_source + + +def test_cpu_restore_preserves_queried_passages_and_vector_files( + tmp_path, portable_source, monkeypatch +): + from shutil import copytree + from conftest import FakeEmbedder + from litkit.portable import articles + from litkit.portable.restore import rebuild_from_vectors + from litkit.retrieval.progressive import search_passages + + workspace, sources = portable_source + release, restored = tmp_path / "release", tmp_path / "remote" / "workspace" + export_vectors(workspace, release, settings=MODELS) + relocated = copytree(sources, tmp_path / "remote" / "archives") + monkeypatch.setattr( + articles, "load_model", lambda *_: pytest.fail("a matching rebuild loaded a model") + ) + report = rebuild_from_vectors(release, relocated, restored) + assert not any(report.values()) + for kind in ("papers", "chunks"): + assert file_hash(restored / "indices" / f"{kind}.faiss") == file_hash( + workspace / "indices" / f"{kind}.faiss" + ) + + def queries(ws): + embedder = FakeEmbedder() + return [ + search_passages( + q, + mode=mode, + db_path=ws / "sqlite/litkit.sqlite3", + paper_index_path=ws / "indices/papers.faiss", + chunk_index_path=ws / "indices/chunks.faiss", + paper_embedder=embedder, + chunk_embedder=embedder, + ) + for q in ("black coffee", "navigation") + for mode in ("exact", "semantic", "hybrid") + ] + + assert queries(restored) == queries(workspace) + + +def test_restore_selectively_reembeds_and_removes_withdrawn_ids( + tmp_path, portable_source, monkeypatch +): + from conftest import FakeEmbedder + from litkit.portable import articles + from litkit.portable.restore import rebuild_from_vectors + + workspace, sources = portable_source + release = tmp_path / "release" + export_vectors(workspace, release, settings=MODELS) + changed_body = "The revised passage concerns roasting beans." + write_tar( + sources / "papers.tar", + { + "renamed.xml": licensed_article("PMC31", "Black coffee", "by", changed_body), + "two.xml": licensed_article( + "PMC99", "Mayflies", "by-nc", "The new paper concerns mayflies." + ), + }, + ) + models = {k: FakeEmbedder() for k in ("papers", "chunks")} + monkeypatch.setattr(articles, "load_model", lambda k, mode, model: models[k]) + restored = tmp_path / "restored" + report = rebuild_from_vectors(release, sources, restored) + assert report["changed_sources"] == ["papers.tar"] + assert len(report["changed_chunks"]) == 1 and len(report["new_chunks"]) == 2 + assert len(report["missing_papers"]) == len(report["new_papers"]) == 1 + assert len(report["missing_chunks"]) == 2 and not report["changed_papers"] + inputs = [t for batch in models["chunks"].calls for t in batch] + assert ( + changed_body in inputs + and len(inputs) == 3 + and all("Private abstract about Black coffee" not in t for t in inputs) + ) + assert len(models["papers"].calls) == len(models["papers"].calls[0]) == 1 + with closing(sqlite3.connect(restored / "sqlite/litkit.sqlite3")) as db: + for table in ("papers", "chunks"): + idx = faiss.read_index(str(restored / f"indices/{table}.faiss")) + assert sorted(faiss.vector_to_array(idx.id_map)) == [ + r[0] for r in db.execute(f"SELECT id FROM {table} ORDER BY id") + ] + assert {r[0] for r in db.execute("SELECT pmcid FROM papers")} == {"PMC31", "PMC99"} + + +@pytest.mark.parametrize("mode", ["semantic", "hybrid"]) +def test_fetched_passages_are_verified_cached_and_reused_in_full_rebuild( + tmp_path, portable_source, monkeypatch, mode +): + from conftest import FakeEmbedder + from litkit.portable import articles + from litkit.portable.restore import rebuild_from_vectors + from litkit.portable.search import search_vectors + + workspace, sources = portable_source + release, cache = tmp_path / "release", tmp_path / "cache" + export_vectors(workspace, release, licenses=["CC-BY-4.0"], settings=MODELS) + monkeypatch.setattr(articles, "load_model", lambda *_: FakeEmbedder()) + calls = [] + + def fetch(pmcid): + calls.append(pmcid) + return licensed_article( + "PMC31", "Black coffee", "by", "Private passage espresso. " * 12 + ).encode() + + result = search_vectors(release, "espresso", mode=mode, limit=5, cache=cache, fetch=fetch) + assert calls == ["PMC31"] and len(result["passages"]) == 2 and not result["unavailable"] + assert ( + search_vectors(release, "espresso", mode=mode, limit=5, cache=cache, fetch=fetch) == result + ) + assert calls == ["PMC31"] + empty = tmp_path / "missing" + empty.mkdir() + restored = tmp_path / "restored" + monkeypatch.setattr( + articles, "load_model", lambda *_: pytest.fail("a verified cached article loaded a model") + ) + report = rebuild_from_vectors(release, empty, restored, cache=cache) + assert ( + report["missing_sources"] == ["papers.tar"] + and len(report["cached_papers"]) == 1 + and not report["missing_papers"] + ) + assert file_hash(restored / "indices/chunks.faiss") == file_hash(release / "chunks.faiss") + + +def test_on_demand_never_returns_drifted_text_or_excluded_license( + tmp_path, portable_source, monkeypatch +): + from conftest import FakeEmbedder + from litkit.portable import articles + from litkit.portable.search import search_vectors + + workspace, _ = portable_source + release = tmp_path / "release" + export_vectors(workspace, release, licenses=["CC-BY-4.0"], settings=MODELS) + monkeypatch.setattr(articles, "load_model", lambda *_: FakeEmbedder()) + for code in ("by", "by-nc"): + response = licensed_article("PMC31", "Black coffee", code, "Replacement body.") + result = search_vectors( + release, "coffee", limit=5, cache=tmp_path / code, fetch=lambda _: response.encode() + ) + assert all("Replacement" not in hit["text"] for hit in result["passages"]) + assert result["unavailable"] and len(result["passages"]) == (1 if code == "by" else 0) + + +def test_restore_refuses_corrupt_release_without_publishing_workspace(tmp_path, portable_source): + from litkit.portable.restore import rebuild_from_vectors + + workspace, sources = portable_source + release, output = tmp_path / "release", tmp_path / "output" + export_vectors(workspace, release, settings=MODELS) + with (release / "chunks.faiss").open("ab") as changed: + changed.write(b"changed") + with pytest.raises(ValueError, match="checksum"): + rebuild_from_vectors(release, sources, output) + assert not output.exists() From 6f979b78c612c4332c74dfb46311399cf470b341 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Fri, 4 Dec 2026 15:02:18 -0700 Subject: [PATCH 2/5] Recover verified aliases and PMID abstracts with current attribution Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 1 + README.md | 3 +- src/litkit/portable/articles.py | 40 ++++- src/litkit/portable/restore.py | 80 +++++++--- src/litkit/portable/search.py | 68 ++++++--- tests/integration/test_portable_restore.py | 166 ++++++++++++++++++++- 6 files changed, 306 insertions(+), 52 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 787f650..30c212c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ internal versions are summarized under 0.3.33. ## [Unreleased] ### Added +- Restore released FAISS files on CPU with verified passage IDs, or fetch matching PMC full text and PubMed abstracts on demand. (#65) - `litkit export-vectors` writes FAISS indexes, text hashes, source checksums, model revisions and per-paper attribution. Use `--license` to select licenses. (#65) - Paper and passage results report publication type and retraction status. Search with repeatable `--type` and `--exclude-type` filters. (#58) diff --git a/README.md b/README.md index 09b2d31..67d6f81 100644 --- a/README.md +++ b/README.md @@ -263,8 +263,7 @@ recorded model snapshots in the Hugging Face cache (`--hf-home`). To retrieve passages before downloading the bulk archives, run `litkit search-vectors RELEASE "query" --mode semantic --limit 10 --cache DIR`. -LitKit searches the chunk index, fetches the matching PMC articles from Europe -PMC, and returns only passages matching their recorded text hashes. The JSON +LitKit searches the chunk index, fetches matching full text from Europe PMC or the abstract record by PMID from PubMed, and returns only passages matching their recorded text hashes. The JSON output includes identifiers and titles for unavailable or changed passages. Hybrid mode reranks the fetched candidates using lexical and semantic ranks. Queries require the recorded chunk embedding model. Subsequent queries reuse diff --git a/src/litkit/portable/articles.py b/src/litkit/portable/articles.py index c9400c1..a6a92d8 100644 --- a/src/litkit/portable/articles.py +++ b/src/litkit/portable/articles.py @@ -4,12 +4,14 @@ import io import os -import re import tempfile from pathlib import Path +from lxml import etree + from litkit.build.helpers import article_passages, paper_input -from litkit.ingest.ingest import parse_xml_fileobj +from litkit.ingest.ingest import _parse_tree +from litkit.ingest.publication_types import publication_fields, publication_source from litkit.portable.release import digest @@ -67,15 +69,37 @@ def cache_path(root, manifest, pid): def parse_cached(raw, metadata, settings): - meta = parse_xml_fileobj(io.BytesIO(raw), **parser_options(settings)) - pmcid = metadata.get("pmcid") - if not re.fullmatch(r"PMC[0-9]+", pmcid or ""): - raise ValueError("No fetchable PMCID") - if meta is None or meta.get("pmcid") != pmcid: - raise ValueError(f"Fetched article identity differs from {pmcid}") + parser = etree.XMLParser( + resolve_entities=False, load_dtd=False, no_network=True, huge_tree=True + ) + try: + tree = etree.parse(io.BytesIO(raw), parser) + except (ValueError, etree.XMLSyntaxError) as error: + raise ValueError("Incomplete or invalid article XML") from error + meta = _parse_tree(tree, "", **parser_options(settings)) + if meta is None: + raise ValueError("Missing article record") + identifiers = [(metadata.get(k), meta.get(k)) for k in ("pmcid", "pmid")] + if not any(a and a == b for a, b in identifiers) or any( + a and b and a != b for a, b in identifiers + ): + raise ValueError("Fetched article identifiers differ from the release") return meta +def status_fields(meta, content_sha, original_member, released): + """Carry a sidecar's status only when the exact publisher member can be verified.""" + fingerprint = released.get("publication_source") + if ( + original_member + and fingerprint + and publication_source(original_member, content_sha).hex() == fingerprint + ): + return {k: released.get(k) for k in ("article_type", "publication_types", "retracted")} + raw_type, types, retracted = publication_fields(meta, None) + return dict(article_type=raw_type, publication_types=types, retracted=retracted) + + def write_cache(path, raw): path.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as handle: diff --git a/src/litkit/portable/restore.py b/src/litkit/portable/restore.py index 0fc3462..f2b0fed 100644 --- a/src/litkit/portable/restore.py +++ b/src/litkit/portable/restore.py @@ -2,9 +2,9 @@ from __future__ import annotations +import hashlib import json import shutil -import sqlite3 from contextlib import closing from pathlib import Path @@ -16,9 +16,12 @@ from litkit.config.paths import WorkspacePaths from litkit.db.handoff import readable_database from litkit.db.schema import init_db, set_stage1_mode, set_workspace_meta +from litkit.index.introspection import kind_and_core +from litkit.index.io import faiss_load, write_index from litkit.ingest.ingest import _is_tar_path +from litkit.ingest.publication_types import publication_source from litkit.portable import articles -from litkit.portable.record import SOURCE_SCHEMA, file_hash +from litkit.portable.record import SOURCE_SCHEMA, archive_checksum, archive_identity, file_hash from litkit.portable.release import digest, new_directory, read_manifest, remove_labels, safe_path @@ -49,8 +52,10 @@ def __init__(self, db, mapping, manifest): "missing_chunks", "new_chunks", "cached_papers", + "invalid_cached_papers", ) } + db.execute("PRAGMA temp_store=FILE") db.executescript( """ CREATE TEMP TABLE owners(pmid TEXT, pmcid TEXT, pid INTEGER PRIMARY KEY); @@ -106,24 +111,29 @@ def resolve(self, name, member, meta): self.next_paper += 1 self.db.execute("INSERT INTO owners VALUES(?,?,?)", (pmid, pmcid, pid)) if match and match[0] == pid: - return pid, 3 if match[1] == match[2] else 2 if not match[1] else 0 + return pid, 4 if match[1] == match[2] else 2 if not match[1] else 0 return pid, 1 - def ingest(self, name, member, uri, size, mtime, meta, settings, *, cached_pid=None): + def ingest( + self, name, member, uri, size, mtime, meta, settings, content_sha, *, cached_pid=None + ): if cached_pid is None: pid, priority = self.resolve(name, member, meta) else: - pid, priority = cached_pid, 3 + pid, priority = cached_pid, 4 self.db.execute("INSERT OR REPLACE INTO files VALUES(?,?,?,?)", (uri, size, mtime, pid)) previous = self.db.execute("SELECT priority FROM picked WHERE pid=?", (pid,)).fetchone() - if priority == 0 or (previous and previous[0] > priority): - return old = self.mapping.execute( - "SELECT doc_id,metadata,digest FROM articles WHERE id=?", (pid,) + "SELECT doc_id,metadata,digest,current_file FROM articles WHERE id=?", (pid,) ).fetchone() # Legacy archives can have aliases and no current-member marker. Prefer a digest-verified edition. - if priority == 2 and old and articles.verified_article(self.mapping, pid, meta, settings): - priority = 3 + if priority in (0, 2) and old: + if articles.verified_article(self.mapping, pid, meta, settings): + priority = 3 + elif priority == 0: + return + if previous and previous[0] > priority: + return if previous and previous[0] == priority: if old and articles.verified_article(self.mapping, pid, meta, settings): return @@ -164,6 +174,8 @@ def ingest(self, name, member, uri, size, mtime, meta, settings, *, cached_pid=N ) ), ) + metadata.update(articles.status_fields(meta, content_sha, old[3] if old else None, prior)) + metadata["publication_source"] = publication_source(uri, content_sha) cols = ",".join(metadata) self.db.execute( f"INSERT INTO papers({cols}) VALUES({','.join('?' for _ in metadata)})", @@ -217,10 +229,10 @@ def read_sources(self, root): config = configs[0] else: config = record["settings"] - checksum = file_hash(path) + identity = archive_identity(path) + checksum, size = archive_checksum(path, expected=identity) if record and checksum != record["sha256"]: self.report["changed_sources"].append(name) - size = path.stat().st_size self.db.execute( "INSERT INTO build_sources VALUES(?,?,?,?)", (str(path), checksum, size, json.dumps(config, sort_keys=True)), @@ -236,17 +248,32 @@ def read_sources(self, root): member.mtime, meta, config, + member.content_sha256, ) + if archive_identity(path) != identity: + raise ValueError(f"Source changed while rebuilding {name}") def read_cache(self, cache, root): - for pid, value in self.mapping.execute("SELECT id,metadata FROM articles"): - if self.db.execute("SELECT 1 FROM picked WHERE pid=?", (pid,)).fetchone(): + folder = articles.cache_path(cache, self.manifest, 0).parent + for path in folder.glob("*.xml"): + if not path.stem.isascii() or not path.stem.isdigit() or len(path.stem) > 18: + continue + pid = int(path.stem) + row = self.mapping.execute( + "SELECT metadata FROM articles WHERE id=?", (pid,) + ).fetchone() + if row is None: continue - path = articles.cache_path(cache, self.manifest, pid) - if not path.is_file(): + value = row[0] + if self.db.execute("SELECT 1 FROM picked WHERE pid=?", (pid,)).fetchone(): continue config = articles.settings_for_article(self.mapping, pid, self.settings) - meta = articles.parse_cached(path.read_bytes(), json.loads(value), config) + try: + raw = path.read_bytes() + meta = articles.parse_cached(raw, json.loads(value), config) + except (ValueError, OSError): + self.report["invalid_cached_papers"].append(pid) + continue if not articles.verified_article( self.mapping, pid, meta, config ) or not articles.license_allowed(meta, self.manifest): @@ -257,7 +284,9 @@ def read_cache(self, cache, root): (pid,), ).fetchone() uri = f"tar://{safe_path(root,name)}!/{member}" - self.ingest(name, member, uri, 0, 0, meta, config, cached_pid=pid) + self.ingest( + name, member, uri, 0, 0, meta, config, hashlib.sha256(raw).digest(), cached_pid=pid + ) self.report["cached_papers"].append(pid) record = next(s for s in self.manifest["sources"] if s["name"] == name) self.db.execute( @@ -307,10 +336,18 @@ def finish(self, release, paths): if table not in self.manifest["indices"]: continue source, target = release / f"{table}.faiss", paths.indices_dir / f"{table}.faiss" + shutil.copyfile(source, target) + if file_hash(target) != self.manifest["checksums"][source.name]: + raise ValueError(f"Release checksum mismatch for {source.name}") + index = faiss_load(target) + actual = {"kind": kind_and_core(index)[0], "dimension": index.d, "count": index.ntotal} + if actual != self.manifest["indices"][table] or not isinstance( + index, faiss.IndexIDMap2 + ): + raise ValueError(f"Release index metadata disagrees with {source.name}") if not (missing or changed or new): - shutil.copyfile(source, target) + del index continue - index = faiss.read_index(str(source)) discard = missing + changed remove_labels(index, discard) if index.ntotal != self.manifest["indices"][table]["count"] - len(discard): @@ -333,7 +370,8 @@ def finish(self, release, paths): faiss.normalize_L2(vectors) index.add_with_ids(vectors, np.asarray(ids, dtype=np.int64)) self.db.execute(f"UPDATE {table} SET in_index=1 WHERE in_index=0") - faiss.write_index(index, str(target)) + write_index(index, target) + del index def rebuild_from_vectors(release, sources, workspace, *, cache=None): diff --git a/src/litkit/portable/search.py b/src/litkit/portable/search.py index 6dcc5b5..a933d33 100644 --- a/src/litkit/portable/search.py +++ b/src/litkit/portable/search.py @@ -2,6 +2,7 @@ from __future__ import annotations +import hashlib import json import re import time @@ -11,16 +12,19 @@ from litkit.db.handoff import readable_database from litkit.portable import articles -from litkit.portable.release import digest, read_manifest from litkit.portable.record import file_hash +from litkit.portable.release import digest, read_manifest from litkit.retrieval.progressive import _score_exact_text, extract_exact_terms from litkit.retrieval.search import faiss_search -def fetch_pmc(pmcid): - if not re.fullmatch(r"PMC[0-9]+", pmcid or ""): - raise ValueError("No fetchable PMCID") - url = f"https://www.ebi.ac.uk/europepmc/webservices/rest/{pmcid}/fullTextXML" +def fetch_article(identifier): + if re.fullmatch(r"PMC[0-9]+", identifier): + url = f"https://www.ebi.ac.uk/europepmc/webservices/rest/{identifier}/fullTextXML" + elif re.fullmatch(r"[0-9]+", identifier): + url = f"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id={identifier}&retmode=xml" + else: + raise ValueError("No fetchable PMCID or PMID") request = Request(url, headers={"User-Agent": "LitKit (https://github.com/lanl/litkit)"}) with urlopen(request, timeout=30) as response: return response.read() @@ -34,6 +38,8 @@ def verified_manifest(release, cache): prior = json.loads(record.read_text(encoding="utf-8")) except (FileNotFoundError, ValueError): prior = {} + if not isinstance(prior, dict): + prior = {} checked = {} for name, expected in manifest["checksums"].items(): path = release / name @@ -76,15 +82,15 @@ def search_vectors(release, query, *, cache, limit=10, mode="semantic", fetch=No with readable_database(release / "mapping.sqlite3") as mapping: for rank, (cid, score) in enumerate(zip(ids, scores, strict=True)): row = mapping.execute( - """SELECT p.paper_id,p.ord,p.digest,a.metadata FROM passages p + """SELECT p.paper_id,p.ord,p.digest,a.current_file,a.metadata FROM passages p JOIN articles a ON a.id=p.paper_id WHERE p.id=?""", (cid,), ).fetchone() if row is None: raise ValueError(f"Unmapped chunk vector {cid}") - pid, ordinal, checksum, metadata = row + pid, ordinal, checksum, member, metadata = row hits = by_paper.setdefault(pid, []) - hits.append((rank, cid, ordinal, checksum, score, metadata)) + hits.append((rank, cid, ordinal, checksum, score, member, metadata)) available = [] retry_after = 0.0 for pid, hits in by_paper.items(): @@ -92,18 +98,42 @@ def search_vectors(release, query, *, cache, limit=10, mode="semantic", fetch=No settings = articles.settings_for_article(mapping, pid, configs) path = articles.cache_path(cache, manifest, pid) try: - if path.is_file(): + try: raw = path.read_bytes() - else: - if fetch is None: - time.sleep(max(0, retry_after - time.monotonic())) - retry_after = time.monotonic() + 0.35 - raw = (fetch or fetch_pmc)(metadata.get("pmcid")) - meta = articles.parse_cached(raw, metadata, settings) + meta = articles.parse_cached(raw, metadata, settings) + except (FileNotFoundError, ValueError): + identifiers = [metadata.get(k) for k in ("pmcid", "pmid")] + # For a release built from a PubMed record, fetch the matching abstract first. + if metadata.get("article_type") is None and metadata.get("publication_types"): + identifiers.reverse() + ids_to_fetch = [ + i for i in identifiers if re.fullmatch(r"(?:PMC)?[0-9]+", i or "") + ] + if not ids_to_fetch: + raise ValueError("No fetchable PMCID or PMID") from None + for index, identifier in enumerate(ids_to_fetch): + if fetch is None: + time.sleep(max(0, retry_after - time.monotonic())) + retry_after = time.monotonic() + 0.35 + try: + raw = (fetch or fetch_article)(identifier) + meta = articles.parse_cached(raw, metadata, settings) + except (OSError, ValueError): + if index == len(ids_to_fetch) - 1: + raise + continue + break + if articles.license_allowed(meta, manifest): + articles.write_cache(path, raw) if not articles.license_allowed(meta, manifest): raise ValueError("Article license differs from the selected release licenses") - if not path.exists(): - articles.write_cache(path, raw) + metadata.update( + articles.status_fields( + meta, hashlib.sha256(raw).digest(), hits[0][-2], metadata + ) + ) + metadata.pop("publication_source", None) + metadata.update(license=meta.get("license"), license_url=meta.get("license_url")) by_ord = { o: (text, page, section) for o, text, page, section, _ in articles.passages(meta, settings) @@ -113,12 +143,13 @@ def search_vectors(release, query, *, cache, limit=10, mode="semantic", fetch=No { "paper_id": pid, "pmcid": metadata.get("pmcid"), + "pmid": metadata.get("pmid"), "title": metadata.get("title"), "reason": str(error), } ) continue - for rank, cid, ordinal, expected, score, _ in hits: + for rank, cid, ordinal, expected, score, _, _ in hits: passage = by_ord.get(ordinal) if not passage or digest(passage[0]) != expected: result["unavailable"].append( @@ -127,6 +158,7 @@ def search_vectors(release, query, *, cache, limit=10, mode="semantic", fetch=No "chunk_id": cid, "ord": ordinal, "pmcid": metadata.get("pmcid"), + "pmid": metadata.get("pmid"), "title": metadata.get("title"), "reason": "Passage text hash differs from the release", } diff --git a/tests/integration/test_portable_restore.py b/tests/integration/test_portable_restore.py index 348fece..72ab699 100644 --- a/tests/integration/test_portable_restore.py +++ b/tests/integration/test_portable_restore.py @@ -1,22 +1,25 @@ """CPU rebuild, source drift and on-demand retrieval from a portable release.""" -import json import sqlite3 from contextlib import closing import faiss import pytest +import test_portable_vectors +from test_portable_vectors import MODELS, licensed_article from conftest import write_tar from litkit.portable.record import file_hash from litkit.portable.release import export_vectors -from test_portable_vectors import MODELS, licensed_article, portable_source + +portable_source = test_portable_vectors.portable_source def test_cpu_restore_preserves_queried_passages_and_vector_files( tmp_path, portable_source, monkeypatch ): from shutil import copytree + from conftest import FakeEmbedder from litkit.portable import articles from litkit.portable.restore import rebuild_from_vectors @@ -155,7 +158,7 @@ def test_on_demand_never_returns_drifted_text_or_excluded_license( for code in ("by", "by-nc"): response = licensed_article("PMC31", "Black coffee", code, "Replacement body.") result = search_vectors( - release, "coffee", limit=5, cache=tmp_path / code, fetch=lambda _: response.encode() + release, "coffee", limit=5, cache=tmp_path / code, fetch=lambda _, xml=response: xml.encode() ) assert all("Replacement" not in hit["text"] for hit in result["passages"]) assert result["unavailable"] and len(result["passages"]) == (1 if code == "by" else 0) @@ -172,3 +175,160 @@ def test_restore_refuses_corrupt_release_without_publishing_workspace(tmp_path, with pytest.raises(ValueError, match="checksum"): rebuild_from_vectors(release, sources, output) assert not output.exists() + + +def test_corrupt_cached_xml_is_recovered_online_and_reported_offline( + tmp_path, portable_source, monkeypatch +): + from conftest import FakeEmbedder + from litkit.portable import articles + from litkit.portable.restore import rebuild_from_vectors + from litkit.portable.search import search_vectors + + workspace, _ = portable_source + release, cache = tmp_path / "release", tmp_path / "cache" + export_vectors(workspace, release, settings=MODELS) + monkeypatch.setattr(articles, "load_model", lambda *_: FakeEmbedder()) + records = { + "PMC31": licensed_article("PMC31", "Black coffee", "by", "Private passage espresso. " * 12), + "PMC42": licensed_article( + "PMC42", "Road maps", "by-nc", "Private passage navigation. " * 12 + ), + } + calls = [] + + def fetch(identifier): + calls.append(identifier) + return records[identifier].encode() + + options = dict(cache=cache, limit=10, fetch=fetch) + original = search_vectors(release, "navigation", **options) + bad = next(cache.glob("*/*.xml")) + bad.write_bytes(b" 20 + + +def test_restore_uses_verified_surviving_alias(tmp_path, monkeypatch): + from test_build_and_query import _ok, litkit + + from litkit.portable import articles + from litkit.portable.restore import rebuild_from_vectors + + sources, workspace = tmp_path / "sources", tmp_path / "ws" + sources.mkdir() + record = licensed_article("PMC31", "Same", "by", "Identical surviving passage.") + for name in ("early", "latest"): + write_tar(sources / (name + ".tar"), {name + ".xml": record}) + _ok( + litkit( + workspace, + "--build-only", + "--faiss-writer", + "--tar-dir", + str(sources), + "--chunks-index", + "flat", + ) + ) + release = tmp_path / "release" + export_vectors(workspace, release, settings=MODELS) + (sources / "latest.tar").unlink() + monkeypatch.setattr( + articles, "load_model", lambda *_: pytest.fail("verified alias was embedded") + ) + report = rebuild_from_vectors(release, sources, tmp_path / "restored") + assert report["missing_sources"] == ["latest.tar"] and not report["missing_papers"] + + +def test_pmids_without_pmc_full_text_can_be_fetched_and_cached(tmp_path, monkeypatch): + from test_build_and_query import _ok, litkit + + from conftest import FakeEmbedder, pubmed_xml + from litkit.portable import articles + from litkit.portable.restore import rebuild_from_vectors + from litkit.portable.search import search_vectors + + sources, workspace = tmp_path / "sources", tmp_path / "ws" + sources.mkdir() + abstract = pubmed_xml("710", "Abstract-only paper", "A distinct result about tidal clocks.") + write_tar(sources / "pubmed.tar", {"entry.xml": abstract}) + _ok( + litkit( + workspace, + "--build-only", + "--faiss-writer", + "--tar-dir", + str(sources), + "--stage1-mode", + "none", + "--chunks-index", + "flat", + ) + ) + release, cache = tmp_path / "release", tmp_path / "cache" + export_vectors(workspace, release, settings={"chunk_model": MODELS["chunk_model"]}) + calls = [] + + def fetch(identifier): + calls.append(identifier) + return abstract.encode() + + monkeypatch.setattr(articles, "load_model", lambda *_: FakeEmbedder()) + options = dict(cache=cache, limit=2, fetch=fetch) + result = search_vectors(release, "tidal clocks", **options) + assert result["passages"] and not result["unavailable"] + assert {p["pmid"] for p in result["passages"]} == {"710"} + assert all("tidal clocks" in p["text"] and not p["pmcid"] for p in result["passages"]) + assert search_vectors(release, "tidal clocks", **options) == result and calls == ["710"] + (sources / "pubmed.tar").unlink() + restored = tmp_path / "restored" + report = rebuild_from_vectors(release, sources, restored, cache=cache) + assert len(report["cached_papers"]) == 1 and not report["missing_papers"] + assert not (restored / "indices/papers.faiss").exists() + + +def test_fetched_text_reports_its_current_license_and_retraction( + tmp_path, portable_source, monkeypatch +): + from conftest import FakeEmbedder + from litkit.portable import articles + from litkit.portable.search import search_vectors + + workspace, _ = portable_source + release = tmp_path / "release" + export_vectors(workspace, release, settings=MODELS) + monkeypatch.setattr(articles, "load_model", lambda *_: FakeEmbedder()) + record = licensed_article("PMC31", "Black coffee", "by-nc", "Private passage espresso. " * 12) + record = record.replace( + "", + '', + ) + result = search_vectors( + release, "espresso", limit=4, cache=tmp_path / "cache", fetch=lambda _: record.encode() + ) + assert result["passages"] and all( + p["license"] == "CC-BY-NC-4.0" and p["retracted"] for p in result["passages"] + ) + assert all("/by-nc/" in p["license_url"] for p in result["passages"]) + + +def test_restore_rejects_incorrect_index_dimensions(tmp_path, portable_source): + import json + from litkit.portable.restore import rebuild_from_vectors + + workspace, sources = portable_source + release, restored = tmp_path / "release", tmp_path / "restored" + export_vectors(workspace, release, settings=MODELS) + path = release / "manifest.json" + manifest = json.loads(path.read_bytes()) + manifest["indices"]["chunks"]["dimension"] += 1 + path.write_text(json.dumps(manifest)) + with pytest.raises(ValueError, match="metadata disagrees"): + rebuild_from_vectors(release, sources, restored) + assert not restored.exists() From 93969d076982b5c0de098471514cce6c212de2b3 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Fri, 4 Dec 2026 15:09:42 -0700 Subject: [PATCH 3/5] Restore the verified edition and validate cached vector searches Signed-off-by: Bill Hlavacek --- src/litkit/index/io.py | 7 +- src/litkit/portable/articles.py | 33 +++++- src/litkit/portable/release.py | 12 +- src/litkit/portable/restore.py | 88 +++++++++----- src/litkit/portable/search.py | 87 +++++++++----- tests/integration/test_portable_restore.py | 131 ++++++++++++++++++++- tests/test_index.py | 5 +- 7 files changed, 294 insertions(+), 69 deletions(-) diff --git a/src/litkit/index/io.py b/src/litkit/index/io.py index 7163a58..3426327 100644 --- a/src/litkit/index/io.py +++ b/src/litkit/index/io.py @@ -170,8 +170,8 @@ def faiss_load(path: Path) -> faiss.Index: def faiss_load_cached(path: Path) -> faiss.Index: """Load a FAISS index with thread-local caching. - Caches indices by (path, mtime) to avoid repeated disk I/O during - search operations. Cache is invalidated when file is modified. + Cache by file identity, size and timestamps so an atomic replacement that + preserves modification time cannot reuse the previous index. Args: path: Path to the index file @@ -186,8 +186,7 @@ def faiss_load_cached(path: Path) -> faiss.Index: except FileNotFoundError: return faiss_load(path) - mt_ns = getattr(st, "st_mtime_ns", int(st.st_mtime * 1_000_000_000)) - key = (str(p.resolve()), mt_ns) + key = (str(p.resolve()), st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns) cache = getattr(_TL_FAISS_CACHE, "faiss", None) if cache is None: diff --git a/src/litkit/portable/articles.py b/src/litkit/portable/articles.py index a6a92d8..2255dc5 100644 --- a/src/litkit/portable/articles.py +++ b/src/litkit/portable/articles.py @@ -2,6 +2,7 @@ from __future__ import annotations +import hashlib import io import os import tempfile @@ -10,6 +11,7 @@ from lxml import etree from litkit.build.helpers import article_passages, paper_input +from litkit.concurrent.locking import FileLock from litkit.ingest.ingest import _parse_tree from litkit.ingest.publication_types import publication_fields, publication_source from litkit.portable.release import digest @@ -111,8 +113,35 @@ def write_cache(path, raw): temporary.unlink(missing_ok=True) -def verified_article(mapping, pid, meta, settings): +def write_cached_article(path, raw): + # Serialize both replacements. An interrupted write is detected by the + # checksum before the next reader accepts the XML. + with FileLock(path.parent / ".article-cache.lock"): + write_cache(path.with_suffix(".sha256"), hashlib.sha256(raw).hexdigest().encode("ascii")) + write_cache(path, raw) + + +def read_cached_article(path, mapping, pid, metadata, settings): + raw = path.read_bytes() + try: + expected = path.with_suffix(".sha256").read_bytes() + except FileNotFoundError: + expected = None + if expected is not None and hashlib.sha256(raw).hexdigest().encode("ascii") != expected: + raise ValueError("Cached article checksum mismatch") + meta = parse_cached(raw, metadata, settings) + if expected is None and not verified_article(mapping, pid, meta, settings): + raise ValueError("Unverified legacy cached article") + return raw, meta + + +def article_match(mapping, pid, meta, settings): expected = dict(mapping.execute("SELECT ord,digest FROM passages WHERE paper_id=?", (pid,))) actual = {ordinal: digest(text) for ordinal, text, *_ in passages(meta, settings)} paper_hash = mapping.execute("SELECT digest FROM articles WHERE id=?", (pid,)).fetchone()[0] - return paper_hash == digest(paper_input(meta)) and expected == actual + complete = paper_hash == digest(paper_input(meta)) and expected == actual + return complete, sum(actual.get(o) == h for o, h in expected.items()) + + +def verified_article(mapping, pid, meta, settings): + return article_match(mapping, pid, meta, settings)[0] diff --git a/src/litkit/portable/release.py b/src/litkit/portable/release.py index f7597a4..75dd80b 100644 --- a/src/litkit/portable/release.py +++ b/src/litkit/portable/release.py @@ -8,8 +8,8 @@ import re import shutil import sqlite3 -import tempfile import tarfile +import tempfile from contextlib import closing, contextmanager from pathlib import Path, PurePosixPath, PureWindowsPath @@ -162,6 +162,16 @@ def remove_labels(index, ids): safe_remove_ids(index, make_id_selector(ids)) +def check_index_metadata(index, descriptor, name): + actual = {"kind": kind_and_core(index)[0], "dimension": index.d, "count": index.ntotal} + if ( + actual != descriptor + or not isinstance(index, faiss.IndexIDMap2) + or index.id_map.size() != index.ntotal + ): + raise ValueError(f"Release index metadata disagrees with {name}") + + def export_index(db, catalog, kind, source, target, *, filtered): """Check the entire label mapping before publishing even a filtered subset.""" mapping = "articles" if kind == "papers" else "passages" diff --git a/src/litkit/portable/restore.py b/src/litkit/portable/restore.py index f2b0fed..8159ed5 100644 --- a/src/litkit/portable/restore.py +++ b/src/litkit/portable/restore.py @@ -16,13 +16,19 @@ from litkit.config.paths import WorkspacePaths from litkit.db.handoff import readable_database from litkit.db.schema import init_db, set_stage1_mode, set_workspace_meta -from litkit.index.introspection import kind_and_core from litkit.index.io import faiss_load, write_index from litkit.ingest.ingest import _is_tar_path from litkit.ingest.publication_types import publication_source from litkit.portable import articles from litkit.portable.record import SOURCE_SCHEMA, archive_checksum, archive_identity, file_hash -from litkit.portable.release import digest, new_directory, read_manifest, remove_labels, safe_path +from litkit.portable.release import ( + check_index_metadata, + digest, + new_directory, + read_manifest, + remove_labels, + safe_path, +) class Rebuild: @@ -32,6 +38,7 @@ def __init__(self, db, mapping, manifest): self.db = db self.mapping = mapping self.manifest = manifest + self.sources = {s["name"]: s for s in manifest["sources"]} self.settings = {s["name"]: s["settings"] for s in manifest["sources"]} self.next_paper = mapping.execute("SELECT COALESCE(MAX(id),0)+1 FROM articles").fetchone()[ 0 @@ -61,7 +68,8 @@ def __init__(self, db, mapping, manifest): CREATE TEMP TABLE owners(pmid TEXT, pmcid TEXT, pid INTEGER PRIMARY KEY); CREATE UNIQUE INDEX temp.owner_pmid ON owners(pmid) WHERE pmid IS NOT NULL; CREATE UNIQUE INDEX temp.owner_pmcid ON owners(pmcid) WHERE pmcid IS NOT NULL; - CREATE TEMP TABLE picked(pid INTEGER PRIMARY KEY, priority INTEGER, name TEXT); + CREATE TEMP TABLE picked(pid INTEGER PRIMARY KEY, priority INTEGER, verified INTEGER, + uri TEXT, content_sha BLOB); """ ) db.executemany( @@ -122,33 +130,60 @@ def ingest( else: pid, priority = cached_pid, 4 self.db.execute("INSERT OR REPLACE INTO files VALUES(?,?,?,?)", (uri, size, mtime, pid)) - previous = self.db.execute("SELECT priority FROM picked WHERE pid=?", (pid,)).fetchone() + previous = self.db.execute( + "SELECT priority,verified,uri,content_sha FROM picked WHERE pid=?", (pid,) + ).fetchone() old = self.mapping.execute( "SELECT doc_id,metadata,digest,current_file FROM articles WHERE id=?", (pid,) ).fetchone() - # Legacy archives can have aliases and no current-member marker. Prefer a digest-verified edition. - if priority in (0, 2) and old: - if articles.verified_article(self.mapping, pid, meta, settings): - priority = 3 - elif priority == 0: - return - if previous and previous[0] > priority: + prior = json.loads(old[1]) if old else {} + exact = ( + old + and old[3] + and prior.get("publication_source") == publication_source(old[3], content_sha).hex() + ) + if exact and priority == 4: + verified = 2 + elif old and articles.verified_article(self.mapping, pid, meta, settings): + # A historical alias can have the same XML with different chunk settings. + verified = 2 if exact else 1 + else: + verified = 0 + if priority in (0, 2) and verified: + priority = 3 + if not priority: return - if previous and previous[0] == priority: - if old and articles.verified_article(self.mapping, pid, meta, settings): + rank = (priority, verified) + if previous: + if rank < previous[:2] or (rank == previous[:2] and previous[3] == content_sha): return - raise ValueError(f"Ambiguous source editions for paper {pid}: {uri}") - self.db.execute("INSERT OR REPLACE INTO picked VALUES(?,?,?)", (pid, priority, name)) + if rank == previous[:2] and previous[2] != uri and old: + if verified: + return + raise ValueError(f"Ambiguous source editions for paper {pid}: {uri}") + # Repeated occurrences of the same member retain archive order when neither + # the publisher fingerprint nor the release text can distinguish them. + self.db.execute( + "INSERT OR REPLACE INTO picked VALUES(?,?,?,?,?)", + (pid, priority, verified, uri, content_sha), + ) + previous_doc = None if previous: + previous_doc = self.db.execute( + "SELECT doc_id,pmid,pmcid FROM papers WHERE id=?", (pid,) + ).fetchone() + if not old and previous_doc: + prior.update(pmid=previous_doc[1], pmcid=previous_doc[2]) self.db.execute("DELETE FROM chunks WHERE paper_id=?", (pid,)) self.db.execute("DELETE FROM papers WHERE id=?", (pid,)) if not articles.license_allowed(meta, self.manifest): return - prior = json.loads(old[1]) if old else {} doc_id = old[0] if old else uri + if previous_doc and not old: + doc_id = previous_doc[0] if ( not old - and self.mapping.execute("SELECT 1 FROM articles WHERE doc_id=?", (uri,)).fetchone() + and self.mapping.execute("SELECT 1 FROM articles WHERE doc_id=?", (doc_id,)).fetchone() ): doc_id = f"portable:{pid}:{uri}" paper_text = paper_input(meta) @@ -209,7 +244,7 @@ def ingest( ) def read_sources(self, root): - records = {s["name"]: s for s in self.manifest["sources"]} + records = self.sources present = { p.relative_to(root).as_posix() for p in root.rglob("*") @@ -256,9 +291,11 @@ def read_sources(self, root): def read_cache(self, cache, root): folder = articles.cache_path(cache, self.manifest, 0).parent for path in folder.glob("*.xml"): - if not path.stem.isascii() or not path.stem.isdigit() or len(path.stem) > 18: + if not path.stem.isascii() or not path.stem.isdigit() or len(path.stem) > 19: continue pid = int(path.stem) + if pid > 2**63 - 1: + continue row = self.mapping.execute( "SELECT metadata FROM articles WHERE id=?", (pid,) ).fetchone() @@ -269,8 +306,9 @@ def read_cache(self, cache, root): continue config = articles.settings_for_article(self.mapping, pid, self.settings) try: - raw = path.read_bytes() - meta = articles.parse_cached(raw, json.loads(value), config) + raw, meta = articles.read_cached_article( + path, self.mapping, pid, json.loads(value), config + ) except (ValueError, OSError): self.report["invalid_cached_papers"].append(pid) continue @@ -288,7 +326,7 @@ def read_cache(self, cache, root): name, member, uri, 0, 0, meta, config, hashlib.sha256(raw).digest(), cached_pid=pid ) self.report["cached_papers"].append(pid) - record = next(s for s in self.manifest["sources"] if s["name"] == name) + record = self.sources[name] self.db.execute( "INSERT OR IGNORE INTO build_sources VALUES(?,?,?,?)", ( @@ -340,11 +378,7 @@ def finish(self, release, paths): if file_hash(target) != self.manifest["checksums"][source.name]: raise ValueError(f"Release checksum mismatch for {source.name}") index = faiss_load(target) - actual = {"kind": kind_and_core(index)[0], "dimension": index.d, "count": index.ntotal} - if actual != self.manifest["indices"][table] or not isinstance( - index, faiss.IndexIDMap2 - ): - raise ValueError(f"Release index metadata disagrees with {source.name}") + check_index_metadata(index, self.manifest["indices"][table], source.name) if not (missing or changed or new): del index continue diff --git a/src/litkit/portable/search.py b/src/litkit/portable/search.py index a933d33..31f6910 100644 --- a/src/litkit/portable/search.py +++ b/src/litkit/portable/search.py @@ -11,9 +11,10 @@ from urllib.request import Request, urlopen from litkit.db.handoff import readable_database +from litkit.index.io import faiss_load_cached from litkit.portable import articles from litkit.portable.record import file_hash -from litkit.portable.release import digest, read_manifest +from litkit.portable.release import check_index_metadata, digest, read_manifest from litkit.retrieval.progressive import _score_exact_text, extract_exact_terms from litkit.retrieval.search import faiss_search @@ -41,7 +42,9 @@ def verified_manifest(release, cache): if not isinstance(prior, dict): prior = {} checked = {} - for name, expected in manifest["checksums"].items(): + # Keep the searched chunks index last so the first query reuses its loaded handle. + for name in sorted(manifest["checksums"], key=lambda name: name == "chunks.faiss"): + expected = manifest["checksums"][name] path = release / name stat = path.stat() identity = [ @@ -52,14 +55,49 @@ def verified_manifest(release, cache): stat.st_mtime_ns, stat.st_ctime_ns, ] - if prior.get(name) != identity and file_hash(path) != expected: - raise ValueError(f"Release checksum mismatch for {name}") + descriptor = manifest["indices"].get(name.removesuffix(".faiss")) + if descriptor is not None: + identity.append(descriptor) + if prior.get(name) != identity: + if file_hash(path) != expected: + raise ValueError(f"Release checksum mismatch for {name}") + if descriptor is not None: + check_index_metadata(faiss_load_cached(path), descriptor, name) checked[name] = identity if checked != prior: articles.write_cache(record, json.dumps(checked).encode()) return manifest +def fetch_for_article(fetch, mapping, pid, metadata, settings, manifest): + identifiers = [metadata.get(k) for k in ("pmcid", "pmid")] + if metadata.get("article_type") is None and metadata.get("publication_types"): + identifiers.reverse() + identifiers = [i for i in identifiers if re.fullmatch(r"(?:PMC)?[0-9]+", i or "")] + best = None + best_matches = -1 + error = ValueError("No fetchable PMCID or PMID") + for identifier in identifiers: + try: + raw = fetch(identifier) + meta = articles.parse_cached(raw, metadata, settings) + if not articles.license_allowed(meta, manifest): + raise ValueError("Article license differs from the selected release licenses") + except (OSError, ValueError) as exc: + error = exc + continue + if len(identifiers) == 1: + return raw, meta + complete, matches = articles.article_match(mapping, pid, meta, settings) + if complete: + return raw, meta + if matches > best_matches: + best, best_matches = (raw, meta), matches + if best is not None: + return best + raise error + + def search_vectors(release, query, *, cache, limit=10, mode="semantic", fetch=None): if not query.strip() or limit < 1 or mode not in ("semantic", "hybrid"): raise ValueError("Supply a query, positive limit and semantic or hybrid mode") @@ -79,6 +117,16 @@ def search_vectors(release, query, *, cache, limit=10, mode="semantic", fetch=No ) configs = {s["name"]: s["settings"] for s in manifest["sources"]} by_paper = {} + retry_after = 0.0 + + def download(identifier): + nonlocal retry_after + if fetch: + return fetch(identifier) + time.sleep(max(0, retry_after - time.monotonic())) + retry_after = time.monotonic() + 0.35 + return fetch_article(identifier) + with readable_database(release / "mapping.sqlite3") as mapping: for rank, (cid, score) in enumerate(zip(ids, scores, strict=True)): row = mapping.execute( @@ -92,39 +140,18 @@ def search_vectors(release, query, *, cache, limit=10, mode="semantic", fetch=No hits = by_paper.setdefault(pid, []) hits.append((rank, cid, ordinal, checksum, score, member, metadata)) available = [] - retry_after = 0.0 for pid, hits in by_paper.items(): metadata = json.loads(hits[0][-1]) settings = articles.settings_for_article(mapping, pid, configs) path = articles.cache_path(cache, manifest, pid) try: try: - raw = path.read_bytes() - meta = articles.parse_cached(raw, metadata, settings) + raw, meta = articles.read_cached_article(path, mapping, pid, metadata, settings) except (FileNotFoundError, ValueError): - identifiers = [metadata.get(k) for k in ("pmcid", "pmid")] - # For a release built from a PubMed record, fetch the matching abstract first. - if metadata.get("article_type") is None and metadata.get("publication_types"): - identifiers.reverse() - ids_to_fetch = [ - i for i in identifiers if re.fullmatch(r"(?:PMC)?[0-9]+", i or "") - ] - if not ids_to_fetch: - raise ValueError("No fetchable PMCID or PMID") from None - for index, identifier in enumerate(ids_to_fetch): - if fetch is None: - time.sleep(max(0, retry_after - time.monotonic())) - retry_after = time.monotonic() + 0.35 - try: - raw = (fetch or fetch_article)(identifier) - meta = articles.parse_cached(raw, metadata, settings) - except (OSError, ValueError): - if index == len(ids_to_fetch) - 1: - raise - continue - break - if articles.license_allowed(meta, manifest): - articles.write_cache(path, raw) + raw, meta = fetch_for_article( + download, mapping, pid, metadata, settings, manifest + ) + articles.write_cached_article(path, raw) if not articles.license_allowed(meta, manifest): raise ValueError("Article license differs from the selected release licenses") metadata.update( diff --git a/tests/integration/test_portable_restore.py b/tests/integration/test_portable_restore.py index 72ab699..1a164bf 100644 --- a/tests/integration/test_portable_restore.py +++ b/tests/integration/test_portable_restore.py @@ -131,6 +131,9 @@ def fetch(pmcid): assert calls == ["PMC31"] empty = tmp_path / "missing" empty.mkdir() + # Existing caches predate the download checksums. A complete match against + # the release's paper and passage hashes still permits an offline restore. + next(cache.glob("*/*.sha256")).unlink() restored = tmp_path / "restored" monkeypatch.setattr( articles, "load_model", lambda *_: pytest.fail("a verified cached article loaded a model") @@ -158,10 +161,25 @@ def test_on_demand_never_returns_drifted_text_or_excluded_license( for code in ("by", "by-nc"): response = licensed_article("PMC31", "Black coffee", code, "Replacement body.") result = search_vectors( - release, "coffee", limit=5, cache=tmp_path / code, fetch=lambda _, xml=response: xml.encode() + release, + "coffee", + limit=5, + cache=tmp_path / code, + fetch=lambda _, xml=response: xml.encode(), ) assert all("Replacement" not in hit["text"] for hit in result["passages"]) assert result["unavailable"] and len(result["passages"]) == (1 if code == "by" else 0) + if code == "by": + assert ( + search_vectors( + release, + "coffee", + limit=5, + cache=tmp_path / code, + fetch=lambda _: pytest.fail("Unmodified remote drift was fetched again"), + ) + == result + ) def test_restore_refuses_corrupt_release_without_publishing_workspace(tmp_path, portable_source): @@ -177,8 +195,9 @@ def test_restore_refuses_corrupt_release_without_publishing_workspace(tmp_path, assert not output.exists() +@pytest.mark.parametrize("well_formed", [False, True]) def test_corrupt_cached_xml_is_recovered_online_and_reported_offline( - tmp_path, portable_source, monkeypatch + tmp_path, portable_source, monkeypatch, well_formed ): from conftest import FakeEmbedder from litkit.portable import articles @@ -204,7 +223,11 @@ def fetch(identifier): options = dict(cache=cache, limit=10, fetch=fetch) original = search_vectors(release, "navigation", **options) bad = next(cache.glob("*/*.xml")) - bad.write_bytes(b" Date: Fri, 4 Dec 2026 15:21:17 -0700 Subject: [PATCH 4/5] Restore published member ownership and verify each requested passage Signed-off-by: Bill Hlavacek --- README.md | 8 +- src/litkit/portable/articles.py | 22 +++- src/litkit/portable/release.py | 11 +- src/litkit/portable/restore.py | 139 ++++++++++++++++---- src/litkit/portable/search.py | 98 +++++++------- tests/integration/test_portable_restore.py | 142 +++++++++++++++++++++ tests/integration/test_portable_vectors.py | 1 + 7 files changed, 337 insertions(+), 84 deletions(-) diff --git a/README.md b/README.md index 67d6f81..b88bf71 100644 --- a/README.md +++ b/README.md @@ -263,8 +263,12 @@ recorded model snapshots in the Hugging Face cache (`--hf-home`). To retrieve passages before downloading the bulk archives, run `litkit search-vectors RELEASE "query" --mode semantic --limit 10 --cache DIR`. -LitKit searches the chunk index, fetches matching full text from Europe PMC or the abstract record by PMID from PubMed, and returns only passages matching their recorded text hashes. The JSON -output includes identifiers and titles for unavailable or changed passages. +LitKit searches the chunk index and checks each requested passage against its +recorded text hash. It can recover an abstract from PubMed and body passages +from Europe PMC for the same paper. Each hit includes the license and +publication status of its source XML. Its `source_identifier` gives the PMCID +or PMID used for the request, or `null` for an older cache with unknown origin. +The JSON output includes identifiers and titles for unavailable or changed passages. Hybrid mode reranks the fetched candidates using lexical and semantic ranks. Queries require the recorded chunk embedding model. Subsequent queries reuse the cached XML. Pass the same `--cache DIR` to a rebuild to recover verified diff --git a/src/litkit/portable/articles.py b/src/litkit/portable/articles.py index 2255dc5..7485aab 100644 --- a/src/litkit/portable/articles.py +++ b/src/litkit/portable/articles.py @@ -5,6 +5,7 @@ import hashlib import io import os +import re import tempfile from pathlib import Path @@ -70,6 +71,18 @@ def cache_path(root, manifest, pid): return Path(root) / manifest["checksums"]["mapping.sqlite3"] / f"{pid}.xml" +def cache_sources(path, metadata): + """Return each fetchable identifier and its XML cache, plus any older shared cache.""" + identifiers = [metadata.get(key) for key in ("pmcid", "pmid")] + if metadata.get("article_type") is None and metadata.get("publication_types"): + identifiers.reverse() + identifiers = [i for i in identifiers if re.fullmatch(r"(?:PMC)?[0-9]+", i or "")] + if len(identifiers) < 2: + return [(identifiers[0] if identifiers else None, path)] + # Older two-identifier downloads did not record which endpoint supplied them. + return [(i, path.with_name(f"{path.stem}.{i}.xml")) for i in identifiers] + [(None, path)] + + def parse_cached(raw, metadata, settings): parser = etree.XMLParser( resolve_entities=False, load_dtd=False, no_network=True, huge_tree=True @@ -135,13 +148,8 @@ def read_cached_article(path, mapping, pid, metadata, settings): return raw, meta -def article_match(mapping, pid, meta, settings): +def verified_article(mapping, pid, meta, settings): expected = dict(mapping.execute("SELECT ord,digest FROM passages WHERE paper_id=?", (pid,))) actual = {ordinal: digest(text) for ordinal, text, *_ in passages(meta, settings)} paper_hash = mapping.execute("SELECT digest FROM articles WHERE id=?", (pid,)).fetchone()[0] - complete = paper_hash == digest(paper_input(meta)) and expected == actual - return complete, sum(actual.get(o) == h for o, h in expected.items()) - - -def verified_article(mapping, pid, meta, settings): - return article_match(mapping, pid, meta, settings)[0] + return paper_hash == digest(paper_input(meta)) and expected == actual diff --git a/src/litkit/portable/release.py b/src/litkit/portable/release.py index 2cf3a14..a71785c 100644 --- a/src/litkit/portable/release.py +++ b/src/litkit/portable/release.py @@ -367,7 +367,7 @@ def export_vectors(workspace, output, *, licenses=(), settings=None, source_root ) where = " WHERE " + predicate if allowed else "" legacy = LegacyArchives(source_root, records, catalog) - originals, selected_sources = set(), set() + excluded_candidates, selected_sources = set(), set() for uri, selected in db.execute( f"SELECT f.path,{predicate} FROM files f JOIN papers p ON p.id=f.paper_id", allowed ): @@ -378,7 +378,14 @@ def export_vectors(workspace, output, *, licenses=(), settings=None, source_root else: # Preserve the publisher's directory layout without requiring # access to archives excluded by the license filter. - originals.update(archive for archive, _ in candidates) + excluded_candidates.add(frozenset(archive for archive, _ in candidates)) + originals = set() + for candidates in excluded_candidates: + # An excluded member may be another paper in the same known archive. + # A speculative delimiter split must not widen the publisher root. + originals.update( + candidates & selected_sources or candidates & records.keys() or candidates + ) source_paths = archive_names(originals | selected_sources, check_collisions=False) for archive in selected_sources - records.keys(): source_paths[archive] = legacy.relocated_name(archive, source_paths[archive]) diff --git a/src/litkit/portable/restore.py b/src/litkit/portable/restore.py index 8159ed5..1497059 100644 --- a/src/litkit/portable/restore.py +++ b/src/litkit/portable/restore.py @@ -39,6 +39,7 @@ def __init__(self, db, mapping, manifest): self.mapping = mapping self.manifest = manifest self.sources = {s["name"]: s for s in manifest["sources"]} + self.reassigned_file = False self.settings = {s["name"]: s["settings"] for s in manifest["sources"]} self.next_paper = mapping.execute("SELECT COALESCE(MAX(id),0)+1 FROM articles").fetchone()[ 0 @@ -84,13 +85,24 @@ def __init__(self, db, mapping, manifest): ) db.execute(SOURCE_SCHEMA) - def resolve(self, name, member, meta): + def resolve(self, name, member, meta, content_sha, unchanged): """A citation ID follows a renamed member; a reused filename cannot steal another ID.""" match = self.mapping.execute( - """SELECT a.id,a.current_file,f.original FROM files f JOIN articles a ON a.id=f.paper_id - WHERE source=? AND member=?""", + """SELECT a.id,CASE WHEN a.current_file=f.original THEN 4 + WHEN a.current_file IS NULL THEN 2 ELSE 0 END, + f.original, a.metadata + FROM files f JOIN articles a ON a.id=f.paper_id WHERE source=? AND member=?""", (name, member), ).fetchone() + if unchanged or ( + match + and match[1] == 4 + and json.loads(match[3]).get("publication_source") + == publication_source(match[2], content_sha).hex() + ): + # The release records the actual owner of every included member. A + # repeated filename can have an earlier or skipped, unrelated citation. + return match[:2] if match else None pmid, pmcid = meta.get("pmid") or None, meta.get("pmcid") or None owners = self.db.execute( "SELECT pid,pmid,pmcid FROM owners WHERE pmid=? OR pmcid=?", (pmid, pmcid) @@ -119,17 +131,33 @@ def resolve(self, name, member, meta): self.next_paper += 1 self.db.execute("INSERT INTO owners VALUES(?,?,?)", (pmid, pmcid, pid)) if match and match[0] == pid: - return pid, 4 if match[1] == match[2] else 2 if not match[1] else 0 + return match[:2] return pid, 1 def ingest( - self, name, member, uri, size, mtime, meta, settings, content_sha, *, cached_pid=None + self, + name, + member, + uri, + size, + mtime, + meta, + settings, + content_sha, + *, + cached_pid=None, + unchanged=False, ): if cached_pid is None: - pid, priority = self.resolve(name, member, meta) + owner = self.resolve(name, member, meta, content_sha, unchanged) + if owner is None: + return + pid, priority = owner else: pid, priority = cached_pid, 4 - self.db.execute("INSERT OR REPLACE INTO files VALUES(?,?,?,?)", (uri, size, mtime, pid)) + registered = self.db.execute( + "INSERT OR IGNORE INTO files VALUES(?,?,?,?)", (uri, size, mtime, pid) + ) previous = self.db.execute( "SELECT priority,verified,uri,content_sha FROM picked WHERE pid=?", (pid,) ).fetchone() @@ -143,10 +171,14 @@ def ingest( and prior.get("publication_source") == publication_source(old[3], content_sha).hex() ) if exact and priority == 4: - verified = 2 + verified = 3 elif old and articles.verified_article(self.mapping, pid, meta, settings): # A historical alias can have the same XML with different chunk settings. - verified = 2 if exact else 1 + consistent = all( + not (meta.get(k) and prior.get(k) and meta[k] != prior[k]) + for k in ("pmid", "pmcid") + ) + verified = 3 if exact else 2 if consistent else 1 else: verified = 0 if priority in (0, 2) and verified: @@ -154,6 +186,20 @@ def ingest( if not priority: return rank = (priority, verified) + earlier_owner = None + if not registered.rowcount: + earlier_owner = self.db.execute( + """SELECT f.paper_id,p.priority,p.verified,p.uri FROM files f + LEFT JOIN picked p ON p.pid=f.paper_id WHERE f.path=? AND f.paper_id<>?""", + (uri, pid), + ).fetchone() + if ( + earlier_owner + and earlier_owner[3] == uri + and earlier_owner[2] + and earlier_owner[1:3] > rank + ): + return if previous: if rank < previous[:2] or (rank == previous[:2] and previous[3] == content_sha): return @@ -167,6 +213,9 @@ def ingest( "INSERT OR REPLACE INTO picked VALUES(?,?,?,?,?)", (pid, priority, verified, uri, content_sha), ) + self.db.execute("INSERT OR REPLACE INTO files VALUES(?,?,?,?)", (uri, size, mtime, pid)) + if earlier_owner: + self.reassigned_file = True previous_doc = None if previous: previous_doc = self.db.execute( @@ -191,6 +240,8 @@ def ingest( k: meta.get(k) or prior.get(k) for k in ("pmid", "pmcid", "doi", "authors", "journal", "year") } + if unchanged or (exact and priority == 4): + metadata.update(pmid=prior.get("pmid"), pmcid=prior.get("pmcid")) metadata.update( {k: meta.get(k) for k in ("title", "abstract", "source_path", "license", "license_url")} ) @@ -266,7 +317,8 @@ def read_sources(self, root): config = record["settings"] identity = archive_identity(path) checksum, size = archive_checksum(path, expected=identity) - if record and checksum != record["sha256"]: + unchanged = record is not None and checksum == record["sha256"] + if record and not unchanged: self.report["changed_sources"].append(name) self.db.execute( "INSERT INTO build_sources VALUES(?,?,?,?)", @@ -284,47 +336,78 @@ def read_sources(self, root): meta, config, member.content_sha256, + unchanged=unchanged, ) if archive_identity(path) != identity: raise ValueError(f"Source changed while rebuilding {name}") + if self.reassigned_file: + # A repeated filename may have temporarily supplied an unrelated + # article before we saw the verified edition. Retain its genuine aliases. + self.db.execute( + "CREATE TEMP TABLE unowned AS SELECT id FROM papers EXCEPT SELECT paper_id FROM files" + ) + self.db.execute("DELETE FROM chunks WHERE paper_id IN (SELECT id FROM unowned)") + self.db.execute("DELETE FROM papers WHERE id IN (SELECT id FROM unowned)") + self.db.execute("DELETE FROM picked WHERE pid IN (SELECT id FROM unowned)") def read_cache(self, cache, root): folder = articles.cache_path(cache, self.manifest, 0).parent + checked = set() for path in folder.glob("*.xml"): - if not path.stem.isascii() or not path.stem.isdigit() or len(path.stem) > 19: + number = path.stem.partition(".")[0] + if not number.isascii() or not number.isdigit() or len(number) > 19: continue - pid = int(path.stem) - if pid > 2**63 - 1: + pid = int(number) + if pid > 2**63 - 1 or pid in checked: continue + checked.add(pid) row = self.mapping.execute( - "SELECT metadata FROM articles WHERE id=?", (pid,) + "SELECT metadata,current_file FROM articles WHERE id=?", (pid,) ).fetchone() if row is None: continue - value = row[0] + metadata = json.loads(row[0]) if self.db.execute("SELECT 1 FROM picked WHERE pid=?", (pid,)).fetchone(): continue config = articles.settings_for_article(self.mapping, pid, self.settings) - try: - raw, meta = articles.read_cached_article( - path, self.mapping, pid, json.loads(value), config - ) - except (ValueError, OSError): - self.report["invalid_cached_papers"].append(pid) - continue - if not articles.verified_article( - self.mapping, pid, meta, config - ) or not articles.license_allowed(meta, self.manifest): + complete = None + invalid = False + primary = articles.cache_path(cache, self.manifest, pid) + for _, candidate in articles.cache_sources(primary, metadata): + try: + raw, meta = articles.read_cached_article( + candidate, self.mapping, pid, metadata, config + ) + except FileNotFoundError: + continue + except (ValueError, OSError): + invalid = True + continue + if articles.license_allowed(meta, self.manifest) and articles.verified_article( + self.mapping, pid, meta, config + ): + content_sha = hashlib.sha256(raw).digest() + if complete is None: + complete = meta, content_sha + if ( + row[1] + and metadata.get("publication_source") + == publication_source(row[1], content_sha).hex() + ): + complete = meta, content_sha + break + if complete is None: + if invalid: + self.report["invalid_cached_papers"].append(pid) continue + meta, content_sha = complete name, member = self.mapping.execute( """SELECT f.source,f.member FROM files f JOIN articles a ON a.id=f.paper_id WHERE a.id=? ORDER BY (f.original=a.current_file) DESC,f.original LIMIT 1""", (pid,), ).fetchone() uri = f"tar://{safe_path(root,name)}!/{member}" - self.ingest( - name, member, uri, 0, 0, meta, config, hashlib.sha256(raw).digest(), cached_pid=pid - ) + self.ingest(name, member, uri, 0, 0, meta, config, content_sha, cached_pid=pid) self.report["cached_papers"].append(pid) record = self.sources[name] self.db.execute( diff --git a/src/litkit/portable/search.py b/src/litkit/portable/search.py index 31f6910..15f6ef7 100644 --- a/src/litkit/portable/search.py +++ b/src/litkit/portable/search.py @@ -69,33 +69,59 @@ def verified_manifest(release, cache): return manifest -def fetch_for_article(fetch, mapping, pid, metadata, settings, manifest): - identifiers = [metadata.get(k) for k in ("pmcid", "pmid")] - if metadata.get("article_type") is None and metadata.get("publication_types"): - identifiers.reverse() - identifiers = [i for i in identifiers if re.fullmatch(r"(?:PMC)?[0-9]+", i or "")] - best = None - best_matches = -1 +def verified_hits(fetch, mapping, pid, metadata, settings, manifest, cache, hits): + """Keep each verified ordinal with the metadata of the XML that supplied it.""" + expected = {ordinal: checksum for _, _, ordinal, checksum, *_ in hits} + matches = {} + member = hits[0][-2] + available = False error = ValueError("No fetchable PMCID or PMID") - for identifier in identifiers: + + def collect(raw, meta, identifier): + nonlocal available + if not articles.license_allowed(meta, manifest): + raise ValueError("Article license differs from the selected release licenses") + available = True + attribution = dict(metadata) + attribution.pop("publication_source", None) + attribution.update( + articles.status_fields(meta, hashlib.sha256(raw).digest(), member, metadata) + ) + attribution.update( + source_identifier=identifier, + license=meta.get("license"), + license_url=meta.get("license_url"), + ) + for ordinal, text, page, section, _ in articles.passages(meta, settings): + if ordinal not in matches and ordinal in expected and digest(text) == expected[ordinal]: + matches[ordinal] = (text, page, section, attribution) + + pending = [] + path = articles.cache_path(cache, manifest, pid) + for identifier, candidate in articles.cache_sources(path, metadata): + try: + raw, meta = articles.read_cached_article(candidate, mapping, pid, metadata, settings) + collect(raw, meta, identifier) + except (OSError, ValueError) as exc: + if identifier: + pending.append((identifier, candidate)) + elif not isinstance(exc, FileNotFoundError): + error = exc + if len(matches) == len(expected): + return matches + for identifier, candidate in pending: try: raw = fetch(identifier) meta = articles.parse_cached(raw, metadata, settings) - if not articles.license_allowed(meta, manifest): - raise ValueError("Article license differs from the selected release licenses") + collect(raw, meta, identifier) + articles.write_cached_article(candidate, raw) except (OSError, ValueError) as exc: error = exc - continue - if len(identifiers) == 1: - return raw, meta - complete, matches = articles.article_match(mapping, pid, meta, settings) - if complete: - return raw, meta - if matches > best_matches: - best, best_matches = (raw, meta), matches - if best is not None: - return best - raise error + if len(matches) == len(expected): + break + if not available: + raise error + return matches def search_vectors(release, query, *, cache, limit=10, mode="semantic", fetch=None): @@ -143,28 +169,10 @@ def download(identifier): for pid, hits in by_paper.items(): metadata = json.loads(hits[0][-1]) settings = articles.settings_for_article(mapping, pid, configs) - path = articles.cache_path(cache, manifest, pid) try: - try: - raw, meta = articles.read_cached_article(path, mapping, pid, metadata, settings) - except (FileNotFoundError, ValueError): - raw, meta = fetch_for_article( - download, mapping, pid, metadata, settings, manifest - ) - articles.write_cached_article(path, raw) - if not articles.license_allowed(meta, manifest): - raise ValueError("Article license differs from the selected release licenses") - metadata.update( - articles.status_fields( - meta, hashlib.sha256(raw).digest(), hits[0][-2], metadata - ) + by_ord = verified_hits( + download, mapping, pid, metadata, settings, manifest, cache, hits ) - metadata.pop("publication_source", None) - metadata.update(license=meta.get("license"), license_url=meta.get("license_url")) - by_ord = { - o: (text, page, section) - for o, text, page, section, _ in articles.passages(meta, settings) - } except (OSError, URLError, ValueError) as error: result["unavailable"].append( { @@ -176,9 +184,9 @@ def download(identifier): } ) continue - for rank, cid, ordinal, expected, score, _, _ in hits: + for rank, cid, ordinal, _, score, _, _ in hits: passage = by_ord.get(ordinal) - if not passage or digest(passage[0]) != expected: + if passage is None: result["unavailable"].append( { "paper_id": pid, @@ -191,7 +199,7 @@ def download(identifier): } ) continue - text, page, section = passage + text, page, section, provenance = passage available.append( ( rank, @@ -203,7 +211,7 @@ def download(identifier): page=page, section=section, score=score, - **metadata, + **provenance, ), ) ) diff --git a/tests/integration/test_portable_restore.py b/tests/integration/test_portable_restore.py index 1a164bf..9dc94a5 100644 --- a/tests/integration/test_portable_restore.py +++ b/tests/integration/test_portable_restore.py @@ -314,6 +314,7 @@ def test_on_demand_tries_other_identifier_after_valid_but_changed_xml(tmp_path, from conftest import FakeEmbedder, jats, pubmed_xml from litkit.portable import articles + from litkit.portable.restore import rebuild_from_vectors from litkit.portable.search import search_vectors sources, workspace = tmp_path / "sources", tmp_path / "original" @@ -351,6 +352,147 @@ def fetch(identifier): assert {h["text"] for h in hits["passages"]} == {abstract, f"{title} {abstract}"} assert not hits["unavailable"] and called == ["PMC31", "718"] assert search_vectors(release, "cells", **options) == hits and len(called) == 2 + empty = tmp_path / "empty" + empty.mkdir() + restored = tmp_path / "restored" + monkeypatch.setattr( + articles, "load_model", lambda *_: pytest.fail("complete alternate XML loaded a model") + ) + report = rebuild_from_vectors(release, empty, restored, cache=options["cache"]) + assert report["cached_papers"] == [1] and not report["missing_papers"] + assert file_hash(release / "chunks.faiss") == file_hash(restored / "indices/chunks.faiss") + + +@pytest.mark.parametrize("change_archive", [False, True]) +@pytest.mark.parametrize("later_revision", [False, True]) +def test_archive_keeps_only_the_published_owner_of_a_repeated_member( + tmp_path, monkeypatch, change_archive, later_revision +): + from test_build_and_query import _ok, litkit + + from conftest import jats + from litkit.portable import articles + from litkit.portable.restore import rebuild_from_vectors + + sources, workspace = tmp_path / "sources", tmp_path / "original" + sources.mkdir() + editions = [ + jats(pmcid=i, title=t, paragraphs=[body]) + for i, t, body in ( + ("PMC41", "older", "source one"), + ("PMC42", "newer", "revised second source" if later_revision else "source two"), + ) + ] + write_tar(sources / "papers.tar", [("same.xml", edition) for edition in editions]) + _ok( + litkit( + workspace, + "--build-only", + "--faiss-writer", + "--tar-dir", + str(sources), + "--papers-index", + "flat", + "--chunks-index", + "flat", + ) + ) + release, restored = tmp_path / "release", tmp_path / "restored" + export_vectors(workspace, release, settings=MODELS) + if change_archive: + write_tar( + sources / "papers.tar", + [("same.xml", edition) for edition in editions] + [("notes.txt", "extra")], + ) + monkeypatch.setattr( + articles, "load_model", lambda *_: pytest.fail("unchanged TAR loaded an embedder") + ) + report = rebuild_from_vectors(release, sources, restored) + assert report.pop("changed_sources") == (["papers.tar"] if change_archive else []) + assert not any(report.values()) + for table, fields in ( + ("papers", "id,doc_id,pmcid,title"), + ("chunks", "id,paper_id,ord,text"), + ("files", "path,size,mtime,paper_id"), + ): + with ( + closing(sqlite3.connect(workspace / "sqlite/litkit.sqlite3")) as original, + closing(sqlite3.connect(restored / "sqlite/litkit.sqlite3")) as rebuilt, + ): + assert original.execute(f"SELECT {fields} FROM {table} ORDER BY 1").fetchall() == ( + rebuilt.execute(f"SELECT {fields} FROM {table} ORDER BY 1").fetchall() + ) + for kind in ("papers", "chunks"): + assert file_hash(release / f"{kind}.faiss") == file_hash(restored / f"indices/{kind}.faiss") + + +def test_on_demand_combines_verified_hits_from_both_records_and_caches_each(tmp_path, monkeypatch): + from test_build_and_query import _ok, litkit + + from conftest import FakeEmbedder, jats, pubmed_xml + from litkit.portable import articles + from litkit.portable.search import search_vectors + + sources, workspace = tmp_path / "sources", tmp_path / "workspace" + sources.mkdir() + title, abstract = "Mineral catalog", "Zeolite crystalline basalt." + body = [(word + " ") * 215 for word in ("zucchini", "copper", "amber", "saffron")] + published = jats(pmcid="PMC31", pmid="718", title=title, abstract=abstract, paragraphs=body) + write_tar(sources / "a.tar", {"entry.xml": published}) + _ok( + litkit( + workspace, + "--build-only", + "--faiss-writer", + "--tar-dir", + str(sources), + "--papers-index", + "flat", + "--chunks-index", + "flat", + ) + ) + release = tmp_path / "release" + export_vectors(workspace, release, settings=MODELS) + monkeypatch.setattr(articles, "load_model", lambda *_: FakeEmbedder()) + pmc = published.replace(abstract, "A revised abstract.").replace( + "", + '' + '', + ) + calls = [] + + def fetch(identifier): + calls.append(identifier) + return (pmc if identifier == "PMC31" else pubmed_xml("718", title, abstract)).encode() + + options = dict(cache=tmp_path / "cache", fetch=fetch) + # A body-only request can be answered from PMC alone. Its cached, revised + # abstract must not mask the PubMed version on the next request. + assert search_vectors(release, body[0], limit=1, **options)["passages"] + assert calls == ["PMC31"] + query = f"{title} {abstract}" + single = search_vectors(release, query, limit=1, **options) + assert not single["unavailable"] and [p["text"] for p in single["passages"]] == [query] + assert calls == ["PMC31", "718"] + result = search_vectors(release, query, limit=20, **options) + assert not result["unavailable"] + assert {p["ord"] for p in result["passages"]} == {-1, 0, 1, 2, 3} + for hit in result["passages"]: + if hit["ord"] == -1: + assert ( + hit["source_identifier"] == "718" + and not hit["retracted"] + and hit["license"] is None + ) + else: + assert ( + hit["source_identifier"] == "PMC31" + and hit["retracted"] + and hit["license"] == "CC-BY-NC-4.0" + ) + assert search_vectors(release, query, limit=20, **options) == result + assert calls == ["PMC31", "718"] def test_pmids_without_pmc_full_text_can_be_fetched_and_cached(tmp_path, monkeypatch): diff --git a/tests/integration/test_portable_vectors.py b/tests/integration/test_portable_vectors.py index 9d58b7e..2293cf3 100644 --- a/tests/integration/test_portable_vectors.py +++ b/tests/integration/test_portable_vectors.py @@ -68,6 +68,7 @@ def test_export_copies_or_filters_vectors_and_does_not_ship_text( workspace, sources = portable_source bundle = tmp_path / "文献 release" manifest = export_vectors(workspace, bundle, licenses=licenses, settings=MODELS) + assert [s["name"] for s in manifest["sources"]] == ["papers.tar"] assert manifest["sources"][0]["sha256"] == file_hash(sources / "papers.tar") assert manifest["sources"][0]["settings"]["chunk_model"] == MODELS["chunk_model"] assert b"Private passage" not in (bundle / "mapping.sqlite3").read_bytes() From 636255fdacbddd5af38105cc45dc333f9c2e5568 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Fri, 4 Dec 2026 15:32:41 -0700 Subject: [PATCH 5/5] Preserve distinct published editions stored under one archive member name Signed-off-by: Bill Hlavacek --- src/litkit/portable/articles.py | 27 ++++- src/litkit/portable/release.py | 25 ++++- src/litkit/portable/restore.py | 88 ++++++++++++--- src/litkit/portable/search.py | 5 +- tests/integration/test_portable_restore.py | 120 +++++++++++++++++++++ 5 files changed, 242 insertions(+), 23 deletions(-) diff --git a/src/litkit/portable/articles.py b/src/litkit/portable/articles.py index 7485aab..25dace1 100644 --- a/src/litkit/portable/articles.py +++ b/src/litkit/portable/articles.py @@ -36,13 +36,32 @@ def license_allowed(meta, manifest): return not manifest["licenses"] or (meta.get("license") or "unknown") in manifest["licenses"] -def settings_for_article(mapping, paper_id, sources): +def prepare_shared_editions(mapping): + # Earlier releases only recorded the final owner of each member name. + if not mapping.execute("SELECT 1 FROM sqlite_master WHERE name='shared_editions'").fetchone(): + mapping.execute( + """CREATE TEMP VIEW IF NOT EXISTS shared_editions AS + SELECT a.id AS paper_id,f.source,f.member FROM articles a JOIN files f + ON f.original=a.current_file WHERE a.id<>f.paper_id""" + ) + + +def article_sources(mapping, paper_id): rows = mapping.execute( - """SELECT DISTINCT f.source FROM files f JOIN articles a ON a.id=f.paper_id - WHERE a.id=? AND (a.current_file IS NULL OR a.current_file=f.original)""", + """SELECT f.source,f.member FROM files f JOIN articles a ON a.id=f.paper_id + WHERE a.id=? AND (a.current_file IS NULL OR a.current_file=f.original) ORDER BY f.original""", (paper_id,), + ).fetchall() + return ( + rows + or mapping.execute( + "SELECT source,member FROM shared_editions WHERE paper_id=?", (paper_id,) + ).fetchall() ) - options = [sources[name] for (name,) in rows] + + +def settings_for_article(paper_id, locations, sources): + options = [sources[name] for name, _ in locations] if not options or any(config != options[0] for config in options[1:]): raise ValueError(f"Cannot determine unique build settings for paper {paper_id}") return options[0] diff --git a/src/litkit/portable/release.py b/src/litkit/portable/release.py index a71785c..d91f9c6 100644 --- a/src/litkit/portable/release.py +++ b/src/litkit/portable/release.py @@ -52,6 +52,8 @@ CREATE TABLE files(source TEXT NOT NULL, member TEXT NOT NULL, paper_id INTEGER NOT NULL, original TEXT NOT NULL, PRIMARY KEY(source, member)); CREATE INDEX files_paper ON files(paper_id); +CREATE TABLE shared_editions(paper_id INTEGER PRIMARY KEY, source TEXT NOT NULL, member TEXT NOT NULL); +CREATE INDEX shared_members ON shared_editions(source,member); """ @@ -379,6 +381,19 @@ def export_vectors(workspace, output, *, licenses=(), settings=None, source_root # Preserve the publisher's directory layout without requiring # access to archives excluded by the license filter. excluded_candidates.add(frozenset(archive for archive, _ in candidates)) + # files.path has one owner, even when several papers were published + # from distinct occurrences of the same tar member name. + if "build_member" in cols: + for pid, uri in db.execute( + f"""SELECT p.id,p.build_member FROM papers p LEFT JOIN files f ON f.path=p.build_member + WHERE p.build_member IS NOT NULL AND f.paper_id IS NOT p.id AND {predicate}""", + allowed, + ): + archive, member_name = legacy.member(uri, archive_candidates(uri, records)) + selected_sources.add(archive) + catalog.execute( + "INSERT INTO shared_editions VALUES (?,?,?)", (pid, archive, member_name) + ) originals = set() for candidates in excluded_candidates: # An excluded member may be another paper in the same known archive. @@ -390,6 +405,13 @@ def export_vectors(workspace, output, *, licenses=(), settings=None, source_root for archive in selected_sources - records.keys(): source_paths[archive] = legacy.relocated_name(archive, source_paths[archive]) validate_archive_names(source_paths[archive] for archive in selected_sources) + for pid, archive in catalog.execute( + "SELECT paper_id,source FROM shared_editions ORDER BY paper_id" + ): + catalog.execute( + "UPDATE shared_editions SET source=? WHERE paper_id=?", + (source_paths[archive], pid), + ) defaults, by_source = supplied_settings(settings, source_paths.values()) for row in db.execute( f"""SELECT p.id,{','.join(fields.values())}, {member}, @@ -453,7 +475,8 @@ def export_vectors(workspace, output, *, licenses=(), settings=None, source_root (source_paths[original], member_name, pid, path), ) if catalog.execute( - "SELECT id FROM articles EXCEPT SELECT paper_id FROM files LIMIT 1" + "SELECT id FROM articles EXCEPT SELECT paper_id FROM files " + "EXCEPT SELECT paper_id FROM shared_editions LIMIT 1" ).fetchone(): raise ValueError("A selected paper lacks an archive member mapping") manifest = { diff --git a/src/litkit/portable/restore.py b/src/litkit/portable/restore.py index 1497059..c41e7a5 100644 --- a/src/litkit/portable/restore.py +++ b/src/litkit/portable/restore.py @@ -71,6 +71,9 @@ def __init__(self, db, mapping, manifest): CREATE UNIQUE INDEX temp.owner_pmcid ON owners(pmcid) WHERE pmcid IS NOT NULL; CREATE TEMP TABLE picked(pid INTEGER PRIMARY KEY, priority INTEGER, verified INTEGER, uri TEXT, content_sha BLOB); + CREATE TEMP TABLE shared(pid INTEGER PRIMARY KEY, source TEXT, member TEXT, uri TEXT, + metadata TEXT, size INTEGER DEFAULT 0, mtime REAL DEFAULT 0); + CREATE INDEX temp.shared_location ON shared(source,member); """ ) db.executemany( @@ -84,6 +87,15 @@ def __init__(self, db, mapping, manifest): ), ) db.execute(SOURCE_SCHEMA) + articles.prepare_shared_editions(mapping) + db.executemany( + "INSERT INTO shared(pid,source,member,uri,metadata) VALUES (?,?,?,?,?)", + mapping.execute( + """SELECT a.id,e.source,e.member,a.current_file,a.metadata FROM shared_editions e + JOIN articles a ON a.id=e.paper_id""" + ), + ) + self.has_shared_editions = db.execute("SELECT 1 FROM shared LIMIT 1").fetchone() is not None def resolve(self, name, member, meta, content_sha, unchanged): """A citation ID follows a renamed member; a reused filename cannot steal another ID.""" @@ -94,15 +106,42 @@ def resolve(self, name, member, meta, content_sha, unchanged): FROM files f JOIN articles a ON a.id=f.paper_id WHERE source=? AND member=?""", (name, member), ).fetchone() - if unchanged or ( + registered = (match[0], match[1], True) if match else None + if unchanged and not self.has_shared_editions: + return registered + if ( match and match[1] == 4 and json.loads(match[3]).get("publication_source") == publication_source(match[2], content_sha).hex() ): + return registered + shared = {} + if self.has_shared_editions: + for pid, uri, value in self.db.execute( + "SELECT pid,uri,metadata FROM shared WHERE source=? AND member=?", (name, member) + ): + metadata = json.loads(value) + fingerprint = metadata.get("publication_source") + if fingerprint and fingerprint == publication_source(uri, content_sha).hex(): + return pid, 4, match is None + shared[pid] = metadata + if unchanged: + # Legacy workspaces may lack raw XML fingerprints. Require both + # a matching citation and the entire published set of text hashes. + for pid, metadata in shared.items(): + identifiers = [(meta.get(key), metadata.get(key)) for key in ("pmcid", "pmid")] + if ( + not metadata.get("publication_source") + and any(a and a == b for a, b in identifiers) + and not any(a and b and a != b for a, b in identifiers) + and articles.verified_article(self.mapping, pid, meta, self.settings[name]) + ): + return pid, 4, match is None + if unchanged: # The release records the actual owner of every included member. A # repeated filename can have an earlier or skipped, unrelated citation. - return match[:2] if match else None + return registered pmid, pmcid = meta.get("pmid") or None, meta.get("pmcid") or None owners = self.db.execute( "SELECT pid,pmid,pmcid FROM owners WHERE pmid=? OR pmcid=?", (pmid, pmcid) @@ -131,8 +170,10 @@ def resolve(self, name, member, meta, content_sha, unchanged): self.next_paper += 1 self.db.execute("INSERT INTO owners VALUES(?,?,?)", (pmid, pmcid, pid)) if match and match[0] == pid: - return match[:2] - return pid, 1 + return registered + if pid in shared: + return pid, 4, match is None + return pid, 1, True def ingest( self, @@ -152,12 +193,17 @@ def ingest( owner = self.resolve(name, member, meta, content_sha, unchanged) if owner is None: return - pid, priority = owner + pid, priority, register_file = owner else: pid, priority = cached_pid, 4 - registered = self.db.execute( - "INSERT OR IGNORE INTO files VALUES(?,?,?,?)", (uri, size, mtime, pid) - ) + file_owner = self.mapping.execute( + "SELECT paper_id FROM files WHERE source=? AND member=?", (name, member) + ).fetchone() + register_file = file_owner is None or file_owner[0] == pid + if register_file: + registered = self.db.execute( + "INSERT OR IGNORE INTO files VALUES(?,?,?,?)", (uri, size, mtime, pid) + ) previous = self.db.execute( "SELECT priority,verified,uri,content_sha FROM picked WHERE pid=?", (pid,) ).fetchone() @@ -187,7 +233,7 @@ def ingest( return rank = (priority, verified) earlier_owner = None - if not registered.rowcount: + if register_file and not registered.rowcount: earlier_owner = self.db.execute( """SELECT f.paper_id,p.priority,p.verified,p.uri FROM files f LEFT JOIN picked p ON p.pid=f.paper_id WHERE f.path=? AND f.paper_id<>?""", @@ -213,7 +259,10 @@ def ingest( "INSERT OR REPLACE INTO picked VALUES(?,?,?,?,?)", (pid, priority, verified, uri, content_sha), ) - self.db.execute("INSERT OR REPLACE INTO files VALUES(?,?,?,?)", (uri, size, mtime, pid)) + if register_file: + self.db.execute("INSERT OR REPLACE INTO files VALUES(?,?,?,?)", (uri, size, mtime, pid)) + else: + self.db.execute("UPDATE shared SET size=?,mtime=? WHERE pid=?", (size, mtime, pid)) if earlier_owner: self.reassigned_file = True previous_doc = None @@ -344,7 +393,9 @@ def read_sources(self, root): # A repeated filename may have temporarily supplied an unrelated # article before we saw the verified edition. Retain its genuine aliases. self.db.execute( - "CREATE TEMP TABLE unowned AS SELECT id FROM papers EXCEPT SELECT paper_id FROM files" + """CREATE TEMP TABLE unowned AS SELECT id FROM papers EXCEPT SELECT paper_id FROM files + EXCEPT SELECT e.pid FROM shared e JOIN picked p ON p.pid=e.pid + WHERE p.priority=4 AND p.verified>=2""" ) self.db.execute("DELETE FROM chunks WHERE paper_id IN (SELECT id FROM unowned)") self.db.execute("DELETE FROM papers WHERE id IN (SELECT id FROM unowned)") @@ -369,7 +420,8 @@ def read_cache(self, cache, root): metadata = json.loads(row[0]) if self.db.execute("SELECT 1 FROM picked WHERE pid=?", (pid,)).fetchone(): continue - config = articles.settings_for_article(self.mapping, pid, self.settings) + locations = articles.article_sources(self.mapping, pid) + config = articles.settings_for_article(pid, locations, self.settings) complete = None invalid = False primary = articles.cache_path(cache, self.manifest, pid) @@ -401,11 +453,7 @@ def read_cache(self, cache, root): self.report["invalid_cached_papers"].append(pid) continue meta, content_sha = complete - name, member = self.mapping.execute( - """SELECT f.source,f.member FROM files f JOIN articles a ON a.id=f.paper_id - WHERE a.id=? ORDER BY (f.original=a.current_file) DESC,f.original LIMIT 1""", - (pid,), - ).fetchone() + name, member = locations[0] uri = f"tar://{safe_path(root,name)}!/{member}" self.ingest(name, member, uri, 0, 0, meta, config, content_sha, cached_pid=pid) self.report["cached_papers"].append(pid) @@ -422,6 +470,12 @@ def read_cache(self, cache, root): def finish(self, release, paths): self.db.execute("DELETE FROM files WHERE paper_id NOT IN (SELECT id FROM papers)") + if self.has_shared_editions: + # A cached paper can be the only available occurrence of a shared path. + self.db.execute( + """INSERT OR IGNORE INTO files SELECT p.build_member,e.size,e.mtime,p.id FROM shared e + JOIN papers p ON p.id=e.pid ORDER BY e.pid""" + ) for table, original in (("papers", "articles"), ("chunks", "passages")): # Compare sorted streams in SQLite; no corpus-sized Python dictionaries. missing = self.report["missing_" + table] diff --git a/src/litkit/portable/search.py b/src/litkit/portable/search.py index 15f6ef7..81ab562 100644 --- a/src/litkit/portable/search.py +++ b/src/litkit/portable/search.py @@ -154,6 +154,7 @@ def download(identifier): return fetch_article(identifier) with readable_database(release / "mapping.sqlite3") as mapping: + articles.prepare_shared_editions(mapping) for rank, (cid, score) in enumerate(zip(ids, scores, strict=True)): row = mapping.execute( """SELECT p.paper_id,p.ord,p.digest,a.current_file,a.metadata FROM passages p @@ -168,7 +169,9 @@ def download(identifier): available = [] for pid, hits in by_paper.items(): metadata = json.loads(hits[0][-1]) - settings = articles.settings_for_article(mapping, pid, configs) + settings = articles.settings_for_article( + pid, articles.article_sources(mapping, pid), configs + ) try: by_ord = verified_hits( download, mapping, pid, metadata, settings, manifest, cache, hits diff --git a/tests/integration/test_portable_restore.py b/tests/integration/test_portable_restore.py index 9dc94a5..a2f2a99 100644 --- a/tests/integration/test_portable_restore.py +++ b/tests/integration/test_portable_restore.py @@ -475,6 +475,7 @@ def fetch(identifier): single = search_vectors(release, query, limit=1, **options) assert not single["unavailable"] and [p["text"] for p in single["passages"]] == [query] assert calls == ["PMC31", "718"] + result = search_vectors(release, query, limit=20, **options) assert not result["unavailable"] assert {p["ord"] for p in result["passages"]} == {-1, 0, 1, 2, 3} @@ -495,6 +496,125 @@ def fetch(identifier): assert calls == ["PMC31", "718"] +@pytest.mark.parametrize( + ("licenses", "older_catalog"), [([], False), (["CC-BY-4.0"], False), ([], True)] +) +def test_two_published_papers_keep_editions_at_the_same_member( + tmp_path, monkeypatch, licenses, older_catalog +): + import json + + from test_build_and_query import _ok, litkit + + from conftest import FakeEmbedder + from litkit.portable import articles + from litkit.portable.restore import rebuild_from_vectors + from litkit.portable.search import search_vectors + + sources, workspace = tmp_path / "sources", tmp_path / "original" + sources.mkdir() + + def xml(identifier, title, license_code): + return licensed_article( + identifier, title, license_code, ("Findings from " + title + ". ") * 50 + ) + + first = xml("PMC111", "Second edition A", "by") + second = xml("PMC222", "Third edition of B here", "by-nc") + write_tar( + sources / "old.tar", + {"a.xml": xml("PMC111", "Old A", "by"), "b.xml": xml("PMC222", "Old B", "by-nc")}, + ) + _ok( + litkit( + workspace, + "--build-only", + "--faiss-writer", + "--tar-dir", + str(sources), + "--papers-index", + "flat", + "--chunks-index", + "flat", + ) + ) + write_tar(sources / "revisions.tar", [("same.xml", first), ("same.xml", second)]) + _ok( + litkit( + workspace, + "--build-only", + "--faiss-writer", + "--tar-dir", + str(sources), + "--papers-index", + "flat", + "--chunks-index", + "flat", + "--chunk-target-chars", + "500", + ) + ) + with closing(sqlite3.connect(workspace / "sqlite/litkit.sqlite3")) as db: + if older_catalog: + db.execute("UPDATE papers SET publication_source=NULL") + db.commit() + published = db.execute( + "SELECT id,pmcid,title,build_member FROM papers ORDER BY id" + ).fetchall() + assert len(published) == 2 and published[0][3] == published[1][3] + assert db.execute( + "SELECT paper_id FROM files WHERE path=?", (published[0][3],) + ).fetchone() == (published[1][0],) + expected = published[:1] if licenses else published + release, restored = tmp_path / "release", tmp_path / "restored" + manifest = export_vectors(workspace, release, licenses=licenses, settings=MODELS) + if older_catalog: + with closing(sqlite3.connect(release / "mapping.sqlite3")) as mapping: + mapping.execute("DROP TABLE shared_editions") + mapping.commit() + manifest["checksums"]["mapping.sqlite3"] = file_hash(release / "mapping.sqlite3") + (release / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8") + assert {s["name"] for s in manifest["sources"]} == {"old.tar", "revisions.tar"} + monkeypatch.setattr( + articles, "load_model", lambda *_: pytest.fail("unchanged members loaded a model") + ) + assert not any(rebuild_from_vectors(release, sources, restored).values()) + for kind in ("papers", "chunks"): + assert file_hash(release / f"{kind}.faiss") == file_hash(restored / f"indices/{kind}.faiss") + with closing(sqlite3.connect(restored / "sqlite/litkit.sqlite3")) as db: + assert ( + db.execute("SELECT id,pmcid,title,build_member FROM papers ORDER BY id").fetchall() + == expected + ) + assert db.execute( + "SELECT paper_id FROM files WHERE path=?", (published[0][3],) + ).fetchone() == (expected[-1][0],) + write_tar( + sources / "revisions.tar", [("same.xml", first), ("same.xml", second), ("note.txt", "new")] + ) + drifted = tmp_path / "drifted" + drift = rebuild_from_vectors(release, sources, drifted) + assert drift.pop("changed_sources") == ["revisions.tar"] and not any(drift.values()) + monkeypatch.setattr(articles, "load_model", lambda *_: FakeEmbedder()) + options = dict( + cache=tmp_path / "cache", + limit=20, + fetch=lambda i: (first if i == "PMC111" else second).encode(), + ) + hits = search_vectors(release, "findings", **options) + assert not hits["unavailable"] and {h["pmcid"] for h in hits["passages"]} == { + r[1] for r in expected + } + empty = tmp_path / "empty" + empty.mkdir() + recovered = tmp_path / "from-cache" + report = rebuild_from_vectors(release, empty, recovered, cache=options["cache"]) + assert sorted(report["cached_papers"]) == [r[0] for r in expected] + assert file_hash(release / "chunks.faiss") == file_hash(recovered / "indices/chunks.faiss") + exported_again = export_vectors(recovered, tmp_path / "from-cache-release", settings=MODELS) + assert [source["name"] for source in exported_again["sources"]] == ["revisions.tar"] + + def test_pmids_without_pmc_full_text_can_be_fetched_and_cached(tmp_path, monkeypatch): from test_build_and_query import _ok, litkit