diff --git a/changelog.d/budget-window-years-in-segments.fixed.md b/changelog.d/budget-window-years-in-segments.fixed.md new file mode 100644 index 000000000..d0341fa28 --- /dev/null +++ b/changelog.d/budget-window-years-in-segments.fixed.md @@ -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. diff --git a/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/budget_window_state.py b/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/budget_window_state.py index f75bd4f2c..6c45fcdb6 100644 --- a/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/budget_window_state.py +++ b/libs/policyengine-simulation-contract/src/policyengine_simulation_contract/budget_window_state.py @@ -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" @@ -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.""" @@ -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() @@ -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), diff --git a/libs/policyengine-simulation-contract/tests/test_budget_window_state.py b/libs/policyengine-simulation-contract/tests/test_budget_window_state.py index 35e66db8a..757c20642 100644 --- a/libs/policyengine-simulation-contract/tests/test_budget_window_state.py +++ b/libs/policyengine-simulation-contract/tests/test_budget_window_state.py @@ -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, @@ -17,6 +19,7 @@ from policyengine_simulation_contract.gateway_models import ( BudgetWindowAnnualImpact, BudgetWindowBatchRequest, + BudgetWindowBatchState, BudgetWindowResult, BudgetWindowTotals, PolicyEngineBundle, @@ -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", diff --git a/projects/policyengine-simulation-executor/src/modal/app.py b/projects/policyengine-simulation-executor/src/modal/app.py index 1717a4244..ac83be3a0 100644 --- a/projects/policyengine-simulation-executor/src/modal/app.py +++ b/projects/policyengine-simulation-executor/src/modal/app.py @@ -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, diff --git a/projects/policyengine-simulation-executor/src/modal/budget_window_context.py b/projects/policyengine-simulation-executor/src/modal/budget_window_context.py index fb58133c5..57646ce53 100644 --- a/projects/policyengine-simulation-executor/src/modal/budget_window_context.py +++ b/projects/policyengine-simulation-executor/src/modal/budget_window_context.py @@ -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, @@ -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, @@ -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, diff --git a/projects/policyengine-simulation-executor/src/modal/budget_window_scheduler.py b/projects/policyengine-simulation-executor/src/modal/budget_window_scheduler.py index 7d96ad6bf..2033cd807 100644 --- a/projects/policyengine-simulation-executor/src/modal/budget_window_scheduler.py +++ b/projects/policyengine-simulation-executor/src/modal/budget_window_scheduler.py @@ -16,6 +16,7 @@ mark_child_completed, mark_child_failed, mark_child_started, + max_running_years, put_batch_job_seed, put_batch_job_state, ) @@ -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, diff --git a/projects/policyengine-simulation-executor/tests/test_budget_window_batch.py b/projects/policyengine-simulation-executor/tests/test_budget_window_batch.py index 48562a06d..cbf2d4eeb 100644 --- a/projects/policyengine-simulation-executor/tests/test_budget_window_batch.py +++ b/projects/policyengine-simulation-executor/tests/test_budget_window_batch.py @@ -3,6 +3,7 @@ from __future__ import annotations from collections import deque +from typing import Any import policyengine_simulation_contract.budget_window_state as state_module import pytest @@ -10,6 +11,7 @@ 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 @@ -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={ @@ -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 diff --git a/projects/policyengine-simulation-executor/tests/test_budget_window_context.py b/projects/policyengine-simulation-executor/tests/test_budget_window_context.py index cff0f6562..4972b14a3 100644 --- a/projects/policyengine-simulation-executor/tests/test_budget_window_context.py +++ b/projects/policyengine-simulation-executor/tests/test_budget_window_context.py @@ -1,31 +1,46 @@ """Tests for budget-window batch context helpers.""" +from typing import Any + import pytest from policyengine_simulation_contract.gateway_models import ( BudgetWindowBatchRequest, PolicyEngineBundle, ) +from policyengine_simulation_contract.job_run_kind import ( + should_run_segmented_national, +) from src.modal.budget_window_context import ( build_batch_context, build_child_simulation_request, ) - -def _build_parent_payload(*, country="us", region="us"): - request = BudgetWindowBatchRequest( - country=country, - region=region, - start_year="2026", - window_size=3, - max_parallel=2, - scope="macro", - reform={}, - _telemetry={ +LABOR_SUPPLY_REFORM = { + "gov.simulation.labor_supply_responses.elasticities.income.all": { + "2026-01-01.2100-12-31": -0.05 + } +} + + +def _build_parent_payload( + **request_overrides: Any, +) -> tuple[BudgetWindowBatchRequest, dict[str, Any]]: + request_fields = { + "country": "us", + "region": "us", + "start_year": "2026", + "window_size": 3, + "max_parallel": 2, + "scope": "macro", + "reform": {}, + "_telemetry": { "submission_claim_id": "proc-123", "capture_mode": "disabled", }, - ) - payload = request.model_dump(mode="json", exclude={"telemetry"}) + } + request = BudgetWindowBatchRequest(**{**request_fields, **request_overrides}) + # The gateway leaves unset fields out of the batch payload. + payload = request.model_dump(mode="json", exclude={"telemetry"}, exclude_none=True) payload["version"] = "1.500.0" payload["_telemetry"] = request.telemetry.model_dump(mode="json") payload["_metadata"] = { @@ -78,21 +93,39 @@ def test_build_child_simulation_request_removes_batch_only_fields(): assert "_metadata" not in child_request.payload -def test_build_child_simulation_request_pins_children_monolithic(): - """A national budget-window child must not fan out again. +def _year_request(**request_overrides: Any) -> dict[str, Any]: + """Return the 2028 year request of a window built with ``request_overrides``.""" + _, payload = _build_parent_payload(**request_overrides) + context = build_batch_context(payload, batch_job_id="parent-123") + return build_child_simulation_request(context, simulation_year="2028").payload - Fanning out would cost years x 21 containers; enabling nested - segmentation is a deliberate follow-up. + +def test_a_plain_us_national_year_runs_in_segments(): + """A year follows the same split rule as a single-year nationwide report. + + The year's request says ``segmented: true``, so its run record shows the + split. """ - _, payload = _build_parent_payload() - context = build_batch_context(payload, batch_job_id="parent-123") + year_request = _year_request() - child_request = build_child_simulation_request( - context, - simulation_year="2028", - ) + assert year_request["segmented"] is True + assert should_run_segmented_national(year_request) is True + + +@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"), + ], +) +def test_a_year_the_split_rule_excludes_runs_in_one_container(request_overrides): + year_request = _year_request(**request_overrides) - assert child_request.payload["segmented"] is False + assert year_request["segmented"] is False + assert should_run_segmented_national(year_request) is False @pytest.mark.parametrize( @@ -109,12 +142,6 @@ def test_build_child_simulation_request_marks_every_year_as_a_budget_window_year summary leaves ``budget_window_year`` records out, whatever the window's country or region and whether or not the year runs in segments. """ - _, payload = _build_parent_payload(country=country, region=region) - context = build_batch_context(payload, batch_job_id="parent-123") - - child_request = build_child_simulation_request( - context, - simulation_year="2028", - ) + year_request = _year_request(country=country, region=region) - assert child_request.payload.get("report_type") == "budget_window_year" + assert year_request.get("report_type") == "budget_window_year" diff --git a/projects/policyengine-simulation-gateway/README.md b/projects/policyengine-simulation-gateway/README.md index 7fa81178a..87f9314d7 100644 --- a/projects/policyengine-simulation-gateway/README.md +++ b/projects/policyengine-simulation-gateway/README.md @@ -201,6 +201,23 @@ Rules: - The entry starts no Stage 12 comparison for a breakdown request (skip reason `unsupported_options`). +## Budget-window batches + +`POST /simulate/economy/budget-window` runs one `run_simulation` request per +year of the window. Each year splits by region group under the rule a +single-year request follows (`should_run_segmented_national`): a plain US +nationwide macro year runs one segment per region group on the segment +worker pool. Every other year runs in one container: any region other than +the whole US (a state, district or place), the UK, a non-macro `scope`, +`segmented: false`, and labour-supply responses in the reform or the +baseline. A budget-window request refuses `include_cliffs: true` with 422. + +When the years split, the batch record's `max_parallel` holds at most 4 +(`max_running_years`), because every running year uses one segment-pool +container per region group, and single-year nationwide reports share that +pool. The record's `request_payload` keeps the number the request asked for. +A window whose years do not split runs as many years at once as it asked for. + ## Image dependencies The Modal image installs with `uv_sync(frozen=True)` from this project's