Repository navigation
Restore the v2 simulation workers from Modal memory snapshots with their country's models loaded - #1142
Merged
Conversation
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>
3 tasks done
anth-volk
marked this pull request as ready for review
November 27, 2026 19:53
This was referenced Nov 27, 2026
Merged
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 #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_ukandrun_single_simulation_segment_usbecome methods of three Modal classes,SimulationWorkerUS,SimulationWorkerUKandSimulationSegmentWorkerUS, withenable_memory_snapshot=True.single_simulation_callable, the coordinator's context and the comparison-run rows hold it.policyengine_simulation_contract.stage12_simulation_workers.worker_class_namemaps it to its class.Before the snapshot. One
@modal.enter(snap=True)hook,load_country_models, runspreload_country_models(<the class's country>).preload_country_modelsstill logs and skips a failure as before.After each restore. A
@modal.enter(snap=False)hook callsrandom.seed(). OpenTelemetry's span IDs and the database and dataset-download retry delays draw fromrandom.Callers.
ModalChildInvoker.spawn), and a US simulation spawns its segments throughSimulationSegmentWorkerUS(Stage12SegmentRunner). Both go throughdeployed_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.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_entrypointruns alongsidedeploy_stage12_v2, so the entrypoint's stable revision serves old code untilpromote_entrypoint;simulation-rollback.ymlcan move Cloud Run traffic back to any retained entrypoint revision;No task covers removing them yet.
Modal client check. The check refusing Modal clients older than 1.6.4 moves from
app.pyintosrc/modal/modal_client_version.py. The v2 app now runs it too, before the cache manifest is read.File length.
v2_app.pywas at 795 of 800 lines, so the images, their deploy-time inputs and the bundle-value checks move unchanged intosrc/modal/v2_images.py, whichv2_app.pyre-exports. That move is its own commit.Snapshot contents checked
Connections: a local run (macOS) imported
v2_app.pyand ran each class'sload_country_modelswithsocket.connectblocked and no Hugging Face token set.requests.get), tried on each resolved address.policyengine_ukandpolicyengine.tax_benefit_models.uk; the US class only the US modules.com.apple.netsrccontrol socket and a Unix socket), which come fromgetaddrinfoon macOS. That a Linux container keeps no resolver socket is unverified here.Random values:
randomis reseeded after each restore.uuid4()draws fromos.urandom, so it differs per container without a reseed.Credentials: .py's data release manifest fetch reads
HUGGING_FACE_TOKENfromos.environfor 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:
HUGGING_FACE_TOKEN(HF_TOKEN,HUGGINGFACE_HUB_TOKENas fallbacks)hf_dataset.pystill reads it per call.pe-uk-private-hf-read-token, keyHUGGING_FACE_TOKEN, written into the deploy's Modal environment from the GitHub organisation secretPE_UK_PRIVATE_HF_READ_TOKENby thepreparejob's copy step (which also runs fordeploy_stage12_v2)hf_secretis inworker_secrets, attached to all three classes and functions. Modal sets Secret values before theenterhooks run.GOOGLE_APPLICATION_CREDENTIALS_JSONstage12-evaluation-gcp-credentials, written from Google Secret Manager bystage12-sync-modal-secrets.shgcp_secretinworker_secretsSTAGE12_DATABASE_URL,STAGE12_ARTIFACT_BUCKET,STAGE12_CACHE_BUCKET,V2_SIMULATION_OUTPUT_BUCKETstage12-evaluation-runtime, written bystage12-sync-modal-secrets.shfrom GitHub environment variables and Google Secret Managercomparison_runtime_secretinworker_secretsMODAL_WORKER_DATABASE_URLpolicyengine-modal-worker-databasereport_run_writer_secrets, on the US and UK simulation workers onlySTAGE12_BUNDLE_MANIFEST_SHA256,STAGE12_BUNDLE_VALUES,STAGE12_CACHE_MANIFEST_DIGEST,POLICYENGINE_DATA_FOLDER,OBSERVABILITY_*,OTEL_EXPORTER_OTLP_ENDPOINT,POLICYENGINE_OTEL_GOOGLE_AUDIENCE.env(...)layer, built on the deploying runner (build_v2_image, now inv2_images.py, unchanged)MODAL_ENVIRONMENT,MODAL_TASK_IDMODAL_TASK_IDto the restored container's own task IDPOLICYENGINE_SKIP_COUNTRY_IMPORTSrelease_bundle.pyandsimulation_runtime.pyon importPOLICYENGINE_US_DATA_MANIFEST_FILE,POLICYENGINE_UK_DATA_MANIFEST_FILESTAGE12_CACHE_BUCKET,STAGE12_CACHE_MANIFEST_DIGEST,STAGE12_EXPECT_*,MODAL_APP_NAMEv2_images.pyandv2_app.pyon the deploying runner, in the same order as before; the Modal client check now runs firstSTAGE12_CACHE_BUCKET; the cache precompute step'smanifest_digestoutput; thepreparejob's version outputs; the application-name step's outputenv:insimulation-deploy.reusable.yml, unchangedMODAL_TOKEN_ID,MODAL_TOKEN_SECRET,MODAL_ENVIRONMENT(entrypoint)Cls.from_nameuses the same client and environment asFunction.from_nameMODAL_TOKEN_ID_SECRET_NAMEandMODAL_TOKEN_SECRET_SECRET_NAMEadd_runtime_secretindeploy-cloud-run-simulation-entry.shCls.from_name(..., environment_name=),hydrate.aio()andNotFoundErroron a missing class were checked in its installed source.Tests
Red-green: each change's failing tests are committed before it (
5328c8debefore9ef223cb,23af84b1befored049fe70,6199f6a6before758ee379). 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:
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.typing.get_type_hints, which Modal calls once a class declares amodal.parameter. The refusal message namedsrc/modal/app.pyfor a v2 deploy. Both fixed test first, and two more tests tightened.Known limitations
validate_worker_us/_ukand 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.ClassGetanswers NOT_FOUND for a class the app's current deployment no longer defines. The tests fake that answer.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
🤖 Generated with Claude Code