From a1adfa293553b1b154179be9f48b564deb66381f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:02:34 +0400 Subject: [PATCH 1/5] Test that comparison-path baselines find the precomputed US baselines The comparison-path coordinator (ReportCoordination), which serves shadow comparisons and the operator route, gives its baseline the report's plan, so a current-law US national baseline segment computes a cache identity the precompute never stores. These tests expect the stored plan instead whenever it holds every column the report reads from the baseline: the CTC report's group-0 segment gets the precomputed identity (it gets stage12-bl1-6bf58faeedaedc36, not stage12-bl1-928929ee9ffcc2a4), a labour-supply reform splits its baseline into segments with that identity, and a baseline stored under its own plan is aggregated with the same values as under the report's plan. A cliff report's baseline and every reform keep the report's plan. Two tests that build the coordinator's dependencies directly now pass a stored plan resolver, so planning a baseline loads no country model. Co-Authored-By: Claude Opus 5.5 --- .../test_stage12_comparison_baseline_cache.py | 405 ++++++++++++++++++ .../tests/test_stage12_coordination.py | 2 + .../tests/test_stage12_coordinator.py | 2 + 3 files changed, 409 insertions(+) create mode 100644 projects/policyengine-simulation-executor/tests/test_stage12_comparison_baseline_cache.py diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_comparison_baseline_cache.py b/projects/policyengine-simulation-executor/tests/test_stage12_comparison_baseline_cache.py new file mode 100644 index 000000000..f9faa2545 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_stage12_comparison_baseline_cache.py @@ -0,0 +1,405 @@ +"""A comparison-path report's current-law baseline finds the precomputed US baselines. + +The precompute stores each US national baseline under its simulation's stored +plan (``resolve_simulation_output_plan``), and a segment worker looks its +baseline up under the digest of the plan its coordinator gave it. The +comparison-path coordinator (``ReportCoordination``), which serves shadow +comparisons and the operator route, gives its baseline that stored plan +whenever it holds every column the report reads from that side, so its +baseline segments load the precomputed files. A report reading columns the +stored plan lacks, such as the cliff columns, keeps the report's plan, and the +reform always keeps it. +""" + +from __future__ import annotations + +from uuid import UUID, uuid5 + +import pandas as pd +import pytest +from policyengine_simulation_contract.stage12_execution import ( + BundleProvenance, + DatasetArtifactMediaType, + DatasetArtifactReference, + DatasetPopulationInput, + DatasetProvenance, + EntityOutputPlan, + GeographySelection, + PlannedSimulationExecutionInput, + ReportAggregate, + ReportExecutionInput, + SimulationExecutionInput, + SimulationRole, + Stage12OutputPlan, + stage12_output_plan_sha256, +) +from policyengine_simulation_executor import simulation_runtime +from policyengine_simulation_executor.spm import normalize_runtime_spm +from policyengine_simulation_executor.stage12_bundle import load_stage12_bundle +from policyengine_simulation_executor.stage12_cache import precompute_planning +from policyengine_simulation_executor.stage12_runtime import segmentation +from policyengine_simulation_executor.stage12_runtime.cached_simulation import ( + qualifying_cache_identity, +) +from policyengine_simulation_executor.stage12_runtime.coordination_core import ( + CoordinatorDependencies, + CoordinatorInvocation, +) +from policyengine_simulation_executor.stage12_runtime.failure_causes import ( + StageProgress, +) +from policyengine_simulation_executor.stage12_runtime.output_planning import ( + resolve_simulation_output_plan, +) +from policyengine_simulation_executor.stage12_runtime.partition import ( + US_REGION_GROUPS, + should_segment_simulation, +) +from policyengine_simulation_executor.stage12_runtime.report_coordination import ( + ReportCoordination, +) +from policyengine_simulation_executor.stage12_runtime.worker_inputs import ( + simulation_runtime_params, +) +from policyengine_simulation_observability.stages import ( + STAGE12_CANONICAL_REPORT_STAGES, +) +from stage12_child_call_support import ImmediateCall +from stage12_fake_stores import FakeArtifacts, FakeStore +from stage12_runtime_support import ( + aggregate_payload, + coordinate_report, + invocation_context, + parent_record, + report_execution_input, + shared_output_plan, +) + +REPORT_YEAR = 2026 +# The reform of the 1.6 · 7 staging report: the CTC base amount raised to $3,000. +CTC_REFORM = { + "gov.irs.credits.ctc.amount.base[0].amount": {"2026-01-01.2100-12-31": 3000} +} +# The same reform with an income-elasticity labour-supply response turned on. +CTC_REFORM_WITH_LABOUR_SUPPLY_RESPONSES = { + **CTC_REFORM, + "gov.simulation.labor_supply_responses.elasticities.income": { + "2026-01-01.2100-12-31": -0.05 + }, +} +REPORT_EVALUATION_ID = UUID("34d79a08-6c93-401a-a6da-0fc6580fe2ab") +# The US labour-supply responses .py's output reads from both sides. +US_RESPONSES = ( + "income_elasticity_lsr", + "substitution_elasticity_lsr", + "weekly_hours_worked_behavioural_response_income_elasticity", + "weekly_hours_worked_behavioural_response_substitution_elasticity", +) +# The inputs a US stored plan copies for .py's labour-supply output. +US_COPIED_INPUTS = ("self_employment_income", "weekly_hours_worked") + + +def _national_report( + reform_policy: dict, *, include_cliffs: bool = False +) -> ReportExecutionInput: + """Build a US national report as the entrypoint's ``adapt_annual_comparison`` does. + + The baseline is current law and the population is the installed bundle's + default dataset, with every aggregate requested. + """ + resolved = load_stage12_bundle() + country = next(item for item in resolved.bundle.countries if item.country == "us") + dataset = next( + item for item in country.datasets if item.identity == country.default_dataset + ) + provenance = BundleProvenance( + policyengine_version=resolved.bundle.policyengine_version, + country_package_name=country.country_package_name, + country_package_version=country.country_package_version, + dataset=DatasetProvenance( + identity=dataset.identity, + uri=dataset.uri, + artifact_revision=dataset.artifact_revision, + data_package_name=country.data_package_name, + data_package_version=country.data_package_version, + ), + bundle_manifest_sha256=resolved.bundle_manifest_sha256, + ) + population = DatasetPopulationInput( + artifact=DatasetArtifactReference( + uri=dataset.uri, + media_type=DatasetArtifactMediaType.HDF5, + content_sha256=dataset.sha256, + ) + ) + options = {"include_cliffs": True} if include_cliffs else {} + + def simulation(role: SimulationRole, policy: dict) -> SimulationExecutionInput: + return SimulationExecutionInput( + evaluation_id=REPORT_EVALUATION_ID, + simulation_execution_id=uuid5(REPORT_EVALUATION_ID, role.value), + role=role, + policy=policy, + population=population, + year=REPORT_YEAR, + geography=GeographySelection(country="us", region="us"), + options=options, + bundle=provenance, + ) + + return ReportExecutionInput( + evaluation_id=REPORT_EVALUATION_ID, + baseline=simulation(SimulationRole.BASELINE, {}), + reform=simulation(SimulationRole.REFORM, reform_policy), + requested_aggregates=tuple(ReportAggregate), + ) + + +def _planned_by_the_comparison_coordinator( + report: ReportExecutionInput, +) -> tuple[Stage12OutputPlan, dict[SimulationRole, PlannedSimulationExecutionInput]]: + """Plan ``report`` as ``ReportCoordination`` does, with the deployed planners. + + Returns the report's plan and each child's planned input by role. Planning + reads only the installed packages: no store, artifact or child is used. + """ + coordination = ReportCoordination( + report=report, + context=invocation_context(), + invocation=CoordinatorInvocation( + application_name=invocation_context().modal_application, + invocation_id="coordinator-1", + ), + persistence=FakeStore(), + artifact_storage=FakeArtifacts(), + child_invoker=None, + dependencies=CoordinatorDependencies(), + stage_plan=STAGE12_CANONICAL_REPORT_STAGES, + progress=StageProgress(), + child_wait_deadline=0.0, + ) + report_plan, children = coordination.plan_simulations() + return report_plan, {child.role: child for child in children} + + +def _group_segment_identity( + planned_baseline: PlannedSimulationExecutionInput, group_index: int +): + """Return the cache identity a segment worker computes for one region group. + + The segment is scoped as ``segmentation`` scopes it, and its region and + dataset are resolved as the worker resolves them, without loading data. + """ + segment = segmentation.build_segment_inputs(planned_baseline)[group_index] + scoped = segmentation._scoped_simulation(segment) + params = simulation_runtime_params(scoped) + region = simulation_runtime.resolve_region( + country_module=simulation_runtime._country_module("us"), + country="us", + params=params, + ) + dataset_selection = simulation_runtime._resolve_dataset_selection( + params, region_resolution=region + ) + return qualifying_cache_identity( + scoped, + resolved=load_stage12_bundle(), + dataset_is_default=dataset_selection.is_default, + scoping_strategy=region.scoping_strategy, + spm=normalize_runtime_spm(params), + ) + + +def _precomputed_simulation_id(group_index: int) -> str: + _simulation, identity = precompute_planning.baseline_identity( + REPORT_YEAR, US_REGION_GROUPS[group_index] + ) + return identity.simulation_id + + +def test_comparison_report_baseline_segment_uses_the_precomputed_identity() -> None: + _report_plan, children = _planned_by_the_comparison_coordinator( + _national_report(CTC_REFORM) + ) + + identity = _group_segment_identity(children[SimulationRole.BASELINE], 0) + + assert identity is not None + assert identity.simulation_id == _precomputed_simulation_id(0) + + +def test_a_labour_supply_reform_splits_its_baseline_into_precomputed_segments() -> None: + report_plan, children = _planned_by_the_comparison_coordinator( + _national_report(CTC_REFORM_WITH_LABOUR_SUPPLY_RESPONSES) + ) + baseline = children[SimulationRole.BASELINE] + + # The report reads responses; its current-law baseline stores none, and + # its region-group segments are looked up in the precomputed cache. + assert report_plan.requirements.labor_supply_response_active + assert should_segment_simulation(baseline) + identity = _group_segment_identity(baseline, 0) + assert identity is not None + assert identity.simulation_id == _precomputed_simulation_id(0) + # The reform's own policy turns responses on, so it isn't split. + assert not should_segment_simulation(children[SimulationRole.REFORM]) + + +def test_a_cliff_report_keeps_the_report_plan_for_its_baseline() -> None: + report = _national_report(CTC_REFORM, include_cliffs=True) + report_plan, children = _planned_by_the_comparison_coordinator(report) + + # The stored plan never holds the cliff columns the report reads. + stored_columns = { + entity.entity: set(entity.materialized_variables) + for entity in resolve_simulation_output_plan(report.baseline).entities + } + assert "cliff_gap" not in stored_columns["person"] + assert children[SimulationRole.BASELINE].output_plan == report_plan + assert not should_segment_simulation(children[SimulationRole.BASELINE]) + + +@pytest.mark.parametrize( + "reform_policy", [CTC_REFORM, CTC_REFORM_WITH_LABOUR_SUPPLY_RESPONSES] +) +def test_the_reform_keeps_the_report_plan(reform_policy: dict) -> None: + report_plan, children = _planned_by_the_comparison_coordinator( + _national_report(reform_policy) + ) + + assert children[SimulationRole.REFORM].output_plan == report_plan + + +def _with_person_columns( + plan: Stage12OutputPlan, + columns: tuple[str, ...], + *, + labour_supply_response_active: bool, +) -> Stage12OutputPlan: + """Return ``plan`` with ``columns`` added to its person entity.""" + entities = tuple( + EntityOutputPlan( + entity=entity.entity, + materialized_variables=tuple( + sorted(set(entity.materialized_variables) | set(columns)) + ), + ) + if entity.entity == "person" + else entity + for entity in plan.entities + ) + requirements = plan.requirements.model_copy( + update={"labor_supply_response_active": labour_supply_response_active} + ) + return plan.model_copy(update={"entities": entities, "requirements": requirements}) + + +class PlanShapedInvoker: + """Start each child by writing a one-row output holding exactly its plan's columns. + + A response column is zero in the baseline, whose current-law policy turns + no response on, and the copied inputs are the same on both sides. + """ + + def __init__(self, artifacts: FakeArtifacts) -> None: + self.artifacts = artifacts + self.planned: dict[str, Stage12OutputPlan] = {} + + def spawn(self, request): + simulation = PlannedSimulationExecutionInput.model_validate(request.simulation) + role = simulation.role.value + self.planned[role] = simulation.output_plan + frames = { + entity.entity: pd.DataFrame( + { + column: [_column_value(column, simulation.role)] + for column in entity.materialized_variables + } + ) + for entity in simulation.output_plan.entities + } + descriptor = self.artifacts.add_simulation(simulation, frames).model_copy( + update={ + "output_plan_sha256": stage12_output_plan_sha256(simulation.output_plan) + } + ) + return ImmediateCall(f"call-{role}", descriptor.model_dump(mode="json"), []) + + def restore(self, invocation_id): + raise AssertionError(invocation_id) + + +def _column_value(column: str, role: SimulationRole) -> float | int: + if column.endswith("_id"): + return 1 + if column in US_COPIED_INPUTS: + return 7.0 + if column in US_RESPONSES: + return 0.0 if role is SimulationRole.BASELINE else 5.0 + return 100.0 if role is SimulationRole.BASELINE else 120.0 + + +def _aggregated_frames(report_plan, baseline_stored_plan): + """Coordinate the fixture report; return the plans given and frames aggregated.""" + artifacts = FakeArtifacts() + invoker = PlanShapedInvoker(artifacts) + aggregated = [] + + def recording_aggregator(**inputs): + aggregated.append(inputs) + return aggregate_payload() + + coordinate_report( + report_execution_input().model_dump(mode="json"), + invocation_context().model_dump(mode="json"), + parent_record().model_dump(mode="json"), + application_name=invocation_context().modal_application, + coordinator_invocation_id="coordinator-1", + store=FakeStore(), + artifacts=artifacts, + invoker=invoker, + aggregator=recording_aggregator, + output_plan_resolver=lambda _report: report_plan, + stored_plan_resolver=lambda _simulation: baseline_stored_plan, + ) + (inputs,) = aggregated + return invoker.planned, { + role: inputs[role].frames for role in ("baseline", "reform") + } + + +def _report_columns(frames, report_plan): + """Return each entity's frame cut down to the columns the report reads.""" + return { + entity.entity: frames[entity.entity][list(entity.materialized_variables)] + for entity in report_plan.entities + } + + +def test_a_baseline_stored_under_its_own_plan_is_aggregated_as_under_the_report_plan(): + # The reform turns responses on, so the report reads them and the copied + # inputs; the current-law baseline's stored plan holds the copied inputs + # and no response. + report_plan = _with_person_columns( + shared_output_plan(), + US_RESPONSES + US_COPIED_INPUTS, + labour_supply_response_active=True, + ) + baseline_stored_plan = _with_person_columns( + shared_output_plan(), US_COPIED_INPUTS, labour_supply_response_active=False + ) + + stored_planned, stored_frames = _aggregated_frames( + report_plan, baseline_stored_plan + ) + # A stored plan equal to the report's plan stands for the earlier planning, + # where the baseline calculated the report's plan, responses as zeros. + report_planned, report_frames = _aggregated_frames(report_plan, report_plan) + + assert stored_planned == {"baseline": baseline_stored_plan, "reform": report_plan} + assert report_planned == {"baseline": report_plan, "reform": report_plan} + for role in ("baseline", "reform"): + stored_side = _report_columns(stored_frames[role], report_plan) + report_side = _report_columns(report_frames[role], report_plan) + for entity, frame in report_side.items(): + pd.testing.assert_frame_equal(stored_side[entity], frame) diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_coordination.py b/projects/policyengine-simulation-executor/tests/test_stage12_coordination.py index cba59a96f..68a0cd3ab 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_coordination.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_coordination.py @@ -443,6 +443,8 @@ def resolve(report, *, stage_scope): invoker=ConcurrentInvoker(artifacts), aggregator=lambda **_: aggregate_payload(), runtime=runtime, + # The baseline's stored plan, so planning loads no country model. + stored_plan_resolver=lambda _simulation: shared_output_plan(), ), ) diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_coordinator.py b/projects/policyengine-simulation-executor/tests/test_stage12_coordinator.py index fda435620..b3348fa65 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_coordinator.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_coordinator.py @@ -82,6 +82,8 @@ def resolver(report): invoker=invoker, aggregator=aggregate, output_plan_resolver=resolver, + # The baseline's stored plan, so planning loads no country model. + stored_plan_resolver=lambda _simulation: shared_output_plan(), ), ) From c00ea9cac4042a2b43bd9ef8cd3eec2a2b309f71 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:05:25 +0400 Subject: [PATCH 2/5] Give comparison-path baselines their stored plan when it holds the report's reads Since the precompute plans the US baselines as simulation runs store them (resolve_simulation_output_plan), only the report-run coordinator's baselines found them. ReportCoordination, which serves shadow comparisons and the operator route, gave each child the report's plan, so every US national baseline segment computed a cache identity the precompute never stores and calculated its baseline. ReportCoordination.child_output_plan now gives the baseline its stored plan whenever that plan holds every column the report reads from the baseline (side_read_plan, checked by the new stored_plan_holds), and keeps the report's plan otherwise, as for include_cliffs reports. The reform always keeps the report's plan. The shared aggregation already reads a side stored under its own plan, zero-filling the labour-supply responses it doesn't store. Both coordinators now resolve a stored plan through CoordinationCore.stored_output_plan. A US national baseline is split into region groups from its own plan, so a comparison report whose reform turns a labour-supply response on now splits its current-law baseline into 20 segments, which find the precomputed files. Co-Authored-By: Claude Opus 5.5 --- ...v2-cache-comparison-baseline-plan.fixed.md | 1 + .../stage-12-modal-worker-foundation.md | 15 ++++++--- .../stage12_runtime/aggregation.py | 3 +- .../stage12_runtime/coordination_core.py | 29 +++++++++++----- .../stage12_runtime/output_planning.py | 20 +++++++++++ .../stage12_runtime/report_coordination.py | 33 +++++++++++++++++-- .../report_run_coordination.py | 7 ++-- 7 files changed, 87 insertions(+), 21 deletions(-) create mode 100644 changelog.d/v2-cache-comparison-baseline-plan.fixed.md diff --git a/changelog.d/v2-cache-comparison-baseline-plan.fixed.md b/changelog.d/v2-cache-comparison-baseline-plan.fixed.md new file mode 100644 index 000000000..75e99e68f --- /dev/null +++ b/changelog.d/v2-cache-comparison-baseline-plan.fixed.md @@ -0,0 +1 @@ +Current-law US national baselines of comparison-path reports in the v2 report app (shadow comparisons with production jobs, and the operator-only `POST /internal/stage12/reports`) load their region-group segments from the precomputed baselines again. Since the precomputed baselines were planned as simulation runs store them, the comparison-path coordinator still gave its baseline the report's plan, so every segment computed a cache key the precompute never stores and calculated its baseline. It now gives the baseline the baseline's stored plan whenever that plan holds every column the report reads from it, as a report run's coordinator does; a report with `include_cliffs: true` and every reform keep the report's plan. A comparison report whose reform turns a labour-supply response on now splits its current-law baseline into 20 segments instead of calculating it in one container. diff --git a/docs/migration/stage-12-modal-worker-foundation.md b/docs/migration/stage-12-modal-worker-foundation.md index 4a31cefec..b8eb48e7a 100644 --- a/docs/migration/stage-12-modal-worker-foundation.md +++ b/docs/migration/stage-12-modal-worker-foundation.md @@ -425,11 +425,18 @@ reads is read with them as zeros. A run that succeeded before this rule, under a report's plan, is reused when it holds what the new report reads from it, and refused (`reused_simulation_output_incompatible`) otherwise. The precomputed US baselines are planned the same way, so a report run's -current-law baseline finds its precomputed files; a comparison-path call (a +current-law baseline finds its precomputed files. A comparison-path call (a shadow comparison with a production job, or the operator-only -`POST /internal/stage12/reports`) still plans its baseline with its report's -plan, so its US national baseline no longer finds them and calculates all 20 -region groups. +`POST /internal/stage12/reports`) gives its baseline the baseline's stored plan +too whenever that plan holds what the report reads from the baseline +(`side_read_plan`), so its current-law US national baseline finds them as +well; it is aggregated as a report run's side is, with any response it doesn't +store read as zeros. Its reform, and the baseline of a report reading columns +the stored plan lacks, such as the cliff columns of `include_cliffs: true`, +keep the report's plan. A US national baseline is split into region groups +from its own plan, so a comparison report whose reform turns a labour-supply +response on now splits its current-law baseline into 20 segments, each found +in the precomputed files, and calculates its reform in one container. **Shared simulation runs.** Identical requests share simulation runs, so a report run may name a run another report run's worker is calculating (C1 · 24, diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/aggregation.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/aggregation.py index ebb6e3e99..4a0e21739 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/aggregation.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/aggregation.py @@ -109,7 +109,8 @@ def validate_aligned_outputs( Raises ``ValueError`` unless the roles, evaluation, bundle, output schema and row identities line up, and each artifact names the plan its own - simulation was given: one plan for both on the comparison path, each + simulation was given: on the comparison path the report's plan, or the + baseline's stored plan when it holds what the report reads, and each simulation's stored plan for a report run. """ if baseline.role.value != "baseline" or reform.role.value != "reform": diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/coordination_core.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/coordination_core.py index 773bb8f60..134df4aea 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/coordination_core.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/coordination_core.py @@ -37,6 +37,7 @@ from .output_planning import ( plan_simulation_input, resolve_report_output_plan, + resolve_simulation_output_plan, validate_output_frames, with_zero_labor_supply_responses, ) @@ -86,12 +87,12 @@ class CoordinatorDependencies: The defaults are the Stage 12 database store, the private artifact bucket, Modal child invocation, the standard aggregate builder and output - plan resolution, no telemetry runtime, the real clock and sleep, the - standard child wait window, and the report run store, the Cloud Storage - reader of reused output files, the stored output plan of each - simulation (``resolve_simulation_output_plan``) and Modal's state of a - call whose probe failed (``modal_call_state``), which only a call that - names a report run uses. + plan resolution, the stored output plan of each simulation + (``resolve_simulation_output_plan``), no telemetry runtime, the real + clock and sleep, the standard child wait window, and the report run + store, the Cloud Storage reader of reused output files and Modal's state + of a call whose probe failed (``modal_call_state``), which only a call + that names a report run uses. """ store: ComparisonStore | None = None @@ -174,7 +175,7 @@ def plan_simulations( """Plan the report's outputs, then each simulation's child input. The child's plan is ``child_output_plan``'s: the report's own plan - unless a coordinator plans each simulation by itself. + unless a coordinator gives a simulation its stored plan. """ with self.stage_scope( Stage.STAGE12_OUTPUT_PLANNING, @@ -203,12 +204,24 @@ def plan_simulations( def child_output_plan( self, - simulation: SimulationExecutionInput, # noqa: ARG002 # a coordinator that plans each simulation by itself reads it + simulation: SimulationExecutionInput, # noqa: ARG002 # a coordinator that gives a simulation its stored plan reads it output_plan: Stage12OutputPlan, ) -> Stage12OutputPlan: """Return the plan ``simulation``'s child calculates: the report's own.""" return output_plan + def stored_output_plan( + self, simulation: SimulationExecutionInput + ) -> Stage12OutputPlan: + """Return the plan every run of ``simulation`` stores, whatever report names it. + + It is ``resolve_simulation_output_plan``'s, or the seam's when set. + """ + resolver = self.dependencies.stored_plan_resolver + if resolver is not None: + return resolver(simulation) + return resolve_simulation_output_plan(simulation, stage_scope=self.stage_scope) + def spawn_child( self, simulation: PlannedSimulationExecutionInput, diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/output_planning.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/output_planning.py index 7a5b398c8..bb0d58056 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/output_planning.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/output_planning.py @@ -285,6 +285,26 @@ def side_read_plan( ) +def stored_plan_holds( + stored_plan: Stage12OutputPlan, read_plan: Stage12OutputPlan +) -> bool: + """Whether a side stored under ``stored_plan`` holds what ``read_plan`` names. + + That is every entity of ``read_plan`` and every column it materializes + for that entity, such as what a report reads from a side + (``side_read_plan``). + """ + stored_columns = { + entity.entity: set(entity.materialized_variables) + for entity in stored_plan.entities + } + return all( + entity.entity in stored_columns + and set(entity.materialized_variables) <= stored_columns[entity.entity] + for entity in read_plan.entities + ) + + def with_zero_labor_supply_responses( frames: Mapping[str, pd.DataFrame], read_plan: Stage12OutputPlan, diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/report_coordination.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/report_coordination.py index b6ec20817..4aa147dcb 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/report_coordination.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/report_coordination.py @@ -2,9 +2,12 @@ The comparison path's coordinator creates an evaluation child record for each simulation, starts or reattaches its worker, then aggregates both -outputs, stores the aggregate and completes its evaluation record. A -detailed-save report run is coordinated on the run tables instead -(``report_run_coordination``). +outputs, stores the aggregate and completes its evaluation record. Its +baseline calculates the baseline's stored plan when that plan holds what the +report reads from it, so a current-law US national baseline finds the +precomputed baselines; otherwise, and for the reform, a child calculates the +report's plan. A detailed-save report run is coordinated on the run tables +instead (``report_run_coordination``). """ from __future__ import annotations @@ -23,6 +26,7 @@ ComparisonSimulationRecord, PlannedSimulationExecutionInput, SimulationArtifactDescriptor, + SimulationExecutionInput, SimulationRole, Stage12OutputPlan, ) @@ -55,6 +59,7 @@ report_failure, ) from .failures import Stage12ExecutionError, Stage12FailureDetail +from .output_planning import side_read_plan, stored_plan_holds from .simulation import descriptor_from_record if TYPE_CHECKING: @@ -86,6 +91,28 @@ def run(self, parent: ComparisonReportRecord) -> dict[str, Any]: wait_for_children(self, calls, descriptors) return self._aggregate_and_complete(parent, output_plan, descriptors) + def child_output_plan( + self, + simulation: SimulationExecutionInput, + output_plan: Stage12OutputPlan, + ) -> Stage12OutputPlan: + """Return the baseline's stored plan if it holds what the report reads from it. + + The precompute stores each current-law US national baseline under + that plan, so the baseline's segments find the precomputed files. A + report reading columns the stored plan lacks, such as the cliff + columns, keeps ``output_plan``, the report's own, for its baseline, + and the reform always keeps it. The aggregation reads a side stored + under its own plan, with any labour-supply response it doesn't store + as zeros, as a report run's does. + """ + if simulation.role is not SimulationRole.BASELINE: + return output_plan + stored_plan = self.stored_output_plan(simulation) + if stored_plan_holds(stored_plan, side_read_plan(output_plan, stored_plan)): + return stored_plan + return output_plan + def child_descriptor( self, role: str, result: object ) -> SimulationArtifactDescriptor: diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/report_run_coordination.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/report_run_coordination.py index cf8d3e7f6..157d9ed64 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/report_run_coordination.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/report_run_coordination.py @@ -57,7 +57,7 @@ Stage12FailureDetail, Stage12InputError, ) -from .output_planning import resolve_simulation_output_plan, side_read_plan +from .output_planning import side_read_plan from .parent_claim import validate_dispatch_context from .report_run_access import report_run_store from .report_run_recording import ( @@ -421,10 +421,7 @@ def child_output_plan( Identical requests share simulation runs, so a run's file holds what any report reads from that side; this report reads ``output_plan``. """ - resolver = self.dependencies.stored_plan_resolver - if resolver is not None: - return resolver(simulation) - return resolve_simulation_output_plan(simulation, stage_scope=self.stage_scope) + return self.stored_output_plan(simulation) def _calculated_as_the_baseline( self, simulation: PlannedSimulationExecutionInput From 32bf311bfdd9e95ef7a60e56a12f38e9dd6b2274 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:23:10 +0400 Subject: [PATCH 3/5] Describe each child's own plan in the Stage 12 docs and test both report shapes Review found passages that still said both children get the same plan, that segmentation follows a shared plan, and that the precomputed files serve only report runs; they now describe each child's own plan. The changelog and the migration doc now say that any US national baseline whose own policy turns no response on is split when its reform turns one on, and that only the precomputed years and SPM selection load from the cache. The observability skill describes the stored-plan resolution inside stage12_child_input_planning. The aggregation test now covers a report turning no response on, where the baseline's file holds columns neither side reads, and its name says what it checks: the aggregation receives the same values in every column the report reads. Co-Authored-By: Claude Opus 5.5 --- ...v2-cache-comparison-baseline-plan.fixed.md | 2 +- docs/engineering/skills/observability.md | 10 ++-- .../stage-12-modal-worker-foundation.md | 36 ++++++++----- .../test_stage12_comparison_baseline_cache.py | 52 +++++++++++++++---- 4 files changed, 73 insertions(+), 27 deletions(-) diff --git a/changelog.d/v2-cache-comparison-baseline-plan.fixed.md b/changelog.d/v2-cache-comparison-baseline-plan.fixed.md index 75e99e68f..4a05a4799 100644 --- a/changelog.d/v2-cache-comparison-baseline-plan.fixed.md +++ b/changelog.d/v2-cache-comparison-baseline-plan.fixed.md @@ -1 +1 @@ -Current-law US national baselines of comparison-path reports in the v2 report app (shadow comparisons with production jobs, and the operator-only `POST /internal/stage12/reports`) load their region-group segments from the precomputed baselines again. Since the precomputed baselines were planned as simulation runs store them, the comparison-path coordinator still gave its baseline the report's plan, so every segment computed a cache key the precompute never stores and calculated its baseline. It now gives the baseline the baseline's stored plan whenever that plan holds every column the report reads from it, as a report run's coordinator does; a report with `include_cliffs: true` and every reform keep the report's plan. A comparison report whose reform turns a labour-supply response on now splits its current-law baseline into 20 segments instead of calculating it in one container. +Current-law US national baselines of comparison-path reports in the v2 report app (shadow comparisons with production jobs, and the operator-only `POST /internal/stage12/reports`) load their region-group segments from the precomputed baselines again, for the years and SPM selection the precompute stores. Since the precomputed baselines were planned as simulation runs store them, the comparison-path coordinator still gave its baseline the report's plan, so every segment computed a cache key the precompute never stores and calculated its baseline. It now gives the baseline the baseline's stored plan whenever that plan holds every column the report reads from it, as a report run's coordinator does; a report with `include_cliffs: true` and every reform keep the report's plan. A comparison report whose reform turns a labour-supply response on, and whose baseline's own policy turns none on, now splits its US national baseline into 20 region-group segments instead of calculating it in one container. diff --git a/docs/engineering/skills/observability.md b/docs/engineering/skills/observability.md index b763b0981..231f187aa 100644 --- a/docs/engineering/skills/observability.md +++ b/docs/engineering/skills/observability.md @@ -138,11 +138,15 @@ operations: | `stage12_country_model_load` | Loading the country model and its Python modules | | `stage12_output_configuration` | Creating planning simulations and configuring requested output groups | | `stage12_output_variable_resolution` | Resolving entity variables and constructing the output schema | -| `stage12_child_input_planning` | Attaching the output plan to one baseline or reform child input | +| `stage12_child_input_planning` | Choosing one baseline or reform child's output plan and attaching it to the child input | `stage12_child_input_planning` runs once for each simulation and includes a -`simulation_role` attribute. The other planning operations include the -`country` attribute. +`simulation_role` attribute. Where a child is given its simulation's stored +plan (each child of a report run, and a comparison-path report's baseline), +resolving that plan records its own `stage12_country_model_load`, +`stage12_output_configuration` and `stage12_output_variable_resolution` +operations inside it. The other planning operations include the `country` +attribute. ### Annual job stage durations diff --git a/docs/migration/stage-12-modal-worker-foundation.md b/docs/migration/stage-12-modal-worker-foundation.md index b8eb48e7a..f44f16099 100644 --- a/docs/migration/stage-12-modal-worker-foundation.md +++ b/docs/migration/stage-12-modal-worker-foundation.md @@ -435,8 +435,11 @@ store read as zeros. Its reform, and the baseline of a report reading columns the stored plan lacks, such as the cliff columns of `include_cliffs: true`, keep the report's plan. A US national baseline is split into region groups from its own plan, so a comparison report whose reform turns a labour-supply -response on now splits its current-law baseline into 20 segments, each found -in the precomputed files, and calculates its reform in one container. +response on, and whose baseline's own policy turns none on, now splits its +baseline into 20 segments and calculates its reform in one container. A +current-law baseline's segments are then found in the precomputed files when +the report's year and SPM selection are ones the precompute stores; any other +such baseline calculates all 20 region groups. **Shared simulation runs.** Identical requests share simulation runs, so a report run may name a run another report run's worker is calculating (C1 · 24, @@ -549,13 +552,18 @@ Planning never loads a dataset or executes a simulation. The former `variables=("*",)` internal marker is not an output expansion mechanism and is no longer used. -The coordinator includes the exact same output plan in the baseline and reform -child inputs. Each child adds the plan's additional variables before calling +The comparison-path coordinator gives the reform child the report's output +plan, and the baseline child either the same plan or, when it holds every +column the report reads from the baseline, the baseline's stored plan (see +"What a simulation run stores"); a report run's coordinator gives each child +its stored plan. Each child adds its plan's additional variables before calling `Simulation.ensure()`, then verifies that every planned entity and column is present before writing its Parquet artifact. The artifact descriptor records a -digest of the plan. After both calls complete, the coordinator checks both plan -digests and independently validates both loaded Parquet schemas before it runs -aggregate calculations. Extra columns are permitted; missing planned columns +digest of the plan. After both calls complete, the coordinator checks each +artifact's plan digest against the plan its child was given, and validates +both loaded Parquet schemas against the report's plan, with any labour-supply +response a side doesn't store read as zeros, before it runs aggregate +calculations. Extra columns are permitted; missing planned columns fail the temporary Stage 12 report without affecting the production result. The plan distinguishes calculated variables from columns copied directly from @@ -656,9 +664,10 @@ Stage 12. ## US segmentation and baseline cache -Segmentation applies by default when both simulation inputs describe a US -national society-wide calculation and the shared output plan does not require -cliff analysis or labor-supply responses. `segmented=false` selects the +Segmentation applies by default to each simulation that describes a US +national society-wide calculation and whose own output plan does not require +cliff analysis or labor-supply responses, so a report may split one side and +calculate the other in one container. `segmented=false` selects the single-container calculation explicitly. UK calculations, subnational US calculations, a report's cliff analysis, and labor-supply-response calculations also use the single-container path. A simulation run's own cliff @@ -667,9 +676,10 @@ is (`should_segment_cliff_calculation`), and its cliff gap and share are taken from the merged rows. `segmented=true` is accepted, but it does not override those numerical eligibility conditions. A US national simulation run started on its own (role `standalone`) is segmented by the same rule. It never -uses the precomputed baseline files, which serve only a report run's -current-law baseline, planned as its simulation run stores its output, so it -calculates all 20 region groups. +uses the precomputed baseline files, which serve only a report's +current-law baseline planned as its simulation run stores its output (a +report run's, or a comparison-path report's that reads no column the stored +plan lacks), so it calculates all 20 region groups. The Stage 12 coordinator still persists only two logical simulation records: one baseline and one reform. Each eligible logical simulation call performs diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_comparison_baseline_cache.py b/projects/policyengine-simulation-executor/tests/test_stage12_comparison_baseline_cache.py index f9faa2545..2796b8c7e 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_comparison_baseline_cache.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_comparison_baseline_cache.py @@ -376,19 +376,51 @@ def _report_columns(frames, report_plan): } -def test_a_baseline_stored_under_its_own_plan_is_aggregated_as_under_the_report_plan(): - # The reform turns responses on, so the report reads them and the copied - # inputs; the current-law baseline's stored plan holds the copied inputs - # and no response. - report_plan = _with_person_columns( - shared_output_plan(), - US_RESPONSES + US_COPIED_INPUTS, - labour_supply_response_active=True, +def _labour_supply_report_plans() -> tuple[Stage12OutputPlan, Stage12OutputPlan]: + """Return the plans of a report whose reform turns responses on. + + The report reads the responses and the copied inputs; the current-law + baseline's stored plan holds the copied inputs and no response. + """ + return ( + _with_person_columns( + shared_output_plan(), + US_RESPONSES + US_COPIED_INPUTS, + labour_supply_response_active=True, + ), + _with_person_columns( + shared_output_plan(), US_COPIED_INPUTS, labour_supply_response_active=False + ), ) - baseline_stored_plan = _with_person_columns( - shared_output_plan(), US_COPIED_INPUTS, labour_supply_response_active=False + + +def _no_response_report_plans() -> tuple[Stage12OutputPlan, Stage12OutputPlan]: + """Return the plans of a report turning no response on. + + The baseline's stored plan holds the copied inputs, which neither side of + the report reads. + """ + return ( + shared_output_plan(), + _with_person_columns( + shared_output_plan(), US_COPIED_INPUTS, labour_supply_response_active=False + ), ) + +@pytest.mark.parametrize( + "report_plans", + [_labour_supply_report_plans, _no_response_report_plans], + ids=["reform_turns_responses_on", "no_responses"], +) +def test_a_baseline_stored_under_its_own_plan_gives_the_same_report_columns( + report_plans, +): + # The aggregation reads each side's columns by name, so a side whose + # report-plan columns hold the same values aggregates to the same result, + # whatever other columns its file holds. + report_plan, baseline_stored_plan = report_plans() + stored_planned, stored_frames = _aggregated_frames( report_plan, baseline_stored_plan ) From d8b2e999d14f0771debddc39a46d44886dc8e698 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:38:36 +0400 Subject: [PATCH 4/5] Say that every comparison-path baseline resolves its stored plan The observability skill said the nested planning operations appear where a child is given its stored plan; the comparison-path coordinator resolves the baseline's stored plan before checking it, so a baseline that keeps the report's plan records them too. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/observability.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/engineering/skills/observability.md b/docs/engineering/skills/observability.md index 231f187aa..573796854 100644 --- a/docs/engineering/skills/observability.md +++ b/docs/engineering/skills/observability.md @@ -141,9 +141,10 @@ operations: | `stage12_child_input_planning` | Choosing one baseline or reform child's output plan and attaching it to the child input | `stage12_child_input_planning` runs once for each simulation and includes a -`simulation_role` attribute. Where a child is given its simulation's stored -plan (each child of a report run, and a comparison-path report's baseline), -resolving that plan records its own `stage12_country_model_load`, +`simulation_role` attribute. Where a coordinator resolves a simulation's +stored plan (for each child of a report run, and for every comparison-path +report's baseline, including one that then keeps the report's plan), that +resolution records its own `stage12_country_model_load`, `stage12_output_configuration` and `stage12_output_variable_resolution` operations inside it. The other planning operations include the `country` attribute. From e84f1cc008023a4f5f8344e88382668eaea18e43 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:09:21 +0400 Subject: [PATCH 5/5] Look up the segment's cache identity with the handlers' run scope Since #1136, qualifying_cache_identity takes the run's RunScope (country, year, region and dataset selection) in place of the dataset-default flag and the scoping strategy. The test now builds it as the segment worker does. Against main's coordinator the identity test still fails with stage12-bl1-6bf58faeedaedc36 against stage12-bl1-928929ee9ffcc2a4. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_stage12_comparison_baseline_cache.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_comparison_baseline_cache.py b/projects/policyengine-simulation-executor/tests/test_stage12_comparison_baseline_cache.py index 2796b8c7e..dd0ad23df 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_comparison_baseline_cache.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_comparison_baseline_cache.py @@ -36,7 +36,7 @@ from policyengine_simulation_executor import simulation_runtime from policyengine_simulation_executor.spm import normalize_runtime_spm from policyengine_simulation_executor.stage12_bundle import load_stage12_bundle -from policyengine_simulation_executor.stage12_cache import precompute_planning +from policyengine_simulation_executor.stage12_cache import levels, precompute_planning from policyengine_simulation_executor.stage12_runtime import segmentation from policyengine_simulation_executor.stage12_runtime.cached_simulation import ( qualifying_cache_identity, @@ -204,8 +204,12 @@ def _group_segment_identity( return qualifying_cache_identity( scoped, resolved=load_stage12_bundle(), - dataset_is_default=dataset_selection.is_default, - scoping_strategy=region.scoping_strategy, + run=levels.RunScope( + country=scoped.geography.country, + year=scoped.year, + region=region, + dataset=dataset_selection, + ), spm=normalize_runtime_spm(params), )