diff --git a/changelog.d/lazy-macro-cache.fixed.md b/changelog.d/lazy-macro-cache.fixed.md new file mode 100644 index 00000000..f7b31929 --- /dev/null +++ b/changelog.d/lazy-macro-cache.fixed.md @@ -0,0 +1 @@ +Avoid constructing macro-cache metadata during calculations when macro-cache reads are disabled. diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index e221c904..eacf415c 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -707,11 +707,10 @@ def _calculate(self, variable_name: str, period: Period = None) -> ArrayLike: if cached_array is not None: return cached_array - smc = SimulationMacroCache(self.tax_benefit_system) - # Check if cache can be used, if available, check if path exists is_cache_available = self.check_macro_cache(variable_name, str(period)) if is_cache_available: + smc = SimulationMacroCache(self.tax_benefit_system) smc.set_cache_path( self.dataset.file_path.parent, self.dataset.name, diff --git a/tests/core/test_simulations.py b/tests/core/test_simulations.py index c6cf3140..ba85f0e8 100644 --- a/tests/core/test_simulations.py +++ b/tests/core/test_simulations.py @@ -1,5 +1,6 @@ from policyengine_core.country_template.situation_examples import single from policyengine_core.simulations import SimulationBuilder +import policyengine_core.simulations.simulation as simulation_module from policyengine_core.simulations.simulation_macro_cache import ( SimulationMacroCache, ) @@ -90,3 +91,24 @@ def test_macro_cache(tax_benefit_system): ) cache.clear_cache(cache.cache_folder_path) assert not cache.cache_folder_path.exists() + + +def test_calculate_without_macro_cache_does_not_build_macro_cache( + tax_benefit_system, monkeypatch +): + class UnexpectedSimulationMacroCache: + def __init__(self, tax_benefit_system): + raise AssertionError( + "SimulationMacroCache should not be constructed when " + "macro cache reads are disabled" + ) + + monkeypatch.setattr( + simulation_module, + "SimulationMacroCache", + UnexpectedSimulationMacroCache, + ) + + simulation = SimulationBuilder().build_default_simulation(tax_benefit_system) + + simulation.calculate("income_tax", "2017-01")