Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
8fcb443
Test that the simulation workers are not also plain functions
anth-volk Nov 25, 2026
2d62feb
Remove the plain run_simulation and run_simulation_segment functions
anth-volk Nov 25, 2026
300bd11
Test the segment worker's success path through its class
anth-volk Nov 25, 2026
e83a1c7
Say that apps from earlier code define the fallback function
anth-volk Nov 25, 2026
a9a3292
Merge remote-tracking branch 'origin/main' into claude/remove-plain-w…
anth-volk Nov 26, 2026
66670bb
Stop testing and documenting container_start for the removed functions
anth-volk Nov 26, 2026
76fc214
Say that apps from before the classes report no call number
anth-volk Nov 26, 2026
13101fe
Test that the gateway spawns no function for an app without the worke…
anth-volk Nov 26, 2026
fed9421
Spawn annual simulations only through the SimulationWorker class
anth-volk Nov 26, 2026
35331a1
Merge remote-tracking branch 'origin/main' into claude/remove-plain-w…
anth-volk Nov 26, 2026
b34826f
Say that only comparison requests stop running on older apps
anth-volk Nov 26, 2026
3a76c06
Test that rollbacks refuse to route latest to an app without the work…
anth-volk Nov 26, 2026
91cd1d8
Refuse to route latest to an app without the SimulationWorker class
anth-volk Nov 26, 2026
65e5f8d
Merge remote-tracking branch 'origin/main' into claude/remove-plain-w…
anth-volk Nov 26, 2026
5eda386
Test that only rollbacks of finished releases refuse an app without t…
anth-volk Nov 26, 2026
525c04f
Refuse only rollbacks of finished releases that move latest
anth-volk Nov 26, 2026
9c7218c
Test that a pending plan among kept plans exempts only its own undo
anth-volk Nov 26, 2026
3939727
Exempt only the pending publication's own plan from the class check
anth-volk Nov 26, 2026
8203cc3
Test undoing a pending latest plan after its run's finished routes plan
anth-volk Nov 26, 2026
60f0c1e
Check each undo against the state it writes over
anth-volk Nov 26, 2026
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
8 changes: 8 additions & 0 deletions .github/workflows/simulation-rollback.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
5 changes: 5 additions & 0 deletions changelog.d/1130.removed.md
Original file line number Diff line number Diff line change
@@ -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.
19 changes: 10 additions & 9 deletions docs/engineering/skills/observability.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand All @@ -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:
Expand Down Expand Up @@ -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).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,12 @@
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"
SIMULATION_WORKER_METHOD = "run_simulation"

SEGMENT_WORKER_CLASS = "SimulationSegmentWorker"
SEGMENT_WORKER_METHOD = "run_simulation_segment"

FUNCTION_FORM_SIMULATION_WORKER = "run_simulation"
10 changes: 10 additions & 0 deletions projects/policyengine-simulation-executor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
59 changes: 8 additions & 51 deletions projects/policyengine-simulation-executor/src/modal/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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 = {
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down
Loading