Skip to content

Run one warm-up calculation in the simulation workers' snapshot hook - #1134

Merged
anth-volk merged 11 commits into
mainfrom
claude/snapshot-warm-up-ecdcc2
Nov 27, 2026
Merged

anth-volk merged 11 commits into
mainfrom
claude/snapshot-warm-up-ecdcc2

Conversation

@anth-volk

@anth-volk anth-volk commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1133

Same-Repository Draft PR Check

  • This PR is a draft.
  • This PR is from a branch in PolicyEngine/policyengine-sim-api, not a personal fork.

Changelog

  • This PR adds a changelog fragment, 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, SimulationWorker and SimulationSegmentWorker (load_country_models in src/modal/app.py), now calls warm_up_first_calculation() after the model preload. The new module is src/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:

  • Group and year: group 1's precomputed current-law request from the US group-of-states handler (stage12_cache/levels_us.py), for the first prebuilt year. Today that is state/hi+state/ia+state/wi in 2026, the group both measurements used;
  • Reform: the Child Tax Credit's base amount set to $2,500 (current law is $2,200).

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.py the diff is one import, the hook's docstring and one call. Tracker task: 1.5 · 8 of project 14.

The branch has main merged in, with #1126, #1131 and #1132. #1132 moved the precompute onto per-country, per-dataset-level handlers and the image's files under prebuilt/<country>/, and removed what the first version of this warm-up imported. That version, merged as it was, would have stopped app.py from 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=True hook in every container that isn't restored. It takes a snapshot only where its worker set MODAL_ENABLE_SNAP_RESTORE=1 (run_function and maybe_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:

    • the year file: the runtime's region and dataset resolution, then 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;
    • the baseline: the precompute's own identity for the group (precompute_planning.baseline_target_identity), as <storage ID>.h5 beside the year file.

    Otherwise it skips with a warning.

  • No credential setup. It calls _run_simulation_impl_core directly, not run_simulation_impl, so it skips the Google Cloud credential setup, which reads the gcp-credentials Secret.

  • 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_number 1.

  • 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 .h5 outputs it saved in the prebuilt folder, where .py saves outputs beside the year file, then runs gc.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_policy in policyengine-us), spm-calculator's threshold tables and price index series, and imported modules.

  • Never fatal. Any Exception, including MemoryError, is logged as a warning, and the container starts as before. The executor modules it uses are imported when it runs, not when app.py imports 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.

8 CPUs, 2026-11-25 1 CPU, 2026-11-26
A restored container's first calculation, same machine type 11–15 s faster 13–16 s faster
Results identical with and without the warm-up identical in all four classes
The warm-up itself, in containers taking the snapshot 72–97 s longer start 64–88 s (65–98 s on 8 CPUs)
Enqueue to start, containers taking the snapshot (median) — 123.2 s on 1 CPU, 145.4 s on 8 CPUs; without the warm-up 52.8 s and 57.7 s

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.

Calculation Without warm-up With warm-up
Restored, at the first call 1.16 GiB 2.03 GiB
2026, baked baseline (peak) 3.44 GiB 3.63 GiB
2028, baseline calculated in the call (peak) 6.92 GiB 7.19 GiB

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

  • A successful warm-up logs nothing visible. Its success message is at INFO, and nothing configures logging before the snapshot, so the root logger stays at WARNING. The preload has the same property. Skips and failures are WARNING, so they are visible. Whether it ran shows as the extra start time of containers taking the snapshot in Modal's container records.
  • A baked baseline that is incomplete, out of date or unreadable is calculated again and saved over the image's file, as a call would do. The warm-up keeps that copy and logs a warning naming the file. Restored containers then load it and don't report the baked file's problem in baseline_artifact.
  • Logging state: .py's once-only memory warnings (8 GB and over) and Python's once-per-location warnings that the warm-up triggers stay in the snapshot. The warm-up process stayed under 3 GiB in the runs above.
  • Not measured: snapshot size and restore time with this code, and how much memory it leaves after its cleanup.
  • Pre-existing, not changed here: the preload before the warm-up already reads HUGGING_FACE_TOKEN and fetches the data release manifest from Hugging Face before the snapshot, as country_model_preload.py says.

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.

Variable Read by When Provider and wiring
MODAL_ENABLE_SNAP_RESTORE warm_up_first_calculation In the snapshot hook, before the snapshot Modal's runtime: per Modal 1.6.4's source (run_function and maybe_snapshot), Modal's worker sets it in containers it snapshots or restores. _ContainerCalls.record_snapshot_hook already reads it. Not a Secret. Unverified on Modal: no run has yet observed it as 1 inside the hook. 1.5 · 5's production check, which compares container_start with Modal's snapshot log lines, will show it. If it isn't 1, the warm-up never runs: no gain, and no other effect.
POLICYENGINE_DATA_FOLDER resolve_data_folder(), through _prebuilt_folder in the warm-up and in the calculation Before the snapshot Image environment: VERSION_ENV in app.py, applied with .env(VERSION_ENV) in build_runtime_simulation_image() (/opt/policyengine/data by default). Fixed per image.
POLICYENGINE_BUNDLE_RECEIPT release_bundle, through the group-of-states handler's default dataset, the baseline identity and the calculation Before the snapshot Image environment, VERSION_ENV, as above. Fixed per image.
GOOGLE_APPLICATION_CREDENTIALS_JSON (Modal Secret gcp-credentials) Not read — The warm-up skips setup_gcp_credentials. Calls after the restore read it as before.
HUGGING_FACE_TOKEN (Modal Secret pe-uk-private-hf-read-token) Not read by the warm-up — Read before the snapshot only by the preload's manifest fetch, which predates this change.

POLICYENGINE_SKIP_COUNTRY_IMPORTS is set to 1 by importing simulation_runtime. release_bundle already does the same when app.py imports it, so the value before the snapshot doesn't change.

Testing

  • Red-green: the failing tests were committed first (39dc645d, a766da31, fd96e70d, and for the move onto the level handlers d606b983), then the changes that make them pass. d606b983 includes 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.
  • Run individually by node ID on the branch with main merged in, all passing: the 15 tests in tests/test_snapshot_warm_up.py, and the 11 tests in tests/test_modal_container_start.py that run the snapshot hook, whose fixture now replaces the warm-up as it replaces the preload. No full suite was run.
  • The strengthened credential and telemetry tests were also run against broken copies of the module that set up credentials, or built an observability runtime, after the calculation. Both failed, where the first versions of those tests passed.
  • test_the_warm_up_reform_changes_a_parameter_of_the_installed_us_model loads 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 Modal testing cover that path, with the test version of the warm-up.
  • Ruff 0.15.22 (format and check), Pyright for the executor package (python -m scripts.rules pyright --sync) and scripts/run_quality_guards.py: all pass.
  • Adversarial review by separate reviewers: three rounds on the first version, and one on the move onto the level handlers.
    • The first two rounds found test weaknesses, a missing year-file check, a missing warning when a baked file is saved over, and inaccurate docstrings. Each was fixed, with a failing test first where it was code.
    • The third round, and the round on the move, found no bug against the acceptance condition; their minor points are fixed or listed above.

🤖 Generated with Claude Code

anth-volk and others added 11 commits November 26, 2026 18:43
…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>
@anth-volk
anth-volk marked this pull request as ready for review November 27, 2026 13:33
@anth-volk
anth-volk merged commit a9a5cea into main Nov 27, 2026
30 checks passed
@anth-volk
anth-volk deleted the claude/snapshot-warm-up-ecdcc2 branch November 27, 2026 13:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Run one warm-up calculation in the simulation workers' snapshot hook

1 participant