From eef13547e1589e68e41936b5db85dbbaefb60ef0 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 04:27:28 +0100 Subject: [PATCH] refactor: share one derived-view cache --- scripts/core/memo.py | 34 ++++++++++++++++++++++++++++++++++ scripts/model/database.py | 26 ++++++++++++-------------- scripts/resolve/collisions.py | 14 ++------------ scripts/resolve/localfile.py | 20 ++++++-------------- scripts/resolve/ownership.py | 26 +++++++++++--------------- scripts/sitegen/render.py | 24 +++++++++++------------- tests/test_casefold_cache.py | 4 ++-- tests/test_site_render.py | 3 +-- 8 files changed, 79 insertions(+), 72 deletions(-) create mode 100644 scripts/core/memo.py diff --git a/scripts/core/memo.py b/scripts/core/memo.py new file mode 100644 index 000000000..8b2589868 --- /dev/null +++ b/scripts/core/memo.py @@ -0,0 +1,34 @@ +"""A view derived from a dict, built once and rebuilt when the dict changes.""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any, Generic, TypeVar + +T = TypeVar("T") + + +class DerivedView(Generic[T]): + """One slot: the dict a view was built from, its size then, and the view. + + The dict itself is held, never its id(): a database freed and replaced + by another at the same address got the old view back, answering from a + collection that no longer existed. A size change rebuilds too, for a + dict grown in place. Arguments after the dict reach `build` and are not + part of the key. + """ + + def __init__(self, build: Callable[..., T]) -> None: + self._build = build + self._slot: tuple[dict, int, T] | None = None + + def __call__(self, source: dict, *extra: Any) -> T: + slot = self._slot + if slot is not None and slot[0] is source and slot[1] == len(source): + return slot[2] + view = self._build(source, *extra) + self._slot = (source, len(source), view) + return view + + def clear(self) -> None: + self._slot = None diff --git a/scripts/model/database.py b/scripts/model/database.py index d7307cdc4..95f88b346 100644 --- a/scripts/model/database.py +++ b/scripts/model/database.py @@ -7,6 +7,7 @@ import os from pathlib import Path from core.cli import InputMissing +from core.memo import DerivedView from core.paths import REPO_ROOT @@ -48,24 +49,21 @@ def load_database(db_path: str) -> dict: ) from None -# One slot: the files dict, its size, and path -> (sha1, record) built from it. -_PATH_INDEX: list[tuple[dict, int, dict[str, tuple[str, dict]]]] = [] - - -def _path_index(db: dict) -> dict[str, tuple[str, dict]]: - """Normalized path -> (sha1, record), built once per database.""" - files = db.get("files", {}) - if _PATH_INDEX: - cached, size, index = _PATH_INDEX[0] - if cached is files and size == len(files): - return index - index = { +def _index_paths(files: dict) -> dict[str, tuple[str, dict]]: + """Normalized path -> (sha1, record).""" + return { os.path.normpath(record["path"]): (sha1, record) for sha1, record in files.items() if record.get("path") } - _PATH_INDEX[:] = [(files, len(files), index)] - return index + + +_path_view = DerivedView(_index_paths) + + +def _path_index(db: dict) -> dict[str, tuple[str, dict]]: + """Normalized path -> (sha1, record), built once per database.""" + return _path_view(db.get("files", {})) def record_at(db: dict, path: str | None) -> dict | None: diff --git a/scripts/resolve/collisions.py b/scripts/resolve/collisions.py index 7e1d28592..49a1deb39 100644 --- a/scripts/resolve/collisions.py +++ b/scripts/resolve/collisions.py @@ -119,22 +119,12 @@ def _declared_hashes(entry: dict, field_name: str) -> set[str]: return set(parse_hash_list(entry.get(field_name))) -def _record_at(path: str, db: dict) -> dict | None: - """The database record stored at path, from an index built once per db. - - A scan of db['files'] on every call was O(calls x 19 000 files) on the - path verify --all and slots.py both take. The index is the pack - resolver's, so one run holds one copy of it. - """ - return record_at(db, path) - - def content_sha1(path: str, db: dict) -> str | None: """The sha1 of the file at path, from the database or read from disk. A data directory cache is not in the database, so its files are hashed. """ - record = _record_at(path, db) + record = record_at(db, path) if record is not None: return record.get("sha1") if not os.path.isfile(path): @@ -144,7 +134,7 @@ def content_sha1(path: str, db: dict) -> str | None: def accepted_by_all(path: str, entries: list[dict], db: dict) -> bool: """Whether every declaration's own hashes accept the file at path.""" - record = _record_at(path, db) + record = record_at(db, path) if record is None: return False for entry in entries: diff --git a/scripts/resolve/localfile.py b/scripts/resolve/localfile.py index a485b9355..a3ceb948f 100644 --- a/scripts/resolve/localfile.py +++ b/scripts/resolve/localfile.py @@ -11,6 +11,7 @@ from dataclasses import dataclass from typing import Any from core.hashing import cut_md5_owner, md5_composite, parse_md5_list +from core.memo import DerivedView from core.ziptools import check_inside_zip from model.database import get_mame_clone_map from model.profiles import CONTENT_CHECKS @@ -41,26 +42,17 @@ from resolve.ownership import ( ) -# One slot: the dict it was built from, its size then, and the folded view. -# Keyed by id() alone, a database freed and replaced by another at the same -# address got the old index back, and the case-insensitive step answered from -# a collection that no longer existed. -_casefold_index_cache: list[tuple[dict, int, dict[str, list[str]]]] = [] - - -def _casefold_name_index(by_name: dict) -> dict[str, list[str]]: - """Build (and cache) a casefolded view of the by_name index.""" - if _casefold_index_cache: - source, size, cached = _casefold_index_cache[0] - if source is by_name and size == len(by_name): - return cached +def _fold_names(by_name: dict) -> dict[str, list[str]]: + """A casefolded view of the by_name index.""" folded: dict[str, list[str]] = {} for name, sha1s in by_name.items(): folded.setdefault(name.casefold(), []).extend(sha1s) - _casefold_index_cache[:] = [(by_name, len(by_name), folded)] return folded +_casefold_name_index = DerivedView(_fold_names) + + HASH_EXACT_RESOLUTION_STATUSES = frozenset( { "sha1_exact", diff --git a/scripts/resolve/ownership.py b/scripts/resolve/ownership.py index 35cca5a71..6c8d8712f 100644 --- a/scripts/resolve/ownership.py +++ b/scripts/resolve/ownership.py @@ -4,6 +4,7 @@ from __future__ import annotations import re +from core.memo import DerivedView from model.collection import manufacturer_slug @@ -33,26 +34,21 @@ def maker_of_relative(relative: str) -> str | None: return parts[0] if len(parts) >= 2 else None -# One slot, keyed like the casefold view: the files dict, its size, the folders. -_maker_folders_cache: list[tuple[dict, int, frozenset[str]]] = [] - - -def _maker_folders(db: dict) -> frozenset[str]: - """Every maker folder the collection files a copy under.""" - files_db = db.get("files", {}) - if _maker_folders_cache: - source, size, folders = _maker_folders_cache[0] - if source is files_db and size == len(files_db): - return folders - bios_dir = str(db.get("bios_dir") or "bios") - folders = frozenset( +def _filed_maker_folders(files_db: dict, bios_dir: str) -> frozenset[str]: + return frozenset( folder for entry in files_db.values() if (folder := maker_folder(str(entry.get("path", "")), bios_dir)) and folder not in BUCKET_FOLDERS ) - _maker_folders_cache[:] = [(files_db, len(files_db), folders)] - return folders + + +_maker_folders_view = DerivedView(_filed_maker_folders) + + +def _maker_folders(db: dict) -> frozenset[str]: + """Every maker folder the collection files a copy under.""" + return _maker_folders_view(db.get("files", {}), str(db.get("bios_dir") or "bios")) def system_makers(file_entry: dict, db: dict) -> frozenset[str]: diff --git a/scripts/sitegen/render.py b/scripts/sitegen/render.py index db27b346d..588a5dd14 100644 --- a/scripts/sitegen/render.py +++ b/scripts/sitegen/render.py @@ -9,6 +9,7 @@ from collections.abc import Callable from model.database import load_database from model import siteinputs from sitegen import markup +from core.memo import DerivedView from core.paths import REPO_ROOT from model.collection import PROGRAM_TOPS, card_moves, manufacturer_slug from model.systemnames import ( @@ -361,22 +362,19 @@ def _in_arcade(sha1: str, db: dict) -> bool: return sha1 in _arcade_suffix_sha1s(db) -_suffix_cache: list[tuple[dict, frozenset[str]] | None] = [None] +def _arcade_tails(by_path_suffix: dict) -> frozenset[str]: + return frozenset( + sha1s[0] + for tail, sha1s in by_path_suffix.items() + if tail.startswith("Arcade/") and len(sha1s) == 1 + ) + + +_arcade_suffixes = DerivedView(_arcade_tails) def _arcade_suffix_sha1s(db: dict) -> frozenset[str]: - # Holding the database itself, never id(db): a database freed and - # replaced at the same address answered with the first one's set. - cached = _suffix_cache[0] - if cached is not None and cached[0] is db: - return cached[1] - found = frozenset( - sha1s[0] - for tail, sha1s in db.get("indexes", {}).get("by_path_suffix", {}).items() - if tail.startswith("Arcade/") and len(sha1s) == 1 - ) - _suffix_cache[0] = (db, found) - return found + return _arcade_suffixes(db.get("indexes", {}).get("by_path_suffix", {})) def _build_boards() -> None: diff --git a/tests/test_casefold_cache.py b/tests/test_casefold_cache.py index 950d9eaba..269cd36fa 100644 --- a/tests/test_casefold_cache.py +++ b/tests/test_casefold_cache.py @@ -54,9 +54,9 @@ class APrimaryUnderAnotherCasing(unittest.TestCase): self.by_name.setdefault(name, []).append(sha1) def _resolve(self, name: str) -> str: - from resolve.localfile import _casefold_index_cache, resolve_local_file + from resolve.localfile import _casefold_name_index, resolve_local_file - _casefold_index_cache.clear() + _casefold_name_index.clear() db = {"files": self.files, "indexes": {"by_name": self.by_name, "by_md5": {}, "by_path_suffix": {}, "by_crc32": {}}} path, _status = resolve_local_file({"name": name}, db) diff --git a/tests/test_site_render.py b/tests/test_site_render.py index e42b7d06f..dbbe31b00 100644 --- a/tests/test_site_render.py +++ b/tests/test_site_render.py @@ -560,8 +560,7 @@ class TheArcadeCacheHoldsItsDatabase(unittest.TestCase): return {"files": {}, "indexes": {"by_path_suffix": {"Arcade/x.zip": [sha1]}}} def test_a_new_database_at_a_reused_address_is_read_again(self): - saved = siterender._suffix_cache[0] - self.addCleanup(siterender._suffix_cache.__setitem__, 0, saved) + self.addCleanup(siterender._arcade_suffixes.clear) first = self._db("a" * 40) self.assertTrue(siterender._in_arcade("a" * 40, first)) address = id(first)