Coverage for execution/config_cache.py: 100%

17 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Mtime-gated read cache for config.json, shared by the per-bar/per-poll 

2config readers (risk/manual_override.py, execution/paper_readiness_io.py, 

3execution/runtime_config_io.py) that are all called far more often than 

4config.json actually changes - once per bar in a Lean backtest, once per 

5poll-loop iteration in retraining/worker.py. 

6 

7The check-cadence in those callers is correct by design (see 

8main.py::_refresh_risk_state()'s own comments) - this module only removes 

9the redundant open()+json.load() cost of reading a file that, in practice, 

10almost never changes between calls. 

11""" 

12 

13from __future__ import annotations 

14 

15from collections.abc import Callable 

16from pathlib import Path 

17from typing import TypeVar 

18 

19T = TypeVar("T") 

20 

21# Keyed by (config_path, loader), not just config_path - multiple distinct 

22# readers (read_manual_trade_lock_override, read_paper_trading_config, 

23# read_runtime_mode) all read the same config.json path with different 

24# loaders. Keying by path alone would let one reader's cached value leak 

25# into another reader's result whenever both are called in the same bar 

26# with the file's mtime unchanged in between - caught via a real Lean 

27# backtest run, not a unit test (each reader's tests use their own 

28# isolated tmp_path with only one loader ever touching it). 

29_cache: dict[tuple[Path, Callable], tuple[float, object]] = {} 

30 

31 

32def read_cached(config_path: Path, loader: Callable[[Path], T]) -> T: 

33 """Returns loader(config_path)'s cached result if config_path's mtime 

34 hasn't changed since the last call for this exact (path, loader) pair; 

35 otherwise calls loader fresh and updates the cache. Falls back to 

36 calling loader directly (bypassing the cache) if the file doesn't 

37 exist, preserving loader's own missing-file handling.""" 

38 if not config_path.exists(): 

39 return loader(config_path) 

40 

41 mtime = config_path.stat().st_mtime 

42 cache_key = (config_path, loader) 

43 cached = _cache.get(cache_key) 

44 if cached is not None and cached[0] == mtime: 

45 return cached[1] 

46 

47 value = loader(config_path) 

48 _cache[cache_key] = (mtime, value) 

49 return value