Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/1141.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The v2 app's US and UK simulation workers and its US segment worker are now methods of Modal classes, `SimulationWorkerUS`, `SimulationWorkerUK` and `SimulationSegmentWorkerUS`, whose containers restore from memory snapshots with their own country's models already loaded, and for the US the SPM capability too. The report coordinator, the US worker's segment fan-out and the simulation entrypoint start them through the classes; the entrypoint falls back to the plain functions on apps deployed before the classes, and the v2 app keeps those functions, without snapshots, for callers still running older code. Deploying the v2 app now refuses Modal clients older than 1.6.4, as deploying the run_simulation app already did.
3 changes: 2 additions & 1 deletion docs/migration/stage-12-modal-worker-foundation.md
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,8 @@ naming the run reads: a row of API v1's `cliff_impacts`, one per
calculation. The simulation service inserts it pending when a report's
create or re-run asks for cliffs (`include_cliffs`, C1 · 39) and the run has
none that hasn't failed, starts the country's simulation worker
(`run_single_simulation_us` or `run_single_simulation_uk`) with the run's own
(`SimulationWorkerUS.run_single_simulation_us` or
`SimulationWorkerUK.run_single_simulation_uk`) with the run's own
simulation input, built as a standalone run's, and a context naming the row
(`Stage12InvocationContext.cliff_result_id`, left out of a context that names
none, which older workers refuse), and records the call. The worker
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""Names of the Modal classes that hold the v2 runtime's simulation workers.

The v2 application (``src/modal/v2_app.py`` in the executor) defines each
simulation worker as a method of a Modal class, so its containers restore from
a memory snapshot with the country's models already loaded:

- ``SimulationWorkerUS.run_single_simulation_us`` and
``SimulationWorkerUK.run_single_simulation_uk`` calculate one simulation.
The report coordinator spawns them for a report's simulations, and the entry
service for standalone simulation runs and cliff calculations.
- ``SimulationSegmentWorkerUS.run_single_simulation_segment_us`` calculates
one region group of a segmented US simulation, in its own container pool.

Each method has the name the worker had as a plain Modal function. That name
is stored data: the v2 version manifest's ``single_simulation_callable``, the
coordinator's context and the comparison-run rows all hold it. So callers keep
the stored name and look its class up here.

Apps deployed before the classes define the workers only as plain functions
with these names, and the v2 application keeps those functions for callers
still running older code.
"""

from __future__ import annotations

from types import MappingProxyType

SEGMENT_WORKER_CLASS = "SimulationSegmentWorkerUS"
SEGMENT_WORKER_METHOD = "run_single_simulation_segment_us"

_WORKER_CLASS_BY_METHOD = MappingProxyType(
{
"run_single_simulation_us": "SimulationWorkerUS",
"run_single_simulation_uk": "SimulationWorkerUK",
SEGMENT_WORKER_METHOD: SEGMENT_WORKER_CLASS,
}
)


def worker_class_name(method_name: str) -> str | None:
"""Return the Modal class whose method ``method_name`` is, or None.

None means the v2 application defines ``method_name`` only as a plain
function, as it does its coordinator and household functions.
"""
return _WORKER_CLASS_BY_METHOD.get(method_name)
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""The Modal classes the v2 runtime's simulation workers are reached through."""

import pytest
from policyengine_simulation_contract.household_execution import (
household_callable_name,
)
from policyengine_simulation_contract.stage12_simulation_workers import (
SEGMENT_WORKER_CLASS,
SEGMENT_WORKER_METHOD,
worker_class_name,
)


@pytest.mark.parametrize(
("method_name", "expected_class_name"),
[
("run_single_simulation_us", "SimulationWorkerUS"),
("run_single_simulation_uk", "SimulationWorkerUK"),
("run_single_simulation_segment_us", "SimulationSegmentWorkerUS"),
],
)
def test_each_simulation_worker_is_a_method_of_its_class_under_its_old_name(
method_name, expected_class_name
) -> None:
# The v2 version manifest, coordinator contexts and comparison-run rows
# store the worker's function name, so the same name reaches the method.
assert worker_class_name(method_name) == expected_class_name


def test_the_segment_worker_names_agree() -> None:
assert worker_class_name(SEGMENT_WORKER_METHOD) == SEGMENT_WORKER_CLASS


