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/budget-window-years-in-segments.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Each year of a US nationwide budget window now splits by region group under the same rule as a single-year request, instead of running in one container, and at most 4 such years run at once. State, UK, labour-supply-reform and `segmented: false` windows still run each year in one container, with the number of years at once that the request asks for.
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,17 @@
BudgetWindowResult,
PolicyEngineBundle,
)
from policyengine_simulation_contract.job_run_kind import (
should_run_segmented_national,
)

logger = logging.getLogger(__name__)

# Each year of a window that splits by region group uses one container per
# group in the segment worker pool, which single-year nationwide reports
# share. At most this many such years run at once.
SPLIT_YEARS_MAX_RUNNING = 4

_UNKNOWN_CHILD_JOB_ID = "unknown"

BUDGET_WINDOW_JOB_DICT_NAME = "simulation-api-budget-window-jobs"
Expand Down Expand Up @@ -50,6 +58,23 @@ def _touch(state: BudgetWindowBatchState) -> BudgetWindowBatchState:
return state


def max_running_years(request: BudgetWindowBatchRequest) -> int:
"""Return how many years of ``request``'s window may run at once.

A window whose years split by region group (``should_run_segmented_national``,
the rule a single-year request follows) runs at most
``SPLIT_YEARS_MAX_RUNNING`` years at once. Any other window runs the
``max_parallel`` it asked for. Every year of a window shares the fields
the rule reads, so the request decides for all of them.
"""
year_fields = request.model_dump(
mode="json", exclude={"telemetry"}, exclude_none=True
)
if should_run_segmented_national(year_fields):
return min(request.max_parallel, SPLIT_YEARS_MAX_RUNNING)
return request.max_parallel


