diff --git a/.linkml-reference-validator.yaml b/.linkml-reference-validator.yaml index 828af5d8d33..714e0d68fbe 100644 --- a/.linkml-reference-validator.yaml +++ b/.linkml-reference-validator.yaml @@ -1,3 +1,5 @@ cache_dir: publications download_supplementary_files: true email: cjmungall@lbl.gov +# Committed, reviewed cache: never re-fetch an entry for a missing/old extractor stamp. +trust_cached_entries: true diff --git a/conf/reference_validator_config.yaml b/conf/reference_validator_config.yaml index 970b2678c46..e4e76e7a1dc 100644 --- a/conf/reference_validator_config.yaml +++ b/conf/reference_validator_config.yaml @@ -11,6 +11,14 @@ unknown_prefix_severity: WARNING # cache_dir: directory containing cached publication text files (PMID_12345.md) cache_dir: publications +# trust_cached_entries: publications/ is a committed, reviewed cache. Since +# linkml-reference-validator 0.3.0, an entry without a current +# extractor_version stamp (nearly all of ours) is otherwise treated as stale +# and re-fetched and rewritten on every validation run, which can shorten a +# body or replace text a curator quoted. Refresh entries deliberately with the +# publication ETL instead. +trust_cached_entries: true + # reference_base_dir: base directory for resolving file: references reference_base_dir: genes diff --git a/conf/reference_validator_warm_config.yaml b/conf/reference_validator_warm_config.yaml new file mode 100644 index 00000000000..b294fea61f6 --- /dev/null +++ b/conf/reference_validator_warm_config.yaml @@ -0,0 +1,47 @@ +# Configuration for warming the committed publications/ cache through +# linkml-reference-validator. +# +# Deliberately do NOT set trust_cached_entries here. The warm sweep exists to +# revisit abstract-only/stale cache entries and upgrade them when full text has +# become available; the normal validation config trusts the cache to avoid this +# network/refetch path during CI. +unknown_prefix_severity: WARNING + +# cache_dir: directory containing cached publication text files (PMID_12345.md) +cache_dir: publications + +# reference_base_dir: base directory for resolving file: references +reference_base_dir: genes + +# skip_prefixes: reference prefixes the validator cannot fetch and should +# silently skip. These are non-literature identifiers where snippet +# validation does not apply. +skip_prefixes: + - GO_REF + - GO + - Reactome + - UniProt + - UniProtKB + - PDB + - EC + - TEMP + - ISBN + - RHEA + - file + - curator_inference + - ComplexPortal + - HPA + - PROSITE + - CHEBI + - PMC + - CONTACT_INFO + - inference + - InterPro + - thesis + - unindexed + +# literal_bracket_patterns: regex patterns for bracketed text that should +# NOT be treated as citation markers (e.g., [2Fe-2S], [MEK], [Ca2+]) +literal_bracket_patterns: + - "[^a-zA-Z\\s]" # keep brackets with non-alpha chars: [2Fe-2S], [Ca2+] + - "^[A-Z]{2,5}$" # keep short uppercase abbreviations: [MEK], [ATP] diff --git a/docs/licenses/linkml-reference-validator-Apache-2.0.txt b/docs/licenses/linkml-reference-validator-Apache-2.0.txt deleted file mode 100644 index d44cd79e2ba..00000000000 --- a/docs/licenses/linkml-reference-validator-Apache-2.0.txt +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2025 Chris Mungall - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/pyproject.toml b/pyproject.toml index 5781b19e55e..7f01dfe0610 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -46,9 +46,9 @@ dependencies = [ "rapidfuzz>=3.14.3", "scipy>=1.16.1", "linkml-data-qc>=0.1.0", - # <0.3: publication_warm.py calls LRV's private ReferenceFetcher._materialize; - # lift the bound once a public API lands (tracked in issue #2789). - "linkml-reference-validator>=0.2.1,<0.3", + # publication_warm.py still calls LRV's private ReferenceFetcher._materialize; + # keep a contract test around that call shape until issue #2789 lands. + "linkml-reference-validator>=0.3.0,<0.4", "linkml-term-validator>=0.4.5", "gocam>=0.11.0", "pyhmmer>=0.12.1", diff --git a/scripts/extract_supporting_text_fixes.py b/scripts/extract_supporting_text_fixes.py index 7e41bdefc83..72b1e634bba 100644 --- a/scripts/extract_supporting_text_fixes.py +++ b/scripts/extract_supporting_text_fixes.py @@ -15,16 +15,13 @@ from linkml_reference_validator.validation.supporting_text_validator import SupportingTextValidator from linkml_reference_validator.models import ReferenceValidationConfig -from ai_gene_review.validation.reference_cache_compat import ( - install_reference_cache_compatibility, -) config = ReferenceValidationConfig( cache_dir="publications", + trust_cached_entries=True, literal_bracket_patterns=[r"[^a-zA-Z\s]"], ) -install_reference_cache_compatibility() validator = SupportingTextValidator(config) SKIP_PREFIXES = { diff --git a/scripts/mark_full_text_unavailable.py b/scripts/mark_full_text_unavailable.py index 03179629480..5f67476febf 100644 --- a/scripts/mark_full_text_unavailable.py +++ b/scripts/mark_full_text_unavailable.py @@ -22,9 +22,6 @@ SupportingTextValidator, ) from linkml_reference_validator.models import ReferenceValidationConfig -from ai_gene_review.validation.reference_cache_compat import ( - install_reference_cache_compatibility, -) yaml_rt = YAML() yaml_rt.preserve_quotes = True @@ -97,9 +94,9 @@ def check_full_text(ref_id: str) -> bool | None: # Set up LRV to check if supporting_text passes strict validation config = ReferenceValidationConfig( cache_dir="publications", + trust_cached_entries=True, literal_bracket_patterns=[r"[^a-zA-Z\s]", r"^[A-Z]{2,5}$"], ) - install_reference_cache_compatibility() lrv = SupportingTextValidator(config) total_marked = 0 diff --git a/scripts/run_reference_validator.sh b/scripts/run_reference_validator.sh index 12cfdef86ca..12ce7650e41 100755 --- a/scripts/run_reference_validator.sh +++ b/scripts/run_reference_validator.sh @@ -8,10 +8,10 @@ # so we pre-process the YAML to remove supporting_text from those entries. # # Accepts one OR many data files. With many files it strips them in a single -# pass and makes a single `validate data F1 F2 ...` call through the version-gated -# ai_gene_review.validation.reference_cli compatibility entry point (the validator builds/parses the schema once), which is dramatically -# faster than one process per file. Requires linkml-reference-validator >= 0.2.1 -# (multi-file `validate data`). +# pass and makes a single `validate data F1 F2 ...` call (the validator +# builds/parses the schema once), which is dramatically faster than one process +# per file. Requires linkml-reference-validator >= 0.3.0 (trusted-cache +# `validate data`). # # Usage: scripts/run_reference_validator.sh validate data F1 [F2 ...] --schema S --target-class C --config CFG @@ -19,7 +19,7 @@ set -euo pipefail run_lrv() { set +e - output="$(uv run python -m ai_gene_review.validation.reference_cli "$@" 2>&1)" + output="$(uv run linkml-reference-validator "$@" 2>&1)" exit_code=$? set -e diff --git a/scripts/warm_reference_cache.py b/scripts/warm_reference_cache.py index 212382980f1..e5a607bf2c9 100644 --- a/scripts/warm_reference_cache.py +++ b/scripts/warm_reference_cache.py @@ -9,6 +9,10 @@ corpus with full-text fetching on (the validator's default) populates the cache so subsequent runs are cache-bound. +Unlike normal validation, this sweep intentionally does not trust cached entries: +its job is to re-fetch abstract-only or stale records and upgrade them when full +text has become available. + This processes the corpus in chunks for progress/resumability and ignores validation pass/fail — the goal here is only to populate the cache. References are read from the structured YAML fields (not a regex over prose), so no malformed @@ -25,7 +29,7 @@ import time SCHEMA = "src/ai_gene_review/schema/gene_review.yaml" -CONFIG = "conf/reference_validator_config.yaml" +CONFIG = "conf/reference_validator_warm_config.yaml" CHUNK = 100 @@ -43,8 +47,7 @@ def main() -> int: # expected and irrelevant here; we only want the references fetched into the cache. subprocess.run( [ - "uv", "run", "python", "-m", - "ai_gene_review.validation.reference_cli", "validate", "data", *batch, + "uv", "run", "linkml-reference-validator", "validate", "data", *batch, "--schema", SCHEMA, "--target-class", "GeneReview", "--config", CONFIG, ], stdout=subprocess.DEVNULL, diff --git a/src/ai_gene_review/etl/gene.py b/src/ai_gene_review/etl/gene.py index 1404eb57161..3ad17bb6469 100644 --- a/src/ai_gene_review/etl/gene.py +++ b/src/ai_gene_review/etl/gene.py @@ -623,7 +623,10 @@ def fetch_gene_data( supporting_entities_backfilled, ) = ( validator.seed_missing_annotations( - yaml_file, goa_file, fetch_titles=fetch_titles + yaml_file, + goa_file, + fetch_titles=fetch_titles, + publications_dir=base_path / "publications", ) ) result["annotations_added"] = added_count @@ -1807,7 +1810,10 @@ def fetch_gene_data_ncRNA( supporting_entities_backfilled, ) = ( validator.seed_missing_annotations( - yaml_file, goa_file, fetch_titles=True + yaml_file, + goa_file, + fetch_titles=True, + publications_dir=base_path / "publications", ) ) result["annotations_added"] = added_count diff --git a/src/ai_gene_review/etl/publication_warm.py b/src/ai_gene_review/etl/publication_warm.py index f7649022cc9..ba9589e3997 100644 --- a/src/ai_gene_review/etl/publication_warm.py +++ b/src/ai_gene_review/etl/publication_warm.py @@ -1,6 +1,6 @@ """Warm the publications cache with full text via linkml-reference-validator. -This module drives the linkml-reference-validator (>= 0.2.1) full-text provider +This module drives the linkml-reference-validator (>= 0.3.0) full-text provider chain — PMC, Europe PMC preprints, Unpaywall, OpenAlex by default — over the repo's own ``publications/PMID_*.md`` cache to upgrade abstract-only records to full text. It is modeled on the monarch-initiative/dismech @@ -394,8 +394,8 @@ def warm_publication( # routine `ReferenceFetcher.fetch` uses internally; it is not yet public # API — public-API request tracked in # https://github.com/ai4curation/ai-gene-review/issues/2789 (to be - # transferred to linkml-reference-validator); pyproject bounds LRV <0.3 - # until it lands. + # transferred to linkml-reference-validator). Keep a contract test + # around the tuple shape while this remains private. try: # external system boundary: symmetric with the locate guard above, # so one failed download still lets later providers try this record text, fmt, _pdf_bytes, error = fetcher._materialize(location) diff --git a/src/ai_gene_review/validation/goa_validator.py b/src/ai_gene_review/validation/goa_validator.py index b0d9787910a..6b01a7b27dd 100644 --- a/src/ai_gene_review/validation/goa_validator.py +++ b/src/ai_gene_review/validation/goa_validator.py @@ -633,6 +633,7 @@ def seed_missing_annotations( goa_file: Optional[Path] = None, output_file: Optional[Path] = None, fetch_titles: bool = False, + publications_dir: Optional[Path] = None, ) -> Tuple[int, Path, int, int, int]: """Seed missing annotations from GOA file into YAML. @@ -645,6 +646,8 @@ def seed_missing_annotations( goa_file: Path to GOA file (if None, derives from yaml_file path) output_file: Output path (if None, overwrites input file) fetch_titles: If True, fetch actual titles from PubMed (may be slow) + publications_dir: Publication cache read and written when fetching + titles (default: ``publications`` relative to the working directory) Returns: Tuple of (annotations added, output file path, references added, @@ -894,8 +897,11 @@ def seeding_key(ann: GOAAnnotation) -> tuple: if pmid.startswith("PMID:"): pmid_num = pmid[5:] # Remove 'PMID:' prefix try: - # Use publications directory for cache - cache_dir = Path("publications") + cache_dir = ( + publications_dir + if publications_dir is not None + else Path("publications") + ) # First try to get just the title from cache (fast) cached_title = get_cached_title(pmid_num, cache_dir) diff --git a/src/ai_gene_review/validation/reference_cache_compat.py b/src/ai_gene_review/validation/reference_cache_compat.py deleted file mode 100644 index af65555af55..00000000000 --- a/src/ai_gene_review/validation/reference_cache_compat.py +++ /dev/null @@ -1,106 +0,0 @@ -"""Backport the cache delimiter fix for the pinned LRV 0.2.1 release. - -The loader below is adapted from linkml-reference-validator 0.2.1, -Copyright 2025 Chris Mungall, Apache-2.0 (see -``docs/licenses/linkml-reference-validator-Apache-2.0.txt``). -Delimiter detection and malformed-metadata handling are guarded; valid metadata, -extraction and validation retain upstream behavior. Upstream fixed this in commit -https://github.com/linkml/linkml-reference-validator/commit/dd9940dacd34b64a83bc1143414ca9ee4f32f3ee -but that unreleased branch also changes cache refresh semantics. - -The dependency has no fetcher-factory argument on its validator or CLI. Repo -validation entry points and reference-cache utilities explicitly install this -version-limited method backport. No installed file or cache is rewritten. Remove it when the pinned -release contains the upstream fix. -""" - -from importlib.metadata import version -import logging -import re -from typing import Optional - -from ruamel.yaml import YAML -from linkml_reference_validator.etl.reference_fetcher import ReferenceFetcher -from linkml_reference_validator.models import ReferenceContent - -logger = logging.getLogger(__name__) - - -def _load_markdown_format_021( - self, content_text: str, reference_id: str -) -> Optional[ReferenceContent]: - """Load reference from markdown format with YAML frontmatter. - - Args: - content_text: File contents - reference_id: Reference identifier - - Returns: - ReferenceContent if successful, None otherwise - """ - parts = re.split(r"(?m)^---[\t ]*\r?$", content_text, maxsplit=2) - if len(parts) < 3: - logger.warning(f"Invalid markdown format for {reference_id}") - return None - - yaml_parser = YAML(typ="safe") - frontmatter = yaml_parser.load(parts[1]) - if not isinstance(frontmatter, dict): - logger.warning("Invalid markdown frontmatter mapping for %s", reference_id) - return None - body = parts[2].strip() - - content = self._extract_content_from_markdown(body) - - authors = self._as_optional_list(frontmatter.get("authors")) - keywords = self._as_optional_list(frontmatter.get("keywords")) - publication_types = self._as_optional_list(frontmatter.get("publication_types")) - - # Parse supplementary files - supplementary_files = self._parse_supplementary_files( - frontmatter.get("supplementary_files") - ) - - metadata: dict = {} - if "extra_fields_captured" in frontmatter: - metadata["extra_fields_captured"] = frontmatter["extra_fields_captured"] - - return ReferenceContent( - reference_id=frontmatter.get("reference_id", reference_id), - title=frontmatter.get("title"), - content=content, - content_type=frontmatter.get("content_type", "unknown"), - authors=authors, - journal=frontmatter.get("journal"), - year=str(frontmatter.get("year")) if frontmatter.get("year") else None, - doi=frontmatter.get("doi"), - keywords=keywords, - publication_types=publication_types, - supplementary_files=supplementary_files, - metadata=metadata, - full_text_provider=frontmatter.get("full_text_provider"), - full_text_url=frontmatter.get("full_text_url"), - oa_status=frontmatter.get("oa_status"), - license=frontmatter.get("license"), - local_pdf_path=frontmatter.get("local_pdf_path"), - full_text_access_type=frontmatter.get("full_text_access_type"), - full_text_source_item_id=frontmatter.get("full_text_source_item_id"), - is_preprint=frontmatter.get("is_preprint"), - peer_review_status=frontmatter.get("peer_review_status"), - full_text_attempted=bool(frontmatter.get("full_text_attempted", False)), - ) - - -def install_reference_cache_compatibility() -> bool: - """Install only the affected 0.2.1 loader; return whether it is active.""" - installed_version = version("linkml-reference-validator") - if installed_version != "0.2.1": - logger.warning( - "Reference-cache delimiter backport is inactive for LRV %s; " - "verify upstream delimiter handling before updating the lock.", - installed_version, - ) - return False - if ReferenceFetcher._load_markdown_format is not _load_markdown_format_021: - ReferenceFetcher._load_markdown_format = _load_markdown_format_021 - return True diff --git a/src/ai_gene_review/validation/reference_cli.py b/src/ai_gene_review/validation/reference_cli.py deleted file mode 100644 index fa473c51ec6..00000000000 --- a/src/ai_gene_review/validation/reference_cli.py +++ /dev/null @@ -1,16 +0,0 @@ -"""Run the upstream reference CLI with the repo's pinned-release compatibility.""" - -from ai_gene_review.validation.reference_cache_compat import ( - install_reference_cache_compatibility, -) - - -def main(): - install_reference_cache_compatibility() - from linkml_reference_validator.cli import main as upstream_main - - return upstream_main() - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/src/ai_gene_review/validation/supporting_text.py b/src/ai_gene_review/validation/supporting_text.py index 67e4e463b38..f0f8f942579 100644 --- a/src/ai_gene_review/validation/supporting_text.py +++ b/src/ai_gene_review/validation/supporting_text.py @@ -53,11 +53,6 @@ def build_supporting_text_validator(publications_dir: Optional[Path] = None): if reference_base_dir is not None and not Path(reference_base_dir).is_absolute(): config_data["reference_base_dir"] = project_root / reference_base_dir - from ai_gene_review.validation.reference_cache_compat import ( - install_reference_cache_compatibility, - ) - - install_reference_cache_compatibility() config = ReferenceValidationConfig(**config_data) return SupportingTextValidator(config), publications_dir diff --git a/tests/conftest.py b/tests/conftest.py index 1b11b739231..e601ad67068 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,18 +1,70 @@ """Shared test configuration and fixtures. -Provides automatic VCR cassette recording/replay for integration tests. +Provides automatic VCR cassette recording/replay for integration tests, and +fails the run if any test writes into the committed publications/ or genes/. """ import builtins import os +import subprocess from pathlib import Path +from typing import Optional import pytest import vcr CASSETTES_DIR = Path(__file__).parent / "cassettes" -WORKING_TREE_GENES = Path(__file__).resolve().parents[1] / "genes" + + +REPO_ROOT = Path(__file__).resolve().parents[1] +WORKING_TREE_GENES = REPO_ROOT / "genes" +# Committed curated data that no test may write to; tests use tmp_path instead. +PROTECTED_TREES = ("publications", "genes") + + +def _protected_tree_status() -> Optional[str]: + """Return git's porcelain status of the protected trees, or None without git. + + Untracked files are included, so a newly cached ``PMID_*.md`` counts too. + """ + try: + result = subprocess.run( + ["git", "status", "--porcelain", "--untracked-files=all", "--", *PROTECTED_TREES], + cwd=REPO_ROOT, + capture_output=True, + text=True, + check=True, + ) + except (OSError, subprocess.CalledProcessError): # not a git checkout + return None + return result.stdout + + +def pytest_sessionstart(session): + """Snapshot the protected trees before any test runs.""" + session.config._protected_tree_status = _protected_tree_status() + + +def pytest_sessionfinish(session, exitstatus): + """Fail the run if any test changed committed publications/ or genes/ files.""" + before = getattr(session.config, "_protected_tree_status", None) + if before is None: + return + after = _protected_tree_status() + if after is None or after == before: + return + changed = sorted(set(after.splitlines()) - set(before.splitlines())) + reporter = session.config.pluginmanager.get_plugin("terminalreporter") + message = ( + "Tests modified the committed " + + "/".join(PROTECTED_TREES) + + " trees (write to tmp_path instead):\n " + + "\n ".join(changed or ["(status changed for already-modified files)"]) + ) + if reporter is not None: + reporter.write_line(message, red=True, bold=True) + session.exitstatus = pytest.ExitCode.TESTS_FAILED def pytest_addoption(parser): diff --git a/tests/test_gene_alternative_products_refresh.py b/tests/test_gene_alternative_products_refresh.py index 750a45f033f..09c6d535040 100644 --- a/tests/test_gene_alternative_products_refresh.py +++ b/tests/test_gene_alternative_products_refresh.py @@ -47,8 +47,8 @@ def test_fetch_repairs_existing_bag6_note_and_preserves_curated_fields(tmp_path, monkeypatch.setattr(gene, "fetch_goa_data", lambda accession: goa) monkeypatch.setattr(gene, "_extract_panther_family_id", lambda text: None) calls = [] - def seed(self, yaml_file, goa_file, fetch_titles=True): - calls.append((yaml_file, goa_file, fetch_titles)) + def seed(self, yaml_file, goa_file, fetch_titles=True, publications_dir=None): + calls.append((yaml_file, goa_file, fetch_titles, publications_dir)) return 0, None, 0, 0, 0 monkeypatch.setattr(GOAValidator, "seed_missing_annotations", seed) result = gene.fetch_gene_data(("human", "BAG6"), base_path=tmp_path, fetch_titles=False) @@ -61,6 +61,7 @@ def seed(self, yaml_file, goa_file, fetch_titles=True): assert second["alternative_product_sequences_repaired"] == 0 assert review.read_bytes() == first_bytes assert len(calls) == 2 and all(call[2] is False for call in calls) + assert all(call[3] == tmp_path / "publications" for call in calls) assert (directory / "BAG6-uniprot.txt").read_text() == raw assert (directory / "BAG6-goa.tsv").read_text() == goa diff --git a/tests/test_goa_validator.py b/tests/test_goa_validator.py index a46ebce2647..aeb2c8007fe 100644 --- a/tests/test_goa_validator.py +++ b/tests/test_goa_validator.py @@ -851,6 +851,47 @@ def test_seed_missing_annotations_true_noop_preserves_yaml_bytes(tmp_path): assert yaml_path.read_text() == original +def test_seed_missing_annotations_uses_given_publications_dir(tmp_path): + """Title lookups read the given cache, not the repo's publications/. + + PMID:12345 is also cached in the committed publications/ with a different + title, so a lookup there would be visible as the wrong title. + """ + validator = GOAValidator() + goa_path = tmp_path / "TEST-goa.tsv" + goa_path.write_text( + "GENE PRODUCT DB\tGENE PRODUCT ID\tSYMBOL\tQUALIFIER\tGO TERM\tGO NAME\t" + "GO ASPECT\tECO ID\tGO EVIDENCE CODE\tREFERENCE\tWITH/FROM\tTAXON ID\t" + "TAXON NAME\tASSIGNED BY\tGENE NAME\tDATE\n" + "UniProtKB\tQ12345\tTEST\tenables\tGO:0001234\ttest function\tMF\t" + "ECO:0000353\tIPI\tPMID:12345\t\tNCBITaxon:9606\tHomo sapiens\t" + "UniProt\tTest protein\t20180515\n" + ) + yaml_path = tmp_path / "TEST-ai-review.yaml" + yaml_path.write_text( + "id: Q12345\n" + "gene_symbol: TEST\n" + "taxon: {id: 'NCBITaxon:9606', label: Homo sapiens}\n" + "description: Test gene\n" + ) + publications_dir = tmp_path / "publications" + publications_dir.mkdir() + (publications_dir / "PMID_12345.md").write_text( + "---\npmid: '12345'\n---\n\n# Fixture-only cached title\n" + ) + + _, _, references_added, _, _ = validator.seed_missing_annotations( + yaml_path, goa_path, fetch_titles=True, publications_dir=publications_dir + ) + + assert references_added == 1 + document = yaml.safe_load(yaml_path.read_text()) + assert document["references"] == [ + {"id": "PMID:12345", "title": "Fixture-only cached title", "findings": []} + ] + assert sorted(publications_dir.iterdir()) == [publications_dir / "PMID_12345.md"] + + def test_seed_missing_annotations_noop_writes_requested_output(tmp_path): """A no-op seed still writes a separately requested output file.""" validator = GOAValidator() diff --git a/tests/test_publication_etl.py b/tests/test_publication_etl.py index 26d524d8fdf..133ae3bbe7a 100644 --- a/tests/test_publication_etl.py +++ b/tests/test_publication_etl.py @@ -163,15 +163,17 @@ def test_extract_pmids_from_empty_yaml(): @pytest.mark.integration -def test_fetch_pubmed_data(): +def test_fetch_pubmed_data(tmp_path): """Test fetching real data from PubMed. This test requires network access and is marked as integration. + The cache goes to tmp_path: the default would overwrite the committed + publications/PMID_29727692.md. """ # Use a known PMID from CFAP300 literature pmid = "29727692" - pub = fetch_pubmed_data(pmid) + pub = fetch_pubmed_data(pmid, cache_dir=tmp_path) assert pub is not None assert pub.pmid == pmid diff --git a/tests/test_publication_warm.py b/tests/test_publication_warm.py index 5fef99d1dc7..14017eb7107 100644 --- a/tests/test_publication_warm.py +++ b/tests/test_publication_warm.py @@ -255,6 +255,22 @@ def test_warm_publication_full_text_via_provider_chain( assert miss_frontmatter["full_text_attempted"] is True +def test_lrv_materialize_private_contract_still_matches_warm_sweep(tmp_path: Path) -> None: + """Guard the private ReferenceFetcher._materialize call until issue #2789 lands.""" + from linkml_reference_validator.models import ( + FullTextLocation, + ReferenceValidationConfig, + ) + from linkml_reference_validator.etl.reference_fetcher import ReferenceFetcher + + fetcher = ReferenceFetcher(ReferenceValidationConfig(cache_dir=tmp_path / "lrv")) + text, fmt, pdf_bytes, error = fetcher._materialize( + FullTextLocation(text="Stub full text.", format_hint="text") + ) + + assert (text, fmt, pdf_bytes, error) == ("Stub full text.", "text", None, False) + + ABSTRACT = ( "The CLAVATA1 and CLAVATA3 genes are required to maintain the balance " "between cell proliferation and organ formation at the shoot and flower " diff --git a/tests/test_reference_cache_compat.py b/tests/test_reference_cache.py similarity index 66% rename from tests/test_reference_cache_compat.py rename to tests/test_reference_cache.py index aa12ebe2df5..a896ac79171 100644 --- a/tests/test_reference_cache_compat.py +++ b/tests/test_reference_cache.py @@ -1,4 +1,9 @@ -"""Regression tests for delimiter-looking values through both validation paths.""" +"""Regression tests for reading the committed publications cache. + +Covers delimiter-looking values (fixed upstream in linkml-reference-validator +0.3.0) through both validation paths, and that validation trusts the cache as +written rather than re-fetching entries that lack an extractor_version stamp. +""" import os from pathlib import Path @@ -12,9 +17,7 @@ pytest.importorskip("linkml_reference_validator") -from ai_gene_review.validation import reference_cache_compat as compat from ai_gene_review.validation.supporting_text import build_supporting_text_validator -from linkml_reference_validator.etl.reference_fetcher import ReferenceFetcher PROJECT_ROOT = Path(__file__).resolve().parents[1] TITLE = "Carbonic anhydrase His----Tyr: structural comparison" @@ -22,13 +25,7 @@ @pytest.fixture(autouse=True) -def isolate_reference_loader(monkeypatch): - # Register restoration before any real installer or later monkeypatch runs. - # MonkeyPatch undoes registrations in reverse order, restoring this original - # method last even when the version-gate test temporarily installs a sentinel. - monkeypatch.setattr( - ReferenceFetcher, "_load_markdown_format", ReferenceFetcher._load_markdown_format - ) +def clear_validator_cache(): build_supporting_text_validator.cache_clear() yield build_supporting_text_validator.cache_clear() @@ -36,6 +33,8 @@ def isolate_reference_loader(monkeypatch): @pytest.fixture def cache(tmp_path): + # No extractor_version stamp, like nearly every committed cache entry: an + # untrusted 0.3.0 fetcher would treat it as stale and re-fetch PMID:1. text = ( "---\npmid: '1'\ntitle: '" + TITLE @@ -48,13 +47,28 @@ def cache(tmp_path): return tmp_path -@pytest.mark.parametrize("newline", ["\n", "\r\n"]) -def test_in_process_title_quote_and_cache_preservation(cache, newline): +@pytest.mark.parametrize( + "config_path", + ["conf/reference_validator_config.yaml", ".linkml-reference-validator.yaml"], +) +def test_repo_configs_trust_committed_cache(config_path): + config = yaml.safe_load((PROJECT_ROOT / config_path).read_text()) + assert config["trust_cached_entries"] is True + + +def test_warm_config_refreshes_stale_cache_entries(): + config = yaml.safe_load( + (PROJECT_ROOT / "conf/reference_validator_warm_config.yaml").read_text() + ) + assert config["cache_dir"] == "publications" + assert not config.get("trust_cached_entries", False) + + +def test_in_process_title_quote_and_cache_preservation(cache): p = cache / "PMID_1.md" - p.write_bytes(p.read_text().replace("\n", newline).encode()) before = p.read_bytes() - build_supporting_text_validator.cache_clear() validator, _ = build_supporting_text_validator(cache) + assert validator.config.trust_cached_entries assert validator.validate_title("PMID:1", TITLE).is_valid assert validator.validate(QUOTE, "PMID:1").is_valid assert not validator.validate_title("PMID:1", "An unrelated title").is_valid @@ -70,28 +84,11 @@ def test_in_process_title_quote_and_cache_preservation(cache, newline): def test_malformed_frontmatter_is_still_rejected(cache): p = cache / "PMID_1.md" p.write_text("---\ntitle: 'unfinished\n---\nBody\n") - build_supporting_text_validator.cache_clear() validator, _ = build_supporting_text_validator(cache) with pytest.raises(Exception, match="quoted scalar|expected"): validator.validate_title("PMID:1", TITLE) -def test_install_is_idempotent_and_limited_to_affected_version(monkeypatch): - monkeypatch.setattr(compat, "version", lambda name: "0.2.1") - assert compat.install_reference_cache_compatibility() - method = ReferenceFetcher._load_markdown_format - assert compat.install_reference_cache_compatibility() - assert ReferenceFetcher._load_markdown_format is method - monkeypatch.setattr(compat, "version", lambda name: "0.2.2") - - def sentinel(*args): - return None - - monkeypatch.setattr(ReferenceFetcher, "_load_markdown_format", sentinel) - assert not compat.install_reference_cache_compatibility() - assert ReferenceFetcher._load_markdown_format is sentinel - - @pytest.mark.parametrize("bad", [None, "title", "quote"]) def test_normal_reference_wrapper_preserves_strict_validation(cache, tmp_path, bad): title = "An unrelated title" if bad == "title" else TITLE @@ -134,6 +131,8 @@ def test_normal_reference_wrapper_preserves_strict_validation(cache, tmp_path, b str(PROJECT_ROOT / "src/ai_gene_review/schema/gene_review.yaml"), "--target-class", "GeneReview", + "--config", + str(PROJECT_ROOT / "conf/reference_validator_config.yaml"), "--cache-dir", str(cache), "--no-full-text", @@ -147,33 +146,16 @@ def test_normal_reference_wrapper_preserves_strict_validation(cache, tmp_path, b assert (cache / "PMID_1.md").read_bytes() == before -@pytest.mark.parametrize("metadata", ["", "plain scalar", "- item", "true"]) -def test_non_mapping_frontmatter_is_rejected_without_fetch(metadata): - fetcher = object.__new__(ReferenceFetcher) - assert compat._load_markdown_format_021( - fetcher, f"---\n{metadata}\n---\nBody", "PMID:1" - ) is None - - -def test_version_gate_reports_inactive_backport(monkeypatch, caplog): - monkeypatch.setattr(compat, "version", lambda name: "0.2.2") - original = ReferenceFetcher._load_markdown_format - assert not compat.install_reference_cache_compatibility() - assert ReferenceFetcher._load_markdown_format is original - assert "inactive for LRV 0.2.2" in caplog.text - - -def test_warming_uses_compatible_cli_without_running_it(monkeypatch): +def test_warming_uses_upstream_cli_without_running_it(monkeypatch): module = runpy.run_path(str(PROJECT_ROOT / "scripts/warm_reference_cache.py")) monkeypatch.setattr(module["glob"], "glob", lambda pattern: ["fixture.yaml"]) calls = [] monkeypatch.setattr(module["subprocess"], "run", lambda *a, **kw: calls.append((a, kw))) assert module["main"]() == 0 - assert calls[0][0][0][:7] == [ - "uv", "run", "python", "-m", "ai_gene_review.validation.reference_cli", - "validate", "data", - ] - assert "--no-full-text" not in calls[0][0][0] + cmd = calls[0][0][0] + assert cmd[:5] == ["uv", "run", "linkml-reference-validator", "validate", "data"] + assert cmd[cmd.index("--config") + 1] == "conf/reference_validator_warm_config.yaml" + assert "--no-full-text" not in cmd @pytest.mark.parametrize("newline", ["\n", "\r\n"]) @@ -199,21 +181,20 @@ def test_full_text_utility_rejects_invalid_metadata(tmp_path, metadata): @pytest.mark.parametrize("script", ["mark_full_text_unavailable.py", "extract_supporting_text_fixes.py"]) -def test_direct_utilities_install_before_validator_construction(monkeypatch, tmp_path, script): +def test_direct_utilities_trust_committed_cache(monkeypatch, tmp_path, script): import linkml_reference_validator.validation.supporting_text_validator as upstream calls = [] + def constructor(config): - assert ReferenceFetcher._load_markdown_format is compat._load_markdown_format_021 calls.append(config) return SimpleNamespace() monkeypatch.setattr(upstream, "SupportingTextValidator", constructor) - monkeypatch.setattr(compat, "version", lambda name: "0.2.1") - monkeypatch.setattr(ReferenceFetcher, "_load_markdown_format", lambda *a: None) monkeypatch.chdir(tmp_path) # No real gene files or publication caches are visited. monkeypatch.setattr(sys, "argv", [script, "--dry-run"]) module = runpy.run_path(str(PROJECT_ROOT / "scripts" / script)) if script == "mark_full_text_unavailable.py": module["main"]() assert len(calls) == 1 + assert calls[0].trust_cached_entries diff --git a/uv.lock b/uv.lock index 942915075eb..0fd7345512c 100644 --- a/uv.lock +++ b/uv.lock @@ -118,7 +118,7 @@ requires-dist = [ { name = "jupyter", specifier = ">=1.1.1" }, { name = "linkml-browser", specifier = ">=0.1.0" }, { name = "linkml-data-qc", specifier = ">=0.1.0" }, - { name = "linkml-reference-validator", specifier = ">=0.2.1,<0.3" }, + { name = "linkml-reference-validator", specifier = ">=0.3.0,<0.4" }, { name = "linkml-runtime", specifier = ">=1.9.4" }, { name = "linkml-term-validator", specifier = ">=0.4.5" }, { name = "lxml", specifier = ">=6.0.1" }, @@ -330,7 +330,7 @@ resolution-markers = [ "python_full_version >= '3.14'", ] dependencies = [ - { name = "cffi", marker = "python_full_version >= '3.14'" }, + { name = "cffi" }, ] sdist = { url = "https://files.pythonhosted.org/packages/b9/e9/184b8ccce6683b0aa2fbb7ba5683ea4b9c5763f1356347f1312c32e3c66e/argon2-cffi-bindings-21.2.0.tar.gz", hash = "sha256:bb89ceffa6c791807d1305ceb77dbfacc5aa499891d2c55661c6459651fc39e3", size = 1779911, upload-time = "2021-12-01T08:52:55.68Z" } wheels = [ @@ -355,7 +355,7 @@ resolution-markers = [ "python_full_version < '3.13'", ] dependencies = [ - { name = "cffi", marker = "python_full_version < '3.14'" }, + { name = "cffi" }, ] sdist = { url = "https://files.pythonhosted.org/packages/5c/2d/db8af0df73c1cf454f71b2bbe5e356b8c1f8041c979f505b3d3186e520a9/argon2_cffi_bindings-25.1.0.tar.gz", hash = "sha256:b957f3e6ea4d55d820e40ff76f450952807013d361a65d7f28acc0acbf29229d", size = 1783441, upload-time = "2025-07-30T10:02:05.147Z" } wheels = [ @@ -2652,7 +2652,7 @@ wheels = [ [[package]] name = "linkml-reference-validator" -version = "0.2.1" +version = "0.3.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "beautifulsoup4" }, @@ -2667,9 +2667,9 @@ dependencies = [ { name = "ruamel-yaml" }, { name = "typer" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/93/4d/f03e952e2435faef11adeb16044e03fed71bdac03ef3511245ced0ce6ea1/linkml_reference_validator-0.2.1.tar.gz", hash = "sha256:ea4cf1145462d12984bf1c484958e8561ec863e7d3eafd8d54e2824cf0d65300", size = 1151372, upload-time = "2026-08-07T00:48:48.94Z" } +sdist = { url = "https://files.pythonhosted.org/packages/6c/dc/a8cafd7268f1d0898abe0398d7e643151f8468181e6177f500c26a594447/linkml_reference_validator-0.3.0.tar.gz", hash = "sha256:0126434d2be99fa3c7a0f0db6784b52c34f0ae695fd0b1b8a9a005c2dd34c25b", size = 1294426, upload-time = "2026-10-04T01:30:46.414Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d0/12/ca4455eec18adb3a2d840f4c5df651b3422fc2d3bf1ab532c3476cfeb4ae/linkml_reference_validator-0.2.1-py3-none-any.whl", hash = "sha256:91d19a3b51001f467b6fb8f6e0968739df81c9b159c5928581fbab4d28c3876c", size = 130650, upload-time = "2026-08-07T00:48:47.285Z" }, + { url = "https://files.pythonhosted.org/packages/e7/e0/446f0710af2097affc613e8e8a2345d6ce6e6480c1556751b349447b35cf/linkml_reference_validator-0.3.0-py3-none-any.whl", hash = "sha256:28064a0ccd13807af1d94e02eeb27e5ebb796e6428b981270f9d389054fb649a", size = 175413, upload-time = "2026-10-04T01:30:44.764Z" }, ] [[package]]