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/v2-remove-plain-worker-functions.removed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Removed the plain `run_single_simulation_us`, `run_single_simulation_uk` and `run_single_simulation_segment_us` functions from the API v2 app. The workers exist only as methods of `SimulationWorkerUS`, `SimulationWorkerUK` and `SimulationSegmentWorkerUS`, and the entry service, the report coordinator and the segment fan-out start them only through those classes, with no fallback to a plain function. An API v2 app deployed before the classes, such as an older .py version's app made the default by hand, can no longer run standalone simulation runs or cliff calculations.
7 changes: 3 additions & 4 deletions docs/engineering/skills/observability.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ for these IDs names one. Do not use `job_id` for a v2 call: it names one
annual Modal invocation of the v1 executor.

A v2 simulation worker's call (the US and UK single-simulation workers and the
US segment worker, as class methods or plain functions) also says which
US segment worker, each a class method) also says which
deployment served it, as the versioned app's workers do: its operation's
`modal_app_name` names the v2 app, and its records' `service.version` is the
bundle's policyengine.py version. Its `service.name` stays the worker's, such
Expand Down Expand Up @@ -259,8 +259,7 @@ Two attributes are set on the operation of each call of:
- the v2 app's simulation workers (the
`SimulationWorkerUS.run_single_simulation_us`,
`SimulationWorkerUK.run_single_simulation_uk` and
`SimulationSegmentWorkerUS.run_single_simulation_segment_us` methods, and
the plain functions of the same names kept for callers on older code), in
`SimulationSegmentWorkerUS.run_single_simulation_segment_us` methods), in
`src/modal/v2_app.py`. Their records come from the services
`policyengine-stage12-us-worker`, `policyengine-stage12-uk-worker` and
`policyengine-stage12-us-segment-worker`. The v2 coordinator and household
Expand All @@ -275,7 +274,7 @@ 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 a plain function, which has no snapshot hook (`run_budget_window_batch`, and the v2 app's plain worker functions), 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 a plain function, which has no snapshot hook (`run_budget_window_batch`), 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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
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.
Callers start the workers only through these classes. Apps deployed before the
classes, such as older .py versions' apps, define the workers only as plain
functions with these names, so those calls fail there.
"""

from __future__ import annotations
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@
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. 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.
containers restore from a memory snapshot with the models loaded, and is
started only through that class; apps deployed before the classes define it
only as a plain function, so a default naming one of them can't start it.

This is the economy path's own Modal access, apart from the Stage 12
comparison path's.
Expand Down Expand Up @@ -273,33 +274,27 @@ async def _spawn_simulation_worker(
) -> 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.
The worker is reached only through its class. Modal looks the class up
when the method spawns, so an app without it, such as one deployed
before the workers were classes, fails the spawn with Modal's
``NotFoundError``. A name with no class is started as a function.
"""
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,
if class_name is None:
return await self._spawn(
worker,
worker.simulation_callable,
payload,
context_payload,
observability_context=observability_context,
)
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_class = modal.Cls.from_name(
worker.application_name,
class_name,
environment_name=self._environment,
)
return await self._spawn_call(
getattr(worker_class(), worker.simulation_callable),
worker.simulation_callable,
payload,
context_payload,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import asyncio
import dataclasses
from types import SimpleNamespace
from typing import Any

Expand Down Expand Up @@ -139,29 +140,41 @@ def from_name(application: str, name: str, *, environment_name: str):
}


CLASS_NOT_FOUND = "the app defines no such class"


class MissingClassMethod:
"""A method of a class the app doesn't define, looked up by name.

Modal resolves the class when the method is first spawned, so the spawn
raises Modal's not-found error.
"""

def __init__(self) -> None:
self.spawn = SimpleNamespace(aio=self._spawn)

async def _spawn(self, *_arguments: Any, **_keywords: Any) -> SimpleNamespace:
raise modal.exception.NotFoundError(CLASS_NOT_FOUND)


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.
(``method_name``). With ``deployed`` False the app has no such class, as
an app deployed before the workers were classes has none, so spawning its
method fails.
"""

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})
method = self.method if self.deployed else MissingClassMethod()
return SimpleNamespace(**{self.method_name: method})


@pytest.fixture
Expand Down Expand Up @@ -267,29 +280,63 @@ def test_a_cliff_calculation_starts_the_countrys_simulation_worker_class(


@pytest.mark.parametrize("start", ["start_simulation_run", "start_cliff_calculation"])
def test_an_app_without_the_worker_class_gets_the_simulation_function(
def test_an_app_without_the_worker_class_fails_the_call_and_starts_no_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.
# An app deployed before the workers were classes, which the manifest's
# default names only if someone moves it back by hand, defines the worker
# only as a plain function. Callers start workers only through the class.
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")

with pytest.raises(modal.exception.NotFoundError, match=CLASS_NOT_FOUND):
asyncio.run(
getattr(ModalEconomyRunCaller("main"), start)(
worker,
{"simulation": 1},
{"run": "context"},
observability_context=None,
)
)

assert looked_up_functions == []
assert function.spawns == []


@pytest.mark.parametrize("start", ["start_simulation_run", "start_cliff_calculation"])
def test_a_simulation_callable_without_a_worker_class_starts_as_a_function(
modal_functions, modal_worker_classes, start
) -> None:
# Only the v2 simulation workers are class methods; a callable the
# contract maps to no class is started as a plain function of the app.
looked_up_functions, function = modal_functions
looked_up_classes, _worker_class = modal_worker_classes
worker = dataclasses.replace(
default_economy_worker(economy_manifest(), "us"),
simulation_callable="a_function_of_another_kind",
)

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

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


Expand Down
50 changes: 2 additions & 48 deletions projects/policyengine-simulation-executor/src/modal/v2_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,13 +186,8 @@ def validate_worker_uk() -> dict:


# Each simulation worker is a method of a Modal class whose containers restore
# from a memory snapshot with the country's models loaded, and a plain function
# of the same name and options, without a snapshot, for callers still running
# code from before the classes: an entry service revision (the stable one
# during a deploy, or one a rollback routes traffic back to), and a coordinator
# or US worker call running while this app is redeployed in place. Both run the
# same calculation. Their CPU, memory, time and container limits are in
# src/modal/v2_worker_resources.py.
# from a memory snapshot with the country's models loaded. Their CPU, memory,
# time and container limits are in src/modal/v2_worker_resources.py.
_SEGMENT_WORKER_OPTIONS: dict[str, Any] = {
**SEGMENT_WORKER_RESOURCES,
"image": us_worker_image,
Expand Down Expand Up @@ -479,47 +474,6 @@ def run_single_simulation_uk(
)


@app.function(**_SEGMENT_WORKER_OPTIONS)
def run_single_simulation_segment_us(
payload: dict,
*,
observability_context: dict | None = None,
simulation_run_id: str | None = None,
) -> dict:
"""``SimulationSegmentWorkerUS``'s method, for callers on older code."""
return _run_single_simulation_segment_us(
payload,
observability_context=observability_context,
simulation_run_id=simulation_run_id,
)


@app.function(**_US_SIMULATION_WORKER_OPTIONS)
def run_single_simulation_us(
payload: dict,
context: dict,
*,
observability_context: dict | None = None,
) -> dict:
"""``SimulationWorkerUS``'s method, for callers on older code."""
return _run_single_simulation_us(
payload, context, observability_context=observability_context
)


@app.function(**_UK_SIMULATION_WORKER_OPTIONS)
def run_single_simulation_uk(
payload: dict,
context: dict,
*,
observability_context: dict | None = None,
) -> dict:
"""``SimulationWorkerUK``'s method, for callers on older code."""
return _run_single_simulation_uk(
payload, context, observability_context=observability_context
)


@app.function(
image=coordinator_image,
cpu=2.0,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""CPU, memory, time and container limits of the v2 app's simulation workers.

``src/modal/v2_app.py`` gives each simulation worker class, and the plain
function of the same name kept for callers on older code, these settings
``src/modal/v2_app.py`` gives each simulation worker class these settings
together with its image and secrets.
"""

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,11 @@ def __init__( # noqa: PLR0913 # the simulation, then keyword-only app, runtime
simulation_run_id: UUID | None = None,
seams: SegmentRunnerSeams | None = None,
) -> None:
"""Look up the segment worker deployed in ``app_name``.
"""Take the segment worker's method from its Modal class in ``app_name``.

It is a method of a Modal class whose containers restore from a
memory snapshot with the US models loaded (``deployed_worker``).
Its containers restore from a memory snapshot with the US models
loaded (``deployed_worker``). Modal looks the class up when ``run``
spawns the first segment, so an app without it fails there.

``cancellation_requested`` is checked between polls. Each segment's
call is passed ``simulation_run_id``, the detailed-save simulation run
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,26 +21,19 @@ def deployed_worker(
"""Return what spawns ``method_name`` in ``application_name``.

A simulation worker is a method of a Modal class, whose containers restore
from a memory snapshot with the models loaded. An application deployed
from a commit from before the classes defines it as a plain function of
the same name, and a call still running when its application is rolled
back in place to such a commit finds only that function. So a class Modal
doesn't find gives the function. Only the class lookup falls back: once
the class resolves, a failed spawn raises as it is. A name with no class
is looked up as a function. ``lookup_options``, such as
``environment_name``, go to either lookup.
from a memory snapshot with the models loaded, and it is reached only
through that class. Modal looks the class up when the method first
spawns, so an application without the class, such as one deployed from a
commit from before the classes, fails that spawn with Modal's
``NotFoundError``. A name with no class is looked up as a function.
``lookup_options``, such as ``environment_name``, go to either lookup.
"""
class_name = worker_class_name(method_name)
if class_name is not None:
worker_class = modal_module.Cls.from_name(
application_name, class_name, **lookup_options
if class_name is None:
return modal_module.Function.from_name(
application_name, method_name, **lookup_options
)
try:
worker_class.hydrate()
except modal_module.exception.NotFoundError:
pass
else:
return getattr(worker_class(), method_name)
return modal_module.Function.from_name(
application_name, method_name, **lookup_options
worker_class = modal_module.Cls.from_name(
application_name, class_name, **lookup_options
)
return getattr(worker_class(), method_name)
Loading