Repository navigation
Run one warm-up calculation in the simulation workers' snapshot hook - #1134
Merged
Merged
Conversation
…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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…ings 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
Since the precompute moved onto the level handlers (#1132), the image keeps year files and baselines under prebuilt/<country>/<dataset>/<subset>/, 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 <noreply@anthropic.com>
#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/<country>/. 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #1133
Same-Repository Draft PR Check
PolicyEngine/policyengine-sim-api, not a personal fork.Changelog
changelog.d/<name>.<type>.md, whose type is breaking, added, changed, fixed or removed. (changelog.d/snapshot-warm-up.changed.md)Summary
The snapshot hook of both simulation workers,
SimulationWorkerandSimulationSegmentWorker(load_country_modelsinsrc/modal/app.py), now callswarm_up_first_calculation()after the model preload. The new module issrc/modal/snapshot_warm_up.py. In a container Modal takes a memory snapshot from, it runs one segmented national child request through the simulation path:stage12_cache/levels_us.py), for the first prebuilt year. Today that isstate/hi+state/ia+state/wiin 2026, the group both measurements used;It discards the result. Containers restored from the snapshot then start with part of the one-time work a process's first calculation for that year does.
In
app.pythe diff is one import, the hook's docstring and one call. Tracker task: 1.5 · 8 of project 14.The branch has
mainmerged in, with #1126, #1131 and #1132. #1132 moved the precompute onto per-country, per-dataset-level handlers and the image's files underprebuilt/<country>/, and removed what the first version of this warm-up imported. That version, merged as it was, would have stoppedapp.pyfrom importing; this one is written against the handlers.When it runs, and what it avoids before the snapshot
Only where Modal takes a snapshot. Modal 1.6.4 runs the
snap=Truehook in every container that isn't restored. It takes a snapshot only where its worker setMODAL_ENABLE_SNAP_RESTORE=1(run_functionandmaybe_snapshot). Elsewhere the warm-up would delay the container's first call by a whole calculation to save it about 15 s, so it does nothing.No connection, no Secret. It runs only if the preload imported the US models, because importing them again could fetch the data release manifest again. It also needs the group's year file and current-law baseline in the image, and finds both as a run of its request does:
simulation_runtime._prebuilt_folder. That lookup returns no folder for a year file the image lacks or .py wouldn't reuse, where .py would build the file from its source, which it may download;precompute_planning.baseline_target_identity), as<storage ID>.h5beside the year file.Otherwise it skips with a warning.
No credential setup. It calls
_run_simulation_impl_coredirectly, notrun_simulation_impl, so it skips the Google Cloud credential setup, which reads thegcp-credentialsSecret.No telemetry. It configures no observability and passes a runtime that records and sends nothing. So it writes no operation record or span, and the container's first real call is still
container_call_number1.Nothing left for a request. Afterwards it removes the simulations it added to .py's in-process cache: the baseline under the baked baseline's storage ID, and the reform under a random ID. It also deletes the
.h5outputs it saved in the prebuilt folder, where .py saves outputs beside the year file, then runsgc.collect(). A later call for the same group loads its baseline from the image, as it would without the warm-up. What stays is what the packages keep for the whole process: the module-level parameter tree that every simulation's baseline branch shares (share_spm_policyin policyengine-us), spm-calculator's threshold tables and price index series, and imported modules.Never fatal. Any
Exception, includingMemoryError, is logged as a warning, and the container starts as before. The executor modules it uses are imported when it runs, not whenapp.pyimports it, so a later move or rename in them, like Plan, build and look up prebuilt year files and baselines through country and dataset-level handlers #1132's, costs only the warm-up.Measured (Modal
testing, both runs approved separately)Both runs used an uncommitted test version of the warm-up. It calculated the same group under the same reform, but kept the warm-up's two simulations in .py's in-process cache, and it ran in every container that wasn't restored.
Only the containers Modal takes snapshots from pay the extra start time: 8 to 10 per class in each run's first batch, then one more for each machine type that had no snapshot yet. Restored containers started a median 6.8 s after enqueue on 1 CPU with the warm-up, against 5.8 s without.
The profile of a first and a second calculation in one process attributed about 20 s to building parameter values at the calculation date and SPM threshold amounts. It doesn't show which of that work a warm-up under another group and reform leaves for a later request. In the code, a request's reform builds its own parameter tree and each simulation its own SPM amount cache. So the 11–16 s gain comes from process-wide state, such as the shared parameter tree its baseline branch uses. Which state it is hasn't been profiled.
Memory, with the segment workers at 1 CPU and 10 GiB (#1126)
From the 1-CPU run, highest of 8 containers. The warm-up version measured kept its two simulations cached, which this code removes, so these figures are an upper bound for this PR.
Against #1126's 10 GiB request, that leaves about 2.8 GiB in the 2028 case.
Recheck for this PR, which merges after #1126: the run above measured 1 CPU and 10 GiB together with a warm-up, but with the test version. Memory leaves 2.8 GiB in the worst case measured, and taking a snapshot took a median 123.2 s from enqueue on 1 CPU.
Not covered, or left as it is
baseline_artifact.HUGGING_FACE_TOKENand fetches the data release manifest from Hugging Face before the snapshot, ascountry_model_preload.pysays.Order
1.5 · 6 (#1126) and 1.5 · 7 (#1131) are merged, and the branch has them.
A deployed warm-up makes restored containers' first calculation faster. #1126's production check compares restored segment children's calculation times with 1.5 · 3's "after" numbers. That check needs to be read before this PR deploys, or it will count the warm-up's gain as part of the 1-CPU change.
When to merge and deploy is the maintainer's call.
Environment variables
The change reads two variables itself, declares none, and attaches no Secret.
MODAL_ENABLE_SNAP_RESTOREwarm_up_first_calculationrun_functionandmaybe_snapshot), Modal's worker sets it in containers it snapshots or restores._ContainerCalls.record_snapshot_hookalready reads it. Not a Secret. Unverified on Modal: no run has yet observed it as1inside the hook. 1.5 · 5's production check, which comparescontainer_startwith Modal's snapshot log lines, will show it. If it isn't1, the warm-up never runs: no gain, and no other effect.POLICYENGINE_DATA_FOLDERresolve_data_folder(), through_prebuilt_folderin the warm-up and in the calculationVERSION_ENVinapp.py, applied with.env(VERSION_ENV)inbuild_runtime_simulation_image()(/opt/policyengine/databy default). Fixed per image.POLICYENGINE_BUNDLE_RECEIPTrelease_bundle, through the group-of-states handler's default dataset, the baseline identity and the calculationVERSION_ENV, as above. Fixed per image.GOOGLE_APPLICATION_CREDENTIALS_JSON(Modal Secretgcp-credentials)setup_gcp_credentials. Calls after the restore read it as before.HUGGING_FACE_TOKEN(Modal Secretpe-uk-private-hf-read-token)POLICYENGINE_SKIP_COUNTRY_IMPORTSis set to1by importingsimulation_runtime.release_bundlealready does the same whenapp.pyimports it, so the value before the snapshot doesn't change.Testing
39dc645d,a766da31,fd96e70d, and for the move onto the level handlersd606b983), then the changes that make them pass.d606b983includes a test that the app still imports and the hook only logs a warning when a module the warm-up uses can't be imported.mainmerged in, all passing: the 15 tests intests/test_snapshot_warm_up.py, and the 11 tests intests/test_modal_container_start.pythat run the snapshot hook, whose fixture now replaces the warm-up as it replaces the preload. No full suite was run.test_the_warm_up_reform_changes_a_parameter_of_the_installed_us_modelloads policyengine-us's own parameter tree (about 12 s) to check the reform names a real parameter. Every other test replaces the calculation with a fake that touches .py's in-process cache and the prebuilt folder as a real one does, and replaces the region, dataset and prebuilt-folder lookups, which need the US model. So no unit test runs the real simulation path. The two measurements on Modaltestingcover that path, with the test version of the warm-up.python -m scripts.rules pyright --sync) andscripts/run_quality_guards.py: all pass.🤖 Generated with Claude Code