From 39dc645d4df5ccf04fce980aa2d58ace7dadedb1 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:24:05 +0400 Subject: [PATCH 01/10] Add failing tests for a warm-up calculation in the workers' snapshot hook The simulation workers' snapshot hook will run one calculation of a region group baked into the image, for the first precompute year, so containers restored from the snapshot start with that year's parameter values and SPM amounts built. These tests cover that the hook runs it once after the preload, only in a container Modal takes a snapshot from; that it uses the image's own baked dataset and baseline, reads no secret and sets up no credentials; that it sends no telemetry and leaves the first call numbered 1; that a failure only logs a warning; and that a later call finds no simulation or output file the warm-up left, so it gets the result it gets without one. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_snapshot_warm_up.py | 484 ++++++++++++++++++ 1 file changed, 484 insertions(+) create mode 100644 projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py diff --git a/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py b/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py new file mode 100644 index 000000000..1515c61a7 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py @@ -0,0 +1,484 @@ +"""The warm-up calculation the simulation workers run before their memory snapshot. + +The first calculation in a process builds the US parameter values for its +year and the SPM threshold amounts, which later calculations reuse. The +workers' snapshot hook runs one calculation of a region group whose dataset +and baseline are in the image, so containers restored from the snapshot +start with that work done. These tests replace the calculation itself with a +fake that touches .py's in-process simulation cache and the data folder as a +real one does. +""" + +from __future__ import annotations + +import importlib +import logging +import os +import sys +from collections.abc import Iterator, MutableMapping +from types import ModuleType, SimpleNamespace +from typing import TYPE_CHECKING +from uuid import uuid4 + +import pytest +from conftest import NoOpObservabilityRuntime +from fixtures.fake_modal import install_fake_modal +from policyengine_observability.runtime import ObservabilityRuntime +from policyengine_simulation_executor import precompute_planning, simulation_runtime +from policyengine_simulation_executor.national_partition import national_region_groups +from src.modal import segmented_national + +if TYPE_CHECKING: + from policyengine.core.cache import LRUCache + +# The image's baked year file for the warm-up year, and the baked baseline's +# storage ID, as the precompute names them. +BAKED_DATASET_FILENAME = "enhanced_cps_2024_year_2026.h5" +BAKED_BASELINE_STORAGE_ID = "bl1-warmupgroupbaseline" +SNAPSHOT_TASK_ID = "ta-01SNAPSHOTTING" +# A request the container serves after its snapshot hook: another region +# group, under another reform, as in the measurement on Modal `testing`. +LATER_REQUEST = { + "country": "us", + "scope": "macro", + "time_period": 2026, + "region_group": ["state/mn", "state/mo", "state/nh"], + "reform": { + "gov.irs.credits.ctc.amount.base[0].amount": {"2026-01-01.2100-12-31": 3000} + }, + "_emit_microdata": True, +} +US_MODEL_MODULES = ("policyengine_us", "policyengine.tax_benefit_models.us") + + +class _PolicyEngineLikeCalculation: + """Stands in for the simulation path, leaving what a real calculation leaves. + + A real calculation's ``ensure()`` adds its baseline to .py's in-process + cache under the baseline's deterministic storage ID, adds its reform under + a new random ID, and saves the reform's output beside the dataset. Each + call returns what it found in the cache and the data folder before it + calculated, which a real call's result depends on: a cached baseline is + used instead of the baked file. + """ + + def __init__(self, cache: LRUCache, data_folder) -> None: + self.cache = cache + self.data_folder = data_folder + self.requests: list[dict] = [] + self.runtimes: list[object] = [] + + def __call__(self, params: dict, *, runtime, progress=None) -> dict: + self.requests.append(params) + self.runtimes.append(runtime) + with runtime.span("calculation"): + runtime.set_context(region="+".join(params.get("region_group", []))) + state_seen = { + "cached_simulations": sorted(self.cache._cache), + "data_folder_files": sorted( + path.name for path in self.data_folder.iterdir() + ), + } + reform_storage_id = str(uuid4()) + self.cache.add(BAKED_BASELINE_STORAGE_ID, SimpleNamespace(role="baseline")) + self.cache.add(reform_storage_id, SimpleNamespace(role="reform")) + (self.data_folder / f"{reform_storage_id}.h5").write_bytes(b"reform output") + return { + "state_seen": state_seen, + "region_group": params.get("region_group"), + "reform": params.get("reform"), + } + + +class _CallRuntime(NoOpObservabilityRuntime): + """A worker call's runtime that records and sends nothing.""" + + def shutdown(self) -> None: + return None + + +class _EnvironmentReadRecorder(MutableMapping): + """Wraps ``os.environ`` and records the name of every variable read.""" + + def __init__(self, environment: MutableMapping) -> None: + self.environment = environment + self.names_read: set[str] = set() + + def __getitem__(self, name: str) -> str: + self.names_read.add(name) + return self.environment[name] + + def __setitem__(self, name: str, value: str) -> None: + self.environment[name] = value + + def __delitem__(self, name: str) -> None: + del self.environment[name] + + def __iter__(self) -> Iterator[str]: + # Listing the variables reads them all, as the credential setup's + # log of Google-related variables does. + for name in list(self.environment): + self.names_read.add(name) + yield name + + def __len__(self) -> int: + return len(self.environment) + + +@pytest.fixture +def warm_up_module(): + return importlib.import_module("src.modal.snapshot_warm_up") + + +@pytest.fixture +def snapshotted_container(monkeypatch): + """Act as a container Modal snapshots, with the US models preloaded.""" + monkeypatch.setenv("MODAL_ENABLE_SNAP_RESTORE", "1") + monkeypatch.setenv("MODAL_TASK_ID", SNAPSHOT_TASK_ID) + for module_name in US_MODEL_MODULES: + monkeypatch.setitem( + sys.modules, + module_name, + sys.modules.get(module_name) or ModuleType(module_name), + ) + + +@pytest.fixture +def requested_identities(monkeypatch): + """Answer the precompute's baseline identity, recording each year and group.""" + requested: list[tuple[int, list[str]]] = [] + + def baked_identity(year, group): + requested.append((year, list(group))) + return SimpleNamespace( + dataset=SimpleNamespace(filename=BAKED_DATASET_FILENAME), + storage_id=BAKED_BASELINE_STORAGE_ID, + ) + + monkeypatch.setattr(precompute_planning, "cohort_identity", baked_identity) + return requested + + +@pytest.fixture +def image_data_folder(tmp_path, monkeypatch, requested_identities): + """Create the image's data folder, holding the warm-up group's baked inputs.""" + data_folder = tmp_path / "data" + data_folder.mkdir() + (data_folder / BAKED_DATASET_FILENAME).write_bytes(b"baked year file") + (data_folder / f"{BAKED_BASELINE_STORAGE_ID}.h5").write_bytes(b"baked baseline") + monkeypatch.setenv("POLICYENGINE_DATA_FOLDER", str(data_folder)) + return data_folder + + +@pytest.fixture +def simulation_cache(monkeypatch): + """Start .py's in-process simulation cache empty, as in a new container.""" + # Imported here, after the executor modules set + # POLICYENGINE_SKIP_COUNTRY_IMPORTS: importing .py first would load both + # countries' models. + from policyengine.core import simulation as policyengine_simulation + from policyengine.core.cache import LRUCache + + cache = LRUCache(max_size=100) + monkeypatch.setattr(policyengine_simulation, "_cache", cache) + return cache + + +@pytest.fixture +def calculation(monkeypatch, simulation_cache, image_data_folder): + """Replace the simulation path's calculation with a .py-like fake.""" + fake_calculation = _PolicyEngineLikeCalculation(simulation_cache, image_data_folder) + monkeypatch.setattr( + simulation_runtime, "_run_simulation_impl_core", fake_calculation + ) + return fake_calculation + + +@pytest.fixture +def modal_app(monkeypatch): + """Import the app afresh, as a new container does, without the real preload.""" + install_fake_modal(monkeypatch) + sys.modules.pop("src.modal.app", None) + app = importlib.import_module("src.modal.app") + monkeypatch.setattr(app, "preload_country_models", lambda: None) + yield app + sys.modules.pop("src.modal.app", None) + + +def _configured_by(runtime_class): + """Return a stand-in for ``_configure_modal_observability``.""" + + def configure_runtime(*, service_role: str): + return runtime_class() + + return configure_runtime + + +def _restore_initial_state(cache: LRUCache, data_folder, files_before: set) -> None: + """Put the cache and data folder back as they were when the container started.""" + cache.clear() + for path in data_folder.iterdir(): + if path.name not in files_before: + path.unlink() + + +def test_the_snapshot_hook_runs_the_warm_up_once_after_the_preload( + modal_app, monkeypatch +): + steps: list[str] = [] + monkeypatch.setattr( + modal_app, "preload_country_models", lambda: steps.append("preload") + ) + monkeypatch.setattr( + modal_app, "warm_up_first_calculation", lambda: steps.append("warm-up") + ) + + for worker_class_name in ("SimulationWorker", "SimulationSegmentWorker"): + worker = getattr(modal_app, worker_class_name)() + worker.load_country_models() + # Restored containers run only the snapshot=False hook. + worker.reseed_random_after_restore() + + assert steps == ["preload", "warm-up", "preload", "warm-up"] + + +@pytest.mark.usefixtures("snapshotted_container") +def test_the_warm_up_calculates_one_baked_group_for_the_first_precompute_year( + warm_up_module, calculation, requested_identities +): + warm_up_module.warm_up_first_calculation() + + [request] = calculation.requests + first_precompute_year = precompute_planning.PRECOMPUTE_YEARS[0] + # A segmented national run's child request, which the precompute bakes a + # current-law baseline for in every year it covers. + assert request["country"] == "us" + assert request["scope"] == "macro" + assert int(request["time_period"]) == first_precompute_year + assert request["region_group"] in national_region_groups("us") + assert request["_emit_microdata"] is True + assert "region" not in request + assert "baseline" not in request + # A reform, so the warm-up calculates the reform as a request does. + assert request["reform"] + assert requested_identities == [(first_precompute_year, request["region_group"])] + + +@pytest.mark.usefixtures("snapshotted_container") +@pytest.mark.parametrize( + "missing_filename", + [BAKED_DATASET_FILENAME, f"{BAKED_BASELINE_STORAGE_ID}.h5"], +) +def test_the_warm_up_skips_with_a_warning_unless_the_image_holds_its_inputs( + warm_up_module, calculation, image_data_folder, missing_filename, caplog +): + # Without a baked year file the dataset would be built from its source, + # which may download it; without a baked baseline it would be calculated. + (image_data_folder / missing_filename).unlink() + + with caplog.at_level(logging.WARNING, logger=warm_up_module.__name__): + warm_up_module.warm_up_first_calculation() + + assert calculation.requests == [] + assert missing_filename in caplog.text + + +@pytest.mark.usefixtures("snapshotted_container") +def test_the_warm_up_reads_no_secret_and_sets_up_no_credentials( + warm_up_module, calculation, monkeypatch +): + monkeypatch.setenv( + "GOOGLE_APPLICATION_CREDENTIALS_JSON", '{"type": "service_account"}' + ) + monkeypatch.setenv("HUGGING_FACE_TOKEN", "hf_secret_value") + + def refuse(*_args, **_kwargs): + msg = "the warm-up must not set up credentials before the snapshot" + raise AssertionError(msg) + + monkeypatch.setattr(simulation_runtime, "setup_gcp_credentials", refuse) + monkeypatch.setattr(simulation_runtime, "run_simulation_impl", refuse) + environment = _EnvironmentReadRecorder(os.environ) + monkeypatch.setattr(os, "environ", environment) + + warm_up_module.warm_up_first_calculation() + + assert len(calculation.requests) == 1 + # Only the snapshot flag Modal sets and the image's data folder. + assert environment.names_read <= { + "MODAL_ENABLE_SNAP_RESTORE", + "POLICYENGINE_DATA_FOLDER", + } + assert "GOOGLE_APPLICATION_CREDENTIALS" not in environment.environment + + +@pytest.mark.usefixtures("snapshotted_container") +def test_the_warm_up_sends_no_telemetry_and_the_first_call_is_still_number_1( + modal_app, calculation, monkeypatch +): + def refuse_observability(*_args, **_kwargs): + # A runtime configured before the snapshot would be shared by every + # restored container, and would export the warm-up's records. + msg = "the warm-up must not configure observability" + raise AssertionError(msg) + + monkeypatch.setattr( + modal_app, "_configure_modal_observability", refuse_observability + ) + monkeypatch.setattr(modal_app, "init_process_observability", refuse_observability) + monkeypatch.setattr(ObservabilityRuntime, "__init__", refuse_observability) + + worker = modal_app.SimulationSegmentWorker() + worker.load_country_models() + + [warm_up_runtime] = calculation.runtimes + assert not isinstance(warm_up_runtime, ObservabilityRuntime) + + call_attributes: dict[str, object] = {} + + class RecordingRuntime(_CallRuntime): + def set_context(self, **attributes): + call_attributes.update(attributes) + + monkeypatch.setattr( + modal_app, + "_configure_modal_observability", + _configured_by(RecordingRuntime), + ) + monkeypatch.setattr( + simulation_runtime, + "run_simulation_impl", + lambda _params, **_options: {"ok": True}, + ) + + assert worker.run_simulation_segment(dict(LATER_REQUEST)) == {"ok": True} + assert call_attributes["container_start"] == "took_snapshot" + assert call_attributes["container_call_number"] == 1 + + +@pytest.mark.usefixtures("snapshotted_container") +def test_a_failed_warm_up_only_logs_a_warning( + warm_up_module, calculation, monkeypatch, caplog +): + files_before = {path.name for path in calculation.data_folder.iterdir()} + + def failing_calculation(params, **options): + calculation(params, **options) + msg = "the reform parameter is not in this model version" + raise ValueError(msg) + + monkeypatch.setattr( + simulation_runtime, "_run_simulation_impl_core", failing_calculation + ) + + with caplog.at_level(logging.WARNING, logger=warm_up_module.__name__): + warm_up_module.warm_up_first_calculation() + + assert "the reform parameter is not in this model version" in caplog.text + # What the failed calculation left is removed too. + assert len(calculation.cache) == 0 + assert {path.name for path in calculation.data_folder.iterdir()} == files_before + + +@pytest.mark.usefixtures("snapshotted_container", "image_data_folder") +def test_a_failure_before_the_calculation_only_logs_a_warning( + warm_up_module, calculation, monkeypatch, caplog +): + def unreadable_identity(_year, _group): + msg = "the bundle receipt is unreadable" + raise OSError(msg) + + monkeypatch.setattr(precompute_planning, "cohort_identity", unreadable_identity) + + with caplog.at_level(logging.WARNING, logger=warm_up_module.__name__): + warm_up_module.warm_up_first_calculation() + + assert calculation.requests == [] + assert "the bundle receipt is unreadable" in caplog.text + + +@pytest.mark.usefixtures("snapshotted_container") +def test_a_failed_warm_up_never_stops_the_container_starting( + modal_app, calculation, monkeypatch +): + attempts: list[str] = [] + + def failing_calculation(_params, **_options): + attempts.append("calculated") + msg = "out of memory" + raise MemoryError(msg) + + monkeypatch.setattr( + simulation_runtime, "_run_simulation_impl_core", failing_calculation + ) + monkeypatch.setattr( + modal_app, + "_configure_modal_observability", + _configured_by(_CallRuntime), + ) + monkeypatch.setattr( + segmented_national, + "dispatch_run_simulation", + lambda _params, **_options: {"ok": True}, + ) + + worker = modal_app.SimulationWorker() + worker.load_country_models() + + assert attempts == ["calculated"] + assert worker.run_simulation({"country": "us"}) == {"ok": True} + + +@pytest.mark.usefixtures("snapshotted_container") +def test_a_call_after_the_warm_up_gets_the_result_it_gets_without_one( + warm_up_module, calculation, simulation_cache, image_data_folder +): + files_before = {path.name for path in image_data_folder.iterdir()} + without_warm_up = calculation( + dict(LATER_REQUEST), runtime=NoOpObservabilityRuntime() + ) + _restore_initial_state(simulation_cache, image_data_folder, files_before) + + warm_up_module.warm_up_first_calculation() + after_warm_up = calculation(dict(LATER_REQUEST), runtime=NoOpObservabilityRuntime()) + + # The call finds no simulation the warm-up cached and no file it saved, + # so it loads the baked baseline from the image as it would without one. + assert len(calculation.requests) == 3 + assert after_warm_up == without_warm_up + + +@pytest.mark.usefixtures("image_data_folder") +def test_a_container_modal_takes_no_snapshot_from_skips_the_warm_up( + warm_up_module, calculation, monkeypatch +): + # Modal runs the snapshot hook in every container that isn't restored, + # but takes a snapshot only where its worker set this flag. Elsewhere the + # warm-up would delay the first call by more than it saves. + monkeypatch.delenv("MODAL_ENABLE_SNAP_RESTORE", raising=False) + for module_name in US_MODEL_MODULES: + monkeypatch.setitem( + sys.modules, + module_name, + sys.modules.get(module_name) or ModuleType(module_name), + ) + + warm_up_module.warm_up_first_calculation() + + assert calculation.requests == [] + + +@pytest.mark.usefixtures("image_data_folder") +def test_the_warm_up_skips_with_a_warning_when_the_us_models_were_not_preloaded( + warm_up_module, calculation, monkeypatch, caplog +): + # Importing them again could fetch the data release manifest again. + monkeypatch.setenv("MODAL_ENABLE_SNAP_RESTORE", "1") + for module_name in US_MODEL_MODULES: + monkeypatch.delitem(sys.modules, module_name, raising=False) + + with caplog.at_level(logging.WARNING, logger=warm_up_module.__name__): + warm_up_module.warm_up_first_calculation() + + assert calculation.requests == [] + assert "policyengine" in caplog.text From 4fa050d3b13bf5cb77166fb2892a28293e24cd12 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:27:00 +0400 Subject: [PATCH 02/10] Run one warm-up calculation in the simulation workers' snapshot hook A process's first calculation for a year builds the US parameter values at the calculation date and the SPM threshold amounts, about 20 s that the model preload doesn't cover. The snapshot hook of SimulationWorker and SimulationSegmentWorker now runs one calculation of a baked region group (state/hi+state/ia+state/wi) for the first precompute year under a small reform, so containers restored from the snapshot start with that work done. The warm-up runs only in a container Modal takes a snapshot from (MODAL_ENABLE_SNAP_RESTORE=1), when the US models were preloaded and the group's year file and baseline are in the image's data folder. It calls the simulation path without the Google Cloud credential setup, which reads a Modal Secret, and with a runtime that records and sends nothing, so it writes no telemetry and no call number. Afterwards it removes the simulations it added to .py's in-process cache and the output files it saved, so later calls load their baselines as they would without it. A failure or skip only logs a warning. The container-start tests' fixture replaces the warm-up, as it replaces the preload. Co-Authored-By: Claude Opus 5.5 --- changelog.d/snapshot-warm-up.changed.md | 1 + .../src/modal/app.py | 5 + .../src/modal/snapshot_warm_up.py | 239 ++++++++++++++++++ .../tests/test_modal_container_start.py | 4 +- 4 files changed, 248 insertions(+), 1 deletion(-) create mode 100644 changelog.d/snapshot-warm-up.changed.md create mode 100644 projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py diff --git a/changelog.d/snapshot-warm-up.changed.md b/changelog.d/snapshot-warm-up.changed.md new file mode 100644 index 000000000..0e40d7860 --- /dev/null +++ b/changelog.d/snapshot-warm-up.changed.md @@ -0,0 +1 @@ +The simulation workers' snapshot hook now runs one warm-up calculation of a region group baked into the image, for the first precompute year, in each container Modal takes a memory snapshot from. Containers restored from the snapshot then start with that year's US parameter values and SPM amounts built, which made their first calculation 11 to 15 s faster on Modal `testing`. Containers that take a snapshot start about 70 to 100 s later. A warm-up that fails or can't run safely only logs a warning, and the container starts as before. diff --git a/projects/policyengine-simulation-executor/src/modal/app.py b/projects/policyengine-simulation-executor/src/modal/app.py index 2d406c4de..cd7bfb542 100644 --- a/projects/policyengine-simulation-executor/src/modal/app.py +++ b/projects/policyengine-simulation-executor/src/modal/app.py @@ -48,6 +48,7 @@ from src.modal.ca_certificates import GRPC_CA_BUNDLE_ENV, OPERATING_SYSTEM_CA_PACKAGE from src.modal.country_model_preload import preload_country_models from src.modal.logging_redaction import redact_params_for_logging +from src.modal.snapshot_warm_up import warm_up_first_calculation from src.modal.static_runtime_files import add_static_runtime_files import modal @@ -566,10 +567,14 @@ def load_country_models(self) -> None: First records whether Modal snapshots this container, and its task ID, so each call can report how its container started (``_ContainerCalls``). Telemetry is non-fatal: a failed record must never stop the preload. + Then, in a container Modal snapshots, runs one warm-up calculation + (``src/modal/snapshot_warm_up.py``), so restored containers start with + the first precompute year's values built. """ with contextlib.suppress(Exception): _CONTAINER_CALLS.record_snapshot_hook() preload_country_models() + warm_up_first_calculation() @modal.enter(snap=False) def reseed_random_after_restore(self) -> None: diff --git a/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py b/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py new file mode 100644 index 000000000..28eb27e42 --- /dev/null +++ b/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py @@ -0,0 +1,239 @@ +"""Run one calculation before Modal takes the simulation workers' memory snapshot. + +A process's first calculation for a year builds work that its later +calculations for that year reuse: the US parameter tree's values at the +calculation date (``ParameterNode._get_at_instant``) and the SPM threshold +amounts. Profiled on Modal ``testing`` on 2026-11-25, that took about 20 s of +the first calculation, and the snapshot hook's model preload doesn't do it. +So ``SimulationWorker`` and ``SimulationSegmentWorker`` in +``src/modal/app.py`` run :func:`warm_up_first_calculation` in their +``@modal.enter(snap=True)`` hook, after the preload, and every container +restored from the snapshot starts with that work done for the warm-up year. +In the same measurement, a warm-up of one region group made restored +containers' first calculation 11 to 15 s faster, with identical results, and the +containers Modal took snapshots from started 72 to 97 s later. + +The warm-up calculates one segmented national run's child request: a region +group whose dataset and current-law baseline the precompute bakes into the +image, for the first precompute year, under a small reform. It runs only +where it is safe before a snapshot, and only where Modal takes one: + +- **Only in a container Modal snapshots.** Modal runs the hook in every + container that isn't restored, and takes a snapshot only where its worker + set ``MODAL_ENABLE_SNAP_RESTORE`` to ``1``. Elsewhere the warm-up would + delay the container's first call by about as long as a calculation, to + save that call about 15 s. +- **No connection.** It runs only when the US models were preloaded, since + importing them again could fetch the data release manifest again, and + when the group's year file and baseline are in the image's data folder, + so nothing is downloaded or built from source. It skips the Google Cloud + credential setup of ``run_simulation_impl``, which reads a Modal Secret: + Secrets aren't read before the snapshot. +- **No telemetry.** It configures no observability and gives the + calculation a runtime that records and sends nothing, so it writes no + operation record or span and no call number (``_ContainerCalls``). +- **Nothing left for a request.** It removes the simulations it added to + .py's in-process cache and the output files it saved in the data folder, + so a later call loads its baseline from the image as it would without the + warm-up. Only what .py and policyengine-core keep for every calculation + stays: the values built for the warm-up year. +- **Never fatal.** A failure or skip logs a warning, and the container + starts as it would without the warm-up. +""" + +from __future__ import annotations + +import contextlib +import gc +import logging +import os +import sys +import time +from contextlib import nullcontext +from pathlib import Path +from typing import TYPE_CHECKING, Any, cast + +from policyengine_simulation_executor.national_partition import ( + US_NATIONAL_REGION_GROUPS, +) +from policyengine_simulation_executor.precompute_planning import ( + PRECOMPUTE_COUNTRY, + PRECOMPUTE_YEARS, + cohort_params, +) +from src.modal.country_model_preload import COUNTRY_MODEL_MODULES + +if TYPE_CHECKING: + from collections.abc import Iterator + + from policyengine_observability import ObservabilityRuntime + +logger = logging.getLogger(__name__) + +# Modal's worker sets this to "1" in the containers it takes a snapshot from +# or restores (``run_function`` in modal/_container_entrypoint.py, Modal +# 1.6.4). Restored containers don't run the snapshot hook. +SNAPSHOT_FLAG_ENV_NAME = "MODAL_ENABLE_SNAP_RESTORE" +WARM_UP_YEAR = PRECOMPUTE_YEARS[0] +# The group the measurement on Modal ``testing`` warmed up with. +WARM_UP_REGION_GROUP = US_NATIONAL_REGION_GROUPS[0] +# The reform makes the warm-up calculate a reform simulation, as a request +# does: the Child Tax Credit's base amount, raised to $2,500. +WARM_UP_REFORM_PARAMETER = "gov.irs.credits.ctc.amount.base[0].amount" +WARM_UP_REFORM_VALUE = 2500 + + +class _RecordNothingRuntime: + """The observability runtime the warm-up's calculation reports to. + + It records and sends nothing. A real runtime configured before the + snapshot would carry one process identity into every restored container, + and would export the warm-up as if it were a call. + """ + + def span(self, *_args: object, **_kwargs: object) -> nullcontext[None]: + """Open nothing.""" + return nullcontext() + + def operation(self, *_args: object, **_kwargs: object) -> nullcontext[None]: + """Open nothing.""" + return nullcontext() + + def set_context(self, **_attributes: object) -> None: + """Keep nothing.""" + + def event(self, *_args: object, **_kwargs: object) -> None: + """Record nothing.""" + + def record_exception(self, *_args: object, **_kwargs: object) -> None: + """Record nothing.""" + + def capture_context(self) -> dict[str, str]: + """Return an empty context.""" + return {} + + +def warm_up_request() -> dict[str, Any]: + """Return the warm-up's request: one region group's child of a national run.""" + request = cohort_params(WARM_UP_YEAR, list(WARM_UP_REGION_GROUP)) + request["reform"] = { + WARM_UP_REFORM_PARAMETER: { + f"{WARM_UP_YEAR}-01-01.2100-12-31": WARM_UP_REFORM_VALUE + } + } + request["_emit_microdata"] = True + return request + + +def warm_up_first_calculation() -> None: + """Run the warm-up calculation in a container Modal takes a snapshot from. + + Does nothing in any other container. Nothing here may stop a container + from starting: a failure or skip logs a warning, and each container's + first calculation then builds its year's values itself, as before. + """ + if os.environ.get(SNAPSHOT_FLAG_ENV_NAME) != "1": + return + started = time.monotonic() + try: + skip_reason = _calculate_unless_unsafe() + except Exception: # noqa: BLE001 # the warm-up only makes first calls faster + logger.warning( + "Warm-up calculation failed; each restored container's first " + "calculation builds its year's values itself", + exc_info=True, + ) + return + if skip_reason is not None: + logger.warning( + "Warm-up calculation skipped, so each restored container's first " + "calculation builds its year's values itself: %s", + skip_reason, + ) + return + logger.info( + "Warm-up calculation of %s for %s finished in %.1fs", + "+".join(WARM_UP_REGION_GROUP), + WARM_UP_YEAR, + time.monotonic() - started, + ) + + +def _calculate_unless_unsafe() -> str | None: + """Run the warm-up calculation, or return why it would be unsafe to.""" + not_preloaded = [ + module_name + for module_name in COUNTRY_MODEL_MODULES[PRECOMPUTE_COUNTRY] + if module_name not in sys.modules + ] + if not_preloaded: + return f"the preload didn't import {', '.join(not_preloaded)}" + from policyengine_simulation_executor.simulation_runtime import ( # noqa: PLC0415 # resolved per call so tests can patch simulation_runtime; loaded in the worker container, not at deploy time + _run_simulation_impl_core, + resolve_data_folder, + ) + + data_folder = Path(resolve_data_folder()) + missing = _missing_baked_inputs(data_folder) + if missing: + return f"the image's data folder lacks {', '.join(missing)}" + with _removing_what_the_calculation_leaves(data_folder): + _run_simulation_impl_core( + warm_up_request(), + runtime=cast("ObservabilityRuntime", _RecordNothingRuntime()), + ) + return None + + +def _missing_baked_inputs(data_folder: Path) -> list[str]: + """Return the warm-up's baked files that aren't in ``data_folder``. + + The year file and the current-law baseline are named as the precompute + names them, and as the calculation looks for them. + """ + from policyengine_simulation_executor.artifact_keys import ( # noqa: PLC0415 # loaded in the worker container, not at deploy time + baseline_artifact_filename, + ) + from policyengine_simulation_executor.precompute_planning import ( # noqa: PLC0415 # resolved per call so tests can patch precompute_planning.cohort_identity + cohort_identity, + ) + + identity = cohort_identity(WARM_UP_YEAR, list(WARM_UP_REGION_GROUP)) + filenames = ( + identity.dataset.filename, + baseline_artifact_filename(identity.storage_id), + ) + return [ + filename for filename in filenames if not (data_folder / filename).is_file() + ] + + +@contextlib.contextmanager +def _removing_what_the_calculation_leaves(data_folder: Path) -> Iterator[None]: + """Remove the simulations and output files a calculation adds, even if it fails. + + .py's ``Simulation.ensure()`` caches each simulation in the process (its + baseline under the baked baseline's storage ID, its reform under a new + random ID) and saves an output it calculated beside the dataset, as + ``.h5``. Left there, they would go into the snapshot, and a + later call for the warm-up's group would use the cached baseline instead + of loading the baked one. + """ + from policyengine.core.simulation import ( # noqa: PLC0415 # resolved per call so tests can patch policyengine's simulation cache + _cache as simulation_cache, + ) + + cached_before = set(simulation_cache._cache) # noqa: SLF001 # policyengine's LRUCache has no public listing or remove + outputs_before = set(data_folder.glob("*.h5")) + try: + yield + finally: + for storage_id in [ + storage_id + for storage_id in simulation_cache._cache # noqa: SLF001 # as above + if storage_id not in cached_before + ]: + simulation_cache._cache.pop(storage_id, None) # noqa: SLF001 # as above + for output in set(data_folder.glob("*.h5")) - outputs_before: + output.unlink(missing_ok=True) + gc.collect() diff --git a/projects/policyengine-simulation-executor/tests/test_modal_container_start.py b/projects/policyengine-simulation-executor/tests/test_modal_container_start.py index 8ca4a7b6b..23af37b8c 100644 --- a/projects/policyengine-simulation-executor/tests/test_modal_container_start.py +++ b/projects/policyengine-simulation-executor/tests/test_modal_container_start.py @@ -71,8 +71,10 @@ def modal_app(monkeypatch): monkeypatch.delenv("MODAL_ENABLE_SNAP_RESTORE", raising=False) sys.modules.pop("src.modal.app", None) app = importlib.import_module("src.modal.app") - # The real preload imports both countries' models. + # The real preload imports both countries' models, and the real warm-up + # calculates a region group (tests/test_snapshot_warm_up.py). monkeypatch.setattr(app, "preload_country_models", lambda: None) + monkeypatch.setattr(app, "warm_up_first_calculation", lambda: None) _replace_worker_jobs(monkeypatch, lambda _params, **_job_options: WORKER_RESULT) yield app sys.modules.pop("src.modal.app", None) From a766da31ff1d88c8a8bb6ffbcbad356facab1fb9 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:51:56 +0400 Subject: [PATCH 03/10] Tighten the warm-up tests after the first review round - A new test, which fails: the warm-up must skip, with a warning, when the baked year file fails .py's reuse checks, since ensure_datasets would then rebuild it from a source it may download. - The credential and observability tests record each refusal as well as raising it, and require that the warm-up logged no warning: the warm-up turns exceptions into warnings, so a refusal raised after the calculation went unnoticed. - The credential test clears GOOGLE_APPLICATION_CREDENTIALS first, so it passes where a developer's shell exports it. - A new test loads policyengine-us's parameter tree and checks that the warm-up's reform names a real parameter, starts in the warm-up year and differs from current law, so a renamed parameter fails a test instead of only every deploy's warm-up. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_snapshot_warm_up.py | 80 +++++++++++++++++-- 1 file changed, 74 insertions(+), 6 deletions(-) diff --git a/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py b/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py index 1515c61a7..e18156512 100644 --- a/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py +++ b/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py @@ -16,6 +16,7 @@ import os import sys from collections.abc import Iterator, MutableMapping +from pathlib import Path from types import ModuleType, SimpleNamespace from typing import TYPE_CHECKING from uuid import uuid4 @@ -24,7 +25,11 @@ from conftest import NoOpObservabilityRuntime from fixtures.fake_modal import install_fake_modal from policyengine_observability.runtime import ObservabilityRuntime -from policyengine_simulation_executor import precompute_planning, simulation_runtime +from policyengine_simulation_executor import ( + precompute_planning, + simulation_runtime, + state_datasets, +) from policyengine_simulation_executor.national_partition import national_region_groups from src.modal import segmented_national @@ -33,6 +38,7 @@ # The image's baked year file for the warm-up year, and the baked baseline's # storage ID, as the precompute names them. +BAKED_DATASET_NAME = "enhanced_cps_2024" BAKED_DATASET_FILENAME = "enhanced_cps_2024_year_2026.h5" BAKED_BASELINE_STORAGE_ID = "bl1-warmupgroupbaseline" SNAPSHOT_TASK_ID = "ta-01SNAPSHOTTING" @@ -151,7 +157,9 @@ def requested_identities(monkeypatch): def baked_identity(year, group): requested.append((year, list(group))) return SimpleNamespace( - dataset=SimpleNamespace(filename=BAKED_DATASET_FILENAME), + dataset=SimpleNamespace( + dataset=BAKED_DATASET_NAME, filename=BAKED_DATASET_FILENAME + ), storage_id=BAKED_BASELINE_STORAGE_ID, ) @@ -167,6 +175,10 @@ def image_data_folder(tmp_path, monkeypatch, requested_identities): (data_folder / BAKED_DATASET_FILENAME).write_bytes(b"baked year file") (data_folder / f"{BAKED_BASELINE_STORAGE_ID}.h5").write_bytes(b"baked baseline") monkeypatch.setenv("POLICYENGINE_DATA_FOLDER", str(data_folder)) + # .py's own checks would read the files' stamps, which these stand-ins lack. + monkeypatch.setattr( + state_datasets, "year_file_reuse_problem", lambda _path, _dataset: None + ) return data_folder @@ -283,16 +295,43 @@ def test_the_warm_up_skips_with_a_warning_unless_the_image_holds_its_inputs( assert missing_filename in caplog.text +@pytest.mark.usefixtures("snapshotted_container") +def test_the_warm_up_skips_with_a_warning_when_the_baked_year_file_would_be_rebuilt( + warm_up_module, calculation, monkeypatch, caplog +): + # .py's ensure_datasets rebuilds a year file that fails its reuse checks + # from the dataset's source, which it may download from Hugging Face. + checked_year_files: list[tuple[str, str]] = [] + + def out_of_date(path, dataset): + checked_year_files.append((Path(path).name, dataset)) + return "the year file records another register of renamed inputs" + + monkeypatch.setattr(state_datasets, "year_file_reuse_problem", out_of_date) + + with caplog.at_level(logging.WARNING, logger=warm_up_module.__name__): + warm_up_module.warm_up_first_calculation() + + assert calculation.requests == [] + assert checked_year_files == [(BAKED_DATASET_FILENAME, BAKED_DATASET_NAME)] + assert "another register of renamed inputs" in caplog.text + + @pytest.mark.usefixtures("snapshotted_container") def test_the_warm_up_reads_no_secret_and_sets_up_no_credentials( - warm_up_module, calculation, monkeypatch + warm_up_module, calculation, monkeypatch, caplog ): + monkeypatch.delenv("GOOGLE_APPLICATION_CREDENTIALS", raising=False) monkeypatch.setenv( "GOOGLE_APPLICATION_CREDENTIALS_JSON", '{"type": "service_account"}' ) monkeypatch.setenv("HUGGING_FACE_TOKEN", "hf_secret_value") + # Recorded as well as raised: the warm-up turns an exception into a + # warning, so a raise alone could go unnoticed. + refusals: list[str] = [] def refuse(*_args, **_kwargs): + refusals.append("credential setup") msg = "the warm-up must not set up credentials before the snapshot" raise AssertionError(msg) @@ -301,8 +340,11 @@ def refuse(*_args, **_kwargs): environment = _EnvironmentReadRecorder(os.environ) monkeypatch.setattr(os, "environ", environment) - warm_up_module.warm_up_first_calculation() + with caplog.at_level(logging.WARNING, logger=warm_up_module.__name__): + warm_up_module.warm_up_first_calculation() + assert refusals == [] + assert caplog.records == [] assert len(calculation.requests) == 1 # Only the snapshot flag Modal sets and the image's data folder. assert environment.names_read <= { @@ -314,11 +356,16 @@ def refuse(*_args, **_kwargs): @pytest.mark.usefixtures("snapshotted_container") def test_the_warm_up_sends_no_telemetry_and_the_first_call_is_still_number_1( - modal_app, calculation, monkeypatch + modal_app, calculation, monkeypatch, caplog ): + # Recorded as well as raised, since the warm-up turns an exception into + # a warning. + refusals: list[str] = [] + def refuse_observability(*_args, **_kwargs): # A runtime configured before the snapshot would be shared by every # restored container, and would export the warm-up's records. + refusals.append("observability configured") msg = "the warm-up must not configure observability" raise AssertionError(msg) @@ -329,8 +376,11 @@ def refuse_observability(*_args, **_kwargs): monkeypatch.setattr(ObservabilityRuntime, "__init__", refuse_observability) worker = modal_app.SimulationSegmentWorker() - worker.load_country_models() + with caplog.at_level(logging.WARNING, logger="src.modal.snapshot_warm_up"): + worker.load_country_models() + assert refusals == [] + assert caplog.records == [] [warm_up_runtime] = calculation.runtimes assert not isinstance(warm_up_runtime, ObservabilityRuntime) @@ -482,3 +532,21 @@ def test_the_warm_up_skips_with_a_warning_when_the_us_models_were_not_preloaded( assert calculation.requests == [] assert "policyengine" in caplog.text + + +def test_the_warm_up_reform_changes_a_parameter_of_the_installed_us_model( + warm_up_module, +): + # policyengine-us's own parameter tree, about 12 s to load; .py's US model + # would also read the data release manifest from Hugging Face. + from policyengine_us.system import system + + [(parameter_name, values_by_period)] = warm_up_module.warm_up_request()[ + "reform" + ].items() + [(period, reform_value)] = values_by_period.items() + period_start, _, _period_end = period.partition(".") + + assert period_start == f"{precompute_planning.PRECOMPUTE_YEARS[0]}-01-01" + # A reform equal to current law would leave nothing to calculate. + assert system.parameters.get_child(parameter_name)(period_start) != reform_value From d34fc8c865f2e11cb93292442fa18c0022e52215 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:53:15 +0400 Subject: [PATCH 04/10] Skip the warm-up when .py would rebuild its baked year file The warm-up now also runs .py's reuse checks on the warm-up group's baked year file, as the state datasets do. A year file that fails them would make ensure_datasets build it again from the dataset's source, which it may download before the snapshot; the warm-up skips with a warning instead. The module docstring, the hook's docstring and the changelog fragment no longer say the warm-up keeps the year's SPM amounts. A request's reform builds its own parameter tree and each simulation its own SPM amount cache; what carries to later requests is what the packages keep for the process, such as the shared parameter tree that baseline branches use and spm-calculator's tables. The measured gain is now quoted for both runs on Modal testing: 11 to 16 s, on 8 CPUs and on 1 CPU. Co-Authored-By: Claude Opus 5.5 --- changelog.d/snapshot-warm-up.changed.md | 2 +- .../src/modal/app.py | 2 +- .../src/modal/snapshot_warm_up.py | 66 ++++++++++++------- 3 files changed, 43 insertions(+), 27 deletions(-) diff --git a/changelog.d/snapshot-warm-up.changed.md b/changelog.d/snapshot-warm-up.changed.md index 0e40d7860..7c914ccc8 100644 --- a/changelog.d/snapshot-warm-up.changed.md +++ b/changelog.d/snapshot-warm-up.changed.md @@ -1 +1 @@ -The simulation workers' snapshot hook now runs one warm-up calculation of a region group baked into the image, for the first precompute year, in each container Modal takes a memory snapshot from. Containers restored from the snapshot then start with that year's US parameter values and SPM amounts built, which made their first calculation 11 to 15 s faster on Modal `testing`. Containers that take a snapshot start about 70 to 100 s later. A warm-up that fails or can't run safely only logs a warning, and the container starts as before. +The simulation workers' snapshot hook now runs one warm-up calculation of a region group baked into the image, for the first precompute year, in each container Modal takes a memory snapshot from. Containers restored from the snapshot then start with part of the work their first calculation for that year would otherwise do, which made their first calculation 11 to 16 s faster on Modal `testing`, on 8 CPUs and on 1 CPU. Containers that take a snapshot start about 70 to 100 s later. A warm-up that fails or can't run safely only logs a warning, and the container starts as before. diff --git a/projects/policyengine-simulation-executor/src/modal/app.py b/projects/policyengine-simulation-executor/src/modal/app.py index cd7bfb542..ae9d15d05 100644 --- a/projects/policyengine-simulation-executor/src/modal/app.py +++ b/projects/policyengine-simulation-executor/src/modal/app.py @@ -569,7 +569,7 @@ def load_country_models(self) -> None: Telemetry is non-fatal: a failed record must never stop the preload. Then, in a container Modal snapshots, runs one warm-up calculation (``src/modal/snapshot_warm_up.py``), so restored containers start with - the first precompute year's values built. + work their first calculation for the first precompute year would do. """ with contextlib.suppress(Exception): _CONTAINER_CALLS.record_snapshot_hook() diff --git a/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py b/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py index 28eb27e42..b9e3a4c31 100644 --- a/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py +++ b/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py @@ -1,17 +1,25 @@ """Run one calculation before Modal takes the simulation workers' memory snapshot. -A process's first calculation for a year builds work that its later -calculations for that year reuse: the US parameter tree's values at the -calculation date (``ParameterNode._get_at_instant``) and the SPM threshold -amounts. Profiled on Modal ``testing`` on 2026-11-25, that took about 20 s of -the first calculation, and the snapshot hook's model preload doesn't do it. +A process's first calculation for a year does work that its later +calculations for that year reuse. Profiled on Modal ``testing`` on +2026-11-25, that was about 20 s of the first calculation, mostly building the +US parameter values at the calculation date (``ParameterNode._get_at_instant``) +and the SPM threshold amounts; the snapshot hook's model preload does neither. +What carries from one request to the next is what the packages keep for the +whole process: every simulation's baseline branch shares the module-level +parameter tree and its values at each date (``share_spm_policy`` in +policyengine-us), and spm-calculator keeps its threshold tables and price +index series. A request's reform builds its own parameter tree, and each +simulation its own SPM amount cache, so those are built in every request. + So ``SimulationWorker`` and ``SimulationSegmentWorker`` in ``src/modal/app.py`` run :func:`warm_up_first_calculation` in their ``@modal.enter(snap=True)`` hook, after the preload, and every container restored from the snapshot starts with that work done for the warm-up year. -In the same measurement, a warm-up of one region group made restored -containers' first calculation 11 to 15 s faster, with identical results, and the -containers Modal took snapshots from started 72 to 97 s later. +Measured on Modal ``testing`` (2026-11-25 on 8 CPUs, 2026-11-26 on 1 CPU), a +warm-up of another region group under another reform made restored +containers' first calculation 11 to 16 s faster, with identical results, and +the containers Modal took snapshots from started about 70 to 100 s later. The warm-up calculates one segmented national run's child request: a region group whose dataset and current-law baseline the precompute bakes into the @@ -25,8 +33,9 @@ save that call about 15 s. - **No connection.** It runs only when the US models were preloaded, since importing them again could fetch the data release manifest again, and - when the group's year file and baseline are in the image's data folder, - so nothing is downloaded or built from source. It skips the Google Cloud + when the group's year file and baseline are in the image's data folder + and the year file passes .py's reuse checks, so nothing is downloaded or + built from source. It skips the Google Cloud credential setup of ``run_simulation_impl``, which reads a Modal Secret: Secrets aren't read before the snapshot. - **No telemetry.** It configures no observability and gives the @@ -35,8 +44,8 @@ - **Nothing left for a request.** It removes the simulations it added to .py's in-process cache and the output files it saved in the data folder, so a later call loads its baseline from the image as it would without the - warm-up. Only what .py and policyengine-core keep for every calculation - stays: the values built for the warm-up year. + warm-up. What stays is what the packages keep for the whole process, as + above, and the modules the calculation imported. - **Never fatal.** A failure or skip logs a warning, and the container starts as it would without the warm-up. """ @@ -174,9 +183,9 @@ def _calculate_unless_unsafe() -> str | None: ) data_folder = Path(resolve_data_folder()) - missing = _missing_baked_inputs(data_folder) - if missing: - return f"the image's data folder lacks {', '.join(missing)}" + baked_inputs_problem = _baked_inputs_problem(data_folder) + if baked_inputs_problem is not None: + return baked_inputs_problem with _removing_what_the_calculation_leaves(data_folder): _run_simulation_impl_core( warm_up_request(), @@ -185,11 +194,13 @@ def _calculate_unless_unsafe() -> str | None: return None -def _missing_baked_inputs(data_folder: Path) -> list[str]: - """Return the warm-up's baked files that aren't in ``data_folder``. +def _baked_inputs_problem(data_folder: Path) -> str | None: + """Return why the warm-up can't use the image's baked inputs, or None. The year file and the current-law baseline are named as the precompute - names them, and as the calculation looks for them. + names them, and as the calculation looks for them. The year file must + also pass .py's reuse checks: otherwise ``ensure_datasets`` would build it + again from the dataset's source, which it may download. """ from policyengine_simulation_executor.artifact_keys import ( # noqa: PLC0415 # loaded in the worker container, not at deploy time baseline_artifact_filename, @@ -197,15 +208,20 @@ def _missing_baked_inputs(data_folder: Path) -> list[str]: from policyengine_simulation_executor.precompute_planning import ( # noqa: PLC0415 # resolved per call so tests can patch precompute_planning.cohort_identity cohort_identity, ) + from policyengine_simulation_executor.state_datasets import ( # noqa: PLC0415 # resolved per call so tests can patch state_datasets.year_file_reuse_problem + year_file_reuse_problem, + ) identity = cohort_identity(WARM_UP_YEAR, list(WARM_UP_REGION_GROUP)) - filenames = ( - identity.dataset.filename, - baseline_artifact_filename(identity.storage_id), - ) - return [ - filename for filename in filenames if not (data_folder / filename).is_file() - ] + year_file = data_folder / identity.dataset.filename + baseline_file = data_folder / baseline_artifact_filename(identity.storage_id) + missing = [path.name for path in (year_file, baseline_file) if not path.is_file()] + if missing: + return f"the image's data folder lacks {', '.join(missing)}" + reuse_problem = year_file_reuse_problem(year_file, identity.dataset.dataset) + if reuse_problem is not None: + return f"its year file {year_file.name} would be built again: {reuse_problem}" + return None @contextlib.contextmanager From fd96e70d32041b8735bafc3ca2d41c6814098378 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:16:33 +0400 Subject: [PATCH 05/10] Test that the warm-up warns when it saves over a baked file A new test, which fails: when .py finds the warm-up group's baked baseline incomplete or out of date, it calculates it again and saves it over the image's file, which then goes into the snapshot. The warm-up must log a warning naming the file, since restored containers then report a baseline hit for it. The test that compared a later call's view of the container is renamed to what it checks, the skip test for models that weren't preloaded checks the skip message and module name, and the secret test says it records only the warm-up's own environment reads. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_snapshot_warm_up.py | 33 +++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py b/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py index e18156512..d2500fb4b 100644 --- a/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py +++ b/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py @@ -337,6 +337,8 @@ def refuse(*_args, **_kwargs): monkeypatch.setattr(simulation_runtime, "setup_gcp_credentials", refuse) monkeypatch.setattr(simulation_runtime, "run_simulation_impl", refuse) + # Records the warm-up's own reads. The calculation is replaced here, so + # what the simulation path reads is checked by reading its code instead. environment = _EnvironmentReadRecorder(os.environ) monkeypatch.setattr(os, "environ", environment) @@ -480,7 +482,7 @@ def failing_calculation(_params, **_options): @pytest.mark.usefixtures("snapshotted_container") -def test_a_call_after_the_warm_up_gets_the_result_it_gets_without_one( +def test_a_call_after_the_warm_up_finds_no_simulation_or_file_the_warm_up_added( warm_up_module, calculation, simulation_cache, image_data_folder ): files_before = {path.name for path in image_data_folder.iterdir()} @@ -498,6 +500,32 @@ def test_a_call_after_the_warm_up_gets_the_result_it_gets_without_one( assert after_warm_up == without_warm_up +@pytest.mark.usefixtures("snapshotted_container") +def test_the_warm_up_warns_when_it_saved_over_a_baked_file( + warm_up_module, calculation, image_data_folder, monkeypatch, caplog +): + # .py calculates a baked baseline again and saves it over the image's + # file when it finds it incomplete or out of date. The rewritten file goes + # into the snapshot, so restored containers load it and report a hit. + baked_baseline = image_data_folder / f"{BAKED_BASELINE_STORAGE_ID}.h5" + + def recalculating_calculation(params, **options): + result = calculation(params, **options) + baked_baseline.write_bytes(b"baseline calculated again by the warm-up") + return result + + monkeypatch.setattr( + simulation_runtime, "_run_simulation_impl_core", recalculating_calculation + ) + + with caplog.at_level(logging.WARNING, logger=warm_up_module.__name__): + warm_up_module.warm_up_first_calculation() + + assert len(calculation.requests) == 1 + [warning] = caplog.records + assert baked_baseline.name in warning.getMessage() + + @pytest.mark.usefixtures("image_data_folder") def test_a_container_modal_takes_no_snapshot_from_skips_the_warm_up( warm_up_module, calculation, monkeypatch @@ -531,7 +559,8 @@ def test_the_warm_up_skips_with_a_warning_when_the_us_models_were_not_preloaded( warm_up_module.warm_up_first_calculation() assert calculation.requests == [] - assert "policyengine" in caplog.text + assert "Warm-up calculation skipped" in caplog.text + assert "policyengine.tax_benefit_models.us" in caplog.text def test_the_warm_up_reform_changes_a_parameter_of_the_installed_us_model( From ab26fe337e1c44ca991cce113f11ea96b28c9f0d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:17:53 +0400 Subject: [PATCH 06/10] Warn when the warm-up saves over a baked file, and correct its docstrings When .py finds the warm-up group's baked baseline incomplete or out of date, it calculates it again and saves it over the image's file. The cleanup can't undo that, and restored containers then load the warm-up's copy and report a baseline hit, so the warm-up now logs a warning naming each file in the data folder whose size or modification time changed. The module docstring no longer says Secrets aren't read before the snapshot: the preload that runs first already reads the Hugging Face token and fetches the data release manifest. It also says that the profile compared two calculations in one process, so it doesn't show which of the one-time work a warm-up leaves for a later request. The hook's summary now names the warm-up. Co-Authored-By: Claude Opus 5.5 --- .../src/modal/app.py | 2 +- .../src/modal/snapshot_warm_up.py | 57 ++++++++++++++----- 2 files changed, 45 insertions(+), 14 deletions(-) diff --git a/projects/policyengine-simulation-executor/src/modal/app.py b/projects/policyengine-simulation-executor/src/modal/app.py index ae9d15d05..846d8df1b 100644 --- a/projects/policyengine-simulation-executor/src/modal/app.py +++ b/projects/policyengine-simulation-executor/src/modal/app.py @@ -562,7 +562,7 @@ class _CountryModelsLoadedBeforeSnapshot: @modal.enter(snap=True) def load_country_models(self) -> None: - """Load both countries' models and the SPM capability into the snapshot. + """Load the models and SPM capability, then warm up, before the snapshot. First records whether Modal snapshots this container, and its task ID, so each call can report how its container started (``_ContainerCalls``). diff --git a/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py b/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py index b9e3a4c31..dd2dae320 100644 --- a/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py +++ b/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py @@ -5,12 +5,14 @@ 2026-11-25, that was about 20 s of the first calculation, mostly building the US parameter values at the calculation date (``ParameterNode._get_at_instant``) and the SPM threshold amounts; the snapshot hook's model preload does neither. -What carries from one request to the next is what the packages keep for the -whole process: every simulation's baseline branch shares the module-level -parameter tree and its values at each date (``share_spm_policy`` in -policyengine-us), and spm-calculator keeps its threshold tables and price -index series. A request's reform builds its own parameter tree, and each -simulation its own SPM amount cache, so those are built in every request. +That profile compared two calculations in one process, so it doesn't show +which of this work a warm-up under another group and reform leaves for a +later request. A request can reuse only what the packages keep for the whole +process, such as the module-level parameter tree that every simulation's +baseline branch shares (``share_spm_policy`` in policyengine-us), +spm-calculator's threshold tables and price index series, and the modules the +calculation imports. A request's reform builds its own parameter tree, and +each simulation its own SPM amount cache. So ``SimulationWorker`` and ``SimulationSegmentWorker`` in ``src/modal/app.py`` run :func:`warm_up_first_calculation` in their @@ -35,9 +37,10 @@ importing them again could fetch the data release manifest again, and when the group's year file and baseline are in the image's data folder and the year file passes .py's reuse checks, so nothing is downloaded or - built from source. It skips the Google Cloud - credential setup of ``run_simulation_impl``, which reads a Modal Secret: - Secrets aren't read before the snapshot. + built from source. It skips the Google Cloud credential setup of + ``run_simulation_impl``, which reads a Modal Secret, and reads no Secret + itself. (The preload before it already reads the Hugging Face token and + fetches the data release manifest, as ``country_model_preload`` says.) - **No telemetry.** It configures no observability and gives the calculation a runtime that records and sends nothing, so it writes no operation record or span and no call number (``_ContainerCalls``). @@ -45,7 +48,10 @@ .py's in-process cache and the output files it saved in the data folder, so a later call loads its baseline from the image as it would without the warm-up. What stays is what the packages keep for the whole process, as - above, and the modules the calculation imported. + above. One case differs: when .py finds the baked baseline incomplete or + out of date, it calculates it again and saves it over the image's file, as + a call would. That file goes into the snapshot, so restored containers + load it and report a hit; the warm-up logs a warning naming it. - **Never fatal.** A failure or skip logs a warning, and the container starts as it would without the warm-up. """ @@ -233,14 +239,18 @@ def _removing_what_the_calculation_leaves(data_folder: Path) -> Iterator[None]: random ID) and saves an output it calculated beside the dataset, as ``.h5``. Left there, they would go into the snapshot, and a later call for the warm-up's group would use the cached baseline instead - of loading the baked one. + of loading the baked one. An output saved over a file the image already + held can't be undone here, so it is logged as a warning. """ from policyengine.core.simulation import ( # noqa: PLC0415 # resolved per call so tests can patch policyengine's simulation cache _cache as simulation_cache, ) cached_before = set(simulation_cache._cache) # noqa: SLF001 # policyengine's LRUCache has no public listing or remove - outputs_before = set(data_folder.glob("*.h5")) + outputs_before = { + output: _size_and_modification_time(output) + for output in data_folder.glob("*.h5") + } try: yield finally: @@ -250,6 +260,27 @@ def _removing_what_the_calculation_leaves(data_folder: Path) -> Iterator[None]: if storage_id not in cached_before ]: simulation_cache._cache.pop(storage_id, None) # noqa: SLF001 # as above - for output in set(data_folder.glob("*.h5")) - outputs_before: + for output in set(data_folder.glob("*.h5")) - outputs_before.keys(): output.unlink(missing_ok=True) gc.collect() + saved_over = sorted( + output.name + for output, state_before in outputs_before.items() + if _size_and_modification_time(output) != state_before + ) + if saved_over: + logger.warning( + "The warm-up calculation saved over %s in the image's data " + "folder, which .py found incomplete or out of date; containers " + "restored from this snapshot load the warm-up's copy", + ", ".join(saved_over), + ) + + +def _size_and_modification_time(path: Path) -> tuple[int, int] | None: + """Return a file's size and modification time in nanoseconds, or None if gone.""" + try: + status = path.stat() + except FileNotFoundError: + return None + return status.st_size, status.st_mtime_ns From a58bed5004c6a16c2399f336600c18855c2b12d8 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:42:12 +0400 Subject: [PATCH 07/10] Describe the warm-up's saved-over baseline case accurately The baked baseline is calculated again when it is incomplete, out of date or unreadable, not only in the two cases the docstrings and the warning named, and the warm-up keeps the recalculated copy by choice. The test module's docstring no longer says SPM threshold amounts carry over to later calculations. Co-Authored-By: Claude Opus 5.5 --- .../src/modal/snapshot_warm_up.py | 18 +++++++++++------- .../tests/test_snapshot_warm_up.py | 13 ++++++------- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py b/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py index dd2dae320..9e36cc426 100644 --- a/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py +++ b/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py @@ -48,10 +48,12 @@ .py's in-process cache and the output files it saved in the data folder, so a later call loads its baseline from the image as it would without the warm-up. What stays is what the packages keep for the whole process, as - above. One case differs: when .py finds the baked baseline incomplete or - out of date, it calculates it again and saves it over the image's file, as - a call would. That file goes into the snapshot, so restored containers - load it and report a hit; the warm-up logs a warning naming it. + above. One case differs: when the baked baseline is incomplete, out of + date or unreadable, the calculation runs it again and saves it over the + image's file, as a call would. The warm-up keeps that copy, which holds + the baseline the calculation needed, so it goes into the snapshot and + restored containers load it; it logs a warning naming the file, since + those containers' calls then don't report the baked file's problem. - **Never fatal.** A failure or skip logs a warning, and the container starts as it would without the warm-up. """ @@ -240,7 +242,8 @@ def _removing_what_the_calculation_leaves(data_folder: Path) -> Iterator[None]: ``.h5``. Left there, they would go into the snapshot, and a later call for the warm-up's group would use the cached baseline instead of loading the baked one. An output saved over a file the image already - held can't be undone here, so it is logged as a warning. + held, when the baked baseline was incomplete, out of date or unreadable, + is kept, and logged as a warning. """ from policyengine.core.simulation import ( # noqa: PLC0415 # resolved per call so tests can patch policyengine's simulation cache _cache as simulation_cache, @@ -271,8 +274,9 @@ def _removing_what_the_calculation_leaves(data_folder: Path) -> Iterator[None]: if saved_over: logger.warning( "The warm-up calculation saved over %s in the image's data " - "folder, which .py found incomplete or out of date; containers " - "restored from this snapshot load the warm-up's copy", + "folder, because the baked file was incomplete, out of date or " + "unreadable; containers restored from this snapshot load the " + "warm-up's copy", ", ".join(saved_over), ) diff --git a/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py b/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py index d2500fb4b..fde9fa560 100644 --- a/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py +++ b/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py @@ -1,12 +1,11 @@ """The warm-up calculation the simulation workers run before their memory snapshot. -The first calculation in a process builds the US parameter values for its -year and the SPM threshold amounts, which later calculations reuse. The -workers' snapshot hook runs one calculation of a region group whose dataset -and baseline are in the image, so containers restored from the snapshot -start with that work done. These tests replace the calculation itself with a -fake that touches .py's in-process simulation cache and the data folder as a -real one does. +A process's first calculation for a year does one-time work that later +calculations reuse. The workers' snapshot hook runs one calculation of a +region group whose dataset and baseline are in the image, so containers +restored from the snapshot start with that work done. These tests replace +the calculation itself with a fake that touches .py's in-process simulation +cache and the data folder as a real one does. """ from __future__ import annotations From d606b983cccedcbd9effef2dab1a369392837d85 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:11:29 +0400 Subject: [PATCH 08/10] Move the warm-up tests onto the prebuilt level handlers (failing) Since the precompute moved onto the level handlers (#1132), the image keeps year files and baselines under prebuilt////, and a run finds its year file through simulation_runtime._prebuilt_folder, which returns no folder for a year file the image lacks or .py wouldn't reuse. The tests now expect the warm-up to: - calculate group 1's precomputed current-law request from the US group-of-states handler, for the first prebuilt year, with a reform added; - look up its baked inputs as a run of that request does: the region and dataset resolution, the prebuilt-folder lookup and the precompute's baseline identity, with the baseline beside the year file; - clean up in the prebuilt folder, where outputs are now saved; - read none of the workers' Secrets, under any name the code reads them by. A new test fails the old module outright: with a module the warm-up uses made unimportable, the app must still import and the hook only log a warning. With main merged in, the old module's import-time imports made the whole app fail to import. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_snapshot_warm_up.py | 304 +++++++++++------- 1 file changed, 187 insertions(+), 117 deletions(-) diff --git a/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py b/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py index fde9fa560..cff0780a0 100644 --- a/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py +++ b/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py @@ -2,10 +2,11 @@ A process's first calculation for a year does one-time work that later calculations reuse. The workers' snapshot hook runs one calculation of a -region group whose dataset and baseline are in the image, so containers -restored from the snapshot start with that work done. These tests replace -the calculation itself with a fake that touches .py's in-process simulation -cache and the data folder as a real one does. +region group whose year file and baseline are prebuilt into the image, so +containers restored from the snapshot start with that work done. These tests +replace the calculation itself with a fake that touches .py's in-process +simulation cache and the prebuilt folder as a real one does, and replace the +region, dataset and prebuilt-folder lookups, which need the US model. """ from __future__ import annotations @@ -15,7 +16,6 @@ import os import sys from collections.abc import Iterator, MutableMapping -from pathlib import Path from types import ModuleType, SimpleNamespace from typing import TYPE_CHECKING from uuid import uuid4 @@ -24,25 +24,24 @@ from conftest import NoOpObservabilityRuntime from fixtures.fake_modal import install_fake_modal from policyengine_observability.runtime import ObservabilityRuntime -from policyengine_simulation_executor import ( - precompute_planning, - simulation_runtime, - state_datasets, -) +from policyengine_simulation_executor import precompute_planning, simulation_runtime from policyengine_simulation_executor.national_partition import national_region_groups +from policyengine_simulation_executor.stage12_cache import levels from src.modal import segmented_national if TYPE_CHECKING: + from pathlib import Path + from policyengine.core.cache import LRUCache -# The image's baked year file for the warm-up year, and the baked baseline's -# storage ID, as the precompute names them. -BAKED_DATASET_NAME = "enhanced_cps_2024" -BAKED_DATASET_FILENAME = "enhanced_cps_2024_year_2026.h5" -BAKED_BASELINE_STORAGE_ID = "bl1-warmupgroupbaseline" +# The default dataset's prebuilt folder, its 2026 year file, and the warm-up +# group's baked baseline, as the precompute names them. +PREBUILT_FOLDER = "prebuilt/us/populace_us_2024/all" +PREBUILT_YEAR_FILENAME = "populace_us_2024_year_2026.h5" +BAKED_BASELINE_STORAGE_ID = "bl3-warmupgroupbaseline" SNAPSHOT_TASK_ID = "ta-01SNAPSHOTTING" # A request the container serves after its snapshot hook: another region -# group, under another reform, as in the measurement on Modal `testing`. +# group, under another reform, as in the measurements on Modal `testing`. LATER_REQUEST = { "country": "us", "scope": "macro", @@ -54,22 +53,33 @@ "_emit_microdata": True, } US_MODEL_MODULES = ("policyengine_us", "policyengine.tax_benefit_models.us") +# Modal Secrets the workers have: Google Cloud credentials and the Hugging +# Face token, under every name the code reads them by. +SECRET_ENVIRONMENT_NAMES = { + "GOOGLE_APPLICATION_CREDENTIALS_JSON", + "GCP_CREDENTIALS_JSON", + "GOOGLE_CREDENTIALS", + "SERVICE_ACCOUNT_JSON", + "HUGGING_FACE_TOKEN", + "HF_TOKEN", + "HUGGINGFACE_HUB_TOKEN", +} class _PolicyEngineLikeCalculation: """Stands in for the simulation path, leaving what a real calculation leaves. A real calculation's ``ensure()`` adds its baseline to .py's in-process - cache under the baseline's deterministic storage ID, adds its reform under - a new random ID, and saves the reform's output beside the dataset. Each - call returns what it found in the cache and the data folder before it - calculated, which a real call's result depends on: a cached baseline is - used instead of the baked file. + cache under the baseline's fixed storage ID, adds its reform under a new + random ID, and saves the reform's output beside the year file, in the + prebuilt folder. Each call returns what it found in the cache and that + folder before it calculated, which a real call's result depends on: a + cached baseline is used instead of the baked file. """ - def __init__(self, cache: LRUCache, data_folder) -> None: + def __init__(self, cache: LRUCache, output_folder: Path) -> None: self.cache = cache - self.data_folder = data_folder + self.output_folder = output_folder self.requests: list[dict] = [] self.runtimes: list[object] = [] @@ -80,14 +90,14 @@ def __call__(self, params: dict, *, runtime, progress=None) -> dict: runtime.set_context(region="+".join(params.get("region_group", []))) state_seen = { "cached_simulations": sorted(self.cache._cache), - "data_folder_files": sorted( - path.name for path in self.data_folder.iterdir() + "output_folder_files": sorted( + path.name for path in self.output_folder.iterdir() ), } reform_storage_id = str(uuid4()) self.cache.add(BAKED_BASELINE_STORAGE_ID, SimpleNamespace(role="baseline")) self.cache.add(reform_storage_id, SimpleNamespace(role="reform")) - (self.data_folder / f"{reform_storage_id}.h5").write_bytes(b"reform output") + (self.output_folder / f"{reform_storage_id}.h5").write_bytes(b"reform output") return { "state_seen": state_seen, "region_group": params.get("region_group"), @@ -150,35 +160,66 @@ def snapshotted_container(monkeypatch): @pytest.fixture def requested_identities(monkeypatch): - """Answer the precompute's baseline identity, recording each year and group.""" - requested: list[tuple[int, list[str]]] = [] - - def baked_identity(year, group): - requested.append((year, list(group))) - return SimpleNamespace( - dataset=SimpleNamespace( - dataset=BAKED_DATASET_NAME, filename=BAKED_DATASET_FILENAME - ), - storage_id=BAKED_BASELINE_STORAGE_ID, - ) + """Answer the precompute's baseline identity, recording each target asked about.""" + requested: list[levels.BaselineTarget] = [] + + def baked_identity(target): + requested.append(target) + return SimpleNamespace(storage_id=BAKED_BASELINE_STORAGE_ID) - monkeypatch.setattr(precompute_planning, "cohort_identity", baked_identity) + monkeypatch.setattr(precompute_planning, "baseline_target_identity", baked_identity) return requested @pytest.fixture -def image_data_folder(tmp_path, monkeypatch, requested_identities): - """Create the image's data folder, holding the warm-up group's baked inputs.""" +def prebuilt_image(tmp_path, monkeypatch, requested_identities): + """Create the image's prebuilt folder, and answer a run's lookups as in the image. + + The prebuilt-folder lookup answers as ``levels.prebuilt_dataset_folder`` + does: the folder when it holds the year file, and None otherwise, which is + also its answer for a year file .py wouldn't reuse. + """ data_folder = tmp_path / "data" - data_folder.mkdir() - (data_folder / BAKED_DATASET_FILENAME).write_bytes(b"baked year file") - (data_folder / f"{BAKED_BASELINE_STORAGE_ID}.h5").write_bytes(b"baked baseline") + prebuilt_folder = data_folder / PREBUILT_FOLDER + prebuilt_folder.mkdir(parents=True) + (prebuilt_folder / PREBUILT_YEAR_FILENAME).write_bytes(b"prebuilt year file") + (prebuilt_folder / f"{BAKED_BASELINE_STORAGE_ID}.h5").write_bytes(b"baseline") monkeypatch.setenv("POLICYENGINE_DATA_FOLDER", str(data_folder)) - # .py's own checks would read the files' stamps, which these stand-ins lack. + group_region = SimpleNamespace( + code="region_group/state/hi+state/ia+state/wi", + scoping_strategy="group row filter", + state_code=None, + ) + default_dataset = simulation_runtime.DatasetSelection( + "populace_us_2024", "hf://policyengine/populace_us_2024.h5", is_default=True + ) + image = SimpleNamespace( + prebuilt_folder=prebuilt_folder, + group_region=group_region, + default_dataset=default_dataset, + regions_resolved=[], + folder_lookups=[], + ) + + def resolve_region(*, country_module, country, params): + image.regions_resolved.append((country, dict(params))) + return group_region + + def prebuilt_folder_lookup(country, region, selection, year): + image.folder_lookups.append((country, region, selection, year)) + if not (prebuilt_folder / PREBUILT_YEAR_FILENAME).is_file(): + return None + return levels.PrebuiltFolder(folder=str(prebuilt_folder), dataset_source=None) + + monkeypatch.setattr(simulation_runtime, "_country_module", lambda country: country) + monkeypatch.setattr(simulation_runtime, "resolve_region", resolve_region) monkeypatch.setattr( - state_datasets, "year_file_reuse_problem", lambda _path, _dataset: None + simulation_runtime, + "_resolve_dataset_selection", + lambda _params, *, region_resolution: default_dataset, ) - return data_folder + monkeypatch.setattr(simulation_runtime, "_prebuilt_folder", prebuilt_folder_lookup) + return image @pytest.fixture @@ -196,9 +237,11 @@ def simulation_cache(monkeypatch): @pytest.fixture -def calculation(monkeypatch, simulation_cache, image_data_folder): +def calculation(monkeypatch, simulation_cache, prebuilt_image): """Replace the simulation path's calculation with a .py-like fake.""" - fake_calculation = _PolicyEngineLikeCalculation(simulation_cache, image_data_folder) + fake_calculation = _PolicyEngineLikeCalculation( + simulation_cache, prebuilt_image.prebuilt_folder + ) monkeypatch.setattr( simulation_runtime, "_run_simulation_impl_core", fake_calculation ) @@ -225,10 +268,18 @@ def configure_runtime(*, service_role: str): return configure_runtime -def _restore_initial_state(cache: LRUCache, data_folder, files_before: set) -> None: - """Put the cache and data folder back as they were when the container started.""" +def _first_group_target() -> levels.BaselineTarget: + """Return group 1's baseline target for the first prebuilt US year.""" + prebuilt = levels.prebuilt_for("us") + assert prebuilt is not None + group_handler = prebuilt.handlers[levels.DatasetLevel.STATE_GROUP] + return group_handler.baseline_targets(prebuilt.years[0])[0] + + +def _restore_initial_state(cache: LRUCache, folder: Path, files_before: set) -> None: + """Put the cache and the folder back as they were when the container started.""" cache.clear() - for path in data_folder.iterdir(): + for path in folder.iterdir(): if path.name not in files_before: path.unlink() @@ -254,66 +305,60 @@ def test_the_snapshot_hook_runs_the_warm_up_once_after_the_preload( @pytest.mark.usefixtures("snapshotted_container") -def test_the_warm_up_calculates_one_baked_group_for_the_first_precompute_year( - warm_up_module, calculation, requested_identities +def test_the_warm_up_calculates_group_1_for_the_first_prebuilt_year( + warm_up_module, calculation, requested_identities, prebuilt_image ): warm_up_module.warm_up_first_calculation() [request] = calculation.requests - first_precompute_year = precompute_planning.PRECOMPUTE_YEARS[0] - # A segmented national run's child request, which the precompute bakes a - # current-law baseline for in every year it covers. - assert request["country"] == "us" - assert request["scope"] == "macro" - assert int(request["time_period"]) == first_precompute_year - assert request["region_group"] in national_region_groups("us") + first_group_target = _first_group_target() + # Group 1's precomputed current-law request, as a segmented national + # run's child receives it, with a reform so the reform is calculated. + assert { + key: value + for key, value in request.items() + if key not in {"reform", "_emit_microdata"} + } == dict(first_group_target.request) + assert request["region_group"] == national_region_groups("us")[0] + assert request["time_period"] == levels.prebuilt_for("us").years[0] assert request["_emit_microdata"] is True - assert "region" not in request - assert "baseline" not in request - # A reform, so the warm-up calculates the reform as a request does. assert request["reform"] - assert requested_identities == [(first_precompute_year, request["region_group"])] + # Its baked inputs are looked up as a run of the request looks them up. + assert requested_identities == [first_group_target] + assert [params for _country, params in prebuilt_image.regions_resolved] == [request] + assert prebuilt_image.folder_lookups == [ + ( + "us", + prebuilt_image.group_region, + prebuilt_image.default_dataset, + first_group_target.year, + ) + ] @pytest.mark.usefixtures("snapshotted_container") @pytest.mark.parametrize( - "missing_filename", - [BAKED_DATASET_FILENAME, f"{BAKED_BASELINE_STORAGE_ID}.h5"], + "missing_input", + [ + (PREBUILT_YEAR_FILENAME, "prebuilt year file"), + (f"{BAKED_BASELINE_STORAGE_ID}.h5", f"{BAKED_BASELINE_STORAGE_ID}.h5"), + ], ) def test_the_warm_up_skips_with_a_warning_unless_the_image_holds_its_inputs( - warm_up_module, calculation, image_data_folder, missing_filename, caplog -): - # Without a baked year file the dataset would be built from its source, - # which may download it; without a baked baseline it would be calculated. - (image_data_folder / missing_filename).unlink() - - with caplog.at_level(logging.WARNING, logger=warm_up_module.__name__): - warm_up_module.warm_up_first_calculation() - - assert calculation.requests == [] - assert missing_filename in caplog.text - - -@pytest.mark.usefixtures("snapshotted_container") -def test_the_warm_up_skips_with_a_warning_when_the_baked_year_file_would_be_rebuilt( - warm_up_module, calculation, monkeypatch, caplog + warm_up_module, calculation, prebuilt_image, missing_input, caplog ): - # .py's ensure_datasets rebuilds a year file that fails its reuse checks - # from the dataset's source, which it may download from Hugging Face. - checked_year_files: list[tuple[str, str]] = [] - - def out_of_date(path, dataset): - checked_year_files.append((Path(path).name, dataset)) - return "the year file records another register of renamed inputs" - - monkeypatch.setattr(state_datasets, "year_file_reuse_problem", out_of_date) + # Without a usable prebuilt year file the dataset would be built from its + # source, which may download it; without a baked baseline the baseline + # would be calculated. + missing_filename, expected_warning = missing_input + (prebuilt_image.prebuilt_folder / missing_filename).unlink() with caplog.at_level(logging.WARNING, logger=warm_up_module.__name__): warm_up_module.warm_up_first_calculation() assert calculation.requests == [] - assert checked_year_files == [(BAKED_DATASET_FILENAME, BAKED_DATASET_NAME)] - assert "another register of renamed inputs" in caplog.text + assert "Warm-up calculation skipped" in caplog.text + assert expected_warning in caplog.text @pytest.mark.usefixtures("snapshotted_container") @@ -336,8 +381,9 @@ def refuse(*_args, **_kwargs): monkeypatch.setattr(simulation_runtime, "setup_gcp_credentials", refuse) monkeypatch.setattr(simulation_runtime, "run_simulation_impl", refuse) - # Records the warm-up's own reads. The calculation is replaced here, so - # what the simulation path reads is checked by reading its code instead. + # Records the warm-up's own reads, the real group target's included. The + # calculation and the lookups that need the model are replaced here, so + # what they read is checked by reading their code instead. environment = _EnvironmentReadRecorder(os.environ) monkeypatch.setattr(os, "environ", environment) @@ -347,11 +393,7 @@ def refuse(*_args, **_kwargs): assert refusals == [] assert caplog.records == [] assert len(calculation.requests) == 1 - # Only the snapshot flag Modal sets and the image's data folder. - assert environment.names_read <= { - "MODAL_ENABLE_SNAP_RESTORE", - "POLICYENGINE_DATA_FOLDER", - } + assert environment.names_read.isdisjoint(SECRET_ENVIRONMENT_NAMES) assert "GOOGLE_APPLICATION_CREDENTIALS" not in environment.environment @@ -411,7 +453,7 @@ def set_context(self, **attributes): def test_a_failed_warm_up_only_logs_a_warning( warm_up_module, calculation, monkeypatch, caplog ): - files_before = {path.name for path in calculation.data_folder.iterdir()} + files_before = {path.name for path in calculation.output_folder.iterdir()} def failing_calculation(params, **options): calculation(params, **options) @@ -428,18 +470,20 @@ def failing_calculation(params, **options): assert "the reform parameter is not in this model version" in caplog.text # What the failed calculation left is removed too. assert len(calculation.cache) == 0 - assert {path.name for path in calculation.data_folder.iterdir()} == files_before + assert {path.name for path in calculation.output_folder.iterdir()} == files_before -@pytest.mark.usefixtures("snapshotted_container", "image_data_folder") +@pytest.mark.usefixtures("snapshotted_container", "prebuilt_image") def test_a_failure_before_the_calculation_only_logs_a_warning( warm_up_module, calculation, monkeypatch, caplog ): - def unreadable_identity(_year, _group): + def unreadable_identity(_target): msg = "the bundle receipt is unreadable" raise OSError(msg) - monkeypatch.setattr(precompute_planning, "cohort_identity", unreadable_identity) + monkeypatch.setattr( + precompute_planning, "baseline_target_identity", unreadable_identity + ) with caplog.at_level(logging.WARNING, logger=warm_up_module.__name__): warm_up_module.warm_up_first_calculation() @@ -448,6 +492,30 @@ def unreadable_identity(_year, _group): assert "the bundle receipt is unreadable" in caplog.text +@pytest.mark.usefixtures("snapshotted_container") +def test_the_app_imports_and_starts_when_the_warm_up_cannot_import_its_modules( + monkeypatch, caplog +): + # A change elsewhere can move or rename what the warm-up imports, as the + # move of the precompute onto the level handlers did. That must cost only + # the warm-up, never the import of the app. + install_fake_modal(monkeypatch) + monkeypatch.setitem( + sys.modules, "policyengine_simulation_executor.precompute_planning", None + ) + for module_name in ("src.modal.snapshot_warm_up", "src.modal.app"): + monkeypatch.delitem(sys.modules, module_name, raising=False) + + app = importlib.import_module("src.modal.app") + monkeypatch.setattr(app, "preload_country_models", lambda: None) + with caplog.at_level(logging.WARNING, logger="src.modal.snapshot_warm_up"): + app.SimulationSegmentWorker().load_country_models() + + assert "Warm-up calculation failed" in caplog.text + for module_name in ("src.modal.snapshot_warm_up", "src.modal.app"): + sys.modules.pop(module_name, None) + + @pytest.mark.usefixtures("snapshotted_container") def test_a_failed_warm_up_never_stops_the_container_starting( modal_app, calculation, monkeypatch @@ -482,13 +550,14 @@ def failing_calculation(_params, **_options): @pytest.mark.usefixtures("snapshotted_container") def test_a_call_after_the_warm_up_finds_no_simulation_or_file_the_warm_up_added( - warm_up_module, calculation, simulation_cache, image_data_folder + warm_up_module, calculation, simulation_cache, prebuilt_image ): - files_before = {path.name for path in image_data_folder.iterdir()} + prebuilt_folder = prebuilt_image.prebuilt_folder + files_before = {path.name for path in prebuilt_folder.iterdir()} without_warm_up = calculation( dict(LATER_REQUEST), runtime=NoOpObservabilityRuntime() ) - _restore_initial_state(simulation_cache, image_data_folder, files_before) + _restore_initial_state(simulation_cache, prebuilt_folder, files_before) warm_up_module.warm_up_first_calculation() after_warm_up = calculation(dict(LATER_REQUEST), runtime=NoOpObservabilityRuntime()) @@ -501,12 +570,12 @@ def test_a_call_after_the_warm_up_finds_no_simulation_or_file_the_warm_up_added( @pytest.mark.usefixtures("snapshotted_container") def test_the_warm_up_warns_when_it_saved_over_a_baked_file( - warm_up_module, calculation, image_data_folder, monkeypatch, caplog + warm_up_module, calculation, prebuilt_image, monkeypatch, caplog ): - # .py calculates a baked baseline again and saves it over the image's - # file when it finds it incomplete or out of date. The rewritten file goes - # into the snapshot, so restored containers load it and report a hit. - baked_baseline = image_data_folder / f"{BAKED_BASELINE_STORAGE_ID}.h5" + # The calculation runs a baked baseline again and saves it over the + # image's file when it is incomplete, out of date or unreadable. The + # rewritten file goes into the snapshot, so restored containers load it. + baked_baseline = prebuilt_image.prebuilt_folder / f"{BAKED_BASELINE_STORAGE_ID}.h5" def recalculating_calculation(params, **options): result = calculation(params, **options) @@ -525,7 +594,7 @@ def recalculating_calculation(params, **options): assert baked_baseline.name in warning.getMessage() -@pytest.mark.usefixtures("image_data_folder") +@pytest.mark.usefixtures("prebuilt_image") def test_a_container_modal_takes_no_snapshot_from_skips_the_warm_up( warm_up_module, calculation, monkeypatch ): @@ -545,7 +614,7 @@ def test_a_container_modal_takes_no_snapshot_from_skips_the_warm_up( assert calculation.requests == [] -@pytest.mark.usefixtures("image_data_folder") +@pytest.mark.usefixtures("prebuilt_image") def test_the_warm_up_skips_with_a_warning_when_the_us_models_were_not_preloaded( warm_up_module, calculation, monkeypatch, caplog ): @@ -569,12 +638,13 @@ def test_the_warm_up_reform_changes_a_parameter_of_the_installed_us_model( # would also read the data release manifest from Hugging Face. from policyengine_us.system import system - [(parameter_name, values_by_period)] = warm_up_module.warm_up_request()[ + target = _first_group_target() + [(parameter_name, values_by_period)] = warm_up_module.warm_up_request(target)[ "reform" ].items() [(period, reform_value)] = values_by_period.items() period_start, _, _period_end = period.partition(".") - assert period_start == f"{precompute_planning.PRECOMPUTE_YEARS[0]}-01-01" + assert period_start == f"{target.year}-01-01" # A reform equal to current law would leave nothing to calculate. assert system.parameters.get_child(parameter_name)(period_start) != reform_value From a2b2da8587d43866d76437c30c26af457667e34a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:14:44 +0400 Subject: [PATCH 09/10] Rework the warm-up onto the prebuilt level handlers #1132 moved the precompute onto the level handlers: it deleted state_datasets.py, replaced the precompute planning names the warm-up imported, and moved baked files under prebuilt//. With that in main, the warm-up module failed to import, and app.py, which imports it, failed with it. - The group and year come from the US group-of-states handler: group 1's current-law request for the first prebuilt year, with the reform added. Group 1 is still state/hi+state/ia+state/wi, the group both measurements used. - The baked inputs are found as a run of that request finds them: region and dataset resolution, then simulation_runtime._prebuilt_folder, which returns no folder for a year file the image lacks or .py wouldn't reuse; the baseline is the precompute's own identity for the group, beside the year file. Either missing skips the warm-up with a warning. - The cleanup looks in the prebuilt folder, where outputs are now saved. - Every executor module the warm-up uses is imported when it runs, so a later move or rename in them only costs the warm-up, with a warning, instead of stopping the app from importing. Co-Authored-By: Claude Opus 5.5 --- .../src/modal/snapshot_warm_up.py | 225 ++++++++++-------- 1 file changed, 132 insertions(+), 93 deletions(-) diff --git a/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py b/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py index 9e36cc426..bbd174f33 100644 --- a/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py +++ b/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py @@ -23,10 +23,11 @@ containers' first calculation 11 to 16 s faster, with identical results, and the containers Modal took snapshots from started about 70 to 100 s later. -The warm-up calculates one segmented national run's child request: a region -group whose dataset and current-law baseline the precompute bakes into the -image, for the first precompute year, under a small reform. It runs only -where it is safe before a snapshot, and only where Modal takes one: +The warm-up calculates one segmented national run's child request: group 1 +of the US group-of-states handler, whose year file and current-law baseline +the precompute builds into the image, for the first prebuilt year, under a +small reform. It runs only where it is safe before a snapshot, and only where +Modal takes one: - **Only in a container Modal snapshots.** Modal runs the hook in every container that isn't restored, and takes a snapshot only where its worker @@ -35,19 +36,20 @@ save that call about 15 s. - **No connection.** It runs only when the US models were preloaded, since importing them again could fetch the data release manifest again, and - when the group's year file and baseline are in the image's data folder - and the year file passes .py's reuse checks, so nothing is downloaded or - built from source. It skips the Google Cloud credential setup of - ``run_simulation_impl``, which reads a Modal Secret, and reads no Secret - itself. (The preload before it already reads the Hugging Face token and - fetches the data release manifest, as ``country_model_preload`` says.) + when the image's prebuilt folder holds the group's year file, in a form + .py reuses, and its baseline. Both are looked up as a run looks them up, + so nothing is downloaded or built from source. It skips the Google Cloud + credential setup of ``run_simulation_impl``, which reads a Modal Secret, + and reads no Secret itself. (The preload before it already reads the + Hugging Face token and fetches the data release manifest, as + ``country_model_preload`` says.) - **No telemetry.** It configures no observability and gives the calculation a runtime that records and sends nothing, so it writes no operation record or span and no call number (``_ContainerCalls``). - **Nothing left for a request.** It removes the simulations it added to - .py's in-process cache and the output files it saved in the data folder, - so a later call loads its baseline from the image as it would without the - warm-up. What stays is what the packages keep for the whole process, as + .py's in-process cache and the output files it saved in the prebuilt + folder, so a later call loads its baseline from the image as it would + without the warm-up. What stays is what the packages keep for the whole process, as above. One case differs: when the baked baseline is incomplete, out of date or unreadable, the calculation runs it again and saves it over the image's file, as a call would. The warm-up keeps that copy, which holds @@ -55,7 +57,9 @@ restored containers load it; it logs a warning naming the file, since those containers' calls then don't report the baked file's problem. - **Never fatal.** A failure or skip logs a warning, and the container - starts as it would without the warm-up. + starts as it would without the warm-up. The executor modules it uses are + imported when it runs, not when ``app.py`` imports this module, so a move + or rename in them costs only the warm-up. """ from __future__ import annotations @@ -70,20 +74,13 @@ from pathlib import Path from typing import TYPE_CHECKING, Any, cast -from policyengine_simulation_executor.national_partition import ( - US_NATIONAL_REGION_GROUPS, -) -from policyengine_simulation_executor.precompute_planning import ( - PRECOMPUTE_COUNTRY, - PRECOMPUTE_YEARS, - cohort_params, -) from src.modal.country_model_preload import COUNTRY_MODEL_MODULES if TYPE_CHECKING: from collections.abc import Iterator from policyengine_observability import ObservabilityRuntime + from policyengine_simulation_executor.stage12_cache.levels import BaselineTarget logger = logging.getLogger(__name__) @@ -91,15 +88,17 @@ # or restores (``run_function`` in modal/_container_entrypoint.py, Modal # 1.6.4). Restored containers don't run the snapshot hook. SNAPSHOT_FLAG_ENV_NAME = "MODAL_ENABLE_SNAP_RESTORE" -WARM_UP_YEAR = PRECOMPUTE_YEARS[0] -# The group the measurement on Modal ``testing`` warmed up with. -WARM_UP_REGION_GROUP = US_NATIONAL_REGION_GROUPS[0] +WARM_UP_COUNTRY = "us" # The reform makes the warm-up calculate a reform simulation, as a request # does: the Child Tax Credit's base amount, raised to $2,500. WARM_UP_REFORM_PARAMETER = "gov.irs.credits.ctc.amount.base[0].amount" WARM_UP_REFORM_VALUE = 2500 +class _WarmUpUnsafeError(Exception): + """The warm-up can't run safely before the snapshot; the message says why.""" + + class _RecordNothingRuntime: """The observability runtime the warm-up's calculation reports to. @@ -130,12 +129,35 @@ def capture_context(self) -> dict[str, str]: return {} -def warm_up_request() -> dict[str, Any]: - """Return the warm-up's request: one region group's child of a national run.""" - request = cohort_params(WARM_UP_YEAR, list(WARM_UP_REGION_GROUP)) +def warm_up_target() -> BaselineTarget: + """Return group 1's precomputed current-law baseline, for the first prebuilt year. + + The US settings' group-of-states handler names the groups and years the + precompute bakes a current-law baseline for. Group 1 is the group the + measurements on Modal ``testing`` warmed up with. + """ + from policyengine_simulation_executor.precompute_planning import ( # noqa: PLC0415 # imported here so a move of the precompute code costs only the warm-up, never the app's import + country_prebuilt, + ) + from policyengine_simulation_executor.stage12_cache.levels import ( # noqa: PLC0415 # as above + DatasetLevel, + ) + + prebuilt = country_prebuilt(WARM_UP_COUNTRY) + group_handler = prebuilt.handlers[DatasetLevel.STATE_GROUP] + return group_handler.baseline_targets(prebuilt.years[0])[0] + + +def warm_up_request(target: BaselineTarget) -> dict[str, Any]: + """Return the warm-up's request: ``target``'s request, with a reform added. + + ``target.request`` is the request a segmented national run's child for the + group receives under current law. + """ + request = dict(target.request) request["reform"] = { WARM_UP_REFORM_PARAMETER: { - f"{WARM_UP_YEAR}-01-01.2100-12-31": WARM_UP_REFORM_VALUE + f"{target.year}-01-01.2100-12-31": WARM_UP_REFORM_VALUE } } request["_emit_microdata"] = True @@ -147,100 +169,117 @@ def warm_up_first_calculation() -> None: Does nothing in any other container. Nothing here may stop a container from starting: a failure or skip logs a warning, and each container's - first calculation then builds its year's values itself, as before. + first calculation then does its one-time work itself, as before. """ if os.environ.get(SNAPSHOT_FLAG_ENV_NAME) != "1": return - started = time.monotonic() try: - skip_reason = _calculate_unless_unsafe() + _calculate_unless_unsafe() + except _WarmUpUnsafeError as unsafe: + logger.warning( + "Warm-up calculation skipped, so each restored container's first " + "calculation does its one-time work itself: %s", + unsafe, + ) except Exception: # noqa: BLE001 # the warm-up only makes first calls faster logger.warning( "Warm-up calculation failed; each restored container's first " - "calculation builds its year's values itself", + "calculation does its one-time work itself", exc_info=True, ) - return - if skip_reason is not None: - logger.warning( - "Warm-up calculation skipped, so each restored container's first " - "calculation builds its year's values itself: %s", - skip_reason, - ) - return - logger.info( - "Warm-up calculation of %s for %s finished in %.1fs", - "+".join(WARM_UP_REGION_GROUP), - WARM_UP_YEAR, - time.monotonic() - started, - ) -def _calculate_unless_unsafe() -> str | None: - """Run the warm-up calculation, or return why it would be unsafe to.""" +def _calculate_unless_unsafe() -> None: + """Run the warm-up calculation; raise ``_WarmUpUnsafeError`` when it isn't safe.""" not_preloaded = [ module_name - for module_name in COUNTRY_MODEL_MODULES[PRECOMPUTE_COUNTRY] + for module_name in COUNTRY_MODEL_MODULES[WARM_UP_COUNTRY] if module_name not in sys.modules ] if not_preloaded: - return f"the preload didn't import {', '.join(not_preloaded)}" + msg = f"the preload didn't import {', '.join(not_preloaded)}" + raise _WarmUpUnsafeError(msg) from policyengine_simulation_executor.simulation_runtime import ( # noqa: PLC0415 # resolved per call so tests can patch simulation_runtime; loaded in the worker container, not at deploy time _run_simulation_impl_core, - resolve_data_folder, ) - data_folder = Path(resolve_data_folder()) - baked_inputs_problem = _baked_inputs_problem(data_folder) - if baked_inputs_problem is not None: - return baked_inputs_problem - with _removing_what_the_calculation_leaves(data_folder): + target = warm_up_target() + request = warm_up_request(target) + prebuilt_folder = _prebuilt_folder_with_baked_inputs(target, request) + started = time.monotonic() + with _removing_what_the_calculation_leaves(prebuilt_folder): _run_simulation_impl_core( - warm_up_request(), - runtime=cast("ObservabilityRuntime", _RecordNothingRuntime()), + request, runtime=cast("ObservabilityRuntime", _RecordNothingRuntime()) ) - return None + logger.info( + "Warm-up calculation of the %s for %s finished in %.1fs", + target.label, + target.year, + time.monotonic() - started, + ) -def _baked_inputs_problem(data_folder: Path) -> str | None: - """Return why the warm-up can't use the image's baked inputs, or None. +def _prebuilt_folder_with_baked_inputs( + target: BaselineTarget, request: dict[str, Any] +) -> Path: + """Return the prebuilt folder holding the warm-up's year file and baseline. - The year file and the current-law baseline are named as the precompute - names them, and as the calculation looks for them. The year file must - also pass .py's reuse checks: otherwise ``ensure_datasets`` would build it - again from the dataset's source, which it may download. + Both are looked up as a run of ``request`` looks them up: the region and + dataset resolution, then the image's prebuilt-folder lookup, which finds + no folder for a year file the image lacks or .py wouldn't reuse; and the + precompute's identity for the group's baseline, which the image keeps + beside the year file as ``.h5``. Raises ``_WarmUpUnsafeError`` + when either is missing: the calculation would then build the year file + from its source, which it may download, or calculate the baseline. """ - from policyengine_simulation_executor.artifact_keys import ( # noqa: PLC0415 # loaded in the worker container, not at deploy time - baseline_artifact_filename, - ) - from policyengine_simulation_executor.precompute_planning import ( # noqa: PLC0415 # resolved per call so tests can patch precompute_planning.cohort_identity - cohort_identity, + from policyengine_simulation_executor.precompute_planning import ( # noqa: PLC0415 # resolved per call so tests can patch precompute_planning; and see warm_up_target + baseline_target_identity, ) - from policyengine_simulation_executor.state_datasets import ( # noqa: PLC0415 # resolved per call so tests can patch state_datasets.year_file_reuse_problem - year_file_reuse_problem, + from policyengine_simulation_executor.simulation_runtime import ( # noqa: PLC0415 # resolved per call so tests can patch simulation_runtime + _country_module, + _prebuilt_folder, + _resolve_dataset_selection, + resolve_region, ) - identity = cohort_identity(WARM_UP_YEAR, list(WARM_UP_REGION_GROUP)) - year_file = data_folder / identity.dataset.filename - baseline_file = data_folder / baseline_artifact_filename(identity.storage_id) - missing = [path.name for path in (year_file, baseline_file) if not path.is_file()] - if missing: - return f"the image's data folder lacks {', '.join(missing)}" - reuse_problem = year_file_reuse_problem(year_file, identity.dataset.dataset) - if reuse_problem is not None: - return f"its year file {year_file.name} would be built again: {reuse_problem}" - return None + region = resolve_region( + country_module=_country_module(target.country), + country=target.country, + params=request, + ) + dataset = _resolve_dataset_selection(request, region_resolution=region) + prebuilt = _prebuilt_folder(target.country, region, dataset, target.year) + if prebuilt is None: + msg = ( + f"the image holds no prebuilt year file .py would reuse for the " + f"{target.label} in {target.year}" + ) + raise _WarmUpUnsafeError(msg) + identity = baseline_target_identity(target) + if identity is None: + msg = f"the {target.label} baseline for {target.year} gets no fixed ID" + raise _WarmUpUnsafeError(msg) + folder = Path(prebuilt.folder) + baseline_filename = f"{identity.storage_id}.h5" + if not (folder / baseline_filename).is_file(): + msg = ( + f"the prebuilt folder {folder} lacks the {target.label} baseline " + f"{baseline_filename}" + ) + raise _WarmUpUnsafeError(msg) + return folder @contextlib.contextmanager -def _removing_what_the_calculation_leaves(data_folder: Path) -> Iterator[None]: +def _removing_what_the_calculation_leaves(output_folder: Path) -> Iterator[None]: """Remove the simulations and output files a calculation adds, even if it fails. .py's ``Simulation.ensure()`` caches each simulation in the process (its baseline under the baked baseline's storage ID, its reform under a new - random ID) and saves an output it calculated beside the dataset, as - ``.h5``. Left there, they would go into the snapshot, and a - later call for the warm-up's group would use the cached baseline instead + random ID) and saves an output it calculated beside the year file it + loaded, in ``output_folder``, as ``.h5``. Left there, they + would go into the snapshot, and a later call for the warm-up's group + would use the cached baseline instead of loading the baked one. An output saved over a file the image already held, when the baked baseline was incomplete, out of date or unreadable, is kept, and logged as a warning. @@ -252,7 +291,7 @@ def _removing_what_the_calculation_leaves(data_folder: Path) -> Iterator[None]: cached_before = set(simulation_cache._cache) # noqa: SLF001 # policyengine's LRUCache has no public listing or remove outputs_before = { output: _size_and_modification_time(output) - for output in data_folder.glob("*.h5") + for output in output_folder.glob("*.h5") } try: yield @@ -263,7 +302,7 @@ def _removing_what_the_calculation_leaves(data_folder: Path) -> Iterator[None]: if storage_id not in cached_before ]: simulation_cache._cache.pop(storage_id, None) # noqa: SLF001 # as above - for output in set(data_folder.glob("*.h5")) - outputs_before.keys(): + for output in set(output_folder.glob("*.h5")) - outputs_before.keys(): output.unlink(missing_ok=True) gc.collect() saved_over = sorted( @@ -273,11 +312,11 @@ def _removing_what_the_calculation_leaves(data_folder: Path) -> Iterator[None]: ) if saved_over: logger.warning( - "The warm-up calculation saved over %s in the image's data " - "folder, because the baked file was incomplete, out of date or " - "unreadable; containers restored from this snapshot load the " - "warm-up's copy", + "The warm-up calculation saved over %s in %s, because the baked " + "file was incomplete, out of date or unreadable; containers " + "restored from this snapshot load the warm-up's copy", ", ".join(saved_over), + output_folder, ) From 401c01bd672ffffd82adbffd21e63ab55f830aeb Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:35:14 +0400 Subject: [PATCH 10/10] Word the saved-over warning for a save that failed partway A recalculated baseline whose save fails partway leaves a truncated file, which restored containers can't load, so the warning no longer says they load the warm-up's copy. Co-Authored-By: Claude Opus 5.5 --- .../src/modal/snapshot_warm_up.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py b/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py index bbd174f33..40cf61010 100644 --- a/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py +++ b/projects/policyengine-simulation-executor/src/modal/snapshot_warm_up.py @@ -314,7 +314,8 @@ def _removing_what_the_calculation_leaves(output_folder: Path) -> Iterator[None] logger.warning( "The warm-up calculation saved over %s in %s, because the baked " "file was incomplete, out of date or unreadable; containers " - "restored from this snapshot load the warm-up's copy", + "restored from this snapshot start with the file as the warm-up " + "left it", ", ".join(saved_over), output_folder, )