Skip to content

Restore the v2 simulation workers from Modal memory snapshots with their country's models loaded - #1142

Merged
anth-volk merged 10 commits into
mainfrom
v2-workers-memory-snapshots
Nov 27, 2026
Merged

anth-volk merged 10 commits into
mainfrom
v2-workers-memory-snapshots

Conversation

@anth-volk

Copy link
Copy Markdown
Contributor

Fixes #1141

Summary

The v2 app's simulation workers now start from Modal memory snapshots with their country's models already loaded, as the run_simulation app's workers have since #1118.

Today a fresh v2 US segment container takes a median 53.6 s from enqueue to models loaded, and a segmented US parent 51.4 s to its first segment dispatch (production calls 25–27 Nov). The run_simulation app's restored containers brought the same steps down to 8.1 s and under 1 s. The v2 "after" numbers come from a separate check once this is deployed.

  • Worker classes. run_single_simulation_us, run_single_simulation_uk and run_single_simulation_segment_us become methods of three Modal classes, SimulationWorkerUS, SimulationWorkerUK and SimulationSegmentWorkerUS, with enable_memory_snapshot=True.

    • Each class has the image, CPU, memory, timeout, retries, container limit and secrets its function had. The options live in one dict per worker, shared by the class and the function.
    • Each method keeps its function's name. That name is stored data: the v2 version manifest's single_simulation_callable, the coordinator's context and the comparison-run rows hold it. policyengine_simulation_contract.stage12_simulation_workers.worker_class_name maps it to its class.
  • Before the snapshot. One @modal.enter(snap=True) hook, load_country_models, runs preload_country_models(<the class's country>).

    • The US classes load the US models and the SPM capability. The UK class loads only the UK models, since its image holds only UK data and SPM is a US measure.
    • So a failed import of one country's models can't affect the other country's workers, and preload_country_models still logs and skips a failure as before.
    • The hook configures no observability; that stays per call, after the restore.
  • After each restore. A @modal.enter(snap=False) hook calls random.seed(). OpenTelemetry's span IDs and the database and dataset-download retry delays draw from random.

  • Callers.

    • The coordinator spawns its children through the class in its own app (ModalChildInvoker.spawn), and a US simulation spawns its segments through SimulationSegmentWorkerUS (Stage12SegmentRunner). Both go through deployed_worker (stage12_runtime/worker_lookup.py). It hydrates the class and, when Modal doesn't find it, uses the plain function of the method's name. That covers a call still running when Stage 12 is rolled back by deploying an older commit with the same .py version, which replaces the app in place. Names without a class are looked up as functions.
    • The simulation entrypoint spawns standalone simulation runs and cliff calculations through the class. On an app without the class (an older .py version's app, which the manifest's default can name after a move or rollback) it falls back to the function. Only the class lookup falls back.
    • coordinate_report, the household functions and the validation functions stay plain functions.
  • Plain functions kept. The three functions stay, without snapshots, running the same code, for callers still on older code:

    • deploy_entrypoint runs alongside deploy_stage12_v2, so the entrypoint's stable revision serves old code until promote_entrypoint;
    • simulation-rollback.yml can move Cloud Run traffic back to any retained entrypoint revision;
    • the v2 app's name depends only on the .py version, so a deploy that keeps it redeploys the live app in place while coordinator and US worker calls are running.

    No task covers removing them yet.

  • Modal client check. The check refusing Modal clients older than 1.6.4 moves from app.py into src/modal/modal_client_version.py. The v2 app now runs it too, before the cache manifest is read.

  • File length. v2_app.py was at 795 of 800 lines, so the images, their deploy-time inputs and the bundle-value checks move unchanged into src/modal/v2_images.py, which v2_app.py re-exports. That move is its own commit.

Snapshot contents checked

  • Connections: a local run (macOS) imported v2_app.py and ran each class's load_country_models with socket.connect blocked and no Hugging Face token set.

    • Each run attempted four connections, all to huggingface.co's addresses on port 443: .py's data release manifest fetch (requests.get), tried on each resolved address.
    • The UK class imported only policyengine_uk and policyengine.tax_benefit_models.uk; the US class only the US modules.
    • No thread was started. No Python socket stayed open: the only descriptors left were macOS's DNS resolver channels (a com.apple.netsrc control socket and a Unix socket), which come from getaddrinfo on macOS. That a Linux container keeps no resolver socket is unverified here.
    • With the fetch blocked, .py falls back to the certification bundled with the package without raising. In a snapshot, a Hugging Face outage at snapshot time therefore lasts for the snapshot's life, as it already does in the run_simulation app.
  • Random values: random is reseeded after each restore. uuid4() draws from os.urandom, so it differs per container without a reseed.

  • Credentials: .py's data release manifest fetch reads HUGGING_FACE_TOKEN from os.environ for one request and keeps it nowhere, as in the run_simulation app since Restore the simulation workers from Modal memory snapshots with the country models loaded #1118. No other secret is read before the snapshot.

Environment variables

Each variable the changed code reads, or that is now read at a different time:

Variable Read by, and when Provider Wiring Status
HUGGING_FACE_TOKEN (HF_TOKEN, HUGGINGFACE_HUB_TOKEN as fallbacks) .py's data release manifest fetch, during the country-model import: now in the snapshot hook, before the snapshot; before this PR, in each fresh container's first call. hf_dataset.py still reads it per call. Modal secret pe-uk-private-hf-read-token, key HUGGING_FACE_TOKEN, written into the deploy's Modal environment from the GitHub organisation secret PE_UK_PRIVATE_HF_READ_TOKEN by the prepare job's copy step (which also runs for deploy_stage12_v2) hf_secret is in worker_secrets, attached to all three classes and functions. Modal sets Secret values before the enter hooks run. Read for one request and kept nowhere. Modal 1.6.4 reloads Secret values on restore; that reload is not checked on Modal for this app (1.5 · 10 can check restores).
GOOGLE_APPLICATION_CREDENTIALS_JSON GCS stores, per call, after the restore Modal secret stage12-evaluation-gcp-credentials, written from Google Secret Manager by stage12-sync-modal-secrets.sh gcp_secret in worker_secrets Unchanged; not read before the snapshot
STAGE12_DATABASE_URL, STAGE12_ARTIFACT_BUCKET, STAGE12_CACHE_BUCKET, V2_SIMULATION_OUTPUT_BUCKET The runtime stores, per call, after the restore Modal secret stage12-evaluation-runtime, written by stage12-sync-modal-secrets.sh from GitHub environment variables and Google Secret Manager comparison_runtime_secret in worker_secrets Unchanged; not read before the snapshot
MODAL_WORKER_DATABASE_URL Report-run and simulation-run recording, per call Modal secret policyengine-modal-worker-database report_run_writer_secrets, on the US and UK simulation workers only Unchanged
STAGE12_BUNDLE_MANIFEST_SHA256, STAGE12_BUNDLE_VALUES, STAGE12_CACHE_MANIFEST_DIGEST, POLICYENGINE_DATA_FOLDER, OBSERVABILITY_*, OTEL_EXPORTER_OTLP_ENDPOINT, POLICYENGINE_OTEL_GOOGLE_AUDIENCE Validation, dataset lookup and observability, per call The image's .env(...) layer, built on the deploying runner (build_v2_image, now in v2_images.py, unchanged) Baked into the image Unchanged
MODAL_ENVIRONMENT, MODAL_TASK_ID Observability, per call, after the restore Modal's runtime Modal 1.6.4 sets MODAL_TASK_ID to the restored container's own task ID Unchanged
POLICYENGINE_SKIP_COUNTRY_IMPORTS .py's package import Set in-process by release_bundle.py and simulation_runtime.py on import Before the hook Unchanged
POLICYENGINE_US_DATA_MANIFEST_FILE, POLICYENGINE_UK_DATA_MANIFEST_FILE .py, optional Set nowhere Without them the manifest is fetched Unchanged
STAGE12_CACHE_BUCKET, STAGE12_CACHE_MANIFEST_DIGEST, STAGE12_EXPECT_*, MODAL_APP_NAME v2_images.py and v2_app.py on the deploying runner, in the same order as before; the Modal client check now runs first GitHub environment variable STAGE12_CACHE_BUCKET; the cache precompute step's manifest_digest output; the prepare job's version outputs; the application-name step's output The "Deploy the additional versioned v2 Modal application" step's env: in simulation-deploy.reusable.yml, unchanged Unchanged
MODAL_TOKEN_ID, MODAL_TOKEN_SECRET, MODAL_ENVIRONMENT (entrypoint) The simulation entrypoint's Modal client, per request; Cls.from_name uses the same client and environment as Function.from_name Google Secret Manager secrets named by MODAL_TOKEN_ID_SECRET_NAME and MODAL_TOKEN_SECRET_SECRET_NAME add_runtime_secret in deploy-cloud-run-simulation-entry.sh Unchanged. The entrypoint locks Modal 1.5.5, whose Cls.from_name(..., environment_name=), hydrate.aio() and NotFoundError on a missing class were checked in its installed source.

Tests

Red-green: each change's failing tests are committed before it (5328c8de before 9ef223cb, 23af84b1 before d049fe70, 6199f6a6 before 758ee379). Only the new and changed tests were run, each selected by node ID. Pyright and the quality guards pass on the changed packages.

Two rounds of adversarial review, each by a separate reviewer given the diff and the acceptance condition:

  • Round 1: a coordinator or US worker call still running when its app is rolled back in place found no class and failed. Fixed by deployed_worker, test first. It also found three loose tests, now tightened: the wait-window check now covers the classes' timeouts; the entrypoint's fake class has only its own method; and a new test checks that importing the app loads neither country's models.
  • Round 2: the classes' annotations failed typing.get_type_hints, which Modal calls once a class declares a modal.parameter. The refusal message named src/modal/app.py for a v2 deploy. Both fixed test first, and two more tests tightened.
  • Both rounds found only rare cases, so a third round was not run.

Known limitations

  • Deploy validation runs no snapshot container. The deploy's validation calls validate_worker_us/_uk and the household functions, which are plain functions. A problem with taking or restoring a snapshot would first show in a real call. 1.5 · 10 checks restores after the deploy.
  • Unverified on Modal: the in-place rollback fallback assumes Modal's ClassGet answers NOT_FOUND for a class the app's current deployment no longer defines. The tests fake that answer.
  • Extra lookups in the entrypoint: each standalone run or cliff spawn now looks up the class (two remote calls) before spawning; on an older app, one failing lookup comes first. Not measured against the entrypoint's 10-second call-start limit. The gateway has made the same lookup per spawn since Restore the simulation workers from Modal memory snapshots with the country models loaded #1118.
  • Separate container limits: each class and its plain function have their own max_containers. While older callers still use the functions, both pools can run at once; each call still runs in one container.

Not in this PR

  • Restore telemetry for the v2 workers (1.5 · 11), a warm-up calculation in the v2 snapshot hook (1.5 · 12) and v2 segment sizing (1.5 · 13).
  • Removing the plain functions: task 1.5 · 14, once this has deployed and a later deploy has replaced the kept Cloud Run rollback revision.
  • Checking restores on Modal (1.5 · 10): this PR deploys nothing.

🤖 Generated with Claude Code

anth-volk and others added 10 commits November 27, 2026 22:31
v2_app.py is at the 800-line limit, and its simulation workers are about to
become Modal classes. The bundle resolution, the US cache manifest read, the
two secrets the image builds attach and the image builders move unchanged into
src/modal/v2_images.py; v2_app.py imports and re-exports them, so the smoke
apps and tests that import them from v2_app keep working. The tests that
reload the app under the fake Modal now reload v2_images too, and the legacy
Hugging Face secret-name check reads the new module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The v2 app's workers are about to restore from memory snapshots too, so it
needs the same refusal of Modal clients that don't reload Secret values on
restore. The check moves unchanged from app.py into
src/modal/modal_client_version.py, as a public function, and app.py runs it
at the same point as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Failing tests for 1.5 · 9:
- the contract names a Modal class for each v2 simulation worker, whose
  method keeps the worker's function name;
- the v2 app declares SimulationWorkerUS, SimulationWorkerUK and
  SimulationSegmentWorkerUS with memory snapshots and today's options, keeps
  the plain functions for callers on older code, loads only each class's own
  country's models in the snapshot hook with no observability, reseeds random
  after each restore, and refuses Modal clients older than 1.6.4 before the
  cache manifest is read;
- preload_country_models loads only the countries it is given, with SPM only
  for the US;
- the US worker's segments, the coordinator's children and the entry
  service's standalone runs and cliff calculations are spawned through the
  classes; the entry service falls back to the function on an app without
  the class.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…els loaded

The v2 app's US and UK simulation workers and its US segment worker become
methods of SimulationWorkerUS, SimulationWorkerUK and
SimulationSegmentWorkerUS, with enable_memory_snapshot=True and the options
the functions had. Each method keeps its function's name, which the v2
version manifest, coordinator contexts and comparison-run rows store, and
policyengine_simulation_contract.stage12_simulation_workers maps that name
to its class.

- Before the snapshot, the classes' @modal.enter(snap=True) hook runs
  preload_country_models for the image's own country only: the US classes
  load the US models and the SPM capability, the UK class the UK models, so
  one country's failed import can't touch the other's workers. It configures
  no observability and opens no client; .py's manifest fetch reads
  HUGGING_FACE_TOKEN for one request, as in the run_simulation app.
- After each restore, a snap=False hook reseeds random, from which span IDs
  and the retry delays are drawn.
- The coordinator's children and the US worker's segments are spawned through
  the classes, in their own app. The simulation entrypoint spawns standalone
  runs and cliff calculations through the class, and falls back to the
  function on an app without it (an older .py version's app).
- The plain functions stay, without snapshots, for callers still running
  older code: the entrypoint's stable revision during a deploy, a revision a
  rollback routes back to, and calls running while the app is redeployed in
  place.
- Importing the v2 app refuses Modal clients older than 1.6.4 before the
  cache manifest is read. The bundle-value assertions move next to the
  bundle in v2_images.py, which keeps v2_app.py under 800 lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…k in place

Review round 1 found that a coordinator or US worker call running when its
app is rolled back in place, to a commit from before the classes, looks up
only the worker class and fails with NotFoundError. Stage 12 is rolled back
by deploying an older commit, which keeps the app name when the .py version
is the same. These tests expect both lookups to hydrate the class and to fall
back to the plain function of the method's name when the app has no class.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The coordinator's children and the US worker's segments now go through
deployed_worker (stage12_runtime/worker_lookup.py): it hydrates the worker's
Modal class and, when Modal doesn't find it, returns the plain function of
the method's name. A coordinator or US worker call still running when its
app is rolled back in place, to a commit from before the classes, then keeps
reaching its workers. Only the class lookup falls back; a failed spawn raises
as it is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The wait-window test now checks the worker classes' Modal timeouts too,
  since the coordinator spawns the class methods.
- The entry service's fake worker class has only the looked-up class's own
  method, so a spawn of the other country's method name fails.
- A new test imports the v2 app in a fresh interpreter and checks that
  neither country's models are loaded, which each class's snapshot hook
  needs to load only its own country.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review round 2 found:
- typing.get_type_hints fails on the worker classes, because
  snapshot_countries is annotated with a name imported only for type
  checking; Modal calls it once a class declares a modal.parameter;
- the Modal client refusal tells a v2 deployer to deploy src/modal/app.py.

The equivalence test now also checks that a class method passes the call's
observability context and simulation run to its operation, and the import
test no longer inherits the deploy step's inputs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… refusal

- snapshot_countries is annotated tuple[str, ...], so typing.get_type_hints
  resolves the worker classes' annotations when Modal reads them.
- require_secret_reloading_modal_client takes the app's file, so a refused
  v2 deploy is told to run `uv run --frozen modal deploy src/modal/v2_app.py`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 19:53
@anth-volk
anth-volk merged commit 26d05f2 into main Nov 27, 2026
28 checks passed
@anth-volk
anth-volk deleted the v2-workers-memory-snapshots branch November 27, 2026 19:53
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.

Restore the v2 simulation workers from Modal memory snapshots with their country's models loaded

1 participant