@pytest.mark.parametrize(
"function_name",
[
"coordinate_report",
household_callable_name("us"),
household_callable_name("uk"),
"validate_worker_us",
# The run_simulation app's worker, which no v2 caller names.
"run_simulation",
],
)
def test_the_v2_apps_other_functions_have_no_worker_class(function_name) -> None:
assert worker_class_name(function_name) is None
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
run's cliff calculation, by the same function in its cliff mode. Each is called by name
with ``spawn``, so a route waits only for Modal to accept the call, and is
given the run IDs it claims and records, never a Stage 12 evaluation
record.
record. The simulation function is a method of a Modal class, whose
containers restore from a memory snapshot with the models loaded, in apps
deployed since the classes; older apps define it as a plain function.

This is the economy path's own Modal access, apart from the Stage 12
comparison path's.
Expand All @@ -25,6 +27,9 @@
V2ManifestLoader,
manifest_digest,
)
from policyengine_simulation_contract.stage12_simulation_workers import (
worker_class_name,
)
from policyengine_simulation_persistence import RunVersions

from policyengine_simulation_entry.household_workers import (
Expand Down Expand Up @@ -231,9 +236,8 @@ async def start_simulation_run(

Raise RuntimeError when Modal returns no call ID.
"""
return await self._spawn(
return await self._spawn_simulation_worker(
worker,
worker.simulation_callable,
simulation_payload,
context_payload,
observability_context=observability_context,
Expand All @@ -252,10 +256,52 @@ async def start_cliff_calculation(
The context names the cliff calculation, which the function claims
and records. Raise RuntimeError when Modal returns no call ID.
"""
return await self._spawn_simulation_worker(
worker,
simulation_payload,
context_payload,
observability_context=observability_context,
)

async def _spawn_simulation_worker(
self,
worker: EconomyWorker,
payload: dict[str, Any],
context_payload: dict[str, Any],
*,
observability_context: dict[str, Any] | None,
) -> str:
"""Start the simulation worker's method on its class; return its call ID.

An app deployed before the workers were classes, which the manifest's
default can name after a move or a rollback, has no such class, so it
gets the plain function of the same name. Only the class lookup falls
back: once the class resolves, a failed spawn raises as it is.
"""
class_name = worker_class_name(worker.simulation_callable)
if class_name is not None:
worker_class = modal.Cls.from_name(
worker.application_name,
class_name,
environment_name=self._environment,
)
try:
await worker_class.hydrate.aio()
except modal.exception.NotFoundError:
pass
else:
method = getattr(worker_class(), worker.simulation_callable)
return await self._spawn_call(
method,
worker.simulation_callable,
payload,
context_payload,
observability_context=observability_context,
)
return await self._spawn(
worker,
worker.simulation_callable,
simulation_payload,
payload,
context_payload,
observability_context=observability_context,
)
Expand All @@ -274,6 +320,23 @@ async def _spawn(
function_name,
environment_name=self._environment,
)
return await self._spawn_call(
function,
function_name,
payload,
context_payload,
observability_context=observability_context,
)

@staticmethod
async def _spawn_call(
function: modal.Function,
function_name: str,
payload: dict[str, Any],
context_payload: dict[str, Any],
*,
observability_context: dict[str, Any] | None,
) -> str:
call = await function.spawn.aio(
payload, context_payload, observability_context=observability_context
)
Expand Down
125 changes: 113 additions & 12 deletions projects/policyengine-simulation-entry/tests/test_economy_workers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from types import SimpleNamespace
from typing import Any

import modal
import pytest
from economy_fixtures import economy_manifest, economy_worker_version
from household_fixtures import (
Expand Down Expand Up @@ -131,6 +132,53 @@ def from_name(application: str, name: str, *, environment_name: str):
return looked_up, function


# Each worker class defines only its own country's method.
WORKER_METHOD_BY_CLASS = {
"SimulationWorkerUS": "run_single_simulation_us",
"SimulationWorkerUK": "run_single_simulation_uk",
}


class FakeWorkerClass:
"""A Modal class looked up by name, whose worker method spawns ``method``.

The instance has only the looked-up class's method, under its name
(``method_name``). With ``deployed`` False, hydrating it fails as it does
for an app deployed before the workers were classes.
"""

def __init__(self, method: FakeFunction) -> None:
self.method = method
self.method_name: str | None = None
self.deployed = True
self.hydrate = SimpleNamespace(aio=self._hydrate)

async def _hydrate(self) -> FakeWorkerClass:
if not self.deployed:
msg = "the app defines no such class"
raise modal.exception.NotFoundError(msg)
return self

def __call__(self) -> SimpleNamespace:
assert self.method_name is not None
return SimpleNamespace(**{self.method_name: self.method})


@pytest.fixture
def modal_worker_classes(monkeypatch):
"""Replace Modal's class lookup by name; return the lookups and the class."""
looked_up: list[tuple[str, str, str]] = []
worker_class = FakeWorkerClass(FakeFunction("fc-started-on-the-class"))

def from_name(application: str, name: str, *, environment_name: str):
looked_up.append((application, name, environment_name))
worker_class.method_name = WORKER_METHOD_BY_CLASS[name]
return worker_class

monkeypatch.setattr(economy_workers.modal.Cls, "from_name", staticmethod(from_name))
return looked_up, worker_class


def test_a_report_run_starts_the_coordinator_with_its_report_and_context(
modal_functions,
) -> None:
Expand All @@ -157,10 +205,11 @@ def test_a_report_run_starts_the_coordinator_with_its_report_and_context(
]


def test_a_standalone_run_starts_the_countrys_simulation_function(
modal_functions,
def test_a_standalone_run_starts_the_countrys_simulation_worker_class(
modal_functions, modal_worker_classes
) -> None:
looked_up, function = modal_functions
looked_up_functions, _function = modal_functions
looked_up_classes, worker_class = modal_worker_classes
worker = default_economy_worker(economy_manifest(), "uk")

call_id = asyncio.run(
Expand All @@ -172,21 +221,27 @@ def test_a_standalone_run_starts_the_countrys_simulation_function(
)
)

assert call_id == "fc-started"
assert looked_up == [(worker.application_name, "run_single_simulation_uk", "main")]
assert function.spawns == [
# The class's containers restore from a memory snapshot with the models
# loaded; the manifest names the worker by its method.
assert call_id == "fc-started-on-the-class"
assert looked_up_classes == [
(worker.application_name, "SimulationWorkerUK", "main")
]
assert looked_up_functions == []
assert worker_class.method.spawns == [
(
({"simulation": 1}, {"simulation_run_id": "run"}),
{"observability_context": None},
)
]


def test_a_cliff_calculation_starts_the_countrys_simulation_function(
modal_functions,
def test_a_cliff_calculation_starts_the_countrys_simulation_worker_class(
modal_functions, modal_worker_classes
) -> None:
"""C1 · 38's cliff mode: the context names the cliff result, not a run."""
looked_up, function = modal_functions
looked_up_functions, _function = modal_functions
looked_up_classes, worker_class = modal_worker_classes
worker = default_economy_worker(economy_manifest(), "uk")

call_id = asyncio.run(
Expand All @@ -198,16 +253,62 @@ def test_a_cliff_calculation_starts_the_countrys_simulation_function(
)
)

assert call_id == "fc-started"
assert looked_up == [(worker.application_name, "run_single_simulation_uk", "main")]
assert function.spawns == [
assert call_id == "fc-started-on-the-class"
assert looked_up_classes == [
(worker.application_name, "SimulationWorkerUK", "main")
]
assert looked_up_functions == []
assert worker_class.method.spawns == [
(
({"simulation": 1}, {"cliff_result_id": "cliffs"}),
{"observability_context": {"observability_id": "observed"}},
)
]


@pytest.mark.parametrize("start", ["start_simulation_run", "start_cliff_calculation"])
def test_an_app_without_the_worker_class_gets_the_simulation_function(
modal_functions, modal_worker_classes, start
) -> None:
# An app deployed for an older .py version, which the manifest's default
# can name after a move or a rollback, defines the worker as a function.
looked_up_functions, function = modal_functions
_looked_up_classes, worker_class = modal_worker_classes
worker_class.deployed = False
worker = default_economy_worker(economy_manifest(), "us")

call_id = asyncio.run(
getattr(ModalEconomyRunCaller("main"), start)(
worker, {"simulation": 1}, {"run": "context"}, observability_context=None
)
)

assert call_id == "fc-started"
assert looked_up_functions == [
(worker.application_name, "run_single_simulation_us", "main")
]
assert worker_class.method.spawns == []
assert function.spawns == [
(({"simulation": 1}, {"run": "context"}), {"observability_context": None})
]


@pytest.mark.parametrize("object_id", [None, ""])
def test_a_class_call_modal_gives_no_id_is_an_error(
modal_worker_classes, object_id
) -> None:
_looked_up, worker_class = modal_worker_classes
worker_class.method.object_id = object_id
worker = default_economy_worker(economy_manifest(), "us")

with pytest.raises(RuntimeError, match="no call ID"):
asyncio.run(
ModalEconomyRunCaller("staging").start_simulation_run(
worker, {}, {}, observability_context=None
)
)


@pytest.mark.parametrize("object_id", [None, ""])
def test_a_call_modal_gives_no_id_is_an_error(modal_functions, object_id) -> None:
_, function = modal_functions
Expand Down
Loading