diff --git a/CHANGELOG.md b/CHANGELOG.md index 5aa9c71..95f98a7 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) - `litkit build-fts` indexes passage text for exact search. The optional index stays current through updates, rebuilds and shard merges. (#56) diff --git a/README.md b/README.md index eabf022..d739a13 100644 --- a/README.md +++ b/README.md @@ -255,3 +255,24 @@ name. For example, `{"sources":{"old.tar":{"chunk_overlap":100}}}` fills that archive's missing overlap setting. Supply all unrecorded fields for legacy archives. Recorded settings must agree with the values supplied for that archive. Use `--source-root DIR` when the legacy archives have moved. + +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 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 +articles that are missing from the bulk sources. diff --git a/src/litkit/cli.py b/src/litkit/cli.py index f96e85a..b0875c6 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1845,7 +1845,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 @@ -1908,6 +1908,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" " litkit build-fts [--workspace DIR] Index passage text for exact search\n" "Progressive retrieval subcommands (all support --json, --limit, --max-chars):\n" " litkit search-papers [query] Stage-1 / metadata search with filters\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/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 new file mode 100644 index 0000000..25dace1 --- /dev/null +++ b/src/litkit/portable/articles.py @@ -0,0 +1,174 @@ +"""Read and verify article inputs for local rebuilds and on-demand passage search.""" + +from __future__ import annotations + +import hashlib +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.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 + + +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 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 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() + ) + + +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] + + +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 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 + ) + 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: + temporary = Path(handle.name) + try: + temporary.write_bytes(raw) + os.replace(temporary, path) + finally: + temporary.unlink(missing_ok=True) + + +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 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/release.py b/src/litkit/portable/release.py index 6002550..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); """ @@ -255,6 +257,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" @@ -357,7 +369,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 ): @@ -368,11 +380,38 @@ 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)) + # 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. + # 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]) 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}, @@ -436,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 new file mode 100644 index 0000000..c41e7a5 --- /dev/null +++ b/src/litkit/portable/restore.py @@ -0,0 +1,569 @@ +"""Reconstruct a searchable workspace from a portable release and local source archives.""" + +from __future__ import annotations + +import hashlib +import json +import shutil +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.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 ( + check_index_metadata, + 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.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 + ] + 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", + "invalid_cached_papers", + ) + } + db.execute("PRAGMA temp_store=FILE") + 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, 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( + "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) + 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.""" + match = self.mapping.execute( + """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() + 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 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) + ).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 registered + if pid in shared: + return pid, 4, match is None + return pid, 1, True + + def ingest( + self, + name, + member, + uri, + size, + mtime, + meta, + settings, + content_sha, + *, + cached_pid=None, + unchanged=False, + ): + if cached_pid is None: + owner = self.resolve(name, member, meta, content_sha, unchanged) + if owner is None: + return + pid, priority, register_file = owner + else: + pid, priority = cached_pid, 4 + 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() + old = self.mapping.execute( + "SELECT doc_id,metadata,digest,current_file FROM articles WHERE id=?", (pid,) + ).fetchone() + 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 = 3 + elif old and articles.verified_article(self.mapping, pid, meta, settings): + # A historical alias can have the same XML with different chunk settings. + 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: + priority = 3 + if not priority: + return + rank = (priority, verified) + earlier_owner = None + 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<>?""", + (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 + 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), + ) + 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 + 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 + 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=?", (doc_id,)).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") + } + 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")} + ) + 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" + ) + ), + ) + 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)})", + 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 = self.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"] + identity = archive_identity(path) + checksum, size = archive_checksum(path, expected=identity) + 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(?,?,?,?)", + (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, + 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 + 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)") + 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"): + number = path.stem.partition(".")[0] + if not number.isascii() or not number.isdigit() or len(number) > 19: + continue + pid = int(number) + if pid > 2**63 - 1 or pid in checked: + continue + checked.add(pid) + row = self.mapping.execute( + "SELECT metadata,current_file FROM articles WHERE id=?", (pid,) + ).fetchone() + if row is None: + continue + metadata = json.loads(row[0]) + if self.db.execute("SELECT 1 FROM picked WHERE pid=?", (pid,)).fetchone(): + continue + 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) + 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 = 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) + record = self.sources[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)") + 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] + 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" + 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) + check_index_metadata(index, self.manifest["indices"][table], source.name) + if not (missing or changed or new): + del index + continue + 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") + write_index(index, target) + del index + + +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..81ab562 --- /dev/null +++ b/src/litkit/portable/search.py @@ -0,0 +1,237 @@ +"""Fetch and verify only the articles selected by a vector query.""" + +from __future__ import annotations + +import hashlib +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.index.io import faiss_load_cached +from litkit.portable import articles +from litkit.portable.record import file_hash +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 + + +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() + + +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 = {} + if not isinstance(prior, dict): + prior = {} + checked = {} + # 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 = [ + expected, + stat.st_dev, + stat.st_ino, + stat.st_size, + stat.st_mtime_ns, + stat.st_ctime_ns, + ] + 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 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") + + 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) + collect(raw, meta, identifier) + articles.write_cached_article(candidate, raw) + except (OSError, ValueError) as exc: + error = exc + 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): + 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 = {} + 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: + 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 + 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, member, metadata = row + hits = by_paper.setdefault(pid, []) + hits.append((rank, cid, ordinal, checksum, score, member, metadata)) + available = [] + for pid, hits in by_paper.items(): + metadata = json.loads(hits[0][-1]) + 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 + ) + except (OSError, URLError, ValueError) as error: + result["unavailable"].append( + { + "paper_id": pid, + "pmcid": metadata.get("pmcid"), + "pmid": metadata.get("pmid"), + "title": metadata.get("title"), + "reason": str(error), + } + ) + continue + for rank, cid, ordinal, _, score, _, _ in hits: + passage = by_ord.get(ordinal) + if passage is None: + result["unavailable"].append( + { + "paper_id": pid, + "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", + } + ) + continue + text, page, section, provenance = passage + available.append( + ( + rank, + dict( + paper_id=pid, + chunk_id=cid, + ord=ordinal, + text=text, + page=page, + section=section, + score=score, + **provenance, + ), + ) + ) + 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 758b480..2cfbf0e 100644 --- a/src/litkit/retrieval/cli_commands.py +++ b/src/litkit/retrieval/cli_commands.py @@ -260,10 +260,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( @@ -406,7 +406,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 @@ -414,7 +414,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..a2f2a99 --- /dev/null +++ b/tests/integration/test_portable_restore.py @@ -0,0 +1,721 @@ +"""CPU rebuild, source drift and on-demand retrieval from a portable release.""" + +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 + +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 + 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() + # 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") + ) + 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 _, 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): + 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() + + +@pytest.mark.parametrize("well_formed", [False, True]) +def test_corrupt_cached_xml_is_recovered_online_and_reported_offline( + tmp_path, portable_source, monkeypatch, well_formed +): + 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( + bad.read_bytes().replace(b"Private passage", b"Damaged passage") + if well_formed + else 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"] + + +@pytest.mark.parametrize("metadata_only", [False, True]) +def test_repeated_member_name_restores_the_published_edition(tmp_path, monkeypatch, metadata_only): + 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 / "original" + sources.mkdir() + title = "Published study" + first_title = title if metadata_only else "Earlier report" + first = licensed_article("PMC31", first_title, "by", "An observation.") + last = licensed_article("PMC31", title, "by-nc", "An observation.") + write_tar(sources / "papers.tar", [("same.xml", first), ("same.xml", last)]) + _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) + monkeypatch.setattr( + articles, "load_model", lambda *_: pytest.fail("Matching archive needed embeddings") + ) + assert not any(rebuild_from_vectors(release, sources, restored).values()) + for ws in (workspace, restored): + with closing(sqlite3.connect(ws / "sqlite/litkit.sqlite3")) as db: + assert db.execute("SELECT title,license FROM papers").fetchall() == [ + (title, "CC-BY-NC-4.0") + ] + + +def test_on_demand_tries_other_identifier_after_valid_but_changed_xml(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.restore import rebuild_from_vectors + from litkit.portable.search import search_vectors + + sources, workspace = tmp_path / "sources", tmp_path / "original" + sources.mkdir() + # A JATS abstract-only record can also be reproduced from its PubMed citation. + title, abstract = "A current title", "Time series in cells." + original = jats(pmid="718", pmcid="PMC31", title=title, abstract=abstract) + write_tar(sources / "papers.tar", {"one.xml": original}) + _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()) + called = [] + + def fetch(identifier): + called.append(identifier) + if identifier == "PMC31": + return original.replace(title, "A different title").encode() + return pubmed_xml("718", title, abstract).encode() + + options = dict(cache=tmp_path / "cache", fetch=fetch) + hits = search_vectors(release, "cells", **options) + 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"] + + +@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 + + 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() + + +def test_cached_search_validates_changed_index_metadata_before_returning_empty( + tmp_path, portable_source +): + import json + + from litkit.portable.search import search_vectors, verified_manifest + + workspace, _ = portable_source + release, cache = tmp_path / "release", tmp_path / "cache" + manifest = export_vectors(workspace, release, settings=MODELS) + verified_manifest(release, cache) + manifest["indices"]["chunks"]["count"] = 0 + (release / "manifest.json").write_text(json.dumps(manifest)) + with pytest.raises(ValueError, match="metadata disagrees with chunks.faiss"): + search_vectors(release, "sample", cache=cache) 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() diff --git a/tests/test_index.py b/tests/test_index.py index 0d89ce3..b968e11 100644 --- a/tests/test_index.py +++ b/tests/test_index.py @@ -481,11 +481,12 @@ def test_faiss_load_cached_reloads_after_file_changes(tmp_path, faiss_lock, unit index_io.clear_faiss_cache() assert index_io.faiss_load_cached(path).ntotal == 0 assert index_io.faiss_load_cached(path) is index_io.faiss_load_cached(path) + original_mtime = path.stat().st_mtime_ns a.add(unit_vectors(3, DIM)) with faiss_lock(): index_io.faiss_save_force(a, path) - # The cache key is (path, mtime_ns); bump mtime in case both saves share a tick. + # A copied release can retain the previous file's modification time. st = path.stat() - os.utime(path, ns=(st.st_atime_ns, st.st_mtime_ns + 1_000_000)) + os.utime(path, ns=(st.st_atime_ns, original_mtime)) assert index_io.faiss_load_cached(path).ntotal == 3 index_io.clear_faiss_cache()