@dataclass(frozen=True)
class BatchRoute:
"""Where a budget-window batch runs: its reported version and its Modal app."""
Expand All @@ -69,7 +94,8 @@ def create_initial_batch_state(
"""Build the ``submitted`` state for a new batch, with every year queued.

The stored request payload omits ``telemetry``, and all timestamps are set
to the current UTC time.
to the current UTC time. ``max_parallel`` is ``max_running_years``; the
stored request payload keeps the number the caller asked for.
"""
years = _build_years(request.start_year, request.window_size)
now = _utc_now_iso()
Expand All @@ -85,7 +111,7 @@ def create_initial_batch_state(
policyengine_bundle=bundle,
start_year=request.start_year,
window_size=request.window_size,
max_parallel=request.max_parallel,
max_parallel=max_running_years(request),
request_payload=request.model_dump(exclude={"telemetry"}, mode="json"),
years=years,
queued_years=list(years),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Tests for budget-window batch state helpers."""

from typing import Any

import pytest
from policyengine_simulation_contract.budget_window_state import (
BatchRoute,
Expand All @@ -17,6 +19,7 @@
from policyengine_simulation_contract.gateway_models import (
BudgetWindowAnnualImpact,
BudgetWindowBatchRequest,
BudgetWindowBatchState,
BudgetWindowResult,
BudgetWindowTotals,
PolicyEngineBundle,
Expand Down Expand Up @@ -60,6 +63,69 @@ def test_create_initial_batch_state_builds_queued_years_and_observability_id():
assert state.observability_id == "00000000-0000-4000-8000-000000000001"


LABOR_SUPPLY_REFORM = {
"gov.simulation.labor_supply_responses.elasticities.income.all": {
"2026-01-01.2100-12-31": -0.05
}
}


def _ten_year_window_state(**request_overrides: Any) -> BudgetWindowBatchState:
"""Return the initial state of a 10-year window asking for 20 years at once.

The request matches what API v1 sends for a US nationwide window;
``request_overrides`` replaces any of its fields.
"""
request_fields = {
"country": "us",
"region": "us",
"start_year": "2026",
"window_size": 10,
"max_parallel": 20,
"scope": "macro",
"reform": {},
}
request = BudgetWindowBatchRequest(**{**request_fields, **request_overrides})
return create_initial_batch_state(
batch_job_id="fc-parent-123",
request=request,
route=BatchRoute(
version="1.500.0", app_name="policyengine-simulation-py4-10-0"
),
bundle=PolicyEngineBundle(model_version="1.500.0"),
)


def test_a_window_of_split_years_runs_at_most_four_years_at_once():
state = _ten_year_window_state()

assert state.max_parallel == 4
# The stored request keeps the number the caller asked for.
assert state.request_payload["max_parallel"] == 20


def test_a_window_of_split_years_asking_for_fewer_than_four_keeps_its_number():
state = _ten_year_window_state(max_parallel=2)

assert state.max_parallel == 2


@pytest.mark.parametrize(
"request_overrides",
[
pytest.param({"region": "state/ca"}, id="state"),
pytest.param({"country": "uk", "region": "uk"}, id="uk"),
pytest.param({"segmented": False}, id="segmented-false"),
pytest.param({"reform": LABOR_SUPPLY_REFORM}, id="labour-supply-reform"),
pytest.param({"scope": None}, id="no-macro-scope"),
],
)
def test_a_window_of_unsplit_years_keeps_the_requested_number(request_overrides):
state = _ten_year_window_state(**request_overrides)

assert state.max_parallel == 20


def test_build_batch_status_response_computes_progress_from_completed_years():
request = BudgetWindowBatchRequest(
country="us",
Expand Down
3 changes: 2 additions & 1 deletion projects/policyengine-simulation-executor/src/modal/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,8 @@ def _job_progress_reporter() -> "JobProgressReporter":

Budget-window children are ordinary ``run_simulation`` calls, so each
writes a record under its own call id. ``/budget-window-jobs`` does not
read those records yet; the writes are a few small Dict puts per year.
read those records yet; the writes are a few small Dict puts per year,
plus one per region group for a year that splits by region group.
"""
from policyengine_simulation_contract.job_progress_state import ( # noqa: PLC0415 # resolved per call so tests can patch job_progress_state
get_job_progress,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
BudgetWindowBatchRequest,
PolicyEngineBundle,
)
from policyengine_simulation_contract.job_run_kind import (
should_run_segmented_national,
)
from policyengine_simulation_contract.report_type import (
BUDGET_WINDOW_YEAR_REPORT_TYPE,
REPORT_TYPE_PARAM,
Expand Down Expand Up @@ -102,8 +105,13 @@ def build_child_simulation_request(
) -> ChildSimulationRequest:
"""Build the single-year child request for ``simulation_year``.

Batch-only fields are stripped and the child is pinned to a monolithic
(non-segmented) run.
Batch-only fields are stripped, and ``report_type`` names the request a
year of a multi-year report. The year splits by region group under the
rule a single-year request follows (``should_run_segmented_national``).
``segmented`` is set on every year to the rule's answer: ``true`` when
the year splits (a plain US nationwide year without labour-supply
responses or ``segmented: false``), ``false`` for every other year, as
before. The batch runs at most ``max_running_years`` years at once.
"""
payload = build_child_payload(
context.raw_params,
Expand All @@ -113,12 +121,9 @@ def build_child_simulation_request(
# leaves out of the single-year rows.
REPORT_TYPE_PARAM: BUDGET_WINDOW_YEAR_REPORT_TYPE,
"time_period": simulation_year,
# Budget-window children stay monolithic for now: a national
# child would otherwise fan out again (years x 21 containers).
# Enabling nested segmentation is a deliberate follow-up.
"segmented": False,
},
)
payload["segmented"] = should_run_segmented_national(payload)

return ChildSimulationRequest(
simulation_year=simulation_year,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
mark_child_completed,
mark_child_failed,
mark_child_started,
max_running_years,
put_batch_job_seed,
put_batch_job_state,
)
Expand Down Expand Up @@ -86,10 +87,16 @@ def load_or_create_batch_state(
*,
runtime: ObservabilityRuntime,
) -> BudgetWindowBatchState:
"""Return the batch's submit-time seed state, creating and storing it if absent."""
"""Return the batch's submit-time seed state, creating and storing it if absent.

A seed's ``max_parallel`` is lowered to ``max_running_years``: a gateway
deployed before that limit stored the number the caller asked for.
"""
with runtime.span(BUDGET_WINDOW_STAGES.name(Stage.BUDGET_WINDOW_STATE_LOAD)):
state = get_batch_job_seed(context.batch_job_id)
if state is None:
if state is not None:
state.max_parallel = min(state.max_parallel, max_running_years(context.request))
else:
state = create_initial_batch_state(
batch_job_id=context.batch_job_id,
request=context.request,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
from __future__ import annotations

from collections import deque
from typing import Any

import policyengine_simulation_contract.budget_window_state as state_module
import pytest
import src.modal.budget_window_batch as batch_module
import src.modal.budget_window_scheduler as scheduler_module
from policyengine_simulation_contract.gateway_models import (
BudgetWindowBatchRequest,
BudgetWindowBatchState,
PolicyEngineBundle,
)
from src.modal.budget_window_batch import run_budget_window_batch_impl
Expand Down Expand Up @@ -168,13 +170,15 @@ def current_function_call_id():
}


def _build_parent_payload(*, window_size: int = 3):
def _build_parent_payload(
*, window_size: int = 3, max_parallel: int = 2, region: str = "us"
) -> tuple[BudgetWindowBatchRequest, dict[str, Any]]:
request = BudgetWindowBatchRequest(
country="us",
region="us",
region=region,
start_year="2026",
window_size=window_size,
max_parallel=2,
max_parallel=max_parallel,
scope="macro",
reform={},
_telemetry={
Expand Down Expand Up @@ -527,3 +531,85 @@ def test_run_budget_window_batch_impl_fails_on_malformed_child_result(
assert state is not None
assert state.status == "failed"
assert state.child_jobs["2026"].status == "failed"


def _year_budget_result(year_index: int) -> dict:
return {
"budget": {
"tax_revenue_impact": 10 + year_index,
"state_tax_revenue_impact": 3,
"benefit_spending_impact": 5,
"budgetary_impact": 15 + year_index,
}
}


def _run_six_year_window_asking_for_twenty(
mock_batch_modal, observability_runtime, *, region: str
) -> tuple[SpawnTracker, BudgetWindowBatchState]:
"""Run a 6-year window whose stored record allows 20 years at once.

The record is written the way a gateway deployed before the year limit
wrote it: with the requested 20. Return the spawn tracker and the stored
state after the run.
"""
request, payload = _build_parent_payload(
window_size=6, max_parallel=20, region=region
)
older_gateway_seed = state_module.create_initial_batch_state(
batch_job_id=mock_batch_modal["parent_call_id"],
request=request,
route=state_module.BatchRoute(
version="1.500.0", app_name="policyengine-simulation-py4-10-0"
),
bundle=PolicyEngineBundle(model_version="1.500.0"),
)
older_gateway_seed.max_parallel = 20
state_module.put_batch_job_seed(older_gateway_seed)

tracker = SpawnTracker()
years = [str(2026 + year_index) for year_index in range(6)]
run_simulation = MockRunSimulationFunction(
tracker=tracker,
results_by_year={
year: [_year_budget_result(year_index)]
for year_index, year in enumerate(years)
},
call_registry=mock_batch_modal["call_registry"],
)
mock_batch_modal["functions"][
("policyengine-simulation-py4-10-0", "SimulationWorker.run_simulation")
] = run_simulation

result = run_budget_window_batch_impl(payload, runtime=observability_runtime)

assert result["status"] == "complete"
assert run_simulation.spawned_years == years
stored_state = state_module.get_batch_job_state(mock_batch_modal["parent_call_id"])
assert stored_state is not None
return tracker, stored_state


def test_a_window_of_split_years_runs_at_most_four_years_at_once(
mock_batch_modal,
observability_runtime,
):
tracker, stored_state = _run_six_year_window_asking_for_twenty(
mock_batch_modal, observability_runtime, region="us"
)

assert tracker.max_active == 4
assert stored_state.max_parallel == 4
assert stored_state.request_payload["max_parallel"] == 20


def test_a_window_of_unsplit_years_keeps_the_requested_number_at_once(
mock_batch_modal,
observability_runtime,
):
tracker, stored_state = _run_six_year_window_asking_for_twenty(
mock_batch_modal, observability_runtime, region="state/ca"
)

assert tracker.max_active == 6
assert stored_state.max_parallel == 20
Loading