diff --git a/CHANGELOG.md b/CHANGELOG.md index 95f98a7..87e8a54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ internal versions are summarized under 0.3.33. ## [Unreleased] ### Added +- Index individual PMID records in PubMed baseline XML gzip files and multi-record tar members. Abstract-only papers remain searchable alongside PMC OA full text. (#73) - Restore released FAISS files on CPU with verified passage IDs, or fetch matching PMC full text and PubMed abstracts on demand. (#65) - `litkit export-vectors` writes FAISS indexes, text hashes, source checksums, model revisions and per-paper attribution. Use `--license` to select licenses. (#65) - Paper and passage results report publication type and retraction status. Search with repeatable `--type` and `--exclude-type` filters. (#58) diff --git a/README.md b/README.md index d739a13..11e8cd5 100644 --- a/README.md +++ b/README.md @@ -276,3 +276,19 @@ Hybrid mode reranks the fetched candidates using lexical and semantic ranks. Queries require the recorded chunk embedding model. Subsequent queries reuse the cached XML. Pass the same `--cache DIR` to a rebuild to recover verified articles that are missing from the bulk sources. + +### Building a combined PubMed and PMC corpus + +Put the NLM annual PubMed baseline files (`pubmed*.xml.gz`) and PMC OA JATS tar +archives in the directory passed to `--tar-dir`, or list them in a tar +manifest. LitKit streams each PubMed citation using its own PMID. Papers with +an abstract and no PMCID are indexed and searchable. If a PMC article has the +same PMID, the index retains the full text and its body passages whichever +source is processed first. Many PubMed citations have no abstract from NLM. + +Use an unfiltered vector export to retain every indexed abstract. PubMed +records often have no machine-readable license, so an export restricted to +named Creative Commons licenses omits them. A receiver can restore from the +same files or fetch matching abstracts by PMID during on-demand search. +The baseline reader stops if it encounters a daily-update `DeleteCitation` +notice. Deletion synchronization is separate from a fresh annual-baseline build. diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index 731ab4e..a33f3ac 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -15,7 +15,7 @@ from contextlib import ExitStack, nullcontext from pathlib import Path from types import SimpleNamespace -from typing import TYPE_CHECKING, Iterator, Sequence +from typing import IO, TYPE_CHECKING, Callable, Iterator, Sequence import faiss @@ -34,6 +34,7 @@ parallel_iter_tar_articles, parse_xml_fileobj, ) +from litkit.ingest.pubmed_bulk import record_name from litkit.ingest.publication_types import publication_fields, publication_source from litkit.ingest import is_uncompressed_tar from litkit.index import ( @@ -104,6 +105,7 @@ def iter_tar_articles( *, include_tables: bool = False, max_table_chars: int = DEFAULT_MAX_TABLE_CHARS, + legacy_member: Callable[[str, IO[bytes]], bool] | None = None, ) -> Iterator[tuple[TarMemberMeta, ArticleMeta]]: """Unified iterator over articles in a tar file. @@ -117,7 +119,7 @@ def iter_tar_articles( """ from litkit.progress import is_quiet - use_parallel = parse_workers > 1 and is_uncompressed_tar(tar_path) + use_parallel = legacy_member is None and parse_workers > 1 and is_uncompressed_tar(tar_path) if use_parallel: if not is_quiet(): @@ -131,7 +133,7 @@ def iter_tar_articles( yield member_meta, article_meta else: # Sequential path for compressed tars (or when parallel disabled) - for tarinfo, fobj in iter_tar_xml_streams(tar_path): + for tarinfo, fobj in iter_tar_xml_streams(tar_path, legacy_member=legacy_member): try: reader = _HashingReader(fobj) article_meta = parse_xml_fileobj( @@ -146,6 +148,7 @@ def iter_tar_articles( size=int(getattr(tarinfo, "size", 0)), mtime=float(getattr(tarinfo, "mtime", 0.0) or 0.0), content_sha256=reader.digest(), + bulk_record=getattr(tarinfo,"bulk_record",False), ) yield member_meta, article_meta finally: @@ -531,7 +534,7 @@ def flush_tar_batch(members): # Set LITKIT_TAR_PRESCAN=0 to skip counting members total_members = ( count_tar_xml_members(tpath) - if os.environ.get("LITKIT_TAR_PRESCAN", "1") == "1" + if not tpath.name.lower().endswith(".xml.gz") and os.environ.get("LITKIT_TAR_PRESCAN", "1") == "1" else None ) @@ -612,8 +615,24 @@ def _render(force: bool = False): include_tables=include_tables, max_table_chars=max_table_chars, ): - f = f"tar://{tpath}!/{m.name}" + f = f"tar://{tpath}!/{record_name(m,meta)}" + if getattr(m, "bulk_record", False): + # The quick tar-header count omits siblings in an XML member. + total_members = None manifest_article = manifest_articles.get(m.name.removeprefix("./")) + st = SimpleNamespace( + st_size=int(getattr(m, "size", 0)), + content_sha256=m.content_sha256 if getattr(m,"bulk_record",False) else None, + st_mtime=float(getattr(m, "mtime", 0.0) or 0.0), + ) + + if skipped < start_persisted and st.content_sha256: + # Older checkpoints counted whole XML members. Validate each bulk PMID before + # skipping its position, including when a distribution was revised or reordered. + local = db_already_processed(cur, f, st) + remote = merged_has_file_hash and db_already_processed(merged, f, st, require_indexed=True) + if not (local or remote): + start_persisted = processed_count = persisted_count = skipped if skipped < start_persisted: if manifest_article is not None and meta is not None: refresh_known_member(f, m, meta, manifest_article) @@ -624,11 +643,6 @@ def _render(force: bool = False): _render(force=True) # render resume point continue - st = SimpleNamespace( - st_size=int(getattr(m, "size", 0)), - st_mtime=float(getattr(m, "mtime", 0.0) or 0.0), - ) - # ═══════════════════════════════════════════════════════════════════ # FAST PATH - No savepoint overhead for already-processed or unparsable # ═══════════════════════════════════════════════════════════════════ @@ -639,7 +653,7 @@ def _render(force: bool = False): # Fast path 1: already processed (vast majority in --update mode) if not rebuilding_tar: known = db_already_processed(cur, f, st) - if not known and merged is not None and db_already_processed(merged, f, st, require_indexed=True): + if not known and merged is not None and (not st.content_sha256 or merged_has_file_hash) and db_already_processed(merged, f, st, require_indexed=True): known = not cur.execute("SELECT 1 FROM files WHERE path=?", (f,)).fetchone() if known: if manifest_article is not None and meta is not None: @@ -749,8 +763,13 @@ def _render(force: bool = False): ta_ab = paper_input(meta) old_ids = [] - reuse_embedding = False - if existing_row: + keep_full_text = bool(existing_row and meta.get("text_source") == "pubmed" and + cur.execute("""SELECT 1 FROM papers p WHERE p.id=? AND + (p.text_source='jats-full-text' OR (p.text_source IS NULL AND EXISTS + (SELECT 1 FROM chunks c WHERE c.paper_id=p.id AND c.ord>=0 + AND coalesce(c.section,'')!='Abstract')))""",(pid,)).fetchone()) + reuse_embedding = keep_full_text + if existing_row and not keep_full_text: if previous_text is None: prior = cur.execute( "SELECT text FROM chunks WHERE paper_id=? AND ord=-1 ORDER BY id DESC LIMIT 1", @@ -787,63 +806,72 @@ def _render(force: bool = False): record_citation_link(cur, pid) db_register_file(cur, str(f), pid, st) - # Another shard may have installed a different version - # since this retained shard last embedded the paper. - if paper_embedder is not None and (not reuse_embedding or shard_revision): - paper_ids_buf.append(pid) - paper_texts_buf.append(ta_ab) - paper_doc_ids_buf.append(canon_doc_id) - if existing_row or shard_revision: - if not shard_revision and not supplied_link: - pmid, pmcid = available_citation_ids(canon_doc_id, pmid, pmcid, cur, merged) - cur.execute( - "UPDATE papers SET title=?, abstract=?, source_path=?, embedding_text=?, " - "doi=COALESCE(NULLIF(?, ''), doi), " - "year=COALESCE(?, year), " - "authors=COALESCE(NULLIF(?, ''), authors), " - "journal=COALESCE(NULLIF(?, ''), journal), " - "pmid=COALESCE(NULLIF(pmid,''),?), pmcid=COALESCE(NULLIF(pmcid,''),?) WHERE id=?", - ( - meta["title"], - meta["abstract"], - meta.get("source_path"), - ta_ab, - meta.get("doi"), - meta.get("year"), - meta.get("authors"), - meta.get("journal"), - pmid, - pmcid, - pid, - ), - ) - 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=?", ( - json.dumps(bibliography, ensure_ascii=False) if bibliography is not None else None, - publication_source(f, m.content_sha256), *publication_fields(meta, manifest_article), pid, - )) - if has_refresh_table: - cur.execute("DELETE FROM publication_refreshes WHERE path=?", (f,)) - 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), - ) - cid = cur.lastrowid - chunk_ids_buf.append(cid) - chunk_texts_buf.append(text_i) - chunk_paper_doc_ids_buf.append(canon_doc_id) - chunk_ords_buf.append(ord_i) + if keep_full_text: + # PubMed-only records supplement the existing full text. Keep its + # passages, source-bound license/status, and existing FAISS labels. + cur.execute("""UPDATE papers SET pmid=coalesce(nullif(pmid,''),?), + pmcid=coalesce(nullif(pmcid,''),?), doi=coalesce(nullif(doi,''),?), + authors=coalesce(nullif(authors,''),?), journal=coalesce(nullif(journal,''),?), + year=coalesce(year,?) WHERE id=?""", + (pmid,pmcid,meta.get("doi"),meta.get("authors"),meta.get("journal"),meta.get("year"),pid)) + else: + # Another shard may have installed a different version + # since this retained shard last embedded the paper. + if paper_embedder is not None and (not reuse_embedding or shard_revision): + paper_ids_buf.append(pid) + paper_texts_buf.append(ta_ab) + paper_doc_ids_buf.append(canon_doc_id) + if existing_row or shard_revision: + if not shard_revision and not supplied_link: + pmid, pmcid = available_citation_ids(canon_doc_id, pmid, pmcid, cur, merged) + cur.execute( + "UPDATE papers SET title=?, abstract=?, source_path=?, embedding_text=?, " + "doi=COALESCE(NULLIF(?, ''), doi), " + "year=COALESCE(?, year), " + "authors=COALESCE(NULLIF(?, ''), authors), " + "journal=COALESCE(NULLIF(?, ''), journal), " + "pmid=COALESCE(NULLIF(pmid,''),?), pmcid=COALESCE(NULLIF(pmcid,''),?) WHERE id=?", + ( + meta["title"], + meta["abstract"], + meta.get("source_path"), + ta_ab, + meta.get("doi"), + meta.get("year"), + meta.get("authors"), + meta.get("journal"), + pmid, + pmcid, + pid, + ), + ) + else: + cur.execute("UPDATE papers SET embedding_text=? WHERE id=?", (ta_ab, pid)) + + cur.execute("UPDATE papers SET license=?,license_url=?,build_member=?,text_source=? WHERE id=?", + (meta.get("license"), meta.get("license_url"), f, meta.get("text_source"), pid)) + bibliography = meta.get("references") + cur.execute("UPDATE papers SET references_json=?, publication_source=?, article_type=?, " + "publication_types=?, retracted=? WHERE id=?", ( + json.dumps(bibliography, ensure_ascii=False) if bibliography is not None else None, + publication_source(f, m.content_sha256), *publication_fields(meta, manifest_article), pid, + )) + if has_refresh_table: + cur.execute("DELETE FROM publication_refreshes WHERE path=?", (f,)) + 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), + ) + cid = cur.lastrowid + chunk_ids_buf.append(cid) + chunk_texts_buf.append(text_i) + chunk_paper_doc_ids_buf.append(canon_doc_id) + chunk_ords_buf.append(ord_i) # ---------- END INGEST BODY ---------- @@ -924,6 +952,7 @@ def _render(force: bool = False): ) with owner_lock, ExitStack() as readers: merged = None + merged_has_file_hash = False merged_has_types = False merged_sequence = 0 has_refresh_table = bool(conn.execute( @@ -954,6 +983,7 @@ def _render(force: bool = False): has_files = main_db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='files'").fetchone() if has_files and main_db.execute("SELECT 1 FROM files LIMIT 1").fetchone(): merged = main_db.cursor() + merged_has_file_hash = "content_sha256" in table_columns(main_db, "files") merged_has_types = "publication_source" in table_columns(main_db, "papers") merged_has_links = bool(merged.execute( "SELECT 1 FROM sqlite_master WHERE name='paper_citation_links'" diff --git a/src/litkit/build/training.py b/src/litkit/build/training.py index 0f9ba40..bbd038f 100644 --- a/src/litkit/build/training.py +++ b/src/litkit/build/training.py @@ -188,6 +188,10 @@ def _flush_train(buf: list[str]) -> np.ndarray: _env_cap = int(os.environ.get("LITKIT_TRAIN_PER_PAPER", "0")) if _env_cap > 0: train_per_paper = _env_cap + elif any(path.name.lower().endswith(".xml.gz") for path in tar_paths_list): + # The annual PubMed baseline has millions of citations. Use the large-corpus + # sampling budget without decompressing every file for a training estimate. + train_per_paper = 8 else: est_papers = 0 for _p in tar_paths_list: @@ -198,8 +202,6 @@ def _flush_train(buf: list[str]) -> np.ndarray: est_papers = max(1, est_papers) train_per_paper = max(8, min(64, math.ceil(train_samples / est_papers))) - target_papers = max(1, train_samples // max(1, train_per_paper)) - papers_used = 0 train_total = sum(int(x.shape[0]) for x in X_train_list) for tpath in tar_paths_list: @@ -218,13 +220,14 @@ def _flush_train(buf: list[str]) -> np.ndarray: text for text, _ in pack_body(meta, chunk_target_chars, chunk_min_chars, chunk_overlap) ] - if chunks and papers_used < target_papers: + if chunks: sel = ( chunks if len(chunks) <= train_per_paper else rng.sample(chunks, train_per_paper) ) - for ch in sel: + remaining = train_samples - train_total - len(texts_buf) + for ch in sel[:remaining]: texts_buf.append(ch) if len(texts_buf) >= batch_train_flush: Xb = _flush_train(texts_buf) @@ -233,9 +236,8 @@ def _flush_train(buf: list[str]) -> np.ndarray: texts_buf.clear() if train_total >= train_samples: break - papers_used += 1 - if papers_used >= target_papers or train_total >= train_samples: + if train_total + len(texts_buf) >= train_samples: break finally: try: @@ -243,7 +245,7 @@ def _flush_train(buf: list[str]) -> np.ndarray: except Exception: pass - if papers_used >= target_papers or train_total >= train_samples: + if train_total + len(texts_buf) >= train_samples: break # Flush remaining buffer diff --git a/src/litkit/cli.py b/src/litkit/cli.py index b0875c6..f0ec1fe 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -2399,6 +2399,7 @@ def _has_tars(p: Path) -> bool: any(p.glob("*.tar")) or any(p.glob("*.tar.*")) # catches .tar.gz, .tar.bz2, etc. or any(p.glob("*.tgz")) + or any(p.glob("*.xml.gz")) ) except Exception: return False @@ -2463,7 +2464,7 @@ def _pick(cands: list[Path]) -> Path | None: if needs_corpus and args.tar_manifest is None and args.tar_dir is not None and not _has_tars(args.tar_dir): raise SystemExit( f"No tar shards found in {args.tar_dir}\n" - "Expected one of: *.tar, *.tar.gz, *.tar.*, or *.tgz.\n" + "Expected one of: *.tar, *.tar.gz, *.tar.*, *.tgz, or PubMed *.xml.gz.\n" "Specify a directory containing shards via --tar-dir or LITKIT_TAR_DIR, " "or pass a file with absolute shard paths via --tar-manifest.\n" f"Defaults: {ROOT.parent / 'litkit_input' / 'tar_shards'} or {WORKSPACE / 'tar_shards'}." diff --git a/src/litkit/db/queries.py b/src/litkit/db/queries.py index 6e48e41..582b299 100644 --- a/src/litkit/db/queries.py +++ b/src/litkit/db/queries.py @@ -36,19 +36,23 @@ def already_processed( Returns: True if file was already processed with same size/mtime """ + checksum = getattr(st, "content_sha256", None) + hash_column = ", f.content_sha256" if checksum else "" if require_indexed: # A SQLite-only worker can register files without ever writing vectors. - cur.execute(""" - SELECT f.size, f.mtime FROM files f JOIN papers p ON p.id=f.paper_id + cur.execute(f""" + SELECT f.size, f.mtime{hash_column} FROM files f JOIN papers p ON p.id=f.paper_id WHERE f.path=? AND p.in_index=1 AND EXISTS (SELECT 1 FROM chunks c WHERE c.paper_id=p.id) AND NOT EXISTS (SELECT 1 FROM chunks c WHERE c.paper_id=p.id AND c.in_index IS NOT 1) """, (fpath,)) else: - cur.execute("SELECT size, mtime FROM files WHERE path=?", (fpath,)) + cur.execute(f"SELECT f.size, f.mtime{hash_column} FROM files f WHERE path=?", (fpath,)) row = cur.fetchone() if row is None: return False + if checksum: + return row[2] == checksum size, mtime = row return size == st.st_size and abs(mtime - st.st_mtime) < 1e-6 @@ -67,6 +71,11 @@ def register_file( paper_id: Associated paper ID st: SimpleNamespace or os.stat() result with st_size and st_mtime """ + checksum = getattr(st, "content_sha256", None) + if checksum: + cur.execute("INSERT OR REPLACE INTO files(path,size,mtime,paper_id,content_sha256) VALUES(?,?,?,?,?)", + (fpath, st.st_size, st.st_mtime, paper_id, checksum)) + return cur.execute( "INSERT OR REPLACE INTO files(path, size, mtime, paper_id) " "VALUES (?, ?, ?, ?)", diff --git a/src/litkit/db/schema.py b/src/litkit/db/schema.py index 0ff1270..464e20b 100644 --- a/src/litkit/db/schema.py +++ b/src/litkit/db/schema.py @@ -45,7 +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, + license TEXT, license_url TEXT, build_member TEXT, text_source TEXT, publication_source BLOB, article_type TEXT, publication_types TEXT, @@ -68,6 +68,7 @@ path TEXT PRIMARY KEY, size INTEGER, mtime REAL, + content_sha256 BLOB, paper_id INTEGER ); CREATE UNIQUE INDEX IF NOT EXISTS papers_pmcid_uq ON papers(pmcid) WHERE pmcid <> ''; @@ -95,7 +96,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", - "license", "license_url", "build_member", "publication_source", "article_type", "publication_types", "retracted") + "license", "license_url", "build_member", "text_source", "publication_source", "article_type", "publication_types", "retracted") } @@ -254,7 +255,8 @@ def ensure_paper_embedding_column(conn: sqlite3.Connection) -> None: _ADDED_COLUMNS = ( ("papers", "license", "TEXT"), ("papers", "license_url", "TEXT"), - ("papers", "build_member", "TEXT"), + ("papers", "build_member", "TEXT"), ("papers", "text_source", "TEXT"), + ("files", "content_sha256", "BLOB"), ("papers", "publication_source", "BLOB"), ("papers", "article_type", "TEXT"), ("papers", "publication_types", "TEXT"), @@ -277,7 +279,7 @@ def ensure_paper_embedding_column(conn: sqlite3.Connection) -> None: def _missing_columns(conn: sqlite3.Connection) -> list[tuple[str, str, str]]: cols = { table: {row[1] for row in conn.execute(f"PRAGMA table_info({table})")} - for table in ("papers", "chunks") + for table in ("papers", "chunks", "files") } missing = [c for c in _ADDED_COLUMNS if c[1] not in cols[c[0]]] if "doc_id" not in cols["papers"]: diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index c1179fc..0f03b5f 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -18,6 +18,7 @@ from litkit.db.queries import available_citation_ids, consolidate_owners, linked_owners, record_citation_link from litkit.db.normalization import normalize_doi from litkit.db.schema import ( + table_columns, DEFAULT_STAGE1_MODE, ensure_in_index_columns, ensure_paper_embedding_column, @@ -228,7 +229,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['license']}, {p_cols['license_url']}, {p_cols['build_member']}, {p_cols['text_source']}, {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)) @@ -254,7 +255,7 @@ def _merge_revised_papers(conn, shard, mapping, since): authors, journal, references_json, - license_name, license_url, build_member, + license_name, license_url, build_member, text_source, publication_source, article_type, publication_types, retracted, embedding_text, ) in revisions: @@ -273,10 +274,12 @@ def _merge_revised_papers(conn, shard, mapping, since): if history_only: # Import any citation fields the bridge lacked but preserve its text, # passages, and bibliography. The files mapping below retains the archive. - conn.execute("""UPDATE papers SET doi=COALESCE(NULLIF(doi,''),?), + pmid, pmcid = available_citation_ids(doc_id, pmid, pmcid, conn) + conn.execute("""UPDATE papers SET pmid=coalesce(nullif(pmid,''),?), + pmcid=coalesce(nullif(pmcid,''),?), doi=COALESCE(NULLIF(doi,''),?), year=COALESCE(year,?), authors=COALESCE(NULLIF(authors,''),?), journal=COALESCE(NULLIF(journal,''),?) WHERE id=?""", - (doi, year, authors, journal, main_id)) + (pmid, pmcid, doi, year, authors, journal, main_id)) continue pmid, pmcid = available_citation_ids(doc_id, pmid, pmcid, conn) # Status belongs to the revision supplying the text. A legacy @@ -286,7 +289,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, + license=:license, license_url=:url, build_member=:member, text_source=:text_source, publication_source=:publication_source, article_type=:article_type, publication_types=:types, retracted=:retracted, doi=COALESCE(NULLIF(:doi,''), doi), @@ -295,7 +298,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, + "license": license_name, "url": license_url, "member": build_member, "text_source": text_source, "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}) @@ -410,11 +413,11 @@ def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge, to_record): # 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, license, license_url, build_member, 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, text_source, 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['license']}, {p_cols['license_url']}, {p_cols['build_member']}, {p_cols['text_source']}, {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 @@ -487,6 +490,19 @@ def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge, to_record): WHERE NULLIF(pmid,'') IS NULL OR NULLIF(pmcid,'') IS NULL) {unlinked}""") + # Keep richer OA content whichever producer is consumed first. + if p_cols["text_source"] != "NULL": + main_cur.execute(f"""UPDATE {temp_map_table} AS m SET history_only=1 + FROM {shard_alias}.papers s JOIN papers d + WHERE m.shard_pid=s.id AND m.main_pid=d.id AND s.text_source='pubmed' + AND (d.text_source='jats-full-text' OR (d.text_source IS NULL AND EXISTS + (SELECT 1 FROM chunks c WHERE c.paper_id=d.id AND c.ord>=0 + AND coalesce(c.section,'')!='Abstract')))""") + main_cur.execute(f"""UPDATE {temp_map_table} AS m SET history_only=0 + FROM {shard_alias}.papers s JOIN papers d + WHERE m.shard_pid=s.id AND m.main_pid=d.id + AND s.text_source='jats-full-text' AND d.text_source='pubmed'""") + # Insert chunks with remapped paper_id main_cur.execute("CREATE TABLE IF NOT EXISTS merged_paper_revisions (paper_id INTEGER PRIMARY KEY)") main_cur.execute(f""" @@ -524,9 +540,10 @@ def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge, to_record): # 3) BULK MERGE FILES # Insert/replace files with remapped paper_id + hash_column = "sf.content_sha256" if "content_sha256" in table_columns(main_conn,"files",shard_alias) else "NULL" main_cur.execute(f""" - INSERT OR REPLACE INTO files(path, size, mtime, paper_id) - SELECT sf.path, sf.size, sf.mtime, pm.main_pid + INSERT OR REPLACE INTO files(path, size, mtime, paper_id, content_sha256) + SELECT sf.path, sf.size, sf.mtime, pm.main_pid, {hash_column} FROM {shard_alias}.files sf JOIN {temp_map_table} pm ON pm.shard_pid = sf.paper_id """) diff --git a/src/litkit/ingest/ingest.py b/src/litkit/ingest/ingest.py index 5a33b70..ee6f2a7 100644 --- a/src/litkit/ingest/ingest.py +++ b/src/litkit/ingest/ingest.py @@ -40,13 +40,16 @@ from __future__ import annotations +from types import SimpleNamespace + +import gzip import hashlib import io import logging import re import tarfile import threading -from collections.abc import Iterable, Iterator +from collections.abc import Callable, Iterable, Iterator from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait from contextlib import closing, contextmanager from pathlib import Path, PureWindowsPath @@ -65,7 +68,7 @@ # Ingest XML and JATS/NXML files _XML_EXTS = (".nxml", ".xml") -_TAR_EXTS = (".tar", ".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz") +_TAR_EXTS = (".tar", ".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz", ".xml.gz") _PAGE_LABEL_RE = re.compile(r"[1-9][0-9]{0,8}") _YEAR_RE = re.compile(r"\b(1\d{3}|2\d{3})\b") @@ -114,6 +117,7 @@ class ArticleMeta(TypedDict): title: str abstract: str paragraphs: list[str] + text_source: NotRequired[str] source_path: NotRequired[str] license: NotRequired[str] license_url: NotRequired[str] @@ -1139,6 +1143,7 @@ def _walk_root(node: etree._Element) -> None: "title": title or "", "abstract": abstract or "", "paragraphs": paras, + "text_source": "jats-full-text" if paras else "jats", } from litkit.portable.record import jats_license @@ -1187,12 +1192,24 @@ def parse_pubmed(tree: etree._ElementTree) -> ArticleMeta: records = tree.xpath('(//*[local-name()="PubmedArticle"])[1]') article = records[0] if records else tree.getroot() xp = article.xpath + if _localname(article.tag) == "PubmedBookArticle" or (_localname(article.tag)=="PubmedArticleSet" and not records): + books = article.xpath("descendant-or-self::*[local-name()='PubmedBookArticle']") + if books: + xp = books[0].xpath + title = xp("string(.//*[local-name()='BookDocument']/*[local-name()='Book']/*[local-name()='BookTitle'])") + title = xp("string(.//*[local-name()='BookDocument']/*[local-name()='ArticleTitle'])") or title + abstract = " ".join(_txt(n) for n in xp(".//*[local-name()='BookDocument']/*[local-name()='Abstract']/*[local-name()='AbstractText']")) + return {"pmid": xp("string(.//*[local-name()='BookDocument']/*[local-name()='PMID'])").strip(), + "pmcid": "", "title": title.strip(), "abstract": abstract.strip(), "paragraphs": [], + "text_source": "pubmed"} pmid = xp('string(.//*[local-name()="MedlineCitation"]/*[local-name()="PMID"][1])').strip() title = xp('string(.//*[local-name()="Article"]/*[local-name()="ArticleTitle"][1])').strip() abs_nodes = xp( './/*[local-name()="Article"]/*[local-name()="Abstract"]/*[local-name()="AbstractText"]' ) - abstract = " ".join([_txt(n) for n in abs_nodes]).strip() + if not abs_nodes: + abs_nodes = xp('.//*[local-name()="MedlineCitation"]/*[local-name()="OtherAbstract"]/*[local-name()="AbstractText"]') + abstract = " ".join(_txt(n) for n in abs_nodes).strip() # The article's own IDs only: PubmedData/ReferenceList/Reference/ArticleIdList # holds the DOIs of cited papers. doi = ( @@ -1243,7 +1260,8 @@ def parse_pubmed(tree: etree._ElementTree) -> ArticleMeta: meta: ArticleMeta = { "pmid": pmid, - "pmcid": "", + "pmcid": xp('string(.//*[local-name()="PubmedData"]/*[local-name()="ArticleIdList"]/*[local-name()="ArticleId"][@IdType="pmc"][1])').strip(), + "text_source": "pubmed", "title": title or "", "abstract": abstract or "", "paragraphs": [], @@ -1518,6 +1536,10 @@ def iter_tar_xml_member_names( exts: Iterable[str] = _XML_EXTS, ) -> Iterator[str]: """Iterate member names inside a tar that look like XML, streaming safely.""" + if str(tar_path).lower().endswith(".xml.gz"): + for record, _ in iter_tar_xml_streams(tar_path, exts): + yield record.name + return with _open_tar_safely(tar_path) as tf: if tf is not None: for member in _iter_xml_members(tf, exts): @@ -1532,10 +1554,22 @@ def count_tar_xml_members(tar_path: str | Path, exts: Iterable[str] = _XML_EXTS) def iter_tar_xml_streams( tar_path: str | Path, exts: Iterable[str] = _XML_EXTS, + *, + legacy_member: Callable[[str, IO[bytes]], bool] | None = None, ) -> Iterator[tuple[tarfile.TarInfo, IO[bytes]]]: + from litkit.ingest.pubmed_bulk import member_records + if str(tar_path).lower().endswith(".xml.gz"): + path = Path(tar_path) + stat = path.stat() + source = SimpleNamespace(name=path.name[:-3],size=stat.st_size,mtime=stat.st_mtime) + with gzip.open(path,"rb") as stream: + yield from member_records(source,stream,distribution=True) + return with _open_tar_safely(tar_path) as tf: if tf is None: return + def open_legacy(info, source): + return tf.extractfile(info) if legacy_member and legacy_member(info.name, source) else None for member in _iter_xml_members(tf, exts): try: stream = tf.extractfile(member) @@ -1544,7 +1578,7 @@ def iter_tar_xml_streams( continue if stream is not None: with stream: - yield member, stream + yield from member_records(member, stream, open_legacy=open_legacy if legacy_member else None) # ------------------------------- @@ -1609,13 +1643,14 @@ def _parse_xml_bytes( class TarMemberMeta: """Minimal file metadata from a tar member, used for checkpointing.""" - __slots__ = ("name", "size", "mtime", "content_sha256") + __slots__ = ("name", "size", "mtime", "content_sha256", "bulk_record") - def __init__(self, name: str, size: int, mtime: float, content_sha256: bytes | None = None): + def __init__(self, name: str, size: int, mtime: float, content_sha256: bytes | None = None, bulk_record: bool = False): self.name = name self.size = size self.mtime = mtime self.content_sha256 = content_sha256 + self.bulk_record = bulk_record def parallel_iter_tar_articles( @@ -1689,7 +1724,7 @@ def parallel_iter_tar_articles( ) else: future = pool.submit(_parse_xml_bytes, data, member.name) - pending[future] = TarMemberMeta(member.name, member.size, member.mtime, hashlib.sha256(data).digest()) + pending[future] = TarMemberMeta(member.name, member.size, member.mtime, hashlib.sha256(data).digest(), getattr(member, "bulk_record", False)) if not pending: return diff --git a/src/litkit/ingest/pubmed_bulk.py b/src/litkit/ingest/pubmed_bulk.py new file mode 100644 index 0000000..9f2365a --- /dev/null +++ b/src/litkit/ingest/pubmed_bulk.py @@ -0,0 +1,115 @@ +"""Stream independently identified citations from NLM PubMed XML distributions.""" + +from __future__ import annotations + +import io +import re +from types import SimpleNamespace + +from lxml import etree + + +def is_article_set(stream): + """Read the XML root without consuming ordinary JATS member data.""" + parser = etree.XMLPullParser( + events=("start",), + resolve_entities=False, + load_dtd=False, + no_network=True, + recover=True, + huge_tree=True, + ) + # Tar and gzip streams buffer lookahead. A long prolog is uncommon and may need a rewind. + prefix = stream.peek(8192) + try: + parser.feed(prefix) + event = next(parser.read_events(), None) + if event is None: + stream.read(len(prefix)) + try: + while (block := stream.read(8192)) and event is None: + parser.feed(block) + event = next(parser.read_events(), None) + finally: + stream.seek(0) + return event is not None and etree.QName(event[1]).localname == "PubmedArticleSet" + except etree.XMLSyntaxError: + return False + + +def _records(stream): + context = etree.iterparse( + stream, + events=("end",), + resolve_entities=False, + load_dtd=False, + no_network=True, + huge_tree=True, + ) + for _, element in context: + parent = element.getparent() + if parent is None or parent.getparent() is not None: + continue + if etree.QName(parent).localname != "PubmedArticleSet": + raise ValueError("Expected a PubmedArticleSet in the PubMed distribution") + tag = etree.QName(element).localname + if tag == "DeleteCitation": + raise ValueError( + "PubMed DeleteCitation requires a deletion update. Use the annual baseline for a fresh build." + ) + if tag in {"PubmedArticle", "PubmedBookArticle"}: + pmid = element.xpath( + "string(./*[local-name()='MedlineCitation' or local-name()='BookDocument']/*[local-name()='PMID'][1])" + ).strip() + if not re.fullmatch(r"[0-9]+", pmid): + raise ValueError("PubMed bulk record has no valid PMID") + yield pmid, etree.tostring(element, encoding="utf-8", with_tail=False) + element.clear() + while element.getprevious() is not None: + del parent[0] + + +def member_records(member, stream, *, distribution=False, open_legacy=None): + """Keep single tar members compatible and give compound records stable PMID keys.""" + if not distribution and not is_article_set(stream): + yield member, stream + return + if open_legacy is not None and (original := open_legacy(member, stream)) is not None: + # Releases built before per-PMID keys refer to the whole physical member. + # Read its original bytes for the publisher fingerprint and sidecar metadata. + with original: + yield member, original + # Common one-record tar members retain their exact original bytes and name. + # A large official distribution never needs to be buffered in memory. + if not distribution and member.size <= 1024 * 1024: + stream = io.BytesIO(stream.read()) + records = _records(stream) + first = next(records, None) + if first is None: + return + second = next(records, None) + if second is None and not distribution: + stream.seek(0) + yield ( + SimpleNamespace( + name=member.name, size=member.size, mtime=member.mtime, bulk_record=True + ), + stream, + ) + return + from itertools import chain + + for pmid, data in chain((first,), (second,) if second else (), records): + item = SimpleNamespace( + name=f"{member.name}#pmid={pmid}", size=len(data), mtime=member.mtime, bulk_record=True + ) + yield item, io.BytesIO(data) + + +def record_name(member, meta): + """Name the logical input consistently, including when a set changes its record count.""" + if getattr(member, "bulk_record", False): + suffix = "#pmid=" + meta["pmid"] + if not member.name.endswith(suffix): + return member.name + suffix + return member.name diff --git a/src/litkit/portable/articles.py b/src/litkit/portable/articles.py index 25dace1..ec4b49b 100644 --- a/src/litkit/portable/articles.py +++ b/src/litkit/portable/articles.py @@ -93,7 +93,9 @@ def cache_path(root, manifest, pid): def cache_sources(path, metadata): """Return each fetchable identifier and its XML cache, plus any older shared cache.""" identifiers = [metadata.get(key) for key in ("pmcid", "pmid")] - if metadata.get("article_type") is None and metadata.get("publication_types"): + if metadata.get("text_source") == "pubmed" or ( + metadata.get("article_type") is None and metadata.get("publication_types") + ): identifiers.reverse() identifiers = [i for i in identifiers if re.fullmatch(r"(?:PMC)?[0-9]+", i or "")] if len(identifiers) < 2: diff --git a/src/litkit/portable/release.py b/src/litkit/portable/release.py index d91f9c6..309545f 100644 --- a/src/litkit/portable/release.py +++ b/src/litkit/portable/release.py @@ -39,6 +39,7 @@ "source_path", "license", "license_url", + "text_source", "article_type", "publication_types", "retracted", @@ -89,7 +90,7 @@ def archive_candidates(uri, recorded): if pair[0] in recorded or pair[0] .lower() - .endswith((".tar", ".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz")) + .endswith((".tar", ".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz", ".xml.gz")) ] @@ -134,7 +135,9 @@ def locations_for(self, archive): def inspect(self, path, member): """Index names once on disk, including for multi-archive legacy workspaces.""" - if path not in self.members: + logical = path.name.lower().endswith(".xml.gz") or bool(re.search(r"#pmid=[0-9]+$", member)) + key = path, logical + if key not in self.members: if not self.members: self.catalog.execute( "CREATE TEMP TABLE archive_members (archive INTEGER, member TEXT, " @@ -143,17 +146,26 @@ def inspect(self, path, member): number = len(self.members) identity = archive_identity(path) try: - with tarfile.open(path, "r|*") as handle: + if logical: + from litkit.build.ingest_loop import iter_tar_articles + from litkit.ingest.pubmed_bulk import record_name + self.catalog.executemany( "INSERT OR IGNORE INTO archive_members VALUES (?,?)", - ((number, info.name) for info in handle if info.isfile()), + ((number, record_name(info, meta)) for info, meta in iter_tar_articles(path)), ) + else: + 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] + self.members[key] = number, identity + number, identity = self.members[key] found = self.catalog.execute( "SELECT 1 FROM archive_members WHERE archive=? AND member=?", (number, member) ).fetchone() diff --git a/src/litkit/portable/restore.py b/src/litkit/portable/restore.py index c41e7a5..b37eb0b 100644 --- a/src/litkit/portable/restore.py +++ b/src/litkit/portable/restore.py @@ -18,6 +18,7 @@ from litkit.db.schema import init_db, set_stage1_mode, set_workspace_meta from litkit.index.io import faiss_load, write_index from litkit.ingest.ingest import _is_tar_path +from litkit.ingest.pubmed_bulk import record_name from litkit.ingest.publication_types import publication_source from litkit.portable import articles from litkit.portable.record import SOURCE_SCHEMA, archive_checksum, archive_identity, file_hash @@ -70,9 +71,11 @@ def __init__(self, db, mapping, manifest): CREATE UNIQUE INDEX temp.owner_pmid ON owners(pmid) WHERE pmid IS NOT NULL; CREATE UNIQUE INDEX temp.owner_pmcid ON owners(pmcid) WHERE pmcid IS NOT NULL; CREATE TEMP TABLE picked(pid INTEGER PRIMARY KEY, priority INTEGER, verified INTEGER, - uri TEXT, content_sha BLOB); + uri TEXT, content_sha BLOB, allowed INTEGER); + CREATE TEMP TABLE pubmed_fallbacks(source TEXT, member TEXT, uri TEXT, size INTEGER, + mtime INTEGER, metadata TEXT, sha BLOB, unchanged INTEGER); CREATE TEMP TABLE shared(pid INTEGER PRIMARY KEY, source TEXT, member TEXT, uri TEXT, - metadata TEXT, size INTEGER DEFAULT 0, mtime REAL DEFAULT 0); + metadata TEXT, size INTEGER DEFAULT 0, mtime REAL DEFAULT 0, sha BLOB); CREATE INDEX temp.shared_location ON shared(source,member); """ ) @@ -188,6 +191,7 @@ def ingest( *, cached_pid=None, unchanged=False, + deferred=False, ): if cached_pid is None: owner = self.resolve(name, member, meta, content_sha, unchanged) @@ -200,17 +204,46 @@ def ingest( "SELECT paper_id FROM files WHERE source=? AND member=?", (name, member) ).fetchone() register_file = file_owner is None or file_owner[0] == pid + old = self.mapping.execute( + "SELECT doc_id,metadata,digest,current_file FROM articles WHERE id=?", (pid,) + ).fetchone() + allowed = articles.license_allowed(meta, self.manifest) + if not old and not allowed: + return + prior = json.loads(old[1]) if old else {} + if ( + old + and self.manifest["licenses"] + and allowed + and meta.get("text_source") == "pubmed" + and prior.get("text_source") != "pubmed" + and cached_pid is None + and not deferred + ): + # Decide which OA edition is current before using an independent abstract. + # SQLite holds only the overlapping citations from license-filtered releases. + self.db.execute( + "INSERT INTO pubmed_fallbacks VALUES(?,?,?,?,?,?,?,?)", + ( + name, + member, + uri, + size, + mtime, + json.dumps(meta, ensure_ascii=False), + content_sha, + unchanged, + ), + ) + return if register_file: registered = self.db.execute( - "INSERT OR IGNORE INTO files VALUES(?,?,?,?)", (uri, size, mtime, pid) + "INSERT OR IGNORE INTO files(path,size,mtime,paper_id,content_sha256) VALUES(?,?,?,?,?)", + (uri, size, mtime, pid, content_sha), ) previous = self.db.execute( - "SELECT priority,verified,uri,content_sha FROM picked WHERE pid=?", (pid,) - ).fetchone() - old = self.mapping.execute( - "SELECT doc_id,metadata,digest,current_file FROM articles WHERE id=?", (pid,) + "SELECT priority,verified,uri,content_sha,allowed FROM picked WHERE pid=?", (pid,) ).fetchone() - prior = json.loads(old[1]) if old else {} exact = ( old and old[3] @@ -229,9 +262,45 @@ def ingest( verified = 0 if priority in (0, 2) and verified: priority = 3 + if not priority and meta.get("text_source") == "pubmed": + # A withdrawn or unavailable PMC member can still have a current PubMed abstract. + priority = 1 + if allowed and meta.get("text_source") == "jats-full-text": + if not old: + priority = 2 # A new citation may arrive in both PubMed and PMC. + elif prior.get("text_source") == "pubmed": + priority = 5 # Newly available body passages enrich the released abstract. + previous_doc = None + if previous: + previous_doc = self.db.execute( + "SELECT doc_id,pmid,pmcid,text_source FROM papers WHERE id=?", (pid,) + ).fetchone() + if ( + previous_doc + and allowed + and all( + not (previous_doc[i] and meta.get(k) and previous_doc[i] != meta[k]) + for i, k in ((1, "pmid"), (2, "pmcid")) + ) + ): + # A losing abstract may carry the only PMCID for the selected full text. + pmid = previous_doc[1] or meta.get("pmid") + pmcid = previous_doc[2] or meta.get("pmcid") + if (pmid or "", pmcid or "") != (previous_doc[1] or "", previous_doc[2] or ""): + self.db.execute("UPDATE papers SET pmid=?,pmcid=? WHERE id=?", (pmid, pmcid, pid)) + prior.update(pmid=pmid, pmcid=pmcid) if not priority: return rank = (priority, verified) + # An excluded authoritative OA edition bars older copies of its full text. + # A separately permitted PubMed abstract may still represent the citation. + fallback = bool( + previous + and not previous[4] + and allowed + and meta.get("text_source") == "pubmed" + and rank < previous[:2] + ) earlier_owner = None if register_file and not registered.rowcount: earlier_owner = self.db.execute( @@ -247,7 +316,9 @@ def ingest( ): return if previous: - if rank < previous[:2] or (rank == previous[:2] and previous[3] == content_sha): + if (rank < previous[:2] and not fallback) or ( + rank == previous[:2] and previous[3] == content_sha + ): return if rank == previous[:2] and previous[2] != uri and old: if verified: @@ -255,26 +326,27 @@ def ingest( raise ValueError(f"Ambiguous source editions for paper {pid}: {uri}") # Repeated occurrences of the same member retain archive order when neither # the publisher fingerprint nor the release text can distinguish them. - self.db.execute( - "INSERT OR REPLACE INTO picked VALUES(?,?,?,?,?)", - (pid, priority, verified, uri, content_sha), - ) + if not fallback: + self.db.execute( + "INSERT OR REPLACE INTO picked VALUES(?,?,?,?,?,?)", + (pid, priority, verified, uri, content_sha, allowed), + ) if register_file: - self.db.execute("INSERT OR REPLACE INTO files VALUES(?,?,?,?)", (uri, size, mtime, pid)) + self.db.execute( + "INSERT OR REPLACE INTO files(path,size,mtime,paper_id,content_sha256) VALUES(?,?,?,?,?)", + (uri, size, mtime, pid, content_sha), + ) else: - self.db.execute("UPDATE shared SET size=?,mtime=? WHERE pid=?", (size, mtime, pid)) + self.db.execute( + "UPDATE shared SET size=?,mtime=?,sha=? WHERE pid=?", + (size, mtime, content_sha, pid), + ) if earlier_owner: self.reassigned_file = True - previous_doc = None if previous: - previous_doc = self.db.execute( - "SELECT doc_id,pmid,pmcid FROM papers WHERE id=?", (pid,) - ).fetchone() - if not old and previous_doc: - prior.update(pmid=previous_doc[1], pmcid=previous_doc[2]) self.db.execute("DELETE FROM chunks WHERE paper_id=?", (pid,)) self.db.execute("DELETE FROM papers WHERE id=?", (pid,)) - if not articles.license_allowed(meta, self.manifest): + if not allowed: return doc_id = old[0] if old else uri if previous_doc and not old: @@ -292,7 +364,17 @@ def ingest( if unchanged or (exact and priority == 4): metadata.update(pmid=prior.get("pmid"), pmcid=prior.get("pmcid")) metadata.update( - {k: meta.get(k) for k in ("title", "abstract", "source_path", "license", "license_url")} + { + k: meta.get(k) + for k in ( + "title", + "abstract", + "source_path", + "license", + "license_url", + "text_source", + ) + } ) references = meta.get("references") metadata.update( @@ -373,13 +455,46 @@ def read_sources(self, root): "INSERT INTO build_sources VALUES(?,?,?,?)", (str(path), checksum, size, json.dumps(config, sort_keys=True)), ) + + def legacy_member(member_name, source): + rows = self.mapping.execute( + """SELECT f.original,a.current_file,json_extract(a.metadata,'$.publication_source') + FROM files f JOIN articles a ON f.paper_id=a.id + WHERE f.source=?1 AND f.member=?2 UNION ALL + SELECT a.current_file,a.current_file,json_extract(a.metadata,'$.publication_source') + FROM shared_editions e JOIN articles a ON a.id=e.paper_id + WHERE e.source=?1 AND e.member=?2""", + (name, member_name), + ).fetchall() + if not rows or unchanged: + return bool(rows) + fingerprints = [ + (uri, fingerprint) + for uri, current, fingerprint in rows + if uri == current and fingerprint + ] + if not fingerprints: + return False + # Repacking a tar preserves the original article and any status + # supplied by a sidecar exactly when its own bytes still match. + sha = hashlib.file_digest(source, "sha256").digest() + source.seek(0) + return any( + publication_source(uri, sha).hex() == fingerprint + for uri, fingerprint in fingerprints + ) + for member, meta in iter_tar_articles( - path, parse_workers=1, **articles.parser_options(config) + path, + parse_workers=1, + legacy_member=legacy_member, + **articles.parser_options(config), ): + key = record_name(member, meta) self.ingest( name, - member.name, - f"tar://{path}!/{member.name}", + key, + f"tar://{path}!/{key}", member.size, member.mtime, meta, @@ -389,6 +504,22 @@ def read_sources(self, root): ) if archive_identity(path) != identity: raise ValueError(f"Source changed while rebuilding {name}") + for name, member, uri, size, mtime, value, sha, unchanged in self.db.execute( + "SELECT * FROM pubmed_fallbacks ORDER BY rowid" + ): + self.ingest( + name, + member, + uri, + size, + mtime, + json.loads(value), + self.settings[name], + sha, + unchanged=unchanged, + deferred=True, + ) + self.db.execute("DROP TABLE pubmed_fallbacks") if self.reassigned_file: # A repeated filename may have temporarily supplied an unrelated # article before we saw the verified edition. Retain its genuine aliases. @@ -418,7 +549,9 @@ def read_cache(self, cache, root): if row is None: continue metadata = json.loads(row[0]) - if self.db.execute("SELECT 1 FROM picked WHERE pid=?", (pid,)).fetchone(): + if self.db.execute( + "SELECT 1 FROM picked WHERE pid=? AND priority>=3", (pid,) + ).fetchone(): continue locations = articles.article_sources(self.mapping, pid) config = articles.settings_for_article(pid, locations, self.settings) @@ -454,7 +587,7 @@ def read_cache(self, cache, root): continue meta, content_sha = complete name, member = locations[0] - uri = f"tar://{safe_path(root,name)}!/{member}" + uri = f"tar://{safe_path(root, name)}!/{member}" self.ingest(name, member, uri, 0, 0, meta, config, content_sha, cached_pid=pid) self.report["cached_papers"].append(pid) record = self.sources[name] @@ -473,7 +606,8 @@ def finish(self, release, paths): if self.has_shared_editions: # A cached paper can be the only available occurrence of a shared path. self.db.execute( - """INSERT OR IGNORE INTO files SELECT p.build_member,e.size,e.mtime,p.id FROM shared e + """INSERT OR IGNORE INTO files(path,size,mtime,paper_id,content_sha256) + SELECT p.build_member,e.size,e.mtime,p.id,e.sha FROM shared e JOIN papers p ON p.id=e.pid ORDER BY e.pid""" ) for table, original in (("papers", "articles"), ("chunks", "passages")): diff --git a/tests/integration/test_bulk_pubmed.py b/tests/integration/test_bulk_pubmed.py new file mode 100644 index 0000000..ca787bc --- /dev/null +++ b/tests/integration/test_bulk_pubmed.py @@ -0,0 +1,574 @@ +"""PubMed baseline records coexist with OA full text in actual builds and releases.""" + +import gzip +import hashlib +import shutil +import sqlite3 +from contextlib import closing +from itertools import permutations + +import faiss +import numpy as np +import pytest +from lxml import etree +from test_batch_resume import Build +from test_build_and_query import _ok, litkit +from test_portable_vectors import MODELS + +from conftest import FakeEmbedder, jats, pubmed_xml, write_tar +from litkit.build.ingest_loop import iter_tar_articles +from litkit.portable import articles +from litkit.portable.release import LegacyArchives, archive_candidates, export_vectors +from litkit.portable.restore import rebuild_from_vectors +from litkit.portable.search import search_vectors + + +def bulk(*entries): + root = etree.Element("PubmedArticleSet") + for pmid, title, abstract in entries: + root.append(etree.fromstring(pubmed_xml(pmid, title, abstract).encode())[0]) + return etree.tostring(root, encoding="utf-8") + + +A = ("710", "Tidal clocks", "An abstract about lunar rhythms.") +B = ("711", "Overlap in PubMed", "The abstract about the overlap.") +FULL = jats( + pmid="711", + pmcid="PMC811", + title="Full text of overlap", + abstract=B[2], + paragraphs=["A distinctive full body passage about tides."], +) + + +@pytest.mark.parametrize("workers", [1, 4]) +def test_multi_record_tar_preserves_distinct_stable_pmid_keys(tmp_path, workers): + archive = write_tar( + tmp_path / "mixed.tar", {"batch.xml": bulk(A, B).decode(), "jats.xml": FULL} + ) + rows = [(m.name, meta["pmid"]) for m, meta in iter_tar_articles(archive, workers)] + assert rows == [ + ("batch.xml#pmid=710", "710"), + ("batch.xml#pmid=711", "711"), + ("jats.xml", "711"), + ] + + +@pytest.mark.parametrize( + "filename,count", [("records.xml.gz", 2), ("records.tar", 2), ("records.tar", 1)] +) +def test_relocated_archive_can_resolve_a_logical_pubmed_member(tmp_path, filename, count): + nested = tmp_path / "outer.tar!" / filename + nested.parent.mkdir() + data = bulk(*(A, B)[:count]) + if filename.endswith(".gz"): + nested.write_bytes(gzip.compress(data)) + else: + write_tar(nested, {"records.xml": data.decode()}) + # A receiver may have both a similarly named tar and the moved distribution. + write_tar(tmp_path / "outer.tar", {"other.xml": FULL}) + uri = f"tar:///published/outer.tar!/{filename}!/records.xml#pmid={A[0]}" + with closing(sqlite3.connect(":memory:")) as db: + archives = LegacyArchives(tmp_path, {}, db) + assert archives.member(uri, archive_candidates(uri, {})) == ( + f"/published/outer.tar!/{filename}", + f"records.xml#pmid={A[0]}", + ) + + +@pytest.mark.parametrize("pubmed_first", [True, False]) +def test_bulk_abstracts_survive_mixed_build_release_and_both_search_modes( + tmp_path, monkeypatch, pubmed_first +): + sources, workspace = tmp_path / "corpus", tmp_path / "workspace" + sources.mkdir() + pubmed = sources / ("a.xml.gz" if pubmed_first else "z.xml.gz") + pubmed.write_bytes(gzip.compress(bulk(A, B))) + write_tar(sources / ("z.tar" if pubmed_first else "a.tar"), {"full.xml": FULL}) + _ok( + litkit( + workspace, + "--build-only", + "--faiss-writer", + "--tar-dir", + str(sources), + "--chunks-index", + "flat", + "--papers-index", + "flat", + ) + ) + + def paper_rows(ws): + with closing(sqlite3.connect(ws / "sqlite/litkit.sqlite3")) as db: + return ( + db.execute( + "SELECT id,doc_id,pmid,pmcid,title,text_source FROM papers ORDER BY pmid" + ).fetchall(), + db.execute( + "SELECT p.pmid,c.id,c.ord,c.text FROM chunks c JOIN papers p ON p.id=c.paper_id ORDER BY p.pmid,c.ord" + ).fetchall(), + ) + + papers, chunks = paper_rows(workspace) + assert [r[2:] for r in papers] == [ + ("710", "", A[1], "pubmed"), + ("711", "PMC811", "Full text of overlap", "jats-full-text"), + ] + assert any(row[0] == "710" and A[2] in row[3] for row in chunks) + assert any(row[0] == "711" and "distinctive full body passage" in row[3] for row in chunks) + release = tmp_path / "release" + export_vectors(workspace, release, settings=MODELS) + restored = tmp_path / "remote" + monkeypatch.setattr( + articles, "load_model", lambda *_: pytest.fail("unchanged bulk data was re-embedded") + ) + assert not any(rebuild_from_vectors(release, sources, restored).values()) + assert paper_rows(restored) == (papers, chunks) + _ok( + litkit( + restored, + "--build-only", + "--faiss-writer", + "--tar-dir", + str(sources), + "--chunks-index", + "flat", + "--papers-index", + "flat", + ) + ) + assert paper_rows(restored) == (papers, chunks) + assert ( + A[2] + in _ok( + litkit(restored, "search-passages", "lunar rhythms", "--mode", "exact", "--json") + ).stdout + ) + monkeypatch.setattr(articles, "load_model", lambda *_: FakeEmbedder()) + records = {"710": pubmed_xml(*A).encode(), "PMC811": FULL.encode()} + for mode in ("semantic", "hybrid"): + result = search_vectors( + release, + "lunar rhythms", + limit=4, + cache=tmp_path / "cache", + fetch=records.__getitem__, + mode=mode, + ) + assert not result["unavailable"] and {p["pmid"] for p in result["passages"]} == { + "710", + "711", + } + + +def test_bulk_checkpoint_rechecks_same_size_reordered_and_missing_records(tmp_path, monkeypatch): + archive = tmp_path / "records.tar" + write_tar(archive, {"bulk.xml": bulk(A, B).decode()}) + build = Build(tmp_path / "producer", archive) + build.run() + updated = ("710", A[1], "An abstract about solar cycles.") + write_tar(archive, {"bulk.xml": bulk(B, updated, ("712", "Third", "Third abstract.")).decode()}) + build.run() + assert build.run()[2:] == (0, 0) + with closing(sqlite3.connect(build.db)) as db: + assert db.execute("SELECT pmid,abstract FROM papers ORDER BY pmid").fetchall() == [ + ("710", updated[2]), + ("711", B[2]), + ("712", "Third abstract."), + ] + assert db.execute( + "SELECT count(*) FROM files WHERE content_sha256 IS NOT NULL" + ).fetchone() == (3,) + + +@pytest.mark.parametrize("pubmed_shard", [0, 1]) +def test_independent_producers_keep_abstract_only_papers_and_oa_bodies(tmp_path, pubmed_shard): + from litkit.db.schema import init_db + from litkit.db.sharding import merge_shard_databases + + abstract = tmp_path / "records.xml.gz" + records = etree.fromstring(bulk(A, B)) + references = etree.SubElement(etree.SubElement(records[1], "PubmedData"), "ArticleIdList") + etree.SubElement(references, "ArticleId", IdType="pmc").text = "PMC811" + abstract.write_bytes(gzip.compress(etree.tostring(records))) + full = write_tar( + tmp_path / "full.tar", + { + "full.xml": jats( + pmid="711", title="Full text", paragraphs=["A distinctive full body passage."] + ) + }, + ) + for shard, archive in ((pubmed_shard, abstract), (1 - pubmed_shard, full)): + producer = Build(tmp_path, archive, shard_id=shard) + producer.run() + with closing(init_db(tmp_path / "litkit.sqlite3")) as db: + merge_shard_databases(db, segment_dir=producer.segments) + assert db.execute("SELECT pmcid FROM papers WHERE pmid='711'").fetchone() == ("PMC811",) + assert db.execute("SELECT pmid,text_source FROM papers ORDER BY pmid").fetchall() == [ + ("710", "pubmed"), + ("711", "jats-full-text"), + ] + assert db.execute( + "SELECT count(*) FROM chunks WHERE text LIKE '%distinctive full body%'" + ).fetchone() == (1,) + + +@pytest.mark.parametrize("workers", [1, 4]) +def test_compound_checkpoint_cannot_skip_a_replacement_singleton(tmp_path, workers): + archive = tmp_path / "set.tar" + write_tar(archive, {"batch.xml": bulk(A, B).decode()}) + producer = Build(tmp_path / "producer", archive) + producer.run(parse_workers=workers) + third = ("713", "Replacement singleton", "A new abstract.") + write_tar(archive, {"batch.xml": bulk(third).decode()}) + producer.run(parse_workers=workers) + with closing(sqlite3.connect(producer.db)) as db: + assert db.execute("SELECT abstract FROM papers WHERE pmid='713'").fetchone() == (third[2],) + assert producer.run(parse_workers=workers)[2:] == (0, 0) + + +def copy_build_workspace(build, ws): + (ws / "sqlite").mkdir(parents=True) + (ws / "indices").mkdir() + shutil.copyfile(build.db, ws / "sqlite/litkit.sqlite3") + for name, index in (("papers", build.paper_path), ("chunks", build.chunk_path)): + shutil.copyfile(index, ws / "indices" / f"{name}.faiss") + + +def test_repacked_legacy_pubmed_editions_sharing_one_member_keep_their_status( + tmp_path, monkeypatch +): + from litkit.ingest import pubmed_bulk + + sources = tmp_path / "sources" + sources.mkdir() + first = write_tar(sources / "old.tar", {"a.xml": bulk(A).decode(), "b.xml": bulk(B).decode()}) + build = Build(tmp_path / "build", first, producer=False) + revised_a = (A[0], "A second edition", "An updated abstract for A.") + revised_b = (B[0], "Revised B edition", "Different observations for B.") + editions = [("same.xml", bulk(rec).decode()) for rec in (revised_a, revised_b)] + revisions = write_tar(sources / "editions.tar", editions) + with monkeypatch.context() as old_reader: + old_reader.setattr(pubmed_bulk, "member_records", lambda m, s, **kw: [(m, s)]) + build.run() + build.run(tar_paths=[revisions]) + ws, release, remote = (tmp_path / name for name in ("workspace", "release", "remote")) + copy_build_workspace(build, ws) + with closing(sqlite3.connect(ws / "sqlite/litkit.sqlite3")) as db: + assert db.execute( + "SELECT count(*),count(DISTINCT build_member) FROM papers" + ).fetchone() == (2, 1) + db.execute("UPDATE papers SET retracted=1") + db.commit() + export_vectors(ws, release, settings=MODELS) + write_tar(revisions, [*editions, ("notes.txt", "Unrelated addition")]) + monkeypatch.setattr( + articles, "load_model", lambda *_: pytest.fail("re-embedded unchanged papers") + ) + report = rebuild_from_vectors(release, sources, remote) + assert report["changed_sources"] == ["editions.tar"] + assert not any(rows for key, rows in report.items() if key != "changed_sources") + with closing(sqlite3.connect(remote / "sqlite/litkit.sqlite3")) as db: + assert db.execute("SELECT pmid,title,retracted FROM papers ORDER BY pmid").fetchall() == [ + (rec[0], rec[1], 1) for rec in (revised_a, revised_b) + ] + + +@pytest.mark.parametrize("count", [1, 2]) +def test_unchanged_restore_reads_the_published_unsuffixed_pubmed_record( + tmp_path, monkeypatch, count +): + from litkit.ingest import pubmed_bulk + from litkit.ingest.publication_types import publication_source + + sources = tmp_path / "sources" + sources.mkdir() + xml = bulk(*(A, B)[:count]) + path = write_tar(sources / "old.tar", {"set.xml": xml.decode()}) + build = Build(tmp_path / "build", path, producer=False) + with monkeypatch.context() as old_reader: + # Previous releases parsed the first paper from the physical PubmedArticleSet. + old_reader.setattr(pubmed_bulk, "member_records", lambda m, s, **kw: [(m, s)]) + build.run() + ws = tmp_path / "workspace" + copy_build_workspace(build, ws) + with closing(sqlite3.connect(ws / "sqlite/litkit.sqlite3")) as db: + uri = f"tar://{path}!/set.xml" + assert db.execute("SELECT pmid,build_member,publication_source FROM papers").fetchall() == [ + (A[0], uri, publication_source(uri, hashlib.sha256(xml).digest())) + ] + db.execute("UPDATE papers SET retracted=1,publication_types='[\"review\"]'") + db.commit() + release, remote = tmp_path / "release", tmp_path / "remote" + export_vectors(ws, release, settings=MODELS) + monkeypatch.setattr( + articles, "load_model", lambda *_: pytest.fail("re-embedded legacy release") + ) + assert not any(rebuild_from_vectors(release, sources, remote).values()) + with closing(sqlite3.connect(remote / "sqlite/litkit.sqlite3")) as db: + assert db.execute( + "SELECT pmid,abstract,retracted,publication_types FROM papers" + ).fetchall() == [(A[0], A[2], 1, '["review"]')] + for name in ("papers.faiss", "chunks.faiss"): + assert (remote / "indices" / name).read_bytes() == (ws / "indices" / name).read_bytes() + monkeypatch.setattr(articles, "load_model", lambda *_: FakeEmbedder()) + write_tar(path, {"notes.txt": "Unrelated change", "set.xml": xml.decode()}) + repacked = tmp_path / "repacked" + report = rebuild_from_vectors(release, sources, repacked) + assert report["changed_sources"] == ["old.tar"] and not report["changed_papers"] + assert len(report["new_papers"]) == count - 1 + with closing(sqlite3.connect(repacked / "sqlite/litkit.sqlite3")) as db: + assert db.execute( + "SELECT retracted,publication_types FROM papers WHERE pmid=?", (A[0],) + ).fetchone() == (1, '["review"]') + write_tar(path, {"set.xml": xml.decode().replace(A[2], "Updated abstract.")}) + revised = tmp_path / "revised" + rebuild_from_vectors(release, sources, revised) + with closing(sqlite3.connect(revised / "sqlite/litkit.sqlite3")) as db: + assert db.execute( + "SELECT abstract,retracted FROM papers WHERE pmid=?", (A[0],) + ).fetchone() == ("Updated abstract.", 0) + + +@pytest.mark.parametrize("workers", [1, 4]) +def test_interrupted_bulk_distribution_restores_every_vector(tmp_path, workers): + archive = tmp_path / "baseline.xml.gz" + archive.write_bytes( + gzip.compress(bulk(*[(str(i), f"Paper {i}", f"Abstract {i}.") for i in range(1, 14)])) + ) + interrupted = Build(tmp_path / "resume", archive) + clean = Build(tmp_path / "clean", archive) + + class InterruptOnLast(FakeEmbedder): + def encode(self, texts, **kwargs): + if any("Paper 13" in text for text in texts): + raise RuntimeError("interrupted bulk build") + return super().encode(texts, **kwargs) + + options = dict(paper_batch=1, parse_workers=workers) + with pytest.raises(RuntimeError, match="interrupted bulk build"): + interrupted.run(paper_embedder=InterruptOnLast(), **options) + assert 0 < interrupted.progress() < 13 + interrupted.run(**options) + clean.run(**options) + for (ids, vectors), (expected_ids, expected_vectors) in zip( + interrupted.consume(), clean.consume(), strict=True + ): + assert ids == expected_ids + np.testing.assert_array_equal(vectors, expected_vectors) + + +def test_abstract_only_training_fills_the_requested_vector_budget(tmp_path): + from litkit.build.training import train_ivfpq_index + from litkit.concurrent.locking import FileLock + + path = tmp_path / "baseline.xml.gz" + path.write_bytes( + gzip.compress(bulk(*[(str(i), "Title", f"Abstract {i}.") for i in range(1, 101)])) + ) + embedder = FakeEmbedder() + train_ivfpq_index( + chunk_dim=32, + chunk_embedder=embedder, + tar_dir=tmp_path, + tar_manifest=None, + train_samples=64, + batch_train_flush=25, + ivf_nlist=1, + pq_m=4, + nprobe=1, + chunk_index_path=tmp_path / "chunks.faiss", + chunk_trained_flag=tmp_path / "chunks.trained.json", + faiss_lock_path=tmp_path / "faiss.writer.lock", + db_lock_path=tmp_path / "db.writer.lock", + FileLock=FileLock, + is_faiss_writer=False, + ) + assert sum(map(len, embedder.calls)) == 64 + + +@pytest.mark.parametrize("pubmed_first", [False, True]) +@pytest.mark.parametrize("published_abstract", [False, True]) +def test_restore_selects_new_full_text_and_keeps_pubmed_identifiers( + tmp_path, monkeypatch, pubmed_first, published_abstract +): + sources = tmp_path / "sources" + sources.mkdir() + baseline = sources / ("a.xml.gz" if pubmed_first else "z.xml.gz") + records = etree.fromstring(bulk(A, B)) + ids = etree.SubElement(etree.SubElement(records[1], "PubmedData"), "ArticleIdList") + etree.SubElement(ids, "ArticleId", IdType="pmc").text = "PMC811" + baseline.write_bytes(gzip.compress(etree.tostring(records) if published_abstract else bulk(A))) + ws, release, remote = (tmp_path / name for name in ("ws", "release", "remote")) + _ok( + litkit( + ws, + "--build-only", + "--faiss-writer", + "--tar-dir", + str(sources), + "--chunks-index", + "flat", + "--papers-index", + "flat", + ) + ) + export_vectors(ws, release, settings=MODELS) + baseline.write_bytes(gzip.compress(etree.tostring(records))) + full = jats(pmid=B[0], title="OA article", abstract=B[2], paragraphs=["Full body passage."]) + write_tar(sources / ("z.tar" if pubmed_first else "a.tar"), {"oa.xml": full}) + monkeypatch.setattr(articles, "load_model", lambda *_: FakeEmbedder()) + report = rebuild_from_vectors(release, sources, remote) + assert len(report["new_papers"]) == (0 if published_abstract else 1) + with closing(sqlite3.connect(remote / "sqlite/litkit.sqlite3")) as db: + assert db.execute( + "SELECT pmid,pmcid,title,text_source FROM papers ORDER BY pmid" + ).fetchall() == [ + (A[0], "", A[1], "pubmed"), + (B[0], "PMC811", "OA article", "jats-full-text"), + ] + assert db.execute( + "SELECT c.text FROM chunks c JOIN papers p ON p.id=c.paper_id WHERE p.pmid=? AND c.text LIKE '%Full body%'", + (B[0],), + ).fetchall() == [("Full body passage.",)] + assert db.execute( + "SELECT count(*) FROM files f JOIN papers p ON p.id=f.paper_id WHERE p.pmid=?", (B[0],) + ).fetchone() == (2,) + for table in ("papers", "chunks"): + index = faiss.read_index(str(remote / "indices" / f"{table}.faiss")) + assert sorted(faiss.vector_to_array(index.id_map)) == [ + row[0] for row in db.execute(f"SELECT id FROM {table} ORDER BY id") + ] + + +@pytest.mark.parametrize("pubmed_first", [False, True]) +def test_filtered_restore_keeps_new_abstract_when_full_text_license_is_excluded( + tmp_path, monkeypatch, pubmed_first +): + sources = tmp_path / "sources" + sources.mkdir() + archive = sources / "corpus.tar" + write_tar(archive, {"baseline.xml": bulk(A).decode()}) + ws, release, remote = (tmp_path / name for name in ("ws", "release", "remote")) + _ok( + litkit( + ws, + "--build-only", + "--faiss-writer", + "--tar-dir", + str(sources), + "--chunks-index", + "flat", + "--papers-index", + "flat", + ) + ) + export_vectors(ws, release, settings=MODELS, licenses=["unknown"]) + permissions = '' + full = FULL.replace("", permissions + "") + files = [("baseline.xml", bulk(A, B).decode()), ("oa.xml", full)] + write_tar(archive, files if pubmed_first else files[::-1]) + monkeypatch.setattr(articles, "load_model", lambda *_: FakeEmbedder()) + report = rebuild_from_vectors(release, sources, remote) + assert len(report["new_papers"]) == 1 + with closing(sqlite3.connect(remote / "sqlite/litkit.sqlite3")) as db: + assert db.execute( + "SELECT pmid,abstract,text_source FROM papers ORDER BY pmid" + ).fetchall() == [(A[0], A[2], "pubmed"), (B[0], B[2], "pubmed")] + assert not db.execute( + "SELECT 1 FROM chunks WHERE text LIKE '%distinctive full body%'" + ).fetchall() + + +def test_restore_retains_pubmed_abstract_when_mapped_oa_file_is_withdrawn(tmp_path, monkeypatch): + sources = tmp_path / "sources" + sources.mkdir() + (sources / "abstracts.xml.gz").write_bytes(gzip.compress(bulk(A, B))) + full = write_tar(sources / "full.tar", {"oa.xml": FULL}) + workspace = tmp_path / "ws" + _ok( + litkit( + workspace, + "--build-only", + "--faiss-writer", + "--tar-dir", + str(sources), + "--chunks-index", + "flat", + "--papers-index", + "flat", + ) + ) + release = tmp_path / "release" + export_vectors(workspace, release, settings=MODELS) + full.unlink() + monkeypatch.setattr(articles, "load_model", lambda *_: FakeEmbedder()) + restored = tmp_path / "restored" + report = rebuild_from_vectors(release, sources, restored) + assert not report["missing_papers"] and report["missing_sources"] == ["full.tar"] + with closing(sqlite3.connect(restored / "sqlite/litkit.sqlite3")) as db: + assert db.execute( + "SELECT abstract,text_source FROM papers WHERE pmid='711'" + ).fetchone() == (B[2], "pubmed") + assert not db.execute( + "SELECT 1 FROM chunks WHERE text LIKE '%distinctive full body%'" + ).fetchall() + + +@pytest.mark.parametrize("order", list(permutations(("pubmed", "historical", "current")))) +def test_changed_oa_license_preserves_permitted_pubmed_abstract(tmp_path, monkeypatch, order): + sources = tmp_path / "sources" + sources.mkdir() + paths = { + kind: sources / (str(i) + (".xml.gz" if kind == "pubmed" else ".tar")) + for i, kind in enumerate(order) + } + baseline = paths["pubmed"] + baseline.write_bytes(gzip.compress(bulk(A, B))) + archive = paths["current"] + + def licensed(code): + license_xml = f'' + return FULL.replace("", license_xml + "") + + for kind in ("historical", "current"): + write_tar(paths[kind], {"oa.xml": licensed("by")}) + inputs = tmp_path / "files.txt" + inputs.write_text("".join(f"{paths[k]}\n" for k in ("pubmed", "historical", "current"))) + ws, release, remote = (tmp_path / name for name in ("ws", "release", "remote")) + _ok( + litkit( + ws, + "--build-only", + "--faiss-writer", + "--tar-manifest", + str(inputs), + "--chunks-index", + "flat", + "--papers-index", + "flat", + ) + ) + manifest = export_vectors(ws, release, settings=MODELS, licenses=["CC-BY-4.0", "unknown"]) + write_tar(archive, {"oa.xml": licensed("by-nc")}) + monkeypatch.setattr(articles, "load_model", lambda *_: FakeEmbedder()) + with closing(sqlite3.connect(release / "mapping.sqlite3")) as mapping: + pid = mapping.execute( + "SELECT id FROM articles WHERE json_extract(metadata,'$.pmid')=?", (B[0],) + ).fetchone()[0] + cache = tmp_path / "cache" + cached = articles.cache_path(cache, manifest, pid) + cached.parent.mkdir(parents=True) + articles.write_cached_article(cached, licensed("by").encode()) + report = rebuild_from_vectors(release, sources, remote, cache=cache) + assert not report["cached_papers"] + assert report["missing_papers"] == [] + with closing(sqlite3.connect(remote / "sqlite/litkit.sqlite3")) as db: + assert db.execute( + "SELECT pmcid,abstract,text_source,license FROM papers WHERE pmid=?", (B[0],) + ).fetchone() == ("PMC811", B[2], "pubmed", None) + assert not db.execute( + "SELECT 1 FROM chunks WHERE text LIKE '%distinctive full body%'" + ).fetchall() diff --git a/tests/test_ingest.py b/tests/test_ingest.py index 5c277da..020087a 100644 --- a/tests/test_ingest.py +++ b/tests/test_ingest.py @@ -84,6 +84,7 @@ def test_parse_pubmed_record(): assert meta == { "pmid": "900005", "pmcid": "", + "text_source": "pubmed", "title": "A PubMed record", "abstract": "Only an abstract.", "paragraphs": [],