fix: record a data tree's version beside its cache

This commit is contained in:
Abdessamad Derraz committed 2026-11-24 01:14:04 +01:00
1 parent 8ac5cc348b
commit dfc1860d0d
9 files changed
+105 -58

No files matched your search

+8 -2
View File
@@ -88,10 +88,16 @@ def list_release_pack_platforms(platforms_dir: str = PLATFORMS_DIR) -> list[str]
]
VERSIONS_FILE = "data/.versions.json"
def versions_file_for(entry: dict) -> Path:
"""Where refresh_data_dirs records a tree's last fetch: beside its cache.
The writer and every reader take it from the entry, so a registry whose
caches sit elsewhere than data/ keeps its records with its trees.
"""
return Path(entry["local_cache"]).parent / ".versions.json"
def load_versions(versions_path: str | os.PathLike[str] = VERSIONS_FILE) -> dict[str, dict]:
def load_versions(versions_path: str | os.PathLike[str]) -> dict[str, dict]:
"""What refresh_data_dirs recorded of each tree's last fetch."""
path = Path(versions_path)
if not path.is_file():
+18 -24
View File
@@ -18,7 +18,7 @@ from pathlib import Path
from core import upstream
from core.artifacts import file_lock as _file_lock, write_text_atomic
from core.upstream import remote_etag as _get_remote_etag
from model.registry import VERSIONS_FILE, load_versions
from model.registry import load_versions, versions_file_for
from packs.datadirextract import extract_tar_subtree, extract_zip_tree
@@ -113,9 +113,7 @@ def hold_data_dirs(stack: contextlib.ExitStack, registry: dict) -> None:
stack.enter_context(cache_lock(cache, shared=True))
def _save_versions(
versions: dict[str, dict], versions_path: str = VERSIONS_FILE
) -> None:
def _save_versions(versions: dict[str, dict], versions_path: str | Path) -> None:
"""Write the version file whole or not at all.
Truncating in place let a concurrent reader load an empty file and die
@@ -125,7 +123,7 @@ def _save_versions(
write_text_atomic(versions_path, json.dumps(versions, indent=2, sort_keys=True) + "\n")
def _record_version(key: str, record: dict, versions_path: str) -> None:
def _record_version(key: str, record: dict, versions_path: str | Path) -> None:
"""Set one key under the file lock, so two writers keep both updates."""
path = Path(versions_path)
with _file_lock(path.with_name(f".{path.name}.lock")):
@@ -296,16 +294,16 @@ def _measure_archive(source_url: str) -> int | None:
return size or None
def _record_archive_size(key: str, entry: dict, versions_path: str) -> None:
def _record_archive_size(key: str, entry: dict) -> None:
"""Record the archive size of a tree current since before it was kept.
The installer announces a tree's download as that size: a tarball
whose tree is 10 KB is a download of 21 MB. Measured, not refetched,
so the tree the packs carry stays the one recorded.
"""
path = Path(versions_path)
path = versions_file_for(entry)
with _file_lock(path.with_name(f".{path.name}.lock")):
versions = load_versions(versions_path)
versions = load_versions(path)
record = versions.get(key)
if record is None or "archive_size" in record:
return
@@ -317,10 +315,10 @@ def _record_archive_size(key: str, entry: dict, versions_path: str) -> None:
if size is None:
return
with _file_lock(path.with_name(f".{path.name}.lock")):
versions = load_versions(versions_path)
versions = load_versions(path)
if key in versions and "archive_size" not in versions[key]:
versions[key]["archive_size"] = size
_save_versions(versions, versions_path)
_save_versions(versions, path)
log.info("[%s] archive size recorded: %d bytes", key, size)
@@ -338,7 +336,6 @@ def refresh_entry(
*,
force: bool = False,
dry_run: bool = False,
versions_path: str = VERSIONS_FILE,
) -> bool | None:
"""Refresh a single data directory entry.
@@ -353,17 +350,17 @@ def refresh_entry(
it, and only a tree to replace waits.
"""
if dry_run:
return _refresh_entry(key, entry, force, dry_run, versions_path)
return _refresh_entry(key, entry, force, dry_run)
if not force:
needs, _remote, cached_tag = _decide(key, entry, False, versions_path)
needs, _remote, cached_tag = _decide(key, entry, False)
if needs is None:
return None
if not needs:
log.info("[%s] up to date (tag: %s)", key, _short_tag(cached_tag))
_record_archive_size(key, entry, versions_path)
_record_archive_size(key, entry)
return False
with cache_lock(entry["local_cache"]):
return _refresh_entry(key, entry, force, dry_run, versions_path)
return _refresh_entry(key, entry, force, dry_run)
def _remote_tag(entry: dict, version: str) -> str | None:
@@ -375,12 +372,12 @@ def _remote_tag(entry: dict, version: str) -> str | None:
def _decide(
key: str, entry: dict, force: bool, versions_path: str
key: str, entry: dict, force: bool
) -> tuple[bool | None, str | None, str | None]:
"""(whether the tree needs a refresh, the remote tag read, the recorded
tag). None when the remote could not be read."""
version = entry.get("version", "master")
cached = load_versions(versions_path).get(key, {})
cached = load_versions(versions_file_for(entry)).get(key, {})
cached_tag = cached.get("sha") or cached.get("etag")
if force or not Path(entry["local_cache"]).exists():
return True, None, cached_tag
@@ -392,7 +389,7 @@ def _decide(
def _refresh_entry(
key: str, entry: dict, force: bool, dry_run: bool, versions_path: str
key: str, entry: dict, force: bool, dry_run: bool
) -> bool | None:
source_type = entry.get("source_type", "tarball")
version = entry.get("version", "master")
@@ -400,7 +397,7 @@ def _refresh_entry(
local_cache = entry["local_cache"]
exclude = entry.get("exclude", [])
needs_refresh, remote_tag, cached_tag = _decide(key, entry, force, versions_path)
needs_refresh, remote_tag, cached_tag = _decide(key, entry, force)
if needs_refresh is None:
return None
if not needs_refresh:
@@ -464,7 +461,7 @@ def _refresh_entry(
record = {"sha": remote_tag or "", "version": version}
if archive_sizes:
record["archive_size"] = archive_sizes[-1]
_record_version(key, record, versions_path)
_record_version(key, record, versions_file_for(entry))
log.info("[%s] refreshed: %d files extracted to %s", key, file_count, local_cache)
return True
@@ -475,7 +472,6 @@ def refresh_all(
*,
force: bool = False,
dry_run: bool = False,
versions_path: str = VERSIONS_FILE,
platform: str | None = None,
) -> dict[str, bool | None]:
"""Refresh all entries in the registry.
@@ -497,7 +493,6 @@ def refresh_all(
entry,
force=force,
dry_run=dry_run,
versions_path=versions_path,
)
if any(results.values()):
# A cache the resolver indexed in this process has changed under it.
@@ -512,7 +507,6 @@ def refresh_keys(
keys: list[str],
*,
force: bool = False,
versions_path: str = VERSIONS_FILE,
) -> list[str]:
"""Refresh the named entries of a registry and return the keys whose
refresh failed."""
@@ -520,7 +514,7 @@ def refresh_keys(
refreshed = False
for key in keys:
log.info("refreshing %s ...", key)
outcome = refresh_entry(key, registry[key], force=force, versions_path=versions_path)
outcome = refresh_entry(key, registry[key], force=force)
if outcome is None:
log.error("refresh of %s failed", key)
failed.append(key)
+3 -5
View File
@@ -6,13 +6,12 @@ import os
import re
import zipfile
from collections.abc import Iterable, Iterator
from pathlib import Path
from typing import TYPE_CHECKING, TypedDict
from core.hashing import compute_hashes
from core.options import reject_unknown
from model.declarations import declared_root
from model.registry import load_versions
from model.registry import load_versions, versions_file_for
from model.profiles import entry_system_ids, installed_data_refs_in
from model.systems import norm_system_id
from packs.archive import PackRecord, Placed, add_pack_member
@@ -380,10 +379,9 @@ def _tree_group(
def _recorded_version(ref: str, entry: dict, versions: dict[str, dict[str, dict]]) -> dict:
"""What refresh_data_dirs recorded of the tree's last fetch, read once
per .versions.json."""
cache = entry.get("local_cache")
if not cache:
if not entry.get("local_cache"):
return {}
recorded = Path(cache).parent / ".versions.json"
recorded = versions_file_for(entry)
if str(recorded) not in versions:
versions[str(recorded)] = load_versions(recorded)
found = versions[str(recorded)].get(ref)
+10 -3
View File
@@ -8,7 +8,7 @@ import urllib.parse
from core.upstream import remote_etag as get_remote_etag
from core.paths import DATA_DIRS_FILE
from model.registry import data_dir_registry_at, load_versions
from model.registry import data_dir_registry_at, load_versions, versions_file_for
from .base_scraper import fetch_text
@@ -50,7 +50,14 @@ def check(registry_path: str = DATA_DIRS_FILE) -> dict:
return {"error": str(exc), "entries": []}
tracked = load_tracked_entries(registry_path)
versions = load_versions()
registry = data_dir_registry_at(registry_path, required=True)
version_files: dict = {}
def stored_etag(key: str) -> str:
path = versions_file_for(registry[key])
if path not in version_files:
version_files[path] = load_versions(path)
return version_files[path].get(key, {}).get("sha", "")
buildbot_set = set(index_zips)
tracked_set = set(tracked.keys())
@@ -63,7 +70,7 @@ def check(registry_path: str = DATA_DIRS_FILE) -> dict:
for z in sorted(tracked_set & buildbot_set):
key, url = tracked[z]
stored = versions.get(key, {}).get("sha", "")
stored = stored_etag(key)
remote = get_remote_etag(url)
if remote is None:
status = "UNKNOWN"
+3 -3
View File
@@ -377,11 +377,11 @@ def _write_platform_pages(run: _SiteRun) -> dict[str, str]:
return published_parts
def _record_data_trees(profiles: dict, pages: PageRegistry) -> None:
def _record_data_trees(profiles: dict, data_registry: dict, pages: PageRegistry) -> None:
"""Record in ``pages`` the data directories: their members, revisions
and readers, and the pages their member lists go to."""
pages.data_members.update(data_directory_members())
pages.data_revisions.update(data_directory_revisions())
pages.data_revisions.update(data_directory_revisions(data_registry))
for key in sorted(profiles):
if not is_emulator(profiles[key]):
continue
@@ -400,7 +400,7 @@ def _write_emulator_pages(run: _SiteRun) -> None:
profiles = run.profiles
print("Generating emulator pages...")
run.pages.emulator_setups.update(emulator_setups(run.coverages, profiles))
_record_data_trees(profiles, run.pages)
_record_data_trees(profiles, run.data_registry, run.pages)
write_if_changed(
str(run.docs / "emulators" / "index.md"), generate_emulators_index(profiles)
)
+5 -3
View File
@@ -14,7 +14,7 @@ from model import siteinputs
from model.largefiles import LARGE_FILES_CACHE
from model.platforms import load_platform_config
from model.profiles import load_emulator_profiles
from model.registry import VERSIONS_FILE
from model.registry import load_data_dir_registry, versions_file_for
from packs.coverage import verify_platform
from packs.shares import core_shares
from packs.verdicts import blocking_missing
@@ -128,8 +128,10 @@ def _coverage_inputs(db_path: Path, platforms_dir: str, emulators_dir: str) -> s
(REPO_ROOT / "recipes", "*.json")):
for path in sorted(p for p in root.resolve().rglob(pattern) if p.is_file()):
add_file(path)
for path in (REPO_ROOT / ".gitignore", REPO_ROOT / "_mame_clones.json",
REPO_ROOT / VERSIONS_FILE):
revisions = sorted({REPO_ROOT / versions_file_for(entry)
for entry in load_data_dir_registry(platforms_dir).values()
if entry.get("local_cache")})
for path in (REPO_ROOT / ".gitignore", REPO_ROOT / "_mame_clones.json", *revisions):
add_file(path)
digest.update(b"offline\0" + (b"1" if run_is_offline() else b"0") + b"\n")
large = Path(LARGE_FILES_CACHE).resolve()
+15 -4
View File
@@ -12,7 +12,7 @@ from pathlib import Path
from core.hashing import declared_hash_lists
from model import siteinputs
from model.collection import manufacturer_slug
from model.registry import load_versions
from model.registry import load_versions, versions_file_for
from model.systemnames import system_name
from model.profiles import is_emulator
from packs.consumers import FileConsumers
@@ -125,9 +125,20 @@ def data_directory_members(install_dir: Path | None = None) -> dict[str, dict[st
return members
def data_directory_revisions(data_dir: Path = REPO_ROOT / "data") -> dict[str, dict]:
"""The revision each data directory was fetched at, as refresh_data_dirs records it."""
return load_versions(data_dir / ".versions.json")
def data_directory_revisions(data_registry: dict[str, dict]) -> dict[str, dict]:
"""The revision each data directory was fetched at, as refresh_data_dirs
records it beside the tree."""
files: dict[Path, dict[str, dict]] = {}
revisions: dict[str, dict] = {}
for ref, entry in data_registry.items():
if not entry.get("local_cache"):
continue
path = REPO_ROOT / versions_file_for(entry)
if path not in files:
files[path] = load_versions(path)
if ref in files[path]:
revisions[ref] = files[path][ref]
return revisions
_GIT_COMMIT = re.compile(r"[0-9a-f]{40}")
+40 -10
View File
@@ -103,7 +103,7 @@ class RefreshConcurrency(unittest.TestCase):
with mock.patch.object(datadirs.urllib.request, "urlopen", fake_urlopen), \
mock.patch.object(datadirs, "_get_remote_etag", return_value="e1"):
self.assertTrue(
datadirs.refresh_entry("pak", entry, force=True, versions_path=self.versions)
datadirs.refresh_entry("pak", entry, force=True)
)
self.assertEqual(seen, [True])
@@ -117,12 +117,12 @@ class RefreshConcurrency(unittest.TestCase):
with mock.patch.object(datadirs.urllib.request, "urlopen",
lambda *a, **k: _Response(payload)), \
mock.patch.object(datadirs, "_get_remote_etag", return_value="e1"):
self.assertTrue(datadirs.refresh_entry("pak", entry, versions_path=self.versions))
self.assertTrue(datadirs.refresh_entry("pak", entry))
self.assertEqual(load_versions(self.versions)["pak"]["archive_size"],
len(payload))
datadirs._record_version("pak", {"sha": "e1"}, self.versions)
(self.cache / "a.bin").write_bytes(b"kept")
self.assertFalse(datadirs.refresh_entry("pak", entry, versions_path=self.versions))
self.assertFalse(datadirs.refresh_entry("pak", entry))
self.assertEqual(load_versions(self.versions)["pak"],
{"sha": "e1", "archive_size": len(payload)})
self.assertEqual((self.cache / "a.bin").read_bytes(), b"kept")
@@ -142,7 +142,7 @@ class RefreshConcurrency(unittest.TestCase):
mock.patch.object(datadirs, "_get_remote_etag", return_value="e1"):
fcntl.flock(reader, fcntl.LOCK_SH)
worker = threading.Thread(target=lambda: result.append(
datadirs.refresh_entry("pak", entry, versions_path=self.versions)
datadirs.refresh_entry("pak", entry)
), daemon=True)
worker.start()
worker.join(timeout=20)
@@ -291,14 +291,14 @@ class DryRunReport(unittest.TestCase):
def test_the_remote_tag_is_shown_beside_the_cached_one(self):
with tempfile.TemporaryDirectory() as tmp:
versions = Path(tmp) / "versions.json"
versions = Path(tmp) / ".versions.json"
versions.write_text(json.dumps({"k": {"etag": '"2725165595"', "archive_size": 1}}))
(Path(tmp) / "k").mkdir()
entry = {"source_type": "zip", "source_url": "https://x.invalid/a.zip",
"local_cache": tmp}
"local_cache": str(Path(tmp) / "k")}
with mock.patch.object(datadirs, "_get_remote_etag", return_value='"2685251384"'), \
self.assertLogs(datadirs.log, "INFO") as logs:
self.assertTrue(datadirs.refresh_entry("k", entry, dry_run=True,
versions_path=str(versions)))
self.assertTrue(datadirs.refresh_entry("k", entry, dry_run=True))
self.assertIn("cached: 2725165595, remote: 2685251384", logs.output[0])
def test_a_run_ends_on_its_counts(self):
@@ -394,12 +394,42 @@ class ASourceThatMovesIsPinnedOrFollowed(unittest.TestCase):
mock.patch.object(datadirs, "_get_remote_etag",
side_effect=AssertionError("an ETag for a revision")), \
mock.patch.object(datadirs, "_download_and_extract_zip", extract):
self.assertTrue(datadirs.refresh_entry("r", entry, force=True,
versions_path=versions))
self.assertTrue(datadirs.refresh_entry("r", entry, force=True))
self.assertEqual(fetched, [f"https://github.com/o/r/archive/{self.COMMIT}.zip"])
self.assertEqual(load_versions(versions)["r"],
{"sha": self.COMMIT, "version": "master"})
def test_the_record_lives_beside_the_tree(self):
"""A registry whose caches sit outside data/ wrote their commits to
./data/.versions.json: the manifest read nothing beside the tree and
listed the branch by name, and the real data/ tree of the same key
was recorded at a commit it did not hold."""
from packs.datatrees import manifest_data_directories
from sitegen.lookup import data_directory_revisions
with tempfile.TemporaryDirectory() as tmp:
cache = Path(tmp) / "x" / "data" / "r"
entry = {"source_type": "zip", "version": "master",
"source_url": "https://github.com/o/r/archive/{version}.zip",
"local_cache": str(cache)}
def extract(url, local_cache, *args, **kwargs):
Path(local_cache).mkdir(parents=True)
(Path(local_cache) / "a.bin").write_bytes(b"abc")
return 1
with mock.patch.object(datadirs, "get_remote_sha", return_value=self.COMMIT), \
mock.patch.object(datadirs, "_download_and_extract_zip", extract):
self.assertTrue(datadirs.refresh_entry("r", entry, force=True))
self.assertEqual(load_versions(cache.parent / ".versions.json")["r"]["sha"],
self.COMMIT)
listed = manifest_data_directories(
[(str(cache / "a.bin"), "r/a.bin")], {"r/a.bin": ("r", ("s",), "r", True)},
{"r": entry}, "")
self.assertEqual(data_directory_revisions({"r": entry})["r"]["sha"], self.COMMIT)
self.assertEqual(listed[0]["url"], f"https://github.com/o/r/archive/{self.COMMIT}.zip")
self.assertNotIn("rolling", listed[0])
def test_every_forge_source_takes_a_commit(self):
"""archive/refs/heads/<commit> is no address: a forge source must be
written so the commit the refresh reads can replace its branch."""
+3 -4
View File
@@ -283,12 +283,12 @@ class TheVersionIsReadBeforeTheDownload(unittest.TestCase):
state["downloaded"] = True
return 3
versions = root / "versions.json"
versions = root / ".versions.json"
entry = {"source_type": "zip", "source_url": "https://example.invalid/Sys.zip",
"local_cache": str(root / "cache")}
with mock.patch.object(datadirs, "_get_remote_etag", etag), \
mock.patch.object(datadirs, "_download_and_extract_zip", download):
self.assertTrue(datadirs._refresh_entry("sys", entry, True, False, str(versions)))
self.assertTrue(datadirs._refresh_entry("sys", entry, True, False))
self.assertEqual(json.loads(versions.read_text())["sys"]["sha"], "build-1")
@@ -299,7 +299,6 @@ class ABadResponseIsTriedAgain(unittest.TestCase):
def setUp(self) -> None:
root = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, root, True)
self.versions = str(root / "versions.json")
self.entry = {"source_type": "zip", "source_url": "https://example.invalid/S.zip",
"local_cache": str(root / "cache")}
self.waits: list[int] = []
@@ -316,7 +315,7 @@ class ABadResponseIsTriedAgain(unittest.TestCase):
with mock.patch.object(datadirs, "_get_remote_etag", lambda _url: "tag"), \
mock.patch.object(datadirs, "_download_and_extract_zip", download), \
mock.patch.object(datadirs.time, "sleep", self.waits.append):
return datadirs._refresh_entry("s", self.entry, True, False, self.versions)
return datadirs._refresh_entry("s", self.entry, True, False)
def test_a_bad_archive_then_a_good_one_refreshes(self):
self.assertTrue(self.run_with([zipfile.BadZipFile("File is not a zip file"), 12]))