Skip to content

Add DataCite fallback, supplementary files, and URL normalization - #36

Merged
dragon-ai-agent merged 1 commit into
mainfrom
supplementary-files
Jan 27, 2026
Merged

dragon-ai-agent merged 1 commit into
mainfrom
supplementary-files

Conversation

@cmungall

Copy link
Copy Markdown
Member

Summary

  • add DataCite fallback for repository DOIs and capture supplementary file metadata
  • normalize bare http(s) references to url: and improve URL cache lookup guidance
  • extract PMID MeSH keywords and document new metadata fields
  • update docs/notebooks for lookup command and repository DOI support

Testing

  • just test

Copilot AI review requested due to automatic review settings January 27, 2026 02:42
@claude

claude Bot commented Jan 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @cmungall's task —— View job


Code Review for DataCite fallback, supplementary files, and URL normalization

I've completed a comprehensive review of this large PR. Here are my findings:

Review Summary

  • Read project guidelines and setup
  • Analyze core functionality changes
  • Review test coverage and quality
  • Check documentation updates
  • Assess security and performance
  • Provide final recommendations

✅ Positive Aspects

1. Well-documented bug fixes

The PR addresses specific issues documented in BUG_ZENODO_DOI_AND_URL_HANDLING.md - fixing Zenodo DOIs failing due to Crossref-only queries and bare HTTPS URLs not being recognized.

2. Robust DataCite fallback implementation

  • DOI source (src/linkml_reference_validator/etl/sources/doi.py:143-209) properly implements fallback to DataCite API when Crossref returns 404
  • Enables support for repository DOIs (Zenodo, Figshare, Dryad)
  • Includes supplementary file metadata extraction from repository APIs

3. URL normalization improvements

  • Bare HTTP(S) URLs now properly handled by early detection (src/linkml_reference_validator/etl/reference_fetcher.py:148-150)
  • Fixes parsing issue where https://example.com was incorrectly parsed as prefix HTTPS

4. Comprehensive test coverage

  • Tests include edge cases for bare URLs, DataCite fallback scenarios, and supplementary file handling
  • Good use of mocking for external API calls
  • Tests follow TDD principles as required by project guidelines

5. Rich metadata support

  • New SupplementaryFile data class captures file metadata without requiring downloads by default
  • MeSH keyword extraction from PMID sources
  • Proper YAML quoting to handle special characters in titles

🔍 Areas of Concern & Recommendations

Security & Performance

1. Rate Limiting Concerns (src/linkml_reference_validator/etl/sources/doi.py:77)

time.sleep(config.rate_limit_delay)

Issue: Rate limiting only applied at start of fetch(), not between Crossref and DataCite calls.

Risk: Could overwhelm DataCite API when many Crossref requests fail.

Recommendation: Add rate limiting between API calls:

def _fetch_from_datacite(self, doi: str, config: ReferenceValidationConfig):
    time.sleep(config.rate_limit_delay)  # Add this
    url = f"https://api.datacite.org/dois/{doi}"
    # ...

2. Timeout Configuration

Good: Consistent 30-second timeouts used throughout.
Recommendation: Consider making timeout configurable for different network environments.

Code Quality

3. Exception Handling

Concern: Project guidelines discourage try/except blocks, but some API calls could benefit from more specific error handling for different HTTP status codes (429, 503, etc.).

Current: Only checks response.status_code != 200
Recommendation: Consider more granular status code handling for better user experience.

4. Repository Detection (src/linkml_reference_validator/etl/sources/doi.py:227-233)

def _detect_repository(self, doi: str) -> Optional[str]:
    if doi.startswith("10.5281/zenodo."):
        return "zenodo"
    return None

Good: Extensible design with TODO comments for additional repositories.
Recommendation: Consider configuration-driven repository detection for easier extension.

Documentation

5. Documentation Quality

Excellent: Updated docs clearly explain new DataCite fallback functionality and repository DOI support.
Minor: Some new .md files in root directory (like BUG_ZENODO_DOI_AND_URL_HANDLING.md) might be better in a docs/ subdirectory.

