diff --git a/.github/workflows/simulation-rollback.yml b/.github/workflows/simulation-rollback.yml index 0aea85ec2..71b3ccbd3 100644 --- a/.github/workflows/simulation-rollback.yml +++ b/.github/workflows/simulation-rollback.yml @@ -17,6 +17,14 @@ name: Roll back Simulation API # 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 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 new file mode 100644 index 000000000..219ab3cb0 --- /dev/null +++ b/changelog.d/1130.removed.md @@ -0,0 +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 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 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/docs/engineering/skills/observability.md b/docs/engineering/skills/observability.md index 2bde14bba..b763b0981 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,12 +234,13 @@ 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 - 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 apps deployed before the worker classes, whose workers load the models + 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). 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..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,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 comparison simulations only +through the class, so it can't run them 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/README.md b/projects/policyengine-simulation-executor/README.md index 8a8d61da6..b3859af39 100644 --- a/projects/policyengine-simulation-executor/README.md +++ b/projects/policyengine-simulation-executor/README.md @@ -54,6 +54,16 @@ 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). 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/app.py b/projects/policyengine-simulation-executor/src/modal/app.py index 605410f70..794be0187 100644 --- a/projects/policyengine-simulation-executor/src/modal/app.py +++ b/projects/policyengine-simulation-executor/src/modal/app.py @@ -466,11 +466,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() @@ -537,9 +537,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 = { @@ -661,49 +661,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, - # The same resources as SimulationSegmentWorker. - cpu=1.0, - memory=10240, - 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/src/modal/routing_publisher/publication.py b/projects/policyengine-simulation-executor/src/modal/routing_publisher/publication.py index 9bb2f1631..effdedb11 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: @@ -106,6 +109,13 @@ def restore_routing_plans(*, environment: str, plans: list[dict]) -> str: 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. + + 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: @@ -121,40 +131,85 @@ 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, + unfinished_plan=pending, + ) 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 _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, + unfinished_plan: dict | None, +) -> 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 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. + """ + 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: + if unfinished_plan is not None and _is_same_plan(plan, unfinished_plan): + continue + require_latest_app_defines_worker_class( + plan["before"], replaced_state=plan["after"], 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..9b91ba4b5 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,61 @@ 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 _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, *, replaced_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 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; any other + Modal error is raised as it is. + + Only a move is checked. If ``state`` routes ``latest.policyengine`` to + 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(replaced_state)[1]: + 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 moving " + "latest there would fail every unpinned comparison request. Routing " + "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 + + def modal_dict_snapshot( *, name: str, @@ -151,7 +207,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, 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( ROUTING_STATE_DICT_NAME, @@ -159,10 +219,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, replaced_state=live_state, environment=environment + ) store[ROUTING_STATE_ACTIVE_KEY] = next_state return next_state diff --git a/projects/policyengine-simulation-executor/tests/test_canonical_spm.py b/projects/policyengine-simulation-executor/tests/test_canonical_spm.py index 5ad58c479..67070cf62 100644 --- a/projects/policyengine-simulation-executor/tests/test_canonical_spm.py +++ b/projects/policyengine-simulation-executor/tests/test_canonical_spm.py @@ -722,15 +722,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 @@ -762,7 +759,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_job_progress.py b/projects/policyengine-simulation-executor/tests/test_job_progress.py index 1f3fc53ed..d473bf689 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,11 +1004,10 @@ def preempted(_params, *, runtime): assert _error_records(written_records) == [] -def test_the_segment_function_kept_for_older_callers_runs_the_same_code( +def test_a_segment_returns_its_result_and_records_success( modal_app, monkeypatch, recorded_observability_runtime ): - # Segmented parents started before the worker classes spawn their - # children through the plain run_simulation_segment function. + # The segmented parent reduces the results its children return. runtime, written_records = recorded_observability_runtime monkeypatch.setattr( modal_app, @@ -1040,7 +1018,11 @@ def test_the_segment_function_kept_for_older_callers_runs_the_same_code( sr, "run_simulation_impl", lambda _params, *, runtime: {"segment": "done"} ) - assert modal_app.run_simulation_segment({"country": "us"}) == {"segment": "done"} + segment_result = modal_app.SimulationSegmentWorker().run_simulation_segment( + {"country": "us"} + ) + + assert segment_result == {"segment": "done"} assert _operation_completions(written_records) == [("INFO", "success")] 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 ad315a306..66a45bae0 100644 --- a/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py +++ b/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py @@ -152,22 +152,6 @@ def test_simulation_workers_are_classes_restored_from_memory_snapshots(monkeypat "SimulationWorker": {**worker_options, **simulation_worker_resources}, "SimulationSegmentWorker": {**worker_options, **segment_worker_resources}, } - # Plain functions with the same names and resources 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, - **simulation_worker_resources, - } - assert function_options["run_simulation_segment"] == { - **function_form_options, - **segment_worker_resources, - } # The budget-window parent stays a small plain function with no snapshot. assert "enable_memory_snapshot" not in function_options["run_budget_window_batch"] @@ -193,8 +177,25 @@ 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): + 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, 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, + simulation_workers.SEGMENT_WORKER_METHOD, + ): + assert worker_method_name not in plain_function_names + assert not hasattr(app, worker_method_name) def test_both_simulation_workers_load_the_country_models_before_the_snapshot( 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" 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..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 @@ -35,6 +35,48 @@ 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``. + 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)) + 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 the app's lookup error, if any.""" + + def __init__(self, lookup_error: Exception | None) -> None: + self.lookup_error = lookup_error + + def hydrate(self) -> FakeWorkerClassHandle: + if self.lookup_error is not None: + raise self.lookup_error + 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..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 @@ -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,34 @@ def test_operator_restores_any_valid_pending_plan_in_the_selected_store( assert store.get("publication") == {"status": "restored", "plan": pending} +def test_operator_recovery_puts_back_what_the_publication_replaced_without_the_class( + monkeypatch, patched_modal, worker_class_lookups +): + """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( + 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")) + + assert ( + registry.finalize_routing_publication( + environment="staging", release_environment="beta", gates_passed=False + ) + == "restored" + ) + + 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"]) 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..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 @@ -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,262 @@ 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 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( + 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_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") + 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"] + + +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_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.""" + 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" + ) 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. + 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 +): + 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") diff --git a/projects/policyengine-simulation-gateway/fixtures/gateway_endpoints.py b/projects/policyengine-simulation-gateway/fixtures/gateway_endpoints.py index 6fe552215..3aa71be75 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 ( @@ -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" @@ -368,9 +362,10 @@ 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 + For an app in ``apps_without_worker_class``, such as one deployed before + 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``. """ @@ -379,40 +374,55 @@ 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 - - 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) - return self + 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 __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 +464,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 +510,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/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 ea0f66d37..98301e87b 100644 --- a/projects/policyengine-simulation-gateway/tests/test_simulation_submission.py +++ b/projects/policyengine-simulation-gateway/tests/test_simulation_submission.py @@ -70,58 +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": {}}, - ) - - # Then - assert response.status_code == 200 - assert response.json()["job_id"] == "mock-job-id-123" - 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 - - 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: + with pytest.raises(mock_modal["exception"].NotFoundError): 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 + # 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 is None + assert mock_modal["func"].calls == [] def test__given_submission__then_returns_job_id_and_poll_url( self, mock_modal, client: TestClient