diff --git a/changelog.d/budget-window-four-years.changed.md b/changelog.d/budget-window-four-years.changed.md new file mode 100644 index 000000000..57c5d0e81 --- /dev/null +++ b/changelog.d/budget-window-four-years.changed.md @@ -0,0 +1 @@ +API v2 runs at most four years of a budget window at once instead of five: the simulation service starts up to a new window's first four years, and each year's coordinator, when its year ends, starts the earliest waiting years until four are under way (running, or started and not yet running). The container limits of API v2's Modal functions are unchanged, so they now have room for three windows at four years each beside 13 other reports. diff --git a/docs/migration/stage-12-modal-worker-foundation.md b/docs/migration/stage-12-modal-worker-foundation.md index 1b2b67c52..2df74e587 100644 --- a/docs/migration/stage-12-modal-worker-foundation.md +++ b/docs/migration/stage-12-modal-worker-foundation.md @@ -27,7 +27,7 @@ simulation submission or polling contracts. report starts 40 region-group calculation calls. These are invocations; Modal may reuse a warm container for more than one invocation. - The report coordinator has a Modal `max_containers` value of 25: three - budget windows at five years each, and ten other reports. Each + budget windows at four years each, and 13 other reports. Each country-specific single-simulation function has 50, both simulations of every coordinator call, and the separate US region-group function has 1,000, every segment of every US simulation call, so calculation work @@ -521,9 +521,9 @@ single-year report's runs, and the reverse. input and context from the first year's: only the year, its three runs, the artifact prefix (`report_run_artifact_prefix`) and the call's creation time differ. -- **At most five at once.** `BudgetWindowStore.advance_window` locks the +- **At most four at once.** `BudgetWindowStore.advance_window` locks the window run's row, then starts the earliest waiting years (pending with no - call) until five are under way (running, or started with a call recorded), + call) until four are under way (running, or started with a call recorded), recording each call while the year is still pending with no call. The lock makes advances that run at once start each year once; a year a duplicate call reaches is claimed by only one call. @@ -549,7 +549,7 @@ single-year report's runs, and the reverse. when they have all ended, or as stalled (`budget_window_stalled`) when years are still waiting. -The coordinator may run 25 calls at once (three windows at five years, and ten +The coordinator may run 25 calls at once (three windows at four years, and 13 other reports), so each simulation worker may run 50 and the US segment function 1,000. diff --git a/libs/policyengine-stage12-persistence/README.md b/libs/policyengine-stage12-persistence/README.md index d239ab585..e829fc7a1 100644 --- a/libs/policyengine-stage12-persistence/README.md +++ b/libs/policyengine-stage12-persistence/README.md @@ -69,7 +69,7 @@ and ends the process with a failure if the check runs for 15 minutes. advances the window. An advance locks the window run's row, then fails the window and its waiting years when a year failed, marks it succeeded when every year succeeded, or starts the earliest waiting years until - `BUDGET_WINDOW_MAX_RUNNING_YEARS` (five) are under way, recording each + `BUDGET_WINDOW_MAX_RUNNING_YEARS` (four) are under way, recording each call while the year is still pending with no call. A year's coordinator call marks its window running. The stuck-run sweep leaves a waiting year to its window, fails the window of a year it fails, and settles a window diff --git a/libs/policyengine-stage12-persistence/src/policyengine_stage12_persistence/budget_window_store.py b/libs/policyengine-stage12-persistence/src/policyengine_stage12_persistence/budget_window_store.py index 7eddcec67..62ec72f6c 100644 --- a/libs/policyengine-stage12-persistence/src/policyengine_stage12_persistence/budget_window_store.py +++ b/libs/policyengine-stage12-persistence/src/policyengine_stage12_persistence/budget_window_store.py @@ -57,7 +57,7 @@ # The most years of one budget window under way at once: running, or started # with a Modal call recorded and waiting for Modal to run it. -BUDGET_WINDOW_MAX_RUNNING_YEARS = 5 +BUDGET_WINDOW_MAX_RUNNING_YEARS = 4 # Each failure records a fixed code, then a summary that holds no # calculation detail; a failed year's own message stays on that year's run. diff --git a/libs/policyengine-stage12-persistence/tests/test_budget_window_sessions.py b/libs/policyengine-stage12-persistence/tests/test_budget_window_sessions.py index 6196f7f0f..ae4c3e941 100644 --- a/libs/policyengine-stage12-persistence/tests/test_budget_window_sessions.py +++ b/libs/policyengine-stage12-persistence/tests/test_budget_window_sessions.py @@ -95,12 +95,12 @@ def test_an_advance_starts_the_earliest_waiting_years( assert advance == WindowAdvance( status=RunStatus.PENDING, changed=False, - started_years=(2026, 2027, 2028, 2029, 2030), + started_years=(2026, 2027, 2028, 2029), ) - assert starter.started == [2026, 2027, 2028, 2029, 2030] + assert starter.started == [2026, 2027, 2028, 2029] years = windows.year_rows(window) assert years[2026]["modal_call_id"].startswith("fc-started-2026") - assert years[2031]["modal_call_id"] is None + assert years[2030]["modal_call_id"] is None assert statements.commits == 1 [lock] = [sent for sent in statements.sent if sent.endswith("FOR UPDATE")] assert "public.budget_window_runs" in lock @@ -122,13 +122,13 @@ def advance(_advancer: int) -> WindowAdvance: with ThreadPoolExecutor(max_workers=advancers) as executor: list(executor.map(advance, range(advancers))) - assert sorted(starter.started) == [2026, 2027, 2028, 2029, 2030] + assert sorted(starter.started) == [2026, 2027, 2028, 2029] started = [ year for year, row in windows.year_rows(window).items() if row["modal_call_id"] is not None ] - assert sorted(started) == [2026, 2027, 2028, 2029, 2030] + assert sorted(started) == [2026, 2027, 2028, 2029] def test_a_refused_start_fails_the_year_and_the_window(store, windows, window) -> None: diff --git a/libs/policyengine-stage12-persistence/tests/test_budget_window_store.py b/libs/policyengine-stage12-persistence/tests/test_budget_window_store.py index d1137fd1e..b665741f7 100644 --- a/libs/policyengine-stage12-persistence/tests/test_budget_window_store.py +++ b/libs/policyengine-stage12-persistence/tests/test_budget_window_store.py @@ -3,7 +3,7 @@ A budget window's years are report runs naming its budget-window run. The simulation service creates them all pending and starts the first ones; each year's coordinator, when its year ends, starts the earliest years still -waiting, keeping at most five under way, and the last year to end marks the +waiting, keeping at most four under way, and the last year to end marks the window. These run against a disposable Postgres that the Public API's v2 migrations created (see ``report_run_database``). """ @@ -116,22 +116,22 @@ def _succeeded(windows, window, years) -> None: ) -def test_the_window_runs_at_most_five_years_at_once() -> None: - assert BUDGET_WINDOW_MAX_RUNNING_YEARS == 5 +def test_the_window_runs_at_most_four_years_at_once() -> None: + assert BUDGET_WINDOW_MAX_RUNNING_YEARS == 4 -def test_the_first_advance_starts_the_five_earliest_years( +def test_the_first_advance_starts_the_four_earliest_years( store, windows, window ) -> None: starter = RecordingStarter() advance = store.advance_window(window.window_run_id, now=LATER, start_year=starter) - assert starter.started == _run_ids(window, range(2026, 2031)) + assert starter.started == _run_ids(window, range(2026, 2030)) assert advance == WindowAdvance( status=RunStatus.PENDING, changed=False, - started_years=(2026, 2027, 2028, 2029, 2030), + started_years=(2026, 2027, 2028, 2029), ) rows = windows.year_rows(window) assert [rows[year]["modal_call_id"] for year in ALL_YEARS] == [ @@ -139,12 +139,12 @@ def test_the_first_advance_starts_the_five_earliest_years( "fc-started-2", "fc-started-3", "fc-started-4", - "fc-started-5", + None, None, None, ] assert {rows[year]["status"] for year in ALL_YEARS} == {"pending"} - assert [rows[year]["updated_at"] for year in range(2026, 2031)] == [LATER] * 5 + assert [rows[year]["updated_at"] for year in range(2026, 2030)] == [LATER] * 4 assert windows.window_row(window)["status"] == "pending" @@ -177,9 +177,30 @@ def test_an_advance_fills_only_the_free_places(store, windows, window) -> None: advance = store.advance_window(window.window_run_id, now=LATER, start_year=starter) - assert starter.started == _run_ids(window, [2030, 2031]) - assert advance.started_years == (2030, 2031) - assert windows.year_rows(window)[2032]["modal_call_id"] is None + # Three years are under way, so one place is free. + assert starter.started == _run_ids(window, [2030]) + assert advance.started_years == (2030,) + rows = windows.year_rows(window) + assert [rows[year]["modal_call_id"] for year in (2031, 2032)] == [None, None] + + +def test_an_advance_with_more_years_under_way_than_the_limit_starts_none( + store, windows, window +) -> None: + # Coordinator calls already running when the limit dropped from five + # may have started one year more than the limit. + under_way = range(2026, 2026 + BUDGET_WINDOW_MAX_RUNNING_YEARS + 1) + windows.set_years(window, under_way, status="running", modal_call_id="fc-run") + starter = RecordingStarter() + + advance = store.advance_window(window.window_run_id, now=LATER, start_year=starter) + + assert starter.started == [] + assert advance == WindowAdvance(status=RunStatus.PENDING, changed=False) + rows = windows.year_rows(window) + waiting = [year for year in ALL_YEARS if year not in under_way] + assert waiting + assert [rows[year]["modal_call_id"] for year in waiting] == [None] * len(waiting) def test_an_advance_without_a_starter_starts_nothing(store, windows, window) -> None: @@ -391,7 +412,7 @@ def claim_then_time_out(year_to_start: YearToStart) -> str: assert advance == WindowAdvance( status=RunStatus.PENDING, changed=False, - started_years=(2026, 2027, 2028, 2029, 2030), + started_years=(2026, 2027, 2028, 2029), ) rows = windows.year_rows(window) assert (rows[2026]["status"], rows[2026]["modal_call_id"]) == ("running", "fc-late") @@ -471,13 +492,12 @@ def advance() -> WindowAdvance: with ThreadPoolExecutor(max_workers=2) as pool: advances = list(pool.map(lambda _: advance(), range(2))) - assert sorted(starter.started) == sorted(_run_ids(window, range(2026, 2031))) + assert sorted(starter.started) == sorted(_run_ids(window, range(2026, 2030))) assert sorted(year for finished in advances for year in finished.started_years) == [ 2026, 2027, 2028, 2029, - 2030, ] @@ -648,8 +668,8 @@ def test_a_reports_later_window_run_starts_only_its_own_years( advance = store.advance_window(rerun.window_run_id, now=LATER, start_year=starter) - assert starter.started == _run_ids(rerun, range(2026, 2031)) - assert advance.started_years == (2026, 2027, 2028, 2029, 2030) + assert starter.started == _run_ids(rerun, range(2026, 2030)) + assert advance.started_years == (2026, 2027, 2028, 2029) assert windows.window_row(window)["status"] == "succeeded" assert {row["status"] for row in windows.year_rows(window).values()} == { "succeeded" diff --git a/projects/policyengine-simulation-entry/README.md b/projects/policyengine-simulation-entry/README.md index 7d134d6c9..2cbc051fa 100644 --- a/projects/policyengine-simulation-entry/README.md +++ b/projects/policyengine-simulation-entry/README.md @@ -294,7 +294,7 @@ that hasn't failed and isn't a recalculation, or else creates one (recording its .py version) and, for each year, a report run naming it and the year, on each side's simulation run of that year, found or inserted. Only for a window run it created does it then start up to the earliest -five years, as its own role, under the window run's row lock +four years, as its own role, under the window run's row lock (`BudgetWindowStore.advance_window`): the first year's coordinator input is built as an economy report's, and each later year's is derived from it. A joined window run is answered as it is, with no new call. @@ -441,7 +441,7 @@ A window created by key with no window run, as `POST /reports/without-run` creates one, has each year's simulations found by their keys instead, when the report's stored key is still the key its stored fields give, so its first re-run is its first calculation. -Only a window run the re-run created has its first years started. Up to five years start at once, as a new window's do (a later year +Only a window run the re-run created has its first years started. Up to four years start at once, as a new window's do (a later year Modal doesn't confirm in time waits for an earlier year's coordinator); it answers 201 with the budget-window create's fields, naming the window run and every year. diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/budget_window_submissions.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/budget_window_submissions.py index 59e42ebb3..afd59f0d5 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/budget_window_submissions.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/budget_window_submissions.py @@ -10,7 +10,7 @@ (``find_or_create_budget_window``), all pending with no Modal call. Only for a window run it created does the service then advance the window as its own role (``BudgetWindowStore.advance_window``): under the window -run's row lock, up to the earliest five years' coordinators are started +run's row lock, up to the earliest four years' coordinators are started and their calls recorded. Each year's coordinator starts the next ones when its year ends. A joined window run is answered as it is. @@ -135,7 +135,7 @@ def advance_window( now: datetime, start_year: YearStarter | None = None, ) -> WindowAdvance: - """Start the earliest waiting years, at most five under way.""" + """Start the earliest waiting years, at most four under way.""" ... diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_rerun_routes.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_rerun_routes.py index 7c43818b7..5185d289a 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_rerun_routes.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_rerun_routes.py @@ -10,7 +10,7 @@ calculates both simulations again, as an extra run marked forced that nothing joins. A budget-window report's run is a budget-window run with a report run - per year, a new one's first five started at once as a new window's are; + per year, up to a new one's first four started at once as a new window's are; it answers as the budget-window create does, naming the window run and every year's runs. A household report's re-run joins or creates its run as an economy report's does, each side's run of its own household simulation, @@ -306,8 +306,8 @@ async def answer( # the route, its record and how to re-run it "create does; a budget window's or household report's re-run " "asking for cliffs is refused (422 cliffs_not_available). A " "budget-window report's run is a " - "budget-window run with a report run per year, a new one's first " - "five started at once, each year on its own year's simulations. " + "budget-window run with a report run per year, up to a new one's " + "first four started at once, each year on its own year's simulations. " "A household report's run calculates its stored household in the " "report's year, in one household function call." ), diff --git a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_routes.py b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_routes.py index fc6dfe509..b3834914e 100644 --- a/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_routes.py +++ b/projects/policyengine-simulation-entry/src/policyengine_simulation_entry/economy_routes.py @@ -10,7 +10,7 @@ ``budget_window`` it finds or creates a budget-window report by key, each year's simulations by their year's keys, and joins its window run on the current versions or creates one with a report run per year, starting up - to the first five years only of a window run it created, answering 201 + to the first four years only of a window run it created, answering 201 with the report, the first year's run, the window run, its status and every year's runs. With ``household`` it finds or creates a household report and a household @@ -563,7 +563,7 @@ def _submission_routes( "include_cliffs is never stored or keyed. " "A budget-window report (report_type budget_window) compares them " "in each year of a window of 1 to 75 years, with a report run per " - "year, at most five running at once, found or created by key as " + "year, at most four running at once, found or created by key as " "an economy report is: its window run on the current versions is " "joined, and each year's sides join their simulations' runs, which " "a single-year report of that year shares. " diff --git a/projects/policyengine-simulation-entry/tests/test_budget_window_submissions.py b/projects/policyengine-simulation-entry/tests/test_budget_window_submissions.py index 38f0037c3..c3c075023 100644 --- a/projects/policyengine-simulation-entry/tests/test_budget_window_submissions.py +++ b/projects/policyengine-simulation-entry/tests/test_budget_window_submissions.py @@ -1,7 +1,7 @@ """Creating a budget-window report and starting its first years. The service creates every year's runs in one transaction, then advances the -window, which starts the earliest years (at most five) by calling the +window, which starts the earliest years (at most four) by calling the coordinator with each year's input. The first year's input is built as a single-year report's is, and every later year's is derived from it. The store and the window advance are faked here; both are tested against @@ -214,7 +214,7 @@ def _submit(submissions, **changes): ) -def test_a_window_is_created_with_a_run_per_year_and_its_first_five_started() -> None: +def test_a_window_is_created_with_a_run_per_year_and_its_first_four_started() -> None: store = FakeWindowStore() caller = FakeCaller() advancer = FakeAdvancer(store) @@ -244,8 +244,14 @@ def test_a_window_is_created_with_a_run_per_year_and_its_first_five_started() -> assert report.population == CATALOG.population(2026) assert report.inputs == {"spm": {"geography_kind": "national"}} assert advancer.advances == [report.window_run_id] - # The first five years were started, each with its own year and runs. - assert len(caller.report_runs) == 5 + # The first four years were started, each with its own year and runs. + assert [year_to_start.year for year_to_start, _ in advancer.started] == [ + 2026, + 2027, + 2028, + 2029, + ] + assert len(caller.report_runs) == 4 for (year_to_start, call_id), (_, payload, context, observed) in zip( advancer.started, caller.report_runs, strict=True ): @@ -431,7 +437,7 @@ async def start_report_run(self, worker, report_payload, context_payload, **kwar def test_the_first_years_share_one_wait_for_modal() -> None: - # A request starting five years one after another never waits more than + # A request starting several years one after another never waits more than # one call's limit: a later year not started in time is left for the # started year's coordinator to start. store = FakeWindowStore() diff --git a/projects/policyengine-simulation-executor/src/modal/v2_app.py b/projects/policyengine-simulation-executor/src/modal/v2_app.py index 3435af165..33e456c4d 100644 --- a/projects/policyengine-simulation-executor/src/modal/v2_app.py +++ b/projects/policyengine-simulation-executor/src/modal/v2_app.py @@ -482,7 +482,7 @@ def run_single_simulation_uk( # the production-result wait, and time to finish and record the report. timeout=COORDINATOR_TIMEOUT_SECONDS, retries=0, - # Three budget windows at five years each, and ten other reports. + # Three budget windows at four years each, and 13 other reports. max_containers=25, secrets=report_run_writer_secrets, ) diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/budget_window_scheduling.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/budget_window_scheduling.py index 4f9fcf4c5..368e5ef4d 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/budget_window_scheduling.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/budget_window_scheduling.py @@ -4,8 +4,9 @@ simulation service creates every year and starts the first ones. A year's coordinator call marks the window running before it claims its year and, once the year has ended, advances the window: it starts the earliest waiting years -in its own Modal application, so that at most five are under way, or marks -the window failed or succeeded (see ``BudgetWindowStore``). +in its own Modal application, so that at most ``BUDGET_WINDOW_MAX_RUNNING_YEARS`` +are under way, or marks the window failed or succeeded (see +``BudgetWindowStore``). Neither step changes the year's own outcome. A failed write is logged, without the error's text, and the stuck-run sweep finishes a window that @@ -127,9 +128,10 @@ def coordinate_window_year[CoordinatorResult]( years in this application. A pre-emption advances nothing: Modal runs the call again, and the restarted call advances when it ends, even when it finds its year already finished. Advancing more than once is safe, - because an advance starts only waiting years and never more than five - under way. A report run outside any window, a call naming no report run, - or a store that cannot be built makes no window writes. When the lookup + because an advance starts only waiting years and never more than + ``BUDGET_WINDOW_MAX_RUNNING_YEARS`` under way. A report run outside any + window, a call naming no report run, or a store that cannot be built + makes no window writes. When the lookup itself fails, nothing is marked and the window is looked up again once the year ends. """ diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_budget_window_capacity.py b/projects/policyengine-simulation-executor/tests/test_stage12_budget_window_capacity.py index 804f6d3aa..cc045423d 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_budget_window_capacity.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_budget_window_capacity.py @@ -17,9 +17,9 @@ from test_stage12_modal_app import _load, declared_modal_options # Budget windows the coordinator has room for at once, each at its cap, -# beside the coordinator calls it had for other reports. +# beside coordinator calls for other reports. WINDOWS_AT_ONCE = 3 -OTHER_REPORTS = 10 +OTHER_REPORTS = 13 SIMULATIONS_PER_REPORT = 2 diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_budget_window_segments.py b/projects/policyengine-simulation-executor/tests/test_stage12_budget_window_segments.py new file mode 100644 index 000000000..1de4670c0 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_stage12_budget_window_segments.py @@ -0,0 +1,180 @@ +"""A budget window's later years are split into US region groups as one year is. + +Every year after a budget window's first has an input derived from another +year's (``year_calculation``), whether the simulation service starts it +among the first years or another year's coordinator starts it +(``ModalYearStarter``, used here). The started year's coordinator gives each +simulation the plan every run of that simulation stores +(``resolve_simulation_output_plan``), and the US simulation worker splits a +simulation into the 20 region groups when ``should_segment_simulation`` says +so: a US national simulation not marked ``segmented: false`` whose own policy +turns no labour-supply response on. These tests take a started year's two +simulations from the year starter's call and pass them through the same +planner, with the installed US model, and the same split rule. +""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import TYPE_CHECKING, Any +from uuid import UUID + +from policyengine_simulation_contract.stage12_execution import ( + ReportExecutionInput, + ReportRunIds, + SimulationRole, +) +from policyengine_simulation_executor.stage12_runtime import budget_window_scheduling +from policyengine_simulation_executor.stage12_runtime.budget_window_scheduling import ( + ModalYearStarter, +) +from policyengine_simulation_executor.stage12_runtime.output_planning import ( + plan_simulation_input, + resolve_simulation_output_plan, +) +from policyengine_simulation_executor.stage12_runtime.partition import ( + should_segment_simulation, +) +from policyengine_stage12_persistence import YearToStart +from stage12_fake_report_runs import report_run_context, report_run_input + +if TYPE_CHECKING: + from policyengine_simulation_contract.stage12_execution import ( + PlannedSimulationExecutionInput, + ) + +LATER_YEAR = 2027 +LATER_YEAR_RUNS = ReportRunIds( + report_run_id=UUID("00000000-0000-0000-0000-0000000003a1"), + baseline_simulation_run_id=UUID("00000000-0000-0000-0000-0000000003b1"), + reform_simulation_run_id=UUID("00000000-0000-0000-0000-0000000003c1"), +) +# Reforms in the form the simulation service gives a coordinator: each +# parameter's value over a dated period, an open-ended value's ending in 2200. +WHOLE_WINDOW_PERIOD = "2026-01-01.2200-12-31" +CHILD_TAX_CREDIT_REFORM = { + "gov.irs.credits.ctc.amount.base[0].amount": {WHOLE_WINDOW_PERIOD: 3_000}, +} +LABOUR_SUPPLY_RESPONSE_REFORM = { + "gov.simulation.labor_supply_responses.elasticities.income": { + WHOLE_WINDOW_PERIOD: 0.1 + }, +} + + +def _first_year( + reform_policy: dict[str, Any], *, options: dict[str, Any] +) -> ReportExecutionInput: + """Return a US national window's first year, both sides given ``options``.""" + first_year = report_run_input() + return first_year.model_copy( + update={ + "baseline": first_year.baseline.model_copy(update={"options": options}), + "reform": first_year.reform.model_copy( + update={"policy": reform_policy, "options": options} + ), + } + ) + + +def _later_year_simulations( + monkeypatch, first_year: ReportExecutionInput +) -> dict[SimulationRole, PlannedSimulationExecutionInput]: + """Start the later year as a coordinator does; plan its two simulations. + + The year starter's Modal call is replaced by one that records the + started coordinator's input. + """ + started_inputs: list[dict[str, Any]] = [] + + def function_from_name(*_args, **_kwargs): + def spawn(year_input, _year_context, **_spawn_options): + started_inputs.append(year_input) + return SimpleNamespace(object_id="fc-later-year") + + return SimpleNamespace(spawn=spawn) + + fake_modal = SimpleNamespace(Function=SimpleNamespace(from_name=function_from_name)) + monkeypatch.setattr( + budget_window_scheduling, "import_module", lambda _module_name: fake_modal + ) + starter = ModalYearStarter( + payload=first_year.model_dump(mode="json"), + context=report_run_context().model_dump(mode="json"), + ) + + starter(YearToStart(year=LATER_YEAR, run_ids=LATER_YEAR_RUNS)) + + (started_input,) = started_inputs + later_year = ReportExecutionInput.model_validate(started_input) + return { + side.role: plan_simulation_input(side, resolve_simulation_output_plan(side)) + for side in (later_year.baseline, later_year.reform) + } + + +def _split_by_role( + simulations: dict[SimulationRole, PlannedSimulationExecutionInput], +) -> dict[SimulationRole, bool]: + return { + role: should_segment_simulation(simulation) + for role, simulation in simulations.items() + } + + +def test_both_simulations_of_a_later_us_national_year_run_in_segments( + monkeypatch, +) -> None: + simulations = _later_year_simulations( + monkeypatch, _first_year(CHILD_TAX_CREDIT_REFORM, options={}) + ) + + for simulation in simulations.values(): + assert simulation.year == LATER_YEAR + assert (simulation.geography.country, simulation.geography.region) == ( + "us", + "us", + ) + assert simulation.output_plan.requirements.include_cliff_impacts is False + assert _split_by_role(simulations) == { + SimulationRole.BASELINE: True, + SimulationRole.REFORM: True, + } + + +def test_a_labour_supply_response_reform_runs_whole_beside_a_split_baseline( + monkeypatch, +) -> None: + simulations = _later_year_simulations( + monkeypatch, _first_year(LABOUR_SUPPLY_RESPONSE_REFORM, options={}) + ) + + # Each simulation is planned on its own policy, so only the reform's + # plan turns the response on. + assert { + role: simulation.output_plan.requirements.labor_supply_response_active + for role, simulation in simulations.items() + } == {SimulationRole.BASELINE: False, SimulationRole.REFORM: True} + assert _split_by_role(simulations) == { + SimulationRole.BASELINE: True, + SimulationRole.REFORM: False, + } + + +def test_a_window_marked_unsegmented_keeps_the_mark_in_its_later_years( + monkeypatch, +) -> None: + # No API v2 request sends this option; a window given it is built here. + simulations = _later_year_simulations( + monkeypatch, + _first_year(CHILD_TAX_CREDIT_REFORM, options={"segmented": False}), + ) + + assert {role: simulation.options for role, simulation in simulations.items()} == { + SimulationRole.BASELINE: {"segmented": False}, + SimulationRole.REFORM: {"segmented": False}, + } + assert _split_by_role(simulations) == { + SimulationRole.BASELINE: False, + SimulationRole.REFORM: False, + }