Testing

6. Test Coverage

Good: Comprehensive test coverage including:

  • DataCite fallback scenarios
  • Bare URL parsing
  • YAML quoting edge cases
  • Supplementary file metadata

Recommendation: Consider adding integration tests that actually call DataCite API (with rate limiting) to catch API changes.

🚀 Overall Assessment

This is a high-quality PR that successfully addresses documented issues while maintaining code quality and following project conventions. The implementation is well-tested and properly documented.

Priority Recommendations

  1. High: Add rate limiting between Crossref and DataCite API calls
  2. Medium: Consider moving root-level .md files to docs/ directory
  3. Low: Make timeout values configurable

Approval Status

✅ Recommend approval with the rate limiting fix applied.

The PR demonstrates excellent adherence to project guidelines:

  • ✅ Test-driven development with comprehensive test coverage
  • ✅ Proper use of docstrings throughout
  • ✅ Avoids unnecessary try/except blocks
  • ✅ Clean, well-structured code that follows existing patterns

@dragon-ai-agent
dragon-ai-agent merged commit ac6a65d into main Jan 27, 2026
12 of 13 checks passed

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds DOI fetching fallback via DataCite (including Zenodo supplementary file metadata), improves handling/normalization of bare HTTP(S) URLs, and enriches ReferenceContent with keywords and supplementary file metadata. Also extends the CLI lookup/cache UX and updates docs/notebooks and dev tooling accordingly.

Changes:

  • Add SupplementaryFile model and keywords/supplementary_files fields on ReferenceContent, plus serialization/deserialization support in ReferenceFetcher.
  • Enhance DOI fetching to fall back to DataCite (with Zenodo file metadata) and improve URL handling by treating bare HTTP/HTTPS URLs as url: references and normalizing them.
  • Extend the CLI (lookup, cache lookup) and documentation/notebooks to expose new metadata, repository DOI behavior, and cache inspection, and add devcontainer / agent config files.

Reviewed changes

Copilot reviewed 26 out of 26 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
tests/test_reference_fetcher.py Adds tests for bare URL parsing/normalization, DOI Crossref/DataCite fallback, Zenodo supplementary files, repository detection helpers, and supplementary file cache serialization.
src/linkml_reference_validator/models.py Introduces download_supplementary_files/max_supplementary_file_size config fields and a SupplementaryFile dataclass; extends ReferenceContent with keywords and supplementary_files.
src/linkml_reference_validator/etl/sources/pmid.py Normalizes Entrez values to strings and adds MeSH keyword extraction into keywords.
src/linkml_reference_validator/etl/sources/doi.py Refactors DOI fetching into Crossref + DataCite paths, adds repository detection and Zenodo file metadata fetching, and populates keywords/supplementary_files.
src/linkml_reference_validator/etl/reference_fetcher.py Updates reference ID parsing to handle bare HTTP(S) URLs and extends cache read/write to include keywords and supplementary_files.
src/linkml_reference_validator/cli/lookup.py Adds --download-files option, exposes keywords and supplementary_files in JSON/text output, and wires flag into config.
docs/reference/cli.md Documents the lookup, validate text-file, and cache lookup commands, and updates CLI reference sections.
docs/notebooks/05_geo_validation.ipynb Uses cache lookup CLI to locate GEO cache files instead of hard-coded paths.
docs/notebooks/04_obo_validation.ipynb Uses cache lookup for PMID cache inspection.
docs/notebooks/02_advanced_usage.ipynb Uses cache lookup for cached reference structure example.
docs/notebooks/01_getting_started.ipynb Uses cache lookup to peek at cached references.
docs/how-to/validate-urls.md Updates URL reference guidance to support bare HTTP(S) URLs and cache lookup usage.
docs/how-to/validate-dois.md Documents Crossref/DataCite behavior, repository DOIs, supplementary files, and when to choose DOI vs PMID.
docs/how-to/use-local-files-and-urls.md Clarifies file reference resolution and bare URL handling and updates cache refresh instructions.
docs/how-to/repair-validation-errors.md Updates example to use cache lookup for inspecting content type.
docs/concepts/content-types.md Updates CLI examples for inspecting content and documents the new keywords and supplementary_files metadata fields.
copilot-instructions.md Adds indirection to agent instructions file.
FEATURE_REQUEST_REPAIR.md Adds a feature request document for an automated --repair mode.
CLI-ISSUES.md Documents a known CLI summary-label issue for validate data.
BUG_ZENODO_DOI_AND_URL_HANDLING.md Captures the root causes and proposed fixes for Zenodo DOI/DataCite and bare HTTPS URL handling.
BUG_GEO_ACCESSION_TO_UID.md Documents a GEO/Entrez UID bug and a proposed fix.
AGENTS.md Adds indirection to additional agent configuration.
.goosehints Points tooling at AGENTS.md.
.devcontainer/post_create.sh Adds post-create setup steps (ODK help, optional tools, Claude Code).
.devcontainer/devcontainer.json Adds a devcontainer definition using the ODK image and common extensions.
.claude/settings.json Simplifies Claude settings JSON.
Comments suppressed due to low confidence (1)

