From b504fe5a68c4f7e027d1f6257ced7e73bc0eeb2f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 10:03:01 +0000 Subject: [PATCH] =?UTF-8?q?perf:=20cache=20config=20YAML/JSON=20parsing=20?= =?UTF-8?q?=E2=80=94=20one=20parse=20per=20file=20per=20process=20(#211)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Config.push/register invalidate the lazily-built config dict and prior config, so every library import re-read every config file from disk. autonerves.parse_cache parses each file once, keyed on absolute path and (mtime_ns, size), and returns a deep copy so results equal a fresh parse. Routed through YAMLConfig, JSONPriorConfig.from_directory and Config.logging_config. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016nhQ8NkMVDS9RLqr6FRXye --- autonerves/conf.py | 4 +- autonerves/directory_config.py | 5 +- autonerves/json_prior/config.py | 12 +-- autonerves/parse_cache.py | 67 +++++++++++++ test_autonerves/test_parse_cache.py | 147 ++++++++++++++++++++++++++++ 5 files changed, 224 insertions(+), 11 deletions(-) create mode 100644 autonerves/parse_cache.py create mode 100644 test_autonerves/test_parse_cache.py diff --git a/autonerves/conf.py b/autonerves/conf.py index 550c206..73550ce 100644 --- a/autonerves/conf.py +++ b/autonerves/conf.py @@ -8,6 +8,7 @@ import yaml +from autonerves import parse_cache from autonerves.directory_config import ( RecursiveConfig, PriorConfigWrapper, @@ -168,8 +169,7 @@ def logging_config(self) -> Optional[Dict]: path = config.path try: if LOGGING_CONFIG_FILE in os.listdir(config.path): - with open(path / LOGGING_CONFIG_FILE) as f: - return yaml.safe_load(f) + return parse_cache.load_yaml(path / LOGGING_CONFIG_FILE) except FileNotFoundError: logger.debug(f"No configuration found at path {config.path}") return None diff --git a/autonerves/directory_config.py b/autonerves/directory_config.py index 232af9c..5bfc343 100644 --- a/autonerves/directory_config.py +++ b/autonerves/directory_config.py @@ -5,7 +5,7 @@ import yaml -from autonerves import exc +from autonerves import exc, parse_cache class AbstractConfig(ABC): @@ -70,8 +70,7 @@ def items(self): class YAMLConfig(AbstractConfig): def __init__(self, path): - with open(path) as f: - self._dict = yaml.safe_load(f) + self._dict = parse_cache.load_yaml(path) def _getitem(self, item): value = self._dict[item] diff --git a/autonerves/json_prior/config.py b/autonerves/json_prior/config.py index 0cffaab..ec357bf 100644 --- a/autonerves/json_prior/config.py +++ b/autonerves/json_prior/config.py @@ -7,6 +7,7 @@ import yaml +from autonerves import parse_cache from autonerves.directory_config import family logger = logging.getLogger(__name__) @@ -149,15 +150,14 @@ def from_directory(cls, directory: str) -> "JSONPriorConfig": config_path = Path(directory) - for suffix, parser in [ - ("json", json.load), - ("yaml", yaml.safe_load), - ("yml", yaml.safe_load), + for suffix, load in [ + ("json", parse_cache.load_json), + ("yaml", parse_cache.load_yaml), + ("yml", parse_cache.load_yaml), ]: for file in config_path.rglob(f"*.{suffix}"): parts = file.relative_to(config_path).with_suffix("").parts - with open(file) as f: - config_dict[".".join(parts)] = parser(f) + config_dict[".".join(parts)] = load(file) return JSONPriorConfig(config_dict, directory=directory) diff --git a/autonerves/parse_cache.py b/autonerves/parse_cache.py new file mode 100644 index 0000000..721da47 --- /dev/null +++ b/autonerves/parse_cache.py @@ -0,0 +1,67 @@ +""" +Process-level cache of parsed configuration files. + +``Config.push`` / ``Config.register`` invalidate the lazily-built config +dictionary and prior configuration, so before this cache every library import +re-read every YAML / JSON config file from disk: hundreds of parses per script +run for a few dozen distinct files. + +Each file is parsed at most once per process while it is unchanged on disk. The +cache key is the absolute path and the parser kind; an entry is reused only +while the file's ``st_mtime_ns`` and ``st_size`` match, so editing a file +re-parses it exactly as before. + +Callers get a deep copy of the cached object, so mutating a loaded config can +never leak into a later load — the result is identical to a fresh parse. +""" + +import copy +import json +import os + +import yaml + +_cache = {} + + +def clear(): + """Drop every cached parse.""" + _cache.clear() + + +def _parse_yaml(f): + # Looked up at call time so a hook on ``yaml.safe_load`` sees every real parse. + return yaml.safe_load(f) + + +def _parse_json(f): + return json.load(f) + + +_PARSERS = {"yaml": _parse_yaml, "json": _parse_json} + + +def _load(path, kind): + path = os.path.abspath(os.fspath(path)) + stat = os.stat(path) + signature = (stat.st_mtime_ns, stat.st_size) + key = (path, kind) + + entry = _cache.get(key) + if entry is None or entry[0] != signature: + with open(path) as f: + parsed = _PARSERS[kind](f) + entry = (signature, parsed) + _cache[key] = entry + + return copy.deepcopy(entry[1]) + + +def load_yaml(path): + """The result of ``yaml.safe_load`` on the file at ``path``, parsed once.""" + return _load(path, "yaml") + + +def load_json(path): + """The result of ``json.load`` on the file at ``path``, parsed once.""" + return _load(path, "json") diff --git a/test_autonerves/test_parse_cache.py b/test_autonerves/test_parse_cache.py new file mode 100644 index 0000000..aeba771 --- /dev/null +++ b/test_autonerves/test_parse_cache.py @@ -0,0 +1,147 @@ +""" +The config parse cache (``autonerves.parse_cache``) must be invisible: every +config object built through it compares equal to one built from fresh parses, +while each file is parsed at most once per process. +""" + +import collections +import json +import os +from pathlib import Path + +import pytest +import yaml + +from autonerves import conf, parse_cache +from autonerves.json_prior.config import JSONPriorConfig + +PACKAGE_ROOT = Path(__file__).parent.parent +CONFIG_SUFFIXES = (".yaml", ".yml", ".json", ".ini") + + +def _packaged_config_directories(): + """Every directory in the repo that ships config files (test fixtures included).""" + candidates = sorted((PACKAGE_ROOT / "test_autonerves" / "files").iterdir()) + candidates += sorted(p for p in (PACKAGE_ROOT / "autonerves").iterdir()) + return [ + directory + for directory in candidates + if directory.is_dir() + and any( + f.endswith(CONFIG_SUFFIXES) + for _, _, files in os.walk(directory) + for f in files + ) + ] + + +PACKAGED = _packaged_config_directories() + + +def _plain(value): + if isinstance(value, conf.DictWrapper): + return {key: _plain(item) for key, item in value.items()} + return value + + +def _snapshot(directory): + """Everything a Config over ``directory`` parses, as plain data.""" + config = conf.Config(directory) + priors = JSONPriorConfig.from_directory(Path(directory) / "priors") + return { + "dict": _plain(config.dict), + "priors": priors.obj, + "logging": config.logging_config, + } + + +def _fresh_load(path, kind): + with open(path) as f: + return yaml.safe_load(f) if kind == "yaml" else json.load(f) + + +@pytest.fixture(autouse=True) +def _clear_cache(): + parse_cache.clear() + yield + parse_cache.clear() + + +@pytest.fixture(name="parse_counter") +def make_parse_counter(monkeypatch): + counts = collections.Counter() + original = yaml.safe_load + + def counting_safe_load(stream, *args, **kwargs): + counts[getattr(stream, "name", None)] += 1 + return original(stream, *args, **kwargs) + + monkeypatch.setattr(yaml, "safe_load", counting_safe_load) + return counts + + +def test_packaged_directories_found(): + names = {d.name for d in PACKAGED} + assert {"config", "default", "config_flip"} <= names + + +@pytest.mark.parametrize("directory", PACKAGED, ids=lambda d: d.name) +def test_cached_parse_deep_equals_fresh_parse(directory, monkeypatch): + with monkeypatch.context() as m: + m.setattr(parse_cache, "_load", _fresh_load) + reference = _snapshot(directory) + + cold = _snapshot(directory) + warm = _snapshot(directory) + + assert cold == reference + assert warm == reference + + +def test_each_file_parsed_once_across_pushes(files_directory, parse_counter): + config = conf.Config(files_directory / "default") + for directory in ("config_flip", "config", "default", "config"): + config.push(files_directory / directory) + config.dict + config.prior_config.prior_configs[0].path_value_map + + assert parse_counter + assert max(parse_counter.values()) == 1 + + +def test_returned_objects_are_independent(tmp_path): + path = tmp_path / "general.yaml" + path.write_text("section:\n key: [1, 2]\n") + + first = parse_cache.load_yaml(path) + first["section"]["key"].append(3) + + assert parse_cache.load_yaml(path) == {"section": {"key": [1, 2]}} + + +def test_changed_file_is_reparsed(tmp_path, parse_counter): + path = tmp_path / "general.yaml" + path.write_text("a: 1\n") + assert parse_cache.load_yaml(path) == {"a": 1} + + path.write_text("a: 22\n") + stat = path.stat() + os.utime(path, ns=(stat.st_atime_ns, stat.st_mtime_ns + 10**9)) + + assert parse_cache.load_yaml(path) == {"a": 22} + assert sum(parse_counter.values()) == 2 + + +def test_missing_file_raises_and_is_not_cached(tmp_path): + path = tmp_path / "missing.yaml" + with pytest.raises(FileNotFoundError): + parse_cache.load_yaml(path) + path.write_text("a: 1\n") + assert parse_cache.load_yaml(path) == {"a": 1} + + +def test_json_and_yaml_kinds_are_cached_separately(tmp_path): + path = tmp_path / "both.json" + path.write_text('{"a": 1}') + assert parse_cache.load_json(path) == {"a": 1} + assert parse_cache.load_yaml(path) == {"a": 1}