diff --git a/CHANGELOG.md b/CHANGELOG.md index ee75374..5aa9c71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ 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) - 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 c4e7218..eabf022 100644 --- a/README.md +++ b/README.md @@ -227,3 +227,31 @@ 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"}} +``` + +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/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 7ff1e1f..731ab4e 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -20,6 +20,7 @@ import faiss from litkit.progress import eprint as _eprint +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, @@ -60,7 +61,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, ) @@ -508,12 +510,24 @@ def stage_indexes(paper_dir, chunk_dir): revised_shard_papers.clear() 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 # Number of *persisted* members previously processed for this tar shard start_persisted = int(ckpt_stream.get(str(tpath), 0)) 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(members): + if initial_identity is not None and archive_identity(tpath) != initial_identity: + raise ValueError(f"Source changed while ingesting {tpath}") + flush_batch(str(tpath), members) + # Set LITKIT_TAR_PRESCAN=0 to skip counting members total_members = ( count_tar_xml_members(tpath) @@ -604,7 +618,7 @@ def _render(force: bool = False): if manifest_article is not None and meta is not None: refresh_known_member(f, m, meta, manifest_article) if pending_refreshes >= ckpt_every: - flush_batch(str(tpath), start_persisted) + flush_tar_batch(start_persisted) skipped += 1 if skipped == start_persisted: _render(force=True) # render resume point @@ -631,7 +645,7 @@ def _render(force: bool = False): if manifest_article is not None and meta is not None: refresh_known_member(f, m, meta, manifest_article) if pending_refreshes >= ckpt_every: - flush_batch(str(tpath), processed_count + 1) + flush_tar_batch(processed_count + 1) processed_count += 1 continue @@ -644,6 +658,12 @@ def _render(force: bool = False): # SLOW PATH - Savepoint-protected writes # ═══════════════════════════════════════════════════════════════════ + 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 buf_snapshot = ( len(paper_ids_buf), @@ -727,11 +747,7 @@ def _render(force: bool = False): ) pid = cur.lastrowid - 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) old_ids = [] reuse_embedding = False if existing_row: @@ -804,6 +820,10 @@ def _render(force: bool = False): else: cur.execute("UPDATE papers SET embedding_text=? WHERE id=?", (ta_ab, pid)) + 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=?, publication_source=?, article_type=?, " "publication_types=?, retracted=? WHERE id=?", ( @@ -812,16 +832,9 @@ def _render(force: bool = False): )) if has_refresh_table: cur.execute("DELETE FROM publication_refreshes WHERE path=?", (f,)) - 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), @@ -894,12 +907,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(processed_count) persisted_count = processed_count _render(force=True) if pending_refreshes or processed_count != persisted_count or str(tpath) not in ckpt_stream: - flush_batch(str(tpath), processed_count) + flush_tar_batch(processed_count) _render(force=True) _progress_newline(sys.stderr) diff --git a/src/litkit/build/publication.py b/src/litkit/build/publication.py index f7d66be..9604b78 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", "obsolete_paper_vectors", "paper_doc_aliases", "paper_citation_links"): + for table in ("merged_paper_revisions", "obsolete_chunk_vectors", "obsolete_paper_vectors", "paper_doc_aliases", "paper_citation_links", "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 7cb688a..f96e85a 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1845,6 +1845,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 + if sys.argv[1:2] == ["build-fts"]: from contextlib import closing from litkit.config.paths import WorkspacePaths @@ -1902,6 +1907,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" " 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/db/schema.py b/src/litkit/db/schema.py index 9457597..0ff1270 100644 --- a/src/litkit/db/schema.py +++ b/src/litkit/db/schema.py @@ -45,6 +45,7 @@ -- Paper vector input when multiple versions share an ID embedding_text TEXT, references_json TEXT, + license TEXT, license_url TEXT, build_member TEXT, publication_source BLOB, article_type TEXT, publication_types TEXT, @@ -94,7 +95,7 @@ def optional_paper_columns( return { name: (f"{prefix}{name}" if name in cols else "NULL") for name in ("doc_id", "source_path", "doi", "year", "authors", "journal", "references_json", - "publication_source", "article_type", "publication_types", "retracted") + "license", "license_url", "build_member", "publication_source", "article_type", "publication_types", "retracted") } @@ -252,6 +253,8 @@ def ensure_paper_embedding_column(conn: sqlite3.Connection) -> None: _ADDED_COLUMNS = ( + ("papers", "license", "TEXT"), ("papers", "license_url", "TEXT"), + ("papers", "build_member", "TEXT"), ("papers", "publication_source", "BLOB"), ("papers", "article_type", "TEXT"), ("papers", "publication_types", "TEXT"), diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index da00798..c1179fc 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -228,6 +228,7 @@ def _merge_revised_papers(conn, shard, mapping, since): revisions = conn.execute(f""" SELECT m.history_only, m.new_alias, p.doc_id, 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']}, {p_cols['publication_source']}, {p_cols['article_type']}, {p_cols['publication_types']}, {p_cols['retracted']}, 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)) @@ -253,6 +254,7 @@ def _merge_revised_papers(conn, shard, mapping, since): authors, journal, references_json, + license_name, license_url, build_member, publication_source, article_type, publication_types, retracted, embedding_text, ) in revisions: @@ -284,6 +286,7 @@ def _merge_revised_papers(conn, shard, mapping, since): (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, + license=:license, license_url=:url, build_member=:member, publication_source=:publication_source, article_type=:article_type, publication_types=:types, retracted=:retracted, doi=COALESCE(NULLIF(:doi,''), doi), @@ -292,6 +295,7 @@ def _merge_revised_papers(conn, shard, mapping, since): 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, + "license": license_name, "url": license_url, "member": build_member, "publication_source": publication_source, "article_type": article_type, "types": publication_types, "retracted": retracted, "doi": doi, "year": year, "authors": authors, "journal": journal, "id": main_id, "pmid": pmid, "pmcid": pmcid}) @@ -398,14 +402,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, publication_source, article_type, publication_types, retracted, in_index + doc_id, pmid, pmcid, doi, year, authors, journal, title, abstract, source_path, embedding_text, references_json, license, license_url, build_member, publication_source, article_type, publication_types, retracted, 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']}, + {p_cols['license']}, {p_cols['license_url']}, {p_cols['build_member']}, {p_cols['publication_source']}, {p_cols['article_type']}, {p_cols['publication_types']}, {p_cols['retracted']}, 0 FROM {shard_alias}.papers p WHERE p.doc_id IS NOT NULL 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/index/io.py b/src/litkit/index/io.py index d0798d7..7163a58 100644 --- a/src/litkit/index/io.py +++ b/src/litkit/index/io.py @@ -53,14 +53,19 @@ def _assert_faiss_locked() -> None: ) -def _write_index_atomically(index: faiss.Index, path: Path) -> None: - tmp = path.with_suffix(path.suffix + ".tmp") +def write_index(index: faiss.Index, path: Path) -> None: + """Write to a caller-owned file, including Unicode paths on Windows.""" if os.name == "nt": # FAISS 1.8 uses narrow filenames on Windows. Python opens Unicode paths. - with tmp.open("wb") as stream: + with path.open("wb") as stream: faiss.write_index(index, faiss.PyCallbackIOWriter(stream.write)) else: - faiss.write_index(index, str(tmp)) + faiss.write_index(index, str(path)) + + +def _write_index_atomically(index: faiss.Index, path: Path) -> None: + tmp = path.with_suffix(path.suffix + ".tmp") + write_index(index, tmp) # fsync the temp file before rename for durability try: diff --git a/src/litkit/ingest/ingest.py b/src/litkit/ingest/ingest.py index 353e21b..5a33b70 100644 --- a/src/litkit/ingest/ingest.py +++ b/src/litkit/ingest/ingest.py @@ -115,6 +115,8 @@ class ArticleMeta(TypedDict): abstract: str paragraphs: list[str] source_path: NotRequired[str] + license: NotRequired[str] + license_url: NotRequired[str] article_type: NotRequired[str] publication_types: NotRequired[list[str]] retracted: NotRequired[bool] @@ -1138,6 +1140,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 from litkit.ingest.publication_types import classify raw_type = root.get("article-type", "") 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..4053123 --- /dev/null +++ b/src/litkit/portable/record.py @@ -0,0 +1,94 @@ +"""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 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 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): + """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: + 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+)(?:/|$)", + 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..6002550 --- /dev/null +++ b/src/litkit/portable/release.py @@ -0,0 +1,633 @@ +"""Export a text-free catalog and matching FAISS files from a completed workspace.""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import shutil +import sqlite3 +import tarfile +import tempfile +from contextlib import closing, contextmanager +from pathlib import Path, PurePosixPath, PureWindowsPath + +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.index.io import faiss_load, write_index +from litkit.portable.record import archive_checksum, archive_identity, 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", + "publication_source", +) +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_candidates(uri, recorded): + if not uri.startswith("tar://"): + 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. + return [ + pair + for pair in candidates + if pair[0] in recorded + or 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, 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: + if self.root is None: + local = Path(archive) + 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 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 and (candidates[0][0] in self.records or self.root is None): + return candidates[0] + matches = [] + for archive, member in candidates: + 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() + 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] + 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 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 + 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: 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(): + 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 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) + or not relative + or str(PurePosixPath(relative)) != relative + or relative == "." + or "\\" in relative + or PureWindowsPath(relative).drive + or ".." in PurePosixPath(relative).parts + or any( + PureWindowsPath(part).is_reserved() + or part.endswith((" ", ".")) + or re.search(r'[<>:"|?*\x00-\x1f]', part) + for part 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}") + 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, *, filtered): + """Check the entire label mapping before publishing even a filtered subset.""" + 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_load(target if selected == row_count else source) + if not isinstance(index, faiss.IndexIDMap2): + raise ValueError(f"{kind} index has no external ID map") + 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 [] + 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 + 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( + 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.") + # 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 != selected: + raise ValueError(f"Could not remove all excluded {kind} vectors") + write_index(index, 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 = {k: f"p.{k}" if k in cols else "NULL" for k in PAPER_FIELDS} + if "publication_source" in cols: + fields["publication_source"] = ( + "CASE WHEN p.publication_source IS NOT NULL THEN lower(hex(p.publication_source)) END" + ) + 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" + 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))) + allowed = tuple(licenses) + predicate = "1" + if allowed: + placeholders = ",".join("?" for _ in allowed) + predicate = ( + f"coalesce(nullif({fields['license']},''),'unknown') IN ({placeholders})" + ) + where = " WHERE " + predicate if allowed else "" + 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 + ): + 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), + 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 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" + ) + 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, + ) + ), + ) + 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 = legacy.member(path, archive_candidates(path, records)) + catalog.execute( + "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" + ).fetchone(): + raise ValueError("A selected paper lacks an archive member mapping") + manifest = { + "format": FORMAT_VERSION, + "stage1_mode": get_stage1_mode(db), + "licenses": list(allowed), + "sources": [], + "indices": {}, + "checksums": {}, + } + 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( + 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, supplied) + else: + path = safe_path(source_root, name) if source_root else Path(original) + if not supplied or not path.is_file(): + raise ValueError( + f"Legacy source {name} needs its archive and explicit build settings" + ) + 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)) + validate_models(manifest["sources"], manifest["stage1_mode"]) + 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, filtered=bool(allowed) + ) + 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" + ) + 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) + 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 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 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 ( + 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") + 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"]: + 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") + safe_path(release, item.get("name")) + name = item["name"].casefold() + if name in names: + raise ValueError(f"Duplicate source archive {item['name']!r}") + names.add(name) + 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]: + 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 f266e1f..c06f0c8 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 @@ -942,7 +967,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": @@ -951,7 +976,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..9d58b7e --- /dev/null +++ b/tests/integration/test_portable_vectors.py @@ -0,0 +1,459 @@ +"""Portable FAISS releases preserve external IDs across machines and source revisions.""" + +import json +import sqlite3 +from contextlib import closing + +import faiss +import pytest +from test_build_and_query import _ok, litkit + +from conftest import downgrade_to_0_3_33, jats, write_tar +from litkit.index.io import faiss_load +from litkit.portable.record import file_hash +from litkit.portable.release import archive_names, export_vectors, read_manifest + +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 / "papers.tar!" + 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_load(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() + + +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"} + + +@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"] + + +@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" + 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) + + +def test_archive_names_can_be_downloaded_on_windows(tmp_path): + from litkit.portable.release import safe_path + + with pytest.raises(ValueError, match="collide"): + archive_names(["/data/Cohort.tar", "/data/cohort.tar"]) + for name in ("studies/CON.tar", "bad?/papers.tar", "trailing./papers.tar"): + with pytest.raises(ValueError, match="Invalid release path"): + safe_path(tmp_path, name)