From ebccee12aff965b85f4354db7b4dd0f6490d94ff Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Fri, 4 Dec 2026 14:30:34 -0700 Subject: [PATCH 1/6] Ingest publication types and retraction status and filter evidence by type Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 3 ++ README.md | 8 +++- src/litkit/build/ingest_loop.py | 21 ++++++++- src/litkit/cli.py | 2 + src/litkit/db/schema.py | 11 ++++- src/litkit/db/sharding.py | 10 +++- src/litkit/ingest/ingest.py | 21 +++++++++ src/litkit/ingest/publication_types.py | 30 ++++++++++++ src/litkit/retrieval/cli_commands.py | 25 +++++++++- src/litkit/retrieval/progressive.py | 64 ++++++++++++++++++++++---- tests/integration/test_batch_resume.py | 41 +++++++++++++++++ tests/test_ingest.py | 14 ++++++ tests/test_progressive_retrieval.py | 6 +++ 13 files changed, 240 insertions(+), 16 deletions(-) create mode 100644 src/litkit/ingest/publication_types.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 7385711..5c451f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ 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) + ## [0.4.0] - 2026-12-03 ### Added diff --git a/README.md b/README.md index 7ca2199..2136baa 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`) | @@ -116,6 +116,12 @@ per million chunks) and `search-papers --mode lexical` every paper; their defaul modes match exact tokens only 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. 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 108d284..1caf981 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -204,6 +204,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. @@ -274,6 +275,13 @@ 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() revised_shard_papers: set[int] = set() @@ -697,8 +705,17 @@ def _render(force: bool = False): ) 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, + types = meta.get("publication_types", ["other"]) + retracted = bool(meta.get("retracted")) + if extra := manifest_articles.get(m.name.removeprefix("./")): + from litkit.ingest.publication_types import classify + + types, marked = classify([*types, *extra.get("publication_types", [])]) + retracted = retracted or marked or extra.get("retracted") is True + cur.execute("UPDATE papers SET references_json=?, article_type=?, " + "publication_types=?, retracted=? WHERE id=?", ( + json.dumps(bibliography, ensure_ascii=False) if bibliography is not None else None, + meta.get("article_type"), json.dumps(types), int(retracted), pid, )) body = pack_body(meta, chunk_target_chars, chunk_min_chars, chunk_overlap) abstract_section = "Abstract" if ab else None diff --git a/src/litkit/cli.py b/src/litkit/cli.py index f058fa3..fd32041 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, @@ -1952,6 +1953,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 bd3c008..45bc5a2 100644 --- a/src/litkit/db/schema.py +++ b/src/litkit/db/schema.py @@ -43,7 +43,10 @@ in_index INTEGER DEFAULT 0, -- Paper vector input when multiple versions share an ID embedding_text TEXT, - references_json TEXT + references_json TEXT, + article_type TEXT, + publication_types TEXT, + retracted INTEGER ); CREATE TABLE IF NOT EXISTS chunks ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -88,7 +91,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", + "article_type", "publication_types", "retracted") } @@ -236,6 +240,9 @@ def ensure_paper_embedding_column(conn: sqlite3.Connection) -> None: _ADDED_COLUMNS = ( + ("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 052447a..bf3e479 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -227,6 +227,7 @@ def _merge_revised_papers(conn, shard, mapping, since): revisions = conn.execute(f""" SELECT m.main_pid, p.id, dest.doc_id, p.pmid, p.pmcid, p.title, p.abstract, {p_cols['source_path']}, {p_cols['doi']}, {p_cols['year']}, {p_cols['authors']}, {p_cols['journal']}, {p_cols['references_json']}, + {p_cols['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 @@ -250,6 +251,7 @@ def _merge_revised_papers(conn, shard, mapping, since): authors, journal, references_json, + article_type, publication_types, retracted, embedding_text, ) in revisions: pmid, pmcid = available_citation_ids(doc_id, pmid, pmcid, conn) @@ -259,12 +261,15 @@ 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, + article_type=COALESCE(:article_type, article_type), + publication_types=COALESCE(:types, publication_types), retracted=COALESCE(: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, + "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""" @@ -374,10 +379,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, 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['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 != '' diff --git a/src/litkit/ingest/ingest.py b/src/litkit/ingest/ingest.py index 0fcc6c4..51032c3 100644 --- a/src/litkit/ingest/ingest.py +++ b/src/litkit/ingest/ingest.py @@ -114,6 +114,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 +1137,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") == "retraction-in" 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: @@ -1225,6 +1238,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: diff --git a/src/litkit/ingest/publication_types.py b/src/litkit/ingest/publication_types.py new file mode 100644 index 0000000..81251ca --- /dev/null +++ b/src/litkit/ingest/publication_types.py @@ -0,0 +1,30 @@ +"""Publication categories shared by archive ingestion and retrieval filters.""" + +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 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 4cd75ba..6b2b53b 100644 --- a/src/litkit/retrieval/progressive.py +++ b/src/litkit/retrieval/progressive.py @@ -16,6 +16,8 @@ from __future__ import annotations +import json +import warnings import math import re import sqlite3 @@ -51,7 +53,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"} @@ -366,6 +368,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: @@ -384,7 +388,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 != "": @@ -392,11 +396,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: @@ -405,6 +414,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"], {} @@ -523,7 +555,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']}" ) @@ -554,6 +587,11 @@ def _disambiguate_file_handles(conn: sqlite3.Connection, rows: list[dict[str, An row["citation_handle"] = handle +def _type_fields(raw, types, retracted): + return {"article_type": raw, "types": json.loads(types) if types else [], + "retracted": bool(retracted) if retracted is not None else None} + + def _row_to_paper_dict( row: tuple[Any, ...], *, @@ -574,6 +612,7 @@ def _row_to_paper_dict( return { "paper_id": paper_id, "doc_id": doc_id, + **_type_fields(*row[11:14]), "pmcid": pmcid, "pmid": pmid, "doi": doi, @@ -998,8 +1037,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. @@ -1042,12 +1084,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 @@ -1180,7 +1222,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}) @@ -1225,6 +1268,7 @@ def _fetch_passages_by_ids( match_types.get(chunk_id, "exact") if match_types is not None else "exact" ), "paper_title": title, + **_type_fields(*row[15:18]), "pmid": pmid, "pmcid": pmcid, "doi": doi, @@ -1541,6 +1585,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. @@ -1592,11 +1639,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( @@ -1866,6 +1913,7 @@ def get_chunk_context( "year": year, "authors": authors, "journal": journal, + **_type_fields(*paper_row[11:14]), "source_path": paper["source_path"], "citation_handle": paper["citation_handle"], "target_ord": target_ord, diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 2a04ee6..715567b 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -1465,3 +1465,44 @@ def fail_cleanup(path): assert build.run()[2:] == (1, 2) assert not list(build.segments.glob(".litkit-batch-*")) 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" diff --git a/tests/test_ingest.py b/tests/test_ingest.py index 7fd7e10..3bf2e9e 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,15 @@ 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) diff --git a/tests/test_progressive_retrieval.py b/tests/test_progressive_retrieval.py index db5b750..e4f8c3a 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) == [] From f4d39de83ebba9caa665e80923a30bea3617260a Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Fri, 4 Dec 2026 14:36:57 -0700 Subject: [PATCH 2/6] Refresh publication status without rebuilding vectors and carry it through cited results Signed-off-by: Bill Hlavacek --- README.md | 4 +- src/litkit/build/ingest_loop.py | 91 +++++++++++++++++++---- src/litkit/build/publication.py | 9 +++ src/litkit/db/schema.py | 4 +- src/litkit/db/sharding.py | 26 +++++-- src/litkit/formatting/answers.py | 4 + src/litkit/ingest/ingest.py | 34 +++++---- src/litkit/ingest/publication_types.py | 27 +++++++ src/litkit/llm/qa.py | 2 + src/litkit/retrieval/progressive.py | 13 +--- src/litkit/retrieval/stages.py | 4 +- tests/integration/test_batch_resume.py | 56 ++++++++++++++ tests/integration/test_build_and_query.py | 7 +- tests/test_formatting.py | 8 ++ tests/test_ingest.py | 23 ++++++ 15 files changed, 262 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index 2136baa..6f12d12 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,9 @@ 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. Rebuild existing +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 1caf981..ce19a39 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -32,6 +32,7 @@ parallel_iter_tar_articles, parse_xml_fileobj, ) +from litkit.ingest.publication_types import publication_fields from litkit.ingest import is_uncompressed_tar from litkit.index import ( make_id_selector, @@ -52,7 +53,7 @@ from litkit.db.handoff import completed_checkpoint, merged_checkpoints, readable_database from litkit.db.queries import available_citation_ids 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 ( @@ -286,11 +287,58 @@ def process_tar_files( replaced_chunks: set[int] = set() revised_shard_papers: set[int] = set() + pending_refreshes = 0 + + def refresh_known_member(path, fields): + """Apply a sidecar change without rewriting text, chunk IDs or vectors.""" + nonlocal pending_refreshes, has_refresh_table + 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_path=f.path" + ) + local = cur.execute(select, (path,)).fetchone() + remote = merged.execute(select, (path,)).fetchone() if merged_has_types else None + if local is None and remote is None: + return + # 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 sequence>?", (path, 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 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, " + "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, *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 @@ -414,6 +462,7 @@ def stage_indexes(paper_dir, chunk_dir): buf.clear() replaced_papers.clear() replaced_chunks.clear() + pending_refreshes = 0 revised_shard_papers.clear() def process_tar(tpath: Path) -> None: @@ -507,13 +556,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, publication_fields(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), @@ -532,6 +586,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, publication_fields(meta, manifest_article)) + if pending_refreshes >= ckpt_every: + flush_batch(str(tpath), processed_count + 1) processed_count += 1 continue @@ -705,18 +763,13 @@ def _render(force: bool = False): ) bibliography = meta.get("references") - types = meta.get("publication_types", ["other"]) - retracted = bool(meta.get("retracted")) - if extra := manifest_articles.get(m.name.removeprefix("./")): - from litkit.ingest.publication_types import classify - - types, marked = classify([*types, *extra.get("publication_types", [])]) - retracted = retracted or marked or extra.get("retracted") is True - cur.execute("UPDATE papers SET references_json=?, article_type=?, " + cur.execute("UPDATE papers SET references_json=?, publication_path=?, article_type=?, " "publication_types=?, retracted=? WHERE id=?", ( json.dumps(bibliography, ensure_ascii=False) if bibliography is not None else None, - meta.get("article_type"), json.dumps(types), int(retracted), pid, + f, *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", []))) @@ -797,7 +850,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) @@ -810,6 +863,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()) ensure_in_index_columns(conn) ensure_paper_embedding_column(conn) paper_output_dir = ( @@ -834,10 +892,11 @@ 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_path" in table_columns(main_db, "papers") 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 4bb741c..72e15e1 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/db/schema.py b/src/litkit/db/schema.py index 4cfcdec..d09b045 100644 --- a/src/litkit/db/schema.py +++ b/src/litkit/db/schema.py @@ -45,6 +45,7 @@ -- Paper vector input when multiple versions share an ID embedding_text TEXT, references_json TEXT, + publication_path TEXT, article_type TEXT, publication_types TEXT, retracted INTEGER @@ -93,7 +94,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", - "article_type", "publication_types", "retracted") + "publication_path", "article_type", "publication_types", "retracted") } @@ -241,6 +242,7 @@ def ensure_paper_embedding_column(conn: sqlite3.Connection) -> None: _ADDED_COLUMNS = ( + ("papers", "publication_path", "TEXT"), ("papers", "article_type", "TEXT"), ("papers", "publication_types", "TEXT"), ("papers", "retracted", "INTEGER"), diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index bf3e479..3e3f633 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -227,7 +227,7 @@ def _merge_revised_papers(conn, shard, mapping, since): revisions = conn.execute(f""" SELECT m.main_pid, p.id, dest.doc_id, p.pmid, p.pmcid, p.title, p.abstract, {p_cols['source_path']}, {p_cols['doi']}, {p_cols['year']}, {p_cols['authors']}, {p_cols['journal']}, {p_cols['references_json']}, - {p_cols['article_type']}, {p_cols['publication_types']}, {p_cols['retracted']}, + {p_cols['publication_path']}, {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 @@ -251,7 +251,7 @@ def _merge_revised_papers(conn, shard, mapping, since): authors, journal, references_json, - article_type, publication_types, retracted, + publication_path, article_type, publication_types, retracted, embedding_text, ) in revisions: pmid, pmcid = available_citation_ids(doc_id, pmid, pmcid, conn) @@ -261,7 +261,8 @@ 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, - article_type=COALESCE(:article_type, article_type), + publication_path=COALESCE(:publication_path, publication_path), + article_type=CASE WHEN :types IS NULL THEN article_type ELSE :article_type END, publication_types=COALESCE(:types, publication_types), retracted=COALESCE(:retracted, retracted), doi=COALESCE(NULLIF(:doi,''), doi), year=COALESCE(:year, year), @@ -269,7 +270,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, - "article_type": article_type, "types": publication_types, "retracted": retracted, + "publication_path": publication_path, "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""" @@ -379,11 +380,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, article_type, publication_types, retracted, in_index + doc_id, pmid, pmcid, doi, year, authors, journal, title, abstract, source_path, embedding_text, references_json, publication_path, 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['article_type']}, {p_cols['publication_types']}, {p_cols['retracted']}, 0 + {p_cols['publication_path']}, {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 != '' @@ -441,6 +442,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_path=r.path 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 51032c3..c19773a 100644 --- a/src/litkit/ingest/ingest.py +++ b/src/litkit/ingest/ingest.py @@ -1143,7 +1143,7 @@ def _walk_root(node: etree._Element) -> None: 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") == "retraction-in" for node in related): + 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) @@ -1172,40 +1172,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 = "" @@ -1240,10 +1244,10 @@ def parse_pubmed(tree: etree._ElementTree) -> ArticleMeta: meta["year"] = year from litkit.ingest.publication_types import classify - types = xp('//*[local-name()="MedlineCitation"]/*[local-name()="Article"]' + 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"]'): + if xp('.//*[local-name()="CommentsCorrections"][@RefType="RetractionIn"]'): labels.append("retracted") meta["publication_types"], meta["retracted"] = classify(labels) if authors_list: diff --git a/src/litkit/ingest/publication_types.py b/src/litkit/ingest/publication_types.py index 81251ca..012f826 100644 --- a/src/litkit/ingest/publication_types.py +++ b/src/litkit/ingest/publication_types.py @@ -1,5 +1,6 @@ """Publication categories shared by archive ingestion and retrieval filters.""" +import json import re PUBLICATION_TYPES = frozenset({ @@ -28,3 +29,29 @@ def classify(labels): if category in PUBLICATION_TYPES and category != "other": types.add(category) return sorted(types or {"other"}), retracted + + +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/progressive.py b/src/litkit/retrieval/progressive.py index 6b2b53b..3e71457 100644 --- a/src/litkit/retrieval/progressive.py +++ b/src/litkit/retrieval/progressive.py @@ -16,7 +16,6 @@ from __future__ import annotations -import json import warnings import math import re @@ -44,6 +43,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: @@ -587,11 +587,6 @@ def _disambiguate_file_handles(conn: sqlite3.Connection, rows: list[dict[str, An row["citation_handle"] = handle -def _type_fields(raw, types, retracted): - return {"article_type": raw, "types": json.loads(types) if types else [], - "retracted": bool(retracted) if retracted is not None else None} - - def _row_to_paper_dict( row: tuple[Any, ...], *, @@ -612,7 +607,7 @@ def _row_to_paper_dict( return { "paper_id": paper_id, "doc_id": doc_id, - **_type_fields(*row[11:14]), + **result_fields(*row[11:14]), "pmcid": pmcid, "pmid": pmid, "doi": doi, @@ -1268,7 +1263,7 @@ def _fetch_passages_by_ids( match_types.get(chunk_id, "exact") if match_types is not None else "exact" ), "paper_title": title, - **_type_fields(*row[15:18]), + **result_fields(*row[15:18]), "pmid": pmid, "pmcid": pmcid, "doi": doi, @@ -1913,7 +1908,7 @@ def get_chunk_context( "year": year, "authors": authors, "journal": journal, - **_type_fields(*paper_row[11:14]), + **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 715567b..7ae5546 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -1506,3 +1506,59 @@ def test_publication_types_update_across_archives(tmp_path, producer): 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 diff --git a/tests/integration/test_build_and_query.py b/tests/integration/test_build_and_query.py index a09a8be..a5d14b9 100644 --- a/tests/integration/test_build_and_query.py +++ b/tests/integration/test_build_and_query.py @@ -1763,7 +1763,7 @@ def test_progressive_retrieval_cli_json_and_payload_bounds(tmp_path, monkeypatch tars = tmp_path / "tars" tars.mkdir() kras_xml = """ -
+
Nature @@ -1775,6 +1775,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.

