From 26749316ac9a2976bde7b0ef666c480864f644a5 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:31:40 +0400 Subject: [PATCH 01/10] Move the v2 app's images and their deploy-time inputs into v2_images.py 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 --- .../src/modal/v2_app.py | 206 +++--------------- .../src/modal/v2_images.py | 196 +++++++++++++++++ .../tests/test_modal_scripts.py | 2 + .../tests/test_stage12_modal_app.py | 2 + .../tests/test_stage12_wait_window.py | 1 + .../tests/test_v2_image_smoke.py | 1 + 6 files changed, 237 insertions(+), 171 deletions(-) create mode 100644 projects/policyengine-simulation-executor/src/modal/v2_images.py diff --git a/projects/policyengine-simulation-executor/src/modal/v2_app.py b/projects/policyengine-simulation-executor/src/modal/v2_app.py index 42a04f241..d3505d4fc 100644 --- a/projects/policyengine-simulation-executor/src/modal/v2_app.py +++ b/projects/policyengine-simulation-executor/src/modal/v2_app.py @@ -19,9 +19,7 @@ from __future__ import annotations -import json import os -from pathlib import Path from typing import TYPE_CHECKING from uuid import UUID @@ -30,17 +28,10 @@ ) from policyengine_simulation_contract.stage12_manifest import v2_application_name from policyengine_simulation_executor import stage12_runtime -from policyengine_simulation_executor.hf_access_validation import ( - HF_MODAL_SECRET_NAME, - HF_RUNTIME_ENV_NAME, -) from policyengine_simulation_executor.stage12_bundle import ( assert_expected_bundle_values, assertion_values, - load_stage12_bundle, ) -from policyengine_simulation_executor.stage12_cache.models import CacheManifest -from policyengine_simulation_executor.stage12_cache.store import Stage12CacheStore from policyengine_simulation_executor.stage12_runtime import report_run_access from policyengine_simulation_executor.stage12_runtime.report_run_access import ( MODAL_WORKER_DATABASE_SECRET_NAME, @@ -54,7 +45,6 @@ ) from policyengine_simulation_observability.observability import ( init_process_observability, - modal_image_environment, ) from policyengine_simulation_observability.stages import ( STAGE12_CANONICAL_REPORT_STAGES, @@ -67,10 +57,21 @@ from policyengine_simulation_observability.telemetry import ( normalize_observability_context, ) -from src.modal.bundle_data import bundle_data_install_command -from src.modal.ca_certificates import GRPC_CA_BUNDLE_ENV, OPERATING_SYSTEM_CA_PACKAGE -from src.modal.stage12_cache_image import fetch_stage12_cache -from src.modal.static_runtime_files import add_static_runtime_files +from src.modal.v2_images import ( + RESOLVED_BUNDLE, + STAGE12_CACHE_BUCKET, + STAGE12_CACHE_CONTENTS, + STAGE12_CACHE_MANIFEST, + STAGE12_DATA_DIR, + build_household_image, + build_v2_image, + coordinator_image, + gcp_secret, + hf_secret, + household_image, + uk_worker_image, + us_worker_image, +) import modal @@ -81,10 +82,7 @@ HouseholdExecutionFailure, HouseholdExecutionResult, ) - from policyengine_simulation_contract.stage12_bundle import ( - CountryId, - Stage12CountryBundle, - ) + from policyengine_simulation_contract.stage12_bundle import CountryId from policyengine_simulation_contract.stage12_execution import ( PlannedSimulationExecutionInput, ) @@ -92,47 +90,29 @@ SimulationCalculation, ) -STAGE12_DATA_DIR = "/opt/policyengine/stage12-data" -_UV_PROJECT_DIR = str(Path(__file__).resolve().parents[2]) if modal.is_local() else "." -RESOLVED_BUNDLE = load_stage12_bundle() +# The images and the deploy-time values their build steps read live in +# src/modal/v2_images.py; this module keeps their names for the smoke apps and +# other code that imports them from here. +__all__ = [ + "RESOLVED_BUNDLE", + "STAGE12_CACHE_BUCKET", + "STAGE12_CACHE_CONTENTS", + "STAGE12_CACHE_MANIFEST", + "STAGE12_DATA_DIR", + "build_household_image", + "build_v2_image", + "coordinator_image", + "gcp_secret", + "hf_secret", + "household_image", + "uk_worker_image", + "us_worker_image", +] + BUNDLE_VALUES = assertion_values(RESOLVED_BUNDLE.bundle) APP_NAME = v2_application_name(RESOLVED_BUNDLE.bundle.policyengine_version) -def _deploy_time_cache_inputs() -> tuple[str, dict | None, dict | None]: - """Resolve the cache manifest, and the contents it must hold, when deploying. - - The contents (years and counts) come from the level handlers' settings, - without loading the US model; the image download step checks the - manifest against them. - """ - if not modal.is_local(): - return "", None, None - from policyengine_simulation_executor.stage12_cache.precompute_planning import ( # noqa: PLC0415 # needed on the deploying machine only - expected_cache_contents, - ) - - contents = expected_cache_contents("us") - bucket = os.environ.get("STAGE12_CACHE_BUCKET", "") - digest = os.environ.get("STAGE12_CACHE_MANIFEST_DIGEST") - if not digest: - return bucket, None, contents - payload = Stage12CacheStore(bucket).read_manifest(digest) - if payload is None: - msg = "Stage 12 cache manifest is unavailable" - raise RuntimeError(msg) - manifest = CacheManifest.model_validate(payload) - if manifest.bundle.bundle_manifest_sha256 != RESOLVED_BUNDLE.bundle_manifest_sha256: - msg = "Stage 12 cache manifest names another bundle" - raise RuntimeError(msg) - return bucket, manifest.canonical_payload(), contents - - -STAGE12_CACHE_BUCKET, STAGE12_CACHE_MANIFEST, STAGE12_CACHE_CONTENTS = ( - _deploy_time_cache_inputs() -) - - def _external_assertions(environment: dict[str, str]) -> dict[str, str]: mapping = { "STAGE12_EXPECT_POLICYENGINE_VERSION": "policyengine_version", @@ -158,11 +138,6 @@ def _external_assertions(environment: dict[str, str]) -> dict[str, str]: app = modal.App(APP_NAME) -gcp_secret = modal.Secret.from_name("stage12-evaluation-gcp-credentials") -hf_secret = modal.Secret.from_name( - HF_MODAL_SECRET_NAME, - required_keys=[HF_RUNTIME_ENV_NAME], -) comparison_runtime_secret = modal.Secret.from_name("stage12-evaluation-runtime") worker_secrets = [ gcp_secret, @@ -179,117 +154,6 @@ def _external_assertions(environment: dict[str, str]) -> dict[str, str]: report_run_writer_secrets = [*worker_secrets, modal_worker_database_secret] -def _country_bundle(country: CountryId) -> Stage12CountryBundle: - return next( - item for item in RESOLVED_BUNDLE.bundle.countries if item.country == country - ) - - -def _v2_package_image() -> modal.Image: - """Return the base of every v2 image: the CA store and the locked packages.""" - return ( - modal.Image.debian_slim(python_version="3.13") - # Upgrade Debian's CA store before anything is downloaded, and make - # grpcio verify servers against it (src/modal/ca_certificates.py). - .apt_install(OPERATING_SYSTEM_CA_PACKAGE) - .env(GRPC_CA_BUNDLE_ENV) - .uv_sync( - uv_project_dir=_UV_PROJECT_DIR, - frozen=True, - extra_options="--only-group modal-simulation-image", - # The repository's uv release, from .uv-version. - uv_version="0.13.6", - ) - ) - - -def _add_v2_sources(image: modal.Image) -> modal.Image: - """Copy the source packages and static runtime files every v2 image runs.""" - image = image.add_local_python_source( - "src.modal", - "policyengine_simulation_executor", - "policyengine_simulation_observability", - "policyengine_simulation_contract", - "policyengine_simulation_persistence", - "policyengine_stage12_persistence", - copy=True, - ) - return add_static_runtime_files(image, uv_project_dir=_UV_PROJECT_DIR) - - -def build_v2_image( - countries: tuple[CountryId, ...], *, include_us_cache: bool = False -) -> modal.Image: - """Build a Stage 12 image with the bundle's certified data for ``countries``. - - The bundle manifest digest and per-country bundle values are baked into - the image environment, which worker validation checks at run time. With - ``include_us_cache``, the image also holds the published US cache. - """ - country_values = { - country: _country_bundle(country).model_dump(mode="json") - for country in countries - } - image = ( - _v2_package_image() - .run_commands( - bundle_data_install_command( - RESOLVED_BUNDLE.bundle.policyengine_version, - countries=countries, - data_dir=STAGE12_DATA_DIR, - ), - secrets=[hf_secret], - ) - .env( - { - **modal_image_environment(), - "POLICYENGINE_DATA_FOLDER": STAGE12_DATA_DIR, - "STAGE12_BUNDLE_MANIFEST_SHA256": ( - RESOLVED_BUNDLE.bundle_manifest_sha256 - ), - "STAGE12_BUNDLE_VALUES": json.dumps( - country_values, - sort_keys=True, - separators=(",", ":"), - ), - "STAGE12_CACHE_MANIFEST_DIGEST": os.environ.get( - "STAGE12_CACHE_MANIFEST_DIGEST", "" - ), - } - ) - ) - if include_us_cache: - image = image.run_function( - fetch_stage12_cache, - args=(STAGE12_CACHE_BUCKET, STAGE12_CACHE_MANIFEST, STAGE12_CACHE_CONTENTS), - secrets=[gcp_secret], - cpu=2.0, - memory=4096, - # The national files and the state datasets (a file per state for - # each precomputed year), downloaded and hashed in turn. - timeout=3600, - ) - return _add_v2_sources(image) - - -def build_household_image() -> modal.Image: - """Build the household functions' image: packages and source only. - - A household calculation reads no dataset, cache or bucket, so the image - downloads none and its build needs no secret. A function given a - household job records it in the database at run time, with the secret - attached to the function. The installed PolicyEngine.py package names the - bundle the functions calculate with. - """ - return _add_v2_sources(_v2_package_image().env(modal_image_environment())) - - -us_worker_image = build_v2_image(("us",), include_us_cache=True) -uk_worker_image = build_v2_image(("uk",)) -coordinator_image = build_v2_image(("us", "uk")) -household_image = build_household_image() - - def _validate(country: CountryId) -> dict: from policyengine_simulation_executor.stage12_worker_validation import ( # noqa: PLC0415 # Modal function body: loaded in the worker container, not at deploy time validate_country_worker, diff --git a/projects/policyengine-simulation-executor/src/modal/v2_images.py b/projects/policyengine-simulation-executor/src/modal/v2_images.py new file mode 100644 index 000000000..ac1e3d96c --- /dev/null +++ b/projects/policyengine-simulation-executor/src/modal/v2_images.py @@ -0,0 +1,196 @@ +"""The v2 application's images, and what their build steps read when deploying. + +Every v2 image starts from the same packages and the refreshed CA store +(``_v2_package_image``). The worker and coordinator images add the bundle's +certified data for their countries; the US worker image also holds the +published US cache, read from the cache manifest the deploy names +(``_deploy_time_cache_inputs``). The household image holds packages and +source only. ``src/modal/v2_app.py`` attaches the images to its functions and +re-exports every name here. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +from typing import TYPE_CHECKING + +from policyengine_simulation_executor.hf_access_validation import ( + HF_MODAL_SECRET_NAME, + HF_RUNTIME_ENV_NAME, +) +from policyengine_simulation_executor.stage12_bundle import load_stage12_bundle +from policyengine_simulation_executor.stage12_cache.models import CacheManifest +from policyengine_simulation_executor.stage12_cache.store import Stage12CacheStore +from policyengine_simulation_observability.observability import ( + modal_image_environment, +) +from src.modal.bundle_data import bundle_data_install_command +from src.modal.ca_certificates import GRPC_CA_BUNDLE_ENV, OPERATING_SYSTEM_CA_PACKAGE +from src.modal.stage12_cache_image import fetch_stage12_cache +from src.modal.static_runtime_files import add_static_runtime_files + +import modal + +if TYPE_CHECKING: + from policyengine_simulation_contract.stage12_bundle import ( + CountryId, + Stage12CountryBundle, + ) + +STAGE12_DATA_DIR = "/opt/policyengine/stage12-data" +_UV_PROJECT_DIR = str(Path(__file__).resolve().parents[2]) if modal.is_local() else "." +RESOLVED_BUNDLE = load_stage12_bundle() + + +def _deploy_time_cache_inputs() -> tuple[str, dict | None, dict | None]: + """Resolve the cache manifest, and the contents it must hold, when deploying. + + The contents (years and counts) come from the level handlers' settings, + without loading the US model; the image download step checks the + manifest against them. + """ + if not modal.is_local(): + return "", None, None + from policyengine_simulation_executor.stage12_cache.precompute_planning import ( # noqa: PLC0415 # needed on the deploying machine only + expected_cache_contents, + ) + + contents = expected_cache_contents("us") + bucket = os.environ.get("STAGE12_CACHE_BUCKET", "") + digest = os.environ.get("STAGE12_CACHE_MANIFEST_DIGEST") + if not digest: + return bucket, None, contents + payload = Stage12CacheStore(bucket).read_manifest(digest) + if payload is None: + msg = "Stage 12 cache manifest is unavailable" + raise RuntimeError(msg) + manifest = CacheManifest.model_validate(payload) + if manifest.bundle.bundle_manifest_sha256 != RESOLVED_BUNDLE.bundle_manifest_sha256: + msg = "Stage 12 cache manifest names another bundle" + raise RuntimeError(msg) + return bucket, manifest.canonical_payload(), contents + + +STAGE12_CACHE_BUCKET, STAGE12_CACHE_MANIFEST, STAGE12_CACHE_CONTENTS = ( + _deploy_time_cache_inputs() +) + + +gcp_secret = modal.Secret.from_name("stage12-evaluation-gcp-credentials") +hf_secret = modal.Secret.from_name( + HF_MODAL_SECRET_NAME, + required_keys=[HF_RUNTIME_ENV_NAME], +) + + +def _country_bundle(country: CountryId) -> Stage12CountryBundle: + return next( + item for item in RESOLVED_BUNDLE.bundle.countries if item.country == country + ) + + +def _v2_package_image() -> modal.Image: + """Return the base of every v2 image: the CA store and the locked packages.""" + return ( + modal.Image.debian_slim(python_version="3.13") + # Upgrade Debian's CA store before anything is downloaded, and make + # grpcio verify servers against it (src/modal/ca_certificates.py). + .apt_install(OPERATING_SYSTEM_CA_PACKAGE) + .env(GRPC_CA_BUNDLE_ENV) + .uv_sync( + uv_project_dir=_UV_PROJECT_DIR, + frozen=True, + extra_options="--only-group modal-simulation-image", + # The repository's uv release, from .uv-version. + uv_version="0.13.6", + ) + ) + + +def _add_v2_sources(image: modal.Image) -> modal.Image: + """Copy the source packages and static runtime files every v2 image runs.""" + image = image.add_local_python_source( + "src.modal", + "policyengine_simulation_executor", + "policyengine_simulation_observability", + "policyengine_simulation_contract", + "policyengine_simulation_persistence", + "policyengine_stage12_persistence", + copy=True, + ) + return add_static_runtime_files(image, uv_project_dir=_UV_PROJECT_DIR) + + +def build_v2_image( + countries: tuple[CountryId, ...], *, include_us_cache: bool = False +) -> modal.Image: + """Build a Stage 12 image with the bundle's certified data for ``countries``. + + The bundle manifest digest and per-country bundle values are baked into + the image environment, which worker validation checks at run time. With + ``include_us_cache``, the image also holds the published US cache. + """ + country_values = { + country: _country_bundle(country).model_dump(mode="json") + for country in countries + } + image = ( + _v2_package_image() + .run_commands( + bundle_data_install_command( + RESOLVED_BUNDLE.bundle.policyengine_version, + countries=countries, + data_dir=STAGE12_DATA_DIR, + ), + secrets=[hf_secret], + ) + .env( + { + **modal_image_environment(), + "POLICYENGINE_DATA_FOLDER": STAGE12_DATA_DIR, + "STAGE12_BUNDLE_MANIFEST_SHA256": ( + RESOLVED_BUNDLE.bundle_manifest_sha256 + ), + "STAGE12_BUNDLE_VALUES": json.dumps( + country_values, + sort_keys=True, + separators=(",", ":"), + ), + "STAGE12_CACHE_MANIFEST_DIGEST": os.environ.get( + "STAGE12_CACHE_MANIFEST_DIGEST", "" + ), + } + ) + ) + if include_us_cache: + image = image.run_function( + fetch_stage12_cache, + args=(STAGE12_CACHE_BUCKET, STAGE12_CACHE_MANIFEST, STAGE12_CACHE_CONTENTS), + secrets=[gcp_secret], + cpu=2.0, + memory=4096, + # The national files and the state datasets (a file per state for + # each precomputed year), downloaded and hashed in turn. + timeout=3600, + ) + return _add_v2_sources(image) + + +def build_household_image() -> modal.Image: + """Build the household functions' image: packages and source only. + + A household calculation reads no dataset, cache or bucket, so the image + downloads none and its build needs no secret. A function given a + household job records it in the database at run time, with the secret + attached to the function. The installed PolicyEngine.py package names the + bundle the functions calculate with. + """ + return _add_v2_sources(_v2_package_image().env(modal_image_environment())) + + +us_worker_image = build_v2_image(("us",), include_us_cache=True) +uk_worker_image = build_v2_image(("uk",)) +coordinator_image = build_v2_image(("us", "uk")) +household_image = build_household_image() diff --git a/projects/policyengine-simulation-executor/tests/test_modal_scripts.py b/projects/policyengine-simulation-executor/tests/test_modal_scripts.py index c2c4bdd7e..90b18155c 100644 --- a/projects/policyengine-simulation-executor/tests/test_modal_scripts.py +++ b/projects/policyengine-simulation-executor/tests/test_modal_scripts.py @@ -336,6 +336,8 @@ def test_deployment_sources_exclude_legacy_hf_secret_names(self): REPO_ROOT / "projects/policyengine-simulation-executor/src/modal/app.py", REPO_ROOT / "projects/policyengine-simulation-executor/src/modal/v2_app.py", REPO_ROOT + / "projects/policyengine-simulation-executor/src/modal/v2_images.py", + REPO_ROOT / "projects/policyengine-simulation-executor/src/modal/precompute_app.py", REPO_ROOT / "projects/policyengine-simulation-executor/src/modal" diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_modal_app.py b/projects/policyengine-simulation-executor/tests/test_stage12_modal_app.py index 88fcae044..9a2ffa850 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_modal_app.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_modal_app.py @@ -44,6 +44,8 @@ def shutdown(self) -> None: def _load(monkeypatch): install_fake_modal(monkeypatch) + # The app builds its images in src/modal/v2_images.py. + sys.modules.pop("src.modal.v2_images", None) sys.modules.pop("src.modal.v2_app", None) return importlib.import_module("src.modal.v2_app") diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_wait_window.py b/projects/policyengine-simulation-executor/tests/test_stage12_wait_window.py index 4e97b6bfc..646e63fcb 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_wait_window.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_wait_window.py @@ -37,6 +37,7 @@ def advance(self, elapsed_seconds): def _declared_modal_timeouts(monkeypatch): install_fake_modal(monkeypatch) + sys.modules.pop("src.modal.v2_images", None) sys.modules.pop("src.modal.v2_app", None) modal_app = importlib.import_module("src.modal.v2_app") return { diff --git a/projects/policyengine-simulation-executor/tests/test_v2_image_smoke.py b/projects/policyengine-simulation-executor/tests/test_v2_image_smoke.py index 9ffe1a674..a8e00e901 100644 --- a/projects/policyengine-simulation-executor/tests/test_v2_image_smoke.py +++ b/projects/policyengine-simulation-executor/tests/test_v2_image_smoke.py @@ -16,6 +16,7 @@ def v2_modules(monkeypatch): """Import the v2 application and its image smoke under the fake Modal.""" install_fake_modal(monkeypatch) + sys.modules.pop("src.modal.v2_images", None) sys.modules.pop("src.modal.v2_app", None) sys.modules.pop("src.modal.v2_image_smoke", None) v2_app = importlib.import_module("src.modal.v2_app") From 262c1eceb7affd52b4414750736acf237a016528 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:32:12 +0400 Subject: [PATCH 02/10] Move the Modal 1.6.4 client check into its own module 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 --- .../src/modal/app.py | 35 +---------------- .../src/modal/modal_client_version.py | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 33 deletions(-) create mode 100644 projects/policyengine-simulation-executor/src/modal/modal_client_version.py diff --git a/projects/policyengine-simulation-executor/src/modal/app.py b/projects/policyengine-simulation-executor/src/modal/app.py index 8d294e701..c4bf759d1 100644 --- a/projects/policyengine-simulation-executor/src/modal/app.py +++ b/projects/policyengine-simulation-executor/src/modal/app.py @@ -17,7 +17,6 @@ from pathlib import Path from typing import TYPE_CHECKING -from packaging.version import InvalidVersion, Version from policyengine_simulation_executor.hf_access_validation import ( HF_MODAL_SECRET_NAME, HF_RUNTIME_ENV_NAME, @@ -48,6 +47,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.modal_client_version import require_secret_reloading_modal_client from src.modal.snapshot_warm_up import warm_up_first_calculation from src.modal.static_runtime_files import add_static_runtime_files @@ -58,39 +58,8 @@ from policyengine_simulation_executor.job_progress import JobProgressReporter -# Containers restored from a memory snapshot reload Secret values only from -# Modal 1.6.4, and each app's containers run the Modal client that deployed it. -# This project's uv.lock pins such a client; the check refuses a deploy or run -# from an environment with an older one, such as a global Modal install. -FIRST_MODAL_CLIENT_RELOADING_SECRETS_ON_RESTORE = Version("1.6.4") - - -def _require_secret_reloading_modal_client(client_version: str) -> None: - """Raise unless ``client_version`` is Modal 1.6.4 or newer. - - Versions compare as Python packaging defines them, so 1.6.4's development - builds and release candidates count as older than 1.6.4. - """ - try: - reloads_secrets = ( - Version(client_version) >= FIRST_MODAL_CLIENT_RELOADING_SECRETS_ON_RESTORE - ) - except InvalidVersion: - reloads_secrets = False - if not reloads_secrets: - msg = ( - f"Modal client {client_version} is not " - f"{FIRST_MODAL_CLIENT_RELOADING_SECRETS_ON_RESTORE} or newer: containers " - "restored from this app's memory snapshots would keep the Secret values " - "from when each snapshot was taken. Deploy and run from this project's " - "locked environment, for example " - "`uv run --frozen modal deploy src/modal/app.py`." - ) - raise RuntimeError(msg) - - if modal.is_local(): - _require_secret_reloading_modal_client(modal.__version__) + require_secret_reloading_modal_client(modal.__version__) def _version_from_env_or_local_bundle_package(env_var: str, package: str) -> str: diff --git a/projects/policyengine-simulation-executor/src/modal/modal_client_version.py b/projects/policyengine-simulation-executor/src/modal/modal_client_version.py new file mode 100644 index 000000000..b3b63f89f --- /dev/null +++ b/projects/policyengine-simulation-executor/src/modal/modal_client_version.py @@ -0,0 +1,38 @@ +"""Refuse to deploy or run an app with snapshots from a Modal client before 1.6.4. + +Containers restored from a memory snapshot reload Secret values only from +Modal 1.6.4, and each app's containers run the Modal client that deployed it. +This project's uv.lock pins such a client; the check refuses a deploy or run +from an environment with an older one, such as a global Modal install. The +run_simulation app (``src/modal/app.py``) and the v2 app +(``src/modal/v2_app.py``) both run it on import, on the deploying machine, +before they read anything. +""" + +from packaging.version import InvalidVersion, Version + +FIRST_MODAL_CLIENT_RELOADING_SECRETS_ON_RESTORE = Version("1.6.4") + + +def require_secret_reloading_modal_client(client_version: str) -> None: + """Raise unless ``client_version`` is Modal 1.6.4 or newer. + + Versions compare as Python packaging defines them, so 1.6.4's development + builds and release candidates count as older than 1.6.4. + """ + try: + reloads_secrets = ( + Version(client_version) >= FIRST_MODAL_CLIENT_RELOADING_SECRETS_ON_RESTORE + ) + except InvalidVersion: + reloads_secrets = False + if not reloads_secrets: + msg = ( + f"Modal client {client_version} is not " + f"{FIRST_MODAL_CLIENT_RELOADING_SECRETS_ON_RESTORE} or newer: containers " + "restored from this app's memory snapshots would keep the Secret values " + "from when each snapshot was taken. Deploy and run from this project's " + "locked environment, for example " + "`uv run --frozen modal deploy src/modal/app.py`." + ) + raise RuntimeError(msg) From 5328c8dee0aebc47c217e657a3ac2ccd668f066d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:36:16 +0400 Subject: [PATCH 03/10] Test the v2 workers as Modal classes restored from memory snapshots MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../tests/test_stage12_simulation_workers.py | 46 +++ .../tests/test_economy_workers.py | 117 +++++- .../tests/test_country_model_preload.py | 21 ++ .../tests/test_stage12_child_state_errors.py | 10 +- .../tests/test_stage12_coordination.py | 90 +++-- .../tests/test_stage12_segment_fanout.py | 67 +++- .../tests/test_update_v2_version_manifest.py | 13 + .../tests/test_v2_worker_classes.py | 342 ++++++++++++++++++ 8 files changed, 646 insertions(+), 60 deletions(-) create mode 100644 libs/policyengine-simulation-contract/tests/test_stage12_simulation_workers.py create mode 100644 projects/policyengine-simulation-executor/tests/test_v2_worker_classes.py diff --git a/libs/policyengine-simulation-contract/tests/test_stage12_simulation_workers.py b/libs/policyengine-simulation-contract/tests/test_stage12_simulation_workers.py new file mode 100644 index 000000000..6d50228df --- /dev/null +++ b/libs/policyengine-simulation-contract/tests/test_stage12_simulation_workers.py @@ -0,0 +1,46 @@ +"""The Modal classes the v2 runtime's simulation workers are reached through.""" + +import pytest +from policyengine_simulation_contract.household_execution import ( + household_callable_name, +) +from policyengine_simulation_contract.stage12_simulation_workers import ( + SEGMENT_WORKER_CLASS, + SEGMENT_WORKER_METHOD, + worker_class_name, +) + + +@pytest.mark.parametrize( + ("method_name", "expected_class_name"), + [ + ("run_single_simulation_us", "SimulationWorkerUS"), + ("run_single_simulation_uk", "SimulationWorkerUK"), + ("run_single_simulation_segment_us", "SimulationSegmentWorkerUS"), + ], +) +def test_each_simulation_worker_is_a_method_of_its_class_under_its_old_name( + method_name, expected_class_name +) -> None: + # The v2 version manifest, coordinator contexts and comparison-run rows + # store the worker's function name, so the same name reaches the method. + assert worker_class_name(method_name) == expected_class_name + + +def test_the_segment_worker_names_agree() -> None: + assert worker_class_name(SEGMENT_WORKER_METHOD) == SEGMENT_WORKER_CLASS + + +@pytest.mark.parametrize( + "function_name", + [ + "coordinate_report", + household_callable_name("us"), + household_callable_name("uk"), + "validate_worker_us", + # The run_simulation app's worker, which no v2 caller names. + "run_simulation", + ], +) +def test_the_v2_apps_other_functions_have_no_worker_class(function_name) -> None: + assert worker_class_name(function_name) is None diff --git a/projects/policyengine-simulation-entry/tests/test_economy_workers.py b/projects/policyengine-simulation-entry/tests/test_economy_workers.py index b6795ca6e..88042a284 100644 --- a/projects/policyengine-simulation-entry/tests/test_economy_workers.py +++ b/projects/policyengine-simulation-entry/tests/test_economy_workers.py @@ -6,6 +6,7 @@ from types import SimpleNamespace from typing import Any +import modal import pytest from economy_fixtures import economy_manifest, economy_worker_version from household_fixtures import ( @@ -131,6 +132,45 @@ def from_name(application: str, name: str, *, environment_name: str): return looked_up, function +class FakeWorkerClass: + """A Modal class looked up by name, whose worker methods spawn ``method``. + + With ``deployed`` False, hydrating it fails as it does for an app deployed + before the workers were classes. + """ + + def __init__(self, method: FakeFunction) -> None: + self.method = method + self.deployed = True + self.hydrate = SimpleNamespace(aio=self._hydrate) + + async def _hydrate(self) -> FakeWorkerClass: + if not self.deployed: + msg = "the app defines no such class" + raise modal.exception.NotFoundError(msg) + return self + + def __call__(self) -> SimpleNamespace: + return SimpleNamespace( + run_single_simulation_us=self.method, + run_single_simulation_uk=self.method, + ) + + +@pytest.fixture +def modal_worker_classes(monkeypatch): + """Replace Modal's class lookup by name; return the lookups and the class.""" + looked_up: list[tuple[str, str, str]] = [] + worker_class = FakeWorkerClass(FakeFunction("fc-started-on-the-class")) + + def from_name(application: str, name: str, *, environment_name: str): + looked_up.append((application, name, environment_name)) + return worker_class + + monkeypatch.setattr(economy_workers.modal.Cls, "from_name", staticmethod(from_name)) + return looked_up, worker_class + + def test_a_report_run_starts_the_coordinator_with_its_report_and_context( modal_functions, ) -> None: @@ -157,10 +197,11 @@ def test_a_report_run_starts_the_coordinator_with_its_report_and_context( ] -def test_a_standalone_run_starts_the_countrys_simulation_function( - modal_functions, +def test_a_standalone_run_starts_the_countrys_simulation_worker_class( + modal_functions, modal_worker_classes ) -> None: - looked_up, function = modal_functions + looked_up_functions, _function = modal_functions + looked_up_classes, worker_class = modal_worker_classes worker = default_economy_worker(economy_manifest(), "uk") call_id = asyncio.run( @@ -172,9 +213,14 @@ def test_a_standalone_run_starts_the_countrys_simulation_function( ) ) - assert call_id == "fc-started" - assert looked_up == [(worker.application_name, "run_single_simulation_uk", "main")] - assert function.spawns == [ + # The class's containers restore from a memory snapshot with the models + # loaded; the manifest names the worker by its method. + assert call_id == "fc-started-on-the-class" + assert looked_up_classes == [ + (worker.application_name, "SimulationWorkerUK", "main") + ] + assert looked_up_functions == [] + assert worker_class.method.spawns == [ ( ({"simulation": 1}, {"simulation_run_id": "run"}), {"observability_context": None}, @@ -182,11 +228,12 @@ def test_a_standalone_run_starts_the_countrys_simulation_function( ] -def test_a_cliff_calculation_starts_the_countrys_simulation_function( - modal_functions, +def test_a_cliff_calculation_starts_the_countrys_simulation_worker_class( + modal_functions, modal_worker_classes ) -> None: """C1 · 38's cliff mode: the context names the cliff result, not a run.""" - looked_up, function = modal_functions + looked_up_functions, _function = modal_functions + looked_up_classes, worker_class = modal_worker_classes worker = default_economy_worker(economy_manifest(), "uk") call_id = asyncio.run( @@ -198,9 +245,12 @@ def test_a_cliff_calculation_starts_the_countrys_simulation_function( ) ) - assert call_id == "fc-started" - assert looked_up == [(worker.application_name, "run_single_simulation_uk", "main")] - assert function.spawns == [ + assert call_id == "fc-started-on-the-class" + assert looked_up_classes == [ + (worker.application_name, "SimulationWorkerUK", "main") + ] + assert looked_up_functions == [] + assert worker_class.method.spawns == [ ( ({"simulation": 1}, {"cliff_result_id": "cliffs"}), {"observability_context": {"observability_id": "observed"}}, @@ -208,6 +258,49 @@ def test_a_cliff_calculation_starts_the_countrys_simulation_function( ] +@pytest.mark.parametrize("start", ["start_simulation_run", "start_cliff_calculation"]) +def test_an_app_without_the_worker_class_gets_the_simulation_function( + modal_functions, modal_worker_classes, start +) -> None: + # An app deployed for an older .py version, which the manifest's default + # can name after a move or a rollback, defines the worker as a function. + looked_up_functions, function = modal_functions + _looked_up_classes, worker_class = modal_worker_classes + worker_class.deployed = False + worker = default_economy_worker(economy_manifest(), "us") + + call_id = asyncio.run( + getattr(ModalEconomyRunCaller("main"), start)( + worker, {"simulation": 1}, {"run": "context"}, observability_context=None + ) + ) + + assert call_id == "fc-started" + assert looked_up_functions == [ + (worker.application_name, "run_single_simulation_us", "main") + ] + assert worker_class.method.spawns == [] + assert function.spawns == [ + (({"simulation": 1}, {"run": "context"}), {"observability_context": None}) + ] + + +@pytest.mark.parametrize("object_id", [None, ""]) +def test_a_class_call_modal_gives_no_id_is_an_error( + modal_worker_classes, object_id +) -> None: + _looked_up, worker_class = modal_worker_classes + worker_class.method.object_id = object_id + worker = default_economy_worker(economy_manifest(), "us") + + with pytest.raises(RuntimeError, match="no call ID"): + asyncio.run( + ModalEconomyRunCaller("staging").start_simulation_run( + worker, {}, {}, observability_context=None + ) + ) + + @pytest.mark.parametrize("object_id", [None, ""]) def test_a_call_modal_gives_no_id_is_an_error(modal_functions, object_id) -> None: _, function = modal_functions diff --git a/projects/policyengine-simulation-executor/tests/test_country_model_preload.py b/projects/policyengine-simulation-executor/tests/test_country_model_preload.py index 140ebd4da..8589d8b0c 100644 --- a/projects/policyengine-simulation-executor/tests/test_country_model_preload.py +++ b/projects/policyengine-simulation-executor/tests/test_country_model_preload.py @@ -42,6 +42,27 @@ def test_preload_imports_both_countries_models_then_fills_the_spm_cache( assert spm_checks == ["checked"] +def test_a_uk_preload_imports_only_the_uk_models_and_checks_no_spm(recorded_preload): + imported_modules, spm_checks = recorded_preload + + country_model_preload.preload_country_models(("uk",)) + + # The v2 UK worker's image holds only UK data, and SPM is a US measure. + assert imported_modules == ["policyengine_uk", "policyengine.tax_benefit_models.uk"] + assert spm_checks == [] + + +def test_a_us_preload_imports_only_the_us_models_then_fills_the_spm_cache( + recorded_preload, +): + imported_modules, spm_checks = recorded_preload + + country_model_preload.preload_country_models(("us",)) + + assert imported_modules == ["policyengine_us", "policyengine.tax_benefit_models.us"] + assert spm_checks == ["checked"] + + def test_a_country_that_fails_to_import_is_left_to_its_own_calls(monkeypatch, caplog): imported_modules: list[str] = [] spm_checks: list[str] = [] diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_child_state_errors.py b/projects/policyengine-simulation-executor/tests/test_stage12_child_state_errors.py index 244a15dac..a01b5be2f 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_child_state_errors.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_child_state_errors.py @@ -341,10 +341,12 @@ def spawn(self, payload, *, observability_context): ), ) - class SegmentFunctionLookup: + class SegmentWorkerLookup: @staticmethod - def from_name(_app_name, _function_name): - return SegmentFunction() + def from_name(_app_name, _class_name): + return lambda: SimpleNamespace( + run_single_simulation_segment_us=SegmentFunction() + ) def segmented_calculator(value, cancellation_requested): return Stage12SegmentRunner( @@ -353,7 +355,7 @@ def segmented_calculator(value, cancellation_requested): runtime=runtime, cancellation_requested=cancellation_requested, seams=SegmentRunnerSeams( - modal_module=SimpleNamespace(Function=SegmentFunctionLookup), + modal_module=SimpleNamespace(Cls=SegmentWorkerLookup), groups=US_REGION_GROUPS, sleep=lambda _seconds: None, ), diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_coordination.py b/projects/policyengine-simulation-executor/tests/test_stage12_coordination.py index cba59a96f..e90f3cb43 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_coordination.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_coordination.py @@ -527,31 +527,54 @@ def aggregate(**values): assert child.simulation_callable == "run_single_simulation_us" -def test_modal_child_invoker_spawns_and_restores_deployed_functions(monkeypatch): +def _recording_modal(calls: list) -> object: + """Stand in for ``modal``, recording each lookup, spawn and restore in ``calls``.""" from types import SimpleNamespace - from policyengine_simulation_executor.stage12_runtime import dependencies - - calls = [] - - def from_name(*args, **kwargs): - calls.append(("from_name", args, kwargs)) - - def spawn(*spawn_args, **spawn_kwargs): - calls.append(("spawn", spawn_args, spawn_kwargs)) - return "spawned-call" + def spawn(*spawn_args, **spawn_kwargs): + calls.append(("spawn", spawn_args, spawn_kwargs)) + return "spawned-call" + def function_from_name(*args, **kwargs): + calls.append(("Function.from_name", args, kwargs)) return SimpleNamespace(spawn=spawn) + def class_from_name(*args, **kwargs): + calls.append(("Cls.from_name", args, kwargs)) + return lambda: SimpleNamespace( + run_single_simulation_us=SimpleNamespace(spawn=spawn) + ) + def from_id(invocation_id): - calls.append(("from_id", (invocation_id,), {})) + calls.append(("FunctionCall.from_id", (invocation_id,), {})) return "restored-call" - fake_modal = SimpleNamespace( - Function=SimpleNamespace(from_name=from_name), + return SimpleNamespace( + Cls=SimpleNamespace(from_name=class_from_name), + Function=SimpleNamespace(from_name=function_from_name), FunctionCall=SimpleNamespace(from_id=from_id), ) + +def _spawn_request(dependencies, function_name: str): + return dependencies.ChildSpawnRequest( + application_name="application", + function_name=function_name, + environment="staging", + simulation={"role": "baseline"}, + context={"request_id": "request-1"}, + observability_context={"traceparent": "trace"}, + ) + + +def test_modal_child_invoker_spawns_a_worker_through_its_class_and_restores_calls( + monkeypatch, +): + from policyengine_simulation_executor.stage12_runtime import dependencies + + calls = [] + fake_modal = _recording_modal(calls) + def import_modal(module_name): assert module_name == "modal" return fake_modal @@ -559,23 +582,16 @@ def import_modal(module_name): monkeypatch.setattr(dependencies, "import_module", import_modal) invoker = dependencies.ModalChildInvoker() - spawned = invoker.spawn( - dependencies.ChildSpawnRequest( - application_name="application", - function_name="run_single_simulation_us", - environment="staging", - simulation={"role": "baseline"}, - context={"request_id": "request-1"}, - observability_context={"traceparent": "trace"}, - ) - ) + spawned = invoker.spawn(_spawn_request(dependencies, "run_single_simulation_us")) restored = invoker.restore("call-1") + # The class's containers restore from a memory snapshot with the models + # loaded; the context still names the worker by its method. assert (spawned, restored) == ("spawned-call", "restored-call") assert calls == [ ( - "from_name", - ("application", "run_single_simulation_us"), + "Cls.from_name", + ("application", "SimulationWorkerUS"), {"environment_name": "staging"}, ), ( @@ -583,10 +599,30 @@ def import_modal(module_name): ({"role": "baseline"}, {"request_id": "request-1"}), {"observability_context": {"traceparent": "trace"}}, ), - ("from_id", ("call-1",), {}), + ("FunctionCall.from_id", ("call-1",), {}), ] +def test_modal_child_invoker_spawns_a_callable_without_a_class_as_a_function( + monkeypatch, +): + from policyengine_simulation_executor.stage12_runtime import dependencies + + calls = [] + fake_modal = _recording_modal(calls) + monkeypatch.setattr(dependencies, "import_module", lambda _name: fake_modal) + + dependencies.ModalChildInvoker().spawn( + _spawn_request(dependencies, "a_function_of_another_kind") + ) + + assert calls[0] == ( + "Function.from_name", + ("application", "a_function_of_another_kind"), + {"environment_name": "staging"}, + ) + + def _shadow_run(store, artifacts, invoker, runtime=None): context = invocation_context().model_copy( update={"production_function_call_id": "production-job-1"} diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_segment_fanout.py b/projects/policyengine-simulation-executor/tests/test_stage12_segment_fanout.py index ce42040e0..f722d39cb 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_segment_fanout.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_segment_fanout.py @@ -111,6 +111,50 @@ def _results(simulation) -> list[dict]: ] +def _segment_worker_lookup( + segment_function: object, + class_lookups: list[tuple[str, str]] | None = None, +) -> SimpleNamespace: + """Stand in for ``modal``: its segment worker class spawns ``segment_function``. + + Each lookup of a class by name is appended to ``class_lookups``. + """ + + class ClassLookup: + @staticmethod + def from_name(app_name, class_name): + if class_lookups is not None: + class_lookups.append((app_name, class_name)) + return lambda: SimpleNamespace( + run_single_simulation_segment_us=segment_function + ) + + return SimpleNamespace(Cls=ClassLookup) + + +def test_segments_are_started_through_the_segment_worker_class() -> None: + # The class's containers restore from a memory snapshot with the US + # models loaded. + simulation = planned_simulation(SimulationRole.BASELINE) + function = FakeFunction(_results(simulation), {}) + class_lookups: list[tuple[str, str]] = [] + runner = Stage12SegmentRunner( + simulation, + app_name="stage12-app", + runtime=cast("ObservabilityRuntime", FakeRuntime()), + seams=SegmentRunnerSeams( + modal_module=_segment_worker_lookup(function, class_lookups), + groups=US_REGION_GROUPS, + sleep=lambda _seconds: None, + ), + ) + + runner.run() + + assert class_lookups == [("stage12-app", "SimulationSegmentWorkerUS")] + assert len(function.spawns) == len(US_REGION_GROUPS) + + def _runner( *, errors: dict[int, list[Exception]] | None = None, @@ -119,13 +163,6 @@ def _runner( simulation = planned_simulation(SimulationRole.BASELINE) function = FakeFunction(_results(simulation), errors or {}) - class FunctionLookup: - @staticmethod - def from_name(app_name, function_name): - assert app_name == "stage12-app" - assert function_name == "run_single_simulation_segment_us" - return function - span_runtime = runtime if runtime is not None else FakeRuntime() sleeps: list[float] = [] runner = Stage12SegmentRunner( @@ -133,7 +170,7 @@ def from_name(app_name, function_name): app_name="stage12-app", runtime=cast("ObservabilityRuntime", span_runtime), seams=SegmentRunnerSeams( - modal_module=SimpleNamespace(Function=FunctionLookup), + modal_module=_segment_worker_lookup(function), groups=US_REGION_GROUPS, sleep=sleeps.append, poll_interval_seconds=0.5, @@ -355,9 +392,10 @@ def spawn(self, payload: dict, **keywords): @pytest.mark.parametrize( ("simulation_run_id", "expected_keyword"), [ - (UUID("00000000-0000-4000-8000-00000000b001"), { - "simulation_run_id": "00000000-0000-4000-8000-00000000b001" - }), + ( + UUID("00000000-0000-4000-8000-00000000b001"), + {"simulation_run_id": "00000000-0000-4000-8000-00000000b001"}, + ), (None, {}), ], ids=["simulation-run", "comparison-path"], @@ -369,18 +407,13 @@ def test_segments_are_started_naming_the_simulation_run_of_their_worker( simulation = planned_simulation(SimulationRole.BASELINE) function = FunctionRecordingSpawnKeywords(_results(simulation)) - class FunctionLookup: - @staticmethod - def from_name(_app_name, _function_name): - return function - runner = Stage12SegmentRunner( simulation, app_name="stage12-app", runtime=cast("ObservabilityRuntime", FakeRuntime()), simulation_run_id=simulation_run_id, seams=SegmentRunnerSeams( - modal_module=SimpleNamespace(Function=FunctionLookup), + modal_module=_segment_worker_lookup(function), groups=US_REGION_GROUPS, sleep=lambda _seconds: None, ), diff --git a/projects/policyengine-simulation-executor/tests/test_update_v2_version_manifest.py b/projects/policyengine-simulation-executor/tests/test_update_v2_version_manifest.py index f30ba6dbf..03ddac5fd 100644 --- a/projects/policyengine-simulation-executor/tests/test_update_v2_version_manifest.py +++ b/projects/policyengine-simulation-executor/tests/test_update_v2_version_manifest.py @@ -11,6 +11,9 @@ LocalAreaReports, V2WorkerValidation, ) +from policyengine_simulation_contract.stage12_simulation_workers import ( + worker_class_name, +) from src.modal.utils import update_v2_version_manifest as publisher @@ -60,6 +63,16 @@ def test_publisher_records_every_bundle_country_as_economy_capable() -> None: ] +def test_each_published_simulation_callable_is_a_worker_class_method() -> None: + worker = publisher.build_worker(_validation().model_dump(mode="json")) + + # The entry service and the coordinator spawn the named simulation + # callable through the class that defines it as a method. + for country in worker.countries: + assert country.single_simulation_callable is not None + assert worker_class_name(country.single_simulation_callable) is not None + + def _local_area_reports(worker) -> dict[str, LocalAreaReports | None]: return {country.country: country.local_area_reports for country in worker.countries} diff --git a/projects/policyengine-simulation-executor/tests/test_v2_worker_classes.py b/projects/policyengine-simulation-executor/tests/test_v2_worker_classes.py new file mode 100644 index 000000000..08c885d9c --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_v2_worker_classes.py @@ -0,0 +1,342 @@ +"""The v2 runtime's simulation workers: Modal classes restored from memory snapshots.""" + +from __future__ import annotations + +import importlib +import random +import sys +from contextlib import contextmanager + +import pytest +from fixtures.fake_modal import install_fake_modal +from policyengine_simulation_contract.stage12_simulation_workers import ( + SEGMENT_WORKER_CLASS, + SEGMENT_WORKER_METHOD, + worker_class_name, +) +from policyengine_simulation_executor.stage12_timeouts import ( + UK_SIMULATION_TIMEOUT_SECONDS, + US_SIMULATION_TIMEOUT_SECONDS, +) + +WORKER_METHOD_NAMES = ( + "run_single_simulation_us", + "run_single_simulation_uk", + "run_single_simulation_segment_us", +) + + +def _load_v2_app(monkeypatch): + install_fake_modal(monkeypatch) + sys.modules.pop("src.modal.v2_images", None) + sys.modules.pop("src.modal.v2_app", None) + return importlib.import_module("src.modal.v2_app") + + +def _worker_class(v2_app, method_name: str) -> type: + class_name = worker_class_name(method_name) + assert class_name is not None, method_name + return getattr(v2_app, class_name) + + +def _expected_worker_options(v2_app) -> dict[str, dict]: + """Each worker's Modal options, shared by its class and its plain function.""" + simulation_worker_resources = { + "cpu": 8.0, + "memory": 32768, + "retries": 0, + # Both simulations of every coordinator call that may run at once, + # and the runs the entry service starts directly. + "max_containers": 50, + "secrets": v2_app.report_run_writer_secrets, + } + return { + "run_single_simulation_us": { + "image": v2_app.us_worker_image, + "timeout": US_SIMULATION_TIMEOUT_SECONDS, + **simulation_worker_resources, + }, + "run_single_simulation_uk": { + "image": v2_app.uk_worker_image, + "timeout": UK_SIMULATION_TIMEOUT_SECONDS, + **simulation_worker_resources, + }, + "run_single_simulation_segment_us": { + "image": v2_app.us_worker_image, + "cpu": 8.0, + "memory": 32768, + "timeout": 3600, + "retries": 0, + "max_containers": 1000, + # A segment returns its result to its worker and records nothing. + "secrets": v2_app.worker_secrets, + }, + } + + +def test_the_v2_simulation_workers_are_classes_restored_from_memory_snapshots( + monkeypatch, +) -> None: + v2_app = _load_v2_app(monkeypatch) + + assert dict(v2_app.app.cls_calls) == { + worker_class_name(method_name): {**options, "enable_memory_snapshot": True} + for method_name, options in _expected_worker_options(v2_app).items() + } + + +def test_each_v2_worker_class_defines_the_method_its_callers_name( + monkeypatch, +) -> None: + v2_app = _load_v2_app(monkeypatch) + recorded_methods = v2_app.modal.lifecycle_hooks.methods + + for method_name in WORKER_METHOD_NAMES: + worker_method = getattr(_worker_class(v2_app, method_name), method_name) + assert worker_method in recorded_methods + # A segmented US simulation spawns its segments through this class. + segment_worker = getattr(v2_app, SEGMENT_WORKER_CLASS) + assert getattr(segment_worker, SEGMENT_WORKER_METHOD) in recorded_methods + + +def test_plain_functions_keep_the_workers_for_callers_on_older_code( + monkeypatch, +) -> None: + v2_app = _load_v2_app(monkeypatch) + function_options = dict(v2_app.app.function_calls) + + # An entry service revision from before the classes, and a coordinator or + # US worker call running while the app is redeployed in place, look these + # functions up by name. They keep the workers' options, without snapshots. + for method_name, options in _expected_worker_options(v2_app).items(): + assert function_options[method_name] == options + + +def test_each_v2_worker_class_has_one_snapshot_hook_and_one_restore_hook( + monkeypatch, +) -> None: + v2_app = _load_v2_app(monkeypatch) + + enter_hooks = v2_app.modal.lifecycle_hooks.enter_hooks + snapshot_hooks = [method for method, snap in enter_hooks if snap] + restore_hooks = [method for method, snap in enter_hooks if not snap] + assert len(snapshot_hooks) == 1 + assert len(restore_hooks) == 1 + for method_name in WORKER_METHOD_NAMES: + worker_class = _worker_class(v2_app, method_name) + assert worker_class.load_country_models is snapshot_hooks[0] + assert worker_class.reseed_random_after_restore is restore_hooks[0] + + +def test_each_v2_worker_class_loads_only_its_own_countrys_models( + monkeypatch, +) -> None: + v2_app = _load_v2_app(monkeypatch) + preloaded_countries: list[tuple[str, ...]] = [] + monkeypatch.setattr( + v2_app, + "preload_country_models", + lambda countries: preloaded_countries.append(tuple(countries)), + ) + + for method_name in WORKER_METHOD_NAMES: + _worker_class(v2_app, method_name)().load_country_models() + + # Each image holds one country's data. A UK container never imports the + # US models, so a failed US import can't affect it, and the reverse. + assert preloaded_countries == [("us",), ("uk",), ("us",)] + + +def test_the_v2_snapshot_hook_configures_no_observability(monkeypatch) -> None: + v2_app = _load_v2_app(monkeypatch) + preloads: list[str] = [] + monkeypatch.setattr( + v2_app, "preload_country_models", lambda _countries: preloads.append("ran") + ) + + def observability_before_the_snapshot(*_arguments, **_keywords): + # A process identity configured here would be shared by every + # container restored from the snapshot. + msg = "observability must be configured per call, after the restore" + raise AssertionError(msg) + + monkeypatch.setattr( + v2_app, "init_process_observability", observability_before_the_snapshot + ) + + for method_name in WORKER_METHOD_NAMES: + _worker_class(v2_app, method_name)().load_country_models() + + assert preloads == ["ran", "ran", "ran"] + + +def test_each_restored_v2_container_draws_its_own_random_numbers(monkeypatch) -> None: + v2_app = _load_v2_app(monkeypatch) + # Every container restored from one snapshot starts from the random state + # the snapshot captured, and Python reseeds only after a fork. + snapshot_state = random.getstate() + + v2_app.SimulationWorkerUS().reseed_random_after_restore() + first_container_span_id = random.getrandbits(64) + random.setstate(snapshot_state) + v2_app.SimulationSegmentWorkerUS().reseed_random_after_restore() + second_container_span_id = random.getrandbits(64) + + # OpenTelemetry draws span IDs this way, and the database and dataset + # download retries draw their delays from the same generator. + assert first_container_span_id != second_container_span_id + + +class RecordingRuntime: + """Stands in for the per-call observability runtime.""" + + def __init__(self) -> None: + self.operation_names: list[str] = [] + self.shutdown_calls = 0 + + def set_context(self, **_attributes) -> None: + pass + + def capture_context(self) -> dict: + return {} + + @contextmanager + def operation(self, name, **_keywords): + self.operation_names.append(name) + yield + + def shutdown(self) -> None: + self.shutdown_calls += 1 + + +def _call_worker(monkeypatch, v2_app, worker) -> dict: + """Call ``worker`` as its callers do; return what it ran and returned.""" + from policyengine_simulation_executor import stage12_runtime + + runtime = RecordingRuntime() + received_keywords: dict = {} + monkeypatch.setattr(v2_app, "init_process_observability", lambda **_: runtime) + monkeypatch.setattr( + v2_app.modal, "current_function_call_id", lambda: "fc-worker-call" + ) + + def run_single_simulation(payload, context, **keywords): + received_keywords.update(keywords) + return {"calculated": payload["role"], "context": context} + + class SegmentResult: + def model_dump(self, *, mode): + assert mode == "python" + return {"calculated": "segment"} + + monkeypatch.setattr(stage12_runtime, "run_single_simulation", run_single_simulation) + monkeypatch.setattr( + stage12_runtime, "calculate_segment", lambda *_, **__: SegmentResult() + ) + if worker.__name__ == SEGMENT_WORKER_METHOD: + result = worker( + {"simulation": {"role": "baseline"}, "segment_index": 0}, + observability_context=None, + ) + else: + result = worker({"role": "baseline"}, {}, observability_context=None) + return { + "result": result, + "operations": runtime.operation_names, + "shutdown_calls": runtime.shutdown_calls, + "modal_call_id": received_keywords.get("modal_call_id"), + "required_country": received_keywords.get("required_country"), + } + + +@pytest.mark.parametrize("method_name", WORKER_METHOD_NAMES) +def test_a_v2_worker_class_method_runs_the_same_code_as_its_plain_function( + monkeypatch, method_name +) -> None: + v2_app = _load_v2_app(monkeypatch) + worker_instance = _worker_class(v2_app, method_name)() + + through_the_class = _call_worker( + monkeypatch, v2_app, getattr(worker_instance, method_name) + ) + through_the_function = _call_worker( + monkeypatch, v2_app, getattr(v2_app, method_name) + ) + + assert through_the_class == through_the_function + assert through_the_class["shutdown_calls"] == 1 + assert len(through_the_class["operations"]) == 1 + if method_name != SEGMENT_WORKER_METHOD: + assert through_the_class["modal_call_id"] == "fc-worker-call" + + +@pytest.mark.parametrize( + "client_version", + # Development builds and release candidates of 1.6.4 come before it. + ["1.4.2", "1.6.3", "1.6.4rc1", "not-a-version"], +) +def test_a_v2_deploy_with_a_modal_client_older_than_1_6_4_is_refused( + monkeypatch, client_version +) -> None: + # Containers restored from a memory snapshot reload Secret values only + # from Modal 1.6.4, and each app runs the client that deployed it. + install_fake_modal(monkeypatch) + monkeypatch.setattr(sys.modules["modal"], "__version__", client_version) + sys.modules.pop("src.modal.v2_images", None) + sys.modules.pop("src.modal.v2_app", None) + + with pytest.raises(RuntimeError, match=r"1\.6\.4") as refused: + importlib.import_module("src.modal.v2_app") + + assert client_version in str(refused.value) + sys.modules.pop("src.modal.v2_images", None) + sys.modules.pop("src.modal.v2_app", None) + + +def test_the_v2_client_check_comes_before_the_cache_manifest_is_read( + monkeypatch, +) -> None: + install_fake_modal(monkeypatch) + monkeypatch.setattr(sys.modules["modal"], "__version__", "1.6.3") + monkeypatch.setenv("STAGE12_CACHE_BUCKET", "cache-bucket") + monkeypatch.setenv("STAGE12_CACHE_MANIFEST_DIGEST", "a" * 64) + manifest_reads: list[str] = [] + + class RecordingCacheStore: + def __init__(self, bucket_name, **_keywords): + manifest_reads.append(bucket_name) + + def read_manifest(self, digest): + manifest_reads.append(digest) + + from policyengine_simulation_executor.stage12_cache import store + + monkeypatch.setattr(store, "Stage12CacheStore", RecordingCacheStore) + sys.modules.pop("src.modal.v2_images", None) + sys.modules.pop("src.modal.v2_app", None) + + with pytest.raises(RuntimeError, match=r"1\.6\.4"): + importlib.import_module("src.modal.v2_app") + + # A refused deploy reads nothing from the cache bucket. + assert manifest_reads == [] + sys.modules.pop("src.modal.v2_images", None) + sys.modules.pop("src.modal.v2_app", None) + + +def test_a_v2_container_imports_the_app_whatever_the_client_version( + monkeypatch, +) -> None: + # Inside a container the client is the one that deployed the app, so the + # check applies only where the app is deployed or run from. + install_fake_modal(monkeypatch) + monkeypatch.setattr(sys.modules["modal"], "__version__", "1.4.2") + monkeypatch.setattr(sys.modules["modal"], "is_local", lambda: False) + sys.modules.pop("src.modal.v2_images", None) + sys.modules.pop("src.modal.v2_app", None) + + v2_app = importlib.import_module("src.modal.v2_app") + + assert v2_app.SimulationWorkerUS is not None + sys.modules.pop("src.modal.v2_images", None) + sys.modules.pop("src.modal.v2_app", None) From 9ef223cbb94a7333067e4024fa703afb298c7fef Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:46:28 +0400 Subject: [PATCH 04/10] Restore the v2 workers from memory snapshots with their country's models 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 --- .../v2-workers-memory-snapshots.changed.md | 1 + .../stage-12-modal-worker-foundation.md | 3 +- .../stage12_simulation_workers.py | 46 ++++ .../economy_workers.py | 71 ++++- .../README.md | 2 +- .../src/modal/country_model_preload.py | 21 +- .../src/modal/v2_app.py | 252 +++++++++++++----- .../src/modal/v2_images.py | 40 ++- .../stage12_runtime/dependencies.py | 33 ++- .../stage12_runtime/fanout.py | 20 +- .../tests/test_stage12_modal_app.py | 2 + 11 files changed, 400 insertions(+), 91 deletions(-) create mode 100644 changelog.d/v2-workers-memory-snapshots.changed.md create mode 100644 libs/policyengine-simulation-contract/src/policyengine_simulation_contract/stage12_simulation_workers.py diff --git a/changelog.d/v2-workers-memory-snapshots.changed.md b/changelog.d/v2-workers-memory-snapshots.changed.md new file mode 100644 index 000000000..3511bfa15 --- /dev/null +++ b/changelog.d/v2-workers-memory-snapshots.changed.md @@ -0,0 +1 @@ +The v2 app's US and UK simulation workers and its US segment worker are now methods of Modal classes, `SimulationWorkerUS`, `SimulationWorkerUK` and `SimulationSegmentWorkerUS`, whose containers restore from memory snapshots with their own country's models already loaded, and for the US the SPM capability too. The report coordinator, the US worker's segment fan-out and the simulation entrypoint start them through the classes; the entrypoint falls back to the plain functions on apps deployed before the classes, and the v2 app keeps those functions, without snapshots, for callers still running older code. Deploying the v2 app now refuses Modal clients older than 1.6.4, as deploying the run_simulation app already did. diff --git a/docs/migration/stage-12-modal-worker-foundation.md b/docs/migration/stage-12-modal-worker-foundation.md index ea48814aa..56cadfd2a 100644 --- a/docs/migration/stage-12-modal-worker-foundation.md +++ b/docs/migration/stage-12-modal-worker-foundation.md @@ -373,7 +373,8 @@ naming the run reads: a row of API v1's `cliff_impacts`, one per calculation. The simulation service inserts it pending when a report's create or re-run asks for cliffs (`include_cliffs`, C1 · 39) and the run has none that hasn't failed, starts the country's simulation worker -(`run_single_simulation_us` or `run_single_simulation_uk`) with the run's own +(`SimulationWorkerUS.run_single_simulation_us` or +`SimulationWorkerUK.run_single_simulation_uk`) with the run's own simulation input, built as a standalone run's, and a context naming the row (`Stage12InvocationContext.cliff_result_id`, left out of a context that names none, which older workers refuse), and records the call. The worker diff --git a/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/stage12_simulation_workers.py b/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/stage12_simulation_workers.py new file mode 100644 index 000000000..a2ba0880a --- /dev/null +++ b/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/stage12_simulation_workers.py @@ -0,0 +1,46 @@ +"""Names of the Modal classes that hold the v2 runtime's simulation workers. + +The v2 application (``src/modal/v2_app.py`` in the executor) defines each +simulation worker as a method of a Modal class, so its containers restore from +a memory snapshot with the country's models already loaded: + +- ``SimulationWorkerUS.run_single_simulation_us`` and + ``SimulationWorkerUK.run_single_simulation_uk`` calculate one simulation. + The report coordinator spawns them for a report's simulations, and the entry + service for standalone simulation runs and cliff calculations. +- ``SimulationSegmentWorkerUS.run_single_simulation_segment_us`` calculates + one region group of a segmented US simulation, in its own container pool. + +Each method has the name the worker had as a plain Modal function. That name +is stored data: the v2 version manifest's ``single_simulation_callable``, the +coordinator's context and the comparison-run rows all hold it. So callers keep +the stored name and look its class up here. + +Apps deployed before the classes define the workers only as plain functions +with these names, and the v2 application keeps those functions for callers +still running older code. +""" + +from __future__ import annotations + +from types import MappingProxyType + +SEGMENT_WORKER_CLASS = "SimulationSegmentWorkerUS" +SEGMENT_WORKER_METHOD = "run_single_simulation_segment_us" + +_WORKER_CLASS_BY_METHOD = MappingProxyType( + { + "run_single_simulation_us": "SimulationWorkerUS", + "run_single_simulation_uk": "SimulationWorkerUK", + SEGMENT_WORKER_METHOD: SEGMENT_WORKER_CLASS, + } +) + + +def worker_class_name(method_name: str) -> str | None: + """Return the Modal class whose method ``method_name`` is, or None. + + None means the v2 application defines ``method_name`` only as a plain + function, as it does its coordinator and household functions. + """ + return _WORKER_CLASS_BY_METHOD.get(method_name) diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_workers.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_workers.py index 1f3d83f86..72ad1e7ad 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_workers.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_workers.py @@ -9,7 +9,9 @@ run's cliff calculation, by the same function in its cliff mode. Each is called by name with ``spawn``, so a route waits only for Modal to accept the call, and is given the run IDs it claims and records, never a Stage 12 evaluation -record. +record. The simulation function is a method of a Modal class, whose +containers restore from a memory snapshot with the models loaded, in apps +deployed since the classes; older apps define it as a plain function. This is the economy path's own Modal access, apart from the Stage 12 comparison path's. @@ -25,6 +27,9 @@ V2ManifestLoader, manifest_digest, ) +from policyengine_simulation_contract.stage12_simulation_workers import ( + worker_class_name, +) from policyengine_simulation_persistence import RunVersions from policyengine_simulation_entry.household_workers import ( @@ -231,9 +236,8 @@ async def start_simulation_run( Raise RuntimeError when Modal returns no call ID. """ - return await self._spawn( + return await self._spawn_simulation_worker( worker, - worker.simulation_callable, simulation_payload, context_payload, observability_context=observability_context, @@ -252,10 +256,52 @@ async def start_cliff_calculation( The context names the cliff calculation, which the function claims and records. Raise RuntimeError when Modal returns no call ID. """ + return await self._spawn_simulation_worker( + worker, + simulation_payload, + context_payload, + observability_context=observability_context, + ) + + async def _spawn_simulation_worker( + self, + worker: EconomyWorker, + payload: dict[str, Any], + context_payload: dict[str, Any], + *, + observability_context: dict[str, Any] | None, + ) -> str: + """Start the simulation worker's method on its class; return its call ID. + + An app deployed before the workers were classes, which the manifest's + default can name after a move or a rollback, has no such class, so it + gets the plain function of the same name. Only the class lookup falls + back: once the class resolves, a failed spawn raises as it is. + """ + class_name = worker_class_name(worker.simulation_callable) + if class_name is not None: + worker_class = modal.Cls.from_name( + worker.application_name, + class_name, + environment_name=self._environment, + ) + try: + await worker_class.hydrate.aio() + except modal.exception.NotFoundError: + pass + else: + method = getattr(worker_class(), worker.simulation_callable) + return await self._spawn_call( + method, + worker.simulation_callable, + payload, + context_payload, + observability_context=observability_context, + ) return await self._spawn( worker, worker.simulation_callable, - simulation_payload, + payload, context_payload, observability_context=observability_context, ) @@ -274,6 +320,23 @@ async def _spawn( function_name, environment_name=self._environment, ) + return await self._spawn_call( + function, + function_name, + payload, + context_payload, + observability_context=observability_context, + ) + + @staticmethod + async def _spawn_call( + function: modal.Function, + function_name: str, + payload: dict[str, Any], + context_payload: dict[str, Any], + *, + observability_context: dict[str, Any] | None, + ) -> str: call = await function.spawn.aio( payload, context_payload, observability_context=observability_context ) diff --git a/projects/policyengine-simulation-executor/README.md b/projects/policyengine-simulation-executor/README.md index 021a72233..d7877091b 100644 --- a/projects/policyengine-simulation-executor/README.md +++ b/projects/policyengine-simulation-executor/README.md @@ -391,7 +391,7 @@ or precompute modules described above. For an eligible US national report, the coordinator starts baseline and reform as separate logical simulations. Each logical simulation starts 20 calls to -`run_single_simulation_segment_us`, then validates and concatenates their +`SimulationSegmentWorkerUS.run_single_simulation_segment_us`, then validates and concatenates their dtype-preserving entity tables. This produces 40 region-group calculation invocations per report while retaining two simulation records and two private simulation artifacts. `segmented=false`, US subnational requests, UK requests, diff --git a/projects/policyengine-simulation-executor/src/modal/country_model_preload.py b/projects/policyengine-simulation-executor/src/modal/country_model_preload.py index ccbbdf299..07908ed8f 100644 --- a/projects/policyengine-simulation-executor/src/modal/country_model_preload.py +++ b/projects/policyengine-simulation-executor/src/modal/country_model_preload.py @@ -1,7 +1,8 @@ """Load the country models before Modal takes the workers' memory snapshot. -``SimulationWorker`` and ``SimulationSegmentWorker`` in ``src/modal/app.py`` -run :func:`preload_country_models` in their ``@modal.enter(snap=True)`` hook. +``SimulationWorker`` and ``SimulationSegmentWorker`` in ``src/modal/app.py``, +and the v2 workers in ``src/modal/v2_app.py``, run +:func:`preload_country_models` in their ``@modal.enter(snap=True)`` hook. Modal runs that hook in every container that isn't restored, and takes the memory snapshot from such a container when it starts it with snapshots enabled. Every container restored from the snapshot starts with the hook's @@ -9,7 +10,7 @@ - the country packages, whose import builds each country's tax-benefit system; -- policyengine.py's model objects for both countries, whose import also reads +- policyengine.py's model objects for each country, whose import also reads the data release manifest from Hugging Face over one HTTPS request that closes when it returns; - the certified SPM capability and its forecast, which the first US call @@ -21,6 +22,7 @@ """ import logging +from collections.abc import Iterable from importlib import import_module from policyengine_simulation_contract.spm import SPMInputError @@ -33,8 +35,12 @@ } -def preload_country_models() -> None: - """Import each country's models, then fill the SPM capability cache. +def preload_country_models(countries: Iterable[str] = ("us", "uk")) -> None: + """Import each of ``countries``' models, then fill the SPM capability cache. + + The run_simulation app's workers load both countries. Each of the v2 + app's workers loads only its image's country, and only the US workers + fill the SPM cache, since SPM is a US measure. Nothing here may stop a container from starting: a failure leaves that work to the calls that need it, as before the preload. A country whose @@ -44,7 +50,10 @@ def preload_country_models() -> None: SPM check caches only a successful result, so each call that needs SPM repeats a failed check. """ + countries = tuple(countries) for country, module_names in COUNTRY_MODEL_MODULES.items(): + if country not in countries: + continue for module_name in module_names: try: import_module(module_name) @@ -58,6 +67,8 @@ def preload_country_models() -> None: exc_info=True, ) break + if "us" not in countries: + return from policyengine_simulation_executor import spm try: diff --git a/projects/policyengine-simulation-executor/src/modal/v2_app.py b/projects/policyengine-simulation-executor/src/modal/v2_app.py index d3505d4fc..af70aa509 100644 --- a/projects/policyengine-simulation-executor/src/modal/v2_app.py +++ b/projects/policyengine-simulation-executor/src/modal/v2_app.py @@ -2,8 +2,12 @@ """Separately named v2 Modal application: report coordinator and country workers. A simulation worker's call calculates a simulation run, or, when its context -names a cliff result, that run's cliff gap and share. Besides the Stage 12 -report coordinator and simulation workers, it defines a +names a cliff result, that run's cliff gap and share. The simulation workers +are methods of Modal classes (``SimulationWorkerUS``, ``SimulationWorkerUK`` +and ``SimulationSegmentWorkerUS``), whose containers restore from a memory +snapshot with their country's models loaded; their callers find each class +in ``policyengine_simulation_contract.stage12_simulation_workers``. Besides +the Stage 12 report coordinator and simulation workers, it defines a household function for each country, ``calculate_household_us`` and ``calculate_household_uk``, in an image without datasets. A call calculates one household under one policy, and records it on the household job it @@ -20,7 +24,8 @@ from __future__ import annotations import os -from typing import TYPE_CHECKING +import random +from typing import TYPE_CHECKING, Any, ClassVar from uuid import UUID from policyengine_simulation_contract.household_execution import ( @@ -28,10 +33,6 @@ ) from policyengine_simulation_contract.stage12_manifest import v2_application_name from policyengine_simulation_executor import stage12_runtime -from policyengine_simulation_executor.stage12_bundle import ( - assert_expected_bundle_values, - assertion_values, -) from policyengine_simulation_executor.stage12_runtime import report_run_access from policyengine_simulation_executor.stage12_runtime.report_run_access import ( MODAL_WORKER_DATABASE_SECRET_NAME, @@ -57,7 +58,9 @@ from policyengine_simulation_observability.telemetry import ( normalize_observability_context, ) +from src.modal.country_model_preload import preload_country_models from src.modal.v2_images import ( + BUNDLE_VALUES, RESOLVED_BUNDLE, STAGE12_CACHE_BUCKET, STAGE12_CACHE_CONTENTS, @@ -94,6 +97,7 @@ # src/modal/v2_images.py; this module keeps their names for the smoke apps and # other code that imports them from here. __all__ = [ + "BUNDLE_VALUES", "RESOLVED_BUNDLE", "STAGE12_CACHE_BUCKET", "STAGE12_CACHE_CONTENTS", @@ -109,29 +113,9 @@ "us_worker_image", ] -BUNDLE_VALUES = assertion_values(RESOLVED_BUNDLE.bundle) APP_NAME = v2_application_name(RESOLVED_BUNDLE.bundle.policyengine_version) -def _external_assertions(environment: dict[str, str]) -> dict[str, str]: - mapping = { - "STAGE12_EXPECT_POLICYENGINE_VERSION": "policyengine_version", - "STAGE12_EXPECT_US_VERSION": "countries.us.country_package_version", - "STAGE12_EXPECT_UK_VERSION": "countries.uk.country_package_version", - "STAGE12_EXPECT_US_DATASET": "countries.us.default_dataset", - "STAGE12_EXPECT_UK_DATASET": "countries.uk.default_dataset", - } - return { - assertion: environment[name] - for name, assertion in mapping.items() - if environment.get(name) - } - - -assert_expected_bundle_values( - RESOLVED_BUNDLE.bundle, - _external_assertions(dict(os.environ)), -) if os.environ.get("MODAL_APP_NAME") not in {None, "", APP_NAME}: msg = "MODAL_APP_NAME does not match the bundle-derived v2 name" raise RuntimeError(msg) @@ -194,18 +178,44 @@ def validate_worker_uk() -> dict: return _validate("uk") -@app.function( - image=us_worker_image, - cpu=8.0, - memory=32768, - timeout=3600, - retries=0, +# Each simulation worker is a method of a Modal class whose containers restore +# from a memory snapshot with the country's models loaded, and a plain function +# of the same name and options, without a snapshot, for callers still running +# code from before the classes: an entry service revision (the stable one +# during a deploy, or one a rollback routes traffic back to), and a coordinator +# or US worker call running while this app is redeployed in place. Both run the +# same calculation. +_SEGMENT_WORKER_OPTIONS: dict[str, Any] = { + "image": us_worker_image, + "cpu": 8.0, + "memory": 32768, + "timeout": 3600, + "retries": 0, # Every segment of every US simulation call that may run at once: a # segment queued behind this limit counts against its caller's wait. - max_containers=1000, - secrets=worker_secrets, -) -def run_single_simulation_segment_us( + "max_containers": 1000, + "secrets": worker_secrets, +} +_US_SIMULATION_WORKER_OPTIONS: dict[str, Any] = { + "image": us_worker_image, + "cpu": 8.0, + "memory": 32768, + "timeout": US_SIMULATION_TIMEOUT_SECONDS, + "retries": 0, + # Both simulations of every coordinator call that may run at once. The + # simulation runs and cliff calculations the simulation service starts + # directly share the same containers. + "max_containers": 50, + "secrets": report_run_writer_secrets, +} +_UK_SIMULATION_WORKER_OPTIONS: dict[str, Any] = { + **_US_SIMULATION_WORKER_OPTIONS, + "image": uk_worker_image, + "timeout": UK_SIMULATION_TIMEOUT_SECONDS, +} + + +def _run_single_simulation_segment_us( payload: dict, *, observability_context: dict | None = None, @@ -246,19 +256,7 @@ def run_single_simulation_segment_us( runtime.shutdown() -@app.function( - image=us_worker_image, - cpu=8.0, - memory=32768, - timeout=US_SIMULATION_TIMEOUT_SECONDS, - retries=0, - # Both simulations of every coordinator call that may run at once. The - # simulation runs and cliff calculations the simulation service starts - # directly share the same containers. - max_containers=50, - secrets=report_run_writer_secrets, -) -def run_single_simulation_us( +def _run_single_simulation_us( payload: dict, context: dict, *, @@ -323,19 +321,7 @@ def segmented_calculator( runtime.shutdown() -@app.function( - image=uk_worker_image, - cpu=8.0, - memory=32768, - timeout=UK_SIMULATION_TIMEOUT_SECONDS, - retries=0, - # Both simulations of every coordinator call that may run at once. The - # simulation runs and cliff calculations the simulation service starts - # directly share the same containers. - max_containers=50, - secrets=report_run_writer_secrets, -) -def run_single_simulation_uk( +def _run_single_simulation_uk( payload: dict, context: dict, *, @@ -382,6 +368,146 @@ def run_single_simulation_uk( runtime.shutdown() +class _V2CountryModelsLoadedBeforeSnapshot: + """Base of the v2 simulation workers: loads the models before the snapshot. + + Modal runs ``snap=True`` hooks in every container that isn't restored, and + takes the memory snapshot from such a container when it starts it with + snapshots enabled; every container restored from the snapshot starts with + the loaded models in memory. ``snap=False`` hooks run after each restore. + Observability is configured per call instead, after the restore, so each + restored container reports its own process identity. + """ + + # The image's own country: a failed import of one country's models can't + # affect the other country's workers. + snapshot_countries: ClassVar[tuple[CountryId, ...]] = () + + @modal.enter(snap=True) + def load_country_models(self) -> None: + """Load the class's country models, and for the US the SPM capability.""" + preload_country_models(self.snapshot_countries) + + @modal.enter(snap=False) + def reseed_random_after_restore(self) -> None: + """Give each restored container its own random sequence. + + The snapshot holds the state of Python's ``random`` module, and Python + reseeds it only after a fork, so every restored container would draw + the same numbers: OpenTelemetry's span IDs, for one, and the delays of + the database and dataset download retries. + """ + random.seed() + + +@app.cls(**_SEGMENT_WORKER_OPTIONS, enable_memory_snapshot=True) +class SimulationSegmentWorkerUS(_V2CountryModelsLoadedBeforeSnapshot): + """Calculates the region-group segments of segmented US simulations. + + A separate class from ``SimulationWorkerUS``, so the segments draw from + their own container pool: a US simulation waiting on its segments must + never share a bounded pool with them. + """ + + snapshot_countries = ("us",) + + @modal.method() + def run_single_simulation_segment_us( + self, + payload: dict, + *, + observability_context: dict | None = None, + simulation_run_id: str | None = None, + ) -> dict: + """Calculate one segment (see ``_run_single_simulation_segment_us``).""" + return _run_single_simulation_segment_us( + payload, + observability_context=observability_context, + simulation_run_id=simulation_run_id, + ) + + +@app.cls(**_US_SIMULATION_WORKER_OPTIONS, enable_memory_snapshot=True) +class SimulationWorkerUS(_V2CountryModelsLoadedBeforeSnapshot): + """Calculates US simulations, cliff calculations included.""" + + snapshot_countries = ("us",) + + @modal.method() + def run_single_simulation_us( + self, + payload: dict, + context: dict, + *, + observability_context: dict | None = None, + ) -> dict: + """Calculate one US simulation (see ``_run_single_simulation_us``).""" + return _run_single_simulation_us( + payload, context, observability_context=observability_context + ) + + +@app.cls(**_UK_SIMULATION_WORKER_OPTIONS, enable_memory_snapshot=True) +class SimulationWorkerUK(_V2CountryModelsLoadedBeforeSnapshot): + """Calculates UK simulations, cliff calculations included.""" + + snapshot_countries = ("uk",) + + @modal.method() + def run_single_simulation_uk( + self, + payload: dict, + context: dict, + *, + observability_context: dict | None = None, + ) -> dict: + """Calculate one UK simulation (see ``_run_single_simulation_uk``).""" + return _run_single_simulation_uk( + payload, context, observability_context=observability_context + ) + + +@app.function(**_SEGMENT_WORKER_OPTIONS) +def run_single_simulation_segment_us( + payload: dict, + *, + observability_context: dict | None = None, + simulation_run_id: str | None = None, +) -> dict: + """``SimulationSegmentWorkerUS``'s method, for callers on older code.""" + return _run_single_simulation_segment_us( + payload, + observability_context=observability_context, + simulation_run_id=simulation_run_id, + ) + + +@app.function(**_US_SIMULATION_WORKER_OPTIONS) +def run_single_simulation_us( + payload: dict, + context: dict, + *, + observability_context: dict | None = None, +) -> dict: + """``SimulationWorkerUS``'s method, for callers on older code.""" + return _run_single_simulation_us( + payload, context, observability_context=observability_context + ) + + +@app.function(**_UK_SIMULATION_WORKER_OPTIONS) +def run_single_simulation_uk( + payload: dict, + context: dict, + *, + observability_context: dict | None = None, +) -> dict: + """``SimulationWorkerUK``'s method, for callers on older code.""" + return _run_single_simulation_uk( + payload, context, observability_context=observability_context + ) + + @app.function( image=coordinator_image, cpu=2.0, diff --git a/projects/policyengine-simulation-executor/src/modal/v2_images.py b/projects/policyengine-simulation-executor/src/modal/v2_images.py index ac1e3d96c..5628cfd12 100644 --- a/projects/policyengine-simulation-executor/src/modal/v2_images.py +++ b/projects/policyengine-simulation-executor/src/modal/v2_images.py @@ -5,8 +5,9 @@ certified data for their countries; the US worker image also holds the published US cache, read from the cache manifest the deploy names (``_deploy_time_cache_inputs``). The household image holds packages and -source only. ``src/modal/v2_app.py`` attaches the images to its functions and -re-exports every name here. +source only. The bundle values the deploy expects (``STAGE12_EXPECT_*``) are +checked here too, before any image is declared. ``src/modal/v2_app.py`` +attaches the images to its functions and re-exports every name here. """ from __future__ import annotations @@ -20,7 +21,11 @@ HF_MODAL_SECRET_NAME, HF_RUNTIME_ENV_NAME, ) -from policyengine_simulation_executor.stage12_bundle import load_stage12_bundle +from policyengine_simulation_executor.stage12_bundle import ( + assert_expected_bundle_values, + assertion_values, + load_stage12_bundle, +) from policyengine_simulation_executor.stage12_cache.models import CacheManifest from policyengine_simulation_executor.stage12_cache.store import Stage12CacheStore from policyengine_simulation_observability.observability import ( @@ -28,6 +33,7 @@ ) from src.modal.bundle_data import bundle_data_install_command from src.modal.ca_certificates import GRPC_CA_BUNDLE_ENV, OPERATING_SYSTEM_CA_PACKAGE +from src.modal.modal_client_version import require_secret_reloading_modal_client from src.modal.stage12_cache_image import fetch_stage12_cache from src.modal.static_runtime_files import add_static_runtime_files @@ -39,9 +45,16 @@ Stage12CountryBundle, ) +# The v2 simulation workers restore from memory snapshots, so a deploy from a +# Modal client that keeps stale Secret values on restore is refused here, +# before the cache manifest is read. +if modal.is_local(): + require_secret_reloading_modal_client(modal.__version__) + STAGE12_DATA_DIR = "/opt/policyengine/stage12-data" _UV_PROJECT_DIR = str(Path(__file__).resolve().parents[2]) if modal.is_local() else "." RESOLVED_BUNDLE = load_stage12_bundle() +BUNDLE_VALUES = assertion_values(RESOLVED_BUNDLE.bundle) def _deploy_time_cache_inputs() -> tuple[str, dict | None, dict | None]: @@ -78,6 +91,27 @@ def _deploy_time_cache_inputs() -> tuple[str, dict | None, dict | None]: ) +def _external_assertions(environment: dict[str, str]) -> dict[str, str]: + mapping = { + "STAGE12_EXPECT_POLICYENGINE_VERSION": "policyengine_version", + "STAGE12_EXPECT_US_VERSION": "countries.us.country_package_version", + "STAGE12_EXPECT_UK_VERSION": "countries.uk.country_package_version", + "STAGE12_EXPECT_US_DATASET": "countries.us.default_dataset", + "STAGE12_EXPECT_UK_DATASET": "countries.uk.default_dataset", + } + return { + assertion: environment[name] + for name, assertion in mapping.items() + if environment.get(name) + } + + +assert_expected_bundle_values( + RESOLVED_BUNDLE.bundle, + _external_assertions(dict(os.environ)), +) + + gcp_secret = modal.Secret.from_name("stage12-evaluation-gcp-credentials") hf_secret = modal.Secret.from_name( HF_MODAL_SECRET_NAME, diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/dependencies.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/dependencies.py index dc0ee0773..d56ade776 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/dependencies.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/dependencies.py @@ -8,6 +8,9 @@ from importlib import import_module from typing import TYPE_CHECKING, Any, Protocol +from policyengine_simulation_contract.stage12_simulation_workers import ( + worker_class_name, +) from policyengine_stage12_persistence import Stage12PersistenceStore from policyengine_simulation_executor.stage12_artifacts import ( @@ -142,16 +145,32 @@ def restore(self, invocation_id: str) -> ChildCall: class ModalChildInvoker: - """``ChildInvoker`` backed by functions deployed to Modal.""" + """``ChildInvoker`` backed by the workers deployed to Modal.""" def spawn(self, request: ChildSpawnRequest) -> ChildCall: - """Look up ``application_name.function_name`` in ``environment``; spawn it.""" + """Look up ``function_name`` in ``application_name`` and spawn it. + + A simulation worker is a method of a Modal class, whose containers + restore from a memory snapshot with the models loaded; the name + stored in the context is the method's. The coordinator spawns only in + its own application, which defines the class. Any other name is + looked up as a plain function. + """ modal: Any = import_module("modal") - function = modal.Function.from_name( - request.application_name, - request.function_name, - environment_name=request.environment, - ) + class_name = worker_class_name(request.function_name) + if class_name is None: + function = modal.Function.from_name( + request.application_name, + request.function_name, + environment_name=request.environment, + ) + else: + worker = modal.Cls.from_name( + request.application_name, + class_name, + environment_name=request.environment, + )() + function = getattr(worker, request.function_name) return function.spawn( request.simulation, request.context, diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/fanout.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/fanout.py index 38162d3d8..5df70f8f3 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/fanout.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/fanout.py @@ -8,6 +8,10 @@ from typing import TYPE_CHECKING, Any import modal +from policyengine_simulation_contract.stage12_simulation_workers import ( + SEGMENT_WORKER_CLASS, + SEGMENT_WORKER_METHOD, +) from policyengine_simulation_observability.stages import ( STAGE12_SIMULATION_STAGES, Stage, @@ -34,7 +38,6 @@ logger = logging.getLogger(__name__) -SEGMENT_FUNCTION_NAME = "run_single_simulation_segment_us" POLL_INTERVAL_INITIAL_SECONDS = 0.5 POLL_INTERVAL_MAX_SECONDS = 8.0 POLL_INTERVAL_BACKOFF_FACTOR = 2.0 @@ -51,7 +54,7 @@ def _next_backoff(current: float, *, maximum: float) -> float: class SegmentRunnerSeams: """What the segment runner looks up and how it waits; defaults are deployed. - ``modal_module`` looks up the segment function, ``groups`` replaces the + ``modal_module`` looks up the segment worker class, ``groups`` replaces the region groups read from the installed model, and polls start ``poll_interval_seconds`` apart and back off to ``poll_interval_max_seconds``, waiting with ``sleep``. @@ -77,7 +80,10 @@ def __init__( # noqa: PLR0913 # the simulation, then keyword-only app, runtime simulation_run_id: UUID | None = None, seams: SegmentRunnerSeams | None = None, ) -> None: - """Look up the segment function deployed in ``app_name``. + """Look up the segment worker class deployed in ``app_name``. + + Its containers restore from a memory snapshot with the US models + loaded, so each segment starts without loading them. ``cancellation_requested`` is checked between polls. Each segment's call is passed ``simulation_run_id``, the detailed-save simulation run @@ -96,10 +102,10 @@ def __init__( # noqa: PLR0913 # the simulation, then keyword-only app, runtime if seams.groups is not None else None ) - self.child_function = seams.modal_module.Function.from_name( - app_name, - SEGMENT_FUNCTION_NAME, - ) + segment_worker = seams.modal_module.Cls.from_name( + app_name, SEGMENT_WORKER_CLASS + )() + self.child_function = getattr(segment_worker, SEGMENT_WORKER_METHOD) def _groups(self) -> list[list[str]]: if self.groups is not None: diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_modal_app.py b/projects/policyengine-simulation-executor/tests/test_stage12_modal_app.py index 9a2ffa850..037932a9c 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_modal_app.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_modal_app.py @@ -924,6 +924,8 @@ def preempted(*_, **__): def test_external_package_values_are_assertions_only(monkeypatch) -> None: install_fake_modal(monkeypatch) monkeypatch.setenv("STAGE12_EXPECT_US_VERSION", "not-the-bundled-version") + # src/modal/v2_images.py checks them, next to the bundle it resolves. + sys.modules.pop("src.modal.v2_images", None) sys.modules.pop("src.modal.v2_app", None) with pytest.raises(ValueError, match="does not match"): From 23af84b1e2a869c97931fa801f13a2980c39fe20 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:04:39 +0400 Subject: [PATCH 05/10] Test that the coordinator and segment fan-out reach an app rolled back 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 --- .../tests/test_stage12_child_state_errors.py | 11 ++- .../tests/test_stage12_coordination.py | 62 ++++++++++++-- .../tests/test_stage12_segment_fanout.py | 81 ++++++++++++++++--- 3 files changed, 134 insertions(+), 20 deletions(-) diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_child_state_errors.py b/projects/policyengine-simulation-executor/tests/test_stage12_child_state_errors.py index a01b5be2f..0122fdf4c 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_child_state_errors.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_child_state_errors.py @@ -341,12 +341,17 @@ def spawn(self, payload, *, observability_context): ), ) + class SegmentWorkerClass: + def hydrate(self): + return self + + def __call__(self): + return SimpleNamespace(run_single_simulation_segment_us=SegmentFunction()) + class SegmentWorkerLookup: @staticmethod def from_name(_app_name, _class_name): - return lambda: SimpleNamespace( - run_single_simulation_segment_us=SegmentFunction() - ) + return SegmentWorkerClass() def segmented_calculator(value, cancellation_requested): return Stage12SegmentRunner( diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_coordination.py b/projects/policyengine-simulation-executor/tests/test_stage12_coordination.py index e90f3cb43..7fc9ae456 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_coordination.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_coordination.py @@ -527,8 +527,16 @@ def aggregate(**values): assert child.simulation_callable == "run_single_simulation_us" -def _recording_modal(calls: list) -> object: - """Stand in for ``modal``, recording each lookup, spawn and restore in ``calls``.""" +class _ClassNotDeployedError(Exception): + """Stands in for ``modal.exception.NotFoundError``.""" + + +def _recording_modal(calls: list, *, class_deployed: bool = True) -> object: + """Stand in for ``modal``, recording each lookup, spawn and restore in ``calls``. + + With ``class_deployed`` False, hydrating a class raises the not-found + error, as for an app rolled back to a commit from before the classes. + """ from types import SimpleNamespace def spawn(*spawn_args, **spawn_kwargs): @@ -539,11 +547,22 @@ def function_from_name(*args, **kwargs): calls.append(("Function.from_name", args, kwargs)) return SimpleNamespace(spawn=spawn) + class WorkerClass: + def hydrate(self): + calls.append(("Cls.hydrate", (), {})) + if not class_deployed: + msg = "the app defines no such class" + raise _ClassNotDeployedError(msg) + return self + + def __call__(self): + return SimpleNamespace( + run_single_simulation_us=SimpleNamespace(spawn=spawn) + ) + def class_from_name(*args, **kwargs): calls.append(("Cls.from_name", args, kwargs)) - return lambda: SimpleNamespace( - run_single_simulation_us=SimpleNamespace(spawn=spawn) - ) + return WorkerClass() def from_id(invocation_id): calls.append(("FunctionCall.from_id", (invocation_id,), {})) @@ -553,6 +572,7 @@ def from_id(invocation_id): Cls=SimpleNamespace(from_name=class_from_name), Function=SimpleNamespace(from_name=function_from_name), FunctionCall=SimpleNamespace(from_id=from_id), + exception=SimpleNamespace(NotFoundError=_ClassNotDeployedError), ) @@ -594,6 +614,7 @@ def import_modal(module_name): ("application", "SimulationWorkerUS"), {"environment_name": "staging"}, ), + ("Cls.hydrate", (), {}), ( "spawn", ({"role": "baseline"}, {"request_id": "request-1"}), @@ -603,6 +624,37 @@ def import_modal(module_name): ] +def test_modal_child_invoker_spawns_the_function_when_the_app_has_no_worker_class( + monkeypatch, +): + from policyengine_simulation_executor.stage12_runtime import dependencies + + calls = [] + fake_modal = _recording_modal(calls, class_deployed=False) + monkeypatch.setattr(dependencies, "import_module", lambda _name: fake_modal) + + spawned = dependencies.ModalChildInvoker().spawn( + _spawn_request(dependencies, "run_single_simulation_us") + ) + + # A coordinator call still running when its app is rolled back in place, + # to a commit from before the classes, finds only the plain function. + assert spawned == "spawned-call" + assert calls[1:] == [ + ("Cls.hydrate", (), {}), + ( + "Function.from_name", + ("application", "run_single_simulation_us"), + {"environment_name": "staging"}, + ), + ( + "spawn", + ({"role": "baseline"}, {"request_id": "request-1"}), + {"observability_context": {"traceparent": "trace"}}, + ), + ] + + def test_modal_child_invoker_spawns_a_callable_without_a_class_as_a_function( monkeypatch, ): diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_segment_fanout.py b/projects/policyengine-simulation-executor/tests/test_stage12_segment_fanout.py index f722d39cb..cd897c79a 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_segment_fanout.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_segment_fanout.py @@ -111,25 +111,54 @@ def _results(simulation) -> list[dict]: ] +class ClassNotDeployedError(Exception): + """Stands in for ``modal.exception.NotFoundError``.""" + + def _segment_worker_lookup( segment_function: object, - class_lookups: list[tuple[str, str]] | None = None, + lookups: list[tuple[str, str, str]] | None = None, + *, + class_deployed: bool = True, ) -> SimpleNamespace: - """Stand in for ``modal``: its segment worker class spawns ``segment_function``. + """Stand in for ``modal``: its segment worker spawns ``segment_function``. - Each lookup of a class by name is appended to ``class_lookups``. + Each lookup by name is appended to ``lookups`` as ``(kind, app, name)``. + With ``class_deployed`` False, hydrating the class raises the not-found + error, and the plain function of the method's name spawns instead. """ + def record(kind: str, app_name: str, name: str) -> None: + if lookups is not None: + lookups.append((kind, app_name, name)) + + class SegmentWorkerClass: + def hydrate(self): + if not class_deployed: + msg = "the app defines no such class" + raise ClassNotDeployedError(msg) + return self + + def __call__(self): + return SimpleNamespace(run_single_simulation_segment_us=segment_function) + class ClassLookup: @staticmethod def from_name(app_name, class_name): - if class_lookups is not None: - class_lookups.append((app_name, class_name)) - return lambda: SimpleNamespace( - run_single_simulation_segment_us=segment_function - ) + record("class", app_name, class_name) + return SegmentWorkerClass() - return SimpleNamespace(Cls=ClassLookup) + class FunctionLookup: + @staticmethod + def from_name(app_name, function_name): + record("function", app_name, function_name) + return segment_function + + return SimpleNamespace( + Cls=ClassLookup, + Function=FunctionLookup, + exception=SimpleNamespace(NotFoundError=ClassNotDeployedError), + ) def test_segments_are_started_through_the_segment_worker_class() -> None: @@ -137,13 +166,13 @@ def test_segments_are_started_through_the_segment_worker_class() -> None: # models loaded. simulation = planned_simulation(SimulationRole.BASELINE) function = FakeFunction(_results(simulation), {}) - class_lookups: list[tuple[str, str]] = [] + lookups: list[tuple[str, str, str]] = [] runner = Stage12SegmentRunner( simulation, app_name="stage12-app", runtime=cast("ObservabilityRuntime", FakeRuntime()), seams=SegmentRunnerSeams( - modal_module=_segment_worker_lookup(function, class_lookups), + modal_module=_segment_worker_lookup(function, lookups), groups=US_REGION_GROUPS, sleep=lambda _seconds: None, ), @@ -151,7 +180,35 @@ def test_segments_are_started_through_the_segment_worker_class() -> None: runner.run() - assert class_lookups == [("stage12-app", "SimulationSegmentWorkerUS")] + assert lookups == [("class", "stage12-app", "SimulationSegmentWorkerUS")] + assert len(function.spawns) == len(US_REGION_GROUPS) + + +def test_segments_start_on_the_function_when_the_app_has_no_segment_class() -> None: + # A US simulation still running when its app is rolled back in place, to a + # commit from before the classes, finds only the plain function. + simulation = planned_simulation(SimulationRole.BASELINE) + function = FakeFunction(_results(simulation), {}) + lookups: list[tuple[str, str, str]] = [] + runner = Stage12SegmentRunner( + simulation, + app_name="stage12-app", + runtime=cast("ObservabilityRuntime", FakeRuntime()), + seams=SegmentRunnerSeams( + modal_module=_segment_worker_lookup( + function, lookups, class_deployed=False + ), + groups=US_REGION_GROUPS, + sleep=lambda _seconds: None, + ), + ) + + runner.run() + + assert lookups == [ + ("class", "stage12-app", "SimulationSegmentWorkerUS"), + ("function", "stage12-app", "run_single_simulation_segment_us"), + ] assert len(function.spawns) == len(US_REGION_GROUPS) From d049fe70e399acd32d833eb88f85734f4b374e1d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:05:31 +0400 Subject: [PATCH 06/10] Fall back to the plain worker function on an app rolled back in place 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 --- .../stage12_runtime/dependencies.py | 32 ++++--------- .../stage12_runtime/fanout.py | 15 +++--- .../stage12_runtime/worker_lookup.py | 46 +++++++++++++++++++ 3 files changed, 62 insertions(+), 31 deletions(-) create mode 100644 projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/worker_lookup.py diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/dependencies.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/dependencies.py index d56ade776..440a93f0c 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/dependencies.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/dependencies.py @@ -8,9 +8,6 @@ from importlib import import_module from typing import TYPE_CHECKING, Any, Protocol -from policyengine_simulation_contract.stage12_simulation_workers import ( - worker_class_name, -) from policyengine_stage12_persistence import Stage12PersistenceStore from policyengine_simulation_executor.stage12_artifacts import ( @@ -19,6 +16,7 @@ ) from .database_retry import open_session_with_retry +from .worker_lookup import deployed_worker if TYPE_CHECKING: from datetime import datetime @@ -150,27 +148,15 @@ class ModalChildInvoker: def spawn(self, request: ChildSpawnRequest) -> ChildCall: """Look up ``function_name`` in ``application_name`` and spawn it. - A simulation worker is a method of a Modal class, whose containers - restore from a memory snapshot with the models loaded; the name - stored in the context is the method's. The coordinator spawns only in - its own application, which defines the class. Any other name is - looked up as a plain function. + A simulation worker is a method of a Modal class, and the name stored + in the context is the method's (``deployed_worker``). """ - modal: Any = import_module("modal") - class_name = worker_class_name(request.function_name) - if class_name is None: - function = modal.Function.from_name( - request.application_name, - request.function_name, - environment_name=request.environment, - ) - else: - worker = modal.Cls.from_name( - request.application_name, - class_name, - environment_name=request.environment, - )() - function = getattr(worker, request.function_name) + function = deployed_worker( + import_module("modal"), + request.application_name, + request.function_name, + environment_name=request.environment, + ) return function.spawn( request.simulation, request.context, diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/fanout.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/fanout.py index 5df70f8f3..4b6203053 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/fanout.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/fanout.py @@ -9,7 +9,6 @@ import modal from policyengine_simulation_contract.stage12_simulation_workers import ( - SEGMENT_WORKER_CLASS, SEGMENT_WORKER_METHOD, ) from policyengine_simulation_observability.stages import ( @@ -23,6 +22,7 @@ from .failures import Stage12CancellationError, Stage12ExecutionError from .partition import stage12_region_groups_for_model from .segmentation import build_segment_inputs, merge_segment_results +from .worker_lookup import deployed_worker if TYPE_CHECKING: from collections.abc import Callable, Sequence @@ -80,10 +80,10 @@ def __init__( # noqa: PLR0913 # the simulation, then keyword-only app, runtime simulation_run_id: UUID | None = None, seams: SegmentRunnerSeams | None = None, ) -> None: - """Look up the segment worker class deployed in ``app_name``. + """Look up the segment worker deployed in ``app_name``. - Its containers restore from a memory snapshot with the US models - loaded, so each segment starts without loading them. + It is a method of a Modal class whose containers restore from a + memory snapshot with the US models loaded (``deployed_worker``). ``cancellation_requested`` is checked between polls. Each segment's call is passed ``simulation_run_id``, the detailed-save simulation run @@ -102,10 +102,9 @@ def __init__( # noqa: PLR0913 # the simulation, then keyword-only app, runtime if seams.groups is not None else None ) - segment_worker = seams.modal_module.Cls.from_name( - app_name, SEGMENT_WORKER_CLASS - )() - self.child_function = getattr(segment_worker, SEGMENT_WORKER_METHOD) + self.child_function = deployed_worker( + seams.modal_module, app_name, SEGMENT_WORKER_METHOD + ) def _groups(self) -> list[list[str]]: if self.groups is not None: diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/worker_lookup.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/worker_lookup.py new file mode 100644 index 000000000..04734aa3a --- /dev/null +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/worker_lookup.py @@ -0,0 +1,46 @@ +"""Find a v2 simulation worker in a deployed application, by its method's name.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from policyengine_simulation_contract.stage12_simulation_workers import ( + worker_class_name, +) + +if TYPE_CHECKING: + from types import ModuleType + + +def deployed_worker( + modal_module: ModuleType, + application_name: str, + method_name: str, + **lookup_options: str, +) -> Any: # noqa: ANN401 # a modal.Function or a Modal class's method, both untyped here + """Return what spawns ``method_name`` in ``application_name``. + + A simulation worker is a method of a Modal class, whose containers restore + from a memory snapshot with the models loaded. An application deployed + from a commit from before the classes defines it as a plain function of + the same name, and a call still running when its application is rolled + back in place to such a commit finds only that function. So a class Modal + doesn't find gives the function. Only the class lookup falls back: once + the class resolves, a failed spawn raises as it is. A name with no class + is looked up as a function. ``lookup_options``, such as + ``environment_name``, go to either lookup. + """ + class_name = worker_class_name(method_name) + if class_name is not None: + worker_class = modal_module.Cls.from_name( + application_name, class_name, **lookup_options + ) + try: + worker_class.hydrate() + except modal_module.exception.NotFoundError: + pass + else: + return getattr(worker_class(), method_name) + return modal_module.Function.from_name( + application_name, method_name, **lookup_options + ) From adff2347a267da9c16cf151f21262f3b2bc13e0d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:06:55 +0400 Subject: [PATCH 07/10] Tighten three tests review round 1 found too loose - 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 --- .../tests/test_economy_workers.py | 22 ++++++++---- .../tests/test_stage12_wait_window.py | 22 ++++++++---- .../tests/test_v2_worker_classes.py | 36 +++++++++++++++++++ 3 files changed, 66 insertions(+), 14 deletions(-) diff --git a/projects/policyengine-simulation-entry/tests/test_economy_workers.py b/projects/policyengine-simulation-entry/tests/test_economy_workers.py index 88042a284..198d415e8 100644 --- a/projects/policyengine-simulation-entry/tests/test_economy_workers.py +++ b/projects/policyengine-simulation-entry/tests/test_economy_workers.py @@ -132,15 +132,24 @@ def from_name(application: str, name: str, *, environment_name: str): return looked_up, function +# Each worker class defines only its own country's method. +WORKER_METHOD_BY_CLASS = { + "SimulationWorkerUS": "run_single_simulation_us", + "SimulationWorkerUK": "run_single_simulation_uk", +} + + class FakeWorkerClass: - """A Modal class looked up by name, whose worker methods spawn ``method``. + """A Modal class looked up by name, whose worker method spawns ``method``. - With ``deployed`` False, hydrating it fails as it does for an app deployed - before the workers were classes. + The instance has only the looked-up class's method, under its name + (``method_name``). With ``deployed`` False, hydrating it fails as it does + for an app deployed before the workers were classes. """ def __init__(self, method: FakeFunction) -> None: self.method = method + self.method_name: str | None = None self.deployed = True self.hydrate = SimpleNamespace(aio=self._hydrate) @@ -151,10 +160,8 @@ async def _hydrate(self) -> FakeWorkerClass: return self def __call__(self) -> SimpleNamespace: - return SimpleNamespace( - run_single_simulation_us=self.method, - run_single_simulation_uk=self.method, - ) + assert self.method_name is not None + return SimpleNamespace(**{self.method_name: self.method}) @pytest.fixture @@ -165,6 +172,7 @@ def modal_worker_classes(monkeypatch): def from_name(application: str, name: str, *, environment_name: str): looked_up.append((application, name, environment_name)) + worker_class.method_name = WORKER_METHOD_BY_CLASS[name] return worker_class monkeypatch.setattr(economy_workers.modal.Cls, "from_name", staticmethod(from_name)) diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_wait_window.py b/projects/policyengine-simulation-executor/tests/test_stage12_wait_window.py index 646e63fcb..679cfc54d 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_wait_window.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_wait_window.py @@ -7,6 +7,9 @@ import pytest from fixtures.fake_modal import install_fake_modal +from policyengine_simulation_contract.stage12_simulation_workers import ( + worker_class_name, +) from policyengine_simulation_executor.stage12_runtime import ( coordination as coordination_module, ) @@ -40,8 +43,11 @@ def _declared_modal_timeouts(monkeypatch): sys.modules.pop("src.modal.v2_images", None) sys.modules.pop("src.modal.v2_app", None) modal_app = importlib.import_module("src.modal.v2_app") + # The coordinator spawns the simulation workers' class methods; callers + # on older code spawn the plain functions. return { - name: options.get("timeout") for name, options in modal_app.app.function_calls + name: options.get("timeout") + for name, options in [*modal_app.app.function_calls, *modal_app.app.cls_calls] } @@ -54,17 +60,19 @@ def _declared_modal_timeouts(monkeypatch): def test_declared_modal_timeouts_fit_the_shared_wait_window(monkeypatch) -> None: declared_timeouts = _declared_modal_timeouts(monkeypatch) window_seconds = coordination_module.SIMULATION_WAIT_TIMEOUT_SECONDS + worker_methods = ( + "run_single_simulation_us", + "run_single_simulation_uk", + "run_single_simulation_segment_us", + ) + worker_classes = {worker_class_name(method) for method in worker_methods} child_worker_timeouts = { name: timeout for name, timeout in declared_timeouts.items() - if name.startswith("run_single_simulation") + if name.startswith("run_single_simulation") or name in worker_classes } - assert set(child_worker_timeouts) == { - "run_single_simulation_us", - "run_single_simulation_uk", - "run_single_simulation_segment_us", - } + assert set(child_worker_timeouts) == {*worker_methods, *worker_classes} # The window covers every worker's own Modal timeout. assert all(window_seconds >= timeout for timeout in child_worker_timeouts.values()) assert ( diff --git a/projects/policyengine-simulation-executor/tests/test_v2_worker_classes.py b/projects/policyengine-simulation-executor/tests/test_v2_worker_classes.py index 08c885d9c..9f90ad978 100644 --- a/projects/policyengine-simulation-executor/tests/test_v2_worker_classes.py +++ b/projects/policyengine-simulation-executor/tests/test_v2_worker_classes.py @@ -3,9 +3,12 @@ from __future__ import annotations import importlib +import os import random +import subprocess import sys from contextlib import contextmanager +from pathlib import Path import pytest from fixtures.fake_modal import install_fake_modal @@ -19,6 +22,7 @@ US_SIMULATION_TIMEOUT_SECONDS, ) +PROJECT_ROOT = Path(__file__).resolve().parents[1] WORKER_METHOD_NAMES = ( "run_single_simulation_us", "run_single_simulation_uk", @@ -147,6 +151,38 @@ def test_each_v2_worker_class_loads_only_its_own_countrys_models( assert preloaded_countries == [("us",), ("uk",), ("us",)] +def test_importing_the_v2_app_loads_neither_countrys_models() -> None: + # The snapshot hook loads one country's models only if the app's own + # import loaded none: .py imports both countries on import unless + # POLICYENGINE_SKIP_COUNTRY_IMPORTS is set, as the executor sets it. + probe = ( + "import sys\n" + "import src.modal.v2_app\n" + "print(sorted(name for name in sys.modules if name in {\n" + " 'policyengine_us', 'policyengine_uk',\n" + " 'policyengine.tax_benefit_models.us',\n" + " 'policyengine.tax_benefit_models.uk',\n" + "}))\n" + ) + environment = { + name: value + for name, value in os.environ.items() + if name != "POLICYENGINE_SKIP_COUNTRY_IMPORTS" + } + + imported = subprocess.run( + [sys.executable, "-c", probe], + cwd=PROJECT_ROOT, + env=environment, + capture_output=True, + text=True, + check=True, + timeout=300, + ) + + assert imported.stdout.strip().splitlines()[-1] == "[]" + + def test_the_v2_snapshot_hook_configures_no_observability(monkeypatch) -> None: v2_app = _load_v2_app(monkeypatch) preloads: list[str] = [] From 6199f6a64b095fccb8746c814162689b502f6ca7 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:30:22 +0400 Subject: [PATCH 08/10] Test the v2 classes' annotations and the v2 refusal message 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 --- .../tests/test_v2_worker_classes.py | 46 +++++++++++++++++-- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/projects/policyengine-simulation-executor/tests/test_v2_worker_classes.py b/projects/policyengine-simulation-executor/tests/test_v2_worker_classes.py index 9f90ad978..3bd539706 100644 --- a/projects/policyengine-simulation-executor/tests/test_v2_worker_classes.py +++ b/projects/policyengine-simulation-executor/tests/test_v2_worker_classes.py @@ -7,6 +7,7 @@ import random import subprocess import sys +import typing from contextlib import contextmanager from pathlib import Path @@ -23,6 +24,12 @@ ) PROJECT_ROOT = Path(__file__).resolve().parents[1] +OBSERVABILITY_CONTEXT = { + "captured_at": "2026-11-27T00:00:00Z", + "observability_id": "00000000-0000-4000-8000-000000000001", + "traceparent": "00-00000000000000000000000000000001-0000000000000001-01", +} +SIMULATION_RUN_ID = "00000000-0000-4000-8000-00000000b001" WORKER_METHOD_NAMES = ( "run_single_simulation_us", "run_single_simulation_uk", @@ -132,6 +139,17 @@ def test_each_v2_worker_class_has_one_snapshot_hook_and_one_restore_hook( assert worker_class.reseed_random_after_restore is restore_hooks[0] +def test_the_v2_worker_classes_annotations_resolve_at_run_time(monkeypatch) -> None: + # Modal reads a class's annotations with typing.get_type_hints, when it + # deploys the class and when a container starts it, once the class + # declares a modal.parameter. + v2_app = _load_v2_app(monkeypatch) + + for method_name in WORKER_METHOD_NAMES: + type_hints = typing.get_type_hints(_worker_class(v2_app, method_name)) + assert "snapshot_countries" in type_hints + + def test_each_v2_worker_class_loads_only_its_own_countrys_models( monkeypatch, ) -> None: @@ -164,10 +182,13 @@ def test_importing_the_v2_app_loads_neither_countrys_models() -> None: " 'policyengine.tax_benefit_models.uk',\n" "}))\n" ) + # Without the deploy step's inputs, the import reads no cache manifest + # and checks no app name or bundle values. environment = { name: value for name, value in os.environ.items() - if name != "POLICYENGINE_SKIP_COUNTRY_IMPORTS" + if name not in {"POLICYENGINE_SKIP_COUNTRY_IMPORTS", "MODAL_APP_NAME"} + and not name.startswith("STAGE12_") } imported = subprocess.run( @@ -228,6 +249,7 @@ class RecordingRuntime: def __init__(self) -> None: self.operation_names: list[str] = [] + self.operation_keywords: list[dict] = [] self.shutdown_calls = 0 def set_context(self, **_attributes) -> None: @@ -237,8 +259,9 @@ def capture_context(self) -> dict: return {} @contextmanager - def operation(self, name, **_keywords): + def operation(self, name, **keywords): self.operation_names.append(name) + self.operation_keywords.append(keywords) yield def shutdown(self) -> None: @@ -272,13 +295,19 @@ def model_dump(self, *, mode): if worker.__name__ == SEGMENT_WORKER_METHOD: result = worker( {"simulation": {"role": "baseline"}, "segment_index": 0}, - observability_context=None, + observability_context=OBSERVABILITY_CONTEXT, + simulation_run_id=SIMULATION_RUN_ID, ) else: - result = worker({"role": "baseline"}, {}, observability_context=None) + result = worker( + {"role": "baseline"}, {}, observability_context=OBSERVABILITY_CONTEXT + ) return { "result": result, "operations": runtime.operation_names, + # The call's own observability context, and for a segment the + # simulation run it names, reach its operation. + "operation_keywords": runtime.operation_keywords, "shutdown_calls": runtime.shutdown_calls, "modal_call_id": received_keywords.get("modal_call_id"), "required_country": received_keywords.get("required_country"), @@ -302,6 +331,13 @@ def test_a_v2_worker_class_method_runs_the_same_code_as_its_plain_function( assert through_the_class == through_the_function assert through_the_class["shutdown_calls"] == 1 assert len(through_the_class["operations"]) == 1 + (operation_keywords,) = through_the_class["operation_keywords"] + assert ( + operation_keywords["remote_context"]["observability_id"] + == (OBSERVABILITY_CONTEXT["observability_id"]) + ) + if method_name == SEGMENT_WORKER_METHOD: + assert operation_keywords["attributes"]["database_row_id"] == SIMULATION_RUN_ID if method_name != SEGMENT_WORKER_METHOD: assert through_the_class["modal_call_id"] == "fc-worker-call" @@ -325,6 +361,8 @@ def test_a_v2_deploy_with_a_modal_client_older_than_1_6_4_is_refused( importlib.import_module("src.modal.v2_app") assert client_version in str(refused.value) + # The message says how to deploy this app from the locked environment. + assert "modal deploy src/modal/v2_app.py" in str(refused.value) sys.modules.pop("src.modal.v2_images", None) sys.modules.pop("src.modal.v2_app", None) From 758ee379bf7067858475d69333ac58ecda617e8c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:30:57 +0400 Subject: [PATCH 09/10] Resolve the v2 classes' annotations at run time; name each app in the 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 --- .../policyengine-simulation-executor/src/modal/app.py | 4 +++- .../src/modal/modal_client_version.py | 9 ++++++--- .../policyengine-simulation-executor/src/modal/v2_app.py | 5 +++-- .../src/modal/v2_images.py | 4 +++- 4 files changed, 15 insertions(+), 7 deletions(-) diff --git a/projects/policyengine-simulation-executor/src/modal/app.py b/projects/policyengine-simulation-executor/src/modal/app.py index c4bf759d1..106a0e2f5 100644 --- a/projects/policyengine-simulation-executor/src/modal/app.py +++ b/projects/policyengine-simulation-executor/src/modal/app.py @@ -59,7 +59,9 @@ if modal.is_local(): - require_secret_reloading_modal_client(modal.__version__) + require_secret_reloading_modal_client( + modal.__version__, app_path="src/modal/app.py" + ) def _version_from_env_or_local_bundle_package(env_var: str, package: str) -> str: diff --git a/projects/policyengine-simulation-executor/src/modal/modal_client_version.py b/projects/policyengine-simulation-executor/src/modal/modal_client_version.py index b3b63f89f..33dbdade4 100644 --- a/projects/policyengine-simulation-executor/src/modal/modal_client_version.py +++ b/projects/policyengine-simulation-executor/src/modal/modal_client_version.py @@ -14,11 +14,14 @@ FIRST_MODAL_CLIENT_RELOADING_SECRETS_ON_RESTORE = Version("1.6.4") -def require_secret_reloading_modal_client(client_version: str) -> None: +def require_secret_reloading_modal_client( + client_version: str, *, app_path: str +) -> None: """Raise unless ``client_version`` is Modal 1.6.4 or newer. Versions compare as Python packaging defines them, so 1.6.4's development - builds and release candidates count as older than 1.6.4. + builds and release candidates count as older than 1.6.4. ``app_path`` is + the app's file, relative to the executor project, named in the message. """ try: reloads_secrets = ( @@ -33,6 +36,6 @@ def require_secret_reloading_modal_client(client_version: str) -> None: "restored from this app's memory snapshots would keep the Secret values " "from when each snapshot was taken. Deploy and run from this project's " "locked environment, for example " - "`uv run --frozen modal deploy src/modal/app.py`." + f"`uv run --frozen modal deploy {app_path}`." ) raise RuntimeError(msg) diff --git a/projects/policyengine-simulation-executor/src/modal/v2_app.py b/projects/policyengine-simulation-executor/src/modal/v2_app.py index af70aa509..c0490b205 100644 --- a/projects/policyengine-simulation-executor/src/modal/v2_app.py +++ b/projects/policyengine-simulation-executor/src/modal/v2_app.py @@ -380,8 +380,9 @@ class _V2CountryModelsLoadedBeforeSnapshot: """ # The image's own country: a failed import of one country's models can't - # affect the other country's workers. - snapshot_countries: ClassVar[tuple[CountryId, ...]] = () + # affect the other country's workers. Annotated with names Python can + # resolve when it runs, since Modal reads class annotations. + snapshot_countries: ClassVar[tuple[str, ...]] = () @modal.enter(snap=True) def load_country_models(self) -> None: diff --git a/projects/policyengine-simulation-executor/src/modal/v2_images.py b/projects/policyengine-simulation-executor/src/modal/v2_images.py index 5628cfd12..d28111bbe 100644 --- a/projects/policyengine-simulation-executor/src/modal/v2_images.py +++ b/projects/policyengine-simulation-executor/src/modal/v2_images.py @@ -49,7 +49,9 @@ # Modal client that keeps stale Secret values on restore is refused here, # before the cache manifest is read. if modal.is_local(): - require_secret_reloading_modal_client(modal.__version__) + require_secret_reloading_modal_client( + modal.__version__, app_path="src/modal/v2_app.py" + ) STAGE12_DATA_DIR = "/opt/policyengine/stage12-data" _UV_PROJECT_DIR = str(Path(__file__).resolve().parents[2]) if modal.is_local() else "." From 8f2b6d73adafbf3b136faa5c3f6af4805f7beb8f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:32:35 +0400 Subject: [PATCH 10/10] Name the changelog fragment after its issue, #1141 Co-Authored-By: Claude Opus 5.5 --- .../{v2-workers-memory-snapshots.changed.md => 1141.changed.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changelog.d/{v2-workers-memory-snapshots.changed.md => 1141.changed.md} (100%) diff --git a/changelog.d/v2-workers-memory-snapshots.changed.md b/changelog.d/1141.changed.md similarity index 100% rename from changelog.d/v2-workers-memory-snapshots.changed.md rename to changelog.d/1141.changed.md