From 8fcb443cc0434d81ab59a10bb2ad0bc39e3ac7fa Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:32:51 +0400 Subject: [PATCH 01/17] Test that the simulation workers are not also plain functions The versioned app still defines plain run_simulation and run_simulation_segment functions beside the worker classes, so this test fails until they are removed. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_modal_bundle_image.py | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py b/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py index 1de495d65..8749f4913 100644 --- a/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py +++ b/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py @@ -192,6 +192,26 @@ def test_simulation_workers_use_the_contract_names(monkeypatch): assert simulation_workers.FUNCTION_FORM_SIMULATION_WORKER == "run_simulation" +def test_the_simulation_workers_are_not_also_plain_functions(monkeypatch): + from policyengine_simulation_contract import simulation_workers + + install_fake_modal(monkeypatch) + sys.modules.pop("src.modal.app", None) + + app = importlib.import_module("src.modal.app") + + # Every caller of an app built from this code reaches the workers through + # their classes. Only apps deployed before the classes define the plain + # run_simulation function that the gateway falls back to. + plain_function_names = [name for name, _options in app.app.function_calls] + assert plain_function_names == ["run_budget_window_batch"] + for worker_method_name in ( + simulation_workers.SIMULATION_WORKER_METHOD, + simulation_workers.SEGMENT_WORKER_METHOD, + ): + assert not hasattr(app, worker_method_name) + + def test_both_simulation_workers_load_the_country_models_before_the_snapshot( monkeypatch, ): From 2d62febf8258dcbd82cf0003bb1535c16193f2a9 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:34:49 +0400 Subject: [PATCH 02/17] Remove the plain run_simulation and run_simulation_segment functions #1118 kept them beside the SimulationWorker and SimulationSegmentWorker classes for callers on the code from before the classes: the old gateway while a deploy replaced the routed app in place, and runs started before it. In Modal main and staging, the routed app and the gateway now both run code from 544ff62, which contains #1118, and no container from before those deploys is left. The gateway keeps its fallback to the run_simulation function of apps deployed before the classes. The tests that called the plain functions go with them. Co-Authored-By: Claude Opus 5.5 --- changelog.d/1130.removed.md | 1 + .../src/modal/app.py | 58 +++---------------- .../tests/test_job_progress.py | 40 ------------- .../tests/test_modal_bundle_image.py | 16 ----- 4 files changed, 9 insertions(+), 106 deletions(-) create mode 100644 changelog.d/1130.removed.md diff --git a/changelog.d/1130.removed.md b/changelog.d/1130.removed.md new file mode 100644 index 000000000..35570eccf --- /dev/null +++ b/changelog.d/1130.removed.md @@ -0,0 +1 @@ +Each versioned simulation app now defines its workers only as the `SimulationWorker` and `SimulationSegmentWorker` classes. The plain `run_simulation` and `run_simulation_segment` functions kept beside them for callers on the code from before the classes are gone. The gateway still reaches the `run_simulation` function of apps deployed before the classes, which stay routable for pinned versions and rollbacks. diff --git a/projects/policyengine-simulation-executor/src/modal/app.py b/projects/policyengine-simulation-executor/src/modal/app.py index db6153ab3..0bdbb622b 100644 --- a/projects/policyengine-simulation-executor/src/modal/app.py +++ b/projects/policyengine-simulation-executor/src/modal/app.py @@ -379,11 +379,11 @@ def _run_simulation( ) -> dict: """Execute one annual economic simulation. - The job behind ``SimulationWorker.run_simulation`` and the plain - ``run_simulation`` function. Imports the implementation in the call; in a - restored container the snapshot hook has already loaded the country models - it uses. Emits redacted operation data through the shared observability - runtime. Records the job's stage for status polls (see ``job_progress``). + The job behind ``SimulationWorker.run_simulation``. Imports the + implementation in the call; in a restored container the snapshot hook has + already loaded the country models it uses. Emits redacted operation data + through the shared observability runtime. Records the job's stage for + status polls (see ``job_progress``). """ progress = _job_progress_reporter() progress.start() @@ -450,9 +450,9 @@ def _run_simulation_segment( ) -> dict: """Run one region-group child of a segmented national run. - The job behind ``SimulationSegmentWorker.run_simulation_segment`` and the - plain ``run_simulation_segment`` function. Calls the monolithic impl - directly — children are ``region_group`` requests and never re-segment. + The job behind ``SimulationSegmentWorker.run_simulation_segment``. Calls + the monolithic impl directly — children are ``region_group`` requests and + never re-segment. """ runtime = _configure_modal_observability(service_role="simulation_worker") redacted_params = { @@ -560,48 +560,6 @@ def run_simulation_segment( ) -# The workers' plain functions from before the classes, kept without memory -# snapshots for callers still running that code. The executor deploys before -# the gateway, and a deploy that keeps the policyengine.py version replaces the -# routed app in place, so the old gateway spawns run_simulation here until the -# new one is live. Runs started before a deploy spawn their children by these -# names too. Remove both once no such caller is left. -@app.function( - image=simulation_image, - cpu=8.0, - memory=32768, - timeout=3600, - retries=0, - max_containers=100, - secrets=[gcp_secret, hf_secret], -) -def run_simulation( - params: dict, - *, - observability_context: dict | None = None, -) -> dict: - """Execute one annual simulation, for callers from before the classes.""" - return _run_simulation(params, observability_context=observability_context) - - -@app.function( - image=simulation_image, - cpu=8.0, - memory=32768, - timeout=3600, - retries=0, - max_containers=300, - secrets=[gcp_secret, hf_secret], -) -def run_simulation_segment( - params: dict, - *, - observability_context: dict | None = None, -) -> dict: - """Run one region-group child, for callers from before the classes.""" - return _run_simulation_segment(params, observability_context=observability_context) - - @app.function( image=simulation_image, cpu=1.0, diff --git a/projects/policyengine-simulation-executor/tests/test_job_progress.py b/projects/policyengine-simulation-executor/tests/test_job_progress.py index 1f3fc53ed..4bd7bc407 100644 --- a/projects/policyengine-simulation-executor/tests/test_job_progress.py +++ b/projects/policyengine-simulation-executor/tests/test_job_progress.py @@ -950,27 +950,6 @@ def dispatch(_params, *, app_name, runtime, progress): assert _operation_completions(written_records) == [("WARNING", "interrupted")] assert _error_records(written_records) == [] - def test__the_function_kept_for_older_callers_records_the_same_job( - self, modal_app, monkeypatch - ): - # The plain run_simulation function serves callers still running the - # code from before the worker classes, such as the gateway during a - # deploy. It runs the class method's code. - def dispatch(_params, *, app_name, runtime, progress): - progress.enter(JobStage.REFORM) - return {"ok": True} - - _events, writes = self._wire(modal_app, monkeypatch, dispatch) - - assert modal_app.run_simulation({"country": "us"}) == {"ok": True} - - assert {job_id for job_id, _ in writes} == {"fc-job-1"} - assert [record.stage for _, record in writes] == [ - JobStage.LOADING_DATA, - JobStage.REFORM, - JobStage.REFORM, - ] - def test__store_failure_does_not_change_the_result(self, modal_app, monkeypatch): from policyengine_simulation_contract import job_progress_state @@ -1025,25 +1004,6 @@ def preempted(_params, *, runtime): assert _error_records(written_records) == [] -def test_the_segment_function_kept_for_older_callers_runs_the_same_code( - modal_app, monkeypatch, recorded_observability_runtime -): - # Segmented parents started before the worker classes spawn their - # children through the plain run_simulation_segment function. - runtime, written_records = recorded_observability_runtime - monkeypatch.setattr( - modal_app, - "_configure_modal_observability", - lambda *, service_role: runtime, - ) - monkeypatch.setattr( - sr, "run_simulation_impl", lambda _params, *, runtime: {"segment": "done"} - ) - - assert modal_app.run_simulation_segment({"country": "us"}) == {"segment": "done"} - assert _operation_completions(written_records) == [("INFO", "success")] - - def _operation_completions(written_records: list[dict]) -> list[tuple[str, str]]: """Return the severity and outcome of each operation completion record.""" return [ diff --git a/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py b/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py index 8749f4913..1d182bb9f 100644 --- a/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py +++ b/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py @@ -147,22 +147,6 @@ def test_simulation_workers_are_classes_restored_from_memory_snapshots(monkeypat "SimulationWorker": {**worker_options, "max_containers": 100}, "SimulationSegmentWorker": {**worker_options, "max_containers": 300}, } - # Plain functions with the same names and limits stay, without a snapshot, - # for callers still running the code from before the classes: the gateway - # while a deploy is under way, and runs that started before it. - function_form_options = { - option: value - for option, value in worker_options.items() - if option != "enable_memory_snapshot" - } - assert function_options["run_simulation"] == { - **function_form_options, - "max_containers": 100, - } - assert function_options["run_simulation_segment"] == { - **function_form_options, - "max_containers": 300, - } # The budget-window parent stays a small plain function with no snapshot. assert "enable_memory_snapshot" not in function_options["run_budget_window_batch"] From 300bd1110c00f601591a59a16cfa5aa3c1943393 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:47:50 +0400 Subject: [PATCH 03/17] Test the segment worker's success path through its class Removing the plain run_simulation_segment function took with it the only test that a segment call returns its result and records a successful operation. That code still runs as SimulationSegmentWorker.run_simulation_segment, so the test now calls the class method. It fails when the method drops its result. Also check only that the two worker names are not plain functions, so an unrelated new function doesn't fail the test, and say in the changelog that only apps deployed from this release lose the functions. Co-Authored-By: Claude Opus 5.5 --- changelog.d/1130.removed.md | 2 +- .../tests/test_job_progress.py | 22 +++++++++++++++++++ .../tests/test_modal_bundle_image.py | 4 ++-- 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/changelog.d/1130.removed.md b/changelog.d/1130.removed.md index 35570eccf..d17deab20 100644 --- a/changelog.d/1130.removed.md +++ b/changelog.d/1130.removed.md @@ -1 +1 @@ -Each versioned simulation app now defines its workers only as the `SimulationWorker` and `SimulationSegmentWorker` classes. The plain `run_simulation` and `run_simulation_segment` functions kept beside them for callers on the code from before the classes are gone. The gateway still reaches the `run_simulation` function of apps deployed before the classes, which stay routable for pinned versions and rollbacks. +Versioned simulation apps deployed from this release define their workers only as the `SimulationWorker` and `SimulationSegmentWorker` classes. The plain `run_simulation` and `run_simulation_segment` functions, which served callers still running the code from before the classes, are removed. Apps deployed before the classes keep their `run_simulation` function, and the gateway still reaches it. diff --git a/projects/policyengine-simulation-executor/tests/test_job_progress.py b/projects/policyengine-simulation-executor/tests/test_job_progress.py index 4bd7bc407..d473bf689 100644 --- a/projects/policyengine-simulation-executor/tests/test_job_progress.py +++ b/projects/policyengine-simulation-executor/tests/test_job_progress.py @@ -1004,6 +1004,28 @@ def preempted(_params, *, runtime): assert _error_records(written_records) == [] +def test_a_segment_returns_its_result_and_records_success( + modal_app, monkeypatch, recorded_observability_runtime +): + # The segmented parent reduces the results its children return. + runtime, written_records = recorded_observability_runtime + monkeypatch.setattr( + modal_app, + "_configure_modal_observability", + lambda *, service_role: runtime, + ) + monkeypatch.setattr( + sr, "run_simulation_impl", lambda _params, *, runtime: {"segment": "done"} + ) + + segment_result = modal_app.SimulationSegmentWorker().run_simulation_segment( + {"country": "us"} + ) + + assert segment_result == {"segment": "done"} + assert _operation_completions(written_records) == [("INFO", "success")] + + def _operation_completions(written_records: list[dict]) -> list[tuple[str, str]]: """Return the severity and outcome of each operation completion record.""" return [ diff --git a/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py b/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py index 1d182bb9f..faa5c805a 100644 --- a/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py +++ b/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py @@ -187,12 +187,12 @@ def test_the_simulation_workers_are_not_also_plain_functions(monkeypatch): # Every caller of an app built from this code reaches the workers through # their classes. Only apps deployed before the classes define the plain # run_simulation function that the gateway falls back to. - plain_function_names = [name for name, _options in app.app.function_calls] - assert plain_function_names == ["run_budget_window_batch"] + plain_function_names = {name for name, _options in app.app.function_calls} for worker_method_name in ( simulation_workers.SIMULATION_WORKER_METHOD, simulation_workers.SEGMENT_WORKER_METHOD, ): + assert worker_method_name not in plain_function_names assert not hasattr(app, worker_method_name) From e83a1c71ef75cce67e373d347a7ab89cbcc77759 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:58:56 +0400 Subject: [PATCH 04/17] Say that apps from earlier code define the fallback function Apps deployed after the worker classes but before this change define the plain run_simulation function too. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_modal_bundle_image.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py b/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py index faa5c805a..f784cd9fc 100644 --- a/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py +++ b/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py @@ -185,7 +185,7 @@ def test_the_simulation_workers_are_not_also_plain_functions(monkeypatch): app = importlib.import_module("src.modal.app") # Every caller of an app built from this code reaches the workers through - # their classes. Only apps deployed before the classes define the plain + # their classes. Only apps deployed from earlier code define the plain # run_simulation function that the gateway falls back to. plain_function_names = {name for name, _options in app.app.function_calls} for worker_method_name in ( From 66670bb10fd218b2273e6dcc049fd5f47532a2de Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:52:52 +0400 Subject: [PATCH 05/17] Stop testing and documenting container_start for the removed functions #1124 tested that the plain run_simulation and run_simulation_segment functions report no_snapshot, and its observability skill section named them. With both functions removed, those four test cases fail with AttributeError. The two tests now check run_budget_window_batch, the app's only plain function, and the skill names the worker class methods instead. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/observability.md | 11 +++++------ .../tests/test_modal_container_start.py | 17 +++++------------ 2 files changed, 10 insertions(+), 18 deletions(-) diff --git a/docs/engineering/skills/observability.md b/docs/engineering/skills/observability.md index 2bde14bba..535e8f76a 100644 --- a/docs/engineering/skills/observability.md +++ b/docs/engineering/skills/observability.md @@ -187,8 +187,8 @@ its running segments. ### Container start and call number -Each call of the versioned app's workers (`run_simulation` and -`run_simulation_segment`, as class methods and as plain functions) and of +Each call of the versioned app's workers (the `SimulationWorker.run_simulation` +and `SimulationSegmentWorker.run_simulation_segment` methods) and of `run_budget_window_batch` sets two attributes on its operation, so on its `operation.completed` log record and its span. Only the operation's span carries them, not its child spans such as `country_module_load`. @@ -197,7 +197,7 @@ operation opens, so a call that fails or is preempted carries them too. | Attribute | Values | |---|---| -| `container_start` | `restored_from_snapshot`: the container was restored from a memory snapshot, so it started with the country models loaded. `took_snapshot`: Modal took the snapshot from this container, after the snapshot hook loaded the models in it. `no_snapshot`: the container neither took a snapshot nor was restored from one. That is every container of the plain `run_simulation` and `run_simulation_segment` functions and of `run_budget_window_batch`, which have no snapshot hook, and a worker class container that Modal started without snapshots, whose hook loaded the models before its first call. | +| `container_start` | `restored_from_snapshot`: the container was restored from a memory snapshot, so it started with the country models loaded. `took_snapshot`: Modal took the snapshot from this container, after the snapshot hook loaded the models in it. `no_snapshot`: the container neither took a snapshot nor was restored from one. That is every container of the plain `run_budget_window_batch` function, which has no snapshot hook, and a worker class container that Modal started without snapshots, whose hook loaded the models before its first call. | | `container_call_number` | The call's place among the container's calls that opened their operation: 1 for the first, 2 for the second, and so on. A call counts even when reading or setting these attributes fails. | How a call tells them apart, in Modal 1.6.4: @@ -234,9 +234,8 @@ times each container was queued and became ready (`enqueued_at` and `started_at`), which include scheduling as well as the restore. A call's spans show the setup still left in it: -- In the first call of a container of the plain `run_simulation` or - `run_simulation_segment` function, which loads the models itself, most of - that setup is in the `country_module_load` span, which +- In apps deployed before the worker classes, whose workers load the models + in their first call, most of that setup is in the `country_module_load` span, which imports policyengine.py's country model module, and, for a US run, in the time from the operation's start to that span, which includes the SPM capability check. A segmented national run's `run_simulation` call opens no diff --git a/projects/policyengine-simulation-executor/tests/test_modal_container_start.py b/projects/policyengine-simulation-executor/tests/test_modal_container_start.py index 8ca4a7b6b..b3724e9d6 100644 --- a/projects/policyengine-simulation-executor/tests/test_modal_container_start.py +++ b/projects/policyengine-simulation-executor/tests/test_modal_container_start.py @@ -131,17 +131,14 @@ def _restore_into_another_container(monkeypatch, worker) -> None: worker.reseed_random_after_restore() -@pytest.mark.parametrize( - "function_name", - ["run_simulation", "run_simulation_segment", "run_budget_window_batch"], -) def test_a_plain_function_call_reports_a_container_started_without_a_snapshot( - modal_app, monkeypatch, function_name + modal_app, monkeypatch ): + # The budget-window parent is the app's only plain function. monkeypatch.setenv("MODAL_TASK_ID", PLAIN_FUNCTION_TASK_ID) attributes_by_call = _record_call_attributes(modal_app, monkeypatch) - assert getattr(modal_app, function_name)(SIMULATION_PARAMS) == WORKER_RESULT + assert modal_app.run_budget_window_batch(SIMULATION_PARAMS) == WORKER_RESULT [call_attributes] = attributes_by_call assert call_attributes["container_start"] == "no_snapshot" @@ -265,12 +262,8 @@ def record_metric_attributes( assert not CONTAINER_START_KEYS & set(metric_attributes) -@pytest.mark.parametrize( - "function_name", - ["run_simulation", "run_simulation_segment", "run_budget_window_batch"], -) def test_a_plain_function_sets_both_attributes_before_its_job_runs( - modal_app, monkeypatch, function_name + modal_app, monkeypatch ): _record_call_attributes(modal_app, monkeypatch) attributes_when_the_job_started: list[dict[str, object]] = [] @@ -281,7 +274,7 @@ def job_reading_its_operation_attributes(_params, *, runtime, **_job_options): _replace_worker_jobs(monkeypatch, job_reading_its_operation_attributes) - assert getattr(modal_app, function_name)(SIMULATION_PARAMS) == WORKER_RESULT + assert modal_app.run_budget_window_batch(SIMULATION_PARAMS) == WORKER_RESULT [job_attributes] = attributes_when_the_job_started assert job_attributes["container_start"] == "no_snapshot" From 76fc214affae1c8ee42a6526b4f63e021ce3f3d0 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:01:38 +0400 Subject: [PATCH 06/17] Say that apps from before the classes report no call number Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/observability.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/engineering/skills/observability.md b/docs/engineering/skills/observability.md index 535e8f76a..b763b0981 100644 --- a/docs/engineering/skills/observability.md +++ b/docs/engineering/skills/observability.md @@ -235,10 +235,12 @@ times each container was queued and became ready (`enqueued_at` and in it: - In apps deployed before the worker classes, whose workers load the models - in their first call, most of that setup is in the `country_module_load` span, which - imports policyengine.py's country model module, and, for a US run, in the - time from the operation's start to that span, which includes the SPM - capability check. A segmented national run's `run_simulation` call opens no + in each container's first call, most of that setup is in the + `country_module_load` span, which imports policyengine.py's country model + module, and, for a US run, in the time from the operation's start to that + span, which includes the SPM capability check. Those apps' records carry + neither attribute, so `container_call_number` can't pick out a container's + first call. A segmented national run's `run_simulation` call opens no `country_module_load` span: its segment workers' calls do. - In a container whose hook loaded the models, the first call's time there should be close to later calls' (`container_call_number` above 1). From 13101fef95bafc2cc592e46b1fda628c8e508dfc Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:48:53 +0400 Subject: [PATCH 07/17] Test that the gateway spawns no function for an app without the worker class The gateway falls back to the plain run_simulation function of an app that has no SimulationWorker class, so this test fails until the fallback is removed. The test fixture now raises the class lookup error when a method of a missing class is spawned, where Modal resolves the lazy handle. Co-Authored-By: Claude Opus 5.5 --- .../fixtures/gateway_endpoints.py | 74 +++++++++++++------ .../tests/test_simulation_submission.py | 29 ++++---- 2 files changed, 63 insertions(+), 40 deletions(-) diff --git a/projects/policyengine-simulation-gateway/fixtures/gateway_endpoints.py b/projects/policyengine-simulation-gateway/fixtures/gateway_endpoints.py index 6fe552215..db608102b 100644 --- a/projects/policyengine-simulation-gateway/fixtures/gateway_endpoints.py +++ b/projects/policyengine-simulation-gateway/fixtures/gateway_endpoints.py @@ -2,7 +2,7 @@ from collections.abc import ItemsView, KeysView from copy import deepcopy -from typing import ClassVar, Self +from typing import ClassVar, NoReturn, Self import pytest from policyengine_simulation_contract.macro_output import ( @@ -368,10 +368,11 @@ class OutputExpiredError(Exception): class MockWorkerClass: """Class handle returned by Modal.Cls.from_name. - ``hydrate`` raises ``NotFoundError`` for an app in ``function_form_apps``, - as Modal does for an app deployed before it defined its workers as - classes. Calling the handle returns an instance whose methods record - their spawns into ``recorder``. + For an app in ``apps_without_worker_class``, such as one deployed before + the workers were classes, Modal can't resolve the class: ``hydrate`` and + a method's spawn raise ``NotFoundError``, as Modal does when it resolves + the lazy handle. Otherwise, calling the handle returns an instance whose + methods record their spawns into ``recorder``. """ def __init__( @@ -379,40 +380,62 @@ def __init__( recorder: MockFunction, app_name: str, class_name: str, - function_form_apps: set[str], + apps_without_worker_class: set[str], ) -> None: """Bind the app and class looked up.""" self.recorder = recorder self.app_name = app_name self.class_name = class_name - self.function_form_apps = function_form_apps + self.apps_without_worker_class = apps_without_worker_class + + def lookup_error(self) -> Exception | None: + """Return the error that resolving the class raises, or None if it exists.""" + if self.app_name not in self.apps_without_worker_class: + return None + msg = ( + f"Lookup failed for Cls '{self.class_name}' from the '{self.app_name}' app" + ) + return MockModalException.NotFoundError(msg) def hydrate(self) -> Self: """Resolve the class, or raise ``NotFoundError`` if the app has none.""" - if self.app_name in self.function_form_apps: - msg = ( - f"Lookup failed for Cls '{self.class_name}' " - f"from the '{self.app_name}' app" - ) - raise MockModalException.NotFoundError(msg) + error = self.lookup_error() + if error is not None: + raise error return self def __call__(self) -> "MockWorkerInstance": """Return an instance of the worker class.""" - return MockWorkerInstance(self.recorder, self.app_name) + return MockWorkerInstance(self) class MockWorkerInstance: """Instance of a worker class: each method spawns under its method name.""" - def __init__(self, recorder: MockFunction, app_name: str) -> None: - """Bind the app whose class this is an instance of.""" - self.recorder = recorder - self.app_name = app_name + def __init__(self, worker_class: MockWorkerClass) -> None: + """Bind the class handle this is an instance of.""" + self.worker_class = worker_class - def __getattr__(self, method_name: str) -> BoundMockFunction: + def __getattr__( + self, method_name: str + ) -> "BoundMockFunction | MissingWorkerMethod": """Return a handle for one method that records into the recorder.""" - return self.recorder.bind(self.app_name, method_name) + error = self.worker_class.lookup_error() + if error is not None: + return MissingWorkerMethod(error) + return self.worker_class.recorder.bind(self.worker_class.app_name, method_name) + + +class MissingWorkerMethod: + """A method of a class the app doesn't define: spawning it raises.""" + + def __init__(self, lookup_error: Exception) -> None: + """Keep the error that resolving the class raises.""" + self.lookup_error = lookup_error + + def spawn(self, *_arguments: object, **_keywords: object) -> NoReturn: + """Raise the class lookup error, as Modal does on the first spawn.""" + raise self.lookup_error @pytest.fixture @@ -454,14 +477,17 @@ def from_name(app_name: str, func_name: str) -> BoundMockFunction: mock_func.last_from_name_call = (app_name, func_name) return mock_func.bind(app_name, func_name) - # Apps deployed before the workers became classes: no class lookup works. - function_form_apps: set[str] = set() + # Apps that define no worker class, such as ones deployed before the + # workers became classes: no class lookup works. + apps_without_worker_class: set[str] = set() class MockModalCls: @staticmethod def from_name(app_name: str, class_name: str) -> MockWorkerClass: mock_func.last_cls_from_name_call = (app_name, class_name) - return MockWorkerClass(mock_func, app_name, class_name, function_form_apps) + return MockWorkerClass( + mock_func, app_name, class_name, apps_without_worker_class + ) class MockModal: Dict = MockModalDict @@ -497,5 +523,5 @@ class MockModal: "dicts": mock_dicts, "function_call": MockFunctionCall, "exception": MockModalException, - "function_form_apps": function_form_apps, + "apps_without_worker_class": apps_without_worker_class, } diff --git a/projects/policyengine-simulation-gateway/tests/test_simulation_submission.py b/projects/policyengine-simulation-gateway/tests/test_simulation_submission.py index ea0f66d37..f4a5e6af9 100644 --- a/projects/policyengine-simulation-gateway/tests/test_simulation_submission.py +++ b/projects/policyengine-simulation-gateway/tests/test_simulation_submission.py @@ -70,35 +70,32 @@ def test__given_no_data_value__then_routes_to_run_simulation( assert "time_period" not in mock_modal["func"].last_payload assert "data_version" not in mock_modal["func"].last_payload - def test__given_an_app_deployed_before_the_worker_class__then_spawns_its_function( + def test__given_an_app_with_no_worker_class__then_no_function_is_spawned( self, mock_modal, client: TestClient ): - """Given an app with no worker class, then spawn its run_simulation function.""" - # Given: a pinned or rolled-back version whose app predates the class. + """Given an app with no worker class, then fail without spawning a function.""" + # Given: a pinned or rolled-back version whose app predates the class + # and defines run_simulation as a plain function. mock_modal["dicts"]["simulation-api-us-versions"] = { "latest": "1.500.0", "1.500.0": "policyengine-simulation-py4-10-0", } - mock_modal["function_form_apps"].add("policyengine-simulation-py4-10-0") + mock_modal["apps_without_worker_class"].add("policyengine-simulation-py4-10-0") # When - response = client.post( - "/simulate/economy/comparison", - json={"country": "us", "scope": "macro", "reform": {}}, - ) + with pytest.raises(mock_modal["exception"].NotFoundError): + client.post( + "/simulate/economy/comparison", + json={"country": "us", "scope": "macro", "reform": {}}, + ) - # Then - assert response.status_code == 200 - assert response.json()["job_id"] == "mock-job-id-123" + # Then: the gateway spawns only through the worker class. assert mock_modal["func"].last_cls_from_name_call == ( "policyengine-simulation-py4-10-0", "SimulationWorker", ) - assert mock_modal["func"].last_from_name_call == ( - "policyengine-simulation-py4-10-0", - "run_simulation", - ) - assert len(mock_modal["func"].calls) == 1 + assert mock_modal["func"].last_from_name_call is None + assert mock_modal["func"].calls == [] def test__given_a_failed_spawn_on_the_worker_class__then_no_function_is_tried( self, mock_modal, client: TestClient From fed9421b4e299412de3e670e5087ba77aee0d3f7 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:00:02 +0400 Subject: [PATCH 08/17] Spawn annual simulations only through the SimulationWorker class The gateway no longer falls back to the plain run_simulation function of apps deployed before the worker classes. API v1 pins .py 6.20.0, whose app has the class, and no older app has logged a call since API v1 moved to it on 16 Nov. A request routed to an older app, pinned or after a rollback of latest, now fails with Modal's NotFoundError, as one routed to an app that isn't deployed does. FUNCTION_FORM_SIMULATION_WORKER, the test fixture's spawn_error option, and the hydrate methods of the test class handles go with the fallback. Co-Authored-By: Claude Opus 5.5 --- changelog.d/1130.removed.md | 4 +++- .../simulation_workers.py | 7 ++---- .../tests/test_canonical_spm.py | 7 ++---- .../tests/test_modal_bundle_image.py | 7 ++---- .../fixtures/gateway_endpoints.py | 23 ++++--------------- .../job_creation_routes.py | 17 +++----------- .../tests/test_simulation_submission.py | 23 ------------------- 7 files changed, 17 insertions(+), 71 deletions(-) diff --git a/changelog.d/1130.removed.md b/changelog.d/1130.removed.md index d17deab20..052a385dc 100644 --- a/changelog.d/1130.removed.md +++ b/changelog.d/1130.removed.md @@ -1 +1,3 @@ -Versioned simulation apps deployed from this release define their workers only as the `SimulationWorker` and `SimulationSegmentWorker` classes. The plain `run_simulation` and `run_simulation_segment` functions, which served callers still running the code from before the classes, are removed. Apps deployed before the classes keep their `run_simulation` function, and the gateway still reaches it. +Versioned simulation apps deployed from this release define their workers only as the `SimulationWorker` and `SimulationSegmentWorker` classes. The plain `run_simulation` and `run_simulation_segment` functions, which served callers still running the code from before the classes, are removed. + +The gateway now spawns annual simulations only through the `SimulationWorker` class, and no longer falls back to the plain `run_simulation` function of apps deployed before the classes. A request routed to one of those apps (every policyengine.py release before 6.20.0), whether pinned or after a rollback of `latest`, now fails instead of running there. diff --git a/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/simulation_workers.py b/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/simulation_workers.py index b5e919ed6..49817e69f 100644 --- a/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/simulation_workers.py +++ b/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/simulation_workers.py @@ -15,9 +15,8 @@ deployed app, so both read them from here. Apps deployed before the workers were classes define ``run_simulation`` as a -plain Modal function. The gateway still routes to those apps, for pinned -versions and after a rollback, so it falls back to that function name when an -app has no ``SimulationWorker`` class. +plain Modal function instead. The gateway spawns only through the class, so it +runs no simulation on those apps. """ SIMULATION_WORKER_CLASS = "SimulationWorker" @@ -25,5 +24,3 @@ SEGMENT_WORKER_CLASS = "SimulationSegmentWorker" SEGMENT_WORKER_METHOD = "run_simulation_segment" - -FUNCTION_FORM_SIMULATION_WORKER = "run_simulation" diff --git a/projects/policyengine-simulation-executor/tests/test_canonical_spm.py b/projects/policyengine-simulation-executor/tests/test_canonical_spm.py index ed388f3ad..c35525fde 100644 --- a/projects/policyengine-simulation-executor/tests/test_canonical_spm.py +++ b/projects/policyengine-simulation-executor/tests/test_canonical_spm.py @@ -714,15 +714,12 @@ def test_gateway_poll_returns_structured_400(monkeypatch, code): assert response.json()["result"] is None -class _HydratedWorkerClass: +class _WorkerClassHandle: """A ``modal.Cls`` lookup of a class the app defines.""" def __init__(self, worker): self.worker = worker - def hydrate(self): - return self - def __call__(self): return self.worker @@ -754,7 +751,7 @@ def test_gateway_submission_uses_registry_capability_before_spawn(monkeypatch): "modal", SimpleNamespace( Cls=SimpleNamespace( - from_name=lambda *_args: _HydratedWorkerClass(simulation_worker) + from_name=lambda *_args: _WorkerClassHandle(simulation_worker) ) ), ) diff --git a/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py b/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py index a42213987..f517382be 100644 --- a/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py +++ b/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py @@ -177,8 +177,6 @@ def test_simulation_workers_use_the_contract_names(monkeypatch): getattr(segment_worker, simulation_workers.SEGMENT_WORKER_METHOD) in recorded_methods ) - # Apps deployed before the class form define run_simulation as a function. - assert simulation_workers.FUNCTION_FORM_SIMULATION_WORKER == "run_simulation" def test_the_simulation_workers_are_not_also_plain_functions(monkeypatch): @@ -189,9 +187,8 @@ def test_the_simulation_workers_are_not_also_plain_functions(monkeypatch): app = importlib.import_module("src.modal.app") - # Every caller of an app built from this code reaches the workers through - # their classes. Only apps deployed from earlier code define the plain - # run_simulation function that the gateway falls back to. + # Every caller of an app built from this code, the gateway included, + # reaches the workers only through their classes. plain_function_names = {name for name, _options in app.app.function_calls} for worker_method_name in ( simulation_workers.SIMULATION_WORKER_METHOD, diff --git a/projects/policyengine-simulation-gateway/fixtures/gateway_endpoints.py b/projects/policyengine-simulation-gateway/fixtures/gateway_endpoints.py index db608102b..3aa71be75 100644 --- a/projects/policyengine-simulation-gateway/fixtures/gateway_endpoints.py +++ b/projects/policyengine-simulation-gateway/fixtures/gateway_endpoints.py @@ -291,17 +291,13 @@ class MockFunction: """Mock for Modal Function.""" def __init__(self) -> None: - """Start with no recorded spawns or lookups. - - Set ``spawn_error`` to make every spawn raise it. - """ + """Start with no recorded spawns or lookups.""" self.last_payload = None self.last_observability_context = None self.last_from_name_call = None self.last_cls_from_name_call = None self.last_call = None self.calls = [] - self.spawn_error: Exception | None = None def bind(self, app_name: str, func_name: str) -> "BoundMockFunction": """Return a handle for one app function that records into this mock.""" @@ -334,8 +330,6 @@ def spawn( A ``run_budget_window_batch`` spawn gets the batch ID and stays running; any other spawn completes immediately. """ - if self.recorder.spawn_error is not None: - raise self.recorder.spawn_error self.recorder.last_payload = payload self.recorder.last_observability_context = observability_context is_batch = self.func_name == "run_budget_window_batch" @@ -369,10 +363,10 @@ class MockWorkerClass: """Class handle returned by Modal.Cls.from_name. For an app in ``apps_without_worker_class``, such as one deployed before - the workers were classes, Modal can't resolve the class: ``hydrate`` and - a method's spawn raise ``NotFoundError``, as Modal does when it resolves - the lazy handle. Otherwise, calling the handle returns an instance whose - methods record their spawns into ``recorder``. + the workers were classes, Modal can't resolve the class: a method's spawn + raises ``NotFoundError``, as Modal does when it resolves the lazy handle. + Otherwise, calling the handle returns an instance whose methods record + their spawns into ``recorder``. """ def __init__( @@ -397,13 +391,6 @@ def lookup_error(self) -> Exception | None: ) return MockModalException.NotFoundError(msg) - def hydrate(self) -> Self: - """Resolve the class, or raise ``NotFoundError`` if the app has none.""" - error = self.lookup_error() - if error is not None: - raise error - return self - def __call__(self) -> "MockWorkerInstance": """Return an instance of the worker class.""" return MockWorkerInstance(self) diff --git a/projects/policyengine-simulation-gateway/src/policyengine_simulation_gateway/job_creation_routes.py b/projects/policyengine-simulation-gateway/src/policyengine_simulation_gateway/job_creation_routes.py index 798b498c4..6ed10a898 100644 --- a/projects/policyengine-simulation-gateway/src/policyengine_simulation_gateway/job_creation_routes.py +++ b/projects/policyengine-simulation-gateway/src/policyengine_simulation_gateway/job_creation_routes.py @@ -31,7 +31,6 @@ supported_local_area_breakdown_capability, ) from policyengine_simulation_contract.simulation_workers import ( - FUNCTION_FORM_SIMULATION_WORKER, SIMULATION_WORKER_CLASS, SIMULATION_WORKER_METHOD, ) @@ -207,21 +206,11 @@ def _spawn_annual_simulation( """Spawn one annual simulation on ``app_name``'s simulation worker. Apps define the worker as a method of a Modal class, so its containers - restore from memory snapshots. Apps deployed before that define it as a - plain function, and stay routable for pinned versions and rollbacks, so - an app with no worker class gets the function. Only the class lookup - falls back: once the class resolves, a failed spawn raises as it is. + restore from memory snapshots. Apps deployed before that define a plain + function instead, and have no such class: Modal raises ``NotFoundError`` + when the spawn resolves the lazy class handle. """ worker_class = modal.Cls.from_name(app_name, SIMULATION_WORKER_CLASS) - try: - worker_class.hydrate() - except modal.exception.NotFoundError: - worker_function = modal.Function.from_name( - app_name, FUNCTION_FORM_SIMULATION_WORKER - ) - return worker_function.spawn( - payload, observability_context=observability_context - ) worker_method = getattr(worker_class(), SIMULATION_WORKER_METHOD) return worker_method.spawn(payload, observability_context=observability_context) diff --git a/projects/policyengine-simulation-gateway/tests/test_simulation_submission.py b/projects/policyengine-simulation-gateway/tests/test_simulation_submission.py index f4a5e6af9..98301e87b 100644 --- a/projects/policyengine-simulation-gateway/tests/test_simulation_submission.py +++ b/projects/policyengine-simulation-gateway/tests/test_simulation_submission.py @@ -97,29 +97,6 @@ def test__given_an_app_with_no_worker_class__then_no_function_is_spawned( assert mock_modal["func"].last_from_name_call is None assert mock_modal["func"].calls == [] - def test__given_a_failed_spawn_on_the_worker_class__then_no_function_is_tried( - self, mock_modal, client: TestClient - ): - """Given the class exists but its spawn fails, then don't fall back.""" - # Given - mock_modal["dicts"]["simulation-api-us-versions"] = { - "latest": "1.500.0", - "1.500.0": "policyengine-simulation-py4-10-0", - } - spawn_failure = mock_modal["exception"].NotFoundError("spawn failed") - mock_modal["func"].spawn_error = spawn_failure - - # When - with pytest.raises(mock_modal["exception"].NotFoundError) as raised: - client.post( - "/simulate/economy/comparison", - json={"country": "us", "scope": "macro", "reform": {}}, - ) - - # Then: the class lookup succeeded, so its spawn error is the answer. - assert raised.value is spawn_failure - assert mock_modal["func"].last_from_name_call is None - def test__given_submission__then_returns_job_id_and_poll_url( self, mock_modal, client: TestClient ): From b34826f45dd32e1c4f13a9b12d45221190b84faa Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:13:21 +0400 Subject: [PATCH 09/17] Say that only comparison requests stop running on older apps The gateway still spawns a budget-window batch on an app from before the worker classes, and that app spawns its yearly simulations itself. The rollback workflow and the executor README now say that a rollback of latest to a release before 6.20.0 fails every unpinned comparison request. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/simulation-rollback.yml | 5 ++++- changelog.d/1130.removed.md | 2 +- .../policyengine_simulation_contract/simulation_workers.py | 4 ++-- projects/policyengine-simulation-executor/README.md | 3 +++ 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/.github/workflows/simulation-rollback.yml b/.github/workflows/simulation-rollback.yml index 0aea85ec2..516ecad00 100644 --- a/.github/workflows/simulation-rollback.yml +++ b/.github/workflows/simulation-rollback.yml @@ -16,7 +16,10 @@ name: Roll back Simulation API # state is what it published, so it never overwrites a later release; the # failed release's routes go too. # - policyengine_version: point latest at that published release. Other -# releases, including the failed one, stay pinnable. +# releases, including the failed one, stay pinnable. The gateway runs +# comparison requests only on apps that define the SimulationWorker class +# (policyengine.py 6.20.0 and later), so after a rollback to an earlier +# release every unpinned comparison request fails. on: workflow_dispatch: diff --git a/changelog.d/1130.removed.md b/changelog.d/1130.removed.md index 052a385dc..2c86faa9a 100644 --- a/changelog.d/1130.removed.md +++ b/changelog.d/1130.removed.md @@ -1,3 +1,3 @@ Versioned simulation apps deployed from this release define their workers only as the `SimulationWorker` and `SimulationSegmentWorker` classes. The plain `run_simulation` and `run_simulation_segment` functions, which served callers still running the code from before the classes, are removed. -The gateway now spawns annual simulations only through the `SimulationWorker` class, and no longer falls back to the plain `run_simulation` function of apps deployed before the classes. A request routed to one of those apps (every policyengine.py release before 6.20.0), whether pinned or after a rollback of `latest`, now fails instead of running there. +The gateway now spawns comparison simulations only through the `SimulationWorker` class, and no longer falls back to the plain `run_simulation` function of apps deployed before the classes. A comparison request routed to one of those apps (every policyengine.py release before 6.20.0), whether pinned or after a rollback of `latest`, now fails instead of running there. Budget-window requests still run on those apps, which spawn their own yearly simulations. diff --git a/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/simulation_workers.py b/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/simulation_workers.py index 49817e69f..8d83c1f65 100644 --- a/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/simulation_workers.py +++ b/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/simulation_workers.py @@ -15,8 +15,8 @@ deployed app, so both read them from here. Apps deployed before the workers were classes define ``run_simulation`` as a -plain Modal function instead. The gateway spawns only through the class, so it -runs no simulation on those apps. +plain Modal function instead. The gateway spawns comparison simulations only +through the class, so it can't run them on those apps. """ SIMULATION_WORKER_CLASS = "SimulationWorker" diff --git a/projects/policyengine-simulation-executor/README.md b/projects/policyengine-simulation-executor/README.md index 6e2e21a41..73ed145b9 100644 --- a/projects/policyengine-simulation-executor/README.md +++ b/projects/policyengine-simulation-executor/README.md @@ -54,6 +54,9 @@ and deployment-run rollback restore that state only while the corresponding publication is still active. Manual rollback checks the plan inventory across all run attempts before restoring the chain. A version-mode rollback instead moves latest to an already published version and keeps other versions pinnable. +The gateway runs comparison requests only on apps that define the +`SimulationWorker` class (policyengine.py 6.20.0 and later), so after a +rollback to an earlier release every unpinned comparison request fails. Routing writes and recovery use no lease or lock expiry wait. For a same-version redeploy that replaced a Modal app in place, redeploy the previous commit to recover its code; restoring routing alone cannot recover it. From 3a76c06dba8e7f9b3118116378bdbf1baca172a7 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:03:53 +0400 Subject: [PATCH 10/17] Test that rollbacks refuse to route latest to an app without the worker class The gateway now runs comparison requests only through an app's SimulationWorker class, which apps deployed before .py 6.20.0 don't define. Restoring latest to such an app, undoing a deployment's plans back to one, or recovering a pending publication onto one would fail every unpinned comparison request. These tests fail until the routing publisher checks the restored app first. The routing tests' fake Modal gains a Cls lookup in which every app defines the class unless a test says otherwise. Co-Authored-By: Claude Opus 5.5 --- .../tests/version_registry/conftest.py | 11 ++- .../version_registry/registry_test_support.py | 45 ++++++++++ .../test_routing_finalization.py | 26 ++++++ .../version_registry/test_routing_rollback.py | 86 ++++++++++++++++++- 4 files changed, 165 insertions(+), 3 deletions(-) diff --git a/projects/policyengine-simulation-executor/tests/version_registry/conftest.py b/projects/policyengine-simulation-executor/tests/version_registry/conftest.py index 30e380b34..414bd2f8e 100644 --- a/projects/policyengine-simulation-executor/tests/version_registry/conftest.py +++ b/projects/policyengine-simulation-executor/tests/version_registry/conftest.py @@ -5,7 +5,7 @@ from typing import TYPE_CHECKING import pytest -from registry_test_support import FakeDict +from registry_test_support import FakeDict, FakeWorkerClassLookups from src.modal.routing_publisher import bundles as routing_bundles from src.modal.routing_publisher import stores as routing_stores @@ -25,7 +25,13 @@ def serialized_workflow(monkeypatch): @pytest.fixture -def patched_modal(monkeypatch, serialized_workflow): +def worker_class_lookups() -> FakeWorkerClassLookups: + """Record the versioned apps' class lookups; every app defines the class.""" + return FakeWorkerClassLookups() + + +@pytest.fixture +def patched_modal(monkeypatch, serialized_workflow, worker_class_lookups): stores: dict[str, FakeDict] = {} class _Dict: @@ -45,6 +51,7 @@ def from_name( class _Modal: Dict = _Dict + Cls = worker_class_lookups monkeypatch.setattr(routing_stores, "modal", _Modal) return stores diff --git a/projects/policyengine-simulation-executor/tests/version_registry/registry_test_support.py b/projects/policyengine-simulation-executor/tests/version_registry/registry_test_support.py index 9eb2601a2..a01c2ec4b 100644 --- a/projects/policyengine-simulation-executor/tests/version_registry/registry_test_support.py +++ b/projects/policyengine-simulation-executor/tests/version_registry/registry_test_support.py @@ -35,6 +35,51 @@ def hydrate(self): return self +class NotFoundError(Exception): + """Named like modal.exception.NotFoundError: the routing code matches the name.""" + + +class FakeWorkerClassLookups: + """``modal.Cls`` for the routing tests: records each class lookup. + + Every app defines the ``SimulationWorker`` class except the ones in + ``apps_without_worker_class``, such as apps deployed before the workers + were classes: resolving their class handle raises ``NotFoundError``. + """ + + def __init__(self) -> None: + self.apps_without_worker_class: set[str] = set() + self.lookups: list[tuple[str, str, str]] = [] + + def from_name( + self, app_name: str, class_name: str, *, environment_name: str + ) -> FakeWorkerClassHandle: + self.lookups.append((environment_name, app_name, class_name)) + return FakeWorkerClassHandle( + app_name, + class_name, + defined=app_name not in self.apps_without_worker_class, + ) + + +class FakeWorkerClassHandle: + """A lazy class handle: resolving it raises if the app has no such class.""" + + def __init__(self, app_name: str, class_name: str, *, defined: bool) -> None: + self.app_name = app_name + self.class_name = class_name + self.defined = defined + + def hydrate(self) -> FakeWorkerClassHandle: + if not self.defined: + msg = ( + f"Lookup failed for Cls '{self.class_name}' " + f"from the '{self.app_name}' app" + ) + raise NotFoundError(msg) + return self + + def _country(country: str, model_version: str) -> registry.CountryBundleMetadata: return { "country": country, diff --git a/projects/policyengine-simulation-executor/tests/version_registry/test_routing_finalization.py b/projects/policyengine-simulation-executor/tests/version_registry/test_routing_finalization.py index 20c14c504..ab666ab42 100644 --- a/projects/policyengine-simulation-executor/tests/version_registry/test_routing_finalization.py +++ b/projects/policyengine-simulation-executor/tests/version_registry/test_routing_finalization.py @@ -10,6 +10,7 @@ install_routing_store, publication_plan, published_routing_state, + versioned_app_name, ) from src.modal.routing_publisher import publication as routing_publication from src.modal.utils import update_version_registry as registry @@ -356,6 +357,31 @@ def test_operator_restores_any_valid_pending_plan_in_the_selected_store( assert store.get("publication") == {"status": "restored", "plan": pending} +def test_operator_recovery_never_routes_latest_to_an_app_without_the_worker_class( + monkeypatch, patched_modal, worker_class_lookups +): + """The gateway can't run comparisons on apps from before .py 6.20.0.""" + before = published_routing_state(monkeypatch, None, "6.17.1", "1.1.0", "2.1.0") + store = install_routing_store(patched_modal, before) + pending = publication_plan( + monkeypatch, + before, + ("6.20.0", "1.1.0", "2.2.0"), + publication_id="74401-1-beta", + ) + registry.record_routing_plan(environment="staging", plan=pending) + registry.apply_routing_plan(environment="staging", plan=pending) + worker_class_lookups.apps_without_worker_class.add(versioned_app_name("6.17.1")) + + with pytest.raises(ValueError, match="defines no SimulationWorker class"): + registry.finalize_routing_publication( + environment="staging", release_environment="beta", gates_passed=False + ) + + assert store.get("active") == pending["after"] + assert store.get("publication") == {"status": "pending", "plan": pending} + + @pytest.mark.parametrize("status", ["pending", "completed", "restored"]) def test_publication_records_are_read_back(monkeypatch, patched_modal, status): before = published_routing_state(monkeypatch, None, "6.0.0", "1.1.0", "2.1.0") diff --git a/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py b/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py index 7b4a94fc0..806a3cfc4 100644 --- a/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py +++ b/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py @@ -9,6 +9,7 @@ from hypothesis import strategies as st from registry_test_support import ( FakeDict, + FakeWorkerClassLookups, install_bundle_manifests, install_routing_store, publication_plan, @@ -71,7 +72,10 @@ def from_name(name, environment_name, create_if_missing): stores[key] = FakeDict() return stores[key] - monkeypatch.setattr(routing_stores, "modal", type("M", (), {"Dict": _Dict})) + modal_with_worker_classes = type( + "M", (), {"Dict": _Dict, "Cls": FakeWorkerClassLookups()} + ) + monkeypatch.setattr(routing_stores, "modal", modal_with_worker_classes) state = None if legacy: # A route seeded from the legacy dicts, with no manifest. @@ -357,6 +361,86 @@ def test_a_chain_of_attempts_is_undone_in_order(monkeypatch, patched_modal): ) +# --- Rollback never routes latest to an app without the worker class ---------- +# +# The gateway spawns comparison requests only through an app's +# SimulationWorker class, which apps deployed before policyengine.py 6.20.0 +# don't define. A rollback that routed latest to one would fail every unpinned +# comparison request, so it is refused and routing is left as it was. + + +def test_restoring_latest_checks_that_its_app_defines_the_worker_class( + monkeypatch, patched_modal, worker_class_lookups +): + state = published_routing_state(monkeypatch, None, "6.20.0", "1.1.0", "2.1.0") + state = published_routing_state(monkeypatch, state, "6.20.3", "1.1.0", "2.2.0") + store = install_routing_store(patched_modal, state) + + restored = registry.restore_routing_state( + environment="staging", policyengine_version="6.20.0" + ) + + assert restored["latest"]["policyengine"] == "6.20.0" + assert store.get("active") == restored + assert worker_class_lookups.lookups == [ + ("staging", versioned_app_name("6.20.0"), "SimulationWorker") + ] + + +def test_restoring_latest_refuses_an_app_without_the_worker_class( + monkeypatch, patched_modal, worker_class_lookups +): + state = published_routing_state(monkeypatch, None, "6.17.1", "1.1.0", "2.1.0") + state = published_routing_state(monkeypatch, state, "6.20.0", "1.1.0", "2.2.0") + store = install_routing_store(patched_modal, state) + worker_class_lookups.apps_without_worker_class.add(versioned_app_name("6.17.1")) + + with pytest.raises(ValueError, match="defines no SimulationWorker class"): + registry.restore_routing_state( + environment="staging", policyengine_version="6.17.1" + ) + + assert store.get("active") == json.loads(json.dumps(state)) + + +def test_undoing_plans_checks_the_app_each_restored_state_routes_latest_to( + monkeypatch, patched_modal, worker_class_lookups +): + original = published_routing_state(monkeypatch, None, "6.20.0", "1.1.0", "2.1.0") + store = install_routing_store(patched_modal, original) + release = publication_plan(monkeypatch, original, ("6.20.3", "1.2.0", "2.2.0")) + registry.apply_routing_plan(environment="staging", plan=release) + + assert ( + registry.restore_routing_plans(environment="staging", plans=[release]) + == "restored" + ) + + assert store.get("active") == json.loads(json.dumps(original)) + assert worker_class_lookups.lookups == [ + ("staging", versioned_app_name("6.20.0"), "SimulationWorker") + ] + + +def test_undoing_plans_writes_nothing_if_any_restored_state_has_no_worker_class( + monkeypatch, patched_modal, worker_class_lookups +): + original = published_routing_state(monkeypatch, None, "6.17.1", "1.1.0", "2.1.0") + store = install_routing_store(patched_modal, original) + first = publication_plan(monkeypatch, original, ("6.20.0", "1.1.0", "2.2.0")) + registry.apply_routing_plan(environment="staging", plan=first) + second = publication_plan(monkeypatch, first["after"], ("6.20.3", "1.2.0", "2.2.0")) + registry.apply_routing_plan(environment="staging", plan=second) + worker_class_lookups.apps_without_worker_class.add(versioned_app_name("6.17.1")) + + # Undoing the second plan alone would route latest to 6.20.0, which has + # the class; undoing the first as well would route it to 6.17.1. + with pytest.raises(ValueError, match="defines no SimulationWorker class"): + registry.restore_routing_plans(environment="staging", plans=[first, second]) + + assert store.get("active") == second["after"] + + @pytest.mark.usefixtures("serialized_workflow") def test_main_restores_several_plans(patched_modal, monkeypatch, capsys, tmp_path): a = published_routing_state(monkeypatch, None, "6.0.0", "1.1.0", "2.1.0") From 91cd1d81701737b0f07c67ff6023d69122208247 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:06:11 +0400 Subject: [PATCH 11/17] Refuse to route latest to an app without the SimulationWorker class The gateway runs comparison requests only through an app's SimulationWorker class, which apps deployed before .py 6.20.0 don't define. Restoring latest with --restore-latest, and undoing plans with --restore-plan or --finalize-publication, now look the class up in the app each restored state routes latest to, and refuse before writing anything when Modal finds none. That covers all three ways of the rollback workflow and the deploy workflow's own restores. The plan restore now works out every state it would write before writing the first, so a refusal never leaves routing half restored. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/simulation-rollback.yml | 10 +-- changelog.d/1130.removed.md | 2 + .../README.md | 6 +- .../modal/routing_publisher/publication.py | 67 +++++++++++++------ .../src/modal/routing_publisher/stores.py | 46 ++++++++++++- 5 files changed, 104 insertions(+), 27 deletions(-) diff --git a/.github/workflows/simulation-rollback.yml b/.github/workflows/simulation-rollback.yml index 516ecad00..87a6e9a96 100644 --- a/.github/workflows/simulation-rollback.yml +++ b/.github/workflows/simulation-rollback.yml @@ -16,10 +16,12 @@ name: Roll back Simulation API # state is what it published, so it never overwrites a later release; the # failed release's routes go too. # - policyengine_version: point latest at that published release. Other -# releases, including the failed one, stay pinnable. The gateway runs -# comparison requests only on apps that define the SimulationWorker class -# (policyengine.py 6.20.0 and later), so after a rollback to an earlier -# release every unpinned comparison request fails. +# releases, including the failed one, stay pinnable. +# +# The gateway runs comparison requests only on apps that define the +# SimulationWorker class (policyengine.py 6.20.0 and later), so each way +# refuses to route latest to an app Modal finds without that class, and +# leaves routing unchanged. on: workflow_dispatch: diff --git a/changelog.d/1130.removed.md b/changelog.d/1130.removed.md index 2c86faa9a..0a7a4313b 100644 --- a/changelog.d/1130.removed.md +++ b/changelog.d/1130.removed.md @@ -1,3 +1,5 @@ Versioned simulation apps deployed from this release define their workers only as the `SimulationWorker` and `SimulationSegmentWorker` classes. The plain `run_simulation` and `run_simulation_segment` functions, which served callers still running the code from before the classes, are removed. The gateway now spawns comparison simulations only through the `SimulationWorker` class, and no longer falls back to the plain `run_simulation` function of apps deployed before the classes. A comparison request routed to one of those apps (every policyengine.py release before 6.20.0), whether pinned or after a rollback of `latest`, now fails instead of running there. Budget-window requests still run on those apps, which spawn their own yearly simulations. + +Rollbacks, and the deploy workflow's restore after a release fails its checks, now refuse to route `latest` to an app that defines no `SimulationWorker` class, and leave routing unchanged. diff --git a/projects/policyengine-simulation-executor/README.md b/projects/policyengine-simulation-executor/README.md index 73ed145b9..10065bb5b 100644 --- a/projects/policyengine-simulation-executor/README.md +++ b/projects/policyengine-simulation-executor/README.md @@ -55,8 +55,10 @@ publication is still active. Manual rollback checks the plan inventory across all run attempts before restoring the chain. A version-mode rollback instead moves latest to an already published version and keeps other versions pinnable. The gateway runs comparison requests only on apps that define the -`SimulationWorker` class (policyengine.py 6.20.0 and later), so after a -rollback to an earlier release every unpinned comparison request fails. +`SimulationWorker` class (policyengine.py 6.20.0 and later). So every +restore refuses to route latest to an app that Modal finds without that +class, and leaves routing unchanged: recovery, deployment-run rollback, +version-mode rollback, and a deployment's own restore after a failed check. Routing writes and recovery use no lease or lock expiry wait. For a same-version redeploy that replaced a Modal app in place, redeploy the previous commit to recover its code; restoring routing alone cannot recover it. diff --git a/projects/policyengine-simulation-executor/src/modal/routing_publisher/publication.py b/projects/policyengine-simulation-executor/src/modal/routing_publisher/publication.py index 9bb2f1631..587c2eb1f 100644 --- a/projects/policyengine-simulation-executor/src/modal/routing_publisher/publication.py +++ b/projects/policyengine-simulation-executor/src/modal/routing_publisher/publication.py @@ -14,7 +14,10 @@ ROUTING_PUBLICATION_KEY, ROUTING_STATE_ACTIVE_KEY, ) -from src.modal.routing_publisher.stores import routing_store +from src.modal.routing_publisher.stores import ( + require_latest_app_defines_worker_class, + routing_store, +) from src.modal.routing_publisher.writers import require_serialized_routing_workflow if TYPE_CHECKING: @@ -105,7 +108,9 @@ def restore_routing_plans(*, environment: str, plans: list[dict]) -> str: skipping plans that changed nothing, until no plan's published state is live. ``unchanged`` means the live state is a starting state no plan replaced (nothing was applied, or it was already - undone). Any other live state is a conflict and nothing is changed. + undone). Any other live state is a conflict and nothing is changed, and + so is a restore that would route ``latest`` to an app without the worker + class. """ require_serialized_routing_workflow() for plan in plans: @@ -121,40 +126,62 @@ def restore_routing_plans(*, environment: str, plans: list[dict]) -> str: return "unchanged" msg = "there is no routing state to restore into" raise RoutingConflictError(msg) - outcome = _restore_live_plans(store, plans) + outcome = _restore_live_plans(store, plans, environment=environment) if pending is not None: write_publication_record(store, plan=pending, status="restored") return outcome -def _restore_live_plans(store: "modal.Dict", plans: list[dict]) -> str: +def _restore_live_plans( + store: "modal.Dict", plans: list[dict], *, environment: str +) -> str: """Restore each live plan's starting state, the one given last first. - Returns ``restored``, or ``unchanged`` when the live state is a starting - state no plan replaced; any other live state is a conflict. + Every state it would write is checked first, and if any routes ``latest`` + to an app without the worker class, nothing is written + (:func:`require_latest_app_defines_worker_class`). Returns ``restored``, + or ``unchanged`` when the live state is a starting state no plan + replaced; any other live state is a conflict. + """ + digest = routing_state_digest(store.get(ROUTING_STATE_ACTIVE_KEY)) + plans_to_undo = _plans_to_undo(plans, live_digest=digest) + if not plans_to_undo: + if not any(plan["before_sha256"] == digest for plan in plans): + msg = ( + "the routing state is neither what this release replaced nor " + "what it published; another change was made, so nothing was " + "restored" + ) + raise RoutingConflictError(msg) + return "unchanged" + for plan in plans_to_undo: + require_latest_app_defines_worker_class(plan["before"], environment=environment) + for plan in plans_to_undo: + _write_starting_state(store, plan) + return "restored" + + +def _plans_to_undo(plans: list[dict], *, live_digest: str) -> list[dict]: + """Return the plans to undo from the live state, in the order to undo them. + + A plan is undone when the state it published is live, which makes its + starting state live; that may be another plan's published state, which is + undone next. Plans that changed nothing are skipped, and when several + plans published the live state, the one given last is undone. """ remaining = [ plan for plan in plans if plan["before_sha256"] != plan["after_sha256"] ] - outcome = "unchanged" + plans_to_undo = [] + digest = live_digest while True: - digest = routing_state_digest(store.get(ROUTING_STATE_ACTIVE_KEY)) live = [plan for plan in remaining if plan["after_sha256"] == digest] if not live: - break + return plans_to_undo plan = live[-1] remaining.remove(plan) - _write_starting_state(store, plan) - outcome = "restored" - if outcome == "unchanged" and not any( - plan["before_sha256"] == digest for plan in plans - ): - msg = ( - "the routing state is neither what this release replaced nor what " - "it published; another change was made, so nothing was restored" - ) - raise RoutingConflictError(msg) - return outcome + plans_to_undo.append(plan) + digest = plan["before_sha256"] def _write_starting_state(store: "modal.Dict", plan: dict) -> None: diff --git a/projects/policyengine-simulation-executor/src/modal/routing_publisher/stores.py b/projects/policyengine-simulation-executor/src/modal/routing_publisher/stores.py index 764d214ba..a18436673 100644 --- a/projects/policyengine-simulation-executor/src/modal/routing_publisher/stores.py +++ b/projects/policyengine-simulation-executor/src/modal/routing_publisher/stores.py @@ -1,5 +1,6 @@ """Open the routing Modal Dicts, and write whole routing states to them.""" +from policyengine_simulation_contract.simulation_workers import SIMULATION_WORKER_CLASS from src.modal.routing_publisher.legacy import ( build_legacy_seed_routing_state, merge_legacy_seed_into_current, @@ -47,6 +48,44 @@ def routing_store(environment: str, *, create_if_missing: bool) -> "modal.Dict | return store +class LatestAppWithoutWorkerClassError(ValueError): + """A routing change would route ``latest`` to an app without the worker class.""" + + +def require_latest_app_defines_worker_class(state: object, *, environment: str) -> None: + """Refuse a routing state whose ``latest`` app can't run comparison requests. + + The gateway spawns comparison requests only through an app's + ``SimulationWorker`` class, which apps deployed before policyengine.py + 6.20.0 don't define, so routing ``latest`` to one of them would fail every + unpinned comparison request. Raises ``LatestAppWithoutWorkerClassError`` + when Modal finds no such class in the app, or no such app. A state that + routes ``latest`` to no app is not this check's concern. + """ + routing = coerce_routing_state(state) + version = routing["latest"].get("policyengine") + app_name = routing["routes"]["policyengine"].get(version) if version else None + if not app_name: + return + worker_class = modal.Cls.from_name( + app_name, SIMULATION_WORKER_CLASS, environment_name=environment + ) + try: + worker_class.hydrate() + except Exception as exc: + if exc.__class__.__name__ != "NotFoundError": + raise + msg = ( + f"policyengine {version} routes to {app_name}, which defines no " + f"{SIMULATION_WORKER_CLASS} class in Modal environment {environment}. " + "The gateway runs comparison requests only through that class, which " + "apps deployed before policyengine.py 6.20.0 don't define, so routing " + "latest there would fail every unpinned comparison request; routing " + "is unchanged" + ) + raise LatestAppWithoutWorkerClassError(msg) from exc + + def modal_dict_snapshot( *, name: str, @@ -151,7 +190,11 @@ def restore_routing_state( policyengine_version: str, expected_latest: str | None = None, ) -> RoutingState: - """Point ``latest`` back at a published policyengine.py version and store it.""" + """Point ``latest`` back at a published policyengine.py version and store it. + + Refuses, writing nothing, a version whose app defines no worker class + (:func:`require_latest_app_defines_worker_class`). + """ require_serialized_routing_workflow() store = modal.Dict.from_name( ROUTING_STATE_DICT_NAME, @@ -164,5 +207,6 @@ def restore_routing_state( policyengine_version=policyengine_version, expected_latest=expected_latest, ) + require_latest_app_defines_worker_class(next_state, environment=environment) store[ROUTING_STATE_ACTIVE_KEY] = next_state return next_state From 5eda3860e2e3475d925d561394fa6cadee699de0 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:47:59 +0400 Subject: [PATCH 12/17] Test that only rollbacks of finished releases refuse an app without the class Undoing an unfinished publication (the deploy workflow's restore after a failed check, or resolve_pending_publication) must put back what it replaced: refusing leaves the publication pending, and every later routing write refuses while one is. A restore that leaves latest on the app it is on changes no request's routing, so it needs no class either. These tests fail until the check is narrowed. A test also checks that a Modal error other than NotFoundError stops the rollback unchanged. Co-Authored-By: Claude Opus 5.5 --- .../version_registry/registry_test_support.py | 29 +++--- .../test_routing_finalization.py | 13 +-- .../version_registry/test_routing_rollback.py | 90 ++++++++++++++++++- 3 files changed, 109 insertions(+), 23 deletions(-) diff --git a/projects/policyengine-simulation-executor/tests/version_registry/registry_test_support.py b/projects/policyengine-simulation-executor/tests/version_registry/registry_test_support.py index a01c2ec4b..a0eaa1136 100644 --- a/projects/policyengine-simulation-executor/tests/version_registry/registry_test_support.py +++ b/projects/policyengine-simulation-executor/tests/version_registry/registry_test_support.py @@ -45,38 +45,35 @@ class FakeWorkerClassLookups: Every app defines the ``SimulationWorker`` class except the ones in ``apps_without_worker_class``, such as apps deployed before the workers were classes: resolving their class handle raises ``NotFoundError``. + Resolving the class of an app in ``lookup_errors`` raises that error. """ def __init__(self) -> None: self.apps_without_worker_class: set[str] = set() + self.lookup_errors: dict[str, Exception] = {} self.lookups: list[tuple[str, str, str]] = [] def from_name( self, app_name: str, class_name: str, *, environment_name: str ) -> FakeWorkerClassHandle: self.lookups.append((environment_name, app_name, class_name)) - return FakeWorkerClassHandle( - app_name, - class_name, - defined=app_name not in self.apps_without_worker_class, - ) + lookup_error = self.lookup_errors.get(app_name) + if lookup_error is None and app_name in self.apps_without_worker_class: + lookup_error = NotFoundError( + f"Lookup failed for Cls '{class_name}' from the '{app_name}' app" + ) + return FakeWorkerClassHandle(lookup_error) class FakeWorkerClassHandle: - """A lazy class handle: resolving it raises if the app has no such class.""" + """A lazy class handle: resolving it raises the app's lookup error, if any.""" - def __init__(self, app_name: str, class_name: str, *, defined: bool) -> None: - self.app_name = app_name - self.class_name = class_name - self.defined = defined + def __init__(self, lookup_error: Exception | None) -> None: + self.lookup_error = lookup_error def hydrate(self) -> FakeWorkerClassHandle: - if not self.defined: - msg = ( - f"Lookup failed for Cls '{self.class_name}' " - f"from the '{self.app_name}' app" - ) - raise NotFoundError(msg) + if self.lookup_error is not None: + raise self.lookup_error return self diff --git a/projects/policyengine-simulation-executor/tests/version_registry/test_routing_finalization.py b/projects/policyengine-simulation-executor/tests/version_registry/test_routing_finalization.py index ab666ab42..270fca9e2 100644 --- a/projects/policyengine-simulation-executor/tests/version_registry/test_routing_finalization.py +++ b/projects/policyengine-simulation-executor/tests/version_registry/test_routing_finalization.py @@ -357,10 +357,10 @@ def test_operator_restores_any_valid_pending_plan_in_the_selected_store( assert store.get("publication") == {"status": "restored", "plan": pending} -def test_operator_recovery_never_routes_latest_to_an_app_without_the_worker_class( +def test_operator_recovery_puts_back_what_the_publication_replaced_without_the_class( monkeypatch, patched_modal, worker_class_lookups ): - """The gateway can't run comparisons on apps from before .py 6.20.0.""" + """Refusing would leave the publication pending, which blocks every write.""" before = published_routing_state(monkeypatch, None, "6.17.1", "1.1.0", "2.1.0") store = install_routing_store(patched_modal, before) pending = publication_plan( @@ -373,13 +373,16 @@ def test_operator_recovery_never_routes_latest_to_an_app_without_the_worker_clas registry.apply_routing_plan(environment="staging", plan=pending) worker_class_lookups.apps_without_worker_class.add(versioned_app_name("6.17.1")) - with pytest.raises(ValueError, match="defines no SimulationWorker class"): + assert ( registry.finalize_routing_publication( environment="staging", release_environment="beta", gates_passed=False ) + == "restored" + ) - assert store.get("active") == pending["after"] - assert store.get("publication") == {"status": "pending", "plan": pending} + assert store.get("active") == before + assert store.get("publication") == {"status": "restored", "plan": pending} + assert worker_class_lookups.lookups == [] @pytest.mark.parametrize("status", ["pending", "completed", "restored"]) diff --git a/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py b/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py index 806a3cfc4..608ce6cf6 100644 --- a/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py +++ b/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py @@ -365,8 +365,11 @@ def test_a_chain_of_attempts_is_undone_in_order(monkeypatch, patched_modal): # # The gateway spawns comparison requests only through an app's # SimulationWorker class, which apps deployed before policyengine.py 6.20.0 -# don't define. A rollback that routed latest to one would fail every unpinned -# comparison request, so it is refused and routing is left as it was. +# don't define. A rollback of a finished release that would move latest to +# another app without the class would fail every unpinned comparison request, +# so it is refused and routing is left as it was. Undoing an unfinished +# publication always puts back what it replaced: refusing would leave the +# publication pending, and every later routing change refuses while one is. def test_restoring_latest_checks_that_its_app_defines_the_worker_class( @@ -441,6 +444,89 @@ def test_undoing_plans_writes_nothing_if_any_restored_state_has_no_worker_class( assert store.get("active") == second["after"] +def test_restoring_latest_to_the_release_it_is_on_needs_no_worker_class( + monkeypatch, patched_modal, worker_class_lookups +): + state = published_routing_state(monkeypatch, None, "6.17.1", "1.1.0", "2.1.0") + store = install_routing_store(patched_modal, state) + worker_class_lookups.apps_without_worker_class.add(versioned_app_name("6.17.1")) + + restored = registry.restore_routing_state( + environment="staging", policyengine_version="6.17.1" + ) + + # Latest stays on the app it was on, so no request routes differently. + assert restored["latest"]["policyengine"] == "6.17.1" + assert store.get("active") == restored + assert worker_class_lookups.lookups == [] + + +def test_undoing_a_plan_that_leaves_latest_where_it_is_needs_no_worker_class( + monkeypatch, patched_modal, worker_class_lookups +): + original = published_routing_state(monkeypatch, None, "6.17.1", "1.1.0", "2.1.0") + store = install_routing_store(patched_modal, original) + # An older release adds its routes without moving latest. + older_release = publication_plan( + monkeypatch, original, ("6.16.0", "1.0.0", "2.0.0") + ) + registry.apply_routing_plan(environment="staging", plan=older_release) + assert older_release["after"]["latest"] == original["latest"] + worker_class_lookups.apps_without_worker_class.add(versioned_app_name("6.17.1")) + + assert ( + registry.restore_routing_plans(environment="staging", plans=[older_release]) + == "restored" + ) + + assert store.get("active") == json.loads(json.dumps(original)) + assert worker_class_lookups.lookups == [] + + +def test_undoing_an_unfinished_publication_puts_back_what_it_replaced( + monkeypatch, patched_modal, worker_class_lookups +): + """A deployment's own restore after a failed check, without the class.""" + original = published_routing_state(monkeypatch, None, "6.17.1", "1.1.0", "2.1.0") + store = install_routing_store(patched_modal, original) + pending = publication_plan( + monkeypatch, + original, + ("6.20.0", "1.1.0", "2.2.0"), + publication_id="74401-1-beta", + ) + registry.record_routing_plan(environment="staging", plan=pending) + registry.apply_routing_plan(environment="staging", plan=pending) + worker_class_lookups.apps_without_worker_class.add(versioned_app_name("6.17.1")) + + assert ( + registry.restore_routing_plans(environment="staging", plans=[pending]) + == "restored" + ) + + assert store.get("active") == json.loads(json.dumps(original)) + assert store.get("publication") == {"status": "restored", "plan": pending} + assert worker_class_lookups.lookups == [] + + +def test_a_failed_worker_class_lookup_stops_the_rollback_and_writes_nothing( + monkeypatch, patched_modal, worker_class_lookups +): + state = published_routing_state(monkeypatch, None, "6.20.0", "1.1.0", "2.1.0") + state = published_routing_state(monkeypatch, state, "6.20.3", "1.1.0", "2.2.0") + store = install_routing_store(patched_modal, state) + lookup_failure = ConnectionError("Modal is unreachable") + worker_class_lookups.lookup_errors[versioned_app_name("6.20.0")] = lookup_failure + + with pytest.raises(ConnectionError) as raised: + registry.restore_routing_state( + environment="staging", policyengine_version="6.20.0" + ) + + assert raised.value is lookup_failure + assert store.get("active") == json.loads(json.dumps(state)) + + @pytest.mark.usefixtures("serialized_workflow") def test_main_restores_several_plans(patched_modal, monkeypatch, capsys, tmp_path): a = published_routing_state(monkeypatch, None, "6.0.0", "1.1.0", "2.1.0") From 525c04f861d2c3e38ca6c3e0c8127eac49f9a99f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:49:52 +0400 Subject: [PATCH 13/17] Refuse only rollbacks of finished releases that move latest Undoing an unfinished publication now always puts back what it replaced. Refusing it left the publication pending, and every later routing write, rollbacks included, refuses while one is. A restore is checked only when it moves latest.policyengine to a different app: one that leaves latest where it is changes where no request goes. The refusal message now says to roll back to a release from .py 6.20.0 on. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/simulation-rollback.yml | 8 +-- changelog.d/1130.removed.md | 4 +- .../README.md | 10 ++-- .../modal/routing_publisher/publication.py | 44 ++++++++++++----- .../src/modal/routing_publisher/stores.py | 49 +++++++++++++------ 5 files changed, 77 insertions(+), 38 deletions(-) diff --git a/.github/workflows/simulation-rollback.yml b/.github/workflows/simulation-rollback.yml index 87a6e9a96..d4a60b20c 100644 --- a/.github/workflows/simulation-rollback.yml +++ b/.github/workflows/simulation-rollback.yml @@ -19,9 +19,11 @@ name: Roll back Simulation API # releases, including the failed one, stay pinnable. # # The gateway runs comparison requests only on apps that define the -# SimulationWorker class (policyengine.py 6.20.0 and later), so each way -# refuses to route latest to an app Modal finds without that class, and -# leaves routing unchanged. +# SimulationWorker class (policyengine.py 6.20.0 and later). So deploy_run_id +# and policyengine_version refuse to move latest to another app Modal finds +# without that class, and leave routing unchanged. resolve_pending_publication +# always puts back what the unfinished publication replaced: every routing +# change refuses while one is pending. on: workflow_dispatch: diff --git a/changelog.d/1130.removed.md b/changelog.d/1130.removed.md index 0a7a4313b..ace884506 100644 --- a/changelog.d/1130.removed.md +++ b/changelog.d/1130.removed.md @@ -1,5 +1,5 @@ Versioned simulation apps deployed from this release define their workers only as the `SimulationWorker` and `SimulationSegmentWorker` classes. The plain `run_simulation` and `run_simulation_segment` functions, which served callers still running the code from before the classes, are removed. -The gateway now spawns comparison simulations only through the `SimulationWorker` class, and no longer falls back to the plain `run_simulation` function of apps deployed before the classes. A comparison request routed to one of those apps (every policyengine.py release before 6.20.0), whether pinned or after a rollback of `latest`, now fails instead of running there. Budget-window requests still run on those apps, which spawn their own yearly simulations. +The gateway now spawns comparison simulations only through the `SimulationWorker` class, and no longer falls back to the plain `run_simulation` function of apps deployed before the classes. A comparison request pinned to one of those apps (every policyengine.py release before 6.20.0) now fails instead of running there. Budget-window requests still run on those apps, which spawn their own yearly simulations. -Rollbacks, and the deploy workflow's restore after a release fails its checks, now refuse to route `latest` to an app that defines no `SimulationWorker` class, and leave routing unchanged. +A version-mode or deployment-run rollback of a finished release now refuses to move `latest` to another app that defines no `SimulationWorker` class, and leaves routing unchanged. Undoing an unfinished publication still puts back what it replaced. diff --git a/projects/policyengine-simulation-executor/README.md b/projects/policyengine-simulation-executor/README.md index 9cde82c23..7738bcd0f 100644 --- a/projects/policyengine-simulation-executor/README.md +++ b/projects/policyengine-simulation-executor/README.md @@ -55,10 +55,12 @@ publication is still active. Manual rollback checks the plan inventory across all run attempts before restoring the chain. A version-mode rollback instead moves latest to an already published version and keeps other versions pinnable. The gateway runs comparison requests only on apps that define the -`SimulationWorker` class (policyengine.py 6.20.0 and later). So every -restore refuses to route latest to an app that Modal finds without that -class, and leaves routing unchanged: recovery, deployment-run rollback, -version-mode rollback, and a deployment's own restore after a failed check. +`SimulationWorker` class (policyengine.py 6.20.0 and later). A version-mode or +deployment-run rollback of a finished release therefore refuses to move latest +to another app that Modal finds without that class, and leaves routing +unchanged. Undoing an unfinished publication (recovery, or a deployment's own +restore after a failed check) always puts back what it replaced, because every +routing change refuses while a publication is pending. Routing writes and recovery use no lease or lock expiry wait. For a same-version redeploy that replaced a Modal app in place, redeploy the previous commit to recover its code; restoring routing alone cannot recover it. diff --git a/projects/policyengine-simulation-executor/src/modal/routing_publisher/publication.py b/projects/policyengine-simulation-executor/src/modal/routing_publisher/publication.py index 587c2eb1f..98900e812 100644 --- a/projects/policyengine-simulation-executor/src/modal/routing_publisher/publication.py +++ b/projects/policyengine-simulation-executor/src/modal/routing_publisher/publication.py @@ -108,9 +108,14 @@ def restore_routing_plans(*, environment: str, plans: list[dict]) -> str: skipping plans that changed nothing, until no plan's published state is live. ``unchanged`` means the live state is a starting state no plan replaced (nothing was applied, or it was already - undone). Any other live state is a conflict and nothing is changed, and - so is a restore that would route ``latest`` to an app without the worker - class. + undone). Any other live state is a conflict and nothing is changed. + + With no publication pending, a restore that would move ``latest`` to an + app without the worker class raises ``LatestAppWithoutWorkerClassError`` + and changes nothing (:func:`require_latest_app_defines_worker_class`). + Undoing an unfinished publication always puts back what it replaced: + every later routing change refuses while a publication is pending, so + refusing to undo one would leave nothing that could. """ require_serialized_routing_workflow() for plan in plans: @@ -126,24 +131,34 @@ def restore_routing_plans(*, environment: str, plans: list[dict]) -> str: return "unchanged" msg = "there is no routing state to restore into" raise RoutingConflictError(msg) - outcome = _restore_live_plans(store, plans, environment=environment) + outcome = _restore_live_plans( + store, + plans, + environment=environment, + check_worker_class=pending is None, + ) if pending is not None: write_publication_record(store, plan=pending, status="restored") return outcome def _restore_live_plans( - store: "modal.Dict", plans: list[dict], *, environment: str + store: "modal.Dict", + plans: list[dict], + *, + environment: str, + check_worker_class: bool, ) -> str: """Restore each live plan's starting state, the one given last first. - Every state it would write is checked first, and if any routes ``latest`` - to an app without the worker class, nothing is written - (:func:`require_latest_app_defines_worker_class`). Returns ``restored``, - or ``unchanged`` when the live state is a starting state no plan - replaced; any other live state is a conflict. + With ``check_worker_class``, every state it would write is checked + first, and if any moves ``latest`` to an app without the worker class, + nothing is written (:func:`require_latest_app_defines_worker_class`). + Returns ``restored``, or ``unchanged`` when the live state is a starting + state no plan replaced; any other live state is a conflict. """ - digest = routing_state_digest(store.get(ROUTING_STATE_ACTIVE_KEY)) + live_state = store.get(ROUTING_STATE_ACTIVE_KEY) + digest = routing_state_digest(live_state) plans_to_undo = _plans_to_undo(plans, live_digest=digest) if not plans_to_undo: if not any(plan["before_sha256"] == digest for plan in plans): @@ -154,8 +169,11 @@ def _restore_live_plans( ) raise RoutingConflictError(msg) return "unchanged" - for plan in plans_to_undo: - require_latest_app_defines_worker_class(plan["before"], environment=environment) + if check_worker_class: + for plan in plans_to_undo: + require_latest_app_defines_worker_class( + plan["before"], live_state=live_state, environment=environment + ) for plan in plans_to_undo: _write_starting_state(store, plan) return "restored" diff --git a/projects/policyengine-simulation-executor/src/modal/routing_publisher/stores.py b/projects/policyengine-simulation-executor/src/modal/routing_publisher/stores.py index a18436673..8cfdda75a 100644 --- a/projects/policyengine-simulation-executor/src/modal/routing_publisher/stores.py +++ b/projects/policyengine-simulation-executor/src/modal/routing_publisher/stores.py @@ -52,20 +52,34 @@ class LatestAppWithoutWorkerClassError(ValueError): """A routing change would route ``latest`` to an app without the worker class.""" -def require_latest_app_defines_worker_class(state: object, *, environment: str) -> None: - """Refuse a routing state whose ``latest`` app can't run comparison requests. +def _latest_route(state: object) -> tuple[str | None, str | None]: + """Return the ``latest.policyengine`` version and the app it routes to.""" + routing = coerce_routing_state(state) + version = routing["latest"].get("policyengine") + app_name = routing["routes"]["policyengine"].get(version) if version else None + return version, app_name + + +def require_latest_app_defines_worker_class( + state: object, *, live_state: object, environment: str +) -> None: + """Refuse a routing state that moves ``latest`` to an app without the worker class. The gateway spawns comparison requests only through an app's ``SimulationWorker`` class, which apps deployed before policyengine.py - 6.20.0 don't define, so routing ``latest`` to one of them would fail every + 6.20.0 don't define, so moving ``latest`` to one of them would fail every unpinned comparison request. Raises ``LatestAppWithoutWorkerClassError`` - when Modal finds no such class in the app, or no such app. A state that - routes ``latest`` to no app is not this check's concern. + when Modal finds no such class in the app, or no such app; any other + Modal error is raised as it is. + + Only a move is checked: a state whose ``latest.policyengine`` routes to + the app the live state's does changes where no request goes. Nor is a + state with no routed ``latest.policyengine`` release; the gateway then + routes requests without a pin by the latest country model, or, with no + routing state at all, by the per-country Dicts from before it. """ - routing = coerce_routing_state(state) - version = routing["latest"].get("policyengine") - app_name = routing["routes"]["policyengine"].get(version) if version else None - if not app_name: + version, app_name = _latest_route(state) + if not app_name or app_name == _latest_route(live_state)[1]: return worker_class = modal.Cls.from_name( app_name, SIMULATION_WORKER_CLASS, environment_name=environment @@ -79,9 +93,9 @@ def require_latest_app_defines_worker_class(state: object, *, environment: str) f"policyengine {version} routes to {app_name}, which defines no " f"{SIMULATION_WORKER_CLASS} class in Modal environment {environment}. " "The gateway runs comparison requests only through that class, which " - "apps deployed before policyengine.py 6.20.0 don't define, so routing " - "latest there would fail every unpinned comparison request; routing " - "is unchanged" + "apps deployed before policyengine.py 6.20.0 don't define, so moving " + "latest there would fail every unpinned comparison request. Routing " + "is unchanged; roll back to a release from policyengine.py 6.20.0 on" ) raise LatestAppWithoutWorkerClassError(msg) from exc @@ -192,8 +206,8 @@ def restore_routing_state( ) -> RoutingState: """Point ``latest`` back at a published policyengine.py version and store it. - Refuses, writing nothing, a version whose app defines no worker class - (:func:`require_latest_app_defines_worker_class`). + Refuses, writing nothing, to move ``latest`` to an app that defines no + worker class (:func:`require_latest_app_defines_worker_class`). """ require_serialized_routing_workflow() store = modal.Dict.from_name( @@ -202,11 +216,14 @@ def restore_routing_state( create_if_missing=False, ) require_finished_publication(store) + live_state = store.get(ROUTING_STATE_ACTIVE_KEY) next_state = build_restored_routing_state( - current_state=store.get(ROUTING_STATE_ACTIVE_KEY), + current_state=live_state, policyengine_version=policyengine_version, expected_latest=expected_latest, ) - require_latest_app_defines_worker_class(next_state, environment=environment) + require_latest_app_defines_worker_class( + next_state, live_state=live_state, environment=environment + ) store[ROUTING_STATE_ACTIVE_KEY] = next_state return next_state From 9c7218c69d1506a5e5ee19684dc811ac69f1cc2e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:01:56 +0400 Subject: [PATCH 14/17] Test that a pending plan among kept plans exempts only its own undo A deployment-run rollback can pass a run's finished plans together with its rerun's pending one. Only the pending plan's own undo may skip the worker class check, so this test fails until the exemption is limited to it. A test also checks that a failed class lookup stops a plan restore unchanged. Co-Authored-By: Claude Opus 5.5 --- .../version_registry/test_routing_rollback.py | 53 ++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py b/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py index 608ce6cf6..1ed5d8b20 100644 --- a/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py +++ b/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py @@ -406,7 +406,7 @@ def test_restoring_latest_refuses_an_app_without_the_worker_class( assert store.get("active") == json.loads(json.dumps(state)) -def test_undoing_plans_checks_the_app_each_restored_state_routes_latest_to( +def test_undoing_a_plan_checks_the_app_its_starting_state_routes_latest_to( monkeypatch, patched_modal, worker_class_lookups ): original = published_routing_state(monkeypatch, None, "6.20.0", "1.1.0", "2.1.0") @@ -509,6 +509,57 @@ def test_undoing_an_unfinished_publication_puts_back_what_it_replaced( assert worker_class_lookups.lookups == [] +def test_only_the_unfinished_publication_among_kept_plans_skips_the_check( + monkeypatch, patched_modal, worker_class_lookups +): + """A run's earlier attempt finished; its rerun's publication is pending.""" + original = published_routing_state(monkeypatch, None, "6.17.1", "1.1.0", "2.1.0") + store = install_routing_store(patched_modal, original) + finished = publication_plan(monkeypatch, original, ("6.20.0", "1.1.0", "2.2.0")) + registry.apply_routing_plan(environment="staging", plan=finished) + pending = publication_plan( + monkeypatch, + finished["after"], + ("6.20.3", "1.2.0", "2.2.0"), + publication_id="74401-2-beta", + ) + registry.record_routing_plan(environment="staging", plan=pending) + registry.apply_routing_plan(environment="staging", plan=pending) + worker_class_lookups.apps_without_worker_class.add(versioned_app_name("6.17.1")) + + # Undoing the finished plan too would move latest to 6.17.1. + with pytest.raises(ValueError, match="defines no SimulationWorker class"): + registry.restore_routing_plans(environment="staging", plans=[finished, pending]) + + assert store.get("active") == pending["after"] + assert store.get("publication") == {"status": "pending", "plan": pending} + # Recovery still undoes the pending publication alone. + assert ( + registry.finalize_routing_publication( + environment="staging", release_environment="beta", gates_passed=False + ) + == "restored" + ) + assert store.get("active") == finished["after"] + + +def test_a_failed_worker_class_lookup_stops_undoing_plans_and_writes_nothing( + monkeypatch, patched_modal, worker_class_lookups +): + original = published_routing_state(monkeypatch, None, "6.20.0", "1.1.0", "2.1.0") + store = install_routing_store(patched_modal, original) + release = publication_plan(monkeypatch, original, ("6.20.3", "1.2.0", "2.2.0")) + registry.apply_routing_plan(environment="staging", plan=release) + lookup_failure = ConnectionError("Modal is unreachable") + worker_class_lookups.lookup_errors[versioned_app_name("6.20.0")] = lookup_failure + + with pytest.raises(ConnectionError) as raised: + registry.restore_routing_plans(environment="staging", plans=[release]) + + assert raised.value is lookup_failure + assert store.get("active") == release["after"] + + def test_a_failed_worker_class_lookup_stops_the_rollback_and_writes_nothing( monkeypatch, patched_modal, worker_class_lookups ): From 39397277853a31800a7bd8ce8655ff24ded89aa3 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:03:11 +0400 Subject: [PATCH 15/17] Exempt only the pending publication's own plan from the class check A deployment-run rollback can pass a run's finished plans together with its rerun's pending one, and the check was skipped for all of them. Now only the pending plan's own undo skips it, and the finished plans are checked. Refusing them leaves nothing stuck: resolve_pending_publication still undoes the pending plan alone. The README, the rollback workflow's header and the changelog now say which restores are checked, and that undoing a pending plan can put latest back on an app from before 6.20.0. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/simulation-rollback.yml | 11 +++-- changelog.d/1130.removed.md | 2 +- .../README.md | 15 +++--- .../modal/routing_publisher/publication.py | 46 +++++++++++-------- .../src/modal/routing_publisher/stores.py | 11 +++-- .../version_registry/test_routing_rollback.py | 10 ++-- 6 files changed, 55 insertions(+), 40 deletions(-) diff --git a/.github/workflows/simulation-rollback.yml b/.github/workflows/simulation-rollback.yml index d4a60b20c..71b3ccbd3 100644 --- a/.github/workflows/simulation-rollback.yml +++ b/.github/workflows/simulation-rollback.yml @@ -19,11 +19,12 @@ name: Roll back Simulation API # releases, including the failed one, stay pinnable. # # The gateway runs comparison requests only on apps that define the -# SimulationWorker class (policyengine.py 6.20.0 and later). So deploy_run_id -# and policyengine_version refuse to move latest to another app Modal finds -# without that class, and leave routing unchanged. resolve_pending_publication -# always puts back what the unfinished publication replaced: every routing -# change refuses while one is pending. +# SimulationWorker class (policyengine.py 6.20.0 and later). So a restore that +# would move latest to another app Modal finds without that class is refused, +# and routing is left unchanged. The exception is undoing the pending +# publication's own plan: resolve_pending_publication, or that plan among a +# deploy_run_id's plans, always puts back what it replaced, because every other +# routing change refuses while a publication is pending. on: workflow_dispatch: diff --git a/changelog.d/1130.removed.md b/changelog.d/1130.removed.md index ace884506..219ab3cb0 100644 --- a/changelog.d/1130.removed.md +++ b/changelog.d/1130.removed.md @@ -2,4 +2,4 @@ Versioned simulation apps deployed from this release define their workers only a The gateway now spawns comparison simulations only through the `SimulationWorker` class, and no longer falls back to the plain `run_simulation` function of apps deployed before the classes. A comparison request pinned to one of those apps (every policyengine.py release before 6.20.0) now fails instead of running there. Budget-window requests still run on those apps, which spawn their own yearly simulations. -A version-mode or deployment-run rollback of a finished release now refuses to move `latest` to another app that defines no `SimulationWorker` class, and leaves routing unchanged. Undoing an unfinished publication still puts back what it replaced. +A rollback that would move `latest` to another app that defines no `SimulationWorker` class is now refused, and routing is left unchanged. Undoing the pending publication's own plan still puts back what it replaced, so it can put `latest` back on an app from before 6.20.0 if `latest` was on one before that deployment; every unpinned comparison request then fails. diff --git a/projects/policyengine-simulation-executor/README.md b/projects/policyengine-simulation-executor/README.md index 7738bcd0f..b3859af39 100644 --- a/projects/policyengine-simulation-executor/README.md +++ b/projects/policyengine-simulation-executor/README.md @@ -55,12 +55,15 @@ publication is still active. Manual rollback checks the plan inventory across all run attempts before restoring the chain. A version-mode rollback instead moves latest to an already published version and keeps other versions pinnable. The gateway runs comparison requests only on apps that define the -`SimulationWorker` class (policyengine.py 6.20.0 and later). A version-mode or -deployment-run rollback of a finished release therefore refuses to move latest -to another app that Modal finds without that class, and leaves routing -unchanged. Undoing an unfinished publication (recovery, or a deployment's own -restore after a failed check) always puts back what it replaced, because every -routing change refuses while a publication is pending. +`SimulationWorker` class (policyengine.py 6.20.0 and later). A restore that +would move latest to another app that Modal finds without that class is +therefore refused, and routing is left unchanged. The one exception is +undoing the pending publication's own plan, which always puts back what it +replaced, because every other routing change refuses while a publication is +pending. That covers recovery and a deployment's restore of its own +unfinished publication after a failed step. It can put latest back on an +app from before policyengine.py 6.20.0, if latest was on one before that +deployment. Routing writes and recovery use no lease or lock expiry wait. For a same-version redeploy that replaced a Modal app in place, redeploy the previous commit to recover its code; restoring routing alone cannot recover it. diff --git a/projects/policyengine-simulation-executor/src/modal/routing_publisher/publication.py b/projects/policyengine-simulation-executor/src/modal/routing_publisher/publication.py index 98900e812..0f9849aba 100644 --- a/projects/policyengine-simulation-executor/src/modal/routing_publisher/publication.py +++ b/projects/policyengine-simulation-executor/src/modal/routing_publisher/publication.py @@ -110,12 +110,12 @@ def restore_routing_plans(*, environment: str, plans: list[dict]) -> str: starting state no plan replaced (nothing was applied, or it was already undone). Any other live state is a conflict and nothing is changed. - With no publication pending, a restore that would move ``latest`` to an - app without the worker class raises ``LatestAppWithoutWorkerClassError`` - and changes nothing (:func:`require_latest_app_defines_worker_class`). - Undoing an unfinished publication always puts back what it replaced: - every later routing change refuses while a publication is pending, so - refusing to undo one would leave nothing that could. + A restore that would move ``latest`` to an app without the worker class + raises ``LatestAppWithoutWorkerClassError`` and changes nothing + (:func:`require_latest_app_defines_worker_class`), with one exception: + undoing the pending publication's own plan always puts back what it + replaced. Every other routing change refuses while a publication is + pending, so refusing to undo it would leave nothing that could. """ require_serialized_routing_workflow() for plan in plans: @@ -135,27 +135,36 @@ def restore_routing_plans(*, environment: str, plans: list[dict]) -> str: store, plans, environment=environment, - check_worker_class=pending is None, + unfinished_plan=pending, ) if pending is not None: write_publication_record(store, plan=pending, status="restored") return outcome +def _is_same_plan(plan: dict, other: dict) -> bool: + """Whether two plans are one publication: same ID and the same two states.""" + return all( + plan.get(key) == other.get(key) + for key in ("publication_id", "before_sha256", "after_sha256") + ) + + def _restore_live_plans( store: "modal.Dict", plans: list[dict], *, environment: str, - check_worker_class: bool, + unfinished_plan: dict | None, ) -> str: """Restore each live plan's starting state, the one given last first. - With ``check_worker_class``, every state it would write is checked - first, and if any moves ``latest`` to an app without the worker class, - nothing is written (:func:`require_latest_app_defines_worker_class`). - Returns ``restored``, or ``unchanged`` when the live state is a starting - state no plan replaced; any other live state is a conflict. + Every state it would write is checked first, except the starting state of + ``unfinished_plan`` (the pending publication), and if any moves + ``latest`` to an app without the worker class, nothing is written + (:func:`require_latest_app_defines_worker_class`). Returns ``restored``, + or ``unchanged`` when the live state is a starting state no plan + replaced; any other live state is a conflict. """ live_state = store.get(ROUTING_STATE_ACTIVE_KEY) digest = routing_state_digest(live_state) @@ -169,11 +178,12 @@ def _restore_live_plans( ) raise RoutingConflictError(msg) return "unchanged" - if check_worker_class: - for plan in plans_to_undo: - require_latest_app_defines_worker_class( - plan["before"], live_state=live_state, environment=environment - ) + for plan in plans_to_undo: + if unfinished_plan is not None and _is_same_plan(plan, unfinished_plan): + continue + require_latest_app_defines_worker_class( + plan["before"], live_state=live_state, environment=environment + ) for plan in plans_to_undo: _write_starting_state(store, plan) return "restored" diff --git a/projects/policyengine-simulation-executor/src/modal/routing_publisher/stores.py b/projects/policyengine-simulation-executor/src/modal/routing_publisher/stores.py index 8cfdda75a..86a8d4163 100644 --- a/projects/policyengine-simulation-executor/src/modal/routing_publisher/stores.py +++ b/projects/policyengine-simulation-executor/src/modal/routing_publisher/stores.py @@ -72,11 +72,12 @@ def require_latest_app_defines_worker_class( when Modal finds no such class in the app, or no such app; any other Modal error is raised as it is. - Only a move is checked: a state whose ``latest.policyengine`` routes to - the app the live state's does changes where no request goes. Nor is a - state with no routed ``latest.policyengine`` release; the gateway then - routes requests without a pin by the latest country model, or, with no - routing state at all, by the per-country Dicts from before it. + Only a move is checked. If ``state`` routes ``latest.policyengine`` to + the same app as ``live_state`` does, no request would go anywhere new. + A state with no routed ``latest.policyengine`` release isn't checked + either: the gateway then routes requests without a pin by the latest + country model, or, with no routing state at all, by the per-country + Dicts from before it. """ version, app_name = _latest_route(state) if not app_name or app_name == _latest_route(live_state)[1]: diff --git a/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py b/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py index 1ed5d8b20..39c669943 100644 --- a/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py +++ b/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py @@ -365,11 +365,11 @@ def test_a_chain_of_attempts_is_undone_in_order(monkeypatch, patched_modal): # # The gateway spawns comparison requests only through an app's # SimulationWorker class, which apps deployed before policyengine.py 6.20.0 -# don't define. A rollback of a finished release that would move latest to -# another app without the class would fail every unpinned comparison request, -# so it is refused and routing is left as it was. Undoing an unfinished -# publication always puts back what it replaced: refusing would leave the -# publication pending, and every later routing change refuses while one is. +# don't define. A restore that would move latest to another app without the +# class would fail every unpinned comparison request, so it is refused and +# routing is left as it was. Undoing the pending publication's own plan always +# puts back what it replaced: refusing would leave the publication pending, and +# every other routing change refuses while one is. def test_restoring_latest_checks_that_its_app_defines_the_worker_class( From 8203cc3f8ee052c166e7d2e6ef21d0b9fd55d1f3 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:24:35 +0400 Subject: [PATCH 16/17] Test undoing a pending latest plan after its run's finished routes plan In the usual deployment-run layout, a completed routes plan is followed by a pending latest plan. Undoing the routes plan leaves latest where undoing the latest plan put it, so the rollback must not look the class up; the check compared it with the live state instead, and refused. The test of finished plans among a pending one now also expects the refusal to name resolve_pending_publication. Both fail until the fix. Co-Authored-By: Claude Opus 5.5 --- .../version_registry/test_routing_rollback.py | 43 ++++++++++++++++++- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py b/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py index 39c669943..178bf9b2e 100644 --- a/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py +++ b/projects/policyengine-simulation-executor/tests/version_registry/test_routing_rollback.py @@ -509,7 +509,41 @@ def test_undoing_an_unfinished_publication_puts_back_what_it_replaced( assert worker_class_lookups.lookups == [] -def test_only_the_unfinished_publication_among_kept_plans_skips_the_check( +def test_the_pending_plan_among_kept_plans_is_undone_without_the_check( + monkeypatch, patched_modal, worker_class_lookups +): + """A run's routes plan finished; its latest plan is pending, finalizer lost.""" + original = published_routing_state(monkeypatch, None, "6.17.1", "1.1.0", "2.1.0") + store = install_routing_store(patched_modal, original) + # An older release adds its routes without moving latest. + routes_plan = publication_plan(monkeypatch, original, ("6.16.0", "1.0.0", "2.0.0")) + registry.apply_routing_plan(environment="staging", plan=routes_plan) + assert routes_plan["after"]["latest"] == original["latest"] + latest_plan = publication_plan( + monkeypatch, + routes_plan["after"], + ("6.20.0", "1.1.0", "2.2.0"), + publication_id="74401-1-beta", + ) + registry.record_routing_plan(environment="staging", plan=latest_plan) + registry.apply_routing_plan(environment="staging", plan=latest_plan) + worker_class_lookups.apps_without_worker_class.add(versioned_app_name("6.17.1")) + + assert ( + registry.restore_routing_plans( + environment="staging", plans=[routes_plan, latest_plan] + ) + == "restored" + ) + + # The pending plan's undo is exempt, and the routes plan's leaves latest + # where that put it, so no class is looked up. + assert store.get("active") == json.loads(json.dumps(original)) + assert store.get("publication") == {"status": "restored", "plan": latest_plan} + assert worker_class_lookups.lookups == [] + + +def test_finished_plans_among_kept_plans_are_still_checked( monkeypatch, patched_modal, worker_class_lookups ): """A run's earlier attempt finished; its rerun's publication is pending.""" @@ -528,9 +562,14 @@ def test_only_the_unfinished_publication_among_kept_plans_skips_the_check( worker_class_lookups.apps_without_worker_class.add(versioned_app_name("6.17.1")) # Undoing the finished plan too would move latest to 6.17.1. - with pytest.raises(ValueError, match="defines no SimulationWorker class"): + with pytest.raises( + ValueError, match="defines no SimulationWorker class" + ) as refused: registry.restore_routing_plans(environment="staging", plans=[finished, pending]) + # A version rollback refuses while a publication is pending, so the + # message names the way that undoes it first. + assert "resolve_pending_publication" in str(refused.value) assert store.get("active") == pending["after"] assert store.get("publication") == {"status": "pending", "plan": pending} # Recovery still undoes the pending publication alone. From 60f0c1ec538dad6210d4b3ce5d69b197bab8ecbf Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:25:35 +0400 Subject: [PATCH 17/17] Check each undo against the state it writes over A plan's undo writes its starting state over its published state, so that is what decides whether it moves latest. Comparing with the live state from before the restore refused the usual deployment-run rollback: a finished routes plan, then a pending latest plan whose undo is exempt, where the routes plan's undo leaves latest where it is. The refusal now also says to undo a pending publication first with resolve_pending_publication. Co-Authored-By: Claude Opus 5.5 --- .../modal/routing_publisher/publication.py | 14 ++++++------- .../src/modal/routing_publisher/stores.py | 20 ++++++++++--------- 2 files changed, 18 insertions(+), 16 deletions(-) diff --git a/projects/policyengine-simulation-executor/src/modal/routing_publisher/publication.py b/projects/policyengine-simulation-executor/src/modal/routing_publisher/publication.py index 0f9849aba..effdedb11 100644 --- a/projects/policyengine-simulation-executor/src/modal/routing_publisher/publication.py +++ b/projects/policyengine-simulation-executor/src/modal/routing_publisher/publication.py @@ -159,15 +159,15 @@ def _restore_live_plans( ) -> str: """Restore each live plan's starting state, the one given last first. - Every state it would write is checked first, except the starting state of - ``unfinished_plan`` (the pending publication), and if any moves - ``latest`` to an app without the worker class, nothing is written - (:func:`require_latest_app_defines_worker_class`). Returns ``restored``, + Every plan's undo is checked first, except that of ``unfinished_plan`` + (the pending publication): each plan is live when it is undone, so its + undo writes its starting state over its published state. If any undo + moves ``latest`` to another app without the worker class, nothing is + written (:func:`require_latest_app_defines_worker_class`). Returns ``restored``, or ``unchanged`` when the live state is a starting state no plan replaced; any other live state is a conflict. """ - live_state = store.get(ROUTING_STATE_ACTIVE_KEY) - digest = routing_state_digest(live_state) + digest = routing_state_digest(store.get(ROUTING_STATE_ACTIVE_KEY)) plans_to_undo = _plans_to_undo(plans, live_digest=digest) if not plans_to_undo: if not any(plan["before_sha256"] == digest for plan in plans): @@ -182,7 +182,7 @@ def _restore_live_plans( if unfinished_plan is not None and _is_same_plan(plan, unfinished_plan): continue require_latest_app_defines_worker_class( - plan["before"], live_state=live_state, environment=environment + plan["before"], replaced_state=plan["after"], environment=environment ) for plan in plans_to_undo: _write_starting_state(store, plan) diff --git a/projects/policyengine-simulation-executor/src/modal/routing_publisher/stores.py b/projects/policyengine-simulation-executor/src/modal/routing_publisher/stores.py index 86a8d4163..9b91ba4b5 100644 --- a/projects/policyengine-simulation-executor/src/modal/routing_publisher/stores.py +++ b/projects/policyengine-simulation-executor/src/modal/routing_publisher/stores.py @@ -61,7 +61,7 @@ def _latest_route(state: object) -> tuple[str | None, str | None]: def require_latest_app_defines_worker_class( - state: object, *, live_state: object, environment: str + state: object, *, replaced_state: object, environment: str ) -> None: """Refuse a routing state that moves ``latest`` to an app without the worker class. @@ -73,14 +73,14 @@ def require_latest_app_defines_worker_class( Modal error is raised as it is. Only a move is checked. If ``state`` routes ``latest.policyengine`` to - the same app as ``live_state`` does, no request would go anywhere new. - A state with no routed ``latest.policyengine`` release isn't checked - either: the gateway then routes requests without a pin by the latest - country model, or, with no routing state at all, by the per-country - Dicts from before it. + the same app as ``replaced_state``, the state it is written over, + requests without a pin keep going to the same app. A state with no + routed ``latest.policyengine`` release isn't checked either: the gateway + then routes requests without a pin by the latest country model, or, + with no routing state at all, by the per-country Dicts from before it. """ version, app_name = _latest_route(state) - if not app_name or app_name == _latest_route(live_state)[1]: + if not app_name or app_name == _latest_route(replaced_state)[1]: return worker_class = modal.Cls.from_name( app_name, SIMULATION_WORKER_CLASS, environment_name=environment @@ -96,7 +96,9 @@ def require_latest_app_defines_worker_class( "The gateway runs comparison requests only through that class, which " "apps deployed before policyengine.py 6.20.0 don't define, so moving " "latest there would fail every unpinned comparison request. Routing " - "is unchanged; roll back to a release from policyengine.py 6.20.0 on" + "is unchanged. Roll back to a release from policyengine.py 6.20.0 on " + "instead; if a routing publication is pending, undo it first with " + "resolve_pending_publication" ) raise LatestAppWithoutWorkerClassError(msg) from exc @@ -224,7 +226,7 @@ def restore_routing_state( expected_latest=expected_latest, ) require_latest_app_defines_worker_class( - next_state, live_state=live_state, environment=environment + next_state, replaced_state=live_state, environment=environment ) store[ROUTING_STATE_ACTIVE_KEY] = next_state return next_state