Skip to content

Commit 04f58af

Browse files
authored
Merge pull request #148 from linkml/fix-file-cache-135
Always read file: references from the file, under one canonical id
2 parents f686e31 + 36293b6 commit 04f58af

4 files changed

Lines changed: 210 additions & 21 deletions

File tree

‎src/linkml_reference_validator/etl/reference_fetcher.py‎

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
)
3838
from linkml_reference_validator.etl.sources import ReferenceSourceRegistry
3939
from linkml_reference_validator.etl.sources.clinicaltrials import NCT_ID_PATTERN
40+
from linkml_reference_validator.etl.sources.file import FileSource
4041
from linkml_reference_validator.etl.acquire import ContentAcquirer, resolve_format, sniff_format
4142
from linkml_reference_validator.etl.identifiers import build_identifiers
4243
from linkml_reference_validator.etl.fulltext.base import PUBLISHER_FREE_ACCESS
@@ -307,6 +308,10 @@ def __init__(self, config: ReferenceValidationConfig):
307308
# obtained: a stale fallback stays flagged on every later read in this
308309
# process instead of being laundered into a fresh-looking hit.
309310
self._cache: dict[str, FetchOutcome] = {}
311+
# What was last written for each file: reference. Never served (a file is
312+
# always read live), only compared, so a file cited many times is written
313+
# once per change rather than once per citation.
314+
self._saved_files: dict[str, ReferenceContent] = {}
310315
self._acquirer = ContentAcquirer()
311316
# Build the PDF extractor once: this validates config.pdf_backend up front
312317
# (an unknown backend raises here, at init, rather than mid-fetch) and avoids
@@ -377,13 +382,22 @@ def fetch_with_provenance(
377382
>>> # outcome.served_stale
378383
"""
379384
normalized_reference_id = self.normalize_reference_id(reference_id)
385+
# A local file is cheap to read and can change at any time, and nothing
386+
# records which version a cache entry was read from. So it is always
387+
# read from the file: neither cache is consulted, and a file that has
388+
# gone is not found, rather than served from an old copy (#135). The
389+
# entry is still written, for the cache commands and export, when it
390+
# differs from what this fetcher last wrote. Skipping the read on an
391+
# unchanged mtime and size would be cheaper, but a timestamp is too
392+
# coarse to catch a same-size edit made just after the last read.
393+
live = normalized_reference_id.startswith("file:")
380394

381395
# Check memory cache
382-
if not force_refresh and normalized_reference_id in self._cache:
396+
if not force_refresh and not live and normalized_reference_id in self._cache:
383397
return self._cache[normalized_reference_id]
384398

385399
# Check disk cache
386-
if not force_refresh:
400+
if not force_refresh and not live:
387401
cached = self._load_from_disk(
388402
normalized_reference_id,
389403
allow_stale=self.config.trust_cached_entries,
@@ -443,7 +457,13 @@ def fetch_with_provenance(
443457
content = self._enrich_with_full_text(content)
444458

445459
if not content:
446-
return self._stale_fallback(normalized_reference_id, force_refresh)
460+
return self._stale_fallback(normalized_reference_id, force_refresh or live)
461+
462+
if live:
463+
if self._saved_files.get(normalized_reference_id) != content:
464+
self._save_by_access(content)
465+
self._saved_files[normalized_reference_id] = content
466+
return FetchOutcome(content=content)
447467

448468
preserved = self._preserve_cached_full_text(
449469
normalized_reference_id, content, force_refresh
@@ -1120,10 +1140,23 @@ def normalize_reference_id(self, reference_id: str) -> str:
11201140
'clinicaltrials:NCT12345678'
11211141
>>> fetcher.normalize_reference_id("CLINICALTRIALS:nct12345678")
11221142
'clinicaltrials:NCT12345678'
1143+
1144+
A ``file:`` path is resolved, so relative and absolute spellings of
1145+
one file are one reference:
1146+
1147+
>>> import tempfile
1148+
>>> base = Path(tempfile.gettempdir())
1149+
>>> config = ReferenceValidationConfig(reference_base_dir=base)
1150+
>>> fetcher = ReferenceFetcher(config)
1151+
>>> relative = fetcher.normalize_reference_id("file:./sub/../notes.md")
1152+
>>> relative == fetcher.normalize_reference_id(f"file:{base / 'notes.md'}")
1153+
True
11231154
"""
11241155
prefix, identifier = self._parse_reference_id(reference_id)
11251156
if prefix == "UNKNOWN":
11261157
return reference_id.strip()
1158+
if prefix == "file":
1159+
return f"file:{FileSource.resolve_path(identifier, self.config)}"
11271160
return f"{prefix}:{identifier}"
11281161

11291162
def _normalize_prefix(self, prefix: str) -> str:
@@ -1147,7 +1180,8 @@ def _normalized_prefix_map(self) -> dict[str, str]:
11471180
def get_cache_path(self, reference_id: str) -> Path:
11481181
"""Get the cache file path for a reference.
11491182
1150-
Bare NCT IDs and ClinicalTrials casing are canonicalized. For configured
1183+
Bare NCT IDs, ClinicalTrials casing and ``file:`` paths are
1184+
canonicalized. For configured
11511185
prefix aliases, pass the result of :meth:`normalize_reference_id`.
11521186
11531187
Args:
@@ -1207,6 +1241,8 @@ def _cache_path(self, reference_id: str, cache_dir: Path) -> Path:
12071241
)
12081242
if prefix == "clinicaltrials":
12091243
reference_id = f"{prefix}:{identifier}"
1244+
if prefix == "file":
1245+
reference_id = f"file:{FileSource.resolve_path(identifier, self.config)}"
12101246
# Other IDs already arrive normalized from fetch(). Reapplying arbitrary
12111247
# prefix maps here could follow a second alias and change the cache key.
12121248
path = cache_dir / cache_filename(reference_id)

‎src/linkml_reference_validator/etl/sources/file.py‎

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
"""
1212

1313
import logging
14+
import os
1415
import re
1516
from pathlib import Path
1617
from typing import Optional
@@ -79,7 +80,7 @@ def fetch(
7980
>>> # Would read file in real usage:
8081
>>> # ref = source.fetch("./notes.md", config)
8182
"""
82-
file_path = self._resolve_path(identifier, config)
83+
file_path = self.resolve_path(identifier, config)
8384

8485
if not file_path.exists():
8586
logger.warning(f"File not found: {file_path}")
@@ -129,40 +130,44 @@ def _fetch_figure(self, file_path: Path, figure_format: str) -> ReferenceContent
129130
content_type=FIGURE_CONTENT_TYPES[figure_format] if text else "unavailable",
130131
)
131132

132-
def _resolve_path(self, identifier: str, config: ReferenceValidationConfig) -> Path:
133+
@staticmethod
134+
def resolve_path(identifier: str, config: ReferenceValidationConfig) -> Path:
133135
"""Resolve a file path from identifier.
134136
135137
- Absolute paths are used directly
136138
- Relative paths use reference_base_dir if set, otherwise CWD
137139
140+
The result is absolute with ``.`` and ``..`` collapsed, so relative and
141+
absolute spellings of one path give one path, and one cache key (#135).
142+
Symlinks are deliberately not followed: a report names the path the
143+
curator wrote, and repointing a link (a "current version" link, say)
144+
does not leave an entry under the old target behind. A link and its
145+
target are therefore two references, each read live from the file.
146+
138147
Args:
139148
identifier: File path string
140149
config: Configuration with optional reference_base_dir
141150
142151
Returns:
143-
Resolved Path object
152+
Resolved absolute Path object
144153
145154
Examples:
155+
>>> import tempfile
146156
>>> from linkml_reference_validator.models import ReferenceValidationConfig
147-
>>> source = FileSource()
148-
>>> config = ReferenceValidationConfig()
149-
>>> # Absolute path stays absolute
150-
>>> p = source._resolve_path("/tmp/test.md", config)
151-
>>> p.is_absolute()
157+
>>> with tempfile.TemporaryDirectory() as d:
158+
... config = ReferenceValidationConfig(reference_base_dir=Path(d))
159+
... relative = FileSource.resolve_path("./sub/../notes.md", config)
160+
... absolute = FileSource.resolve_path(str(Path(d) / "notes.md"), config)
161+
>>> relative == absolute and relative.is_absolute()
152162
True
153163
"""
154164
path = Path(identifier)
155165

156-
# Absolute paths are used directly
157-
if path.is_absolute():
158-
return path
159-
160166
# Relative paths: use base_dir if set, otherwise CWD
161-
base_dir = getattr(config, "reference_base_dir", None)
162-
if base_dir is not None:
163-
return Path(base_dir) / path
164-
else:
165-
return Path.cwd() / path
167+
if not path.is_absolute():
168+
base_dir = config.reference_base_dir
169+
path = Path(base_dir) / path if base_dir is not None else Path.cwd() / path
170+
return Path(os.path.abspath(path))
166171

167172
def _extract_title(self, content: str, file_path: Path) -> str:
168173
"""Extract title from content or use filename.

‎tests/test_cli_cache_reference.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,3 +269,20 @@ def test_a_preserved_entry_keeps_failing_until_forced(cache_dir, mocker):
269269
# What --force costs, asserted rather than left to the reader. It is the
270270
# remedy the failure message names, so the cost belongs in the contract.
271271
assert "Scraped page text" not in path.read_text(encoding="utf-8")
272+
273+
274+
def test_caching_a_file_reference_writes_a_current_entry(cache_dir, tmp_path):
275+
"""A file: reference is read live, yet the command still leaves an entry (#135)."""
276+
notes = tmp_path / "notes.md"
277+
notes.write_text("# Notes\n\nversion one", encoding="utf-8")
278+
279+
result = _run(cache_dir, f"file:{notes}")
280+
281+
assert result.exit_code == 0, result.output
282+
assert "Successfully cached" in result.output
283+
entry = _fetcher(cache_dir).get_cache_path(f"file:{notes}").read_text()
284+
assert "version one" in entry
285+
286+
notes.write_text("# Notes\n\nversion two", encoding="utf-8")
287+
assert _run(cache_dir, f"file:{notes}").exit_code == 0
288+
assert "version two" in _fetcher(cache_dir).get_cache_path(f"file:{notes}").read_text()

‎tests/test_file_reference_cache.py‎

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
"""A ``file:`` reference is always read from the file, never from a cache (#135)."""
2+
3+
import pytest
4+
5+
from linkml_reference_validator.etl.reference_fetcher import ReferenceFetcher
6+
from linkml_reference_validator.models import ReferenceValidationConfig
7+
8+
9+
def svg(label: str) -> str:
10+
"""An SVG figure that draws one text label."""
11+
return f'<svg xmlns="http://www.w3.org/2000/svg"><text>{label}</text></svg>'
12+
13+
14+
@pytest.fixture
15+
def config(tmp_path):
16+
"""A config with its own cache, resolving relative paths against ``refs``."""
17+
return ReferenceValidationConfig(
18+
cache_dir=tmp_path / "cache", reference_base_dir=tmp_path / "refs"
19+
)
20+
21+
22+
@pytest.fixture
23+
def notes(config):
24+
"""A markdown file in the reference base directory, reading ``version one``."""
25+
config.reference_base_dir.mkdir()
26+
path = config.reference_base_dir / "notes.md"
27+
path.write_text("version one", encoding="utf-8")
28+
return path
29+
30+
31+
def test_new_fetcher_sees_an_edited_file(config, notes):
32+
assert ReferenceFetcher(config).fetch(f"file:{notes}").content == "version one"
33+
notes.write_text("version two", encoding="utf-8")
34+
assert ReferenceFetcher(config).fetch(f"file:{notes}").content == "version two"
35+
36+
37+
def test_same_fetcher_sees_an_edited_file(config, notes):
38+
fetcher = ReferenceFetcher(config)
39+
assert fetcher.fetch(f"file:{notes}").content == "version one"
40+
notes.write_text("version two", encoding="utf-8")
41+
assert fetcher.fetch(f"file:{notes}").content == "version two"
42+
43+
44+
def test_trusted_cache_does_not_hide_an_edit(config, notes):
45+
config.trust_cached_entries = True
46+
assert ReferenceFetcher(config).fetch(f"file:{notes}").content == "version one"
47+
notes.write_text("version two", encoding="utf-8")
48+
assert ReferenceFetcher(config).fetch(f"file:{notes}").content == "version two"
49+
50+
51+
def test_deleted_file_is_not_served_from_the_cache(config, notes):
52+
fetcher = ReferenceFetcher(config)
53+
assert fetcher.fetch(f"file:{notes}") is not None
54+
notes.unlink()
55+
assert fetcher.fetch(f"file:{notes}") is None
56+
assert ReferenceFetcher(config).fetch(f"file:{notes}") is None
57+
58+
59+
def test_relative_and_absolute_ids_share_one_entry(config, notes):
60+
fetcher = ReferenceFetcher(config)
61+
relative = fetcher.fetch("file:notes.md")
62+
absolute = fetcher.fetch(f"file:{notes}")
63+
assert relative.content == absolute.content == "version one"
64+
assert relative.reference_id == absolute.reference_id == f"file:{notes}"
65+
assert fetcher.get_cache_path("file:notes.md") == fetcher.get_cache_path(f"file:{notes}")
66+
assert fetcher.get_cache_path("file:./notes.md") == fetcher.get_cache_path(f"file:{notes}")
67+
assert [p.name for p in config.cache_dir.glob("*.md")] == [
68+
fetcher.get_cache_path(f"file:{notes}").name
69+
]
70+
71+
72+
def test_relative_id_normalizes_to_the_absolute_path(config, notes):
73+
fetcher = ReferenceFetcher(config)
74+
assert fetcher.normalize_reference_id("file:./notes.md") == f"file:{notes}"
75+
assert fetcher.normalize_reference_id("file:sub/../notes.md") == f"file:{notes}"
76+
77+
78+
def test_relative_fetch_sees_an_edit(config, notes):
79+
fetcher = ReferenceFetcher(config)
80+
assert fetcher.fetch("file:notes.md").content == "version one"
81+
notes.write_text("version two", encoding="utf-8")
82+
assert fetcher.fetch(f"file:{notes}").content == "version two"
83+
assert ReferenceFetcher(config).fetch("file:notes.md").content == "version two"
84+
85+
86+
def test_svg_figure_sees_an_edit(config):
87+
config.reference_base_dir.mkdir()
88+
figure = config.reference_base_dir / "fig.svg"
89+
figure.write_text(svg("PTEN"), encoding="utf-8")
90+
fetcher = ReferenceFetcher(config)
91+
assert fetcher.fetch("file:fig.svg").content == "PTEN"
92+
figure.write_text(svg("AKT"), encoding="utf-8")
93+
assert fetcher.fetch("file:fig.svg").content == "AKT"
94+
assert ReferenceFetcher(config).fetch(f"file:{figure}").content == "AKT"
95+
assert len(list(config.cache_dir.glob("*.md"))) == 1
96+
97+
98+
def test_unchanged_file_is_written_once(config, notes, mocker):
99+
fetcher = ReferenceFetcher(config)
100+
save = mocker.spy(fetcher, "_save_to_disk")
101+
for _ in range(3):
102+
assert fetcher.fetch("file:notes.md").content == "version one"
103+
assert save.call_count == 1
104+
notes.write_text("version two", encoding="utf-8")
105+
assert fetcher.fetch("file:notes.md").content == "version two"
106+
assert save.call_count == 2
107+
assert "version two" in fetcher.get_cache_path("file:notes.md").read_text()
108+
109+
110+
def test_symlink_keeps_the_path_as_written(config, notes):
111+
current = config.reference_base_dir / "current.md"
112+
current.symlink_to(notes)
113+
fetcher = ReferenceFetcher(config)
114+
ref = fetcher.fetch("file:current.md")
115+
assert ref.content == "version one"
116+
assert ref.reference_id == f"file:{current}"
117+
other = config.reference_base_dir / "other.md"
118+
other.write_text("other version", encoding="utf-8")
119+
current.unlink()
120+
current.symlink_to(other)
121+
assert fetcher.fetch("file:current.md").content == "other version"
122+
assert len(list(config.cache_dir.glob("*.md"))) == 1
123+
124+
125+
def test_forced_refresh_of_a_deleted_file_finds_nothing(config, notes):
126+
fetcher = ReferenceFetcher(config)
127+
assert fetcher.fetch(f"file:{notes}") is not None
128+
notes.unlink()
129+
outcome = fetcher.fetch_with_provenance(f"file:{notes}", force_refresh=True)
130+
assert outcome.content is None
131+
assert not outcome.served_stale

0 commit comments

Comments
 (0)