From 9c60abd048088dfffcf62512dfc509cd6bf9cec8 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Fri, 4 Dec 2026 14:42:35 -0700 Subject: [PATCH 1/4] Record build provenance and export text-free FAISS releases Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 3 + README.md | 21 ++ src/litkit/build/helpers.py | 17 + src/litkit/build/ingest_loop.py | 34 +- src/litkit/build/publication.py | 2 +- src/litkit/cli.py | 6 + src/litkit/db/schema.py | 7 +- src/litkit/db/sharding.py | 15 +- src/litkit/embeddings/sbert_mpnet.py | 3 + src/litkit/embeddings/specter2.py | 1 + src/litkit/ingest/ingest.py | 9 + src/litkit/portable/__init__.py | 1 + src/litkit/portable/cli.py | 39 +++ src/litkit/portable/record.py | 78 +++++ src/litkit/portable/release.py | 341 +++++++++++++++++++++ tests/integration/test_batch_resume.py | 4 +- tests/integration/test_portable_vectors.py | 92 ++++++ 17 files changed, 648 insertions(+), 25 deletions(-) create mode 100644 src/litkit/portable/__init__.py create mode 100644 src/litkit/portable/cli.py create mode 100644 src/litkit/portable/record.py create mode 100644 src/litkit/portable/release.py create mode 100644 tests/integration/test_portable_vectors.py diff --git a/CHANGELOG.md b/CHANGELOG.md index a4eb5e3..caea5ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ internal versions are summarized under 0.3.33. ## [Unreleased] +### Added +- `litkit export-vectors` writes FAISS indexes, text hashes, source checksums, model revisions and per-paper attribution. Use `--license` to select licenses. (#65) + ### Fixed - Concurrent SQLite opens wait for a WAL mode switch up to the configured busy timeout. (#52) - macOS builds and queries pin OpenMP and MKL to one thread before loading FAISS and torch, including when the shell requests more. (#53) diff --git a/README.md b/README.md index 7ca2199..9fc5a4b 100644 --- a/README.md +++ b/README.md @@ -216,3 +216,24 @@ derivative works, distribute copies to the public, perform publicly and display others to do so. LANL software release O5068. + +## Vector releases + +`litkit export-vectors RELEASE --workspace WORKSPACE` writes the FAISS files, +a SQLite mapping from vector IDs to documents and hashed passages, source +checksums and build settings in `manifest.json`, and paper citations and +licenses in `attribution.jsonl`. The release omits abstracts and passage text. +Pass `--license CC-BY-4.0` to include papers with that license. Repeat the +option for more licenses. Articles without a license have the label `unknown`. + +New builds record each archive's SHA-256, chunk and table settings, LitKit +version and model snapshot revisions. For a legacy workspace, supply a JSON +file with `--settings` and make its source archives available. The file uses +the fields below. Substitute the actual model revisions and build options. + +```json +{"litkit_version":"0.4.0","chunk_target_chars":1200,"chunk_min_chars":300, + "chunk_overlap":200,"include_tables":false,"max_table_chars":4000, + "paper_model":{"name":"allenai/specter2_base","revision":"PAPER_COMMIT"}, + "chunk_model":{"name":"sentence-transformers/all-mpnet-base-v2","revision":"CHUNK_COMMIT"}} +``` diff --git a/src/litkit/build/helpers.py b/src/litkit/build/helpers.py index 5353c87..c6dd5ea 100644 --- a/src/litkit/build/helpers.py +++ b/src/litkit/build/helpers.py @@ -133,6 +133,23 @@ def pack_body(meta: ArticleMeta, max_chars: int, min_chars: int, overlap_chars: return chunks +def paper_input(meta): + title = (meta.get("title") or "").strip() + abstract = (meta.get("abstract") or "").strip() + return (title + " " + abstract).strip() or ( + meta["paragraphs"][0][:800] if meta["paragraphs"] else "untitled" + ) + + +def article_passages(meta, paper_text, target, minimum, overlap): + """Yield the stable ordinal, text, page, section and citations for each vector.""" + abstract_refs = tuple(dict.fromkeys(rid for _, _, rid in meta.get("abstract_citations", []))) + if paper_text: + yield -1, paper_text, None, "Abstract" if (meta.get("abstract") or "").strip() else None, abstract_refs + for ordinal, chunk in enumerate(pack_body(meta, target, minimum, overlap)): + yield ordinal, chunk[0], chunk[1], getattr(chunk, "section", None), getattr(chunk, "citations", ()) + + def dedupe_papers_with_doc_ids( ids: list[int], texts: list[str], doc_ids: list[str], *, keep_last: bool = False ) -> tuple[list[int], list[str], list[str]]: diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index 108d284..f056920 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -19,6 +19,7 @@ import faiss from litkit.progress import eprint as _eprint +from litkit.portable.record import SOURCE_SCHEMA, source_record, settings_record from litkit.embeddings.base import ( progress_newline as _progress_newline, progress_write as _progress_write, @@ -56,7 +57,8 @@ from litkit.db.sharding import producer_shard_lock from litkit.segments.metadata import verify_legacy_shard from litkit.build.helpers import ( - pack_body, + article_passages, + paper_input, dedupe_papers_with_doc_ids, dedupe_chunks_with_doc_ids, ) @@ -409,6 +411,9 @@ def stage_indexes(paper_dir, chunk_dir): revised_shard_papers.clear() def process_tar(tpath: Path) -> None: + provenance = None + source_settings = settings_record(chunk_target_chars, chunk_min_chars, chunk_overlap, include_tables, + max_table_chars, paper_embedder, chunk_embedder) rebuilding_tar = str(tpath) in rebuild_tars # Number of *persisted* members previously processed for this tar shard start_persisted = int(ckpt_stream.get(str(tpath), 0)) @@ -536,6 +541,10 @@ def _render(force: bool = False): # SLOW PATH - Savepoint-protected writes # ═══════════════════════════════════════════════════════════════════ + if provenance is None and tpath.is_file(): + provenance = source_record(tpath, source_settings) + conn.execute(SOURCE_SCHEMA) + # Snapshot buffer lengths BEFORE processing so we can truncate on rollback buf_snapshot = ( len(paper_ids_buf), @@ -627,11 +636,7 @@ def _render(force: bool = False): db_register_file(cur, str(f), pid, st) - ta = (meta["title"] or "").strip() - ab = (meta["abstract"] or "").strip() - ta_ab = (ta + " " + ab).strip() or ( - meta["paragraphs"][0][:800] if meta["paragraphs"] else "untitled" - ) + ta_ab = paper_input(meta) # Rebuilds keep the first canonical paper embedding, including # when an alias arrives after its original batch was published. # Updates still embed revised text received under a new path. @@ -696,20 +701,17 @@ def _render(force: bool = False): ), ) + if provenance: + cur.execute("INSERT OR IGNORE INTO build_sources VALUES (?,?,?,?)", provenance) + cur.execute("UPDATE papers SET license=?,license_url=?,build_member=? WHERE id=?", + (meta.get("license"), meta.get("license_url"), f, pid)) bibliography = meta.get("references") cur.execute("UPDATE papers SET references_json=? WHERE id=?", ( json.dumps(bibliography, ensure_ascii=False) if bibliography is not None else None, pid, )) - body = pack_body(meta, chunk_target_chars, chunk_min_chars, chunk_overlap) - abstract_section = "Abstract" if ab else None - abstract_refs = tuple(dict.fromkeys(rid for _, _, rid in meta.get("abstract_citations", []))) - proposed_chunks = [(-1, ta_ab, None, abstract_section, abstract_refs)] if ta_ab else [] - proposed_chunks.extend( - (i, item[0], item[1], getattr(item, "section", None), getattr(item, "citations", ())) - for i, item in enumerate(body) - ) - - for ord_i, text_i, page, section, refs in proposed_chunks: + for ord_i, text_i, page, section, refs in article_passages( + meta, ta_ab, chunk_target_chars, chunk_min_chars, chunk_overlap + ): cur.execute( "INSERT INTO chunks(paper_id, ord, text, page, section, cited_refs) VALUES (?,?,?,?,?,?)", (pid, ord_i, text_i, page, section, json.dumps(refs) if refs else None), diff --git a/src/litkit/build/publication.py b/src/litkit/build/publication.py index 4bb741c..3107a53 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -32,7 +32,7 @@ def reset_publication(conn: sqlite3.Connection, sqlite_dir: Path, seg_dir: Path) if read_publication(conn): conn.execute("UPDATE ingest_publication SET tar=NULL WHERE singleton=1") - for table in ("merged_paper_revisions", "obsolete_chunk_vectors"): + for table in ("merged_paper_revisions", "obsolete_chunk_vectors", "build_sources"): if conn.execute("SELECT 1 FROM sqlite_master WHERE name=?", (table,)).fetchone(): conn.execute(f"DELETE FROM {table}") if conn.execute("SELECT 1 FROM sqlite_master WHERE name='merged_shard_checkpoints'").fetchone(): diff --git a/src/litkit/cli.py b/src/litkit/cli.py index f058fa3..8f1d21a 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1844,6 +1844,11 @@ def main(): sys.stderr.write("[env] Python >= 3.10 required.\n") sys.exit(2) + if sys.argv[1:2] == ["export-vectors"]: + from litkit.portable.cli import main as portable_main + portable_main(sys.argv[1:]) + return + # Dispatch progressive retrieval subcommands before loading heavy dependencies. _progressive_cmds = frozenset( { @@ -1876,6 +1881,7 @@ def main(): ap = argparse.ArgumentParser( 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" "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/db/schema.py b/src/litkit/db/schema.py index eaa8d33..a073ea5 100644 --- a/src/litkit/db/schema.py +++ b/src/litkit/db/schema.py @@ -44,7 +44,8 @@ in_index INTEGER DEFAULT 0, -- Paper vector input when multiple versions share an ID embedding_text TEXT, - references_json TEXT + references_json TEXT, + license TEXT, license_url TEXT, build_member TEXT ); CREATE TABLE IF NOT EXISTS chunks ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -89,7 +90,7 @@ def optional_paper_columns( prefix = f"{alias}." if alias else "" return { name: (f"{prefix}{name}" if name in cols else "NULL") - for name in ("doc_id", "source_path", "doi", "year", "authors", "journal", "references_json") + for name in ("doc_id", "source_path", "doi", "year", "authors", "journal", "references_json", "license", "license_url", "build_member") } @@ -237,6 +238,8 @@ def ensure_paper_embedding_column(conn: sqlite3.Connection) -> None: _ADDED_COLUMNS = ( + ("papers", "license", "TEXT"), ("papers", "license_url", "TEXT"), + ("papers", "build_member", "TEXT"), ("papers", "references_json", "TEXT"), ("chunks", "cited_refs", "TEXT"), ("papers", "in_index", "INTEGER DEFAULT 0"), diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index 052447a..15e702c 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -227,6 +227,7 @@ def _merge_revised_papers(conn, shard, mapping, since): revisions = conn.execute(f""" SELECT m.main_pid, p.id, dest.doc_id, p.pmid, p.pmcid, p.title, p.abstract, {p_cols['source_path']}, {p_cols['doi']}, {p_cols['year']}, {p_cols['authors']}, {p_cols['journal']}, {p_cols['references_json']}, + {p_cols['license']}, {p_cols['license_url']}, {p_cols['build_member']}, COALESCE(p.embedding_text, (SELECT c.text FROM {shard}.chunks c WHERE c.paper_id=p.id AND c.ord=-1 ORDER BY c.id DESC LIMIT 1)) FROM {shard}.papers p JOIN {mapping} m ON m.shard_pid=p.id @@ -250,6 +251,7 @@ def _merge_revised_papers(conn, shard, mapping, since): authors, journal, references_json, + license_name, license_url, build_member, embedding_text, ) in revisions: pmid, pmcid = available_citation_ids(doc_id, pmid, pmcid, conn) @@ -258,13 +260,13 @@ def _merge_revised_papers(conn, shard, mapping, since): UPDATE papers SET in_index=CASE WHEN COALESCE(embedding_text, (SELECT text FROM chunks WHERE paper_id=:id AND ord=-1 ORDER BY id DESC LIMIT 1) ) IS :input THEN in_index ELSE 0 END, - title=:title, abstract=:abstract, source_path=:source, embedding_text=:input, references_json=:refs, + title=:title, abstract=:abstract, source_path=:source, embedding_text=:input, references_json=:refs, license=:license, license_url=:url, build_member=:member, doi=COALESCE(NULLIF(:doi,''), doi), year=COALESCE(:year, year), authors=COALESCE(NULLIF(:authors,''), authors), journal=COALESCE(NULLIF(:journal,''), journal), pmid=COALESCE(NULLIF(pmid,''), :pmid), pmcid=COALESCE(NULLIF(pmcid,''), :pmcid) WHERE id=:id - """, {"title": title, "abstract": abstract, "source": source_path, "input": embedding_text, "refs": references_json, + """, {"title": title, "abstract": abstract, "source": source_path, "input": embedding_text, "refs": references_json, "license": license_name, "url": license_url, "member": build_member, "doi": doi, "year": year, "authors": authors, "journal": journal, "id": main_id, "pmid": pmid, "pmcid": pmcid}) inserted += conn.execute(f""" @@ -370,14 +372,19 @@ def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge, to_record): embedding_text = paper_embedding_column(main_conn, shard_alias) + if main_cur.execute(f"SELECT 1 FROM {shard_alias}.sqlite_master WHERE name='build_sources'").fetchone(): + from litkit.portable.record import SOURCE_SCHEMA + main_cur.execute(SOURCE_SCHEMA) + main_cur.execute(f"INSERT OR IGNORE INTO build_sources SELECT * FROM {shard_alias}.build_sources") # 1) BULK MERGE PAPERS # Insert papers that don't already exist (by doc_id) main_cur.execute(f""" INSERT OR IGNORE INTO papers( - doc_id, pmid, pmcid, doi, year, authors, journal, title, abstract, source_path, embedding_text, references_json, in_index + doc_id, pmid, pmcid, doi, year, authors, journal, title, abstract, source_path, embedding_text, references_json, license, license_url, build_member, in_index ) SELECT p.doc_id, p.pmid, p.pmcid, {p_cols['doi']}, {p_cols['year']}, {p_cols['authors']}, {p_cols['journal']}, - p.title, p.abstract, {source_path}, {embedding_text}, {p_cols['references_json']}, 0 + p.title, p.abstract, {source_path}, {embedding_text}, {p_cols['references_json']}, + {p_cols['license']}, {p_cols['license_url']}, {p_cols['build_member']}, 0 FROM {shard_alias}.papers p WHERE p.doc_id IS NOT NULL AND p.doc_id != '' diff --git a/src/litkit/embeddings/sbert_mpnet.py b/src/litkit/embeddings/sbert_mpnet.py index 1a5dd19..72cf7f2 100644 --- a/src/litkit/embeddings/sbert_mpnet.py +++ b/src/litkit/embeddings/sbert_mpnet.py @@ -50,8 +50,11 @@ 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.revision = model_path.name + # Multi-GPU only when >1 CUDA device multi_gpu = len(self.devices) > 1 and self.devices[0].startswith("cuda") options = safe_weight_options(model_path) diff --git a/src/litkit/embeddings/specter2.py b/src/litkit/embeddings/specter2.py index 3dadd98..09c5052 100644 --- a/src/litkit/embeddings/specter2.py +++ b/src/litkit/embeddings/specter2.py @@ -40,6 +40,7 @@ def __init__( self.model_id = model_id self.device = device or detect_device() local_path = local_snapshot_dir(self.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/ingest/ingest.py b/src/litkit/ingest/ingest.py index 0fcc6c4..fa891b8 100644 --- a/src/litkit/ingest/ingest.py +++ b/src/litkit/ingest/ingest.py @@ -114,6 +114,8 @@ class ArticleMeta(TypedDict): abstract: str paragraphs: list[str] source_path: NotRequired[str] + license: NotRequired[str] + license_url: NotRequired[str] references: NotRequired[list[dict[str, str]]] paragraph_citations: NotRequired[dict[int, list[tuple[int, int, str]]]] abstract_citations: NotRequired[list[tuple[int, int, str]]] @@ -1134,6 +1136,13 @@ def _walk_root(node: etree._Element) -> None: "abstract": abstract or "", "paragraphs": paras, } + from litkit.portable.record import jats_license + + license_name, license_url = jats_license(root.find("{*}front/{*}article-meta")) + if license_name: + meta["license"] = license_name + if license_url: + meta["license_url"] = license_url if references is not None: meta["references"] = references if paragraph_citations: diff --git a/src/litkit/portable/__init__.py b/src/litkit/portable/__init__.py new file mode 100644 index 0000000..7b23c32 --- /dev/null +++ b/src/litkit/portable/__init__.py @@ -0,0 +1 @@ +"""Vector release, source reconstruction and on-demand retrieval.""" diff --git a/src/litkit/portable/cli.py b/src/litkit/portable/cli.py new file mode 100644 index 0000000..3350a63 --- /dev/null +++ b/src/litkit/portable/cli.py @@ -0,0 +1,39 @@ +"""Command-line interface to portable LitKit vector releases.""" + +import argparse +import json +import sqlite3 +from pathlib import Path + +from litkit.config.paths import WorkspacePaths + + +def main(argv): + 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( + "--license", + dest="licenses", + action="append", + default=[], + help="Include this exact license label (repeatable)", + ) + parser.add_argument("--settings", type=Path, help="JSON build settings for legacy workspaces") + parser.add_argument("--source-root", type=Path, help="Location of relocated legacy archives") + args = parser.parse_args(argv[1:]) + try: + paths = WorkspacePaths.from_env_or_default(workspace_override=args.workspace) + settings = json.loads(args.settings.read_text(encoding="utf-8")) if args.settings else None + result = export_vectors( + paths.workspace, + args.output, + licenses=args.licenses, + settings=settings, + source_root=args.source_root, + ) + print(json.dumps(result)) + except (OSError, sqlite3.Error, ValueError, RuntimeError, KeyError) as error: + parser.exit(1, f"{parser.prog}: {error}\n") diff --git a/src/litkit/portable/record.py b/src/litkit/portable/record.py new file mode 100644 index 0000000..9965df1 --- /dev/null +++ b/src/litkit/portable/record.py @@ -0,0 +1,78 @@ +"""Build inputs needed to reproduce an article's passages and embeddings.""" + +from __future__ import annotations + +import hashlib +import json +import re +from pathlib import Path + +from litkit import __version__ + +SOURCE_SCHEMA = """CREATE TABLE IF NOT EXISTS build_sources( + path TEXT NOT NULL, sha256 TEXT NOT NULL, size INTEGER NOT NULL, + settings TEXT NOT NULL, PRIMARY KEY(path, sha256, settings))""" + + +def file_hash(path): + with Path(path).open("rb") as file: + return hashlib.file_digest(file, "sha256").hexdigest() + + +def model_record(embedder): + if embedder is None: + return None + return { + "name": getattr(embedder, "model_id", None), + "revision": getattr(embedder, "revision", None), + } + + +def settings_record(target, minimum, overlap, tables, table_limit, paper, chunk): + return dict( + litkit_version=__version__, + chunk_target_chars=target, + chunk_min_chars=minimum, + chunk_overlap=overlap, + include_tables=tables, + max_table_chars=table_limit, + paper_model=model_record(paper), + chunk_model=model_record(chunk), + ) + + +def source_record(path, settings): + path = Path(path) + before = path.stat() + digest = file_hash(path) + after = path.stat() + if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns): + raise ValueError(f"Source changed while recording its checksum: {path}") + return str(path), digest, after.st_size, json.dumps(settings, sort_keys=True) + + +def jats_license(meta): + """Return an article's license label and URL from its own permissions.""" + if meta is None: + return None, None + for node in meta.findall("{*}permissions/{*}license"): + href = node.get("{http://www.w3.org/1999/xlink}href") or node.get("href") + if not href: + link = node.find(".//{*}ext-link") + if link is not None: + href = link.get("{http://www.w3.org/1999/xlink}href") + if href and ( + cc := re.match( + r"https?://(?:www\.)?creativecommons\.org/(licenses|publicdomain)/([\w-]+)/(\d+\.\d+)(?:/|$)", + href, + re.I, + ) + ): + if cc[1].lower() == "licenses": + return "CC-" + cc[2].upper() + "-" + cc[3], href + if cc[2].lower() == "zero": + return "CC0-" + cc[3], href + label = node.get("license-type") or " ".join(" ".join(node.itertext()).split()) + if label or href: + return label or "other", href + return None, None diff --git a/src/litkit/portable/release.py b/src/litkit/portable/release.py new file mode 100644 index 0000000..cf02cb7 --- /dev/null +++ b/src/litkit/portable/release.py @@ -0,0 +1,341 @@ +"""Export a text-free catalog and matching FAISS files from a completed workspace.""" + +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import sqlite3 +import tempfile +from contextlib import closing, contextmanager +from pathlib import Path + +import faiss +import numpy as np + +from litkit.concurrent.locking import LockManager +from litkit.config.paths import WorkspacePaths +from litkit.db.handoff import readable_database +from litkit.db.publication import read_publication +from litkit.db.schema import get_stage1_mode, table_columns +from litkit.index.ids import copy_hnsw_without_ids, make_id_selector, safe_remove_ids +from litkit.index.introspection import kind_and_core +from litkit.portable.record import file_hash + +FORMAT_VERSION = 1 +PAPER_FIELDS = ( + "doc_id", + "pmid", + "pmcid", + "doi", + "title", + "year", + "authors", + "journal", + "source_path", + "license", + "license_url", + "article_type", + "publication_types", + "retracted", +) +CATALOG = """ +CREATE TABLE articles(id INTEGER PRIMARY KEY, doc_id TEXT UNIQUE NOT NULL, metadata TEXT NOT NULL, + digest TEXT NOT NULL, current_file TEXT); +CREATE TABLE passages(id INTEGER PRIMARY KEY, paper_id INTEGER NOT NULL, ord INTEGER NOT NULL, + digest TEXT NOT NULL, UNIQUE(paper_id,ord)); +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); +""" + + +def digest(text): + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +@contextmanager +def new_directory(destination): + """Publish only a completed release or workspace. A failed attempt can be retried.""" + destination = Path(destination).resolve() + if destination.exists(): + raise FileExistsError(f"Choose a new output directory: {destination}") + destination.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix=".litkit-", dir=destination.parent) as temporary: + stage = Path(temporary) / "output" + stage.mkdir() + yield stage + stage.rename(destination) + + +def archive_member(uri): + archive, separator, member = uri.removeprefix("tar://").rpartition("!/") + if not uri.startswith("tar://") or not separator or not member: + raise ValueError(f"Cannot identify the source archive for {uri!r}") + return archive, member + + +def safe_path(root, relative): + path = (Path(root) / relative).resolve() + if Path(relative).is_absolute() or not path.is_relative_to(Path(root).resolve()): + raise ValueError(f"Invalid release path {relative!r}") + return path + + +def remove_labels(index, ids): + if not len(ids): + return + if kind_and_core(index)[0] == "hnsw": + copy_hnsw_without_ids(faiss.clone_index(index), index, set(map(int, ids))) + else: + safe_remove_ids(index, make_id_selector(ids)) + + +def export_index(db, catalog, kind, source, target): + """Check the entire label mapping before publishing even a filtered subset.""" + index = faiss.read_index(str(source)) + if not isinstance(index, faiss.IndexIDMap2): + raise ValueError(f"{kind} index has no external ID map") + mapping = "articles" if kind == "papers" else "passages" + catalog.execute("DROP TABLE IF EXISTS temp.labels") + catalog.execute("CREATE TEMP TABLE labels(id INTEGER PRIMARY KEY)") + labels = faiss.rev_swig_ptr(index.id_map.data(), index.ntotal) if index.ntotal else [] + try: + catalog.executemany("INSERT INTO labels VALUES (?)", ((int(i),) for i in labels)) + except sqlite3.IntegrityError as error: + raise ValueError( + f"Duplicate {kind} vectors. Reconcile the workspace before export." + ) from error + row_count = db.execute(f"SELECT count(*) FROM {kind}").fetchone()[0] + if ( + row_count != index.ntotal + or db.execute(f"SELECT 1 FROM {kind} WHERE in_index IS NOT 1 LIMIT 1").fetchone() + ): + raise ValueError(f"Incomplete {kind} index. Reconcile the workspace before export.") + if any( + a != b + for a, b in zip( + db.execute(f"SELECT id FROM {kind} ORDER BY id"), + catalog.execute("SELECT id FROM labels ORDER BY id"), + strict=True, + ) + ): + raise ValueError(f"{kind} vector IDs differ from workspace rows. Reconcile before export.") + if catalog.execute(f"SELECT id FROM {mapping} EXCEPT SELECT id FROM labels LIMIT 1").fetchone(): + raise ValueError(f"Missing {kind} vector ID") + excluded = np.fromiter( + (r[0] for r in catalog.execute(f"SELECT id FROM labels EXCEPT SELECT id FROM {mapping}")), + dtype=np.int64, + ) + if len(excluded): + remove_labels(index, excluded) + if index.ntotal != row_count - len(excluded): + raise ValueError(f"Could not remove all excluded {kind} vectors") + faiss.write_index(index, str(target)) + else: + shutil.copyfile(source, target) + return {"kind": kind_and_core(index)[0], "dimension": index.d, "count": index.ntotal} + + +def export_vectors(workspace, output, *, licenses=(), settings=None, source_root=None): + paths = WorkspacePaths.from_env_or_default(workspace_override=Path(workspace)) + locks = LockManager.from_paths(paths) + with ( + new_directory(output) as stage, + locks.db_lock(), + locks.faiss_lock(), + readable_database(paths.db_path) as db, + ): + db.execute("BEGIN") + if read_publication(db): + raise ValueError("Finish the interrupted build before exporting its vectors.") + catalog_path = stage / "mapping.sqlite3" + with ( + closing(sqlite3.connect(catalog_path)) as catalog, + (stage / "attribution.jsonl").open("w", encoding="utf-8") as attribution, + ): + catalog.executescript(CATALOG) + cols = table_columns(db, "papers") + fields = [f"p.{k}" if k in cols else "NULL" for k in PAPER_FIELDS] + embedding = "p.embedding_text" if "embedding_text" in cols else "NULL" + member = "p.build_member" if "build_member" in cols else "NULL" + source_paths = {} + source_names = [ + r[0] + for r in db.execute( + "SELECT DISTINCT substr(path,7,instr(path,'!/')-7) FROM files WHERE path LIKE 'tar://%'" + ) + ] + common = ( + Path(os.path.commonpath([str(Path(p).parent) for p in source_names])) + if source_names + else Path(".") + ) + for original in source_names: + source_paths[original] = Path(original).relative_to(common).as_posix() + allowed = set(licenses) + for row in db.execute( + f"""SELECT p.id,{','.join(fields)}, {member}, + COALESCE({embedding}, (SELECT text FROM chunks WHERE paper_id=p.id AND ord=-1 ORDER BY id DESC LIMIT 1), + trim(coalesce(title,'') || ' ' || coalesce(abstract,''))) FROM papers p ORDER BY p.id""" + ): + pid = row[0] + metadata = dict(zip(PAPER_FIELDS, row[1:-2], strict=True)) + if allowed and (metadata.get("license") or "unknown") not in allowed: + continue + if not metadata["doc_id"]: + raise ValueError(f"Paper {pid} has no stable doc_id") + catalog.execute( + "INSERT INTO articles VALUES (?,?,?,?,?)", + ( + pid, + metadata["doc_id"], + json.dumps(metadata), + digest(row[-1] or "untitled"), + row[-2], + ), + ) + attribution.write( + json.dumps( + { + k: metadata[k] + for k in ( + "doc_id", + "pmid", + "pmcid", + "doi", + "title", + "authors", + "year", + "journal", + "license", + "license_url", + ) + }, + ensure_ascii=False, + ) + + "\n" + ) + # Read passages in index order per selected paper, bounding memory by a single row. + for (pid,) in catalog.execute("SELECT id FROM articles"): + catalog.executemany( + "INSERT INTO passages VALUES (?,?,?,?)", + ( + (cid, pid, ordinal, digest(text)) + for cid, ordinal, text in db.execute( + "SELECT id,ord,text FROM chunks WHERE paper_id=?", (pid,) + ) + ), + ) + for path, pid in db.execute("SELECT path,paper_id FROM files"): + original, member_name = archive_member(path) + catalog.execute( + "INSERT INTO files SELECT ?,?,?,? WHERE EXISTS(SELECT 1 FROM articles WHERE id=?)", + (source_paths[original], member_name, pid, path, pid), + ) + if catalog.execute( + "SELECT id FROM articles EXCEPT SELECT paper_id FROM files LIMIT 1" + ).fetchone(): + raise ValueError("A selected paper lacks an archive member mapping") + manifest = { + "format": FORMAT_VERSION, + "stage1_mode": get_stage1_mode(db), + "licenses": list(licenses), + "sources": [], + "indices": {}, + "checksums": {}, + } + records = {} + if db.execute("SELECT 1 FROM sqlite_master WHERE name='build_sources'").fetchone(): + for path, sha, size, options in db.execute("SELECT * FROM build_sources"): + records.setdefault(path, []).append((sha, size, json.loads(options))) + for original, name in source_paths.items(): + options = records.get(original, []) + if len(options) > 1: + raise ValueError( + f"Multiple source versions or build configurations recorded for {name}. Rebuild from the intended archive." + ) + if options: + sha, size, config = options[0] + config = complete_settings(config, settings or {}) + else: + path = safe_path(source_root, name) if source_root else Path(original) + if not settings or not path.is_file(): + raise ValueError( + f"Legacy source {name} needs its archive and explicit build settings" + ) + config, sha, size = settings, file_hash(path), path.stat().st_size + validate_settings(config, manifest["stage1_mode"]) + manifest["sources"].append(dict(name=name, sha256=sha, size=size, settings=config)) + for kind, path in ( + ("papers", paths.paper_index_path), + ("chunks", paths.chunk_index_path), + ): + if kind == "papers" and manifest["stage1_mode"] == "none": + continue + name = f"{kind}.faiss" + manifest["indices"][kind] = export_index(db, catalog, kind, path, stage / name) + catalog.commit() + for name in ( + "mapping.sqlite3", + "attribution.jsonl", + *(f"{k}.faiss" for k in manifest["indices"]), + ): + manifest["checksums"][name] = file_hash(stage / name) + (stage / "manifest.json").write_text( + json.dumps(manifest, indent=2) + "\n", encoding="utf-8" + ) + return manifest + + +def complete_settings(recorded, supplied): + """Fill missing legacy provenance without relabeling known vectors.""" + result = dict(recorded) + for key, value in supplied.items(): + existing = result.get(key) + if isinstance(existing, dict) and isinstance(value, dict): + value = complete_settings(existing, value) + elif existing is not None and existing != value: + raise ValueError(f"Supplied setting disagrees with the build record for {key}") + result[key] = value + return result + + +def validate_settings(settings, mode): + required = { + "litkit_version", + "chunk_target_chars", + "chunk_min_chars", + "chunk_overlap", + "include_tables", + "max_table_chars", + "paper_model", + "chunk_model", + } + if missing := required.difference(settings): + raise ValueError(f"Missing build settings: {sorted(missing)}") + for key in (("chunk_model",) if mode == "none" else ("paper_model", "chunk_model")): + model = settings[key] + if not model or not model.get("name") or not model.get("revision"): + raise ValueError(f"Supply the model name and revision for {key} in the build settings") + + +def read_manifest(release, *, verify=True): + release = Path(release) + data = json.loads((release / "manifest.json").read_text(encoding="utf-8")) + if data["format"] != FORMAT_VERSION or data["stage1_mode"] not in {"specter2", "mpnet", "none"}: + raise ValueError("Unsupported vector release format or Stage-1 mode") + required = {"mapping.sqlite3", "attribution.jsonl", "chunks.faiss"} + if data["stage1_mode"] != "none": + required.add("papers.faiss") + if set(data["checksums"]) != required: + raise ValueError("Incomplete vector release checksums") + for item in data["sources"]: + safe_path(release, item["name"]) + validate_settings(item["settings"], data["stage1_mode"]) + if verify: + for name in required: + if file_hash(release / name) != data["checksums"][name]: + raise ValueError(f"Release checksum mismatch for {name}") + return data diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 2a04ee6..0138afd 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -941,7 +941,7 @@ def fail_rename(*args): def test_member_savepoint_preserves_only_successful_members(tmp_path, archive, monkeypatch, strict): from litkit.build import ingest_loop - real_pack = ingest_loop.pack_body + real_pack = ingest_loop.article_passages def fail_middle(meta, *args): if meta["title"] == "Article 1": @@ -950,7 +950,7 @@ def fail_middle(meta, *args): build = Build(tmp_path / "producer", archive) with monkeypatch.context() as fault: - fault.setattr(ingest_loop, "pack_body", fail_middle) + fault.setattr(ingest_loop, "article_passages", fail_middle) if strict: with pytest.raises(InjectedFailure): build.run() diff --git a/tests/integration/test_portable_vectors.py b/tests/integration/test_portable_vectors.py new file mode 100644 index 0000000..3040f8f --- /dev/null +++ b/tests/integration/test_portable_vectors.py @@ -0,0 +1,92 @@ +"""Portable FAISS releases preserve external IDs across machines and source revisions.""" + +import json +import sqlite3 +from contextlib import closing + +import faiss +import pytest + +from conftest import jats, write_tar +from litkit.portable.record import file_hash +from litkit.portable.release import export_vectors +from test_build_and_query import litkit, _ok + +MODELS = { + "paper_model": {"name": "fixture", "revision": "v1"}, + "chunk_model": {"name": "fixture", "revision": "v1"}, +} + + +def licensed_article(pmcid, title, license_code, body): + permissions = ( + f'' + ) + return jats( + pmcid=pmcid, title=title, abstract="Private abstract about " + title, paragraphs=[body] + ).replace("", permissions + "") + + +@pytest.fixture +def portable_source(tmp_path): + workspace = tmp_path / "original" + sources = tmp_path / "sources" + sources.mkdir() + write_tar( + sources / "papers.tar", + { + "one.xml": licensed_article( + "PMC31", "Black coffee", "by", "Private passage espresso. " * 12 + ), + "two.xml": licensed_article( + "PMC42", "Road maps", "by-nc", "Private passage navigation. " * 12 + ), + }, + ) + _ok( + litkit( + workspace, + "--build-only", + "--faiss-writer", + "--tar-dir", + str(sources), + "--papers-index", + "hnsw", + "--chunks-index", + "flat", + ) + ) + return workspace, sources + + +@pytest.mark.parametrize("licenses", [[], ["CC-BY-4.0"]]) +def test_export_copies_or_filters_vectors_and_does_not_ship_text( + tmp_path, portable_source, licenses +): + workspace, sources = portable_source + bundle = tmp_path / "release" + manifest = export_vectors(workspace, bundle, licenses=licenses, settings=MODELS) + 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() + assert b"Private abstract" not in (bundle / "mapping.sqlite3").read_bytes() + with closing(sqlite3.connect(bundle / "mapping.sqlite3")) as mapping: + for table, kind in (("articles", "papers"), ("passages", "chunks")): + ids = [r[0] for r in mapping.execute(f"SELECT id FROM {table} ORDER BY id")] + index = faiss.read_index(str(bundle / f"{kind}.faiss")) + assert sorted(faiss.vector_to_array(index.id_map)) == ids + if not licenses: + assert file_hash(bundle / f"{kind}.faiss") == file_hash( + workspace / "indices" / f"{kind}.faiss" + ) + entries = [json.loads(line) for line in (bundle / "attribution.jsonl").read_text().splitlines()] + assert {e["pmcid"] for e in entries} == ({"PMC31"} if licenses else {"PMC31", "PMC42"}) + + +def test_export_rejects_conflicting_settings(tmp_path, portable_source): + workspace, _ = portable_source + destination = tmp_path / "release" + with pytest.raises(ValueError, match="chunk_target_chars"): + export_vectors(workspace, destination, settings=MODELS | {"chunk_target_chars": 999}) + assert not destination.exists() From 7924aacc79e0d4fcfabd9d25d36fc948860da1a9 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Fri, 4 Dec 2026 14:52:51 -0700 Subject: [PATCH 2/4] Preserve source provenance and verify published vector releases Signed-off-by: Bill Hlavacek --- README.md | 7 + src/litkit/build/ingest_loop.py | 21 +- src/litkit/portable/record.py | 36 ++- src/litkit/portable/release.py | 280 ++++++++++++++++----- tests/integration/test_batch_resume.py | 25 ++ tests/integration/test_portable_vectors.py | 187 +++++++++++++- 6 files changed, 474 insertions(+), 82 deletions(-) diff --git a/README.md b/README.md index 9fc5a4b..9df80b6 100644 --- a/README.md +++ b/README.md @@ -237,3 +237,10 @@ 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"}} ``` + +If archives used different settings, put shared fields in a `defaults` object +and archive-specific fields in a `sources` object keyed by relative archive +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. diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index f056920..eac169c 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -19,7 +19,7 @@ import faiss from litkit.progress import eprint as _eprint -from litkit.portable.record import SOURCE_SCHEMA, source_record, settings_record +from litkit.portable.record import SOURCE_SCHEMA, archive_identity, source_record, settings_record from litkit.embeddings.base import ( progress_newline as _progress_newline, progress_write as _progress_write, @@ -412,6 +412,10 @@ def stage_indexes(paper_dir, chunk_dir): def process_tar(tpath: Path) -> None: provenance = None + try: + initial_identity = archive_identity(tpath) + except FileNotFoundError: + initial_identity = None source_settings = settings_record(chunk_target_chars, chunk_min_chars, chunk_overlap, include_tables, max_table_chars, paper_embedder, chunk_embedder) rebuilding_tar = str(tpath) in rebuild_tars @@ -420,6 +424,11 @@ def process_tar(tpath: Path) -> None: processed_count = start_persisted # increments after each successfully handled member persisted_count = start_persisted # last value safely fsynced via commit + checkpoint + def flush_tar_batch(): + if provenance and archive_identity(tpath) != initial_identity: + raise ValueError(f"Source changed while ingesting {tpath}") + flush_batch(str(tpath), processed_count) + # Set LITKIT_TAR_PRESCAN=0 to skip counting members total_members = ( count_tar_xml_members(tpath) @@ -541,8 +550,10 @@ def _render(force: bool = False): # SLOW PATH - Savepoint-protected writes # ═══════════════════════════════════════════════════════════════════ - if provenance is None and tpath.is_file(): - provenance = source_record(tpath, source_settings) + if provenance is None: + if initial_identity is None: + raise ValueError(f"Source appeared after ingestion began: {tpath}") + provenance = source_record(tpath, source_settings, expected=initial_identity) conn.execute(SOURCE_SCHEMA) # Snapshot buffer lengths BEFORE processing so we can truncate on rollback @@ -778,12 +789,12 @@ def _render(force: bool = False): or len(chunk_ids_buf) >= chunk_batch or (not embed_producer and processed_count - persisted_count >= ckpt_every) ): - flush_batch(str(tpath), processed_count) + flush_tar_batch() persisted_count = processed_count _render(force=True) if processed_count != persisted_count or str(tpath) not in ckpt_stream: - flush_batch(str(tpath), processed_count) + flush_tar_batch() _render(force=True) _progress_newline(sys.stderr) diff --git a/src/litkit/portable/record.py b/src/litkit/portable/record.py index 9965df1..4053123 100644 --- a/src/litkit/portable/record.py +++ b/src/litkit/portable/record.py @@ -41,14 +41,23 @@ def settings_record(target, minimum, overlap, tables, table_limit, paper, chunk) ) -def source_record(path, settings): - path = Path(path) - before = path.stat() - digest = file_hash(path) - after = path.stat() - if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns): +def archive_identity(path): + stat = Path(path).stat() + return stat.st_dev, stat.st_ino, stat.st_ctime_ns, stat.st_mtime_ns, stat.st_size + + +def archive_checksum(path, *, expected=None): + before = archive_identity(path) if expected is None else expected + sha = file_hash(path) + after = archive_identity(path) + if before != after: raise ValueError(f"Source changed while recording its checksum: {path}") - return str(path), digest, after.st_size, json.dumps(settings, sort_keys=True) + return sha, after[-1] + + +def source_record(path, settings, *, expected=None): + sha, size = archive_checksum(path, expected=expected) + return str(path), sha, size, json.dumps(settings, sort_keys=True) def jats_license(meta): @@ -58,9 +67,16 @@ def jats_license(meta): for node in meta.findall("{*}permissions/{*}license"): href = node.get("{http://www.w3.org/1999/xlink}href") or node.get("href") if not href: - link = node.find(".//{*}ext-link") - if link is not None: - href = link.get("{http://www.w3.org/1999/xlink}href") + for link in node.iter("{*}license_ref", "{*}ext-link"): + href = link.get("{http://www.w3.org/1999/xlink}href") or link.get("href") + if not href: + value = "".join(link.itertext()).strip() + if value.lower().startswith(("https://", "http://")): + href = value + if href: + break + if href: + href = href.strip() if href and ( cc := re.match( r"https?://(?:www\.)?creativecommons\.org/(licenses|publicdomain)/([\w-]+)/(\d+\.\d+)(?:/|$)", diff --git a/src/litkit/portable/release.py b/src/litkit/portable/release.py index cf02cb7..8bb1a37 100644 --- a/src/litkit/portable/release.py +++ b/src/litkit/portable/release.py @@ -5,11 +5,12 @@ import hashlib import json import os +import re import shutil import sqlite3 import tempfile from contextlib import closing, contextmanager -from pathlib import Path +from pathlib import Path, PurePosixPath, PureWindowsPath import faiss import numpy as np @@ -21,7 +22,7 @@ from litkit.db.schema import get_stage1_mode, table_columns from litkit.index.ids import copy_hnsw_without_ids, make_id_selector, safe_remove_ids from litkit.index.introspection import kind_and_core -from litkit.portable.record import file_hash +from litkit.portable.record import archive_checksum, file_hash FORMAT_VERSION = 1 PAPER_FIELDS = ( @@ -70,13 +71,49 @@ def new_directory(destination): def archive_member(uri): - archive, separator, member = uri.removeprefix("tar://").rpartition("!/") + archive, separator, member = uri.removeprefix("tar://").partition("!/") + # The separator can also occur in a source directory or in the member name. + while "!/" in member and not archive.lower().endswith( + (".tar", ".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz") + ): + directory, separator, member = member.partition("!/") + archive += "!/" + directory if not uri.startswith("tar://") or not separator or not member: raise ValueError(f"Cannot identify the source archive for {uri!r}") return archive, member +def archive_names(originals): + """Relativize publisher paths using their original platform's path syntax.""" + paths = { + name: PureWindowsPath(name) if PureWindowsPath(name).drive else PurePosixPath(name) + for name in originals + } + common = os.path.commonprefix([path.parent.parts for path in paths.values()]) if paths else () + result = {} + for name, path in paths.items(): + parts = path.parts[len(common) :] + if path.anchor and not common: + # Different Windows volumes have no common parent directory. + volume = path.drive.strip("\\/").replace(":", "").replace("\\", "/") + parts = (volume, *parts[1:]) + result[name] = PurePosixPath(*parts).as_posix() + if len(set(result.values())) != len(result): + raise ValueError("Source archive names collide after conversion to portable paths") + return result + + def safe_path(root, relative): + if ( + not isinstance(relative, str) + or not relative + or str(PurePosixPath(relative)) != relative + or relative == "." + or "\\" in relative + or PureWindowsPath(relative).drive + or ".." in PurePosixPath(relative).parts + ): + raise ValueError(f"Invalid release path {relative!r}") path = (Path(root) / relative).resolve() if Path(relative).is_absolute() or not path.is_relative_to(Path(root).resolve()): raise ValueError(f"Invalid release path {relative!r}") @@ -92,12 +129,22 @@ def remove_labels(index, ids): safe_remove_ids(index, make_id_selector(ids)) -def export_index(db, catalog, kind, source, target): +def export_index(db, catalog, kind, source, target, *, filtered): """Check the entire label mapping before publishing even a filtered subset.""" - index = faiss.read_index(str(source)) + mapping = "articles" if kind == "papers" else "passages" + row_count = db.execute(f"SELECT count(*) FROM {kind}").fetchone()[0] + selected = catalog.execute(f"SELECT count(*) FROM {mapping}").fetchone()[0] + if not filtered and selected != row_count: + raise ValueError( + f"Some {kind} rows have no matching paper. Reconcile the workspace before export." + ) + if selected == row_count: + shutil.copyfile(source, target) + index = faiss.read_index(str(target if selected == row_count else source)) if not isinstance(index, faiss.IndexIDMap2): raise ValueError(f"{kind} index has no external ID map") - mapping = "articles" if kind == "papers" else "passages" + if index.id_map.size() != index.ntotal: + raise ValueError(f"Incomplete {kind} vector ID map. Reconcile the workspace before export.") catalog.execute("DROP TABLE IF EXISTS temp.labels") catalog.execute("CREATE TEMP TABLE labels(id INTEGER PRIMARY KEY)") labels = faiss.rev_swig_ptr(index.id_map.data(), index.ntotal) if index.ntotal else [] @@ -107,10 +154,9 @@ def export_index(db, catalog, kind, source, target): raise ValueError( f"Duplicate {kind} vectors. Reconcile the workspace before export." ) from error - row_count = db.execute(f"SELECT count(*) FROM {kind}").fetchone()[0] - if ( - row_count != index.ntotal - or db.execute(f"SELECT 1 FROM {kind} WHERE in_index IS NOT 1 LIMIT 1").fetchone() + if row_count != index.ntotal or ( + "in_index" in table_columns(db, kind) + and db.execute(f"SELECT 1 FROM {kind} WHERE in_index IS NOT 1 LIMIT 1").fetchone() ): raise ValueError(f"Incomplete {kind} index. Reconcile the workspace before export.") if any( @@ -122,19 +168,19 @@ def export_index(db, catalog, kind, source, target): ) ): raise ValueError(f"{kind} vector IDs differ from workspace rows. Reconcile before export.") - if catalog.execute(f"SELECT id FROM {mapping} EXCEPT SELECT id FROM labels LIMIT 1").fetchone(): - raise ValueError(f"Missing {kind} vector ID") - excluded = np.fromiter( - (r[0] for r in catalog.execute(f"SELECT id FROM labels EXCEPT SELECT id FROM {mapping}")), - dtype=np.int64, - ) - if len(excluded): + # Mapping IDs were selected from the same SQLite snapshot that matched all labels above. + if selected != row_count: + excluded = np.fromiter( + ( + r[0] + for r in catalog.execute(f"SELECT id FROM labels EXCEPT SELECT id FROM {mapping}") + ), + dtype=np.int64, + ) remove_labels(index, excluded) - if index.ntotal != row_count - len(excluded): + if index.ntotal != selected: raise ValueError(f"Could not remove all excluded {kind} vectors") faiss.write_index(index, str(target)) - else: - shutil.copyfile(source, target) return {"kind": kind_and_core(index)[0], "dimension": index.d, "count": index.ntotal} @@ -157,33 +203,40 @@ def export_vectors(workspace, output, *, licenses=(), settings=None, source_root ): catalog.executescript(CATALOG) cols = table_columns(db, "papers") - fields = [f"p.{k}" if k in cols else "NULL" for k in PAPER_FIELDS] + fields = {k: f"p.{k}" if k in cols else "NULL" for k in PAPER_FIELDS} + if "doc_id" not in cols: + # Match the stable identifier assigned by the pre-0.3.34 migration. + db.execute( + """CREATE TEMP TABLE first_files AS SELECT paper_id,path FROM files + WHERE rowid IN (SELECT MIN(rowid) FROM files GROUP BY paper_id)""" + ) + db.execute("CREATE UNIQUE INDEX first_files_id ON first_files(paper_id)") + fields["doc_id"] = "(SELECT path FROM first_files WHERE paper_id=p.id)" embedding = "p.embedding_text" if "embedding_text" in cols else "NULL" member = "p.build_member" if "build_member" in cols else "NULL" - source_paths = {} - source_names = [ + db.create_function("source_archive", 1, lambda uri: archive_member(uri)[0]) + source_paths = archive_names( r[0] for r in db.execute( - "SELECT DISTINCT substr(path,7,instr(path,'!/')-7) FROM files WHERE path LIKE 'tar://%'" + "SELECT DISTINCT source_archive(path) FROM files WHERE path LIKE 'tar://%!/_%'" ) - ] - common = ( - Path(os.path.commonpath([str(Path(p).parent) for p in source_names])) - if source_names - else Path(".") ) - for original in source_names: - source_paths[original] = Path(original).relative_to(common).as_posix() - allowed = set(licenses) + defaults, by_source = supplied_settings(settings, source_paths.values()) + allowed = tuple(licenses) + where = "" + if allowed: + placeholders = ",".join("?" for _ in allowed) + where = ( + f" WHERE coalesce(nullif({fields['license']},''),'unknown') IN ({placeholders})" + ) for row in db.execute( - f"""SELECT p.id,{','.join(fields)}, {member}, + f"""SELECT p.id,{','.join(fields.values())}, {member}, COALESCE({embedding}, (SELECT text FROM chunks WHERE paper_id=p.id AND ord=-1 ORDER BY id DESC LIMIT 1), - trim(coalesce(title,'') || ' ' || coalesce(abstract,''))) FROM papers p ORDER BY p.id""" + trim(coalesce(title,'') || ' ' || coalesce(abstract,''))) FROM papers p {where} ORDER BY p.id""", + allowed, ): pid = row[0] metadata = dict(zip(PAPER_FIELDS, row[1:-2], strict=True)) - if allowed and (metadata.get("license") or "unknown") not in allowed: - continue if not metadata["doc_id"]: raise ValueError(f"Paper {pid} has no stable doc_id") catalog.execute( @@ -217,22 +270,27 @@ def export_vectors(workspace, output, *, licenses=(), settings=None, source_root ) + "\n" ) - # Read passages in index order per selected paper, bounding memory by a single row. - for (pid,) in catalog.execute("SELECT id FROM articles"): - catalog.executemany( - "INSERT INTO passages VALUES (?,?,?,?)", - ( - (cid, pid, ordinal, digest(text)) - for cid, ordinal, text in db.execute( - "SELECT id,ord,text FROM chunks WHERE paper_id=?", (pid,) - ) - ), - ) - for path, pid in db.execute("SELECT path,paper_id FROM files"): + catalog.executemany( + "INSERT INTO passages VALUES (?,?,?,?)", + ( + (cid, pid, ordinal, digest(text)) + for cid, pid, ordinal, text in db.execute( + "SELECT c.id,c.paper_id,c.ord,c.text FROM chunks c JOIN papers p ON p.id=c.paper_id" + + where, + allowed, + ) + ), + ) + selected_sources = set() + for path, pid in db.execute( + "SELECT f.path,f.paper_id FROM files f JOIN papers p ON p.id=f.paper_id" + where, + allowed, + ): original, member_name = archive_member(path) + selected_sources.add(original) catalog.execute( - "INSERT INTO files SELECT ?,?,?,? WHERE EXISTS(SELECT 1 FROM articles WHERE id=?)", - (source_paths[original], member_name, pid, path, pid), + "INSERT INTO files VALUES (?,?,?,?)", + (source_paths[original], member_name, pid, path), ) if catalog.execute( "SELECT id FROM articles EXCEPT SELECT paper_id FROM files LIMIT 1" @@ -241,7 +299,7 @@ def export_vectors(workspace, output, *, licenses=(), settings=None, source_root manifest = { "format": FORMAT_VERSION, "stage1_mode": get_stage1_mode(db), - "licenses": list(licenses), + "licenses": list(allowed), "sources": [], "indices": {}, "checksums": {}, @@ -250,7 +308,9 @@ def export_vectors(workspace, output, *, licenses=(), settings=None, source_root if db.execute("SELECT 1 FROM sqlite_master WHERE name='build_sources'").fetchone(): for path, sha, size, options in db.execute("SELECT * FROM build_sources"): records.setdefault(path, []).append((sha, size, json.loads(options))) - for original, name in source_paths.items(): + for original in sorted(selected_sources, key=source_paths.__getitem__): + name = source_paths[original] + supplied = defaults | by_source.get(name, {}) options = records.get(original, []) if len(options) > 1: raise ValueError( @@ -258,16 +318,18 @@ def export_vectors(workspace, output, *, licenses=(), settings=None, source_root ) if options: sha, size, config = options[0] - config = complete_settings(config, settings or {}) + config = complete_settings(config, supplied) else: path = safe_path(source_root, name) if source_root else Path(original) - if not settings or not path.is_file(): + if not supplied or not path.is_file(): raise ValueError( f"Legacy source {name} needs its archive and explicit build settings" ) - config, sha, size = settings, file_hash(path), path.stat().st_size + sha, size = archive_checksum(path) + config = supplied validate_settings(config, manifest["stage1_mode"]) manifest["sources"].append(dict(name=name, sha256=sha, size=size, settings=config)) + validate_models(manifest["sources"], manifest["stage1_mode"]) for kind, path in ( ("papers", paths.paper_index_path), ("chunks", paths.chunk_index_path), @@ -275,7 +337,9 @@ def export_vectors(workspace, output, *, licenses=(), settings=None, source_root if kind == "papers" and manifest["stage1_mode"] == "none": continue name = f"{kind}.faiss" - manifest["indices"][kind] = export_index(db, catalog, kind, path, stage / name) + manifest["indices"][kind] = export_index( + db, catalog, kind, path, stage / name, filtered=bool(allowed) + ) catalog.commit() for name in ( "mapping.sqlite3", @@ -286,9 +350,30 @@ def export_vectors(workspace, output, *, licenses=(), settings=None, source_root (stage / "manifest.json").write_text( json.dumps(manifest, indent=2) + "\n", encoding="utf-8" ) + read_manifest(stage, verify=False) return manifest +def supplied_settings(settings, names): + if settings is None: + return {}, {} + if not isinstance(settings, dict): + raise ValueError("Build settings must be a JSON object") + if not {"defaults", "sources"}.intersection(settings): + return settings, {} + if settings.keys() - {"defaults", "sources"}: + raise ValueError("Place shared build settings under 'defaults' when using 'sources'") + defaults = settings.get("defaults", {}) + sources = settings.get("sources", {}) + if not isinstance(defaults, dict) or not isinstance(sources, dict): + raise ValueError("Build settings defaults and sources must be JSON objects") + if unknown := sources.keys() - set(names): + raise ValueError(f"Unknown source names in build settings: {sorted(unknown)}") + if any(not isinstance(value, dict) for value in sources.values()): + raise ValueError("Each source's settings must be a JSON object") + return defaults, sources + + def complete_settings(recorded, supplied): """Fill missing legacy provenance without relabeling known vectors.""" result = dict(recorded) @@ -313,27 +398,94 @@ def validate_settings(settings, mode): "paper_model", "chunk_model", } + if not isinstance(settings, dict): + raise ValueError("Build settings must be a JSON object") if missing := required.difference(settings): raise ValueError(f"Missing build settings: {sorted(missing)}") + if not isinstance(settings["litkit_version"], str) or not settings["litkit_version"].strip(): + raise ValueError("Supply the LitKit version in the build settings") + if not isinstance(settings["include_tables"], bool): + raise ValueError("include_tables must be a boolean") + for key in ("chunk_target_chars", "chunk_min_chars", "chunk_overlap", "max_table_chars"): + if type(settings[key]) is not int: + raise ValueError(f"{key} must be an integer") for key in (("chunk_model",) if mode == "none" else ("paper_model", "chunk_model")): model = settings[key] - if not model or not model.get("name") or not model.get("revision"): + if not isinstance(model, dict) or not all( + isinstance(model.get(k), str) and model[k].strip() for k in ("name", "revision") + ): raise ValueError(f"Supply the model name and revision for {key} in the build settings") +def validate_models(sources, mode): + if len(sources) < 2: + return + for key in (("chunk_model",) if mode == "none" else ("paper_model", "chunk_model")): + first = sources[0] + reference = first["settings"][key] + for source in sources[1:]: + model = source["settings"][key] + if (model["name"], model["revision"]) != (reference["name"], reference["revision"]): + raise ValueError( + f"{key} differs between {first['name']} ({reference['name']}@{reference['revision']}) " + f"and {source['name']} ({model['name']}@{model['revision']}). " + "Rebuild the index with one model revision." + ) + + def read_manifest(release, *, verify=True): release = Path(release) data = json.loads((release / "manifest.json").read_text(encoding="utf-8")) - if data["format"] != FORMAT_VERSION or data["stage1_mode"] not in {"specter2", "mpnet", "none"}: + if ( + not isinstance(data, dict) + or type(data.get("format")) is not int + or data["format"] != FORMAT_VERSION + or data.get("stage1_mode") not in ("specter2", "mpnet", "none") + ): raise ValueError("Unsupported vector release format or Stage-1 mode") - required = {"mapping.sqlite3", "attribution.jsonl", "chunks.faiss"} - if data["stage1_mode"] != "none": - required.add("papers.faiss") - if set(data["checksums"]) != required: + if not isinstance(data.get("licenses"), list) or not all( + isinstance(x, str) for x in data["licenses"] + ): + raise ValueError("Invalid release license filter") + indices = {"chunks"} if data["stage1_mode"] == "none" else {"papers", "chunks"} + if not isinstance(data.get("indices"), dict) or data["indices"].keys() != indices: + raise ValueError("Incomplete vector release index metadata") + for name, index in data["indices"].items(): + if ( + not isinstance(index, dict) + or not isinstance(index.get("kind"), str) + or not index["kind"] + or type(index.get("dimension")) is not int + or index["dimension"] <= 0 + or type(index.get("count")) is not int + or index["count"] < 0 + ): + raise ValueError(f"Invalid {name} index metadata") + required = {"mapping.sqlite3", "attribution.jsonl", *(f"{kind}.faiss" for kind in indices)} + if not isinstance(data.get("checksums"), dict) or data["checksums"].keys() != required: raise ValueError("Incomplete vector release checksums") + if not all( + isinstance(x, str) and re.fullmatch(r"[0-9a-f]{64}", x) for x in data["checksums"].values() + ): + raise ValueError("Invalid vector release checksum") + if not isinstance(data.get("sources"), list): + raise ValueError("Invalid source archive list") + names = set() for item in data["sources"]: - safe_path(release, item["name"]) - validate_settings(item["settings"], data["stage1_mode"]) + if ( + not isinstance(item, dict) + or not isinstance(item.get("sha256"), str) + or not re.fullmatch(r"[0-9a-f]{64}", item["sha256"]) + or type(item.get("size")) is not int + or item["size"] < 0 + ): + raise ValueError("Invalid source archive checksum or size") + path = safe_path(release, item.get("name")) + if path in names: + raise ValueError(f"Duplicate source archive {item['name']!r}") + names.add(path) + validate_settings(item.get("settings"), data["stage1_mode"]) + validate_models(data["sources"], data["stage1_mode"]) if verify: for name in required: if file_hash(release / name) != data["checksums"][name]: diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 0138afd..c235219 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -87,6 +87,31 @@ def test_producer_resolves_equivalent_output_directories(tmp_path, archive): assert not list(build.segments.glob(".litkit-batch-*")) +@pytest.mark.parametrize("before_member", [0, 1]) +def test_build_rejects_archive_replaced_between_parse_and_publication( + tmp_path, archive, monkeypatch, before_member +): + from litkit.build import ingest_loop + + build = Build(tmp_path / "producer", archive) + original = ingest_loop.iter_tar_articles + replacement = write_tar(tmp_path / "new.tar", {"0.xml": jats(title="Different bytes")}) + + def replace_during_batch(*args, **kwargs): + # Buffering models completed parser workers still serving the old generation. + articles = list(original(*args, **kwargs)) + for i, article in enumerate(articles): + if i == before_member: + replacement.replace(archive) + yield article + + monkeypatch.setattr(ingest_loop, "iter_tar_articles", replace_during_batch) + with pytest.raises(ValueError, match="Source changed while"): + build.run() + assert build.rows() == (0, 0, 0) + assert build.progress() == 0 + + class Build: def __init__(self, root, tar, *, producer=True, shard_id=0): self.root = root diff --git a/tests/integration/test_portable_vectors.py b/tests/integration/test_portable_vectors.py index 3040f8f..4a031f8 100644 --- a/tests/integration/test_portable_vectors.py +++ b/tests/integration/test_portable_vectors.py @@ -6,11 +6,11 @@ import faiss import pytest +from test_build_and_query import _ok, litkit -from conftest import jats, write_tar +from conftest import downgrade_to_0_3_33, jats, write_tar from litkit.portable.record import file_hash -from litkit.portable.release import export_vectors -from test_build_and_query import litkit, _ok +from litkit.portable.release import archive_names, export_vectors, read_manifest MODELS = { "paper_model": {"name": "fixture", "revision": "v1"}, @@ -90,3 +90,184 @@ def test_export_rejects_conflicting_settings(tmp_path, portable_source): with pytest.raises(ValueError, match="chunk_target_chars"): export_vectors(workspace, destination, settings=MODELS | {"chunk_target_chars": 999}) assert not destination.exists() + + +def test_export_uses_only_selected_sources_and_reads_ali_license(tmp_path): + sources = tmp_path / "sources!" + sources.mkdir() + workspace = tmp_path / "workspace" + url = "https://creativecommons.org/licenses/by/4.0/" + license_xml = ( + '' + f" {url} " + ) + xml = jats(pmcid="PMC33", title="Included").replace( + "", license_xml + "" + ) + member = "supplement!/one.xml" + write_tar(sources / "one.tar", {member: xml}) + excluded = write_tar( + sources / "two.tar", {"two.xml": licensed_article("PMC44", "Excluded", "by-nc", "Text.")} + ) + _ok( + litkit( + workspace, + "--build-only", + "--faiss-writer", + "--tar-dir", + str(sources), + "--papers-index", + "flat", + "--chunks-index", + "flat", + ) + ) + with closing(sqlite3.connect(workspace / "sqlite" / "litkit.sqlite3")) as db: + db.execute("DELETE FROM build_sources WHERE path=?", (str(excluded),)) + db.commit() + excluded.unlink() + settings = tmp_path / "settings.json" + settings.write_text(json.dumps(MODELS)) + bundle = tmp_path / "release" + proc = _ok( + litkit( + workspace, + "export-vectors", + str(bundle), + "--settings", + str(settings), + "--license", + "CC-BY-4.0", + ) + ) + assert [s["name"] for s in json.loads(proc.stdout)["sources"]] == ["one.tar"] + entry = json.loads((bundle / "attribution.jsonl").read_text()) + assert (entry["pmcid"], entry["license"], entry["license_url"]) == ("PMC33", "CC-BY-4.0", url) + with closing(sqlite3.connect(bundle / "mapping.sqlite3")) as db: + assert db.execute("SELECT source,member FROM files").fetchall() == [("one.tar", member)] + + +def test_mixed_recorded_and_relocated_legacy_sources(tmp_path, portable_source): + workspace, sources = portable_source + legacy = write_tar(sources / "legacy.tar", {"three.xml": jats(pmcid="PMC55", title="Third")}) + _ok( + litkit( + workspace, + "--build-only", + "--faiss-writer", + "--tar-dir", + str(sources), + "--chunk-target-chars", + "500", + "--chunks-index", + "flat", + "--papers-index", + "hnsw", + ) + ) + db_path = workspace / "sqlite" / "litkit.sqlite3" + with closing(sqlite3.connect(db_path)) as db: + config = json.loads( + db.execute( + "SELECT settings FROM build_sources WHERE path=?", (str(legacy),) + ).fetchone()[0] + ) + db.execute("DELETE FROM build_sources WHERE path=?", (str(legacy),)) + db.commit() + relocated = tmp_path / "relocated" + sources.rename(relocated) + settings = tmp_path / "settings.json" + settings.write_text(json.dumps({"defaults": MODELS, "sources": {legacy.name: config | MODELS}})) + proc = _ok( + litkit( + workspace, + "export-vectors", + str(tmp_path / "release"), + "--source-root", + str(relocated), + "--settings", + str(settings), + ) + ) + entries = {s["name"]: s for s in json.loads(proc.stdout)["sources"]} + assert entries["legacy.tar"]["settings"]["chunk_target_chars"] == 500 + assert entries["legacy.tar"]["sha256"] == file_hash(relocated / "legacy.tar") + assert entries["papers.tar"]["settings"]["chunk_target_chars"] == 1200 + different_model = config | MODELS | {"chunk_model": {"name": "fixture", "revision": "v2"}} + with pytest.raises(ValueError, match="chunk_model differs.*Rebuild"): + export_vectors( + workspace, + tmp_path / "mixed-model", + source_root=relocated, + settings={"defaults": MODELS, "sources": {legacy.name: different_model}}, + ) + + +def test_legacy_export_preserves_first_member_id_without_upgrading_workspace( + tmp_path, portable_source +): + workspace, _ = portable_source + db_path = workspace / "sqlite" / "litkit.sqlite3" + with closing(sqlite3.connect(db_path)) as db: + config = json.loads(db.execute("SELECT settings FROM build_sources").fetchone()[0]) | MODELS + ids = db.execute("SELECT id,doc_id FROM papers ORDER BY id").fetchall() + downgrade_to_0_3_33(workspace) + with closing(sqlite3.connect(db_path)) as db: + for table in ("papers", "chunks"): + db.execute(f"ALTER TABLE {table} DROP COLUMN in_index") + db.commit() + before = file_hash(db_path) + bundle = tmp_path / "release" + export_vectors(workspace, bundle, licenses=["unknown"], settings=config) + with closing(sqlite3.connect(bundle / "mapping.sqlite3")) as mapping: + assert mapping.execute("SELECT id,doc_id FROM articles ORDER BY id").fetchall() == ids + assert file_hash(db_path) == before + + +def test_export_validates_copied_faiss_before_publishing(tmp_path, portable_source, monkeypatch): + from litkit.portable import release + + workspace, _ = portable_source + copyfile = release.shutil.copyfile + + def changed_file(source, target): + copyfile(source, target) + if target.name == "papers.faiss": + # Simulate a different generation of the source being copied. + index = faiss.read_index(str(target)) + index.reset() + faiss.write_index(index, str(target)) + + monkeypatch.setattr(release.shutil, "copyfile", changed_file) + output = tmp_path / "release" + with pytest.raises(ValueError, match="Incomplete papers index"): + export_vectors(workspace, output, settings=MODELS) + assert not output.exists() + + +def test_archive_names_use_publisher_path_syntax(): + a, b = r"C:\PMC\a\papers.tar", r"C:\PMC\b\papers.tar" + assert archive_names([a, b]) == {a: "a/papers.tar", b: "b/papers.tar"} + c = r"D:\PMC\a\papers.tar" + assert archive_names([a, c]) == {a: "C/PMC/a/papers.tar", c: "D/PMC/a/papers.tar"} + + +def test_release_reader_checks_manifest_before_using_files(tmp_path, portable_source): + workspace, _ = portable_source + bundle = tmp_path / "release" + manifest = export_vectors(workspace, bundle, settings=MODELS) + assert read_manifest(bundle) == manifest + entry = manifest["sources"][0] + for changed, diagnostic in ( + ({"indices": {}}, "index metadata"), + ({"sources": [entry, entry]}, "Duplicate source"), + ({"sources": [entry | {"name": "../archive.tar"}]}, "Invalid release path"), + ({"sources": [entry | {"size": -1}]}, "checksum or size"), + ( + {"sources": [entry | {"settings": entry["settings"] | {"include_tables": "false"}}]}, + "boolean", + ), + ): + (bundle / "manifest.json").write_text(json.dumps(manifest | changed)) + with pytest.raises(ValueError, match=diagnostic): + read_manifest(bundle, verify=False) From 7012434f8a6c297e5bbdf8ce93d968c403e722f4 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Fri, 4 Dec 2026 15:04:59 -0700 Subject: [PATCH 3/4] Resolve relocated legacy archives from their selected members Signed-off-by: Bill Hlavacek --- src/litkit/portable/release.py | 179 ++++++++++++++------- tests/integration/test_portable_vectors.py | 90 +++++++++++ 2 files changed, 215 insertions(+), 54 deletions(-) diff --git a/src/litkit/portable/release.py b/src/litkit/portable/release.py index f7597a4..92ef7eb 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 @@ -24,7 +24,7 @@ from litkit.index.ids import copy_hnsw_without_ids, make_id_selector, safe_remove_ids from litkit.index.introspection import kind_and_core from litkit.index.io import faiss_load, write_index -from litkit.portable.record import archive_checksum, file_hash +from litkit.portable.record import archive_checksum, archive_identity, file_hash FORMAT_VERSION = 1 PAPER_FIELDS = ( @@ -73,49 +73,105 @@ def new_directory(destination): stage.rename(destination) -def archive_member(uri, recorded=(), source_root=None): +def archive_candidates(uri, recorded): if not uri.startswith("tar://"): - raise ValueError(f"Cannot identify the source archive for {uri!r}") + return [] path = uri.removeprefix("tar://") candidates = [ (path[: m.start()], path[m.end() :]) for m in re.finditer("!/", path) if m.end() < len(path) ] # A directory or an XML member may itself contain the delimiter. - matches = [pair for pair in candidates if pair[0] in recorded] - if not matches: - matches = [ - pair - for pair in candidates - if pair[0] - .lower() - .endswith((".tar", ".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz")) - ] - if len(matches) > 1: - located = [] - for archive, member in matches: + return [pair for pair in candidates if pair[0] in recorded] or [ + pair + for pair in candidates + if pair[0] + .lower() + .endswith((".tar", ".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz")) + ] + + +def publisher_path(name): + return PureWindowsPath(name) if PureWindowsPath(name).drive else PurePosixPath(name) + + +class LegacyArchives: + """Locate ambiguous legacy members once per archive and hash the same edition.""" + + def __init__(self, source_root): + self.root = Path(source_root).resolve() if source_root is not None else None + self.locations = {} + self.members = {} + self.resolved = {} + + def locations_for(self, archive): + if archive not in self.locations: + if self.root is None: local = Path(archive) - if not local.is_file() and source_root: - name = archive_names([*recorded, archive])[archive] - local = safe_path(source_root, name) - if local.is_file(): - with tarfile.open(local, "r:*") as handle: - try: - handle.getmember(member) - except KeyError: - continue - located.append((archive, member)) - matches = located - if len(matches) != 1: - raise ValueError(f"Cannot identify a unique source archive for {uri!r}") - return matches[0] - - -def archive_names(originals): + files = [local] if local.is_file() else [] + else: + # The receiver may have copied any enclosing publisher directory. + # Try its suffixes without walking the receiver's directory tree. + path = publisher_path(archive) + parts = path.parts[1:] if path.anchor else path.parts + if path.drive: + volume = path.drive.strip("\\/").replace(":", "").replace("\\", "/") + parts = (*PurePosixPath(volume).parts, *parts) + files = [] + for start in range(len(parts)): + relative = PurePosixPath(*parts[start:]).as_posix() + local = self.root / relative + if local.is_file(): + safe_path(self.root, relative) + files.append(local) + self.locations[archive] = files + return self.locations[archive] + + def member(self, uri, candidates): + if len(candidates) == 1: + return candidates[0] + matches = [] + for archive, member in candidates: + for local in self.locations_for(archive): + path = local.resolve() + if path not in self.members: + identity = archive_identity(path) + try: + with tarfile.open(path, "r:*") as handle: + names = {info.name for info in handle if info.isfile()} + except tarfile.TarError as error: + raise ValueError( + f"Cannot inspect candidate source archive {local}: {error}" + ) from error + self.members[path] = identity, names + identity, names = self.members[path] + if member in names: + matches.append((archive, member, local, identity)) + if len(matches) != 1: + raise ValueError(f"Cannot identify a unique source archive for {uri!r}") + archive, member, local, identity = matches[0] + if self.resolved.setdefault(archive, (local, identity)) != (local, identity): + raise ValueError(f"Members of {archive!r} resolve to different source archives") + return archive, member + + def relocated_name(self, archive, name): + if self.root is None: + return name + local = self.resolved[archive][0] if archive in self.resolved else None + if local is None and not (self.root / name).is_file(): + files = self.locations_for(archive) + if len(files) > 1: + raise ValueError(f"Cannot identify a unique source archive for {archive!r}") + local = files[0] if files else None + return local.relative_to(self.root).as_posix() if local is not None else name + + def checksum(self, archive, local): + expected = self.resolved[archive][1] if archive in self.resolved else None + return archive_checksum(local, expected=expected) + + +def archive_names(originals, *, check_collisions=True): """Relativize publisher paths using their original platform's path syntax.""" - paths = { - name: PureWindowsPath(name) if PureWindowsPath(name).drive else PurePosixPath(name) - for name in originals - } + paths = {name: publisher_path(name) for name in originals} common = os.path.commonprefix([path.parent.parts for path in paths.values()]) if paths else () result = {} for name, path in paths.items(): @@ -125,11 +181,17 @@ def archive_names(originals): volume = path.drive.strip("\\/").replace(":", "").replace("\\", "/") parts = (volume, *parts[1:]) result[name] = PurePosixPath(*parts).as_posix() - if len({s.casefold() for s in result.values()}) != len(result): - raise ValueError("Source archive names collide after conversion to portable paths") + if check_collisions: + validate_archive_names(result.values()) return result +def validate_archive_names(names): + names = list(names) + if len({name.casefold() for name in names}) != len(names): + raise ValueError("Source archive names collide after conversion to portable paths") + + def safe_path(root, relative): if ( not isinstance(relative, str) @@ -255,21 +317,32 @@ def export_vectors(workspace, output, *, licenses=(), settings=None, source_root if db.execute("SELECT 1 FROM sqlite_master WHERE name='build_sources'").fetchone(): for path, sha, size, options in db.execute("SELECT * FROM build_sources"): records.setdefault(path, []).append((sha, size, json.loads(options))) - db.create_function("source_archive", 1, lambda uri: archive_member(uri, records, source_root)[0]) - source_paths = archive_names( - r[0] - for r in db.execute( - "SELECT DISTINCT source_archive(path) FROM files WHERE path LIKE 'tar://%!/_%'" - ) - ) - defaults, by_source = supplied_settings(settings, source_paths.values()) allowed = tuple(licenses) - where = "" + predicate = "1" if allowed: placeholders = ",".join("?" for _ in allowed) - where = ( - f" WHERE coalesce(nullif({fields['license']},''),'unknown') IN ({placeholders})" + predicate = ( + f"coalesce(nullif({fields['license']},''),'unknown') IN ({placeholders})" ) + where = " WHERE " + predicate if allowed else "" + legacy = LegacyArchives(source_root) + originals, 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 + ): + candidates = archive_candidates(uri, records) + if selected: + archive, _ = legacy.member(uri, candidates) + selected_sources.add(archive) + else: + # Preserve the publisher's directory layout without requiring + # access to archives excluded by the license filter. + originals.update(archive for archive, _ in 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) + defaults, by_source = supplied_settings(settings, source_paths.values()) for row in db.execute( f"""SELECT p.id,{','.join(fields.values())}, {member}, COALESCE({embedding}, (SELECT text FROM chunks WHERE paper_id=p.id AND ord=-1 ORDER BY id DESC LIMIT 1), @@ -322,13 +395,11 @@ def export_vectors(workspace, output, *, licenses=(), settings=None, source_root ) ), ) - selected_sources = set() for path, pid in db.execute( "SELECT f.path,f.paper_id FROM files f JOIN papers p ON p.id=f.paper_id" + where, allowed, ): - original, member_name = archive_member(path, records, source_root) - selected_sources.add(original) + original, member_name = legacy.member(path, archive_candidates(path, records)) catalog.execute( "INSERT INTO files VALUES (?,?,?,?)", (source_paths[original], member_name, pid, path), @@ -362,7 +433,7 @@ def export_vectors(workspace, output, *, licenses=(), settings=None, source_root raise ValueError( f"Legacy source {name} needs its archive and explicit build settings" ) - sha, size = archive_checksum(path) + sha, size = legacy.checksum(original, path) config = supplied validate_settings(config, manifest["stage1_mode"]) manifest["sources"].append(dict(name=name, sha256=sha, size=size, settings=config)) diff --git a/tests/integration/test_portable_vectors.py b/tests/integration/test_portable_vectors.py index 7b22363..e39a22b 100644 --- a/tests/integration/test_portable_vectors.py +++ b/tests/integration/test_portable_vectors.py @@ -253,6 +253,96 @@ def test_archive_names_use_publisher_path_syntax(): assert archive_names([a, c]) == {a: "C/PMC/a/papers.tar", c: "D/PMC/a/papers.tar"} +@pytest.fixture +def relocated_legacy_archives(tmp_path): + workspace = tmp_path / "workspace" + old = tmp_path / "old" + nested = old / "outer.tar!" / "branch" / "a.tar" + peer = old / "peer" / "b.tar" + nested.parent.mkdir(parents=True) + peer.parent.mkdir() + write_tar(nested, {"one.xml": licensed_article("PMC1", "Coffee", "by", "Fresh beans.")}) + write_tar(peer, {"two.xml": licensed_article("PMC2", "Tea", "by-nc", "Tea leaves.")}) + manifest = tmp_path / "archives.txt" + manifest.write_text(f"{nested}\n{peer}\n", encoding="utf-8") + _ok( + litkit( + workspace, + "--build-only", + "--faiss-writer", + "--tar-manifest", + str(manifest), + "--papers-index", + "flat", + "--chunks-index", + "flat", + ) + ) + with closing(sqlite3.connect(workspace / "sqlite/litkit.sqlite3")) as db: + settings = json.loads( + db.execute("SELECT settings FROM build_sources LIMIT 1").fetchone()[0] + ) + db.execute("DROP TABLE build_sources") + if "\\" in str(old): + # Emulate a POSIX publisher's paths when the receiver runs on Windows. + for (path,) in db.execute("SELECT path FROM files").fetchall(): + db.execute("UPDATE files SET path=? WHERE path=?", (path.replace("\\", "/"), path)) + db.commit() + relocated = old.rename(tmp_path / "newroot") + return workspace, relocated, settings | MODELS + + +@pytest.mark.parametrize("licenses", [[], ["CC-BY-4.0"], ["CC-BY-NC-4.0"]]) +def test_relocated_nested_legacy_archive_uses_its_member( + tmp_path, relocated_legacy_archives, licenses +): + workspace, relocated, settings = relocated_legacy_archives + nested, peer = "outer.tar!/branch/a.tar", "peer/b.tar" + expected = {nested: "one.xml", peer: "two.xml"} + if licenses: + excluded = nested if licenses == ["CC-BY-NC-4.0"] else peer + (relocated / excluded).unlink() + del expected[excluded] + release = tmp_path / "release" + manifest = export_vectors( + workspace, release, settings=settings, licenses=licenses, source_root=relocated + ) + assert {s["name"]: s["sha256"] for s in manifest["sources"]} == { + name: file_hash(relocated / name) for name in expected + } + with closing(sqlite3.connect(release / "mapping.sqlite3")) as mapping: + assert dict(mapping.execute("SELECT source,member FROM files")) == expected + + +def test_ambiguous_relocated_legacy_archive_is_diagnosed(tmp_path, relocated_legacy_archives): + workspace, relocated, settings = relocated_legacy_archives + write_tar( + relocated / "outer.tar", + {"branch/a.tar!/one.xml": licensed_article("PMC1", "Coffee", "by", "Fresh beans.")}, + ) + settings_file = tmp_path / "settings.json" + settings_file.write_text(json.dumps(settings)) + release = tmp_path / "release" + result = litkit( + workspace, + "export-vectors", + str(release), + "--settings", + str(settings_file), + "--source-root", + str(relocated), + ) + assert result.returncode != 0 + assert "Cannot identify a unique source archive" in result.stderr + assert "one.xml" in result.stderr + assert not release.exists() + # Neither possible interpretation of the excluded article is needed. + filtered = export_vectors( + workspace, release, licenses=["CC-BY-NC-4.0"], settings=settings, source_root=relocated + ) + assert [archive["name"] for archive in filtered["sources"]] == ["peer/b.tar"] + + def test_release_reader_checks_manifest_before_using_files(tmp_path, portable_source): workspace, _ = portable_source bundle = tmp_path / "文献 release" From 8909bc0cd1ae84343102d94d0e7f886b1934764d Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Fri, 4 Dec 2026 15:10:48 -0700 Subject: [PATCH 4/4] Verify the archive member before choosing a relocated source Signed-off-by: Bill Hlavacek --- src/litkit/portable/release.py | 85 +++++++++++++++------- tests/integration/test_portable_vectors.py | 85 ++++++++++++++++++++++ 2 files changed, 143 insertions(+), 27 deletions(-) diff --git a/src/litkit/portable/release.py b/src/litkit/portable/release.py index 92ef7eb..6002550 100644 --- a/src/litkit/portable/release.py +++ b/src/litkit/portable/release.py @@ -81,10 +81,11 @@ def archive_candidates(uri, recorded): (path[: m.start()], path[m.end() :]) for m in re.finditer("!/", path) if m.end() < len(path) ] # A directory or an XML member may itself contain the delimiter. - return [pair for pair in candidates if pair[0] in recorded] or [ + return [ pair for pair in candidates - if pair[0] + if pair[0] in recorded + or pair[0] .lower() .endswith((".tar", ".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz")) ] @@ -97,11 +98,14 @@ def publisher_path(name): class LegacyArchives: """Locate ambiguous legacy members once per archive and hash the same edition.""" - def __init__(self, source_root): + def __init__(self, source_root, records, catalog): self.root = Path(source_root).resolve() if source_root is not None else None + self.records = records + self.catalog = catalog self.locations = {} self.members = {} self.resolved = {} + self.checksums = {} def locations_for(self, archive): if archive not in self.locations: @@ -126,26 +130,59 @@ def locations_for(self, archive): self.locations[archive] = files return self.locations[archive] + def inspect(self, path, member): + """Index names once on disk, including for multi-archive legacy workspaces.""" + if path not in self.members: + if not self.members: + self.catalog.execute( + "CREATE TEMP TABLE archive_members (archive INTEGER, member TEXT, " + "PRIMARY KEY(archive, member)) WITHOUT ROWID" + ) + number = len(self.members) + identity = archive_identity(path) + try: + with tarfile.open(path, "r|*") as handle: + self.catalog.executemany( + "INSERT OR IGNORE INTO archive_members VALUES (?,?)", + ((number, info.name) for info in handle if info.isfile()), + ) + except tarfile.TarError as error: + raise ValueError( + f"Cannot inspect candidate source archive {path}: {error}" + ) from error + self.members[path] = number, identity + number, identity = self.members[path] + found = self.catalog.execute( + "SELECT 1 FROM archive_members WHERE archive=? AND member=?", (number, member) + ).fetchone() + return identity, found is not None + def member(self, uri, candidates): - if len(candidates) == 1: + if len(candidates) == 1 and (candidates[0][0] in self.records or self.root is None): return candidates[0] matches = [] for archive, member in candidates: - for local in self.locations_for(archive): + locations = self.locations_for(archive) + versions = self.records.get(archive, []) + if versions and not locations and Path(archive).is_file(): + locations = [Path(archive)] + verified_record = False + for local in locations: path = local.resolve() - if path not in self.members: - identity = archive_identity(path) - try: - with tarfile.open(path, "r:*") as handle: - names = {info.name for info in handle if info.isfile()} - except tarfile.TarError as error: - raise ValueError( - f"Cannot inspect candidate source archive {local}: {error}" - ) from error - self.members[path] = identity, names - identity, names = self.members[path] - if member in names: + identity, found = self.inspect(path, member) + if versions: + if path not in self.checksums: + self.checksums[path] = archive_checksum(path, expected=identity) + if self.checksums[path] not in {(sha, size) for sha, size, _ in versions}: + continue + verified_record = True + if found: matches.append((archive, member, local, identity)) + if versions and not verified_record: + raise ValueError( + f"Cannot identify a unique source archive for {uri!r}: " + f"supply the recorded edition of {archive!r}" + ) if len(matches) != 1: raise ValueError(f"Cannot identify a unique source archive for {uri!r}") archive, member, local, identity = matches[0] @@ -154,15 +191,9 @@ def member(self, uri, candidates): return archive, member def relocated_name(self, archive, name): - if self.root is None: - return name - local = self.resolved[archive][0] if archive in self.resolved else None - if local is None and not (self.root / name).is_file(): - files = self.locations_for(archive) - if len(files) > 1: - raise ValueError(f"Cannot identify a unique source archive for {archive!r}") - local = files[0] if files else None - return local.relative_to(self.root).as_posix() if local is not None else name + if self.root is not None: + return self.resolved[archive][0].relative_to(self.root).as_posix() + return name def checksum(self, archive, local): expected = self.resolved[archive][1] if archive in self.resolved else None @@ -325,7 +356,7 @@ def export_vectors(workspace, output, *, licenses=(), settings=None, source_root f"coalesce(nullif({fields['license']},''),'unknown') IN ({placeholders})" ) where = " WHERE " + predicate if allowed else "" - legacy = LegacyArchives(source_root) + legacy = LegacyArchives(source_root, records, catalog) originals, 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 diff --git a/tests/integration/test_portable_vectors.py b/tests/integration/test_portable_vectors.py index e39a22b..9d58b7e 100644 --- a/tests/integration/test_portable_vectors.py +++ b/tests/integration/test_portable_vectors.py @@ -343,6 +343,91 @@ def test_ambiguous_relocated_legacy_archive_is_diagnosed(tmp_path, relocated_leg assert [archive["name"] for archive in filtered["sources"]] == ["peer/b.tar"] +@pytest.mark.parametrize("replace_recorded", [False, True]) +def test_recorded_archive_prefix_does_not_own_a_nested_legacy_member( + tmp_path, relocated_legacy_archives, replace_recorded +): + from litkit.portable.record import SOURCE_SCHEMA + + workspace, relocated, settings = relocated_legacy_archives + unrelated = write_tar(relocated / "outer.tar", {"other.xml": jats(title="Other article")}) + with closing(sqlite3.connect(workspace / "sqlite/litkit.sqlite3")) as db: + db.execute(SOURCE_SCHEMA) + db.execute( + "INSERT INTO build_sources VALUES(?,?,?,?)", + ( + (tmp_path / "old/outer.tar").as_posix(), + file_hash(unrelated), + unrelated.stat().st_size, + json.dumps(settings), + ), + ) + db.commit() + name = "outer.tar!/branch/a.tar" + release = tmp_path / "release" + if replace_recorded: + write_tar(unrelated, {"other.xml": jats(title="A later archive version")}) + with pytest.raises(ValueError, match="supply the recorded edition"): + export_vectors( + workspace, release, settings=settings, licenses=["CC-BY-4.0"], source_root=relocated + ) + assert not release.exists() + return + manifest = export_vectors( + workspace, release, settings=settings, licenses=["CC-BY-4.0"], source_root=relocated + ) + assert [(s["name"], s["sha256"]) for s in manifest["sources"]] == [ + (name, file_hash(relocated / name)) + ] + with closing(sqlite3.connect(release / "mapping.sqlite3")) as mapping: + assert mapping.execute("SELECT source,member FROM files").fetchall() == [(name, "one.xml")] + + +@pytest.mark.parametrize("duplicate_member", [False, True]) +def test_relocated_legacy_archive_with_an_unrelated_basename(tmp_path, duplicate_member): + workspace, old = tmp_path / "workspace", tmp_path / "old" + year = old / "2025" + year.mkdir(parents=True) + xml = jats(pmcid="PMC123", title="Selected paper") + write_tar(year / "papers.tar", {"selected.xml": xml}) + _ok( + litkit( + workspace, + "--build-only", + "--faiss-writer", + "--tar-dir", + str(year), + "--papers-index", + "flat", + "--chunks-index", + "flat", + ) + ) + with closing(sqlite3.connect(workspace / "sqlite/litkit.sqlite3")) as db: + settings = ( + json.loads(db.execute("SELECT settings FROM build_sources").fetchone()[0]) | MODELS + ) + db.execute("DROP TABLE build_sources") + db.commit() + relocated = old.rename(tmp_path / "newroot") + member = "selected.xml" if duplicate_member else "other.xml" + write_tar(relocated / "papers.tar", {member: jats(title="Different paper")}) + release = tmp_path / "export" + if duplicate_member: + with pytest.raises(ValueError, match="Cannot identify a unique source archive"): + export_vectors(workspace, release, settings=settings, source_root=relocated) + assert not release.exists() + else: + manifest = export_vectors(workspace, release, settings=settings, source_root=relocated) + assert [(s["name"], s["sha256"]) for s in manifest["sources"]] == [ + ("2025/papers.tar", file_hash(relocated / "2025/papers.tar")) + ] + with closing(sqlite3.connect(release / "mapping.sqlite3")) as mapping: + assert mapping.execute("SELECT source,member FROM files").fetchall() == [ + ("2025/papers.tar", "selected.xml") + ] + + def test_release_reader_checks_manifest_before_using_files(tmp_path, portable_source): workspace, _ = portable_source bundle = tmp_path / "文献 release"