@@ -1927,3 +1928,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 3bf2e9e..5c277da 100644 --- a/tests/test_ingest.py +++ b/tests/test_ingest.py @@ -951,3 +951,26 @@ def test_pubmed_publication_types_distinguish_notice_from_target(): "
") 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 From 20b8e3cab65c921b869d317fa88642ed70bdc145 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Fri, 4 Dec 2026 14:39:17 -0700 Subject: [PATCH 3/6] Bind metadata refreshes to the archive revision that supplied the paper Signed-off-by: Bill Hlavacek --- src/litkit/build/ingest_loop.py | 30 +++++++++--------- src/litkit/db/schema.py | 6 ++-- src/litkit/db/sharding.py | 14 ++++----- src/litkit/ingest/publication_types.py | 8 +++++ tests/integration/test_batch_resume.py | 42 ++++++++++++++++++++++++++ 5 files changed, 76 insertions(+), 24 deletions(-) diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index ce19a39..3a1b2d2 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -32,7 +32,7 @@ parallel_iter_tar_articles, parse_xml_fileobj, ) -from litkit.ingest.publication_types import publication_fields +from litkit.ingest.publication_types import publication_fields, publication_source from litkit.ingest import is_uncompressed_tar from litkit.index import ( make_id_selector, @@ -289,17 +289,19 @@ def process_tar_files( pending_refreshes = 0 - def refresh_known_member(path, fields): + 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, meta) 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_path=f.path" + "FROM files f JOIN papers p ON p.id=f.paper_id WHERE f.path=? AND p.publication_source=?" ) - local = cur.execute(select, (path,)).fetchone() - remote = merged.execute(select, (path,)).fetchone() if merged_has_types else None + 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. @@ -307,7 +309,7 @@ def refresh_known_member(path, fields): if embed_producer and has_refresh_table: queued = cur.execute( "SELECT article_type, types, retracted FROM publication_refreshes " - "WHERE path=? AND sequence>?", (path, merged_sequence), + "WHERE path=? AND source=? AND sequence>?", (path, source, merged_sequence), ).fetchone() if queued is not None: if queued == fields: @@ -321,12 +323,12 @@ def refresh_known_member(path, fields): (*fields, local[0])) if embed_producer: if not has_refresh_table: - cur.execute("CREATE TABLE publication_refreshes (path TEXT PRIMARY KEY, " + 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, *fields, publication.checkpoint.get("segment_sequence", 0) + 1)) + 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: @@ -560,7 +562,7 @@ def _render(force: bool = False): 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, publication_fields(meta, manifest_article)) + refresh_known_member(f, m, meta, manifest_article) if pending_refreshes >= ckpt_every: flush_batch(str(tpath), start_persisted) skipped += 1 @@ -587,7 +589,7 @@ def _render(force: bool = False): 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, publication_fields(meta, manifest_article)) + refresh_known_member(f, m, meta, manifest_article) if pending_refreshes >= ckpt_every: flush_batch(str(tpath), processed_count + 1) processed_count += 1 @@ -763,10 +765,10 @@ def _render(force: bool = False): ) bibliography = meta.get("references") - cur.execute("UPDATE papers SET references_json=?, publication_path=?, article_type=?, " + 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, - f, *publication_fields(meta, manifest_article), pid, + publication_source(f, m, meta), *publication_fields(meta, manifest_article), pid, )) if has_refresh_table: cur.execute("DELETE FROM publication_refreshes WHERE path=?", (f,)) @@ -892,7 +894,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_types = "publication_path" in table_columns(main_db, "papers") + merged_has_types = "publication_source" in table_columns(main_db, "papers") producer_id = chunk_seg_writer.shard_id receipt = merged_checkpoints(main_db, producer_id).get(producer_id) merged_sequence = (receipt or {}).get("segment_sequence", 0) diff --git a/src/litkit/db/schema.py b/src/litkit/db/schema.py index d09b045..97743a7 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, - publication_path TEXT, + publication_source BLOB, article_type TEXT, publication_types TEXT, retracted INTEGER @@ -94,7 +94,7 @@ def optional_paper_columns( return { name: (f"{prefix}{name}" if name in cols else "NULL") for name in ("doc_id", "source_path", "doi", "year", "authors", "journal", "references_json", - "publication_path", "article_type", "publication_types", "retracted") + "publication_source", "article_type", "publication_types", "retracted") } @@ -242,7 +242,7 @@ def ensure_paper_embedding_column(conn: sqlite3.Connection) -> None: _ADDED_COLUMNS = ( - ("papers", "publication_path", "TEXT"), + ("papers", "publication_source", "BLOB"), ("papers", "article_type", "TEXT"), ("papers", "publication_types", "TEXT"), ("papers", "retracted", "INTEGER"), diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index 3e3f633..c4cbdb6 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -227,7 +227,7 @@ def _merge_revised_papers(conn, shard, mapping, since): revisions = conn.execute(f""" SELECT m.main_pid, p.id, dest.doc_id, p.pmid, p.pmcid, p.title, p.abstract, {p_cols['source_path']}, {p_cols['doi']}, {p_cols['year']}, {p_cols['authors']}, {p_cols['journal']}, {p_cols['references_json']}, - {p_cols['publication_path']}, {p_cols['article_type']}, {p_cols['publication_types']}, {p_cols['retracted']}, + {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 @@ -251,7 +251,7 @@ def _merge_revised_papers(conn, shard, mapping, since): authors, journal, references_json, - publication_path, article_type, publication_types, retracted, + publication_source, article_type, publication_types, retracted, embedding_text, ) in revisions: pmid, pmcid = available_citation_ids(doc_id, pmid, pmcid, conn) @@ -261,7 +261,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, - publication_path=COALESCE(:publication_path, publication_path), + publication_source=COALESCE(:publication_source, publication_source), article_type=CASE WHEN :types IS NULL THEN article_type ELSE :article_type END, publication_types=COALESCE(:types, publication_types), retracted=COALESCE(:retracted, retracted), doi=COALESCE(NULLIF(:doi,''), doi), @@ -270,7 +270,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, - "publication_path": publication_path, "article_type": article_type, "types": publication_types, "retracted": retracted, + "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""" @@ -380,11 +380,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, publication_path, article_type, publication_types, retracted, 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']}, - {p_cols['publication_path']}, {p_cols['article_type']}, {p_cols['publication_types']}, {p_cols['retracted']}, 0 + {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 != '' @@ -453,7 +453,7 @@ def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge, to_record): 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_path=r.path AND r.sequence>? + WHERE p.id=f.paper_id AND p.publication_source=r.source AND r.sequence>? """, (previous.get("segment_sequence", 0),)) # 3) BULK MERGE FILES diff --git a/src/litkit/ingest/publication_types.py b/src/litkit/ingest/publication_types.py index 012f826..61c8ace 100644 --- a/src/litkit/ingest/publication_types.py +++ b/src/litkit/ingest/publication_types.py @@ -1,5 +1,6 @@ """Publication categories shared by archive ingestion and retrieval filters.""" +import hashlib import json import re @@ -31,6 +32,13 @@ def classify(labels): return sorted(types or {"other"}), retracted +def publication_source(path, member, meta): + """Identify the exact member revision that supplied a paper's publication metadata.""" + identity = [path, member.size, float(member.mtime), meta.get("pmid"), meta.get("pmcid"), + meta["title"], meta["abstract"]] + return hashlib.sha256(json.dumps(identity, ensure_ascii=False).encode("utf-8")).digest() + + def publication_fields(meta, manifest_article): """Return the stored raw type, normalized types and retraction flag.""" types = meta.get("publication_types", ["other"]) diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 7ae5546..2c43a3d 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -1562,3 +1562,45 @@ def test_unconsumed_manifest_change_can_be_reversed_on_a_detached_producer(tmp_p 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 + + +def test_queued_manifest_refresh_cannot_replace_a_newer_archive_revision(tmp_path): + from litkit.retrieval import get_paper + + archive = tmp_path / "changed.tar" + member = "valid/paper.xml" + write_tar(archive, {member: jats(pmcid="PMC41", title="Report A")}) + 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() + merge_shard_databases(main, delete_after_merge=True, segment_dir=producer.segments) + producer.ingest_merged(main) + sidecar = tmp_path / "workspace.json" + sidecar.write_text('{"articles":{"valid/paper.xml":{"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: jats(pmcid="PMC41", title="Report B")}) + writer.run(conn=main, rebuild=True) + merge_shard_databases(main, delete_after_merge=True, segment_dir=producer.segments) + paper = get_paper("PMC41", conn=main) + assert (paper["title"], paper["retracted"]) == ("Report B", False) From bb48353365ca618f5d8ff1dcc65bed77de6be84f Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Fri, 4 Dec 2026 14:41:18 -0700 Subject: [PATCH 4/6] Keep metadata-only publisher changes atomic on autocommit connections Signed-off-by: Bill Hlavacek --- src/litkit/build/ingest_loop.py | 2 ++ tests/integration/test_batch_resume.py | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index 3a1b2d2..f00c16f 100644 --- a/src/litkit/build/ingest_loop.py +++ b/src/litkit/build/ingest_loop.py @@ -318,6 +318,8 @@ def refresh_known_member(path, member, meta, manifest_article): 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])) diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 2c43a3d..4892b3a 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -1604,3 +1604,27 @@ def test_queued_manifest_refresh_cannot_replace_a_newer_archive_revision(tmp_pat merge_shard_databases(main, delete_after_merge=True, segment_dir=producer.segments) paper = get_paper("PMC41", conn=main) assert (paper["title"], paper["retracted"]) == ("Report B", False) + + +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 From 19f9dec1250f2c509f7192e6a3581f827d92d7b8 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Fri, 4 Dec 2026 14:43:43 -0700 Subject: [PATCH 5/6] Bind queued publication status to the full archive member digest Signed-off-by: Bill Hlavacek --- src/litkit/build/ingest_loop.py | 33 +++++++++++++++++++++----- src/litkit/ingest/ingest.py | 8 ++++--- src/litkit/ingest/publication_types.py | 8 +++---- tests/integration/test_batch_resume.py | 25 +++++++++++++------ 4 files changed, 53 insertions(+), 21 deletions(-) diff --git a/src/litkit/build/ingest_loop.py b/src/litkit/build/ingest_loop.py index f00c16f..21591be 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 @@ -74,13 +75,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. @@ -109,18 +129,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: @@ -292,7 +313,7 @@ def process_tar_files( 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, meta) + 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=?" @@ -770,7 +791,7 @@ def _render(force: bool = False): 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, meta), *publication_fields(meta, manifest_article), pid, + 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,)) diff --git a/src/litkit/ingest/ingest.py b/src/litkit/ingest/ingest.py index c19773a..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 @@ -1599,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( @@ -1678,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 index 61c8ace..5f1bea2 100644 --- a/src/litkit/ingest/publication_types.py +++ b/src/litkit/ingest/publication_types.py @@ -32,11 +32,9 @@ def classify(labels): return sorted(types or {"other"}), retracted -def publication_source(path, member, meta): - """Identify the exact member revision that supplied a paper's publication metadata.""" - identity = [path, member.size, float(member.mtime), meta.get("pmid"), meta.get("pmcid"), - meta["title"], meta["abstract"]] - return hashlib.sha256(json.dumps(identity, ensure_ascii=False).encode("utf-8")).digest() +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): diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 4892b3a..7077f57 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -1581,29 +1581,40 @@ def test_manifest_refresh_cannot_retract_a_different_paper_at_a_reused_path(tmp_ assert get_paper("PMC41", conn=conn)["retracted"] is False -def test_queued_manifest_refresh_cannot_replace_a_newer_archive_revision(tmp_path): +@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" - write_tar(archive, {member: jats(pmcid="PMC41", title="Report A")}) + 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() + 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" - sidecar.write_text('{"articles":{"valid/paper.xml":{"retracted":true}}}') + # 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: jats(pmcid="PMC41", title="Report B")}) - writer.run(conn=main, rebuild=True) + 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["title"], paper["retracted"]) == ("Report B", False) + assert (paper["types"], paper["retracted"]) == (["research"], False) def test_failed_manifest_publication_rolls_back_an_autocommit_connection(tmp_path, monkeypatch): From a537395e4134bf9028e9f426d7df4f022dec37b7 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Fri, 4 Dec 2026 14:56:00 -0700 Subject: [PATCH 6/6] Keep publication status bound to the revision supplying the text Signed-off-by: Bill Hlavacek --- src/litkit/db/sharding.py | 7 +++--- tests/integration/test_batch_resume.py | 31 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/litkit/db/sharding.py b/src/litkit/db/sharding.py index ed581d6..da00798 100644 --- a/src/litkit/db/sharding.py +++ b/src/litkit/db/sharding.py @@ -277,14 +277,15 @@ 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=COALESCE(:publication_source, publication_source), - article_type=CASE WHEN :types IS NULL THEN article_type ELSE :article_type END, - publication_types=COALESCE(:types, publication_types), retracted=COALESCE(:retracted, retracted), + 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), diff --git a/tests/integration/test_batch_resume.py b/tests/integration/test_batch_resume.py index 084f1fc..f266e1f 100644 --- a/tests/integration/test_batch_resume.py +++ b/tests/integration/test_batch_resume.py @@ -1618,6 +1618,37 @@ def test_queued_manifest_refresh_cannot_replace_a_newer_archive_revision(tmp_pat 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