diff --git a/CHANGELOG.md b/CHANGELOG.md index 8af559d..ee75374 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ internal versions are summarized under 0.3.33. ## [Unreleased] ### Added +- 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) ### Fixed diff --git a/README.md b/README.md index cc340d7..c4e7218 100644 --- a/README.md +++ b/README.md @@ -105,7 +105,7 @@ and `--workspace`; see `litkit --help`. | Command | Description | |--------|-------------| -| `litkit search-papers [QUERY]` | Rank papers, or list them by metadata (`--year-from`, `--year-to`, `--author`, `--journal`, `--doi`, `--pmcid`, `--pmid`) | +| `litkit search-papers [QUERY]` | Rank papers, or list them by metadata (repeatable `--type` and `--exclude-type`, `--year-from`, `--year-to`, `--author`, `--journal`, `--doi`, `--pmcid`, `--pmid`) | | `litkit search-passages QUERY` | `--mode hybrid` (default), `semantic`, or `exact` token search (`G12C`, `SHP-2`, `k_off`); `--section Methods` | | `litkit chunk-context PAPER ORD` | Chunks `ORD - window .. ORD + window` of one paper (`--window`, default 2) | | `litkit get-paper PAPER` | Metadata, abstract and ordered chunks (`--section`, `--no-include-tables`) | @@ -119,6 +119,14 @@ Without FTS5, exact mode scans the passages. Lexical paper search scans paper metadata. Hybrid search matches exact tokens within the Stage 1 shortlist. A DOI or a filename shared by multiple records returns `ambiguous_identifier` with two candidate `paper:N` handles. Use the exact handle from search results, or inspect the candidates to choose a record. Save a passage’s `evidence_handle` to check its full source text on later reads. Its `evidence:v1:` prefix prevents legacy readers from silently opening an unchecked location. It combines the paper, ordinal and a 96-bit prefix of SHA-256. After a content change, `chunk-context` and `get-paper` return `stale_handle` (exit 5). If the original text moved to exactly one other ordinal in the paper, the error includes a replacement handle. The Python APIs raise `StaleHandleError`. A numeric paper ID also carries a fingerprint of its document metadata so a reassigned row cannot silently change sources. Existing location handles still refer to the current index. +Paper and passage results include the raw JATS `article_type`, normalized `types` +and a `retracted` flag. A retraction notice has type `retraction`; the affected +paper carries the flag. For archives from a text-fetch workspace, pass +`--publication-manifest /path/to/.text-fetch/workspace.json` during ingest to +include source publication types by exact archive member path. After a text-fetch +metadata refresh, rerun the update with the same archive and manifest to refresh +its publication status while reusing the existing embeddings. Rebuild existing +workspaces to populate these fields for previously indexed papers. The same operations are available in Python as `litkit.retrieval.search_papers`, `search_passages`, `get_chunk_context` and `get_paper`. diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index b6b764b..7ff1e1f 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -6,6 +6,7 @@ from __future__ import annotations +import hashlib import json import os import sqlite3 @@ -32,6 +33,7 @@ parallel_iter_tar_articles, parse_xml_fileobj, ) +from litkit.ingest.publication_types import publication_fields, publication_source from litkit.ingest import is_uncompressed_tar from litkit.index import ( make_id_selector, @@ -54,7 +56,7 @@ from litkit.db.handoff import completed_checkpoint, merged_checkpoints, readable_database from litkit.db.queries import available_citation_ids, consolidate_owners, linked_owners, record_citation_link from litkit.db.publication import read_publication -from litkit.db.schema import ensure_in_index_columns, ensure_paper_embedding_column +from litkit.db.schema import ensure_in_index_columns, ensure_paper_embedding_column, table_columns from litkit.db.sharding import producer_shard_lock from litkit.segments.metadata import verify_legacy_shard from litkit.build.helpers import ( @@ -75,13 +77,32 @@ ) +class _HashingReader: + """Hash raw XML as the parser consumes a compressed archive member.""" + + def __init__(self, stream): + self.stream = stream + self.hasher = hashlib.sha256() + + def read(self, size=-1): + block = self.stream.read(size) + self.hasher.update(block) + return block + + def digest(self): + # A recovering parser can finish before the end of malformed XML. + while self.read(64 * 1024): + pass + return self.hasher.digest() + + def iter_tar_articles( tar_path: Path, parse_workers: int = 8, *, include_tables: bool = False, max_table_chars: int = DEFAULT_MAX_TABLE_CHARS, -) -> Iterator[tuple[TarMemberMeta | SimpleNamespace, ArticleMeta]]: +) -> Iterator[tuple[TarMemberMeta, ArticleMeta]]: """Unified iterator over articles in a tar file. For uncompressed .tar files (when parse_workers > 1), uses parallel XML parsing. @@ -110,18 +131,19 @@ def iter_tar_articles( # Sequential path for compressed tars (or when parallel disabled) for tarinfo, fobj in iter_tar_xml_streams(tar_path): try: + reader = _HashingReader(fobj) article_meta = parse_xml_fileobj( - fobj, + reader, tarinfo.name, include_tables=include_tables, max_table_chars=max_table_chars, ) if article_meta is not None: - # Wrap TarInfo in SimpleNamespace for consistent interface - member_meta = SimpleNamespace( + member_meta = TarMemberMeta( name=tarinfo.name, size=int(getattr(tarinfo, "size", 0)), mtime=float(getattr(tarinfo, "mtime", 0.0) or 0.0), + content_sha256=reader.digest(), ) yield member_meta, article_meta finally: @@ -215,6 +237,7 @@ def process_tar_files( parse_workers: int, include_tables: bool = False, max_table_chars: int = DEFAULT_MAX_TABLE_CHARS, + publication_manifest: Path | None = None, _producer_locked: bool = False, ) -> tuple[faiss.Index | None, faiss.Index, int, int]: """Process tar files and ingest articles into DB and indices. @@ -285,16 +308,74 @@ def process_tar_files( papers_added_total = 0 chunks_added_total = 0 + manifest_articles = {} + if publication_manifest is not None: + with Path(publication_manifest).open(encoding="utf-8") as source: + manifest_articles = json.load(source)["articles"] + if not isinstance(manifest_articles, dict): + raise ValueError("Expected text-fetch workspace metadata with an articles mapping") + replaced_papers: set[int] = set() replaced_chunks: set[int] = set() retired_papers: set[int] = set() revised_shard_papers: set[int] = set() + pending_refreshes = 0 + + def refresh_known_member(path, member, meta, manifest_article): + """Apply a sidecar change without rewriting text, chunk IDs or vectors.""" + nonlocal pending_refreshes, has_refresh_table + source = publication_source(path, member.content_sha256) + select = ( + "SELECT p.id, p.article_type, p.publication_types, p.retracted " + "FROM files f JOIN papers p ON p.id=f.paper_id WHERE f.path=? AND p.publication_source=?" + ) + local = cur.execute(select, (path, source)).fetchone() + remote = merged.execute(select, (path, source)).fetchone() if merged_has_types else None + if local is None and remote is None: + return + fields = publication_fields(meta, manifest_article) + # A detached shard may already hold a newer, unconsumed refresh. + # Compare against it even when the manifest changes back to the value + # that the main DB still reports. + queued = None + if embed_producer and has_refresh_table: + queued = cur.execute( + "SELECT article_type, types, retracted FROM publication_refreshes " + "WHERE path=? AND source=? AND sequence>?", (path, source, merged_sequence), + ).fetchone() + if queued is not None: + if queued == fields: + return + elif all(row is None or row[1:] == fields for row in (local, remote)): + return + if embed_producer: + publication.reserve() + if not conn.in_transaction: + conn.execute("BEGIN") + if local is not None: + cur.execute("UPDATE papers SET article_type=?, publication_types=?, retracted=? WHERE id=?", + (*fields, local[0])) + if embed_producer: + if not has_refresh_table: + cur.execute("CREATE TABLE publication_refreshes (path TEXT PRIMARY KEY, source BLOB NOT NULL, " + "article_type TEXT, types TEXT, retracted INTEGER, sequence INTEGER)") + cur.execute("CREATE INDEX publication_refresh_sequence ON publication_refreshes(sequence)") + has_refresh_table = True + cur.execute("INSERT OR REPLACE INTO publication_refreshes VALUES (?,?,?,?,?,?)", + (path, source, *fields, publication.checkpoint.get("segment_sequence", 0) + 1)) + pending_refreshes += 1 + def flush_batch(tar: str, members: int) -> None: - nonlocal paper_index, chunk_index, papers_added_total, chunks_added_total + nonlocal paper_index, chunk_index, papers_added_total, chunks_added_total, pending_refreshes if not (paper_ids_buf or chunk_ids_buf): + if pending_refreshes and embed_producer: + publication.publish(tar, members, lambda paper_dir, chunk_dir: (None, None)) + pending_refreshes = 0 + return if publication.token is not None: publication.discard_uncommitted() + pending_refreshes = 0 commit_transaction(conn) publication.checkpoint_tar(tar, members) return @@ -423,6 +504,7 @@ def stage_indexes(paper_dir, chunk_dir): retired_papers.clear() replaced_papers.clear() replaced_chunks.clear() + pending_refreshes = 0 revised_shard_papers.clear() def process_tar(tpath: Path) -> None: @@ -516,13 +598,18 @@ def _render(force: bool = False): include_tables=include_tables, max_table_chars=max_table_chars, ): + f = f"tar://{tpath}!/{m.name}" + manifest_article = manifest_articles.get(m.name.removeprefix("./")) if skipped < start_persisted: + 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) skipped += 1 if skipped == start_persisted: _render(force=True) # render resume point continue - f = f"tar://{tpath}!/{m.name}" st = SimpleNamespace( st_size=int(getattr(m, "size", 0)), st_mtime=float(getattr(m, "mtime", 0.0) or 0.0), @@ -541,6 +628,10 @@ def _render(force: bool = False): if not known and merged is not None 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: + refresh_known_member(f, m, meta, manifest_article) + if pending_refreshes >= ckpt_every: + flush_batch(str(tpath), processed_count + 1) processed_count += 1 continue @@ -714,9 +805,13 @@ def _render(force: bool = False): cur.execute("UPDATE papers SET embedding_text=? WHERE id=?", (ta_ab, pid)) bibliography = meta.get("references") - cur.execute("UPDATE papers SET references_json=? WHERE id=?", ( - json.dumps(bibliography, ensure_ascii=False) if bibliography is not None else None, pid, + 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,)) 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", []))) @@ -803,7 +898,7 @@ def _render(force: bool = False): persisted_count = processed_count _render(force=True) - if processed_count != persisted_count or str(tpath) not in ckpt_stream: + if pending_refreshes or processed_count != persisted_count or str(tpath) not in ckpt_stream: flush_batch(str(tpath), processed_count) _render(force=True) _progress_newline(sys.stderr) @@ -816,6 +911,11 @@ def _render(force: bool = False): ) with owner_lock, ExitStack() as readers: merged = None + merged_has_types = False + merged_sequence = 0 + has_refresh_table = bool(conn.execute( + "SELECT 1 FROM sqlite_master WHERE name='publication_refreshes'" + ).fetchone()) merged_has_links = False ensure_in_index_columns(conn) ensure_paper_embedding_column(conn) @@ -841,13 +941,14 @@ 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_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'" ).fetchone()) producer_id = chunk_seg_writer.shard_id - publication.bind_producer_outputs( - merged_checkpoints(main_db, producer_id).get(producer_id), main_db - ) + receipt = merged_checkpoints(main_db, producer_id).get(producer_id) + merged_sequence = (receipt or {}).get("segment_sequence", 0) + publication.bind_producer_outputs(receipt, main_db) verify_legacy_shard( conn, producer_id, paper_output_dir, chunk_seg_writer.outdir, merged_db=main_db, diff --git a/src/litkit/build/publication.py b/src/litkit/build/publication.py index c4e3ad4..f7d66be 100644 --- a/src/litkit/build/publication.py +++ b/src/litkit/build/publication.py @@ -263,6 +263,15 @@ def _finish(self, directories, tar, members, paper, chunk): maybe_fsync_dir(target) maybe_fsync_dir(pending) sequenced, _, sequence, _ = segment_order(chunk or paper or "") + if self.producer and self.conn.execute( + "SELECT 1 FROM sqlite_master WHERE name='publication_refreshes'" + ).fetchone(): + # A metadata-only refresh emits no segment filename. Its durable + # sequence must advance on recovery as well as on a clean commit. + latest = self.conn.execute("SELECT MAX(sequence) FROM publication_refreshes").fetchone()[0] + if latest is not None: + sequence = max(latest, sequence or 0) + sequenced = True if sequenced: self.checkpoint["segment_sequence"] = max(sequence, self.checkpoint.get("segment_sequence", 0)) self.checkpoint_tar(tar, members) diff --git a/src/litkit/cli.py b/src/litkit/cli.py index fe4b6a1..7cb688a 100644 --- a/src/litkit/cli.py +++ b/src/litkit/cli.py @@ -1608,6 +1608,7 @@ def _resolve_build_stage1_mode(*, persist: bool) -> str: chunk_min_chars=int(getattr(args, "chunk_min_chars", BODY_MIN_CHARS)), chunk_overlap=int(getattr(args, "chunk_overlap", CHUNK_OVERLAP_CHARS)), ckpt_shard_id=ckpt_shard_id, + publication_manifest=getattr(args, "publication_manifest", None), _producer_locked=args.embed_producer, parse_workers=args.parse_workers, include_tables=include_tables, @@ -1978,6 +1979,7 @@ def main(): "true", "yes", ) + ap.add_argument("--publication-manifest", type=Path, help="text-fetch .text-fetch/workspace.json for the input archives") ap.add_argument( "--include-tables", action=argparse.BooleanOptionalAction, diff --git a/src/litkit/db/schema.py b/src/litkit/db/schema.py index 2b72773..9457597 100644 --- a/src/litkit/db/schema.py +++ b/src/litkit/db/schema.py @@ -44,7 +44,11 @@ in_index INTEGER DEFAULT 0, -- Paper vector input when multiple versions share an ID embedding_text TEXT, - references_json TEXT + references_json TEXT, + publication_source BLOB, + article_type TEXT, + publication_types TEXT, + retracted INTEGER ); CREATE TABLE IF NOT EXISTS chunks ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -89,7 +93,8 @@ def optional_paper_columns( prefix = f"{alias}." if alias else "" return { name: (f"{prefix}{name}" if name in cols else "NULL") - for name in ("doc_id", "source_path", "doi", "year", "authors", "journal", "references_json") + for name in ("doc_id", "source_path", "doi", "year", "authors", "journal", "references_json", + "publication_source", "article_type", "publication_types", "retracted") } @@ -247,6 +252,10 @@ def ensure_paper_embedding_column(conn: sqlite3.Connection) -> None: _ADDED_COLUMNS = ( + ("papers", "publication_source", "BLOB"), + ("papers", "article_type", "TEXT"), + ("papers", "publication_types", "TEXT"), + ("papers", "retracted", "INTEGER"), ("papers", "references_json", "TEXT"), ("chunks", "cited_refs", "TEXT"), ("papers", "in_index", "INTEGER DEFAULT 0"), diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index f0e74f1..da00798 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['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)) FROM {shard}.papers p JOIN {mapping} m ON m.shard_pid=p.id @@ -252,6 +253,7 @@ def _merge_revised_papers(conn, shard, mapping, since): authors, journal, references_json, + publication_source, article_type, publication_types, retracted, embedding_text, ) in revisions: if (history_only or new_alias) and doi and not (pmid and pmcid): @@ -275,17 +277,22 @@ def _merge_revised_papers(conn, shard, mapping, since): (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 + # revision has unknown status and cannot authorize an earlier sidecar. conn.execute(""" UPDATE papers SET in_index=CASE WHEN COALESCE(embedding_text, (SELECT text FROM chunks WHERE paper_id=:id AND ord=-1 ORDER BY id DESC LIMIT 1) ) IS :input THEN in_index ELSE 0 END, title=:title, abstract=:abstract, source_path=:source, embedding_text=:input, references_json=:refs, + publication_source=:publication_source, article_type=:article_type, + publication_types=:types, retracted=:retracted, doi=COALESCE(NULLIF(:doi,''), doi), year=COALESCE(:year, year), authors=COALESCE(NULLIF(:authors,''), authors), journal=COALESCE(NULLIF(:journal,''), journal), pmid=COALESCE(NULLIF(pmid,''), :pmid), pmcid=COALESCE(NULLIF(pmcid,''), :pmcid) WHERE id=:id """, {"title": title, "abstract": abstract, "source": source_path, "input": embedding_text, "refs": references_json, + "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}) inserted += conn.execute(f""" @@ -395,10 +402,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, in_index + 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 ) SELECT p.doc_id, p.pmid, p.pmcid, {p_cols['doi']}, {p_cols['year']}, {p_cols['authors']}, {p_cols['journal']}, - p.title, p.abstract, {source_path}, {embedding_text}, {p_cols['references_json']}, 0 + p.title, p.abstract, {source_path}, {embedding_text}, {p_cols['references_json']}, + {p_cols['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 AND p.doc_id != '' @@ -491,6 +499,19 @@ def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge, to_record): chunks_merged += _merge_revised_papers( main_conn, shard_alias, temp_map_table, previous.get("segment_sequence", 0) ) + if main_cur.execute( + f"SELECT 1 FROM {shard_alias}.sqlite_master WHERE name='publication_refreshes'" + ).fetchone(): + # Detached producers may have only a metadata change for + # a paper already merged into the main DB. Only the + # latest archive's member owns its publication metadata. + main_cur.execute(f""" + UPDATE papers AS p + SET article_type=r.article_type, publication_types=r.types, retracted=r.retracted + FROM {shard_alias}.publication_refreshes r + JOIN files f ON f.path=r.path + WHERE p.id=f.paper_id AND p.publication_source=r.source AND r.sequence>? + """, (previous.get("segment_sequence", 0),)) # 3) BULK MERGE FILES # Insert/replace files with remapped paper_id diff --git a/src/litkit/formatting/answers.py b/src/litkit/formatting/answers.py index 3ee4b6c..7668213 100644 --- a/src/litkit/formatting/answers.py +++ b/src/litkit/formatting/answers.py @@ -173,6 +173,7 @@ def _replace(match: re.Match) -> str: "doi": ch.get("doi"), "paper_title": ch.get("paper_title") or ch.get("title"), "year": ch.get("year"), + "retracted": ch.get("retracted"), } ) return normalized_answer, doc_refs @@ -212,6 +213,9 @@ def _doc_key(d: dict[str, Any]) -> int: if not title_and_year.endswith("."): title_and_year += "." + if d.get("retracted"): + title_and_year += " [RETRACTED]" + id_parts: list[str] = [] doi = (d.get("doi") or "").strip() pmcid = (d.get("pmcid") or "").strip() diff --git a/src/litkit/ingest/ingest.py b/src/litkit/ingest/ingest.py index 0fcc6c4..353e21b 100644 --- a/src/litkit/ingest/ingest.py +++ b/src/litkit/ingest/ingest.py @@ -40,6 +40,7 @@ from __future__ import annotations +import hashlib import io import logging import re @@ -114,6 +115,9 @@ class ArticleMeta(TypedDict): abstract: str paragraphs: list[str] source_path: NotRequired[str] + article_type: NotRequired[str] + publication_types: NotRequired[list[str]] + retracted: NotRequired[bool] references: NotRequired[list[dict[str, str]]] paragraph_citations: NotRequired[dict[int, list[tuple[int, int, str]]]] abstract_citations: NotRequired[list[tuple[int, int, str]]] @@ -1134,6 +1138,16 @@ def _walk_root(node: etree._Element) -> None: "abstract": abstract or "", "paragraphs": paras, } + from litkit.ingest.publication_types import classify + + raw_type = root.get("article-type", "") + subjects = root.findall("{*}front/{*}article-meta/{*}article-categories//{*}subject") + related = root.findall("{*}front/{*}article-meta/{*}related-article") + labels = [raw_type, *(_txt(node) for node in subjects)] + if any(node.get("related-article-type") in {"retraction-in", "retraction-forward"} for node in related): + labels.append("retracted") + meta["article_type"] = raw_type + meta["publication_types"], meta["retracted"] = classify(labels) if references is not None: meta["references"] = references if paragraph_citations: @@ -1159,40 +1173,44 @@ def _walk_root(node: etree._Element) -> None: def parse_pubmed(tree: etree._ElementTree) -> ArticleMeta: """Parse PubMed XML (non-JATS) into a consistent structure.""" - xp = tree.xpath - pmid = xp('string(//*[local-name()="PubmedArticle"]//*[local-name()="PMID"][1])').strip() or "" - title = xp('string(//*[local-name()="Article"]/*[local-name()="ArticleTitle"][1])').strip() + # A PubmedArticleSet can contain multiple independent citations. This API + # returns one record, so every field must be relative to the same record. + records = tree.xpath('(//*[local-name()="PubmedArticle"])[1]') + article = records[0] if records else tree.getroot() + xp = article.xpath + 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"]' + './/*[local-name()="Article"]/*[local-name()="Abstract"]/*[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 = ( xp( - 'string(//*[local-name()="PubmedData"]/*[local-name()="ArticleIdList"]' + 'string(.//*[local-name()="PubmedData"]/*[local-name()="ArticleIdList"]' '/*[local-name()="ArticleId"][@IdType="doi"][1])' ).strip() or xp( - 'string(//*[local-name()="Article"]/*[local-name()="ELocationID"][@EIdType="doi"][1])' + 'string(.//*[local-name()="Article"]/*[local-name()="ELocationID"][@EIdType="doi"][1])' ).strip() ) year_raw = ( - xp('string(//*[local-name()="JournalIssue"]/*[local-name()="PubDate"]/*[local-name()="Year"][1])').strip() + xp('string(.//*[local-name()="JournalIssue"]/*[local-name()="PubDate"]/*[local-name()="Year"][1])').strip() or xp( - 'string(//*[local-name()="JournalIssue"]/*[local-name()="PubDate"]/*[local-name()="MedlineDate"][1])' + 'string(.//*[local-name()="JournalIssue"]/*[local-name()="PubDate"]/*[local-name()="MedlineDate"][1])' ).strip() ) year = _parse_year_text(year_raw) journal = ( - xp('string(//*[local-name()="Article"]/*[local-name()="Journal"]/*[local-name()="Title"][1])').strip() + xp('string(.//*[local-name()="Article"]/*[local-name()="Journal"]/*[local-name()="Title"][1])').strip() or xp( - 'string(//*[local-name()="Article"]/*[local-name()="Journal"]/*[local-name()="ISOAbbreviation"][1])' + 'string(.//*[local-name()="Article"]/*[local-name()="Journal"]/*[local-name()="ISOAbbreviation"][1])' ).strip() - or xp('string(//*[local-name()="MedlineJournalInfo"]/*[local-name()="MedlineTA"][1])').strip() + or xp('string(.//*[local-name()="MedlineJournalInfo"]/*[local-name()="MedlineTA"][1])').strip() ) authors_list: list[str] = [] - for author_el in xp('//*[local-name()="Article"]/*[local-name()="AuthorList"]/*[local-name()="Author"]'): + for author_el in xp('.//*[local-name()="Article"]/*[local-name()="AuthorList"]/*[local-name()="Author"]'): last = "" fore = "" initials = "" @@ -1225,6 +1243,14 @@ def parse_pubmed(tree: etree._ElementTree) -> ArticleMeta: meta["doi"] = doi if year is not None: meta["year"] = year + from litkit.ingest.publication_types import classify + + types = xp('.//*[local-name()="MedlineCitation"]/*[local-name()="Article"]' + '/*[local-name()="PublicationTypeList"]/*[local-name()="PublicationType"]') + labels = [_txt(node) for node in types] + if xp('.//*[local-name()="CommentsCorrections"][@RefType="RetractionIn"]'): + labels.append("retracted") + meta["publication_types"], meta["retracted"] = classify(labels) if authors_list: meta["authors"] = "; ".join(authors_list) if journal: @@ -1574,12 +1600,13 @@ def _parse_xml_bytes( class TarMemberMeta: """Minimal file metadata from a tar member, used for checkpointing.""" - __slots__ = ("name", "size", "mtime") + __slots__ = ("name", "size", "mtime", "content_sha256") - def __init__(self, name: str, size: int, mtime: float): + def __init__(self, name: str, size: int, mtime: float, content_sha256: bytes | None = None): self.name = name self.size = size self.mtime = mtime + self.content_sha256 = content_sha256 def parallel_iter_tar_articles( @@ -1653,7 +1680,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) + pending[future] = TarMemberMeta(member.name, member.size, member.mtime, hashlib.sha256(data).digest()) if not pending: return diff --git a/src/litkit/ingest/publication_types.py b/src/litkit/ingest/publication_types.py new file mode 100644 index 0000000..5f1bea2 --- /dev/null +++ b/src/litkit/ingest/publication_types.py @@ -0,0 +1,63 @@ +"""Publication categories shared by archive ingestion and retrieval filters.""" + +import hashlib +import json +import re + +PUBLICATION_TYPES = frozenset({ + "research", "review", "systematic-review", "meta-analysis", "editorial", + "comment", "perspective", "letter", "case-report", "correction", "retraction", "other", +}) +_ALIASES = { + "research-article": "research", "original-research": "research", + "research-articles": "research", "original-article": "research", + "review-article": "review", "reviews": "review", "systematic-reviews": "systematic-review", + "meta-analyses": "meta-analysis", "article-commentary": "comment", "commentary": "comment", + "perspectives": "perspective", "opinion": "perspective", "case-reports": "case-report", + "published-erratum": "correction", "erratum": "correction", "retraction-of-publication": "retraction", + "clinical-trial": "research", "randomized-controlled-trial": "research", "observational-study": "research", +} + + +def classify(labels): + types = set() + retracted = False + for label in labels: + key = re.sub(r"[\s_]+", "-", label.strip().casefold()) + if key in {"retracted", "retracted-article", "retracted-publication"}: + retracted = True + category = _ALIASES.get(key, key) + if category in PUBLICATION_TYPES and category != "other": + types.add(category) + return sorted(types or {"other"}), retracted + + +def publication_source(path: str, content_sha256: bytes) -> bytes: + """Bind publication metadata to an archive member's path and exact bytes.""" + return hashlib.sha256(path.encode("utf-8") + b"\0" + content_sha256).digest() + + +def publication_fields(meta, manifest_article): + """Return the stored raw type, normalized types and retraction flag.""" + types = meta.get("publication_types", ["other"]) + retracted = bool(meta.get("retracted")) + if manifest_article is not None: + evidence = manifest_article.get("source_types") + if meta.get("article_type") is not None and evidence is not None and "jats" not in evidence: + # text-fetch's PDF converter supplies a generic research-article + # wrapper even for technical reports. Only the publisher can assign + # its category. Preserve the wrapper's raw attribute for inspection. + types = [] + retracted = False + types, marked = classify([*types, *manifest_article.get("publication_types", [])]) + retracted = retracted or marked or manifest_article.get("retracted") is True + return meta.get("article_type"), json.dumps(types), int(retracted) + + +def result_fields(raw, types, retracted): + """Represent SQL NULL as unknown for papers built with older schemas.""" + return { + "article_type": raw, + "types": json.loads(types) if types else [], + "retracted": bool(retracted) if retracted is not None else None, + } diff --git a/src/litkit/llm/qa.py b/src/litkit/llm/qa.py index 2f5e9b7..73b07cd 100644 --- a/src/litkit/llm/qa.py +++ b/src/litkit/llm/qa.py @@ -90,6 +90,8 @@ def pack_context( meta_parts.append(f"PMCID:{ch['pmcid']}") if ch.get("pmid") and not ch.get("pmcid"): meta_parts.append(f"PMID:{ch['pmid']}") + if ch.get("retracted"): + meta_parts.append("RETRACTED") meta_str = f" ({', '.join(meta_parts)})" if meta_parts else "" # Format block: [i] Title (PMCID:xxx)\nText diff --git a/src/litkit/retrieval/cli_commands.py b/src/litkit/retrieval/cli_commands.py index 58ec453..758b480 100644 --- a/src/litkit/retrieval/cli_commands.py +++ b/src/litkit/retrieval/cli_commands.py @@ -156,6 +156,8 @@ def _add_paper_filter_args(parser: argparse.ArgumentParser) -> None: parser.add_argument("--doi", type=str, default=None, help="Filter by exact DOI.") parser.add_argument("--pmcid", type=str, default=None, help="Filter by exact PMCID.") parser.add_argument("--pmid", type=str, default=None, help="Filter by exact PMID.") + parser.add_argument("--type", dest="types", action="append", help="Include papers with any listed publication type (repeatable).") + parser.add_argument("--exclude-type", dest="exclude_types", action="append", help="Exclude papers with a listed publication type (repeatable).") parser.add_argument("--journal", type=str, default=None, help="Filter by journal name.") @@ -173,9 +175,16 @@ def _add_embedder_args(parser: argparse.ArgumentParser) -> None: ) +def _print_publication_types(row): + if row.get("types"): + print(" Publication types: " + ", ".join(row["types"])) + if row.get("retracted"): + print(" RETRACTED") + + def _collect_filters(args: argparse.Namespace) -> dict[str, Any]: out: dict[str, Any] = {} - for key in ("year_from", "year_to", "author", "doi", "pmcid", "pmid", "journal"): + for key in ("year_from", "year_to", "author", "doi", "pmcid", "pmid", "journal", "types", "exclude_types"): val = getattr(args, key, None) if val is not None and val != "": out[key] = val @@ -225,6 +234,7 @@ def _run_search_papers(argv: list[str]) -> int: as_json=args.json, ) + result_warnings = [] filters = _collect_filters(args) query_s = (args.query or "").strip() stage1_mode = _read_stage1_mode_readonly(paths.db_path) @@ -259,6 +269,7 @@ def _run_search_papers(argv: list[str]) -> int: results = search_papers( query=query_s or None, filters=filters, + result_warnings=result_warnings, limit=args.limit, db_path=paths.db_path, paper_index_path=paper_index_path, @@ -281,6 +292,7 @@ def _run_search_papers(argv: list[str]) -> int: "query": query_s, "mode": effective_mode, "filters": filters, + **({"warnings": result_warnings} if result_warnings else {}), "count": len(results), "results": results, } @@ -288,6 +300,8 @@ def _run_search_papers(argv: list[str]) -> int: ) return 0 + for message in result_warnings: + print(message, file=sys.stderr) if not results: print("No matching papers found.") return 0 @@ -296,6 +310,7 @@ def _run_search_papers(argv: list[str]) -> int: year_s = f" ({p['year']})" if p.get("year") else "" handle = p.get("citation_handle", f"paper:{p['paper_id']}") print(f"[{idx}] {p['title'] or 'untitled'}{year_s} — {handle} (chunks={p['chunk_count']})") + _print_publication_types(p) if p.get("authors"): print(f" Authors: {p['authors']}") if p.get("journal"): @@ -364,6 +379,7 @@ def _run_search_passages(argv: list[str]) -> int: as_json=args.json, ) + result_warnings = [] filters = _collect_filters(args) sections = args.section if args.section else None section_arg: str | list[str] | None = ( @@ -419,6 +435,7 @@ def _run_search_passages(argv: list[str]) -> int: min_chunks_per_paper=args.min_chunks_per_paper, per_paper_cap=args.per_paper_cap, filters=filters, + result_warnings=result_warnings, ) except ValueError as err: emit_cli_error("invalid_argument", str(err), as_json=args.json) @@ -433,6 +450,7 @@ def _run_search_passages(argv: list[str]) -> int: "mode": args.mode, "section": section_arg, "filters": filters, + **({"warnings": result_warnings} if result_warnings else {}), "count": len(results), "results": results, } @@ -440,6 +458,8 @@ def _run_search_passages(argv: list[str]) -> int: ) return 0 + for message in result_warnings: + print(message, file=sys.stderr) if not results: print("No matching passages found.") return 0 @@ -447,6 +467,7 @@ def _run_search_passages(argv: list[str]) -> int: for idx, ch in enumerate(results, start=1): sec = f" [{ch['section']}]" if ch.get("section") else "" print(f"[{idx}] {ch['citation_handle']}{sec} (score={ch['score']:.4f}, {ch['match_type']})") + _print_publication_types(ch) if ch.get("paper_title"): print(f" {ch['paper_title']}") print(f" {ch['text']}") @@ -510,6 +531,7 @@ def _run_chunk_context(argv: list[str]) -> int: return 0 print(f"{ctx['title'] or 'untitled'} ({ctx['citation_handle']})") + _print_publication_types(ctx) for ch in ctx["chunks"]: marker = ">>>" if ch["is_target"] else " " sec = f" [{ch['section']}]" if ch.get("section") else "" @@ -586,6 +608,7 @@ def _run_get_paper(argv: list[str]) -> int: year_s = f" ({paper['year']})" if paper.get("year") else "" print(f"{paper['title'] or 'untitled'}{year_s} — {paper['citation_handle']}") + _print_publication_types(paper) if paper.get("authors"): print(f"Authors: {paper['authors']}") if paper.get("journal"): diff --git a/src/litkit/retrieval/progressive.py b/src/litkit/retrieval/progressive.py index 0edc190..7a76791 100644 --- a/src/litkit/retrieval/progressive.py +++ b/src/litkit/retrieval/progressive.py @@ -16,6 +16,7 @@ from __future__ import annotations +import warnings import math import re import sqlite3 @@ -43,6 +44,7 @@ parse_evidence_handle, source_digest, ) +from litkit.ingest.publication_types import result_fields from litkit.retrieval.helpers import _STOPWORDS, escape_like if TYPE_CHECKING: @@ -52,7 +54,7 @@ VALID_PASSAGE_MODES: tuple[str, ...] = ("hybrid", "semantic", "exact") VALID_PAPER_MODES: tuple[str, ...] = ("auto", "semantic", "lexical", "hybrid") _VALID_FILTER_KEYS = frozenset( - {"year_from", "year_to", "author", "doi", "pmcid", "pmid", "journal"} + {"year_from", "year_to", "author", "doi", "pmcid", "pmid", "journal", "types", "exclude_types"} ) _EXACT_STOPWORDS = _STOPWORDS | {"or", "so", "if", "do", "no", "up", "out", "any", "all"} @@ -358,6 +360,8 @@ def _merge_filters( pmcid: str | None = None, pmid: str | None = None, journal: str | None = None, + types: Sequence[str] | str | None = None, + exclude_types: Sequence[str] | str | None = None, ) -> dict[str, Any]: merged: dict[str, Any] = {} if filters: @@ -376,7 +380,7 @@ def _merge_filters( "doi": doi, "pmcid": pmcid, "pmid": pmid, - "journal": journal, + "journal": journal, "types": types, "exclude_types": exclude_types, } for k, v in explicit.items(): if v is not None and v != "": @@ -384,11 +388,16 @@ def _merge_filters( return merged +class PublicationTypeWarning(UserWarning): + """The requested type filter is unavailable on a legacy database.""" + + def _build_paper_filter_sql( conn: sqlite3.Connection, filters: Mapping[str, Any], *, alias: str = "p", + result_warnings: list[str] | None = None, ) -> tuple[list[str], dict[str, Any]]: """Build parameterized SQL WHERE clauses for paper metadata filters.""" if not filters: @@ -397,6 +406,29 @@ def _build_paper_filter_sql( clauses: list[str] = [] params: dict[str, Any] = {} + for key in ("types", "exclude_types"): + values = filters.get(key) + if not values: + continue + from litkit.ingest.publication_types import PUBLICATION_TYPES + + names = [values] if isinstance(values, str) else list(values) + if any(name not in PUBLICATION_TYPES for name in names): + raise ValueError(f"Unknown publication type in {names!r}. Choose from {sorted(PUBLICATION_TYPES)}.") + if "publication_types" not in cols: + message = "This workspace lacks publication types. Rebuild to filter by type." + if result_warnings is None: + warnings.warn(message, PublicationTypeWarning, stacklevel=3) + else: + result_warnings.append(message) + return ["1 = 0"], {} + keys = [f"f_{key}_{i}" for i in range(len(names))] + params.update(zip(keys, names, strict=True)) + placeholders = ",".join(":" + k for k in keys) + exists = "EXISTS" if key == "types" else "NOT EXISTS" + clauses.append(f"{alias}.publication_types IS NOT NULL AND {exists}" + f" (SELECT 1 FROM json_each({alias}.publication_types) WHERE value IN ({placeholders}))") + if "year_from" in filters: if "year" not in cols: return ["1 = 0"], {} @@ -515,7 +547,8 @@ def _paper_select_sql(conn: sqlite3.Connection, alias: str = "p") -> str: return ( f"{alias}.id, {p_cols['doc_id']}, {alias}.pmid, {alias}.pmcid, " f"{p_cols['doi']}, {alias}.title, {alias}.abstract, " - f"{p_cols['year']}, {p_cols['authors']}, {p_cols['journal']}, {p_cols['source_path']}" + f"{p_cols['year']}, {p_cols['authors']}, {p_cols['journal']}, {p_cols['source_path']}, " + f"{p_cols['article_type']}, {p_cols['publication_types']}, {p_cols['retracted']}" ) @@ -566,6 +599,7 @@ def _row_to_paper_dict( return { "paper_id": paper_id, "doc_id": doc_id, + **result_fields(*row[11:14]), "pmcid": pmcid, "pmid": pmid, "doi": doi, @@ -990,8 +1024,11 @@ def search_papers( pmcid: str | None = None, pmid: str | None = None, journal: str | None = None, + types: Sequence[str] | str | None = None, + exclude_types: Sequence[str] | str | None = None, mode: str = "auto", max_chars: int | None = None, + result_warnings: list[str] | None = None, connect_db=None, ) -> list[dict[str, Any]]: """Stage-1 and/or metadata search over papers with optional filters. @@ -1034,12 +1071,12 @@ def search_papers( doi=doi, pmcid=pmcid, pmid=pmid, - journal=journal, + journal=journal, types=types, exclude_types=exclude_types, ) query_s = (query or "").strip() with _open_conn(conn, db_path, connect_db) as db: - filter_clauses, filter_params = _build_paper_filter_sql(db, merged_filters) + filter_clauses, filter_params = _build_paper_filter_sql(db, merged_filters, result_warnings=result_warnings) cols = table_columns(db, "papers") # Pure metadata listing when no query text is given @@ -1172,7 +1209,8 @@ def _fetch_passages_by_ids( SELECT c.id, c.paper_id, c.ord, c.text, {c_cols['section']}, {c_cols['page']}, p.title, p.pmid, p.pmcid, {p_cols['doi']}, {p_cols['year']}, {p_cols['authors']}, {p_cols['journal']}, - {p_cols['source_path']}, {p_cols['doc_id']} + {p_cols['source_path']}, {p_cols['doc_id']}, + {p_cols['article_type']}, {p_cols['publication_types']}, {p_cols['retracted']} FROM chunks c JOIN papers p ON p.id = c.paper_id WHERE c.id IN ({marks}) @@ -1217,6 +1255,7 @@ def _fetch_passages_by_ids( match_types.get(chunk_id, "exact") if match_types is not None else "exact" ), "paper_title": title, + **result_fields(*row[15:18]), "pmid": pmid, "pmcid": pmcid, "doi": doi, @@ -1506,6 +1545,9 @@ def search_passages( pmcid: str | None = None, pmid: str | None = None, journal: str | None = None, + types: Sequence[str] | str | None = None, + exclude_types: Sequence[str] | str | None = None, + result_warnings: list[str] | None = None, connect_db=None, ) -> list[dict[str, Any]]: """Search passages using `"hybrid"`, `"semantic"`, or `"exact"` retrieval. @@ -1557,11 +1599,11 @@ def search_passages( doi=doi, pmcid=pmcid, pmid=pmid, - journal=journal, + journal=journal, types=types, exclude_types=exclude_types, ) with _open_conn(conn, db_path, connect_db) as db: - filter_clauses, filter_params = _build_paper_filter_sql(db, merged_filters) + filter_clauses, filter_params = _build_paper_filter_sql(db, merged_filters, result_warnings=result_warnings) if norm_mode == "exact": exact_hits = _exact_passage_search( @@ -1831,6 +1873,7 @@ def get_chunk_context( "year": year, "authors": authors, "journal": journal, + **result_fields(*paper_row[11:14]), "source_path": paper["source_path"], "citation_handle": paper["citation_handle"], "target_ord": target_ord, diff --git a/src/litkit/retrieval/stages.py b/src/litkit/retrieval/stages.py index 2922809..8ac6608 100644 --- a/src/litkit/retrieval/stages.py +++ b/src/litkit/retrieval/stages.py @@ -22,6 +22,7 @@ optional_paper_columns, ) from litkit.frontload.cap import cap_chunks_per_paper +from litkit.ingest.publication_types import result_fields from litkit.index import faiss_load_cached, faiss_present_ids from litkit.retrieval.helpers import ( avg_chunks_for_papers, @@ -344,7 +345,7 @@ def get_chunks(conn, ids: list[int]) -> list[dict[str, Any]]: f"""SELECT c.id, c.paper_id, c.ord, c.text, p.title, p.pmid, p.pmcid, {p_cols['source_path']}, {c_cols['page']}, {p_cols['doi']}, {p_cols['year']}, {p_cols['authors']}, {p_cols['journal']}, - {c_cols['section']} + {c_cols['section']}, {p_cols['article_type']}, {p_cols['publication_types']}, {p_cols['retracted']} FROM chunks c JOIN papers p ON p.id=c.paper_id WHERE c.id IN ({marks})""", ids, @@ -371,5 +372,6 @@ def get_chunks(conn, ids: list[int]) -> list[dict[str, Any]]: "authors": row[11], "journal": row[12], "section": row[13], + **result_fields(*row[14:17]), }) return out diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index d56f7aa..f266e1f 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -1468,6 +1468,211 @@ def fail_cleanup(path): assert [len(ids) for ids, _ in build.consume()] == [3, 6] +@pytest.mark.parametrize("producer", [False, True]) +def test_publication_types_update_across_archives(tmp_path, producer): + from litkit.retrieval import get_chunk_context, get_paper, search_papers, search_passages + import json + + archive = tmp_path / "initial.tar" + build = Build(tmp_path / "sqlite", archive, producer=producer) + path = build.root / "litkit.sqlite3" if producer else build.db + source = tmp_path / "workspace.json" + source.write_text(json.dumps({"articles": { + "valid/notice.xml": {"publication_types": ["retraction-of-publication"]}, + "valid/revised.xml": {"publication_types": ["retracted-publication"], "retracted": True}, + }})) + title = "Cohort analysis" + original = jats(pmcid="PMC42", title=title).replace( + "research-article", "review-article").replace( + "", "Systematic Review" + "") + notice = jats(pmcid="PMC43", title="Cohort notice").replace("research-article", "retraction") + write_tar(archive, {"valid/original.xml": original, "valid/notice.xml": notice}) + with closing(init_db(path)) as db: + for n in (0, 1): + if n: + archive = tmp_path / "later.tar" + write_tar(archive, {"valid/revised.xml": original}) + build.run(tar_paths=[archive], publication_manifest=source) + if producer: + merge_shard_databases(db, delete_after_merge=False, segment_dir=build.segments) + build.ingest_merged(db) + paper = get_paper("PMC42", conn=db) + assert paper["article_type"] == "review-article" + assert paper["types"] == ["review", "systematic-review"] + assert paper["retracted"] is bool(n) + assert get_paper("PMC43", conn=db)["retracted"] is False + for hit in (get_chunk_context("PMC42", -1, conn=db), + search_papers(types="review", exclude_types=["retraction"], conn=db)[0], + search_passages("cohort", types="systematic-review", mode="exact", conn=db)[0]): + assert hit["retracted"] is bool(n) + assert hit["pmcid"] == "PMC42" + + +@pytest.mark.parametrize("build_mode", ["writer", "retained-producer", "detached-producer"]) +def test_refresh_known_member_from_changed_text_fetch_manifest(tmp_path, build_mode): + import json + from litkit.retrieval import get_paper + + producer = build_mode != "writer" + archive = tmp_path / "articles.tar" + build = Build(tmp_path / "sqlite", archive, producer=producer) + db_path = build.root / "litkit.sqlite3" if producer else build.db + member = "valid/report.xml" + write_tar(archive, {member: jats(pmcid="PMC42", title="Technical report")}) + sidecar = tmp_path / "workspace.json" + with closing(init_db(db_path)) as db: + for i, (labels, types, retracted) in enumerate([ + (["Technical Report"], ["other"], False), + (["Systematic Review", "Retracted Publication"], ["systematic-review"], True), + (["Review"], ["review"], False), + ]): + info = {"source_types": {"osti": labels}, "publication_types": labels, "retracted": retracted} + sidecar.write_text(json.dumps({"articles": {member: info}})) + counts = build.run(publication_manifest=sidecar)[2:] + if i: + assert counts == (0, 0) + if producer: + merge_shard_databases(db, delete_after_merge=build_mode == "detached-producer", + segment_dir=build.segments) + build.ingest_merged(db) + paper = get_paper("PMC42", conn=db) + assert paper["article_type"] == "research-article" # synthetic GROBID XML wrapper + assert paper["types"] == types + assert paper["retracted"] is retracted + chunk_ids = [c["chunk_id"] for c in paper["chunks"]] + if i: + assert chunk_ids == original_ids + else: + original_ids = chunk_ids + + +def test_unconsumed_manifest_change_can_be_reversed_on_a_detached_producer(tmp_path): + import json + from litkit.retrieval import get_paper + + archive = write_tar(tmp_path / "a.tar", {"valid/x.xml": jats(pmcid="PMC42", title="Report")}) + build = Build(tmp_path / "sqlite", archive) + sidecar = tmp_path / "workspace.json" + with closing(init_db(build.root / "litkit.sqlite3")) as main: + build.run() + merge_shard_databases(main, delete_after_merge=True, segment_dir=build.segments) + build.ingest_merged(main) + for flag in (True, False): + sidecar.write_text(json.dumps({"articles": {"valid/x.xml": {"retracted": flag}}})) + assert build.run(publication_manifest=sidecar)[2:] == (0, 0) + merge_shard_databases(main, delete_after_merge=True, segment_dir=build.segments) + assert get_paper("PMC42", conn=main)["retracted"] is False + + +def test_manifest_refresh_cannot_retract_a_different_paper_at_a_reused_path(tmp_path): + from litkit.retrieval import get_paper + + archive = tmp_path / "changed.tar" + build = Build(tmp_path / "sqlite", archive, producer=False) + member = "valid/paper.xml" + write_tar(archive, {member: jats(pmcid="PMC41", title="Report A")}) + build.run() + # Identical member size and timestamp alone cannot establish identity. + write_tar(archive, {member: jats(pmcid="PMC42", title="Report B")}) + sidecar = tmp_path / "workspace.json" + sidecar.write_text('{"articles":{"valid/paper.xml":{"retracted":true}}}') + assert build.run(publication_manifest=sidecar)[2:] == (0, 0) + with closing(init_db(build.db)) as conn: + assert get_paper("PMC41", conn=conn)["retracted"] is False + + +@pytest.mark.parametrize("writer_workers", [1, 2]) +@pytest.mark.parametrize("changed", ["body", "native_status"]) +def test_queued_manifest_refresh_cannot_replace_a_newer_archive_revision(tmp_path, writer_workers, changed): + from litkit.retrieval import get_paper + + archive = tmp_path / "changed.tar" + member = "valid/paper.xml" + xml = jats(pmcid="PMC41", title="Report", paragraphs=["Revision A"]) + if changed == "native_status": + initial = xml.replace("", '') + updated = initial.replace("retraction-forward", "unrelated-relation") + else: + initial = xml + updated = xml.replace("Revision A", "Revision B") + assert len(initial) == len(updated) + write_tar(archive, {member: initial}) + root = tmp_path / "sqlite" + producer = Build(root, archive) + writer = Build(root, archive, producer=False) + with closing(init_db(root / "litkit.sqlite3")) as main: + producer.run(parse_workers=2) + merge_shard_databases(main, delete_after_merge=True, segment_dir=producer.segments) + producer.ingest_merged(main) + sidecar = tmp_path / "workspace.json" + # Force a queued status change even when the old XML was itself retracted. + sidecar.write_text('{"articles":{"valid/paper.xml":{"publication_types":["review"],"retracted":true}}}') + assert producer.run(publication_manifest=sidecar)[2:] == (0, 0) + # A newer version took ownership of the same path before the consumer + # could apply the queued status for Report A. + write_tar(archive, {member: updated}) + writer.run(conn=main, rebuild=True, parse_workers=writer_workers) + merge_shard_databases(main, delete_after_merge=True, segment_dir=producer.segments) + paper = get_paper("PMC41", conn=main) + assert (paper["types"], paper["retracted"]) == (["research"], False) + + +@pytest.mark.parametrize("bridge_shard", [0, 1], ids=["bridge-first", "refresh-first"]) +def test_legacy_bridge_does_not_inherit_older_members_queued_retraction(tmp_path, bridge_shard): + from litkit.retrieval import get_paper + + member = "article.xml" + old = Build(tmp_path, tmp_path / "original.tar", shard_id=1 - bridge_shard) + bridge = Build(tmp_path, tmp_path / "revision.tar", shard_id=bridge_shard) + write_tar(old.tar, {member: jats(pmid="123", title="Original report")}) + write_tar(bridge.tar, {member: jats(pmid="123", pmcid="PMC42", title="Revised report")}) + with closing(init_db(tmp_path / "litkit.sqlite3")) as main: + old.run() + merge_shard_databases(main, delete_after_merge=True, segment_dir=old.segments) + old.ingest_merged(main) + sidecar = tmp_path / "workspace.json" + sidecar.write_text('{"articles":{"article.xml":{"retracted":true}}}') + assert old.run(publication_manifest=sidecar)[2:] == (0, 0) + bridge.run() + # A queued producer shard from before article-status provenance was recorded. + with closing(sqlite3.connect(bridge.db)) as shard: + for field in ("publication_source", "article_type", "publication_types", "retracted"): + shard.execute(f"ALTER TABLE papers DROP COLUMN {field}") + shard.commit() + for _ in range(2): + merge_shard_databases(main, delete_after_merge=False, segment_dir=bridge.segments) + paper = get_paper("PMC42", conn=main) + assert (paper["title"], paper["article_type"], paper["types"], paper["retracted"]) == ( + "Revised report", None, [], None + ) + assert main.execute("SELECT publication_source FROM papers").fetchall() == [(None,)] + + +def test_failed_manifest_publication_rolls_back_an_autocommit_connection(tmp_path, monkeypatch): + from litkit.build.publication import BatchPublication + from litkit.retrieval import get_paper + + member = "valid/paper.xml" + archive = write_tar(tmp_path / "a.tar", {member: jats(pmcid="PMC41", title="Report")}) + producer = Build(tmp_path / "sqlite", archive) + producer.run() + sidecar = tmp_path / "workspace.json" + sidecar.write_text('{"articles":{"valid/paper.xml":{"retracted":true}}}') + + def interrupt(*args): + raise OSError("interrupted before publication") + + with closing(sqlite3.connect(producer.db, autocommit=True)) as db: + with monkeypatch.context() as fault: + fault.setattr(BatchPublication, "publish", interrupt) + with pytest.raises(OSError, match="interrupted before publication"): + producer.run(conn=db, publication_manifest=sidecar) + assert get_paper("PMC41", conn=db)["retracted"] is False + assert producer.run(conn=db, publication_manifest=sidecar)[2:] == (0, 0) + assert get_paper("PMC41", conn=db)["retracted"] is True + + def test_linked_identifiers_replace_buffered_rows_and_retry_after_failure(tmp_path, monkeypatch): archive = tmp_path / "together.tar" write_tar(archive, [ diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index 678bf63..5ca69df 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -1761,7 +1761,7 @@ def test_progressive_retrieval_cli_json_and_payload_bounds(tmp_path, monkeypatch tars = tmp_path / "tars" tars.mkdir() kras_xml = """ -
+
Nature @@ -1773,6 +1773,7 @@ def test_progressive_retrieval_cli_json_and_payload_bounds(tmp_path, monkeypatch HlavacekWilliam S. 2022 +

Kinetic characterization of KRAS G12C with SOS1 and SHP-2 inhibitors.

@@ -1925,3 +1926,7 @@ def test_progressive_retrieval_cli_json_and_payload_bounds(tmp_path, monkeypatch assert 1 <= leg_data["count"] <= 2 assert sum(len(r["text"]) for r in leg_data["results"]) <= 150 assert all("citation_handle" in r for r in leg_data["results"]) + evidence = [r for r in leg_data["results"] if r["pmcid"] == "PMC555001"] + assert evidence and all(r["retracted"] and "research" in r["types"] for r in evidence) + packed = _ok(litkit(ws, "KRAS G12C", "--no-llm", "--limit", "2")) + assert "RETRACTED" in packed.stdout diff --git a/tests/test_formatting.py b/tests/test_formatting.py index 38bba86..3583c3f 100644 --- a/tests/test_formatting.py +++ b/tests/test_formatting.py @@ -199,3 +199,11 @@ def test_render_references_order_ids_and_title_fallback(): def test_render_references_untitled_and_empty(): assert render_references([{"docnum": 1}]) == "References\n[1] untitled." assert render_references([]) == "References\n" + + +def test_retracted_paper_remains_flagged_in_the_cited_references(): + _, refs = normalize_answer_and_build_refs( + "Evidence [1].", [{"paper_id": 7, "paper_title": "Original study", "retracted": True}] + ) + assert refs[0]["retracted"] is True + assert "Original study. [RETRACTED]" in render_references(refs) diff --git a/tests/test_ingest.py b/tests/test_ingest.py index 7fd7e10..5c277da 100644 --- a/tests/test_ingest.py +++ b/tests/test_ingest.py @@ -87,6 +87,8 @@ def test_parse_pubmed_record(): "title": "A PubMed record", "abstract": "Only an abstract.", "paragraphs": [], + "publication_types": ["other"], + "retracted": False, } @@ -937,3 +939,38 @@ def test_parse_pubmed_ignores_doi_of_cited_reference(): meta = _parse(xml) assert meta is not None assert meta["doi"] == "10.9999/own.2018.1" + +def test_pubmed_publication_types_distinguish_notice_from_target(): + for label, expected, retracted in [ + ("Retraction of Publication", ["retraction"], False), + ("Retracted Publication", ["other"], True), + ("Meta-Analysis", ["meta-analysis"], False), + ]: + xml = pubmed_xml("123", "Record", "Summary").replace( + "
", f"{label}" + "
") + meta = _parse(xml) + assert (meta["publication_types"], meta["retracted"]) == (expected, retracted) + + +def test_pubmed_set_does_not_assign_another_records_retraction(): + first = pubmed_xml("1", "First", "First abstract") + second = pubmed_xml("2", "Retracted", "Second abstract").split("")[1] + second = second.replace( + "", + "Retracted Publication" + "", + ).replace("", '') + record = _parse(first.replace("", second)) + assert (record["pmid"], record["abstract"], record["retracted"]) == ("1", "First abstract", False) + + +@pytest.mark.parametrize( + ("relationship", "expected"), + [("retraction-forward", True), ("retraction-in", True), ("retracted-article", False)], +) +def test_publisher_retraction_links_are_directional(relationship, expected): + xml = jats(pmcid="PMC42", title="A paper").replace( + "", f'' + ) + assert _parse(xml)["retracted"] is expected diff --git a/tests/test_progressive_retrieval.py b/tests/test_progressive_retrieval.py index a31be31..ead08de 100644 --- a/tests/test_progressive_retrieval.py +++ b/tests/test_progressive_retrieval.py @@ -675,6 +675,12 @@ def test_progressive_apis_work_on_readonly_legacy_db_without_new_columns(tmp_pat assert papers[0]["year"] is None # Filtering on missing columns returns empty cleanly (no OperationalError) + with pytest.warns(UserWarning, match="lacks publication types"): + assert search_papers(types="review", conn=ro) == [] + warnings = [] + assert search_passages("KRAS", exclude_types="review", mode="exact", conn=ro, + result_warnings=warnings) == [] + assert len(warnings) == 1 and "publication types" in warnings[0] assert search_papers(filters={"year_from": 2020}, conn=ro) == [] assert search_papers(filters={"author": "Smith"}, conn=ro) == [] assert search_papers(filters={"doi": "10.1/a"}, conn=ro) == []