src/linkml_reference_validator/cli/lookup.py:1

  • The new --download-files / -D flag only sets config.download_supplementary_files but there is no corresponding logic in the DOI/url sources to actually download files or populate SupplementaryFile.local_path, so the option currently has no observable effect despite the help text promising downloads. Either wire config.download_supplementary_files (and max_supplementary_file_size) into the DOI/repository fetching code to perform downloads and set local_path, or adjust the option name/help text to reflect that only metadata is captured.
"""Top-level lookup command for quick reference lookups."""

Comment on lines +53 to +59
# Option for downloading supplementary files
DownloadFilesOption = Annotated[
bool,
typer.Option(
"--download-files",
"-D",
help="Download supplementary files from repositories (e.g., Zenodo). By default, only metadata is captured.",

Copilot AI Jan 27, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new --download-files / -D flag only sets config.download_supplementary_files but there is no corresponding logic in the DOI/url sources to actually download files or populate SupplementaryFile.local_path, so the option currently has no observable effect despite the help text promising downloads. Either wire config.download_supplementary_files (and max_supplementary_file_size) into the DOI/repository fetching code to perform downloads and set local_path, or adjust the option name/help text to reflect that only metadata is captured.

Suggested change
# Option for downloading supplementary files
DownloadFilesOption = Annotated[
bool,
typer.Option(
"--download-files",
"-D",
help="Download supplementary files from repositories (e.g., Zenodo). By default, only metadata is captured.",
# Option for including supplementary file metadata (no download)
DownloadFilesOption = Annotated[
bool,
typer.Option(
"--download-files",
"-D",
help="Include metadata about supplementary files from repositories (e.g., Zenodo). Files are not downloaded; only metadata is captured.",

Copilot uses AI. Check for mistakes.
Comment on lines 235 to +239
config = load_validation_config(config_file)
if cache_dir:
config.cache_dir = cache_dir
if download_files:
config.download_supplementary_files = True

Copilot AI Jan 27, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new --download-files / -D flag only sets config.download_supplementary_files but there is no corresponding logic in the DOI/url sources to actually download files or populate SupplementaryFile.local_path, so the option currently has no observable effect despite the help text promising downloads. Either wire config.download_supplementary_files (and max_supplementary_file_size) into the DOI/repository fetching code to perform downloads and set local_path, or adjust the option name/help text to reflect that only metadata is captured.

Copilot uses AI. Check for mistakes.
Comment on lines +78 to +94
### Downloading Supplementary Files

By default, only metadata about supplementary files is captured. To download the actual files:

```bash
linkml-reference-validator lookup -D DOI:10.5281/zenodo.7961621
```

Downloaded files are stored in:
```
references_cache/
files/
DOI_10.5281_zenodo.7961621/
Dickinson_Varenna2022.pdf
workshop_slides.pptx
data_analysis.xlsx
```

Copilot AI Jan 27, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This section documents actual file downloads and a references_cache/files/... layout, but the current implementation only fetches supplementary file metadata and never writes downloaded files or local_path entries. Either implement the described download behavior (e.g., using download_supplementary_files and max_supplementary_file_size) or revise the docs to clarify that only metadata is stored until a download feature is added.

Suggested change
### Downloading Supplementary Files
By default, only metadata about supplementary files is captured. To download the actual files:
```bash
linkml-reference-validator lookup -D DOI:10.5281/zenodo.7961621
```
Downloaded files are stored in:
```
references_cache/
files/
DOI_10.5281_zenodo.7961621/
Dickinson_Varenna2022.pdf
workshop_slides.pptx
data_analysis.xlsx
```
### Supplementary Files Metadata
Currently, only metadata about supplementary files is captured. The validator does not download or cache the actual file contents yet.
The `linkml-reference-validator lookup` command will list available supplementary files (for example, their names and sizes) in the CLI output, but files are not written to disk and no `references_cache/files/...` layout is created.
Support for downloading supplementary files may be added in a future version (for example, via a `download_supplementary_files` option and a configurable `max_supplementary_file_size`), but this is not implemented in the current release.

Copilot uses AI. Check for mistakes.
Comment on lines +190 to +206
def _fetch_mesh_terms(
self, pmid: str, config: ReferenceValidationConfig
) -> Optional[list[str]]:
"""Fetch MeSH terms for a PMID from PubMed XML.

Args:
pmid: PubMed ID
config: Configuration for rate limiting

Returns:
List of MeSH terms if available

Examples:
>>> source = PMIDSource()
>>> # Would return MeSH terms like:
>>> # ['Adaptation, Physiological/genetics', 'Climate Change', ...]
"""

Copilot AI Jan 27, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new MeSH extraction logic and its propagation into ReferenceContent.keywords are untested, even though other fetcher behaviors are covered in tests/test_reference_fetcher.py. Consider adding tests that mock the Entrez XML response to verify that MeSH terms are parsed correctly (including qualifiers) and that they survive through to cache serialization/deserialization.

Copilot uses AI. Check for mistakes.
Comment on lines +222 to +234
terms = []
for heading in mesh_list.find_all("MeshHeading"):
descriptor = heading.find("DescriptorName")
if descriptor:
term = descriptor.get_text()
# Include qualifiers if present (e.g., "genetics", "metabolism")
qualifiers = heading.find_all("QualifierName")
if qualifiers:
qualifier_texts = [q.get_text() for q in qualifiers]
term = f"{term}/{', '.join(qualifier_texts)}"
terms.append(term)

return terms if terms else None

Copilot AI Jan 27, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new MeSH extraction logic and its propagation into ReferenceContent.keywords are untested, even though other fetcher behaviors are covered in tests/test_reference_fetcher.py. Consider adding tests that mock the Entrez XML response to verify that MeSH terms are parsed correctly (including qualifiers) and that they survive through to cache serialization/deserialization.

Copilot uses AI. Check for mistakes.
lines.append("")
lines.append(f"--- Supplementary Files ({len(reference.supplementary_files)}) ---")
for sf in reference.supplementary_files:
size_str = f" ({sf.size_bytes:,} bytes)" if sf.size_bytes else ""

Copilot AI Jan 27, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using if sf.size_bytes will omit a valid size of 0 bytes, producing no size string for empty files; checking sf.size_bytes is not None instead would correctly display 0 bytes while still skipping unknown sizes. This avoids misleading output in edge cases where an intentionally empty supplementary file exists.

Suggested change
size_str = f" ({sf.size_bytes:,} bytes)" if sf.size_bytes else ""
size_str = f" ({sf.size_bytes:,} bytes)" if sf.size_bytes is not None else ""

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants