diff --git a/changelog.d/v2-cache-level-handlers.changed.md b/changelog.d/v2-cache-level-handlers.changed.md new file mode 100644 index 000000000..d580ddda6 --- /dev/null +++ b/changelog.d/v2-cache-level-handlers.changed.md @@ -0,0 +1 @@ +The v2 report app's cache now plans, builds and looks up its files through the same level handlers as the run_simulation app, with its own list of the levels it covers (US national and state year files, and the 20 state-group baselines). Its keys, store paths, files and fixed baseline IDs are unchanged. The files now sit under `prebuilt/us///` in the US worker image, every manifest entry records its folder, so the manifest digest changes once, and the image build checks the years and file counts the deploying machine computes from the handler settings. diff --git a/docs/migration/stage-12-modal-worker-foundation.md b/docs/migration/stage-12-modal-worker-foundation.md index 4a31cefec..ea48814aa 100644 --- a/docs/migration/stage-12-modal-worker-foundation.md +++ b/docs/migration/stage-12-modal-worker-foundation.md @@ -768,12 +768,20 @@ filter, and stores each state's file under the year file's own name. It refuses data in which a household's district code names another state's district, because district runs read their state's file. -Precompute publishes a canonical manifest containing the 63 national files and -the state datasets. The deployment passes that manifest's SHA-256 digest into -the US image build. The image build downloads and verifies every listed file, -placing each state dataset in `state-datasets///` under the -data folder, then records the exact cache release in worker-validation -metadata and the v2 version manifest. A state or district calculation reads +Precompute plans these files through the level handlers in +`stage12_cache/levels*.py`, which the run_simulation app also uses: the years +come from the US handler settings, the files from the handlers of the levels +`stage12_cache/cache_levels.py` lists for this cache (US national and state +year files, and the state-group baselines). It publishes a canonical manifest +containing the 63 national files and the state datasets, each entry naming the +prebuilt folder its file lands in. The deployment passes that manifest's +SHA-256 digest, and the years and counts the cache must hold +(`expected_cache_contents`), into the US image build. The image build +downloads and verifies every listed file into its folder under the data +folder: the national year files and the baselines computed on them in +`prebuilt/us//all/`, and each state dataset in +`prebuilt/us///`. It then records the exact cache release in +worker-validation metadata and the v2 version manifest. A state or district calculation reads its state's file when the image holds it for the requested year and .py would reuse it, and prepares the dataset during the calculation otherwise. The UK and coordinator images do not contain these files. Deployment validation runs diff --git a/projects/policyengine-simulation-executor/README.md b/projects/policyengine-simulation-executor/README.md index b3859af39..021a72233 100644 --- a/projects/policyengine-simulation-executor/README.md +++ b/projects/policyengine-simulation-executor/README.md @@ -448,10 +448,15 @@ workers, its image and functions mount only the read-only `pe-uk-private-hf-read-token` Hugging Face secret, which supplies `HUGGING_FACE_TOKEN`, and `stage12-evaluation-gcp-credentials`; the US data it reads comes from the -public `policyengine/populace-us` dataset repository. The US worker image -downloads and verifies the manifest's files during image construction: the 63 -national files into the data folder, and each state dataset into -`state-datasets///` under the year file's own name. The +public `policyengine/populace-us` dataset repository. The plan comes from +the level handlers in `stage12_cache/levels*.py` and the cache's own levels in +`stage12_cache/cache_levels.py`. The US worker image downloads and verifies +the manifest's files during image construction, each into the prebuilt folder +its manifest entry names: the 63 national files into +`prebuilt/us//all/`, and each state dataset into +`prebuilt/us///` under the year file's own name. The +deploying machine passes the image build the years and file counts to expect +(`expected_cache_contents`). The release validation checks the recorded manifest, hashes a baseline file, and requires a real calculation to load that file without recomputing it. Worker validation also calculates a US household under a nonempty CTC reform using @@ -460,8 +465,9 @@ digest is then stored in the separate v2 version manifest. The cache is an optimization, not required state for a calculation: an absent file causes a normal calculation, and a file missing planned output columns is -recalculated. Only empty-policy baseline region-group calculations against the -bundle's default dataset are eligible to read it. Reform calculations never +recalculated. Only empty-policy baseline calculations of a group of states against +the bundle's default dataset, at a level `cache_levels.py` lists, are eligible +to read it. Reform calculations never read a baseline file. ## Observability diff --git a/projects/policyengine-simulation-executor/fixtures/v2_cache_us_inputs.py b/projects/policyengine-simulation-executor/fixtures/v2_cache_us_inputs.py new file mode 100644 index 000000000..61b5144c7 --- /dev/null +++ b/projects/policyengine-simulation-executor/fixtures/v2_cache_us_inputs.py @@ -0,0 +1,411 @@ +"""Fixed inputs for the tests that pin what the v2 report app's US cache does today. + +The v2 cache (``stage12_cache``) plans, keys and looks up its files from the +installed Stage 12 bundle, the release bundle, .py's dataset names, the SPM +capability, the US country model's regions and its own cache bucket. +``install_v2_cache_us_inputs`` replaces each with a fixed stand-in, so the +plan, the keys, the manifest and the lookup outcomes are pure functions of +the values below and can be compared with recorded values exactly: + +* the Stage 12 bundle lists two US datasets, the default ``populace_us_2024`` + and the state-level ``populace_us_2024_acs_local``, with fixed hashes, + revisions and package versions, and a fixed bundle digest; +* the release bundle maps the same two names to fixed URIs, so state regions + resolve to the state-level dataset as today's US model's states do; +* the 51 US state regions (50 states and DC) have the real region codes, + state codes and FIPS numbers, scoped by a ``state_fips`` row filter; +* .py's dataset-name lookups return the dataset's own name; +* the cache bucket is a fake GCS client kept in memory. + +The national partition is NOT replaced: plans use the real 20 region groups +in ``stage12_runtime.partition.US_REGION_GROUPS``. The output plan and the +region groups' scope keys come from this repository's code and the installed +.py, as they do in production. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from hashlib import sha256 +from pathlib import Path +from types import SimpleNamespace +from typing import TYPE_CHECKING, Any + +from google.api_core.exceptions import NotFound, PreconditionFailed +from policyengine.core.scoping_strategy import RowFilterStrategy +from policyengine_simulation_contract.spm import SPMCapability +from policyengine_simulation_contract.stage12_bundle import ( + ResolvedStage12Bundle, + Stage12BundleManifest, + Stage12CountryBundle, + Stage12Dataset, +) +from policyengine_simulation_executor import ( + region_resolution, + release_bundle, + simulation_runtime, +) +from policyengine_simulation_executor.stage12_cache import ( + precompute_baselines, + precompute_datasets, + precompute_planning, + store, +) +from policyengine_simulation_executor.stage12_runtime import ( + simulation as stage12_simulation, +) + +if TYPE_CHECKING: + import pytest + +# (state code, FIPS number) for the 50 states and DC, in FIPS order. +US_STATE_FIPS: tuple[tuple[str, int], ...] = ( + ("AL", 1), + ("AK", 2), + ("AZ", 4), + ("AR", 5), + ("CA", 6), + ("CO", 8), + ("CT", 9), + ("DE", 10), + ("DC", 11), + ("FL", 12), + ("GA", 13), + ("HI", 15), + ("ID", 16), + ("IL", 17), + ("IN", 18), + ("IA", 19), + ("KS", 20), + ("KY", 21), + ("LA", 22), + ("ME", 23), + ("MD", 24), + ("MA", 25), + ("MI", 26), + ("MN", 27), + ("MS", 28), + ("MO", 29), + ("MT", 30), + ("NE", 31), + ("NV", 32), + ("NH", 33), + ("NJ", 34), + ("NM", 35), + ("NY", 36), + ("NC", 37), + ("ND", 38), + ("OH", 39), + ("OK", 40), + ("OR", 41), + ("PA", 42), + ("RI", 44), + ("SC", 45), + ("SD", 46), + ("TN", 47), + ("TX", 48), + ("UT", 49), + ("VT", 50), + ("VA", 51), + ("WA", 53), + ("WV", 54), + ("WI", 55), + ("WY", 56), +) + +DEFAULT_DATASET = "populace_us_2024" +STATE_LEVEL_DATASET = "populace_us_2024_acs_local" +DEFAULT_DATASET_URI = "hf://policyengine/populace-us/populace_us_2024.h5@rev-default" +STATE_LEVEL_DATASET_URI = ( + "hf://policyengine/populace-us/populace_us_2024_acs_local.h5@rev-local" +) +BUNDLE_MANIFEST_SHA256 = "b" * 64 +DEFAULT_DATASET_SHA256 = "1" * 64 +STATE_LEVEL_DATASET_SHA256 = "2" * 64 +POLICYENGINE_VERSION = "6.20.0" +CORE_PACKAGE_VERSION = "3.33.3" +US_PACKAGE_VERSION = "2.2.2" +DATA_PACKAGE_VERSION = "1.4.0" +DATA_ARTIFACT_REVISION = "rev-default" + + +def fixed_stage12_bundle() -> ResolvedStage12Bundle: + """Return the installed Stage 12 bundle the pins use, with fixed values.""" + default = Stage12Dataset( + identity=DEFAULT_DATASET, + uri=DEFAULT_DATASET_URI, + artifact_revision=DATA_ARTIFACT_REVISION, + sha256=DEFAULT_DATASET_SHA256, + repo_type="dataset", + ) + state_level = Stage12Dataset( + identity=STATE_LEVEL_DATASET, + uri=STATE_LEVEL_DATASET_URI, + artifact_revision="rev-local", + sha256=STATE_LEVEL_DATASET_SHA256, + repo_type="dataset", + ) + country = Stage12CountryBundle( + country="us", + country_package_name="policyengine-us", + country_package_version=US_PACKAGE_VERSION, + country_package_requirement=f"policyengine-us=={US_PACKAGE_VERSION}", + data_package_name="populace-us", + data_package_version=DATA_PACKAGE_VERSION, + data_release_version=DATA_PACKAGE_VERSION, + data_artifact_revision=DATA_ARTIFACT_REVISION, + default_dataset=DEFAULT_DATASET, + default_dataset_uri=DEFAULT_DATASET_URI, + datasets=(default, state_level), + ) + return ResolvedStage12Bundle( + bundle=Stage12BundleManifest( + policyengine_version=POLICYENGINE_VERSION, + policyengine_requirement=f"policyengine=={POLICYENGINE_VERSION}", + core_package_version=CORE_PACKAGE_VERSION, + core_package_requirement=f"policyengine-core=={CORE_PACKAGE_VERSION}", + countries=(country,), + ), + bundle_manifest_sha256=BUNDLE_MANIFEST_SHA256, + ) + + +def fixed_release_bundle() -> SimpleNamespace: + """Return the release bundle region and dataset resolution read.""" + return SimpleNamespace( + country="us", + policyengine_version=POLICYENGINE_VERSION, + model_version=US_PACKAGE_VERSION, + data_version=DATA_PACKAGE_VERSION, + data_package_version=DATA_PACKAGE_VERSION, + data_artifact_revision=DATA_ARTIFACT_REVISION, + default_dataset=DEFAULT_DATASET, + default_dataset_uri=DEFAULT_DATASET_URI, + dataset_uris={ + DEFAULT_DATASET: DEFAULT_DATASET_URI, + STATE_LEVEL_DATASET: STATE_LEVEL_DATASET_URI, + }, + ) + + +def us_state_regions() -> list[SimpleNamespace]: + """Return stand-ins for the US model's 51 states, on the state-level dataset.""" + return [ + SimpleNamespace( + code=f"state/{state_code.lower()}", + label=state_code, + dataset_path=STATE_LEVEL_DATASET_URI, + scoping_strategy=RowFilterStrategy( + variable_name="state_fips", variable_value=state_fips + ), + parent_code="us", + state_code=state_code, + ) + for state_code, state_fips in US_STATE_FIPS + ] + + +def us_district_region(state_code: str, district_number: int) -> SimpleNamespace: + """Return a stand-in congressional district of ``state_code``.""" + state_fips = dict(US_STATE_FIPS)[state_code] + return SimpleNamespace( + code=f"congressional_district/{state_code}{district_number:02d}", + label=f"{state_code}-{district_number:02d}", + dataset_path=STATE_LEVEL_DATASET_URI, + scoping_strategy=RowFilterStrategy( + variable_name="congressional_district_geoid", + variable_value=state_fips * 100 + district_number, + ), + parent_code=f"state/{state_code.lower()}", + state_code=state_code, + ) + + +def fixed_spm_capability() -> SPMCapability: + """Return an SPM capability whose defaults are fixed values. + + The installed image's capability pins the forecast it ships; this one + pins a synthetic forecast hash, so SPM-keyed identities stay fixed. + """ + return SPMCapability.model_validate( + { + "defaults": { + "forecast_content_sha256": "a" * 64, + "scenario": "ce_trend", + "geography_kind": "national", + "geography_id": None, + "county_vintage": "2020", + "as_of": None, + } + } + ) + + +@dataclass +class InMemoryCacheBucket: + """A fake GCS client over one in-memory bucket. + + ``objects`` maps an object path to its bytes and ``metadata`` to the + metadata stored with it. Writes with ``if_generation_match=0`` to an + existing path raise ``PreconditionFailed``, as GCS does. + """ + + objects: dict[str, bytes] = field(default_factory=dict) + metadata: dict[str, dict[str, str]] = field(default_factory=dict) + + def bucket(self, _bucket_name: str) -> SimpleNamespace: + """Return a bucket handle whose blobs read and write ``objects``.""" + return SimpleNamespace(blob=lambda path: _InMemoryBlob(self, path)) + + def store(self, path: str, payload: bytes) -> None: + """Hold ``payload`` at ``path`` with the digest and size an upload records.""" + self.objects[path] = payload + self.metadata[path] = { + "sha256": sha256(payload).hexdigest(), + "size_bytes": str(len(payload)), + } + + +@dataclass +class _InMemoryBlob: + bucket_client: InMemoryCacheBucket + path: str + metadata: dict[str, str] | None = None + + def exists(self) -> bool: + return self.path in self.bucket_client.objects + + def reload(self) -> None: + if self.path not in self.bucket_client.objects: + raise NotFound(self.path) + self.metadata = self.bucket_client.metadata.get(self.path) + + def _write(self, payload: bytes, if_generation_match: int | None) -> None: + if if_generation_match == 0 and self.path in self.bucket_client.objects: + raise PreconditionFailed(self.path) + self.bucket_client.objects[self.path] = payload + self.bucket_client.metadata[self.path] = dict(self.metadata or {}) + + def upload_from_string( + self, + payload: str | bytes, + *, + content_type: str, # noqa: ARG002 # mirrors google.cloud.storage.Blob + if_generation_match: int | None = None, + ) -> None: + self._write( + payload.encode() if isinstance(payload, str) else payload, + if_generation_match, + ) + + def upload_from_filename( + self, filename: str, *, if_generation_match: int | None = None + ) -> None: + self._write(Path(filename).read_bytes(), if_generation_match) + + def download_as_bytes(self) -> bytes: + if self.path not in self.bucket_client.objects: + raise NotFound(self.path) + return self.bucket_client.objects[self.path] + + def download_to_filename(self, filename: str) -> None: + Path(filename).write_bytes(self.download_as_bytes()) + + +def install_v2_cache_us_inputs(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: + """Replace every input of the v2 cache's US plan and lookup with a fixed stand-in. + + Returns the Stage 12 and release bundles, the 51 state regions, the + stand-in US country module, the fake cache bucket and ``spm``, whose + ``spm_capability`` a test may set (None: no SPM capability). + """ + # These two modules import .py's manifest helpers by value while loading; + # import them before the helpers are replaced, so no production module + # binds a stand-in. .py and the SPM module load only when inputs are + # installed, as the module-level import ban requires. + import policyengine.tax_benefit_models.common.model_version + import policyengine.tax_benefit_models.us.datasets # noqa: F401 # must load before the manifest stand-ins (see above) + from policyengine.provenance import manifest as manifest_module + from policyengine_simulation_executor import spm as executor_spm + + stage12_bundle = fixed_stage12_bundle() + for module in ( + precompute_planning, + precompute_datasets, + precompute_baselines, + stage12_simulation, + ): + # Only the modules that read the bundle themselves; the others take it + # from these. + if hasattr(module, "load_stage12_bundle"): + monkeypatch.setattr(module, "load_stage12_bundle", lambda: stage12_bundle) + + release = fixed_release_bundle() + for module in (release_bundle, simulation_runtime, region_resolution): + monkeypatch.setattr( + module, "get_country_release_bundle", lambda _country: release + ) + + monkeypatch.setattr( + manifest_module, + "resolve_dataset_reference", + lambda _country, dataset: f"hf://policyengine/populace-us/{dataset}.h5", + ) + monkeypatch.setattr( + manifest_module, + "dataset_logical_name", + lambda reference: reference.rsplit("/", 1)[-1].split(".h5", 1)[0], + ) + + regions = us_state_regions() + districts = [us_district_region("UT", 1), us_district_region("CA", 12)] + regions_by_code = {region.code: region for region in (*regions, *districts)} + country_module = SimpleNamespace( + model=SimpleNamespace( + get_region=regions_by_code.get, + region_registry=SimpleNamespace( + get_by_type=lambda region_type: { + "state": list(regions), + "congressional_district": list(districts), + }.get(region_type, []) + ), + ) + ) + # The level handlers resolve the country model through simulation_runtime; + # the cache's own modules that import it by name are covered too. + for module in (precompute_planning, precompute_datasets, simulation_runtime): + if hasattr(module, "_country_module"): + monkeypatch.setattr( + module, "_country_module", lambda _country: country_module + ) + + spm_state = SimpleNamespace(spm_capability=None) + monkeypatch.setattr( + executor_spm, "runtime_spm_capability", lambda: spm_state.spm_capability + ) + # Proving a selection can be measured reads the installed forecast; the + # synthetic forecast hash names none. + monkeypatch.setattr( + executor_spm, + "_prevalidate_selection", + lambda _selection_json, _start_year, _window_size: None, + ) + + cache_bucket = InMemoryCacheBucket() + monkeypatch.setattr(store, "_default_client", lambda: cache_bucket) + return SimpleNamespace( + stage12_bundle=stage12_bundle, + release_bundle=release, + regions=regions, + districts=districts, + country_module=country_module, + cache_bucket=cache_bucket, + spm=spm_state, + ) + + +def enable_fixed_spm(inputs: SimpleNamespace) -> dict[str, Any]: + """Give the US bundle ``fixed_spm_capability`` and return its default selection.""" + capability = fixed_spm_capability() + inputs.spm.spm_capability = capability + return capability.defaults.model_dump(mode="json") diff --git a/projects/policyengine-simulation-executor/src/modal/stage12_cache_image.py b/projects/policyengine-simulation-executor/src/modal/stage12_cache_image.py index e6b2513f7..c90048a6e 100644 --- a/projects/policyengine-simulation-executor/src/modal/stage12_cache_image.py +++ b/projects/policyengine-simulation-executor/src/modal/stage12_cache_image.py @@ -1,4 +1,12 @@ -"""Self-contained Stage 12 cache fetch used during Modal image construction.""" +"""Self-contained Stage 12 cache fetch used during Modal image construction. + +It runs as an image-build step before the package source is added to the +image, so it imports only the standard library at module level and nothing +from the package. The deploying machine passes it the manifest and the +contents the cache must hold (``expected_cache_contents``: the years and the +year-file and baseline counts), and each manifest entry names the prebuilt +folder its file lands in. +""" from __future__ import annotations @@ -12,23 +20,40 @@ from google.cloud.storage import Client +_PREBUILT_DIRECTORY = "prebuilt" +# A prebuilt folder names at least the directory, the country and the dataset. +_MINIMUM_FOLDER_PARTS = 3 + + def fetch_stage12_cache( - bucket: str, manifest: dict | None, *, client: Client | None = None + bucket: str, + manifest: dict | None, + expected_contents: dict | None, + *, + client: Client | None = None, ) -> None: - """Download and verify every manifest-listed cache file into the image.""" - artifacts, canonical = _validated_manifest(bucket, manifest) + """Download and verify every manifest-listed cache file into the image. + + ``expected_contents`` holds the years and the ``dataset`` and ``baseline`` + counts the manifest must list. + """ + artifacts, canonical, country = _validated_manifest( + bucket, manifest, expected_contents + ) if client is None: client = _storage_client() data_dir = Path(os.environ["POLICYENGINE_DATA_FOLDER"]) - destinations = _artifact_destinations(artifacts, data_dir) + destinations = _artifact_destinations(artifacts, data_dir, country=country) data_dir.mkdir(parents=True, exist_ok=True) for artifact, destination in zip(artifacts, destinations, strict=True): _fetch_artifact(artifact, client=client, bucket=bucket, destination=destination) (data_dir / ".stage12-cache-manifest.json").write_bytes(canonical) -def _validated_manifest(bucket: str, manifest: dict | None) -> tuple[list, bytes]: - """Return the manifest's artifacts and canonical bytes once it is verified. +def _validated_manifest( + bucket: str, manifest: dict | None, expected_contents: dict | None +) -> tuple[list, bytes, str]: + """Return the manifest's artifacts, canonical bytes and country once verified. The manifest must name the installed bundle, the expected years and artifact counts, and match the deployment's digest. @@ -36,8 +61,9 @@ def _validated_manifest(bucket: str, manifest: dict | None) -> tuple[list, bytes if not bucket or not manifest: msg = "Stage 12 cache deployment has no bucket or manifest" raise RuntimeError(msg) - _require_installed_identity(manifest) - artifacts = _expected_artifacts(manifest) + years, counts = _expected_years_and_counts(expected_contents) + _require_installed_identity(manifest, years) + artifacts = _expected_artifacts(manifest, counts) canonical = json.dumps( manifest, sort_keys=True, @@ -49,10 +75,33 @@ def _validated_manifest(bucket: str, manifest: dict | None) -> tuple[list, bytes if manifest_digest != os.getenv("STAGE12_CACHE_MANIFEST_DIGEST"): msg = "Stage 12 cache manifest digest differs from deployment" raise RuntimeError(msg) - return artifacts, canonical + return artifacts, canonical, str(manifest.get("country")) + + +def _expected_years_and_counts( + expected_contents: dict | None, +) -> tuple[list, dict]: + """Return the years and artifact counts the deployment expects. + + Raises ``RuntimeError`` when the deploying machine passed none, or ones + of another shape. + """ + years = (expected_contents or {}).get("years") + counts = (expected_contents or {}).get("artifact_counts") + if ( + not isinstance(years, list) + or not years + or not all(isinstance(year, int) for year in years) + or not isinstance(counts, dict) + or set(counts) != {"dataset", "baseline"} + or not all(isinstance(count, int) for count in counts.values()) + ): + msg = "Stage 12 cache deployment has no expected contents" + raise RuntimeError(msg) + return years, counts -def _require_installed_identity(manifest: dict) -> None: +def _require_installed_identity(manifest: dict, years: list) -> None: """Require the manifest's schema, installed bundle and precomputed years.""" if manifest.get("schema") != "stage12-mf1": msg = "Stage 12 cache manifest schema is unsupported" @@ -63,16 +112,17 @@ def _require_installed_identity(manifest: dict) -> None: ) != os.getenv("STAGE12_BUNDLE_MANIFEST_SHA256"): msg = "Stage 12 cache manifest names another installed bundle" raise RuntimeError(msg) - if manifest.get("years") != [2026, 2027, 2025]: + if manifest.get("years") != years: msg = "Stage 12 cache manifest has an unexpected year set" raise RuntimeError(msg) -def _expected_artifacts(manifest: dict) -> list: +def _expected_artifacts(manifest: dict, counts: dict) -> list: """Return the manifest's artifact list once its contents are as expected. - It must have 3 datasets and 60 baselines, no artifact of another kind, and - either no state datasets or the same states' files for every year. + It must have the expected numbers of datasets and baselines, no artifact + of another kind, and either no state datasets or the same states' files + for every year. """ artifacts = manifest.get("artifacts") if not isinstance(artifacts, list): @@ -83,7 +133,7 @@ def _expected_artifacts(manifest: dict) -> list: kind: sum(item.get("type") == kind for item in entries) for kind in ("dataset", "baseline") } - if type_counts != {"dataset": 3, "baseline": 60}: + if type_counts != counts: msg = "Stage 12 cache manifest has an unexpected artifact count" raise RuntimeError(msg) if any( @@ -104,20 +154,19 @@ def _expected_artifacts(manifest: dict) -> list: return artifacts -def _relative_destination(artifact: dict) -> PurePosixPath | None: +def _relative_destination(artifact: dict, *, country: str) -> PurePosixPath | None: """Return where a listed file lands, relative to the data folder, or None. - Dataset and baseline files land directly in the data folder; a state - dataset lands in its ``folder``, a relative path without ``.`` or ``..`` - parts. None means the entry names an unsafe place. + Every file lands in its ``folder``: a relative path without ``.`` or + ``..`` parts under ``prebuilt//``, naming at least a dataset, so + prebuilt files never land beside the source datasets the bundle install + writes into the data folder. None means the entry names an unsafe place. """ filename = artifact.get("filename") if not isinstance(filename, str) or PurePosixPath(filename).name != filename: return None if "\\" in filename or filename in {"", ".", ".."}: return None - if artifact.get("type") != "state_dataset": - return PurePosixPath(filename) folder = artifact.get("folder") if not isinstance(folder, str) or not folder or "\\" in folder: return None @@ -126,12 +175,16 @@ def _relative_destination(artifact: dict) -> PurePosixPath | None: PurePosixPath(folder).is_absolute() or any(part in {".", ".."} for part in parts) or "/".join(parts) != folder + or len(parts) < _MINIMUM_FOLDER_PARTS + or parts[:2] != (_PREBUILT_DIRECTORY, country) ): return None return PurePosixPath(folder, filename) -def _artifact_destinations(artifacts: list, data_dir: Path) -> list[Path]: +def _artifact_destinations( + artifacts: list, data_dir: Path, *, country: str +) -> list[Path]: """Check every listed file's metadata and return where each one lands. Runs before anything downloads, so a bad entry leaves no file behind. @@ -142,7 +195,7 @@ def _artifact_destinations(artifacts: list, data_dir: Path) -> list[Path]: if not isinstance(artifact, dict): msg = "Stage 12 cache artifact entry is invalid" raise TypeError(msg) - relative = _relative_destination(artifact) + relative = _relative_destination(artifact, country=country) if ( relative is None or relative in seen diff --git a/projects/policyengine-simulation-executor/src/modal/v2_app.py b/projects/policyengine-simulation-executor/src/modal/v2_app.py index 972735629..42a04f241 100644 --- a/projects/policyengine-simulation-executor/src/modal/v2_app.py +++ b/projects/policyengine-simulation-executor/src/modal/v2_app.py @@ -99,14 +99,24 @@ APP_NAME = v2_application_name(RESOLVED_BUNDLE.bundle.policyengine_version) -def _deploy_time_cache_inputs() -> tuple[str, dict | None]: - """Resolve and validate the cache manifest on the deploying machine.""" +def _deploy_time_cache_inputs() -> tuple[str, dict | None, dict | None]: + """Resolve the cache manifest, and the contents it must hold, when deploying. + + The contents (years and counts) come from the level handlers' settings, + without loading the US model; the image download step checks the + manifest against them. + """ if not modal.is_local(): - return "", None + return "", None, None + from policyengine_simulation_executor.stage12_cache.precompute_planning import ( # noqa: PLC0415 # needed on the deploying machine only + expected_cache_contents, + ) + + contents = expected_cache_contents("us") bucket = os.environ.get("STAGE12_CACHE_BUCKET", "") digest = os.environ.get("STAGE12_CACHE_MANIFEST_DIGEST") if not digest: - return bucket, None + return bucket, None, contents payload = Stage12CacheStore(bucket).read_manifest(digest) if payload is None: msg = "Stage 12 cache manifest is unavailable" @@ -115,10 +125,12 @@ def _deploy_time_cache_inputs() -> tuple[str, dict | None]: if manifest.bundle.bundle_manifest_sha256 != RESOLVED_BUNDLE.bundle_manifest_sha256: msg = "Stage 12 cache manifest names another bundle" raise RuntimeError(msg) - return bucket, manifest.canonical_payload() + return bucket, manifest.canonical_payload(), contents -STAGE12_CACHE_BUCKET, STAGE12_CACHE_MANIFEST = _deploy_time_cache_inputs() +STAGE12_CACHE_BUCKET, STAGE12_CACHE_MANIFEST, STAGE12_CACHE_CONTENTS = ( + _deploy_time_cache_inputs() +) def _external_assertions(environment: dict[str, str]) -> dict[str, str]: @@ -249,12 +261,12 @@ def build_v2_image( if include_us_cache: image = image.run_function( fetch_stage12_cache, - args=(STAGE12_CACHE_BUCKET, STAGE12_CACHE_MANIFEST), + args=(STAGE12_CACHE_BUCKET, STAGE12_CACHE_MANIFEST, STAGE12_CACHE_CONTENTS), secrets=[gcp_secret], cpu=2.0, memory=4096, - # The 63 national files and the state datasets (a file per state - # for each precomputed year), downloaded and hashed in turn. + # The national files and the state datasets (a file per state for + # each precomputed year), downloaded and hashed in turn. timeout=3600, ) return _add_v2_sources(image) diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/cache_levels.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/cache_levels.py new file mode 100644 index 000000000..56b1a45fa --- /dev/null +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/cache_levels.py @@ -0,0 +1,41 @@ +"""Which year files and baselines the v2 report app's cache builds, per country. + +The level handlers (``levels``) say what each country and dataset level +builds; these settings say which of those levels the v2 cache covers. They +are the cache's own, separate from the run_simulation app's +``CountryPrebuilt.year_file_levels`` and ``baseline_levels``, so a task that +adds files or fixed baseline IDs to the run_simulation app does not add them +to the v2 cache by itself. + +``CACHE_BASELINE_LEVELS`` also decides which runs get a fixed cache ID at run +time (``stage12_runtime.cached_simulation.qualifying_cache_identity``): only a +run whose level the cache precomputes baselines for. Today that is the US +state groups, the 20 groups a nationwide US report splits into. UK levels +join at task 2.2 · 6; US single states only if task 2.1 is extended to the v2 +report app. + +Every function reads the settings when called, so tests can replace them. +""" + +from __future__ import annotations + +from policyengine_simulation_executor.stage12_cache.levels import DatasetLevel + +# The year-file levels the cache builds and the image holds, per country. +CACHE_YEAR_FILE_LEVELS: dict[str, tuple[DatasetLevel, ...]] = { + "us": (DatasetLevel.NATIONAL, DatasetLevel.STATE), +} +# The levels whose current-law baselines the cache precomputes, per country. +CACHE_BASELINE_LEVELS: dict[str, tuple[DatasetLevel, ...]] = { + "us": (DatasetLevel.STATE_GROUP,), +} + + +def cache_year_file_levels(country: str) -> tuple[DatasetLevel, ...]: + """Return the year-file levels the cache builds for ``country``, if any.""" + return CACHE_YEAR_FILE_LEVELS.get(country.lower(), ()) + + +def cache_baseline_levels(country: str) -> tuple[DatasetLevel, ...]: + """Return the levels whose baselines the cache precomputes for ``country``.""" + return CACHE_BASELINE_LEVELS.get(country.lower(), ()) diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/models.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/models.py index 68d2aa875..0d27d1c3b 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/models.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/models.py @@ -26,23 +26,31 @@ class CacheBundleIdentity(StrictCacheModel): class DatasetPlanEntry(StrictCacheModel): - """One planned dataset year, its cache path and whether it is already stored.""" + """One planned dataset year, its cache path and whether it is already stored. + ``folder`` is the handler's prebuilt folder for the year file, where the + worker image places it, relative to its data folder. + """ + + country: str year: int digest: str path: str filename: str + folder: str exists: bool class StateDatasetPlanEntry(StrictCacheModel): """One state's planned year file, filtered from a regional dataset. - ``folder`` is where the worker image places the file, relative to its - data folder; every state's file has the same ``filename``. ``exists`` - records whether the bucket already holds it. + ``folder`` is the handler's prebuilt folder for the state, where the + worker image places the file, relative to its data folder; every state's + file has the same ``filename``. ``exists`` records whether the bucket + already holds it. """ + country: str year: int state_code: str region: str @@ -57,16 +65,19 @@ class StateDatasetPlanEntry(StrictCacheModel): class BaselinePlanEntry(StrictCacheModel): """One planned baseline for a year and region group. - ``filename`` is the name .py saves and loads; ``exists`` records whether - the bucket already holds the file. + ``filename`` is the name .py saves and loads, beside the year file it is + computed on, so ``folder`` is that year file's prebuilt folder. + ``exists`` records whether the bucket already holds the file. """ + country: str year: int segment_index: Annotated[int, Field(ge=0, lt=20)] region_codes: Annotated[tuple[str, ...], Field(min_length=1)] digest: str path: str filename: str + folder: str simulation_id: str output_plan_sha256: str exists: bool @@ -148,11 +159,15 @@ class DeterminismVerdict(StrictCacheModel): class ManifestArtifact(StrictCacheModel): - """One dataset or baseline file listed in the cache manifest.""" + """One dataset or baseline file listed in the cache manifest. + + The worker image places it in ``folder``, relative to its data folder. + """ type: Literal["dataset", "baseline"] path: str filename: str + folder: str year: int identity_digest: str content_sha256: str diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/precompute.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/precompute.py index 2aeca5ac5..b1a9bcdf6 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/precompute.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/precompute.py @@ -25,13 +25,11 @@ from .precompute_datasets import build_dataset_impl, build_state_datasets_impl from .precompute_planning import ( DETERMINISM_SCHEMA, - PRECOMPUTE_YEARS, - StateDatasetTarget, determinism_record, determinism_record_path, + expected_cache_contents, plan_artifacts_impl, select_work, - state_dataset_targets, ) from .store import Stage12CacheStore @@ -43,21 +41,19 @@ __all__ = [ "DETERMINISM_SCHEMA", "MANIFEST_DIGEST_PREFIX", - "PRECOMPUTE_YEARS", "CachePrecomputeFunctions", - "StateDatasetTarget", "build_dataset_impl", "build_manifest", "build_state_datasets_impl", "compute_baseline_impl", "determinism_record", "determinism_record_path", + "expected_cache_contents", "manifest_digest_line", "plan_artifacts_impl", "publish_manifest_impl", "run_precompute", "select_work", - "state_dataset_targets", "verify_determinism_impl", ] @@ -72,8 +68,8 @@ def manifest_digest_line(digest: str) -> str: def build_manifest(plan: PrecomputePlan, store: Stage12CacheStore) -> CacheManifest: """List every planned file with the digest and size the bucket reports. - Datasets, then baselines, then state datasets, each in plan order, so a - plan without state datasets keeps the manifest it always had. + Datasets, then baselines, then state datasets, each in plan order. Each + entry records the prebuilt folder the worker image places it in. """ artifacts: list[CacheManifestEntry] = [] for entry in plan.datasets: @@ -83,6 +79,7 @@ def build_manifest(plan: PrecomputePlan, store: Stage12CacheStore) -> CacheManif type="dataset", path=entry.path, filename=entry.filename, + folder=entry.folder, year=entry.year, identity_digest=entry.digest, content_sha256=stored.content_sha256, @@ -96,6 +93,7 @@ def build_manifest(plan: PrecomputePlan, store: Stage12CacheStore) -> CacheManif type="baseline", path=entry.path, filename=entry.filename, + folder=entry.folder, year=entry.year, identity_digest=entry.digest, content_sha256=stored.content_sha256, diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/precompute_baselines.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/precompute_baselines.py index 3a0dce0ae..85edf239b 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/precompute_baselines.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/precompute_baselines.py @@ -22,6 +22,7 @@ ) from .precompute_planning import ( baseline_identity, + bundle_country, determinism_record, determinism_record_path, scoped_planned_simulation, @@ -34,10 +35,23 @@ import pandas as pd -def _ensure_dataset_file(bucket: str, year: int) -> None: +def _baseline_folder(expected: BaselinePlanEntry) -> Path: + """Return the prebuilt folder of a baseline and the year file it is computed on.""" + return Path(simulation_runtime.resolve_data_folder()) / expected.folder - identity = collect_dataset_identity(load_stage12_bundle(), country="us", year=year) - local_path = Path(simulation_runtime.resolve_data_folder()) / identity.filename + +def _ensure_year_file(bucket: str, expected: BaselinePlanEntry) -> None: + """Download the baseline's year file into its prebuilt folder unless it is there. + + The worker's prebuilt-folder lookup then loads the year file from that + folder, and .py saves the computed baseline beside it. + """ + identity = collect_dataset_identity( + load_stage12_bundle(), + country=bundle_country(expected.country), + year=expected.year, + ) + local_path = _baseline_folder(expected) / identity.filename if not local_path.exists(): Stage12CacheStore(bucket).download_file(identity.store_path, local_path) @@ -52,15 +66,17 @@ def compute_baseline_impl( already holds other data. """ simulation, identity = baseline_identity( - expected.year, tuple(expected.region_codes) + expected.year, + tuple(expected.region_codes), + country=bundle_country(expected.country), ) if identity.store_path != expected.path: msg = "planned and runtime Stage 12 baseline identities differ" raise RuntimeError(msg) - _ensure_dataset_file(bucket, expected.year) + _ensure_year_file(bucket, expected) started = time.monotonic() stage12_simulation.calculate_simulation_frames(simulation) - local_path = Path(simulation_runtime.resolve_data_folder()) / identity.filename + local_path = _baseline_folder(expected) / identity.filename if not local_path.exists(): msg = ( f"Stage 12 baseline calculation produced no cache file {identity.filename}" @@ -108,10 +124,13 @@ def verify_determinism_impl( raise RuntimeError(msg) store = Stage12CacheStore(bucket) group = tuple(expected.region_codes) - baseline = scoped_planned_simulation(expected.year, group) - reform = scoped_planned_simulation(expected.year, group, reform=True) - _ensure_dataset_file(bucket, expected.year) - local_path = Path(simulation_runtime.resolve_data_folder()) / expected.filename + country = bundle_country(expected.country) + baseline = scoped_planned_simulation(expected.year, group, country=country) + reform = scoped_planned_simulation( + expected.year, group, reform=True, country=country + ) + _ensure_year_file(bucket, expected) + local_path = _baseline_folder(expected) / expected.filename if not local_path.exists(): store.download_file(expected.path, local_path) cached_calculation = stage12_simulation.calculate_simulation_frames(baseline) diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/precompute_datasets.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/precompute_datasets.py index 663cf6f4b..1de8be7fb 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/precompute_datasets.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/precompute_datasets.py @@ -1,55 +1,73 @@ -"""Build the Stage 12 cache's national and per-state datasets.""" +"""Build the Stage 12 cache's year files through the level handlers, then upload them. + +The handlers write the files: the national handler has .py prepare the +default dataset's year file, and the state handler filters each state's rows +of the state-level dataset's year file and checks .py would reuse the result. +This module checks each planned entry's key in the container, has the handler +write the files and uploads them under their keys. +""" from __future__ import annotations -import gc import tempfile import time from pathlib import Path from typing import TYPE_CHECKING -from policyengine_simulation_executor import simulation_runtime -from policyengine_simulation_executor.simulation_runtime import _country_module from policyengine_simulation_executor.stage12_bundle import load_stage12_bundle from .keys import collect_dataset_identity, collect_state_dataset_identity +from .levels import DatasetLevel from .models import ( DatasetBuildResult, DatasetPlanEntry, StateDatasetBuildResult, StateDatasetPlanEntry, ) -from .precompute_planning import state_dataset_targets -from .state_datasets import state_dataset_relative_folder, year_file_reuse_problem +from .precompute_planning import bundle_country, country_prebuilt from .store import Stage12CacheStore if TYPE_CHECKING: from collections.abc import Sequence - from types import ModuleType - from microdf import MicroDataFrame - from policyengine.core.scoping_strategy import RowFilterStrategy + from .levels import YearFileTarget def build_dataset_impl(bucket: str, expected: DatasetPlanEntry) -> DatasetBuildResult: - """Have .py put one planned dataset year in the data folder, then upload it. + """Have the national handler write one planned year file, then upload it. Raises ``RuntimeError`` when the installed bundle gives another identity - than the plan, or when the cache path already holds other data. + than the plan, when the handler plans no year file in the entry's folder, + or when the cache path already holds other data. """ - resolved = load_stage12_bundle() - identity = collect_dataset_identity(resolved, country="us", year=expected.year) + identity = collect_dataset_identity( + load_stage12_bundle(), + country=bundle_country(expected.country), + year=expected.year, + ) if identity.store_path != expected.path: msg = "planned and runtime Stage 12 dataset identities differ" raise RuntimeError(msg) + handler = country_prebuilt(expected.country).handlers[DatasetLevel.NATIONAL] + targets = [ + target + for target in handler.year_file_targets(expected.year) + if target.folder == expected.folder + ] + if len(targets) != 1: + msg = ( + f"The national handler plans no {expected.year} year file in " + f"{expected.folder}" + ) + raise RuntimeError(msg) started = time.monotonic() - _country_module("us").ensure_datasets( - datasets=[identity.dataset], - years=[expected.year], - data_folder=simulation_runtime.resolve_data_folder(), - ) - local_path = Path(simulation_runtime.resolve_data_folder()) / identity.filename - uploaded, stored = Stage12CacheStore(bucket).upload_file(expected.path, local_path) + with tempfile.TemporaryDirectory( + prefix="policyengine-stage12-datasets-" + ) as work_folder: + written = handler.write_year_files(expected.year, targets, Path(work_folder)) + uploaded, stored = Stage12CacheStore(bucket).upload_file( + expected.path, written[targets[0]] + ) return DatasetBuildResult( **stored.model_dump(), year=expected.year, @@ -58,18 +76,22 @@ def build_dataset_impl(bucket: str, expected: DatasetPlanEntry) -> DatasetBuildR ) -def _checked_state_targets( +def _planned_state_targets( year: int, expected: Sequence[StateDatasetPlanEntry] -) -> dict[str, RowFilterStrategy]: - """Return each planned state's row filter, after re-deriving its key here. - - Raises ``RuntimeError`` when the installed bundle gives another identity - than the plan, so nothing is built under a key that does not describe it, - and when a state has no row filter, before anything is prepared. +) -> list[YearFileTarget]: + """Return the state handler's target for each planned entry, in entry order. + + Each entry's key is derived again here, from the installed bundle and the + handler's target. Raises ``ValueError`` for an entry of another year or + country, and ``RuntimeError`` when the handler has no target for an + entry's state or the keys differ, so nothing is built under a key that + does not describe it. """ - resolved = load_stage12_bundle() - targets = {target.region: target for target in state_dataset_targets()} - datasets = set() + countries = {entry.country for entry in expected} + if len(countries) != 1: + msg = f"One state file build covers one country, not {sorted(countries)}" + raise ValueError(msg) + (country,) = countries for entry in expected: if entry.year != year: msg = ( @@ -77,24 +99,29 @@ def _checked_state_targets( f"{entry.year}, not {year}" ) raise ValueError(msg) - target = targets.get(entry.region) - if target is None: + handler = country_prebuilt(country).handlers[DatasetLevel.STATE] + by_region = { + target.subset.region: target + for target in handler.year_file_targets(year) + if target.subset is not None + } + resolved = load_stage12_bundle() + targets = [] + for entry in expected: + target = by_region.get(entry.region) + if target is None or target.subset is None: msg = f"No state dataset target for {entry.region} in this container" raise RuntimeError(msg) - if target.scoping_strategy is None: - msg = f"{entry.region} has no row filter to build its state file with" - raise RuntimeError(msg) identity = collect_state_dataset_identity( resolved, - country="us", + country=bundle_country(country), year=year, dataset=target.dataset, - state_code=target.state_code, - state_fips=target.state_fips, - filter_variable=target.filter_variable, + state_code=target.subset.code, + state_fips=target.subset.value, + filter_variable=target.subset.variable, ) - folder = state_dataset_relative_folder(target.dataset, target.state_code) - if (identity.store_path, identity.filename, folder) != ( + if (identity.store_path, identity.filename, target.folder) != ( entry.path, entry.filename, entry.folder, @@ -104,52 +131,8 @@ def _checked_state_targets( f"for {entry.region} {year}" ) raise RuntimeError(msg) - datasets.add(target.dataset) - if len(datasets) > 1: - msg = f"One state dataset build covers one dataset, not {sorted(datasets)}" - raise ValueError(msg) - strategies = {} - for entry in expected: - strategy = targets[entry.region].scoping_strategy - if strategy is not None: - strategies[entry.region] = strategy - return strategies - - -def _registered_district_geoids(country_module: ModuleType) -> set[int]: - """Return the district codes the US congressional-district regions filter on.""" - return { - int(region.scoping_strategy.variable_value) - for region in country_module.model.region_registry.get_by_type( - "congressional_district" - ) - } - - -def _require_districts_within_their_states( - household: MicroDataFrame, district_geoids: set[int] -) -> None: - """Refuse a dataset in which a household sits in another state's district. - - District requests read their state's file and filter it by - ``congressional_district_geoid`` (state FIPS times 100 plus the district - number). A code that names no district, such as an unassigned 0, matches - no district request and changes no result. Both columns are labels; - nothing here is weighted. - """ - if "congressional_district_geoid" not in household.columns: - return - district = household["congressional_district_geoid"] - in_another_state = district.isin(sorted(district_geoids)) & ( - (district // 100) != household["state_fips"] - ) - if in_another_state.any(): - msg = ( - "Some households have a congressional district code that names " - "another state's district; their state's file would not match " - "that district's results" - ) - raise RuntimeError(msg) + targets.append(target) + return targets def build_state_datasets_impl( @@ -161,74 +144,23 @@ def build_state_datasets_impl( ) -> tuple[StateDatasetBuildResult, ...]: """Build, check and upload one year's Stage 12 state datasets. - Has .py prepare the regional dataset's full-country year file once, then - for each planned state keeps the rows its region's own scoping strategy - keeps, writes them with .py's ``save()``, copies the year-file stamp, - confirms that .py's reuse checks accept the file, and uploads it. + The state handler prepares the state-level dataset's full year file once, + writes each planned state's rows as its own year file and confirms .py + would reuse it; each file is then uploaded under its planned key. """ - from policyengine.tax_benefit_models.us.datasets import ( - PolicyEngineUSDataset, - USYearData, - ) - from policyengine.tax_benefit_models.us.legacy_inputs import ( - read_year_file_stamp, - write_year_file_stamp, - ) - from policyengine.tax_benefit_models.us.model import US_GROUP_ENTITIES - if not expected: return () started = time.monotonic() - strategies = _checked_state_targets(year, expected) - dataset = expected[0].dataset + targets = _planned_state_targets(year, expected) work_folder = work_folder or Path( tempfile.mkdtemp(prefix="policyengine-stage12-state-datasets-") ) - source_folder = str(work_folder / "source") - country_module = _country_module("us") - - # Preparing the year file runs a Microsimulation over every state, whose - # objects hold reference cycles; release them before filtering 51 copies. - country_module.ensure_datasets( - datasets=[dataset], years=[year], data_folder=source_folder - ) - gc.collect() - (source,) = country_module.load_datasets( - datasets=[dataset], years=[year], data_folder=source_folder - ).values() - stamp = read_year_file_stamp(source.filepath) - if stamp is None: - msg = f"The prepared year file {source.filepath} has no year-file stamp" - raise RuntimeError(msg) - _require_districts_within_their_states( - source.data.household, _registered_district_geoids(country_module) - ) - + handler = country_prebuilt(expected[0].country).handlers[DatasetLevel.STATE] + written = handler.write_year_files(year, targets, work_folder) store = Stage12CacheStore(bucket) results = [] - for entry in expected: - rows = strategies[entry.region].apply( - entity_data=source.data.entity_data, - group_entities=US_GROUP_ENTITIES, - year=year, - ) - local_file = work_folder / entry.folder / entry.filename - PolicyEngineUSDataset( - name=f"{dataset}-{entry.state_code.lower()}-year-{year}", - description=f"{entry.region} rows of {dataset} for {year}", - filepath=str(local_file), - year=year, - metadata=dict(source.metadata), - data=USYearData(**rows), - ).save() - # save() rewrites the file without the stamp, so stamp it afterwards, - # as create_datasets does. - write_year_file_stamp(local_file, stamp) - problem = year_file_reuse_problem(local_file, dataset) - if problem is not None: - msg = f"ensure_datasets would not reuse {local_file}: {problem}" - raise RuntimeError(msg) - uploaded, stored = store.upload_file(entry.path, local_file) + for entry, target in zip(expected, targets, strict=True): + uploaded, stored = store.upload_file(entry.path, written[target]) results.append( StateDatasetBuildResult( **stored.model_dump(), diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/precompute_planning.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/precompute_planning.py index 9d209fadc..9035f0f38 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/precompute_planning.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/precompute_planning.py @@ -1,11 +1,17 @@ -"""Plan the Stage 12 cache: baseline identities, state dataset targets and work.""" +"""Plan the Stage 12 cache through the level handlers: targets, identities and work. + +The level handlers (``levels``) say which year files and baselines a country +builds for each year and where the image keeps them; ``cache_levels`` says +which of those levels this cache covers. This module turns each target into +the cache's own ``stage12-*`` identity and records whether the bucket holds it. +""" from __future__ import annotations -from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, cast from uuid import NAMESPACE_URL, uuid5 +from policyengine_simulation_contract.stage12_bundle import SUPPORTED_COUNTRIES from policyengine_simulation_contract.stage12_execution import ( BundleProvenance, DatasetArtifactMediaType, @@ -25,6 +31,9 @@ resolve_region, ) from policyengine_simulation_executor.stage12_bundle import load_stage12_bundle +from policyengine_simulation_executor.stage12_runtime.cached_simulation import ( + qualifying_cache_identity, +) from policyengine_simulation_executor.stage12_runtime.output_planning import ( plan_simulation_input, resolve_simulation_output_plan, @@ -34,13 +43,21 @@ simulation_runtime_params, ) +from .cache_levels import cache_baseline_levels, cache_year_file_levels from .keys import ( Stage12BaselineCacheIdentity, canonical_digest, - collect_baseline_identity, collect_dataset_identity, collect_state_dataset_identity, ) +from .levels import ( + CountryPrebuilt, + DatasetLevel, + RunScope, + YearFileTarget, + prebuilt_for, + year_file_name, +) from .models import ( BaselinePlanEntry, CacheBundleIdentity, @@ -49,51 +66,91 @@ StateDatasetPlanEntry, WorkSelection, ) -from .state_datasets import state_dataset_relative_folder from .store import Stage12CacheStore if TYPE_CHECKING: from collections.abc import Sequence - from policyengine.core.scoping_strategy import RowFilterStrategy - -PRECOMPUTE_YEARS = (2026, 2027, 2025) + from policyengine_simulation_contract.stage12_bundle import ( + CountryId, + ResolvedStage12Bundle, + ) DETERMINISM_SCHEMA = "stage12-dv1" -def _bundle_identity() -> CacheBundleIdentity: +def required_baseline_levels(country: str) -> tuple[DatasetLevel, ...]: + """Return the cache's baseline levels for ``country``; ``RuntimeError`` if none. + + The precompute's determinism check, the manifest's publication and the + deployed worker's check each probe a precomputed baseline, so a cache + without one is refused before anything is built. + """ + baseline_levels = cache_baseline_levels(country) + if not baseline_levels: + msg = ( + f"The {country} v2 cache needs at least one baseline level: its " + "precompute, manifest and deploy check each probe a baseline" + ) + raise RuntimeError(msg) + return baseline_levels + + +def bundle_country(country: str) -> CountryId: + """Return ``country`` as a Stage 12 bundle country; ``ValueError`` otherwise.""" + if country not in SUPPORTED_COUNTRIES: + msg = f"{country!r} is not a Stage 12 bundle country" + raise ValueError(msg) + return cast("CountryId", country) + + +def country_prebuilt(country: str) -> CountryPrebuilt: + """Return ``country``'s handler settings; ``RuntimeError`` for a country without.""" + prebuilt = prebuilt_for(country) + if prebuilt is None: + msg = f"No prebuilt-file handlers exist for {country}" + raise RuntimeError(msg) + return prebuilt + + +def _bundle_identity(country: CountryId) -> CacheBundleIdentity: resolved = load_stage12_bundle() - country = next(item for item in resolved.bundle.countries if item.country == "us") + country_bundle = next( + item for item in resolved.bundle.countries if item.country == country + ) return CacheBundleIdentity( bundle_manifest_sha256=resolved.bundle_manifest_sha256, policyengine_version=resolved.bundle.policyengine_version, core_package_version=resolved.bundle.core_package_version, - country_package_version=country.country_package_version, - data_package_version=country.data_package_version, - data_artifact_revision=country.data_artifact_revision, - default_dataset=country.default_dataset, + country_package_version=country_bundle.country_package_version, + data_package_version=country_bundle.data_package_version, + data_artifact_revision=country_bundle.data_artifact_revision, + default_dataset=country_bundle.default_dataset, ) def _planned_pair( - year: int, + year: int, country: CountryId = "us" ) -> tuple[PlannedSimulationExecutionInput, PlannedSimulationExecutionInput]: resolved = load_stage12_bundle() - country = next(item for item in resolved.bundle.countries if item.country == "us") + country_bundle = next( + item for item in resolved.bundle.countries if item.country == country + ) dataset = next( - item for item in country.datasets if item.identity == country.default_dataset + item + for item in country_bundle.datasets + if item.identity == country_bundle.default_dataset ) provenance = BundleProvenance( policyengine_version=resolved.bundle.policyengine_version, - country_package_name=country.country_package_name, - country_package_version=country.country_package_version, + country_package_name=country_bundle.country_package_name, + country_package_version=country_bundle.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, + data_package_name=country_bundle.data_package_name, + data_package_version=country_bundle.data_package_version, ), bundle_manifest_sha256=resolved.bundle_manifest_sha256, ) @@ -114,7 +171,7 @@ def simulation(role: SimulationRole) -> SimulationExecutionInput: policy={}, population=population, year=year, - geography=GeographySelection(country="us", region="us"), + geography=GeographySelection(country=country, region=country), bundle=provenance, ) @@ -131,50 +188,51 @@ def simulation(role: SimulationRole) -> SimulationExecutionInput: def scoped_planned_simulation( - year: int, group: tuple[str, ...], *, reform: bool = False + year: int, + group: tuple[str, ...], + *, + reform: bool = False, + country: CountryId = "us", ) -> PlannedSimulationExecutionInput: """Return the year's planned baseline, or reform, scoped to one region group.""" - baseline, reform_input = _planned_pair(year) + baseline, reform_input = _planned_pair(year, country) selected = reform_input if reform else baseline return selected.model_copy(update={"options": {"region_group": list(group)}}) -def _scope_key(year: int, group: tuple[str, ...]) -> str: - - params = { - "country": "us", - "scope": "macro", - "time_period": str(year), - "region_group": list(group), - } - resolution = resolve_region( - country_module=_country_module("us"), - country="us", - params=params, - ) - value = getattr(resolution.scoping_strategy, "cache_key", None) - if not isinstance(value, str) or not value: - msg = "Stage 12 region group produced no cache identity" - raise RuntimeError(msg) - return value - - def baseline_identity( - year: int, group: tuple[str, ...] + year: int, group: tuple[str, ...], *, country: CountryId = "us" ) -> tuple[PlannedSimulationExecutionInput, Stage12BaselineCacheIdentity]: - """Return a planned baseline and the identity its worker reads it under.""" + """Return a planned baseline and the identity its worker reads it under. + + The identity comes from ``qualifying_cache_identity``, the rule the worker + applies to the same request, so the precompute writes each baseline + under the name the worker looks it up by. Raises ``RuntimeError`` when + that rule gives the planned baseline no identity. + """ from policyengine_simulation_executor.spm import normalize_runtime_spm - simulation = scoped_planned_simulation(year, group) - identity = collect_baseline_identity( + simulation = scoped_planned_simulation(year, group, country=country) + params = simulation_runtime_params(simulation) + country_module = _country_module(country) + region = resolve_region( + country_module=country_module, country=country, params=params + ) + selection = _resolve_dataset_selection(params, region_resolution=region) + identity = qualifying_cache_identity( simulation, resolved=load_stage12_bundle(), - region_codes=group, - scope_key=_scope_key(year, group), + run=RunScope(country=country, year=year, region=region, dataset=selection), # The selection the worker builds the simulation with, which names # the file .py saves and loads. - spm=normalize_runtime_spm(simulation_runtime_params(simulation)), + spm=normalize_runtime_spm(params), ) + if identity is None: + msg = ( + f"The planned {country} {year} baseline for {list(group)} gets no " + "cache identity: the precompute's and the worker's rules differ" + ) + raise RuntimeError(msg) return simulation, identity @@ -186,111 +244,122 @@ def determinism_record(baselines: Sequence[BaselinePlanEntry]) -> dict[str, Any] } -def determinism_record_path(baselines: Sequence[BaselinePlanEntry]) -> str: +def determinism_record_path( + baselines: Sequence[BaselinePlanEntry], country: str | None = None +) -> str: """Return the bucket path of the determinism record for these baselines. The path is named by the record's digest, so any change to the planned - baselines needs a new passing check. + baselines needs a new passing check. ``country`` defaults to the one the + baselines share; ``ValueError`` when there is none to take. """ - return f"determinism/us/{canonical_digest(determinism_record(baselines))}.json" - - -@dataclass(frozen=True) -class StateDatasetTarget: - """A US state whose requests load a non-default dataset, and its row filter. - - Stage 12 bakes this state's rows of ``dataset`` as their own year file: - the households whose ``filter_variable`` equals ``state_fips``. - ``scoping_strategy`` is the region's own .py strategy, the one a request - for the state applies. - """ - - region: str - state_code: str - state_fips: int - filter_variable: str - dataset: str - scoping_strategy: RowFilterStrategy | None = field( - default=None, compare=False, repr=False + countries = {entry.country for entry in baselines} + if country is None: + if len(countries) != 1: + msg = "A determinism record covers one country's baselines" + raise ValueError(msg) + (country,) = countries + return ( + f"determinism/{country}/{canonical_digest(determinism_record(baselines))}.json" ) -def state_dataset_targets() -> tuple[StateDatasetTarget, ...]: - """Return every US state region that loads a non-default dataset, by state code. - - Each state is resolved as a Stage 12 worker resolves a request for it - (``resolve_region`` then ``_resolve_dataset_selection``), so a bundle - that sends states back to the default dataset gets no state files. - """ - country_module = _country_module("us") - targets = [] - for region in country_module.model.region_registry.get_by_type("state"): - params = { - "country": "us", - "region": region.code, - "time_period": PRECOMPUTE_YEARS[0], - } - resolution = resolve_region( - country_module=country_module, country="us", params=params +def _key_free_target_problem( + resolved: ResolvedStage12Bundle, target: YearFileTarget +) -> str | None: + """Return why the cache has no key for ``target``, or None when it has one.""" + if target.level is DatasetLevel.NATIONAL and target.subset is None: + country_bundle = next( + item for item in resolved.bundle.countries if item.country == target.country ) - selection = _resolve_dataset_selection(params, region_resolution=resolution) - if selection.is_default: - continue - strategy = resolution.scoping_strategy - variable_name = getattr(strategy, "variable_name", None) - variable_value = getattr(strategy, "variable_value", None) - if not variable_name or variable_value is None or not resolution.state_code: - msg = ( - f"State region {resolution.code} loads {selection.name} but has no " - "row filter and state code to build its state file from" - ) - raise RuntimeError(msg) - targets.append( - StateDatasetTarget( - region=resolution.code, - state_code=resolution.state_code, - state_fips=int(variable_value), - filter_variable=variable_name, - dataset=selection.name, - scoping_strategy=strategy, - ) + if target.dataset != country_bundle.default_dataset: + return f"a whole year file of {target.dataset}, not the default dataset" + return None + if target.level is DatasetLevel.STATE and target.subset is not None: + return None + return f"a {target.level} year file of {target.dataset}" + + +def _year_file_entry( + resolved: ResolvedStage12Bundle, + target: YearFileTarget, + store: Stage12CacheStore, +) -> DatasetPlanEntry | StateDatasetPlanEntry: + """Turn one handler year-file target into the cache's plan entry for it.""" + problem = _key_free_target_problem(resolved, target) + if problem is not None: + msg = f"The {target.country} cache has no v2 cache key for {problem}" + raise RuntimeError(msg) + country = bundle_country(target.country) + if target.subset is None: + identity = collect_dataset_identity(resolved, country=country, year=target.year) + else: + identity = collect_state_dataset_identity( + resolved, + country=country, + year=target.year, + dataset=target.dataset, + state_code=target.subset.code, + state_fips=target.subset.value, + filter_variable=target.subset.variable, ) - return tuple(sorted(targets, key=lambda target: target.state_code)) - + if identity.filename != year_file_name(target): + msg = ( + f"The cache would store {identity.filename} where the handlers look " + f"for {year_file_name(target)}" + ) + raise RuntimeError(msg) + exists = store.exists(identity.store_path) + if target.subset is None: + return DatasetPlanEntry( + country=target.country, + year=target.year, + digest=identity.digest, + path=identity.store_path, + filename=identity.filename, + folder=target.folder, + exists=exists, + ) + return StateDatasetPlanEntry( + country=target.country, + year=target.year, + state_code=target.subset.code, + region=target.subset.region, + dataset=target.dataset, + digest=identity.digest, + path=identity.store_path, + filename=identity.filename, + folder=target.folder, + exists=exists, + ) -def plan_artifacts_impl(bucket: str) -> PrecomputePlan: - """Plan every dataset and baseline file and record which the bucket holds. - The plan covers each precompute year and US region group, and records - whether a passing determinism check exists for these baselines. - """ - resolved = load_stage12_bundle() - store = Stage12CacheStore(bucket) - targets = state_dataset_targets() - datasets = [] - baselines = [] - state_datasets = [] - for year in PRECOMPUTE_YEARS: - dataset = collect_dataset_identity(resolved, country="us", year=year) - datasets.append( - DatasetPlanEntry( - year=year, - digest=dataset.digest, - path=dataset.store_path, - filename=dataset.filename, - exists=store.exists(dataset.store_path), +def _baseline_entries( + prebuilt: CountryPrebuilt, year: int, store: Stage12CacheStore +) -> list[BaselinePlanEntry]: + """Plan each baseline the cache precomputes for ``year``, in handler order.""" + entries = [] + country = bundle_country(prebuilt.country) + for level in required_baseline_levels(prebuilt.country): + if level is not DatasetLevel.STATE_GROUP: + msg = ( + f"The {prebuilt.country} cache has no v2 cache key for {level} " + "baselines" ) - ) - for index, group in enumerate(US_REGION_GROUPS): - simulation, identity = baseline_identity(year, group) - baselines.append( + raise RuntimeError(msg) + for index, target in enumerate(prebuilt.handlers[level].baseline_targets(year)): + group = tuple(target.request["region_group"]) + simulation, identity = baseline_identity(year, group, country=country) + entries.append( BaselinePlanEntry( + country=prebuilt.country, year=year, segment_index=index, region_codes=group, digest=identity.digest, path=identity.store_path, filename=identity.filename, + folder=target.year_file.folder, simulation_id=identity.simulation_id, output_plan_sha256=stage12_output_plan_sha256( simulation.output_plan @@ -298,44 +367,72 @@ def plan_artifacts_impl(bucket: str) -> PrecomputePlan: exists=store.exists(identity.store_path), ) ) - for target in targets: - state_identity = collect_state_dataset_identity( - resolved, - country="us", - year=year, - dataset=target.dataset, - state_code=target.state_code, - state_fips=target.state_fips, - filter_variable=target.filter_variable, - ) - state_datasets.append( - StateDatasetPlanEntry( - year=year, - state_code=target.state_code, - region=target.region, - dataset=target.dataset, - digest=state_identity.digest, - path=state_identity.store_path, - filename=state_identity.filename, - folder=state_dataset_relative_folder( - target.dataset, target.state_code - ), - exists=store.exists(state_identity.store_path), - ) - ) + return entries + + +def plan_artifacts_impl(bucket: str, country: str = "us") -> PrecomputePlan: + """Plan every year file and baseline the cache holds, and which the bucket has. + + The years come from the country's handler settings, the files from the + handlers of the levels the cache covers (``cache_levels``). The plan also + records whether a passing determinism check exists for these baselines. + The v2 cache covers only the US until task 2.2 · 6, hence the default. + """ + prebuilt = country_prebuilt(country) + required_baseline_levels(country) + resolved = load_stage12_bundle() + store = Stage12CacheStore(bucket) + datasets: list[DatasetPlanEntry] = [] + baselines: list[BaselinePlanEntry] = [] + state_datasets: list[StateDatasetPlanEntry] = [] + for year in prebuilt.years: + for level in cache_year_file_levels(country): + for target in prebuilt.handlers[level].year_file_targets(year): + entry = _year_file_entry(resolved, target, store) + if isinstance(entry, DatasetPlanEntry): + datasets.append(entry) + else: + state_datasets.append(entry) + baselines.extend(_baseline_entries(prebuilt, year, store)) return PrecomputePlan( - years=PRECOMPUTE_YEARS, + years=prebuilt.years, datasets=tuple(datasets), baselines=tuple(baselines), state_datasets=tuple(state_datasets), - bundle=_bundle_identity(), + bundle=_bundle_identity(bundle_country(country)), partition_sha256=canonical_digest( {"groups": [list(group) for group in US_REGION_GROUPS]} ), - determinism_verified=store.exists(determinism_record_path(baselines)), + determinism_verified=store.exists(determinism_record_path(baselines, country)), ) +def expected_cache_contents(country: str) -> dict[str, Any]: + """Return the years, year-file count and baseline count the cache holds. + + The image download step and the deployed worker's check require exactly + these. They come from the handler settings and the cache's levels, and + never load the country model: the deploying machine computes them. + Year files here are whole-dataset ones (the manifest's ``dataset`` + entries); state files are counted per state by the worker check. + """ + prebuilt = country_prebuilt(country) + years = list(prebuilt.years) + year_file_count = 0 + if DatasetLevel.NATIONAL in cache_year_file_levels(country): + national = prebuilt.handlers[DatasetLevel.NATIONAL] + year_file_count = sum(len(national.year_file_targets(year)) for year in years) + baseline_count = sum( + len(prebuilt.handlers[level].baseline_targets(year)) + for year in years + for level in required_baseline_levels(country) + ) + return { + "years": years, + "artifact_counts": {"dataset": year_file_count, "baseline": baseline_count}, + } + + def select_work(plan: PrecomputePlan) -> WorkSelection: """Select only missing files: a stored cache file is never replaced.""" return WorkSelection( diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/state_datasets.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/state_datasets.py index 7633041f2..800245d5d 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/state_datasets.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/state_datasets.py @@ -1,35 +1,17 @@ -"""Where the Stage 12 US worker image keeps baked per-state datasets. +"""The year-file reuse checks .py runs, which the level handlers apply. -Stage 12's own copy of the main path's per-state dataset layout (see -``policyengine_simulation_executor.state_datasets``): Stage 12 does not -import the main path's precompute modules. A state's year files sit at -``/state-datasets///`` under the -basename the dataset's own year file has, so ``ensure_datasets`` called on -that folder finds the state's file where it would look for the full one. +The level handlers (``levels_us``) write each state's year file and decide +whether an image's prebuilt year file is usable; both ask +``year_file_reuse_problem`` whether .py's ``ensure_datasets`` would reuse a +file or rebuild it. """ from __future__ import annotations -import logging -from pathlib import Path from typing import TYPE_CHECKING if TYPE_CHECKING: - from policyengine_simulation_executor.simulation_runtime import DatasetSelection - -logger = logging.getLogger(__name__) - -STATE_DATASETS_DIRECTORY = "state-datasets" - - -def state_dataset_relative_folder(dataset: str, state_code: str) -> str: - """Return a state's folder relative to the Stage 12 data folder.""" - return f"{STATE_DATASETS_DIRECTORY}/{dataset}/{state_code.upper()}" - - -def state_dataset_folder(data_folder: str, dataset: str, state_code: str) -> str: - """Return the absolute folder of a state's baked year files.""" - return str(Path(data_folder) / state_dataset_relative_folder(dataset, state_code)) + from pathlib import Path def year_file_reuse_problem(path: str | Path, dataset: str) -> str | None: @@ -54,49 +36,3 @@ def year_file_reuse_problem(path: str | Path, dataset: str) -> str | None: if problem is not None: return problem return year_file_problem(path, _expected_legacy_spm_profile(dataset)) - - -def baked_state_data_folder( - *, - country: str, - selection: DatasetSelection, - state_code: str | None, - year: int, - data_folder: str, -) -> str | None: - """Return the baked folder a US state or district calculation should load. - - A calculation qualifies when it loads a non-default dataset for a US - state (a district passes its state's code) and the image holds that - state's year file for ``year``, which must also pass .py's reuse checks: - otherwise ``ensure_datasets`` would rebuild the full regional dataset - inside the baked folder. Returns None in every other case, and the - calculation prepares the dataset as before. - """ - if country.lower() != "us" or not state_code or selection.is_default: - return None - from policyengine.provenance.manifest import ( - dataset_logical_name, - resolve_dataset_reference, - ) - - folder = state_dataset_folder(data_folder, selection.name, state_code) - stem = dataset_logical_name(resolve_dataset_reference("us", selection.name)) - year_file = Path(folder) / f"{stem}_year_{year}.h5" - if not year_file.is_file(): - return None - try: - problem = year_file_reuse_problem(year_file, selection.name) - except ImportError: - # The reuse checks read private .py helpers. If an upgrade moves one, - # the calculation prepares its dataset instead of failing. - logger.warning( - "Not reading the baked state file %s: .py's year-file reuse " - "checks could not be imported", - year_file, - ) - return None - if problem is not None: - logger.warning("Not reading the baked state file %s: %s", year_file, problem) - return None - return folder diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/cached_simulation.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/cached_simulation.py index 6e779eb52..2a4129857 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/cached_simulation.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/cached_simulation.py @@ -6,7 +6,6 @@ from typing import TYPE_CHECKING, Any from policyengine.core import Simulation -from policyengine.core.scoping_strategy import RegionGroupStrategy from policyengine.core.simulation import _cache from policyengine_simulation_contract.stage12_execution import ( PlannedSimulationExecutionInput, @@ -15,19 +14,24 @@ ) from pydantic import PrivateAttr +from policyengine_simulation_executor.stage12_cache.cache_levels import ( + cache_baseline_levels, +) from policyengine_simulation_executor.stage12_cache.keys import ( Stage12BaselineCacheIdentity, collect_baseline_identity, ) +from policyengine_simulation_executor.stage12_cache.levels import prebuilt_for from .output_planning import validate_output_frames if TYPE_CHECKING: from collections.abc import Mapping - from policyengine.core.scoping_strategy import ScopingStrategy from policyengine_simulation_contract.stage12_bundle import ResolvedStage12Bundle + from policyengine_simulation_executor.stage12_cache.levels import RunScope + logger = logging.getLogger(__name__) CACHE_HIT = "hit" @@ -39,18 +43,25 @@ def qualifying_cache_identity( simulation: PlannedSimulationExecutionInput, *, resolved: ResolvedStage12Bundle, - dataset_is_default: bool, - scoping_strategy: ScopingStrategy | None, + run: RunScope, spm: Mapping[str, Any] | None, ) -> Stage12BaselineCacheIdentity | None: - """Return a safe cache identity, or None for an ineligible simulation.""" - if not _is_current_law_default_baseline( - simulation, dataset_is_default=dataset_is_default - ): + """Return a safe cache identity, or None for an ineligible simulation. + + A simulation qualifies when it is a current-law baseline whose region + group lists only states, its level (from the level handlers) is one the + cache precomputes baselines for (``cache_levels``), and the level's handler + gives it a baseline scope. The scope's cache key enters the identity. A + scope lookup that fails gives no identity, so the run computes its + baseline instead of failing. + """ + if not _is_current_law_baseline(simulation): return None region_codes = _state_region_group(simulation) - scope_key = _region_group_cache_key(scoping_strategy) - if region_codes is None or scope_key is None: + if region_codes is None: + return None + scope_key = _cached_level_scope_key(run) + if scope_key is None: return None return collect_baseline_identity( simulation, @@ -61,15 +72,9 @@ def qualifying_cache_identity( ) -def _is_current_law_default_baseline( - simulation: PlannedSimulationExecutionInput, *, dataset_is_default: bool -) -> bool: - """Whether a simulation is a baseline with no reform on the default dataset.""" - return ( - simulation.role is SimulationRole.BASELINE - and not simulation.policy - and dataset_is_default - ) +def _is_current_law_baseline(simulation: PlannedSimulationExecutionInput) -> bool: + """Whether a simulation is a baseline with no reform.""" + return simulation.role is SimulationRole.BASELINE and not simulation.policy def _state_region_group( @@ -86,11 +91,32 @@ def _state_region_group( return tuple(code for code in raw_group if isinstance(code, str)) -def _region_group_cache_key(scoping_strategy: ScopingStrategy | None) -> str | None: - """Return a region-group scope's cache key, or None when it has none.""" - if not isinstance(scoping_strategy, RegionGroupStrategy): +def _cached_level_scope_key(run: RunScope) -> str | None: + """Return the scope key of a run whose level the cache precomputes, or None. + + The level's handler decides the scope, including that the run reads the + default dataset. None when the run's country has no handlers, its level + is not one the cache covers, the handler gives no scope or no key, or the + lookup fails, loading the handler settings included. + """ + try: + prebuilt = prebuilt_for(run.country) + level = None if prebuilt is None else prebuilt.level_of(run) + if prebuilt is None or level is None: + return None + if level not in cache_baseline_levels(run.country): + return None + scope = prebuilt.handlers[level].baseline_scope(run) + except Exception: # noqa: BLE001 # a lookup failure costs a computed baseline, never the request; it is logged + logger.warning( + "Could not look up the baseline scope of %s region %s; computing " + "its baseline under a random ID", + run.country, + run.region.code, + exc_info=True, + ) return None - scope_key = getattr(scoping_strategy, "cache_key", None) + scope_key = None if scope is None else scope.scope_key if not isinstance(scope_key, str) or not scope_key: return None return scope_key diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/simulation.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/simulation.py index 188f3bb76..d519b8608 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/simulation.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/simulation.py @@ -36,6 +36,7 @@ canonical_json_bytes, ) from policyengine_simulation_executor.stage12_bundle import load_stage12_bundle +from policyengine_simulation_executor.stage12_cache import levels from policyengine_simulation_executor.uk_local_authority_metadata import ( detect_uk_area_dataset_metadata, detect_uk_run_dataset_metadata, @@ -133,8 +134,12 @@ def build_stage12_simulation( identity = qualifying_cache_identity( execution, resolved=load_stage12_bundle(), - dataset_is_default=resolved.dataset_selection.is_default, - scoping_strategy=resolved.region.scoping_strategy, + run=levels.RunScope( + country=execution.geography.country, + year=execution.year, + region=resolved.region, + dataset=resolved.dataset_selection, + ), spm=selection, ) spm_kwargs: dict[str, Any] = {"spm": selection} if selection is not None else {} @@ -279,9 +284,6 @@ def calculate_simulation_frames( resolve_region, setup_gcp_credentials, ) - from policyengine_simulation_executor.stage12_cache import ( # noqa: PLC0415 # resolved per call so tests can patch the baked-folder lookup - state_datasets, - ) with ( stage_span(Stage.CREDENTIAL_SETUP), @@ -302,19 +304,23 @@ def calculate_simulation_frames( ) _require_loaded_dataset_matches_provenance(simulation, dataset_selection) with stage_span(Stage.DATASET_LOAD): + # Read through the module, so tests can replace the lookup. + prebuilt = levels.prebuilt_dataset_folder( + levels.RunScope( + country=country, + year=simulation.year, + region=region, + dataset=dataset_selection, + ), + resolve_data_folder(), + ) dataset = load_with_download_retry( partial( _load_dataset, params, selection=dataset_selection, country_module=country_module, - data_folder=state_datasets.baked_state_data_folder( - country=country, - selection=dataset_selection, - state_code=region.state_code, - year=simulation.year, - data_folder=resolve_data_folder(), - ), + data_folder=None if prebuilt is None else prebuilt.folder, ), dataset_name=dataset_selection.name, ) diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_worker_validation.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_worker_validation.py index d8d1b5590..8a040b28d 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_worker_validation.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_worker_validation.py @@ -18,12 +18,14 @@ resolve_data_folder, ) from policyengine_simulation_executor.stage12_bundle import load_stage12_bundle -from policyengine_simulation_executor.stage12_cache import ( - precompute as cache_precompute, +from policyengine_simulation_executor.stage12_cache.cache_levels import ( + cache_year_file_levels, ) +from policyengine_simulation_executor.stage12_cache.levels import DatasetLevel from policyengine_simulation_executor.stage12_cache.models import CacheManifest -from policyengine_simulation_executor.stage12_cache.precompute import PRECOMPUTE_YEARS from policyengine_simulation_executor.stage12_cache.precompute_planning import ( + country_prebuilt, + expected_cache_contents, scoped_planned_simulation, ) from policyengine_simulation_executor.stage12_runtime.dependencies import ( @@ -149,26 +151,30 @@ def _check_uk_local_authority_dataset(dataset_path: str) -> None: detect_uk_local_authority_metadata_from_hdf(dataset_path) -# The installed cache holds one dataset per precomputed year and one baseline -# per US region group per year; the deploy check probes the first year. -STAGE12_CACHE_ARTIFACT_COUNT = len(PRECOMPUTE_YEARS) * (1 + len(US_REGION_GROUPS)) -STAGE12_CACHE_PROBE_YEAR = PRECOMPUTE_YEARS[0] +# Only the US worker image holds the v2 cache. +CACHE_COUNTRY = "us" def expected_state_dataset_count() -> int: """Return how many state dataset files the installed bundle's cache holds. - One per precomputed year for each US state region on a non-default - dataset; none when every state uses the default dataset. + One per precomputed year for each US state the state handler builds a + file for (each state region on a non-default dataset); none when every + state uses the default dataset or the cache bakes no state files. """ - return len(PRECOMPUTE_YEARS) * len(cache_precompute.state_dataset_targets()) + if DatasetLevel.STATE not in cache_year_file_levels(CACHE_COUNTRY): + return 0 + prebuilt = country_prebuilt(CACHE_COUNTRY) + handler = prebuilt.handlers[DatasetLevel.STATE] + return sum(len(handler.year_file_targets(year)) for year in prebuilt.years) def _require_installed_artifacts( manifest: CacheManifest, data_folder: Path, *, state_dataset_count: int ) -> None: """Require the expected number of listed files and every state file on disk.""" - if len(manifest.artifacts) != STAGE12_CACHE_ARTIFACT_COUNT + state_dataset_count: + counts = expected_cache_contents(CACHE_COUNTRY)["artifact_counts"] + if len(manifest.artifacts) != sum(counts.values()) + state_dataset_count: msg = "installed Stage 12 cache artifact count differs" raise RuntimeError(msg) for item in manifest.artifacts: @@ -189,7 +195,8 @@ def _check_installed_cache(expected_manifest_sha256: str) -> dict[str, Any]: msg = "installed Stage 12 cache manifest digest differs" raise RuntimeError(msg) manifest = CacheManifest.model_validate_json(payload) - if manifest.years != PRECOMPUTE_YEARS: + years = tuple(expected_cache_contents(CACHE_COUNTRY)["years"]) + if manifest.years != years: msg = "installed Stage 12 cache years differ" raise RuntimeError(msg) _require_installed_artifacts( @@ -197,15 +204,17 @@ def _check_installed_cache(expected_manifest_sha256: str) -> dict[str, Any]: data_folder, state_dataset_count=expected_state_dataset_count(), ) + # The deploy check probes the first year's first group baseline. + probe_year = years[0] probe = next( item for item in manifest.artifacts - if item.type == "baseline" and item.year == STAGE12_CACHE_PROBE_YEAR + if item.type == "baseline" and item.year == probe_year ) - probe_path = data_folder / probe.filename + probe_path = data_folder / probe.folder / probe.filename _check_dataset_access(str(probe_path), probe.content_sha256) calculation = calculate_simulation_frames( - scoped_planned_simulation(STAGE12_CACHE_PROBE_YEAR, US_REGION_GROUPS[0]) + scoped_planned_simulation(probe_year, US_REGION_GROUPS[0]) ) if calculation.cache_outcome != "hit": msg = "deployed Stage 12 cache probe did not load a cache hit" diff --git a/projects/policyengine-simulation-executor/tests/stage12_runtime_support.py b/projects/policyengine-simulation-executor/tests/stage12_runtime_support.py index 7a7425ed4..a63bf8b09 100644 --- a/projects/policyengine-simulation-executor/tests/stage12_runtime_support.py +++ b/projects/policyengine-simulation-executor/tests/stage12_runtime_support.py @@ -294,7 +294,7 @@ def run_until_dataset_loaded( ): """Run a Stage 12 calculation up to its dataset load; return what it did.""" from policyengine_simulation_executor import simulation_runtime - from policyengine_simulation_executor.stage12_cache import state_datasets + from policyengine_simulation_executor.stage12_cache import levels from policyengine_simulation_executor.stage12_runtime import simulation as worker loads = [] @@ -304,9 +304,20 @@ def load_dataset(_params, *, selection, country_module, data_folder=None): loads.append({"selection": selection, "data_folder": data_folder}) return object() - def lookup(**kwargs): - lookups.append(kwargs) - return baked_folder + def lookup(run, data_folder): + # The run's facts a prebuilt-folder lookup decides by. + lookups.append( + { + "country": run.country, + "selection": run.dataset, + "state_code": run.region.state_code, + "year": run.year, + "data_folder": data_folder, + } + ) + if baked_folder is None: + return None + return levels.PrebuiltFolder(folder=baked_folder, dataset_source=None) def stop_after_loading(*_args, **_kwargs): raise _StoppedAfterLoadingError @@ -323,7 +334,7 @@ def stop_after_loading(*_args, **_kwargs): lambda _params, *, region_resolution: selection, ) monkeypatch.setattr(simulation_runtime, "_load_dataset", load_dataset) - monkeypatch.setattr(state_datasets, "baked_state_data_folder", lookup) + monkeypatch.setattr(levels, "prebuilt_dataset_folder", lookup) monkeypatch.setattr( worker, "detect_uk_run_dataset_metadata", lambda *_a, **_k: None ) diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_cache_image.py b/projects/policyengine-simulation-executor/tests/test_stage12_cache_image.py index 388e54ebd..8fe844c17 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_cache_image.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_cache_image.py @@ -10,6 +10,14 @@ import pytest from src.modal.stage12_cache_image import fetch_stage12_cache +# What the deploying machine passes for the US cache (expected_cache_contents). +EXPECTED_CONTENTS = { + "years": [2026, 2027, 2025], + "artifact_counts": {"dataset": 3, "baseline": 60}, +} +# Where the national year files and the baselines computed on them land. +NATIONAL_FOLDER = "prebuilt/us/populace_us_2024/all" + class _Blob: def __init__(self, payload: bytes): @@ -41,6 +49,7 @@ def _manifest() -> tuple[dict, dict[str, bytes]]: "type": kind, "path": path, "filename": filename, + "folder": NATIONAL_FOLDER, "year": (2026, 2027, 2025)[index % 3], "identity_digest": f"identity-{kind}-{index}", "content_sha256": sha256(payload).hexdigest(), @@ -86,9 +95,11 @@ def test_fetches_and_verifies_all_cache_files(monkeypatch, tmp_path) -> None: monkeypatch.setenv("STAGE12_BUNDLE_MANIFEST_SHA256", "b" * 64) monkeypatch.setenv("STAGE12_CACHE_MANIFEST_DIGEST", _digest(manifest)) - fetch_stage12_cache("cache-bucket", manifest, client=_Client(payloads)) + fetch_stage12_cache( + "cache-bucket", manifest, EXPECTED_CONTENTS, client=_Client(payloads) + ) - assert len(list(tmp_path.glob("*.h5"))) == 63 + assert len(list((tmp_path / NATIONAL_FOLDER).glob("*.h5"))) == 63 assert (tmp_path / ".stage12-cache-manifest.json").exists() @@ -98,13 +109,17 @@ def test_rejects_foreign_or_corrupt_cache(monkeypatch, tmp_path) -> None: monkeypatch.setenv("STAGE12_BUNDLE_MANIFEST_SHA256", "different") monkeypatch.setenv("STAGE12_CACHE_MANIFEST_DIGEST", _digest(manifest)) with pytest.raises(RuntimeError, match="another installed bundle"): - fetch_stage12_cache("cache-bucket", manifest, client=_Client(payloads)) + fetch_stage12_cache( + "cache-bucket", manifest, EXPECTED_CONTENTS, client=_Client(payloads) + ) monkeypatch.setenv("STAGE12_BUNDLE_MANIFEST_SHA256", "b" * 64) corrupt_path = manifest["artifacts"][0]["path"] payloads[corrupt_path] = b"corrupt" with pytest.raises(RuntimeError, match=r"size differs|digest differs"): - fetch_stage12_cache("cache-bucket", manifest, client=_Client(payloads)) + fetch_stage12_cache( + "cache-bucket", manifest, EXPECTED_CONTENTS, client=_Client(payloads) + ) def _use_deployment(monkeypatch, tmp_path, manifest: dict) -> None: @@ -160,7 +175,9 @@ def test_rejects_a_manifest_before_downloading_anything( _use_deployment(monkeypatch, tmp_path, manifest) with pytest.raises(error, match=message): - fetch_stage12_cache("cache-bucket", manifest, client=_Client(payloads)) + fetch_stage12_cache( + "cache-bucket", manifest, EXPECTED_CONTENTS, client=_Client(payloads) + ) assert list(tmp_path.iterdir()) == [] @@ -180,7 +197,10 @@ def test_rejects_a_deployment_without_a_bucket_or_manifest( RuntimeError, match=r"^Stage 12 cache deployment has no bucket or manifest$" ): fetch_stage12_cache( - bucket, manifest if has_manifest else None, client=_Client(payloads) + bucket, + manifest if has_manifest else None, + EXPECTED_CONTENTS, + client=_Client(payloads), ) @@ -194,7 +214,9 @@ def test_rejects_a_manifest_whose_digest_differs_from_the_deployment( with pytest.raises( RuntimeError, match=r"^Stage 12 cache manifest digest differs from deployment$" ): - fetch_stage12_cache("cache-bucket", manifest, client=_Client(payloads)) + fetch_stage12_cache( + "cache-bucket", manifest, EXPECTED_CONTENTS, client=_Client(payloads) + ) assert list(tmp_path.iterdir()) == [] @@ -205,7 +227,9 @@ def test_rejects_an_artifact_entry_that_is_not_an_object(monkeypatch, tmp_path) _use_deployment(monkeypatch, tmp_path, manifest) with pytest.raises(TypeError, match=r"^Stage 12 cache artifact entry is invalid$"): - fetch_stage12_cache("cache-bucket", manifest, client=_Client(payloads)) + fetch_stage12_cache( + "cache-bucket", manifest, EXPECTED_CONTENTS, client=_Client(payloads) + ) assert not (tmp_path / ".stage12-cache-manifest.json").exists() @@ -241,7 +265,9 @@ def test_rejects_invalid_artifact_metadata(monkeypatch, tmp_path, change) -> Non with pytest.raises( RuntimeError, match=r"^Stage 12 cache artifact metadata is invalid$" ): - fetch_stage12_cache("cache-bucket", manifest, client=_Client(payloads)) + fetch_stage12_cache( + "cache-bucket", manifest, EXPECTED_CONTENTS, client=_Client(payloads) + ) def test_rejects_a_same_size_file_with_another_digest_and_leaves_no_partial( @@ -253,9 +279,12 @@ def test_rejects_a_same_size_file_with_another_digest_and_leaves_no_partial( _use_deployment(monkeypatch, tmp_path, manifest) with pytest.raises(RuntimeError, match=r"^Stage 12 cache artifact digest differs$"): - fetch_stage12_cache("cache-bucket", manifest, client=_Client(payloads)) + fetch_stage12_cache( + "cache-bucket", manifest, EXPECTED_CONTENTS, client=_Client(payloads) + ) - assert list(tmp_path.iterdir()) == [] + # Only the empty folder the file would have landed in remains. + assert [path for path in tmp_path.rglob("*") if path.is_file()] == [] @pytest.mark.parametrize( @@ -297,7 +326,7 @@ def build_client(**arguments): ) monkeypatch.setattr(storage, "Client", build_client) - fetch_stage12_cache("cache-bucket", manifest) + fetch_stage12_cache("cache-bucket", manifest, EXPECTED_CONTENTS) if credentials_encoding == "unset": assert credential_infos == [] @@ -307,7 +336,7 @@ def build_client(**arguments): assert client_arguments == [ {"credentials": "service-account-credentials", "project": "cache-project"} ] - assert len(list(tmp_path.glob("*.h5"))) == 63 + assert len(list((tmp_path / NATIONAL_FOLDER).glob("*.h5"))) == 63 REGIONAL_DATASET = "populace_us_2024_acs_local" @@ -320,7 +349,7 @@ def _state_artifact(year: int, state_code: str, **changes) -> tuple[dict, bytes] "type": "state_dataset", "path": f"state-datasets/us/{year}-{state_code}/{filename}", "filename": filename, - "folder": f"state-datasets/{REGIONAL_DATASET}/{state_code}", + "folder": f"prebuilt/us/{REGIONAL_DATASET}/{state_code}", "state_code": state_code, "year": year, "identity_digest": f"identity-state-{year}-{state_code}", @@ -345,14 +374,16 @@ def test_places_each_state_file_in_its_state_folder(monkeypatch, tmp_path) -> No manifest, payloads = _manifest_with_state_datasets() _use_deployment(monkeypatch, tmp_path, manifest) - fetch_stage12_cache("cache-bucket", manifest, client=_Client(payloads)) + fetch_stage12_cache( + "cache-bucket", manifest, EXPECTED_CONTENTS, client=_Client(payloads) + ) - state_folder = tmp_path / "state-datasets" / REGIONAL_DATASET + state_folder = tmp_path / "prebuilt" / "us" / REGIONAL_DATASET for year in (2026, 2027, 2025): for state_code in ("UT", "WY"): stored = state_folder / state_code / f"{REGIONAL_DATASET}_year_{year}.h5" assert stored.read_bytes() == f"state-{year}-{state_code}".encode() - assert len(list(tmp_path.glob("*.h5"))) == 63 + assert len(list((tmp_path / NATIONAL_FOLDER).glob("*.h5"))) == 63 def _drop_one_state_file(manifest: dict) -> None: @@ -391,7 +422,9 @@ def test_rejects_inconsistent_state_datasets_before_downloading( _use_deployment(monkeypatch, tmp_path, manifest) with pytest.raises(RuntimeError, match=message): - fetch_stage12_cache("cache-bucket", manifest, client=_Client(payloads)) + fetch_stage12_cache( + "cache-bucket", manifest, EXPECTED_CONTENTS, client=_Client(payloads) + ) assert list(tmp_path.iterdir()) == [] @@ -399,11 +432,14 @@ def test_rejects_inconsistent_state_datasets_before_downloading( @pytest.mark.parametrize( "folder", [ - "/absolute/UT", - "state-datasets/../../escape", - "state-datasets/./UT", - "state-datasets//UT", - "state-datasets\\UT", + f"/prebuilt/us/{REGIONAL_DATASET}/UT", + "prebuilt/us/../../escape", + f"prebuilt/us/./{REGIONAL_DATASET}/UT", + f"prebuilt/us//{REGIONAL_DATASET}/UT", + f"prebuilt\\us\\{REGIONAL_DATASET}\\UT", + f"state-datasets/{REGIONAL_DATASET}/UT", + "prebuilt/us", + f"prebuilt/uk/{REGIONAL_DATASET}/UT", "", None, ], @@ -418,7 +454,9 @@ def test_rejects_an_unsafe_state_folder_before_downloading( with pytest.raises( RuntimeError, match=r"^Stage 12 cache artifact metadata is invalid$" ): - fetch_stage12_cache("cache-bucket", manifest, client=_Client(payloads)) + fetch_stage12_cache( + "cache-bucket", manifest, EXPECTED_CONTENTS, client=_Client(payloads) + ) assert list(tmp_path.iterdir()) == [] @@ -435,6 +473,8 @@ def test_rejects_two_entries_for_one_state_file_before_downloading( with pytest.raises( RuntimeError, match=r"^Stage 12 cache artifact metadata is invalid$" ): - fetch_stage12_cache("cache-bucket", manifest, client=_Client(payloads)) + fetch_stage12_cache( + "cache-bucket", manifest, EXPECTED_CONTENTS, client=_Client(payloads) + ) assert list(tmp_path.iterdir()) == [] diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_cache_precompute.py b/projects/policyengine-simulation-executor/tests/test_stage12_cache_precompute.py index 95fce42ae..e55b1d37a 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_cache_precompute.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_cache_precompute.py @@ -33,6 +33,10 @@ ) from pydantic import ValidationError +# The US handler settings' years, in submission order. +PLANNED_YEARS = (2026, 2027, 2025) +NATIONAL_FOLDER = "prebuilt/us/populace_us_2024/all" + def _bundle() -> CacheBundleIdentity: return CacheBundleIdentity( @@ -49,31 +53,35 @@ def _bundle() -> CacheBundleIdentity: def _plan(*, exists: bool = False, verified: bool | None = None) -> PrecomputePlan: datasets = tuple( DatasetPlanEntry( + country="us", year=year, digest=f"dataset-{year}", path=f"datasets/us/dataset-{year}/populace_year_{year}.h5", filename=f"populace_year_{year}.h5", + folder=NATIONAL_FOLDER, exists=exists, ) - for year in precompute.PRECOMPUTE_YEARS + for year in PLANNED_YEARS ) baselines = tuple( BaselinePlanEntry( + country="us", year=year, segment_index=index, region_codes=group, digest=f"baseline-{year}-{index}", path=f"baselines/us/baseline-{year}-{index}/stage12-bl1-{index}.h5", filename=f"stage12-bl1-{index}.h5", + folder=NATIONAL_FOLDER, simulation_id=f"stage12-bl1-{index}", output_plan_sha256="b" * 64, exists=exists, ) - for year in precompute.PRECOMPUTE_YEARS + for year in PLANNED_YEARS for index, group in enumerate(US_REGION_GROUPS) ) return PrecomputePlan( - years=precompute.PRECOMPUTE_YEARS, + years=PLANNED_YEARS, datasets=datasets, baselines=baselines, bundle=_bundle(), @@ -89,6 +97,7 @@ def _plan(*, exists: bool = False, verified: bool | None = None) -> PrecomputePl def _state_entry(year: int, state_code: str, *, exists: bool) -> StateDatasetPlanEntry: digest = f"state-{year}-{state_code}" return StateDatasetPlanEntry( + country="us", year=year, state_code=state_code, region=f"state/{state_code.lower()}", @@ -96,7 +105,7 @@ def _state_entry(year: int, state_code: str, *, exists: bool) -> StateDatasetPla digest=digest, path=f"state-datasets/us/{digest}/{REGIONAL_DATASET}_year_{year}.h5", filename=f"{REGIONAL_DATASET}_year_{year}.h5", - folder=f"state-datasets/{REGIONAL_DATASET}/{state_code}", + folder=f"prebuilt/us/{REGIONAL_DATASET}/{state_code}", exists=exists, ) @@ -106,7 +115,7 @@ def _plan_with_state_datasets(*, exists: bool = False) -> PrecomputePlan: update={ "state_datasets": tuple( _state_entry(year, state_code, exists=exists) - for year in precompute.PRECOMPUTE_YEARS + for year in PLANNED_YEARS for state_code in ("UT", "WY") ) } @@ -235,167 +244,6 @@ def test_plan_with_state_datasets_round_trips_the_modal_boundary() -> None: assert PrecomputePlan.model_validate(plan.model_dump()) == plan -@pytest.fixture -def stubbed_planning(monkeypatch): - """Stub everything plan_artifacts_impl reads except the state targets.""" - client = _FakeClient() - _use_store(monkeypatch, client) - monkeypatch.setattr(precompute_planning, "load_stage12_bundle", lambda: "resolved") - monkeypatch.setattr(precompute_planning, "_bundle_identity", _bundle) - monkeypatch.setattr( - precompute_planning, - "collect_dataset_identity", - lambda _resolved, *, country, year: SimpleNamespace( - digest=f"dataset-{year}", - store_path=f"datasets/{country}/dataset-{year}/populace_year_{year}.h5", - filename=f"populace_year_{year}.h5", - ), - ) - monkeypatch.setattr(precompute_planning, "US_REGION_GROUPS", (("state/ca",),)) - monkeypatch.setattr( - precompute_planning, - "baseline_identity", - lambda year, _group: ( - SimpleNamespace(output_plan=None), - SimpleNamespace( - digest=f"baseline-{year}", - store_path=f"baselines/us/baseline-{year}/stage12-bl1-{year}.h5", - filename=f"stage12-bl1-{year}.h5", - simulation_id=f"stage12-bl1-{year}", - ), - ), - ) - monkeypatch.setattr( - precompute_planning, "stage12_output_plan_sha256", lambda _: "b" * 64 - ) - - def fake_state_identity(resolved, *, country, year, dataset, **state_filter): - assert resolved == "resolved" - digest = ( - f"state-{year}-{state_filter['state_code']}-" - f"{state_filter['state_fips']}-{state_filter['filter_variable']}" - ) - return SimpleNamespace( - digest=digest, - store_path=f"state-datasets/{country}/{digest}/{dataset}_year_{year}.h5", - filename=f"{dataset}_year_{year}.h5", - ) - - monkeypatch.setattr( - precompute_planning, "collect_state_dataset_identity", fake_state_identity - ) - targets = [ - precompute.StateDatasetTarget( - region="state/ut", - state_code="UT", - state_fips=49, - filter_variable="state_fips", - dataset=REGIONAL_DATASET, - ), - precompute.StateDatasetTarget( - region="state/wy", - state_code="WY", - state_fips=56, - filter_variable="state_fips", - dataset=REGIONAL_DATASET, - ), - ] - monkeypatch.setattr( - precompute_planning, "state_dataset_targets", lambda: tuple(targets) - ) - return SimpleNamespace(client=client, targets=targets) - - -def test_plan_lists_every_state_dataset_year_major_with_presence( - stubbed_planning, -) -> None: - stubbed_planning.client.objects[ - f"state-datasets/us/state-2026-UT-49-state_fips/{REGIONAL_DATASET}_year_2026.h5" - ] = {"payload": b"h5", "metadata": {"sha256": "f" * 64, "size_bytes": "2"}} - - plan = precompute.plan_artifacts_impl("cache-bucket") - - assert [(entry.year, entry.state_code) for entry in plan.state_datasets] == [ - (2026, "UT"), - (2026, "WY"), - (2027, "UT"), - (2027, "WY"), - (2025, "UT"), - (2025, "WY"), - ] - assert [entry.exists for entry in plan.state_datasets] == [ - True, - False, - False, - False, - False, - False, - ] - first = plan.state_datasets[0] - assert first.region == "state/ut" - assert first.dataset == REGIONAL_DATASET - assert first.folder == f"state-datasets/{REGIONAL_DATASET}/UT" - assert first.filename == f"{REGIONAL_DATASET}_year_2026.h5" - assert len(plan.datasets) == 3 - - -def test_states_on_the_default_dataset_add_no_state_datasets( - stubbed_planning, monkeypatch -) -> None: - monkeypatch.setattr(precompute_planning, "state_dataset_targets", tuple) - - assert precompute.plan_artifacts_impl("cache-bucket").state_datasets == () - - -def test_state_targets_follow_how_a_request_for_the_state_resolves( - monkeypatch, -) -> None: - from policyengine.core.scoping_strategy import RowFilterStrategy - from policyengine_simulation_executor.release_bundle import ( - get_country_release_bundle, - ) - - bundle = get_country_release_bundle("us") - - def region(state_code, fips, dataset_path): - return SimpleNamespace( - code=f"state/{state_code.lower()}", - dataset_path=dataset_path, - scoping_strategy=RowFilterStrategy( - variable_name="state_fips", variable_value=fips - ), - parent_code="us", - state_code=state_code, - ) - - regions = [ - region("WY", 56, bundle.dataset_uris[REGIONAL_DATASET]), - region("UT", 49, bundle.dataset_uris[REGIONAL_DATASET]), - region("ID", 16, bundle.default_dataset_uri), - ] - by_code = {item.code: item for item in regions} - country_module = SimpleNamespace( - model=SimpleNamespace( - get_region=by_code.get, - region_registry=SimpleNamespace( - get_by_type=lambda kind: list(regions) if kind == "state" else [] - ), - ) - ) - monkeypatch.setattr( - precompute_planning, "_country_module", lambda _country: country_module - ) - - targets = precompute.state_dataset_targets() - - assert [(target.region, target.state_fips) for target in targets] == [ - ("state/ut", 49), - ("state/wy", 56), - ] - assert {target.dataset for target in targets} == {REGIONAL_DATASET} - assert targets[0].scoping_strategy is by_code["state/ut"].scoping_strategy - - class _Call: def __init__(self, result, events, label): self.result = result @@ -556,7 +404,7 @@ def test_precompute_builds_each_year_of_state_datasets_in_one_call() -> None: year, [entry.model_dump() for entry in plan.state_datasets if entry.year == year], ) - for year in precompute.PRECOMPUTE_YEARS + for year in PLANNED_YEARS ] @@ -587,7 +435,7 @@ def test_precompute_reports_each_builds_uploads_bytes_and_time() -> None: echo=lines.append, ) - for year in precompute.PRECOMPUTE_YEARS: + for year in PLANNED_YEARS: assert ( f"State datasets {year} {REGIONAL_DATASET}: 2 built, 1 uploaded " "(100 bytes) in 12.5 s" @@ -599,7 +447,7 @@ def test_precompute_builds_each_year_and_dataset_in_its_own_call() -> None: events = [] plan = _plan_with_state_datasets() other = _state_entry(2026, "ID", exists=False).model_copy( - update={"dataset": "populace_other", "folder": "state-datasets/other/ID"} + update={"dataset": "populace_other", "folder": "prebuilt/us/populace_other/ID"} ) plan = plan.model_copy(update={"state_datasets": (*plan.state_datasets, other)}) handles = _state_run_handles(events, plan) @@ -753,7 +601,7 @@ def test_manifest_lists_state_datasets_after_the_others_in_plan_order() -> None: ) -def test_manifest_without_state_datasets_keeps_its_published_shape() -> None: +def test_manifest_records_the_folder_of_every_year_file_and_baseline() -> None: from policyengine_simulation_executor.stage12_cache.models import CacheManifest store = SimpleNamespace( @@ -763,8 +611,7 @@ def test_manifest_without_state_datasets_keeps_its_published_shape() -> None: ) payload = precompute.build_manifest(_plan(exists=True), store).canonical_payload() - assert all(set(item) != {"folder"} for item in payload["artifacts"]) - assert all("folder" not in item for item in payload["artifacts"]) + assert {item["folder"] for item in payload["artifacts"]} == {NATIONAL_FOLDER} assert CacheManifest.model_validate(payload).canonical_payload() == payload @@ -866,13 +713,16 @@ def test_determinism_check_records_only_a_pass_that_loaded_the_stored_file( _use_store(monkeypatch, client) plan = _plan(exists=True, verified=False) probe = plan.baselines[0] - (tmp_path / probe.filename).write_bytes(b"h5") + (tmp_path / probe.folder).mkdir(parents=True, exist_ok=True) + (tmp_path / probe.folder / probe.filename).write_bytes(b"h5") monkeypatch.setattr(simulation_runtime, "resolve_data_folder", lambda: tmp_path) - monkeypatch.setattr(precompute_baselines, "_ensure_dataset_file", lambda *_: None) + monkeypatch.setattr(precompute_baselines, "_ensure_year_file", lambda *_: None) monkeypatch.setattr( precompute_baselines, "scoped_planned_simulation", - lambda _year, _group, *, reform=False: "reform" if reform else "baseline", + lambda _year, _group, *, reform=False, country: ( + "reform" if reform else "baseline" + ), ) calculations = { "baseline": SimulationCalculation( @@ -898,11 +748,13 @@ def test_determinism_check_records_only_a_pass_that_loaded_the_stored_file( def _use_determinism_calculations(monkeypatch, tmp_path, cached, fresh) -> None: monkeypatch.setattr(simulation_runtime, "resolve_data_folder", lambda: tmp_path) - monkeypatch.setattr(precompute_baselines, "_ensure_dataset_file", lambda *_: None) + monkeypatch.setattr(precompute_baselines, "_ensure_year_file", lambda *_: None) monkeypatch.setattr( precompute_baselines, "scoped_planned_simulation", - lambda _year, _group, *, reform=False: "reform" if reform else "baseline", + lambda _year, _group, *, reform=False, country: ( + "reform" if reform else "baseline" + ), ) calculations = { "baseline": SimulationCalculation(frames=cached, cache_outcome="hit"), @@ -922,7 +774,8 @@ def test_determinism_check_reports_each_kind_of_frame_difference( _use_store(monkeypatch, client) plan = _plan(exists=True, verified=False) probe = plan.baselines[0] - (tmp_path / probe.filename).write_bytes(b"h5") + (tmp_path / probe.folder).mkdir(parents=True, exist_ok=True) + (tmp_path / probe.folder / probe.filename).write_bytes(b"h5") cached = { "person": pd.DataFrame({"person_id": [1], "age": [30], "income": [1.0]}), "tax_unit": pd.DataFrame({"tax_unit_id": [1]}), @@ -976,14 +829,17 @@ def write_json(self, *_): plan = _plan(exists=True, verified=False) probe = plan.baselines[0] if already_local: - (tmp_path / probe.filename).write_bytes(b"h5") + (tmp_path / probe.folder).mkdir(parents=True, exist_ok=True) + (tmp_path / probe.folder / probe.filename).write_bytes(b"h5") _use_determinism_calculations(monkeypatch, tmp_path, _frames(30), _frames(30)) verdict = precompute.verify_determinism_impl("cache-bucket", plan, probe) assert verdict.equal is True expected_downloads = ( - [] if already_local else [(probe.path, tmp_path / probe.filename)] + [] + if already_local + else [(probe.path, tmp_path / probe.folder / probe.filename)] ) assert downloads == expected_downloads @@ -997,14 +853,14 @@ def test_installed_bundle_plans_a_regional_file_per_state_and_year( plan = precompute.plan_artifacts_impl("cache-bucket") - assert len(plan.state_datasets) == 51 * len(precompute.PRECOMPUTE_YEARS) + assert len(plan.state_datasets) == 51 * len(PLANNED_YEARS) assert {entry.dataset for entry in plan.state_datasets} == {REGIONAL_DATASET} utah = next( entry for entry in plan.state_datasets if entry.year == 2026 and entry.state_code == "UT" ) - assert utah.folder == f"state-datasets/{REGIONAL_DATASET}/UT" + assert utah.folder == f"prebuilt/us/{REGIONAL_DATASET}/UT" assert utah.filename == f"{REGIONAL_DATASET}_year_2026.h5" @@ -1070,6 +926,13 @@ def state_build(self, monkeypatch, tmp_path): from fixtures import state_dataset_sources as sources from policyengine.core.scoping_strategy import RowFilterStrategy from policyengine.tax_benefit_models import us as us_module + from policyengine_simulation_executor.stage12_cache import levels_us + from policyengine_simulation_executor.stage12_cache.levels import ( + DatasetLevel, + SubsetFilter, + YearFileTarget, + prebuilt_folder, + ) client = _FakeClient() _use_store(monkeypatch, client) @@ -1081,24 +944,31 @@ def state_build(self, monkeypatch, tmp_path): sources=sources, ) - def target(state_code, fips): - return precompute.StateDatasetTarget( - region=f"state/{state_code.lower()}", - state_code=state_code, - state_fips=fips, - filter_variable="state_fips", + def target(year, state_code, fips): + return YearFileTarget( + country="us", + level=DatasetLevel.STATE, dataset=sources.REGIONAL_DATASET, - scoping_strategy=RowFilterStrategy( - variable_name="state_fips", variable_value=fips + year=year, + subset=SubsetFilter( + region=f"state/{state_code.lower()}", + code=state_code, + variable="state_fips", + value=fips, + scoping_strategy=RowFilterStrategy( + variable_name="state_fips", variable_value=fips + ), ), + folder=prebuilt_folder("us", sources.REGIONAL_DATASET, state_code), ) - state.targets = [ - target("UT", sources.UTAH_FIPS), - target("WY", sources.WYOMING_FIPS), - ] + state.targets = [("UT", sources.UTAH_FIPS), ("WY", sources.WYOMING_FIPS)] monkeypatch.setattr( - precompute_datasets, "state_dataset_targets", lambda: tuple(state.targets) + levels_us.UsStateHandler, + "year_file_targets", + lambda _handler, year: [ + target(year, state_code, fips) for state_code, fips in state.targets + ], ) monkeypatch.setattr( precompute_datasets, "load_stage12_bundle", lambda: "resolved" @@ -1138,7 +1008,7 @@ def fake_ensure_datasets(*, datasets, years, data_folder): for geoid in (4901, 4902, 4903, 4904, 5600) ] monkeypatch.setattr( - precompute_datasets, + simulation_runtime, "_country_module", lambda _country: SimpleNamespace( ensure_datasets=fake_ensure_datasets, @@ -1165,6 +1035,7 @@ def _entry(self, state_build, state_code): state_code=state_code, ) return StateDatasetPlanEntry( + country="us", year=self.YEAR, state_code=state_code, region=f"state/{state_code.lower()}", @@ -1172,7 +1043,7 @@ def _entry(self, state_build, state_code): digest=identity.digest, path=identity.store_path, filename=identity.filename, - folder=f"state-datasets/{dataset}/{state_code}", + folder=f"prebuilt/us/{dataset}/{state_code}", exists=False, ) @@ -1255,16 +1126,6 @@ def test_a_household_without_a_district_code_does_not_stop_the_build( assert [result.state_code for result in results] == ["UT", "WY"] - def test_refuses_a_target_without_a_row_filter(self, state_build): - from dataclasses import replace - - state_build.targets[0] = replace(state_build.targets[0], scoping_strategy=None) - - with pytest.raises(RuntimeError, match="no row filter"): - self._build(state_build, [self._entry(state_build, "UT")]) - assert state_build.client.objects == {} - assert state_build.ensure_calls == [] - def test_reports_how_long_the_years_build_had_run(self, state_build): results = self._build( state_build, diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_cache_runtime.py b/projects/policyengine-simulation-executor/tests/test_stage12_cache_runtime.py index ece37bc94..432f8663e 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_cache_runtime.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_cache_runtime.py @@ -72,6 +72,28 @@ def _resolved() -> ResolvedStage12Bundle: ) +def _run(strategy, *, is_default: bool = True): + """Return the resolved run a region-group request gives, with ``strategy``.""" + from policyengine_simulation_executor.simulation_runtime import ( + DatasetSelection, + RegionResolution, + ) + from policyengine_simulation_executor.stage12_cache.levels import RunScope + + return RunScope( + country="us", + year=2026, + region=RegionResolution( + code="region_group/state/ca", scoping_strategy=strategy + ), + dataset=DatasetSelection( + name="populace_us_2024", + uri="hf://policyengine/data/populace_us_2024.h5@revision", + is_default=is_default, + ), + ) + + def _strategy(): from policyengine.core.scoping_strategy import ( RegionGroupStrategy, @@ -93,8 +115,7 @@ def test_cache_writer_and_reader_share_full_identity() -> None: reader = qualifying_cache_identity( simulation, resolved=resolved, - dataset_is_default=True, - scoping_strategy=strategy, + run=_run(strategy), spm=SPM_SELECTION, ) writer = collect_baseline_identity( @@ -182,8 +203,7 @@ def test_only_current_law_default_dataset_baseline_qualifies() -> None: ) kwargs = { "resolved": _resolved(), - "dataset_is_default": True, - "scoping_strategy": _strategy(), + "run": _run(_strategy()), "spm": SPM_SELECTION, } assert qualifying_cache_identity(baseline, **kwargs) is not None @@ -201,7 +221,9 @@ def test_only_current_law_default_dataset_baseline_qualifies() -> None: is None ) assert ( - qualifying_cache_identity(baseline, **{**kwargs, "dataset_is_default": False}) + qualifying_cache_identity( + baseline, **{**kwargs, "run": _run(_strategy(), is_default=False)} + ) is None ) @@ -264,8 +286,7 @@ def test_only_a_state_region_group_with_a_scope_cache_key_qualifies( qualifying_cache_identity( baseline, resolved=_resolved(), - dataset_is_default=True, - scoping_strategy=_scoping_strategy(strategy_name), + run=_run(_scoping_strategy(strategy_name)), spm=SPM_SELECTION, ) is None diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_dataset_download_retry.py b/projects/policyengine-simulation-executor/tests/test_stage12_dataset_download_retry.py index be40daa9a..f22921829 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_dataset_download_retry.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_dataset_download_retry.py @@ -140,7 +140,7 @@ def test_stage12_worker_retries_a_dataset_download_that_timed_out( DatasetSelection, RegionResolution, ) - from policyengine_simulation_executor.stage12_cache import state_datasets + from policyengine_simulation_executor.stage12_cache import levels from policyengine_simulation_executor.stage12_runtime import simulation as worker waits: list[float] = [] @@ -179,7 +179,9 @@ def stop_after_loading(*_args, **_kwargs): lambda _params, *, region_resolution: selection, ) monkeypatch.setattr(simulation_runtime, "_load_dataset", flaky_load_dataset) - monkeypatch.setattr(state_datasets, "baked_state_data_folder", lambda **_: None) + monkeypatch.setattr( + levels, "prebuilt_dataset_folder", lambda _run, _data_folder: None + ) monkeypatch.setattr( worker, "detect_uk_run_dataset_metadata", lambda *_a, **_k: None ) diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_local_area_dataset_load.py b/projects/policyengine-simulation-executor/tests/test_stage12_local_area_dataset_load.py index a60c6349f..273b9ef71 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_local_area_dataset_load.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_local_area_dataset_load.py @@ -252,7 +252,7 @@ def _run_until_built( ) -> _Calculation: """Run a UK calculation of Wales up to its simulation build.""" from policyengine_simulation_executor import simulation_runtime - from policyengine_simulation_executor.stage12_cache import state_datasets + from policyengine_simulation_executor.stage12_cache import levels calculation = _Calculation() dataset = SimpleNamespace( @@ -292,7 +292,7 @@ def stop_before_simulating(_params, *, resolved, **_kwargs): simulation_runtime, "_load_dataset", lambda *_args, **_kwargs: dataset ) monkeypatch.setattr( - state_datasets, "baked_state_data_folder", lambda **_kwargs: None + levels, "prebuilt_dataset_folder", lambda _run, _data_folder: None ) monkeypatch.setattr( worker, "detect_uk_run_dataset_metadata", detect_on_the_national_dataset diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_precompute_app.py b/projects/policyengine-simulation-executor/tests/test_stage12_precompute_app.py index 44a95cd53..b5e0c21b4 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_precompute_app.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_precompute_app.py @@ -107,6 +107,7 @@ def test_state_dataset_wrapper_validates_entries_in_and_dumps_results_out( module = _load(monkeypatch) entry = StateDatasetPlanEntry( + country="us", year=2026, state_code="UT", region="state/ut", @@ -114,7 +115,7 @@ def test_state_dataset_wrapper_validates_entries_in_and_dumps_results_out( digest="s1", path="state-datasets/us/s1/populace_us_2024_acs_local_year_2026.h5", filename="populace_us_2024_acs_local_year_2026.h5", - folder="state-datasets/populace_us_2024_acs_local/UT", + folder="prebuilt/us/populace_us_2024_acs_local/UT", exists=False, ) result = StateDatasetBuildResult( diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_precomputed_baseline_plan.py b/projects/policyengine-simulation-executor/tests/test_stage12_precomputed_baseline_plan.py index 9c9844082..5d6914ea2 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_precomputed_baseline_plan.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_precomputed_baseline_plan.py @@ -25,8 +25,9 @@ def test_a_precomputed_simulation_is_planned_as_its_simulation_run_stores_it( reform: bool, # noqa: FBT001 # the parametrized side ) -> None: + first_year = precompute_planning.country_prebuilt("us").years[0] planned = precompute_planning.scoped_planned_simulation( - precompute_planning.PRECOMPUTE_YEARS[0], US_REGION_GROUPS[0], reform=reform + first_year, US_REGION_GROUPS[0], reform=reform ) unplanned = SimulationExecutionInput.model_validate( planned.model_dump(mode="json", exclude={"output_plan"}) diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_state_datasets.py b/projects/policyengine-simulation-executor/tests/test_stage12_state_datasets.py index 5b6eef5a2..46d025dca 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_state_datasets.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_state_datasets.py @@ -1,13 +1,13 @@ -"""Stage 12's per-state datasets: their cache identity and image folders. +"""Stage 12's per-state datasets: their cache identity. -Stage 12 keeps its own copy of the main path's per-state dataset machinery, -keyed from the published Stage 12 bundle. +The cache keys each state's year file from the published Stage 12 bundle. +Where the file sits in the image, and when a run reads it, is the level +handlers' (``stage12_cache.levels_us``), tested with them. """ from __future__ import annotations import dataclasses -from pathlib import Path import pytest from policyengine_simulation_contract.stage12_bundle import ( @@ -16,7 +16,6 @@ Stage12CountryBundle, Stage12Dataset, ) -from policyengine_simulation_executor.stage12_cache import state_datasets from policyengine_simulation_executor.stage12_cache.keys import ( Stage12StateDatasetCacheIdentity, collect_dataset_identity, @@ -148,91 +147,3 @@ def test_the_national_dataset_identity_is_unchanged(): assert identity.dataset == "populace_us_2024" assert identity.source_sha256 == "a" * 64 assert identity.payload["schema"] == "stage12-ds1" - - -def test_state_folder_sits_under_the_stage12_data_folder(): - assert state_datasets.state_dataset_relative_folder(REGIONAL_DATASET, "ut") == ( - f"state-datasets/{REGIONAL_DATASET}/UT" - ) - assert state_datasets.state_dataset_folder( - "/opt/policyengine/stage12-data", REGIONAL_DATASET, "UT" - ) == (f"/opt/policyengine/stage12-data/state-datasets/{REGIONAL_DATASET}/UT") - - -def _regional_selection(): - from policyengine_simulation_executor.release_bundle import ( - get_country_release_bundle, - ) - from policyengine_simulation_executor.simulation_runtime import DatasetSelection - - bundle = get_country_release_bundle("us") - return DatasetSelection( - name=REGIONAL_DATASET, - uri=bundle.dataset_uris[REGIONAL_DATASET], - is_default=False, - ) - - -def _bake_utah(data_folder: Path, *, stamp: bool = True) -> Path: - from fixtures.state_dataset_sources import write_year_file - - folder = Path( - state_datasets.state_dataset_folder(str(data_folder), REGIONAL_DATASET, "UT") - ) - folder.mkdir(parents=True) - write_year_file(folder, year=2026, stamp=stamp) - return folder - - -def _lookup(data_folder, selection, *, state_code="UT", year=2026, country="us"): - return state_datasets.baked_state_data_folder( - country=country, - selection=selection, - state_code=state_code, - year=year, - data_folder=str(data_folder), - ) - - -def test_a_state_reads_its_baked_folder(tmp_path): - folder = _bake_utah(tmp_path) - - assert _lookup(tmp_path, _regional_selection()) == str(folder) - - -def test_a_year_or_state_without_a_baked_file_reads_nothing_baked(tmp_path): - _bake_utah(tmp_path) - - assert _lookup(tmp_path, _regional_selection(), year=2028) is None - assert _lookup(tmp_path, _regional_selection(), state_code="WY") is None - - -def test_an_unstamped_file_reads_nothing_baked(tmp_path): - _bake_utah(tmp_path, stamp=False) - - assert _lookup(tmp_path, _regional_selection()) is None - - -def test_default_datasets_and_other_regions_read_nothing_baked(tmp_path): - from policyengine_simulation_executor.simulation_runtime import DatasetSelection - - _bake_utah(tmp_path) - default = DatasetSelection( - name="populace_us_2024", uri="hf://default", is_default=True - ) - - assert _lookup(tmp_path, default) is None - assert _lookup(tmp_path, _regional_selection(), state_code=None) is None - assert _lookup(tmp_path, _regional_selection(), country="uk") is None - - -def test_a_renamed_dotpy_reuse_check_falls_back_to_on_demand_loading( - monkeypatch, tmp_path -): - """A .py upgrade moving the private SPM profile helper must not fail runs.""" - from policyengine.tax_benefit_models.us import datasets as us_datasets - - _bake_utah(tmp_path) - monkeypatch.delattr(us_datasets, "_expected_legacy_spm_profile") - - assert _lookup(tmp_path, _regional_selection()) is None diff --git a/projects/policyengine-simulation-executor/tests/test_stage12_worker_validation.py b/projects/policyengine-simulation-executor/tests/test_stage12_worker_validation.py index 8eeb6ff45..dd199dd96 100644 --- a/projects/policyengine-simulation-executor/tests/test_stage12_worker_validation.py +++ b/projects/policyengine-simulation-executor/tests/test_stage12_worker_validation.py @@ -433,28 +433,31 @@ def test_digest_mismatch_is_checked_before_any_dataset_access() -> None: def _installed_manifest(*, state_codes=("UT", "WY")): from policyengine_simulation_executor.stage12_cache.models import CacheManifest - from policyengine_simulation_executor.stage12_cache.precompute import ( - PRECOMPUTE_YEARS, + from policyengine_simulation_executor.stage12_cache.precompute_planning import ( + country_prebuilt, ) from policyengine_simulation_executor.stage12_runtime.partition import ( US_REGION_GROUPS, ) + years = country_prebuilt("us").years + def entry(kind, year, index): return { "type": kind, "path": f"{kind}s/us/{year}-{index}/{kind}-{year}-{index}.h5", "filename": f"{kind}-{year}-{index}.h5", + "folder": "prebuilt/us/populace_us_2024/all", "year": year, "identity_digest": f"{kind}-{year}-{index}", "content_sha256": "f" * 64, "size_bytes": 1, } - artifacts = [entry("dataset", year, 0) for year in PRECOMPUTE_YEARS] + artifacts = [entry("dataset", year, 0) for year in years] artifacts += [ entry("baseline", year, index) - for year in PRECOMPUTE_YEARS + for year in years for index in range(len(US_REGION_GROUPS)) ] artifacts += [ @@ -462,21 +465,21 @@ def entry(kind, year, index): "type": "state_dataset", "path": f"state-datasets/us/{year}-{state}/acs_year_{year}.h5", "filename": f"acs_year_{year}.h5", - "folder": f"state-datasets/acs/{state}", + "folder": f"prebuilt/us/acs/{state}", "state_code": state, "year": year, "identity_digest": f"state-{year}-{state}", "content_sha256": "f" * 64, "size_bytes": 1, } - for year in PRECOMPUTE_YEARS + for year in years for state in state_codes ] return CacheManifest.model_validate( { "schema": "stage12-mf1", "country": "us", - "years": list(PRECOMPUTE_YEARS), + "years": list(years), "partition_sha256": "d" * 64, "bundle": { "bundle_manifest_sha256": "b" * 64, @@ -532,11 +535,20 @@ def test_installed_cache_refuses_a_missing_state_file(tmp_path) -> None: def test_expected_state_file_count_follows_the_installed_bundle(monkeypatch) -> None: from policyengine_simulation_executor import stage12_worker_validation as module - from policyengine_simulation_executor.stage12_cache import precompute + from policyengine_simulation_executor.stage12_cache import levels_us + from policyengine_simulation_executor.stage12_cache.precompute_planning import ( + country_prebuilt, + ) - monkeypatch.setattr(precompute, "state_dataset_targets", lambda: ("UT", "WY")) + monkeypatch.setattr( + levels_us.UsStateHandler, + "year_file_targets", + lambda _handler, _year: ("UT", "WY"), + ) - assert module.expected_state_dataset_count() == 2 * len(precompute.PRECOMPUTE_YEARS) + assert module.expected_state_dataset_count() == 2 * len( + country_prebuilt("us").years + ) def test_the_reported_cache_release_still_matches_its_contract_with_state_files( diff --git a/projects/policyengine-simulation-executor/tests/test_v2_cache_handlers.py b/projects/policyengine-simulation-executor/tests/test_v2_cache_handlers.py new file mode 100644 index 000000000..e8bc581b1 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_v2_cache_handlers.py @@ -0,0 +1,490 @@ +"""The v2 report app's cache plans, places and checks files through the handlers. + +The v2 cache takes its years from the US handler settings, its year files and +baselines from the handlers' targets, and its image folders from the targets' +``prebuilt/…`` folders. Which year-file and baseline levels it covers are its +own settings (``stage12_cache.cache_levels``): it never follows the +run_simulation app's levels, so a run_simulation task cannot add files or +fixed IDs to the v2 cache by itself. + +The inputs are the fixed stand-ins in ``fixtures.v2_cache_us_inputs``. +""" + +from __future__ import annotations + +from hashlib import sha256 +from types import SimpleNamespace +from typing import TYPE_CHECKING + +import pytest +from fixtures.v2_cache_us_inputs import ( + BUNDLE_MANIFEST_SHA256, + DEFAULT_DATASET, + STATE_LEVEL_DATASET, + enable_fixed_spm, + install_v2_cache_us_inputs, +) +from policyengine_simulation_executor.stage12_cache import keys, precompute +from policyengine_simulation_executor.stage12_cache.store import Stage12CacheStore +from src.modal.stage12_cache_image import fetch_stage12_cache + +if TYPE_CHECKING: + from pathlib import Path + +BUCKET = "bucket-handlers" +NATIONAL_FOLDER = f"prebuilt/us/{DEFAULT_DATASET}/all" + + +def _state_folder(state_code: str) -> str: + return f"prebuilt/us/{STATE_LEVEL_DATASET}/{state_code}" + + +def _stored_bytes(path: str) -> bytes: + return f"v2-cache-handlers:{path}".encode() + + +@pytest.fixture +def us_inputs(monkeypatch): + inputs = install_v2_cache_us_inputs(monkeypatch) + enable_fixed_spm(inputs) + return inputs + + +@pytest.fixture(scope="module") +def published(): + """Plan the fixed US inputs, store each planned file and build the manifest.""" + with pytest.MonkeyPatch.context() as module_patch: + inputs = install_v2_cache_us_inputs(module_patch) + enable_fixed_spm(inputs) + plan = precompute.plan_artifacts_impl(BUCKET) + for entry in (*plan.datasets, *plan.baselines, *plan.state_datasets): + inputs.cache_bucket.store(entry.path, _stored_bytes(entry.path)) + manifest = precompute.build_manifest( + plan, Stage12CacheStore(BUCKET) + ).canonical_payload() + yield SimpleNamespace(plan=plan, inputs=inputs, manifest=manifest) + + +class TestPlanThroughTheHandlers: + """``plan_artifacts_impl`` asks the handlers what to build and where it goes.""" + + def test_every_entry_names_its_country_and_prebuilt_folder(self, published): + plan = published.plan + + assert {entry.country for entry in plan.datasets} == {"us"} + assert {entry.country for entry in plan.baselines} == {"us"} + assert {entry.country for entry in plan.state_datasets} == {"us"} + assert [entry.folder for entry in plan.datasets] == [NATIONAL_FOLDER] * 3 + # A baseline sits beside the year file it was computed on, where + # .py's Simulation.ensure() looks for it. + assert [entry.folder for entry in plan.baselines] == [NATIONAL_FOLDER] * 60 + assert [entry.folder for entry in plan.state_datasets] == [ + _state_folder(entry.state_code) for entry in plan.state_datasets + ] + + def test_the_years_follow_the_us_handler_settings(self, us_inputs, monkeypatch): + from policyengine_simulation_executor.stage12_cache import levels_us + + monkeypatch.setattr(levels_us, "US_PREBUILT_YEARS", (2026,)) + + plan = precompute.plan_artifacts_impl(BUCKET) + + assert plan.years == (2026,) + assert [entry.year for entry in plan.datasets] == [2026] + assert len(plan.baselines) == 20 + assert len(plan.state_datasets) == 51 + + def test_the_baselines_follow_the_caches_own_baseline_levels( + self, us_inputs, monkeypatch + ): + from policyengine_simulation_executor.stage12_cache import cache_levels + from policyengine_simulation_executor.stage12_cache.levels import ( + DatasetLevel, + ) + + monkeypatch.setattr( + cache_levels, + "CACHE_BASELINE_LEVELS", + {"us": (DatasetLevel.STATE_GROUP, DatasetLevel.STATE)}, + ) + + # The cache has no key for single-state baselines. + with pytest.raises(RuntimeError, match="no v2 cache key for state baselines"): + precompute.plan_artifacts_impl(BUCKET) + + def test_refuses_a_cache_without_baselines_before_building_anything( + self, us_inputs, monkeypatch + ): + """The precompute, the manifest and the deploy check all need a baseline.""" + from policyengine_simulation_executor.stage12_cache import ( + cache_levels, + precompute_planning, + ) + + monkeypatch.setattr(cache_levels, "CACHE_BASELINE_LEVELS", {"us": ()}) + + with pytest.raises(RuntimeError, match="at least one baseline level"): + precompute.plan_artifacts_impl(BUCKET) + with pytest.raises(RuntimeError, match="at least one baseline level"): + precompute_planning.expected_cache_contents("us") + + def test_the_year_files_follow_the_caches_own_year_file_levels( + self, us_inputs, monkeypatch + ): + from policyengine_simulation_executor.stage12_cache import cache_levels + from policyengine_simulation_executor.stage12_cache.levels import ( + DatasetLevel, + ) + + monkeypatch.setattr( + cache_levels, "CACHE_YEAR_FILE_LEVELS", {"us": (DatasetLevel.NATIONAL,)} + ) + + plan = precompute.plan_artifacts_impl(BUCKET) + + assert plan.state_datasets == () + assert len(plan.datasets) == 3 + + def test_the_cache_does_not_follow_the_run_simulation_apps_levels( + self, us_inputs, monkeypatch + ): + from policyengine_simulation_executor.stage12_cache import levels_us + from policyengine_simulation_executor.stage12_cache.levels import ( + CountryPrebuilt, + DatasetLevel, + ) + + original = levels_us.us_prebuilt + + def with_state_baselines() -> CountryPrebuilt: + settings = original() + return CountryPrebuilt( + country=settings.country, + years=settings.years, + year_file_levels=(DatasetLevel.NATIONAL,), + baseline_levels=(DatasetLevel.STATE_GROUP, DatasetLevel.STATE), + handlers=settings.handlers, + classify=settings.classify, + baseline_output_preparer=settings.baseline_output_preparer, + ) + + monkeypatch.setattr(levels_us, "us_prebuilt", with_state_baselines) + + plan = precompute.plan_artifacts_impl(BUCKET) + + assert len(plan.baselines) == 60 + assert len(plan.state_datasets) == 153 + + def test_refuses_a_year_file_the_v2_cache_has_no_key_for( + self, us_inputs, monkeypatch + ): + from policyengine_simulation_executor.stage12_cache import levels_us + from policyengine_simulation_executor.stage12_cache.levels import ( + DatasetLevel, + YearFileTarget, + ) + + # A whole year file of the state-level dataset: v2's dataset key + # covers only the bundle's default dataset. + def unsupported_targets(_handler, year): + return [ + YearFileTarget( + country="us", + level=DatasetLevel.NATIONAL, + dataset=STATE_LEVEL_DATASET, + year=year, + subset=None, + folder=f"prebuilt/us/{STATE_LEVEL_DATASET}/all", + ) + ] + + monkeypatch.setattr( + levels_us.UsNationalHandler, "year_file_targets", unsupported_targets + ) + + with pytest.raises(RuntimeError, match="no v2 cache key"): + precompute.plan_artifacts_impl(BUCKET) + + +class TestExpectedCacheContents: + """The years and counts the download step and deploy check require.""" + + def test_the_us_contents(self, us_inputs): + from policyengine_simulation_executor.stage12_cache import ( + precompute_planning, + ) + + assert precompute_planning.expected_cache_contents("us") == { + "years": [2026, 2027, 2025], + "artifact_counts": {"dataset": 3, "baseline": 60}, + } + + def test_follow_the_handler_years(self, us_inputs, monkeypatch): + from policyengine_simulation_executor.stage12_cache import ( + levels_us, + precompute_planning, + ) + + monkeypatch.setattr(levels_us, "US_PREBUILT_YEARS", (2026, 2027)) + + assert precompute_planning.expected_cache_contents("us") == { + "years": [2026, 2027], + "artifact_counts": {"dataset": 2, "baseline": 40}, + } + + def test_load_no_country_model(self, us_inputs, monkeypatch): + """The deploying machine computes them without loading the US model.""" + from policyengine_simulation_executor import simulation_runtime + from policyengine_simulation_executor.stage12_cache import ( + precompute_planning, + ) + + def refuse_to_load(_country): + msg = "the US country model was loaded" + raise AssertionError(msg) + + monkeypatch.setattr(simulation_runtime, "_country_module", refuse_to_load) + + contents = precompute_planning.expected_cache_contents("us") + + assert contents["artifact_counts"] == {"dataset": 3, "baseline": 60} + + +def test_every_manifest_entry_records_its_folder(published): + folders = { + (item["type"], item["folder"]) for item in published.manifest["artifacts"] + } + + assert ("dataset", NATIONAL_FOLDER) in folders + assert ("baseline", NATIONAL_FOLDER) in folders + assert ("state_dataset", _state_folder("CA")) in folders + assert all(item["folder"] for item in published.manifest["artifacts"]) + assert published.manifest["schema"] == "stage12-mf1" + + +@pytest.fixture +def image(published, monkeypatch, tmp_path): + """Give a test an image data folder and a download into it, as deployed.""" + data_folder = tmp_path / "data" + monkeypatch.setenv("POLICYENGINE_DATA_FOLDER", str(data_folder)) + monkeypatch.setenv("STAGE12_BUNDLE_MANIFEST_SHA256", BUNDLE_MANIFEST_SHA256) + expected = { + "years": [2026, 2027, 2025], + "artifact_counts": {"dataset": 3, "baseline": 60}, + } + + def fetch(manifest: dict, expected_contents: dict = expected) -> None: + monkeypatch.setenv( + "STAGE12_CACHE_MANIFEST_DIGEST", keys.canonical_digest(manifest) + ) + fetch_stage12_cache( + BUCKET, + manifest, + expected_contents, + client=published.inputs.cache_bucket, + ) + + return SimpleNamespace(data_folder=data_folder, fetch=fetch) + + +def _files_under(folder: Path) -> list[Path]: + return sorted(path for path in folder.rglob("*") if path.is_file()) + + +def _with_artifact_folder(manifest: dict, kind: str, folder: object) -> dict: + artifacts = list(manifest["artifacts"]) + index = next( + position for position, item in enumerate(artifacts) if item["type"] == kind + ) + changed = dict(artifacts[index]) + if folder is None: + changed.pop("folder", None) + else: + changed["folder"] = folder + artifacts[index] = changed + return {**manifest, "artifacts": artifacts} + + +class TestDownloadStep: + """``fetch_stage12_cache`` places each file in the folder its entry names.""" + + def test_places_every_file_in_its_prebuilt_folder(self, published, image): + image.fetch(published.manifest) + + for entry in (*published.plan.datasets, *published.plan.baselines): + destination = image.data_folder / NATIONAL_FOLDER / entry.filename + assert destination.read_bytes() == _stored_bytes(entry.path) + for entry in published.plan.state_datasets: + destination = ( + image.data_folder / _state_folder(entry.state_code) / entry.filename + ) + assert destination.read_bytes() == _stored_bytes(entry.path) + assert not list(image.data_folder.glob("*.h5")) + + @pytest.mark.parametrize( + ("kind", "folder"), + [ + pytest.param("dataset", None, id="year-file-without-a-folder"), + pytest.param("baseline", "", id="baseline-with-an-empty-folder"), + pytest.param("dataset", "datasets/us", id="outside-prebuilt"), + pytest.param( + "baseline", f"prebuilt/uk/{DEFAULT_DATASET}/all", id="another-country" + ), + pytest.param("state_dataset", "prebuilt/us", id="no-dataset-folder"), + pytest.param( + "state_dataset", "prebuilt/us/../../escape", id="leaves-the-folder" + ), + ], + ) + def test_refuses_an_unsafe_or_missing_folder_before_downloading( + self, published, image, kind, folder + ): + with pytest.raises( + RuntimeError, match=r"^Stage 12 cache artifact metadata is invalid$" + ): + image.fetch(_with_artifact_folder(published.manifest, kind, folder)) + + assert not image.data_folder.exists() or _files_under(image.data_folder) == [] + + def test_checks_the_years_and_counts_it_is_given(self, published, image): + one_year = { + "years": [2026], + "artifact_counts": {"dataset": 1, "baseline": 20}, + } + + with pytest.raises( + RuntimeError, match=r"^Stage 12 cache manifest has an unexpected year set$" + ): + image.fetch(published.manifest, one_year) + + one_year_manifest = { + **published.manifest, + "years": [2026], + "artifacts": [ + item for item in published.manifest["artifacts"] if item["year"] == 2026 + ], + } + image.fetch(one_year_manifest, one_year) + + assert len(_files_under(image.data_folder / NATIONAL_FOLDER)) == 21 + + @pytest.mark.parametrize( + "expected_contents", + [ + pytest.param(None, id="none"), + pytest.param({}, id="empty"), + pytest.param({"years": [2026, 2027, 2025]}, id="no-counts"), + pytest.param( + {"years": [], "artifact_counts": {"dataset": 3, "baseline": 60}}, + id="no-years", + ), + pytest.param( + { + "years": [2026, 2027, 2025], + "artifact_counts": {"dataset": "3", "baseline": 60}, + }, + id="count-not-an-integer", + ), + pytest.param( + {"years": [2026, 2027, 2025], "artifact_counts": {"dataset": 3}}, + id="a-kind-missing", + ), + ], + ) + def test_refuses_a_deployment_without_usable_expected_contents( + self, published, image, expected_contents + ): + with pytest.raises( + RuntimeError, match=r"^Stage 12 cache deployment has no expected contents$" + ): + image.fetch(published.manifest, expected_contents) + + assert not image.data_folder.exists() or _files_under(image.data_folder) == [] + + def test_refuses_counts_other_than_the_ones_it_is_given(self, published, image): + fewer_baselines = { + "years": [2026, 2027, 2025], + "artifact_counts": {"dataset": 3, "baseline": 59}, + } + + with pytest.raises( + RuntimeError, + match=r"^Stage 12 cache manifest has an unexpected artifact count$", + ): + image.fetch(published.manifest, fewer_baselines) + + +def test_the_worker_image_build_passes_the_expected_contents(monkeypatch): + from policyengine_simulation_executor.stage12_cache import precompute_planning + from test_stage12_modal_app import _load + + module = _load(monkeypatch) + + (fetch,) = [ + call for call in module.us_worker_image.calls if call[0] == "run_function" + ] + _bucket, _manifest, expected = fetch[2]["args"] + assert expected == precompute_planning.expected_cache_contents("us") + + +class TestDeployTimeCheck: + """``_check_installed_cache`` reads the files where the download step put them.""" + + def test_reads_its_probe_baseline_from_the_national_prebuilt_folder( + self, published, image, monkeypatch + ): + from policyengine_simulation_executor import stage12_worker_validation + + image.fetch(published.manifest) + checked = [] + original_check = stage12_worker_validation._check_dataset_access + + def check_dataset_access(path, expected_sha256): + checked.append(path) + original_check(path, expected_sha256) + + monkeypatch.setattr( + stage12_worker_validation, "_check_dataset_access", check_dataset_access + ) + monkeypatch.setattr( + stage12_worker_validation, + "calculate_simulation_frames", + lambda _simulation: SimpleNamespace(cache_outcome="hit"), + ) + + stage12_worker_validation._check_installed_cache( + keys.canonical_digest(published.manifest) + ) + + assert checked == [ + str( + image.data_folder + / NATIONAL_FOLDER + / published.plan.baselines[0].filename + ) + ] + + def test_refuses_a_state_file_missing_from_its_prebuilt_folder( + self, published, image + ): + from policyengine_simulation_executor import stage12_worker_validation + + image.fetch(published.manifest) + california = published.plan.state_datasets[4] + assert california.state_code == "CA" + (image.data_folder / _state_folder("CA") / california.filename).unlink() + + with pytest.raises(RuntimeError, match="state dataset file is missing"): + stage12_worker_validation._check_installed_cache( + sha256( + (image.data_folder / ".stage12-cache-manifest.json").read_bytes() + ).hexdigest() + ) + + def test_counts_the_state_files_from_the_handlers(self, us_inputs, monkeypatch): + from policyengine_simulation_executor import stage12_worker_validation + from policyengine_simulation_executor.stage12_cache import levels_us + + monkeypatch.setattr(levels_us, "US_PREBUILT_YEARS", (2026,)) + + assert stage12_worker_validation.expected_state_dataset_count() == 51 diff --git a/projects/policyengine-simulation-executor/tests/test_v2_cache_runtime_handlers.py b/projects/policyengine-simulation-executor/tests/test_v2_cache_runtime_handlers.py new file mode 100644 index 000000000..617f10f1e --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_v2_cache_runtime_handlers.py @@ -0,0 +1,480 @@ +"""The v2 report app's worker and precompute builders go through the level handlers. + +At run time the worker takes each run's prebuilt folder from the handlers +(``levels.prebuilt_dataset_folder``) and its baseline's scope key from the +handler's ``baseline_scope``. A fixed cache ID still needs a current-law +baseline whose region group lists only states, and a level the v2 cache +precomputes baselines for (``cache_levels``). The precompute writes year +files through the handlers' ``write_year_files``. + +The inputs are the fixed stand-ins in ``fixtures.v2_cache_us_inputs``. +""" + +from __future__ import annotations + +from pathlib import Path +from types import SimpleNamespace + +import pytest +from fixtures.v2_cache_us_inputs import ( + DEFAULT_DATASET, + STATE_LEVEL_DATASET, + enable_fixed_spm, + install_v2_cache_us_inputs, +) +from policyengine_simulation_executor import simulation_runtime +from policyengine_simulation_executor.stage12_cache import ( + precompute, + precompute_baselines, + precompute_datasets, +) +from policyengine_simulation_executor.stage12_cache.precompute_planning import ( + scoped_planned_simulation, +) +from policyengine_simulation_executor.stage12_runtime import ( + simulation as stage12_simulation, +) +from policyengine_simulation_executor.stage12_runtime.partition import US_REGION_GROUPS +from policyengine_simulation_executor.stage12_runtime.worker_inputs import ( + simulation_runtime_params, +) + +BUCKET = "bucket-runtime-handlers" +NATIONAL_FOLDER = f"prebuilt/us/{DEFAULT_DATASET}/all" +FIRST_GROUP = tuple(US_REGION_GROUPS[0]) + + +@pytest.fixture +def us_inputs(monkeypatch, tmp_path): + inputs = install_v2_cache_us_inputs(monkeypatch) + enable_fixed_spm(inputs) + inputs.data_folder = tmp_path / "data" + inputs.data_folder.mkdir() + monkeypatch.setenv("POLICYENGINE_DATA_FOLDER", str(inputs.data_folder)) + return inputs + + +class _RecordedCachedSimulation: + kind = "cached" + + def __init__(self, **keyword_arguments): + self.arguments = keyword_arguments + + def configure_stage12_cache(self, _output_plan): + return None + + +def _recorded_plain_simulation(**keyword_arguments): + return SimpleNamespace(kind="random", arguments=keyword_arguments) + + +@pytest.fixture +def recorded_build(us_inputs, monkeypatch): + """Build a planned simulation as the worker does, recording what is built.""" + monkeypatch.setattr( + stage12_simulation, "Stage12CachedSimulation", _RecordedCachedSimulation + ) + monkeypatch.setattr(stage12_simulation, "Simulation", _recorded_plain_simulation) + + def build(simulation): + params = simulation_runtime_params(simulation) + country = simulation.geography.country + country_module = simulation_runtime._country_module(country) + region = simulation_runtime.resolve_region( + country_module=country_module, country=country, params=params + ) + selection = simulation_runtime._resolve_dataset_selection( + params, region_resolution=region + ) + return stage12_simulation.build_stage12_simulation( + params, + resolved=stage12_simulation.ResolvedSimulationInputs( + country_module=country_module, + region=region, + dataset_selection=selection, + dataset=object(), + ), + policy=None, + execution=simulation, + ) + + return build + + +class TestFixedIdsThroughTheHandlers: + """``qualifying_cache_identity`` asks the handlers for the level and scope.""" + + def test_the_scope_key_comes_from_the_handler(self, recorded_build, monkeypatch): + from policyengine_simulation_executor.stage12_cache import keys, levels_us + from policyengine_simulation_executor.stage12_cache.levels import ( + BaselineScope, + ) + from policyengine_simulation_executor.stage12_cache.precompute_planning import ( + baseline_identity, + ) + + _simulation, planned = baseline_identity(2026, FIRST_GROUP) + monkeypatch.setattr( + levels_us.UsStateGroupHandler, + "baseline_scope", + lambda _handler, run: BaselineScope( + region=run.region.code, scope_key="scope-from-the-handler" + ), + ) + + built = recorded_build(scoped_planned_simulation(2026, FIRST_GROUP)) + + expected = keys.Stage12BaselineCacheIdentity( + dataset=planned.dataset, + region_codes=FIRST_GROUP, + scope_key="scope-from-the-handler", + output_plan_sha256=planned.output_plan_sha256, + spm=planned.spm, + ) + assert built.kind == "cached" + assert built.arguments["id"] == expected.simulation_id + + def test_a_handler_without_a_scope_gives_a_random_id( + self, recorded_build, monkeypatch + ): + from policyengine_simulation_executor.stage12_cache import levels_us + + monkeypatch.setattr( + levels_us.UsStateGroupHandler, "baseline_scope", lambda _handler, _run: None + ) + + built = recorded_build(scoped_planned_simulation(2026, FIRST_GROUP)) + + assert built.kind == "random" + + def test_a_failing_scope_lookup_gives_a_random_id( + self, recorded_build, monkeypatch + ): + from policyengine_simulation_executor.stage12_cache import levels_us + + def fail(_handler, _run): + msg = "scope lookup failed" + raise RuntimeError(msg) + + monkeypatch.setattr(levels_us.UsStateGroupHandler, "baseline_scope", fail) + + built = recorded_build(scoped_planned_simulation(2026, FIRST_GROUP)) + + assert built.kind == "random" + + def test_failing_handler_settings_give_a_random_id( + self, recorded_build, monkeypatch + ): + from policyengine_simulation_executor.stage12_cache import levels_us + + def fail(): + msg = "the US handler settings failed to load" + raise RuntimeError(msg) + + monkeypatch.setattr(levels_us, "us_prebuilt", fail) + + built = recorded_build(scoped_planned_simulation(2026, FIRST_GROUP)) + + assert built.kind == "random" + + def test_a_level_the_cache_does_not_precompute_gives_a_random_id( + self, recorded_build, monkeypatch + ): + from policyengine_simulation_executor.stage12_cache import cache_levels + + monkeypatch.setattr(cache_levels, "CACHE_BASELINE_LEVELS", {"us": ()}) + + built = recorded_build(scoped_planned_simulation(2026, FIRST_GROUP)) + + assert built.kind == "random" + + def test_a_cached_level_still_needs_a_states_only_group(self, recorded_build): + """A group with a district gets a handler scope, but no fixed ID.""" + from policyengine_simulation_executor.stage12_cache.levels import ( + DatasetLevel, + RunScope, + prebuilt_for, + ) + + group_with_a_district = scoped_planned_simulation( + 2026, ("state/ca", "congressional_district/UT01") + ) + params = simulation_runtime_params(group_with_a_district) + region = simulation_runtime.resolve_region( + country_module=simulation_runtime._country_module("us"), + country="us", + params=params, + ) + run = RunScope( + country="us", + year=2026, + region=region, + dataset=simulation_runtime._resolve_dataset_selection( + params, region_resolution=region + ), + ) + prebuilt = prebuilt_for("us") + + # Only the states-only check keeps this group from a fixed ID: its + # level is one the cache precomputes, and the handler gives it a key. + assert prebuilt.level_of(run) is DatasetLevel.STATE_GROUP + scope = prebuilt.handlers[DatasetLevel.STATE_GROUP].baseline_scope(run) + assert scope is not None + assert scope.scope_key + assert recorded_build(group_with_a_district).kind == "random" + + +class _StoppedAfterLoadingError(Exception): + """Raised by the stubbed simulation build once the dataset has loaded.""" + + +@pytest.fixture +def recorded_load(us_inputs, monkeypatch): + """Run a calculation up to its dataset load; return the selection and folder.""" + from contextlib import nullcontext + + loads = [] + + def load_dataset(_params, *, selection, country_module, data_folder=None): + loads.append((selection.name, data_folder)) + return object() + + def stop_after_loading(*_args, **_kwargs): + raise _StoppedAfterLoadingError + + monkeypatch.setattr(stage12_simulation, "_require_installed_bundle", lambda _: None) + monkeypatch.setattr(simulation_runtime, "setup_gcp_credentials", nullcontext) + monkeypatch.setattr(simulation_runtime, "_load_dataset", load_dataset) + monkeypatch.setattr( + stage12_simulation, "detect_uk_run_dataset_metadata", lambda *_a, **_k: None + ) + monkeypatch.setattr( + stage12_simulation, "build_stage12_simulation", stop_after_loading + ) + + def load(simulation): + loads.clear() + with pytest.raises(_StoppedAfterLoadingError): + stage12_simulation.calculate_simulation_frames(simulation) + (loaded,) = loads + return loaded + + return load + + +def test_the_worker_takes_each_runs_folder_from_the_handlers( + us_inputs, recorded_load, monkeypatch +): + from policyengine_simulation_executor.stage12_cache import levels + + asked = [] + + def prebuilt_dataset_folder(run, data_folder): + asked.append((run.country, run.year, run.region.code, run.dataset.name)) + return levels.PrebuiltFolder( + folder=f"{data_folder}/{NATIONAL_FOLDER}", dataset_source=None + ) + + monkeypatch.setattr(levels, "prebuilt_dataset_folder", prebuilt_dataset_folder) + + loaded = recorded_load(scoped_planned_simulation(2026, FIRST_GROUP)) + + assert loaded == ( + DEFAULT_DATASET, + f"{us_inputs.data_folder}/{NATIONAL_FOLDER}", + ) + assert asked == [ + ( + "us", + 2026, + "region_group/" + "+".join(sorted(FIRST_GROUP)), + DEFAULT_DATASET, + ) + ] + + +class TestBuildersThroughTheHandlers: + """The precompute writes year files through the handlers, then uploads them.""" + + def test_the_deleted_copies_are_gone(self): + from policyengine_simulation_executor.stage12_cache import ( + precompute_planning, + state_datasets, + ) + + for name in ( + "_checked_state_targets", + "_registered_district_geoids", + "_require_districts_within_their_states", + ): + assert not hasattr(precompute_datasets, name), name + for name in ("StateDatasetTarget", "state_dataset_targets", "PRECOMPUTE_YEARS"): + assert not hasattr(precompute_planning, name), name + for name in ( + "baked_state_data_folder", + "state_dataset_folder", + "state_dataset_relative_folder", + ): + assert not hasattr(state_datasets, name), name + assert callable(state_datasets.year_file_reuse_problem) + + def test_the_state_build_writes_through_the_state_handler( + self, us_inputs, monkeypatch, tmp_path + ): + from policyengine_simulation_executor.stage12_cache import levels_us + from policyengine_simulation_executor.stage12_cache.levels import ( + year_file_name, + ) + + plan = precompute.plan_artifacts_impl(BUCKET) + entries = [ + entry + for entry in plan.state_datasets + if entry.year == 2026 and entry.state_code in {"UT", "WY"} + ] + writes = [] + + def write_year_files(_handler, year, targets, work_folder): + writes.append((year, [target.subset.code for target in targets])) + written = {} + for target in targets: + path = Path(work_folder) / target.folder / year_file_name(target) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(f"rows of {target.subset.code}".encode()) + written[target] = path + return written + + monkeypatch.setattr( + levels_us.UsStateHandler, "write_year_files", write_year_files + ) + + results = precompute.build_state_datasets_impl( + BUCKET, 2026, entries, work_folder=tmp_path / "work" + ) + + assert writes == [(2026, ["UT", "WY"])] + assert [result.state_code for result in results] == ["UT", "WY"] + assert us_inputs.cache_bucket.objects[entries[0].path] == b"rows of UT" + assert us_inputs.cache_bucket.objects[entries[1].path] == b"rows of WY" + + def test_the_national_build_leaves_no_work_folder_behind( + self, us_inputs, monkeypatch + ): + from policyengine_simulation_executor.stage12_cache import levels_us + from policyengine_simulation_executor.stage12_cache.levels import ( + year_file_name, + ) + + plan = precompute.plan_artifacts_impl(BUCKET) + work_folders = [] + + def write_year_files(_handler, _year, targets, work_folder): + work_folders.append(Path(work_folder)) + (target,) = targets + path = us_inputs.data_folder / year_file_name(target) + path.write_bytes(b"national year file") + return {target: path} + + monkeypatch.setattr( + levels_us.UsNationalHandler, "write_year_files", write_year_files + ) + + precompute.build_dataset_impl(BUCKET, plan.datasets[0]) + + (work_folder,) = work_folders + assert not work_folder.exists() + + def test_the_national_build_writes_through_the_national_handler( + self, us_inputs, monkeypatch + ): + from policyengine_simulation_executor.stage12_cache import levels_us + from policyengine_simulation_executor.stage12_cache.levels import ( + year_file_name, + ) + + plan = precompute.plan_artifacts_impl(BUCKET) + entry = plan.datasets[0] + writes = [] + + def write_year_files(_handler, year, targets, _work_folder): + writes.append((year, [target.folder for target in targets])) + (target,) = targets + path = us_inputs.data_folder / year_file_name(target) + path.write_bytes(b"national year file") + return {target: path} + + monkeypatch.setattr( + levels_us.UsNationalHandler, "write_year_files", write_year_files + ) + + result = precompute.build_dataset_impl(BUCKET, entry) + + assert writes == [(2026, [NATIONAL_FOLDER])] + assert result.uploaded is True + assert us_inputs.cache_bucket.objects[entry.path] == b"national year file" + + def test_a_baseline_is_computed_beside_its_year_file_in_the_prebuilt_folder( + self, us_inputs, monkeypatch + ): + plan = precompute.plan_artifacts_impl(BUCKET) + year_file = plan.datasets[0] + baseline = plan.baselines[0] + us_inputs.cache_bucket.store(year_file.path, b"national year file") + folder = us_inputs.data_folder / NATIONAL_FOLDER + seen = [] + + def calculate(simulation): + seen.append(sorted(path.name for path in folder.glob("*.h5"))) + (folder / baseline.filename).write_bytes(b"baseline output") + return SimpleNamespace(frames={}, cache_outcome="miss") + + monkeypatch.setattr( + precompute_baselines.stage12_simulation, + "calculate_simulation_frames", + calculate, + ) + + result = precompute.compute_baseline_impl(BUCKET, baseline) + + assert seen == [[year_file.filename]] + assert (folder / year_file.filename).read_bytes() == b"national year file" + assert result.uploaded is True + assert us_inputs.cache_bucket.objects[baseline.path] == b"baseline output" + assert not list(us_inputs.data_folder.glob("*.h5")) + + def test_the_baseline_calculation_reads_the_downloaded_prebuilt_year_file( + self, us_inputs, monkeypatch, tmp_path + ): + """The real prebuilt-folder lookup, during the precompute, finds the file.""" + from contextlib import nullcontext + + from fixtures.state_dataset_sources import write_year_file + + plan = precompute.plan_artifacts_impl(BUCKET) + year_file = plan.datasets[0] + baseline = plan.baselines[0] + stamped = write_year_file(tmp_path, year=2026, dataset=DEFAULT_DATASET) + us_inputs.cache_bucket.store(year_file.path, stamped.read_bytes()) + loads = [] + + def load_dataset(_params, *, selection, country_module, data_folder=None): + loads.append(data_folder) + raise _StoppedAfterLoadingError + + monkeypatch.setattr(simulation_runtime, "setup_gcp_credentials", nullcontext) + monkeypatch.setattr(simulation_runtime, "_load_dataset", load_dataset) + + with pytest.raises(_StoppedAfterLoadingError): + precompute.compute_baseline_impl(BUCKET, baseline) + + assert loads == [str(us_inputs.data_folder / baseline.folder)] + + def test_the_state_folder_of_a_plan_entry_is_the_handlers(self, us_inputs): + plan = precompute.plan_artifacts_impl(BUCKET) + utah = next( + entry + for entry in plan.state_datasets + if entry.year == 2026 and entry.state_code == "UT" + ) + + assert utah.folder == f"prebuilt/us/{STATE_LEVEL_DATASET}/UT" diff --git a/projects/policyengine-simulation-executor/tests/test_v2_cache_us_image_pins.py b/projects/policyengine-simulation-executor/tests/test_v2_cache_us_image_pins.py new file mode 100644 index 000000000..9f0250f63 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_v2_cache_us_image_pins.py @@ -0,0 +1,310 @@ +"""Pins of the v2 report app's US image download step and its deploy-time check. + +Every expected value below is what ``main`` produced on 2026-11-25 (commit +6865dc2c) for the fixed inputs in ``fixtures.v2_cache_us_inputs``, with each +planned file stored in a fake bucket as the bytes ``v2-cache-pin:``. +The manifest is the one the precompute publishes for that plan, so these +pins run the plan, the manifest, ``fetch_stage12_cache`` (the image build's +download step) and ``_check_installed_cache`` (the deployed worker's check) +end to end. + +What the download step accepts and refuses must stay unchanged when the v2 +cache moves onto the level handlers: exactly 3 year files and 60 baselines, +the years 2026, 2027 and 2025 in that order, and each file's SHA-256 and +size. Since 2026-11-27 the step receives those years and counts from the +deploying machine (``EXPECTED_CONTENTS`` here) instead of holding them as +constants; what it accepts and refuses is unchanged. Where it places the +files is pinned apart, in ``TestImageFolders``: they moved to the handlers' +``prebuilt/…`` folders that day, in a commit of their own. +""" + +from __future__ import annotations + +import json +from hashlib import sha256 +from types import SimpleNamespace +from typing import TYPE_CHECKING + +import pytest +from fixtures.v2_cache_us_inputs import ( + BUNDLE_MANIFEST_SHA256, + STATE_LEVEL_DATASET, + enable_fixed_spm, + install_v2_cache_us_inputs, +) +from policyengine_simulation_executor.stage12_cache import keys, precompute +from policyengine_simulation_executor.stage12_cache.store import Stage12CacheStore +from policyengine_simulation_executor.stage12_runtime.partition import US_REGION_GROUPS +from src.modal.stage12_cache_image import fetch_stage12_cache + +if TYPE_CHECKING: + from pathlib import Path + +BUCKET = "bucket-pins" +# What the deploying machine passes the download step for the US cache: the +# years and the year-file and baseline counts ``main`` held as constants. +EXPECTED_CONTENTS = { + "years": [2026, 2027, 2025], + "artifact_counts": {"dataset": 3, "baseline": 60}, +} +MANIFEST_COPY = ".stage12-cache-manifest.json" +NATIONAL_FOLDER = "prebuilt/us/populace_us_2024/all" + + +def _stored_bytes(path: str) -> bytes: + return f"v2-cache-pin:{path}".encode() + + +def _canonical_bytes(payload: dict) -> bytes: + return json.dumps( + payload, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=True, + allow_nan=False, + ).encode("utf-8") + + +@pytest.fixture(scope="module") +def published(): + """Plan the fixed US inputs, store each planned file and build the manifest.""" + with pytest.MonkeyPatch.context() as module_patch: + inputs = install_v2_cache_us_inputs(module_patch) + enable_fixed_spm(inputs) + plan = precompute.plan_artifacts_impl(BUCKET) + for entry in (*plan.datasets, *plan.baselines, *plan.state_datasets): + inputs.cache_bucket.store(entry.path, _stored_bytes(entry.path)) + manifest = precompute.build_manifest( + plan, Stage12CacheStore(BUCKET) + ).canonical_payload() + yield SimpleNamespace(plan=plan, inputs=inputs, manifest=manifest) + + +@pytest.fixture +def image(published, monkeypatch, tmp_path): + """Give a test an image data folder and a download into it, as deployed.""" + data_folder = tmp_path / "data" + monkeypatch.setenv("POLICYENGINE_DATA_FOLDER", str(data_folder)) + monkeypatch.setenv("STAGE12_BUNDLE_MANIFEST_SHA256", BUNDLE_MANIFEST_SHA256) + + def fetch(manifest: dict) -> None: + monkeypatch.setenv( + "STAGE12_CACHE_MANIFEST_DIGEST", keys.canonical_digest(manifest) + ) + fetch_stage12_cache( + BUCKET, + manifest, + EXPECTED_CONTENTS, + client=published.inputs.cache_bucket, + ) + + return SimpleNamespace(data_folder=data_folder, fetch=fetch) + + +def _files_under(folder: Path) -> list[Path]: + return sorted(path for path in folder.rglob("*") if path.is_file()) + + +def test_downloads_the_published_manifest_of_the_plan(published, image): + image.fetch(published.manifest) + + h5_files = [ + path for path in _files_under(image.data_folder) if path.suffix == ".h5" + ] + assert len(h5_files) == 3 + 60 + 153 + copy = (image.data_folder / MANIFEST_COPY).read_bytes() + assert copy == _canonical_bytes(published.manifest) + assert sha256(copy).hexdigest() == keys.canonical_digest(published.manifest) + + +def _with_years(manifest: dict, years: list[int]) -> dict: + return {**manifest, "years": years} + + +def _with_an_extra_artifact(manifest: dict, kind: str) -> dict: + template = next(item for item in manifest["artifacts"] if item["type"] == kind) + extra = {**template, "filename": f"extra-{template['filename']}", "year": 2028} + return {**manifest, "artifacts": [*manifest["artifacts"], extra]} + + +def _without_the_first_artifact(manifest: dict, kind: str) -> dict: + first = next(item for item in manifest["artifacts"] if item["type"] == kind) + return { + **manifest, + "artifacts": [item for item in manifest["artifacts"] if item is not first], + } + + +@pytest.mark.parametrize( + ("change", "message"), + [ + pytest.param( + lambda manifest: _with_years(manifest, [2025, 2026, 2027]), + "^Stage 12 cache manifest has an unexpected year set$", + id="same-years-in-another-order", + ), + pytest.param( + lambda manifest: _with_years(manifest, [2026, 2027, 2025, 2028]), + "^Stage 12 cache manifest has an unexpected year set$", + id="a-fourth-year", + ), + pytest.param( + lambda manifest: _with_an_extra_artifact(manifest, "dataset"), + "^Stage 12 cache manifest has an unexpected artifact count$", + id="four-year-files", + ), + pytest.param( + lambda manifest: _without_the_first_artifact(manifest, "dataset"), + "^Stage 12 cache manifest has an unexpected artifact count$", + id="two-year-files", + ), + pytest.param( + lambda manifest: _with_an_extra_artifact(manifest, "baseline"), + "^Stage 12 cache manifest has an unexpected artifact count$", + id="sixty-one-baselines", + ), + ], +) +def test_refuses_a_manifest_with_other_counts_or_years_before_downloading( + published, image, change, message +): + with pytest.raises(RuntimeError, match=message): + image.fetch(change(published.manifest)) + + assert not image.data_folder.exists() or _files_under(image.data_folder) == [] + + +def test_refuses_a_file_of_another_size_and_leaves_none_of_it(published, image): + baseline = published.plan.baselines[0] + bucket = published.inputs.cache_bucket + original = bucket.objects[baseline.path] + bucket.objects[baseline.path] = original + b"-longer" + try: + with pytest.raises( + RuntimeError, match=r"^Stage 12 cache artifact size differs$" + ): + image.fetch(published.manifest) + finally: + bucket.objects[baseline.path] = original + + assert not [ + path + for path in _files_under(image.data_folder) + if path.name.startswith(baseline.filename) + ] + assert not (image.data_folder / MANIFEST_COPY).exists() + + +class TestDeployTimeCheck: + """``_check_installed_cache``: what a deployed US worker requires of its image.""" + + def test_expects_the_planned_counts_and_years(self, published): + from policyengine_simulation_executor import stage12_worker_validation + from policyengine_simulation_executor.stage12_cache import ( + precompute_planning, + ) + + # main held these as STAGE12_CACHE_ARTIFACT_COUNT (63) and + # STAGE12_CACHE_PROBE_YEAR (2026). + assert precompute_planning.expected_cache_contents("us") == (EXPECTED_CONTENTS) + assert stage12_worker_validation.expected_state_dataset_count() == 153 + + def test_accepts_the_downloaded_cache_and_reports_its_release( + self, published, image, monkeypatch + ): + from policyengine_simulation_executor import stage12_worker_validation + + image.fetch(published.manifest) + probes = [] + + def calculate(simulation): + probes.append(simulation) + return SimpleNamespace(cache_outcome="hit") + + monkeypatch.setattr( + stage12_worker_validation, "calculate_simulation_frames", calculate + ) + digest = keys.canonical_digest(published.manifest) + + summary = stage12_worker_validation._check_installed_cache(digest) + + assert summary == { + "manifest_sha256": digest, + "partition_sha256": ( + "25f8ed5bbcbe25592433b8bda46d73a4597f960f79ae8058f4eef33ed1e0e615" + ), + "years": [2026, 2027, 2025], + "segment_count": 20, + "dataset_count": 3, + "baseline_count": 60, + } + (probe,) = probes + assert probe.year == 2026 + assert probe.options == {"region_group": list(US_REGION_GROUPS[0])} + + +class TestImageFolders: + """Where the download step and the deploy-time check find each file. + + Until 2026-11-27 (``main`` at 6865dc2c) year files and baselines landed in + the data folder itself and state files in ``state-datasets// + ``. Every file now lands in its handler's ``prebuilt/…`` folder. + """ + + def test_year_files_and_baselines_land_in_the_national_folder( + self, published, image + ): + image.fetch(published.manifest) + + for entry in (*published.plan.datasets, *published.plan.baselines): + destination = image.data_folder / NATIONAL_FOLDER / entry.filename + assert destination.read_bytes() == _stored_bytes(entry.path) + assert not list(image.data_folder.glob("*.h5")) + + def test_state_files_land_in_their_state_folders(self, published, image): + image.fetch(published.manifest) + + for entry in published.plan.state_datasets: + destination = ( + image.data_folder + / "prebuilt" + / "us" + / STATE_LEVEL_DATASET + / entry.state_code + / entry.filename + ) + assert destination.read_bytes() == _stored_bytes(entry.path) + + def test_the_deploy_check_reads_its_probe_baseline_from_the_national_folder( + self, published, image, monkeypatch + ): + from policyengine_simulation_executor import stage12_worker_validation + + image.fetch(published.manifest) + checked = [] + original_check = stage12_worker_validation._check_dataset_access + + def check_dataset_access(path, expected_sha256): + checked.append(path) + original_check(path, expected_sha256) + + monkeypatch.setattr( + stage12_worker_validation, "_check_dataset_access", check_dataset_access + ) + monkeypatch.setattr( + stage12_worker_validation, + "calculate_simulation_frames", + lambda _simulation: SimpleNamespace(cache_outcome="hit"), + ) + + stage12_worker_validation._check_installed_cache( + keys.canonical_digest(published.manifest) + ) + + assert checked == [ + str( + image.data_folder + / NATIONAL_FOLDER + / published.plan.baselines[0].filename + ) + ] diff --git a/projects/policyengine-simulation-executor/tests/test_v2_cache_us_lookup_pins.py b/projects/policyengine-simulation-executor/tests/test_v2_cache_us_lookup_pins.py new file mode 100644 index 000000000..ad0ae6f18 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_v2_cache_us_lookup_pins.py @@ -0,0 +1,362 @@ +"""Pins of how the v2 report app's US worker looks its cache files up at run time. + +Every expected value below is what ``main`` produced on 2026-11-25 (commit +6865dc2c) for the fixed inputs in ``fixtures.v2_cache_us_inputs``. Two +lookups are pinned, each through the worker function that uses it, so the +pins hold however the lookup is implemented: + +* which runs ``build_stage12_simulation`` gives a fixed cache identity (a + ``Stage12CachedSimulation``, whose saved file the worker image may hold) + and which a random one (a plain ``Simulation``). Moving the v2 cache onto + the level handlers must leave every outcome unchanged; in particular a US + national run without a region group, a single state, a district and a + UK-wide run get no v2 cache identity, though the run_simulation app gives + some of them one; +* which folder ``calculate_simulation_frames`` loads each run's dataset from + (``TestDatasetFolders``). The baked folders moved to the handlers' + ``prebuilt/…`` folders on 2026-11-27, in a commit of their own. +""" + +from __future__ import annotations + +from contextlib import nullcontext +from types import SimpleNamespace +from typing import TYPE_CHECKING + +import pytest +from fixtures.v2_cache_us_inputs import ( + DEFAULT_DATASET, + STATE_LEVEL_DATASET, + enable_fixed_spm, + install_v2_cache_us_inputs, +) +from policyengine_simulation_contract.stage12_execution import ( + GeographySelection, + SimulationRole, +) +from policyengine_simulation_executor import simulation_runtime +from policyengine_simulation_executor.stage12_cache import keys, precompute +from policyengine_simulation_executor.stage12_cache.precompute_planning import ( + _planned_pair, + scoped_planned_simulation, +) +from policyengine_simulation_executor.stage12_runtime import ( + simulation as stage12_simulation, +) +from policyengine_simulation_executor.stage12_runtime.partition import US_REGION_GROUPS +from policyengine_simulation_executor.stage12_runtime.worker_inputs import ( + simulation_runtime_params, +) + +if TYPE_CHECKING: + from pathlib import Path + +BUCKET = "bucket-pins" +FIXED_SPM_SELECTION = { + "forecast_content_sha256": "a" * 64, + "scenario": "ce_trend", + "geography_kind": "national", + "geography_id": None, + "county_vintage": "2020", + "as_of": None, +} +SPM_SUFFIX = "-spm-7396bf5f4876c42bb6cba0f9533478098edc0861cc3657bd0d60f88dbb26ac39" + + +class _RecordedCachedSimulation: + """Stands in for ``Stage12CachedSimulation``: records what it was built with.""" + + kind = "cached" + + def __init__(self, **keyword_arguments): + self.arguments = keyword_arguments + self.output_plan = None + + def configure_stage12_cache(self, output_plan): + self.output_plan = output_plan + + +def _recorded_plain_simulation(**keyword_arguments): + return SimpleNamespace(kind="random", arguments=keyword_arguments) + + +@pytest.fixture(scope="module") +def us_inputs(): + with pytest.MonkeyPatch.context() as module_patch: + inputs = install_v2_cache_us_inputs(module_patch) + enable_fixed_spm(inputs) + yield inputs + + +@pytest.fixture(scope="module") +def us_plan(us_inputs): + return precompute.plan_artifacts_impl(BUCKET) + + +@pytest.fixture +def recorded_build(us_inputs, monkeypatch): + """Build a planned simulation as the worker does, recording what is built.""" + monkeypatch.setattr( + stage12_simulation, "Stage12CachedSimulation", _RecordedCachedSimulation + ) + monkeypatch.setattr(stage12_simulation, "Simulation", _recorded_plain_simulation) + + def build(simulation): + params = simulation_runtime_params(simulation) + country = simulation.geography.country + country_module = simulation_runtime._country_module(country) + region = simulation_runtime.resolve_region( + country_module=country_module, country=country, params=params + ) + selection = simulation_runtime._resolve_dataset_selection( + params, region_resolution=region + ) + return stage12_simulation.build_stage12_simulation( + params, + resolved=stage12_simulation.ResolvedSimulationInputs( + country_module=country_module, + region=region, + dataset_selection=selection, + dataset=object(), + ), + policy=None, + execution=simulation, + ) + + return build + + +def _baseline_for(region: str, year: int = 2026): + """Plan the current-law US baseline for one region, with no region group.""" + baseline, _reform = _planned_pair(year) + return baseline.model_copy( + update={"geography": GeographySelection(country="us", region=region)} + ) + + +def _grouped_baseline(group: list[str], year: int = 2026): + """Plan the current-law US baseline scoped to ``group``, a planned one or not.""" + return scoped_planned_simulation(year, tuple(group)) + + +class TestCacheIdentities: + """Which runs get a fixed v2 cache identity.""" + + def test_every_planned_group_baseline_reads_its_planned_file( + self, us_plan, recorded_build + ): + for entry in us_plan.baselines: + built = recorded_build( + scoped_planned_simulation(entry.year, tuple(entry.region_codes)) + ) + + assert built.kind == "cached", entry.region_codes + assert built.arguments["id"] == entry.simulation_id + assert built.arguments["spm"] == FIXED_SPM_SELECTION + # .py saves and loads the file as the ID plus the SPM digest. + assert entry.filename == ( + f"{built.arguments['id']}" + f"-spm-{keys.canonical_digest(built.arguments['spm'])}.h5" + ) + assert built.output_plan is not None + + def test_a_state_group_outside_the_partition_gets_a_fixed_identity( + self, recorded_build + ): + built = recorded_build(_grouped_baseline(["state/ca", "state/ny"])) + + assert built.kind == "cached" + assert built.arguments["id"] == "stage12-bl1-c0445de8790068d7" + + def test_a_planned_group_in_a_year_without_files_gets_a_fixed_identity( + self, recorded_build + ): + built = recorded_build(_grouped_baseline(list(US_REGION_GROUPS[0]), year=2028)) + + assert built.kind == "cached" + assert built.arguments["id"] == "stage12-bl1-10b3e998a57c0266" + + @pytest.mark.parametrize( + "run", + [ + pytest.param( + lambda: scoped_planned_simulation( + 2026, tuple(US_REGION_GROUPS[0]), reform=True + ), + id="reform-side-of-a-planned-group", + ), + pytest.param( + lambda: scoped_planned_simulation( + 2026, tuple(US_REGION_GROUPS[0]) + ).model_copy(update={"policy": {"gov.irs.credits.ctc.amount": 1}}), + id="planned-group-with-a-policy", + ), + pytest.param( + lambda: scoped_planned_simulation( + 2026, tuple(US_REGION_GROUPS[0]) + ).model_copy(update={"role": SimulationRole.REFORM}), + id="planned-group-in-the-reform-role", + ), + pytest.param(lambda: _baseline_for("us"), id="us-national-without-a-group"), + pytest.param(lambda: _baseline_for("state/ca"), id="single-state"), + pytest.param( + lambda: _baseline_for("congressional_district/UT01"), id="district" + ), + pytest.param( + lambda: _grouped_baseline(["state/ca", "congressional_district/UT01"]), + id="group-with-a-district", + ), + pytest.param( + lambda: _baseline_for("us").model_copy( + update={"geography": GeographySelection(country="uk", region="uk")} + ), + id="uk-wide", + ), + ], + ) + def test_other_runs_get_a_random_identity(self, recorded_build, run): + built = recorded_build(run()) + + assert built.kind == "random" + assert "id" not in built.arguments + + +class _StoppedAfterLoadingError(Exception): + """Raised by the stubbed simulation build once the dataset has loaded.""" + + +@pytest.fixture +def recorded_load(us_inputs, monkeypatch, tmp_path): + """Run a calculation up to its dataset load; return the selection and folder.""" + data_folder = tmp_path / "data" + data_folder.mkdir() + monkeypatch.setenv("POLICYENGINE_DATA_FOLDER", str(data_folder)) + loads = [] + + def load_dataset(_params, *, selection, country_module, data_folder=None): + loads.append((selection.name, data_folder)) + return object() + + def stop_after_loading(*_args, **_kwargs): + raise _StoppedAfterLoadingError + + monkeypatch.setattr(stage12_simulation, "_require_installed_bundle", lambda _: None) + monkeypatch.setattr(simulation_runtime, "setup_gcp_credentials", nullcontext) + monkeypatch.setattr(simulation_runtime, "_load_dataset", load_dataset) + monkeypatch.setattr( + stage12_simulation, "detect_uk_run_dataset_metadata", lambda *_a, **_k: None + ) + monkeypatch.setattr( + stage12_simulation, "build_stage12_simulation", stop_after_loading + ) + + def load(simulation): + loads.clear() + with pytest.raises(_StoppedAfterLoadingError): + stage12_simulation.calculate_simulation_frames(simulation) + (loaded,) = loads + return loaded + + return SimpleNamespace(load=load, data_folder=data_folder) + + +def _bake_state_file(data_folder: Path, state_code: str, year: int, *, stamp=True): + """Put a state's year file where the worker image holds it.""" + from fixtures.state_dataset_sources import write_year_file + + folder = data_folder / "prebuilt" / "us" / STATE_LEVEL_DATASET / state_code + folder.mkdir(parents=True, exist_ok=True) + write_year_file(folder, year=year, stamp=stamp) + return folder + + +def _bake_national_file(data_folder: Path, year: int) -> Path: + """Put the default dataset's year file where the worker image holds it.""" + from fixtures.state_dataset_sources import write_year_file + + folder = data_folder / "prebuilt" / "us" / DEFAULT_DATASET / "all" + folder.mkdir(parents=True, exist_ok=True) + write_year_file(folder, year=year, dataset=DEFAULT_DATASET) + return folder + + +class TestDatasetFolders: + """Which folder the worker loads each run's dataset from. + + None means the loader's own default: the image data folder for the + default dataset and a temporary folder for any other. Until 2026-11-27 + (``main`` at 6865dc2c) a state's file sat in ``state-datasets// + ``, and national and group runs always loaded the default dataset + from the data folder itself, where the national year files and baselines + sat. Each baked file now sits in its handler's ``prebuilt/…`` folder, and + national and group runs read the national one when the image holds it. + """ + + def test_national_and_group_runs_load_the_national_folder_when_baked( + self, recorded_load + ): + group_run = scoped_planned_simulation(2026, tuple(US_REGION_GROUPS[0])) + _bake_state_file(recorded_load.data_folder, "CA", 2026) + + assert recorded_load.load(_baseline_for("us")) == (DEFAULT_DATASET, None) + assert recorded_load.load(group_run) == (DEFAULT_DATASET, None) + + national = _bake_national_file(recorded_load.data_folder, 2026) + + assert recorded_load.load(_baseline_for("us")) == ( + DEFAULT_DATASET, + str(national), + ) + assert recorded_load.load(group_run) == (DEFAULT_DATASET, str(national)) + assert recorded_load.load(_baseline_for("us", year=2028)) == ( + DEFAULT_DATASET, + None, + ) + + def test_a_state_with_a_baked_file_loads_its_state_folder(self, recorded_load): + folder = _bake_state_file(recorded_load.data_folder, "CA", 2026) + + assert recorded_load.load(_baseline_for("state/ca")) == ( + STATE_LEVEL_DATASET, + str(folder), + ) + assert folder == ( + recorded_load.data_folder + / "prebuilt" + / "us" + / "populace_us_2024_acs_local" + / "CA" + ) + + def test_a_district_loads_its_states_folder(self, recorded_load): + utah = _bake_state_file(recorded_load.data_folder, "UT", 2026) + california = _bake_state_file(recorded_load.data_folder, "CA", 2026) + + assert recorded_load.load(_baseline_for("congressional_district/UT01")) == ( + STATE_LEVEL_DATASET, + str(utah), + ) + assert recorded_load.load(_baseline_for("congressional_district/CA12")) == ( + STATE_LEVEL_DATASET, + str(california), + ) + + def test_a_state_or_year_without_a_usable_baked_file_loads_on_demand( + self, recorded_load + ): + _bake_state_file(recorded_load.data_folder, "CA", 2026) + _bake_state_file(recorded_load.data_folder, "UT", 2026, stamp=False) + + assert recorded_load.load(_baseline_for("state/wy")) == ( + STATE_LEVEL_DATASET, + None, + ) + assert recorded_load.load(_baseline_for("state/ca", year=2028)) == ( + STATE_LEVEL_DATASET, + None, + ) + # .py would rebuild an unstamped year file, so it is not read. + assert recorded_load.load(_baseline_for("state/ut")) == ( + STATE_LEVEL_DATASET, + None, + ) diff --git a/projects/policyengine-simulation-executor/tests/test_v2_cache_us_manifest_pins.py b/projects/policyengine-simulation-executor/tests/test_v2_cache_us_manifest_pins.py new file mode 100644 index 000000000..48bfae2c5 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_v2_cache_us_manifest_pins.py @@ -0,0 +1,234 @@ +"""Pins of the v2 report app's US cache manifest: entry order, payload and digest. + +Every expected value below is what ``main`` produced on 2026-11-25 (commit +6865dc2c) for the fixed inputs in ``fixtures.v2_cache_us_inputs``, with each +planned file stored in a fake bucket as the bytes ``v2-cache-pin:``. +Moving the v2 cache onto the level handlers keeps its manifest (schema +``stage12-mf1``), so each value must stay unchanged. + +The manifest records each file's image folder. On 2026-11-27 the folders +moved to the handlers' ``prebuilt/…`` folders, and year files and baselines +began to record theirs too (before, only state files did). That changed the +manifest's digest through the ``folder`` fields alone, so the digest is +pinned twice: without the folder fields +(``test_digest_without_the_image_folders``), unchanged since ``main``, and in +full (``TestImageFolders``), with the value of the new layout. +""" + +from __future__ import annotations + +import json +from hashlib import sha256 + +import pytest +from fixtures.v2_cache_us_inputs import ( + STATE_LEVEL_DATASET, + enable_fixed_spm, + install_v2_cache_us_inputs, +) +from policyengine_simulation_executor.stage12_cache import keys, precompute +from policyengine_simulation_executor.stage12_cache.models import CacheManifest +from policyengine_simulation_executor.stage12_cache.store import Stage12CacheStore + +BUCKET = "bucket-pins" +SPM_SUFFIX = "-spm-7396bf5f4876c42bb6cba0f9533478098edc0861cc3657bd0d60f88dbb26ac39" +YEAR_FILE_2026 = "e4a6dacf5954ccac03abfbcba50c44a3a156d351ed25e3214ae20d7e093e0dac" +FIRST_BASELINE = "88acdd57481da78416475d199be783bb06732a81094dd3658518ad028e0502bd" +ALASKA_2026 = "be2d28af31a275139be0a74a47d02582ca4f6cbfa10d956c3f3c4f227113bbbc" + + +def _stored_bytes(path: str) -> bytes: + return f"v2-cache-pin:{path}".encode() + + +@pytest.fixture(scope="module") +def stored_plan(): + """Plan the fixed US inputs and store every planned file in the fake bucket.""" + with pytest.MonkeyPatch.context() as module_patch: + inputs = install_v2_cache_us_inputs(module_patch) + enable_fixed_spm(inputs) + plan = precompute.plan_artifacts_impl(BUCKET) + for entry in (*plan.datasets, *plan.baselines, *plan.state_datasets): + inputs.cache_bucket.store(entry.path, _stored_bytes(entry.path)) + yield plan, inputs + + +@pytest.fixture(scope="module") +def manifest_payload(stored_plan): + plan, _inputs = stored_plan + return precompute.build_manifest( + plan, Stage12CacheStore(BUCKET) + ).canonical_payload() + + +def test_lists_year_files_then_baselines_then_state_files_in_plan_order( + stored_plan, manifest_payload +): + plan, _inputs = stored_plan + artifacts = manifest_payload["artifacts"] + + assert [item["type"] for item in artifacts] == ( + ["dataset"] * 3 + ["baseline"] * 60 + ["state_dataset"] * 153 + ) + assert [item["path"] for item in artifacts] == [ + entry.path for entry in (*plan.datasets, *plan.baselines, *plan.state_datasets) + ] + assert [item["identity_digest"] for item in artifacts] == [ + entry.digest + for entry in (*plan.datasets, *plan.baselines, *plan.state_datasets) + ] + + +def test_records_each_stored_files_hash_and_size(manifest_payload): + for item in manifest_payload["artifacts"]: + payload = _stored_bytes(item["path"]) + assert item["content_sha256"] == sha256(payload).hexdigest() + assert item["size_bytes"] == len(payload) + + +def test_the_top_level_fields(manifest_payload): + assert { + key: value for key, value in manifest_payload.items() if key != "artifacts" + } == { + "schema": "stage12-mf1", + "country": "us", + "years": [2026, 2027, 2025], + "partition_sha256": ( + "25f8ed5bbcbe25592433b8bda46d73a4597f960f79ae8058f4eef33ed1e0e615" + ), + "bundle": { + "bundle_manifest_sha256": "b" * 64, + "policyengine_version": "6.20.0", + "core_package_version": "3.33.3", + "country_package_version": "2.2.2", + "data_package_version": "1.4.0", + "data_artifact_revision": "rev-default", + "default_dataset": "populace_us_2024", + }, + } + + +def test_digest_without_the_image_folders(manifest_payload): + without_folders = { + **manifest_payload, + "artifacts": [ + {key: value for key, value in item.items() if key != "folder"} + for item in manifest_payload["artifacts"] + ], + } + + assert keys.canonical_digest(without_folders) == ( + "d6d8427104e32fa1e1e449f3f7c255485b158cae9fb32e858ad16204881586f8" + ) + + +def test_the_exact_payload_of_a_one_entry_per_kind_plan(stored_plan): + plan, _inputs = stored_plan + small_plan = plan.model_copy( + update={ + "datasets": plan.datasets[:1], + "baselines": plan.baselines[:1], + "state_datasets": plan.state_datasets[:1], + } + ) + + payload = precompute.build_manifest( + small_plan, Stage12CacheStore(BUCKET) + ).canonical_payload() + + assert payload["artifacts"] == [ + { + "type": "dataset", + "path": f"datasets/us/{YEAR_FILE_2026}/populace_us_2024_year_2026.h5", + "filename": "populace_us_2024_year_2026.h5", + "folder": "prebuilt/us/populace_us_2024/all", + "year": 2026, + "identity_digest": YEAR_FILE_2026, + "content_sha256": ( + "bca9c3dc606ee939620d2d4947eccbc7cbb8eda318480290c5095e0df0417b9b" + ), + "size_bytes": 119, + }, + { + "type": "baseline", + "path": ( + f"baselines/us/{FIRST_BASELINE}/" + f"stage12-bl1-88acdd57481da784{SPM_SUFFIX}.h5" + ), + "filename": f"stage12-bl1-88acdd57481da784{SPM_SUFFIX}.h5", + "folder": "prebuilt/us/populace_us_2024/all", + "year": 2026, + "identity_digest": FIRST_BASELINE, + "content_sha256": ( + "b73d92af8db734a891c932d7f63c6bd6a06a6f777984a4d865551f050adc1e14" + ), + "size_bytes": 191, + }, + { + "type": "state_dataset", + "path": ( + f"state-datasets/us/{ALASKA_2026}/{STATE_LEVEL_DATASET}_year_2026.h5" + ), + "filename": f"{STATE_LEVEL_DATASET}_year_2026.h5", + "folder": f"prebuilt/us/{STATE_LEVEL_DATASET}/AK", + "state_code": "AK", + "year": 2026, + "identity_digest": ALASKA_2026, + "content_sha256": ( + "e162fc40ab4a4407755ac797821fa3f66776a9d5cf46b976c3335f5f9ca92b83" + ), + "size_bytes": 135, + }, + ] + assert CacheManifest.model_validate(payload).canonical_payload() == payload + + +def test_publishing_writes_the_canonical_bytes_once_under_their_digest(stored_plan): + plan, inputs = stored_plan + record_path = precompute.determinism_record_path(plan.baselines) + inputs.cache_bucket.store(record_path, b"{}") + try: + digest = precompute.publish_manifest_impl(BUCKET, plan) + manifest_path = f"manifests/{digest}.json" + published = inputs.cache_bucket.objects[manifest_path] + republished_digest = precompute.publish_manifest_impl(BUCKET, plan) + finally: + inputs.cache_bucket.objects.pop(record_path, None) + inputs.cache_bucket.metadata.pop(record_path, None) + + payload = precompute.build_manifest( + plan, Stage12CacheStore(BUCKET) + ).canonical_payload() + canonical = json.dumps( + payload, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=True, + allow_nan=False, + ).encode("utf-8") + assert published == canonical + # The image download step checks the manifest's SHA-256 against this digest. + assert sha256(published).hexdigest() == digest + assert republished_digest == digest + assert inputs.cache_bucket.objects[manifest_path] == published + + +def test_the_line_the_precompute_prints_for_the_deploy_job(): + assert precompute.MANIFEST_DIGEST_PREFIX == "STAGE12_CACHE_MANIFEST_DIGEST=" + assert precompute.manifest_digest_line("d" * 64) == ( + "STAGE12_CACHE_MANIFEST_DIGEST=" + "d" * 64 + ) + + +class TestImageFolders: + """The full digest, which covers each file's image folder. + + It was 0e2b95a1…bce3fe on ``main`` (6865dc2c), with state files in + ``state-datasets/…`` and no folder for year files and baselines. This is + the same manifest with every file in its ``prebuilt/…`` folder. + """ + + def test_full_digest(self, manifest_payload): + assert keys.canonical_digest(manifest_payload) == ( + "eeaaf3bab1c0eeaaa23499129cd59af0d24896e89ad24d167443e37ab01a477e" + ) diff --git a/projects/policyengine-simulation-executor/tests/test_v2_cache_us_plan_pins.py b/projects/policyengine-simulation-executor/tests/test_v2_cache_us_plan_pins.py new file mode 100644 index 000000000..e6ad778c3 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_v2_cache_us_plan_pins.py @@ -0,0 +1,453 @@ +"""Pins of the v2 report app's US cache plan, and of the keys and store paths it uses. + +Every expected value below is what ``main`` produced on 2026-11-25 (commit +6865dc2c) for the fixed inputs in ``fixtures.v2_cache_us_inputs``. Moving the +v2 cache (``stage12_cache``) onto the level handlers must leave each value +unchanged: the same years, year files, state files and region-group +baselines in the same order, with the same ``stage12-ds1``, ``stage12-sds1`` +and ``stage12-bl1`` keys and store paths. + +The image folders a plan entry names are pinned apart, in ``TestImageFolders``: +they moved to the handlers' ``prebuilt/…`` folders on 2026-11-27, in a commit +of their own. On that date the years and the state targets also began to be +read through the handlers, as ``main``'s ``PRECOMPUTE_YEARS`` and +``state_dataset_targets`` were deleted; their values are unchanged. Any other +deliberate change to a key, path or digest updates its pinned value in a +commit of its own that says why. + +Long lists are pinned by the SHA-256 of their canonical JSON (``_digest_of``) +plus their first entries in full, so a failure names the section that moved. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pytest +from fixtures.v2_cache_us_inputs import ( + STATE_LEVEL_DATASET, + US_STATE_FIPS, + enable_fixed_spm, + install_v2_cache_us_inputs, +) +from policyengine_simulation_executor.stage12_cache import keys, precompute +from policyengine_simulation_executor.stage12_cache.models import CacheBundleIdentity +from policyengine_simulation_executor.stage12_runtime.partition import ( + US_REGION_GROUPS as PARTITION_GROUPS, +) + +if TYPE_CHECKING: + from policyengine_simulation_executor.stage12_cache.models import PrecomputePlan + +BUCKET = "bucket-pins" +PLANNED_YEARS = [2026, 2027, 2025] +FIXED_SPM_SELECTION = { + "forecast_content_sha256": "a" * 64, + "scenario": "ce_trend", + "geography_kind": "national", + "geography_id": None, + "county_vintage": "2020", + "as_of": None, +} +SPM_SUFFIX = "-spm-7396bf5f4876c42bb6cba0f9533478098edc0861cc3657bd0d60f88dbb26ac39" +# The output plan a report run's worker stores a current-law US run under. +OUTPUT_PLAN_SHA256 = "baeec697c2c3b88895014ccd3cdb62fd44b3c3c8a16e77658820f6fcf03a0c04" + +# The household-balanced partition of segmented national runs, in run order. +US_REGION_GROUPS = [ + ["state/hi", "state/ia", "state/wi"], + ["state/ak", "state/ga", "state/la"], + ["state/al", "state/co", "state/ri"], + ["state/mn", "state/mo", "state/nh"], + ["state/az", "state/de", "state/me"], + ["state/ny", "state/wv"], + ["state/in", "state/ky", "state/md"], + ["state/mt", "state/sc", "state/wa"], + ["state/id", "state/or", "state/tn"], + ["state/ar", "state/nc", "state/nd"], + ["state/dc", "state/ks", "state/mi"], + ["state/ct", "state/oh", "state/vt"], + ["state/nv", "state/va", "state/wy"], + ["state/pa", "state/ut"], + ["state/sd", "state/tx"], + ["state/ca"], + ["state/il", "state/ms"], + ["state/fl", "state/nm"], + ["state/ne", "state/nj"], + ["state/ma", "state/ok"], +] + + +def _digest_of(entries: list) -> str: + return keys.canonical_digest({"entries": entries}) + + +def _dataset_rows(plan: PrecomputePlan) -> list[list]: + return [ + [entry.year, entry.digest, entry.path, entry.filename] + for entry in plan.datasets + ] + + +def _baseline_rows(plan: PrecomputePlan) -> list[list]: + return [ + [ + entry.year, + entry.segment_index, + list(entry.region_codes), + entry.digest, + entry.path, + entry.filename, + entry.simulation_id, + entry.output_plan_sha256, + ] + for entry in plan.baselines + ] + + +def _state_dataset_rows(plan: PrecomputePlan) -> list[list]: + """Each state file's identity, without the image folder it lands in.""" + return [ + [ + entry.year, + entry.state_code, + entry.region, + entry.dataset, + entry.digest, + entry.path, + entry.filename, + ] + for entry in plan.state_datasets + ] + + +@pytest.fixture(scope="module") +def us_inputs(): + with pytest.MonkeyPatch.context() as module_patch: + inputs = install_v2_cache_us_inputs(module_patch) + enable_fixed_spm(inputs) + yield inputs + + +@pytest.fixture(scope="module") +def us_plan(us_inputs): + return precompute.plan_artifacts_impl(BUCKET) + + +class TestUsPlan: + """The plan ``plan_artifacts_impl`` makes for a bundle with an SPM capability.""" + + def test_plans_the_three_years_in_submission_order(self, us_plan): + from policyengine_simulation_executor.stage12_cache.levels import ( + prebuilt_for, + ) + + assert list(us_plan.years) == PLANNED_YEARS + assert list(prebuilt_for("us").years) == PLANNED_YEARS + + def test_plans_the_default_dataset_year_file_for_each_year(self, us_plan): + assert _dataset_rows(us_plan) == [ + [ + 2026, + "e4a6dacf5954ccac03abfbcba50c44a3a156d351ed25e3214ae20d7e093e0dac", + "datasets/us/e4a6dacf5954ccac03abfbcba50c44a3a156d351ed25e3214ae20d7e093e0dac/populace_us_2024_year_2026.h5", + "populace_us_2024_year_2026.h5", + ], + [ + 2027, + "d7bc670e1f294b2a29edc94c2ba5e5c1faf85fedcc6d2330b2b326da3198261f", + "datasets/us/d7bc670e1f294b2a29edc94c2ba5e5c1faf85fedcc6d2330b2b326da3198261f/populace_us_2024_year_2027.h5", + "populace_us_2024_year_2027.h5", + ], + [ + 2025, + "76d63c9ad2b18986cf3bc23f7e21b73ccea3f90390757c69f08b0a9deb135a1a", + "datasets/us/76d63c9ad2b18986cf3bc23f7e21b73ccea3f90390757c69f08b0a9deb135a1a/populace_us_2024_year_2025.h5", + "populace_us_2024_year_2025.h5", + ], + ] + + def test_plans_one_baseline_per_year_and_region_group_in_order(self, us_plan): + assert [list(group) for group in PARTITION_GROUPS] == US_REGION_GROUPS + assert [ + [entry.year, entry.segment_index, list(entry.region_codes)] + for entry in us_plan.baselines + ] == [ + [year, index, group] + for year in PLANNED_YEARS + for index, group in enumerate(US_REGION_GROUPS) + ] + + def test_every_baseline_is_keyed_on_the_stored_output_plan(self, us_plan): + assert {entry.output_plan_sha256 for entry in us_plan.baselines} == { + OUTPUT_PLAN_SHA256 + } + + def test_pins_every_baseline_identity(self, us_plan): + rows = _baseline_rows(us_plan) + assert rows[0] == [ + 2026, + 0, + ["state/hi", "state/ia", "state/wi"], + "88acdd57481da78416475d199be783bb06732a81094dd3658518ad028e0502bd", + "baselines/us/88acdd57481da78416475d199be783bb06732a81094dd3658518ad028e0502bd/" + f"stage12-bl1-88acdd57481da784{SPM_SUFFIX}.h5", + f"stage12-bl1-88acdd57481da784{SPM_SUFFIX}.h5", + "stage12-bl1-88acdd57481da784", + OUTPUT_PLAN_SHA256, + ] + assert rows[-1] == [ + 2025, + 19, + ["state/ma", "state/ok"], + "f4135fce4cc7e0c580912d3d3d2614bd425276611045a8d4c2dd2df18487f2a1", + "baselines/us/f4135fce4cc7e0c580912d3d3d2614bd425276611045a8d4c2dd2df18487f2a1/" + f"stage12-bl1-f4135fce4cc7e0c5{SPM_SUFFIX}.h5", + f"stage12-bl1-f4135fce4cc7e0c5{SPM_SUFFIX}.h5", + "stage12-bl1-f4135fce4cc7e0c5", + OUTPUT_PLAN_SHA256, + ] + assert _digest_of(rows) == ( + "e4975f0601fe92ff5b418fd4f9d0a9e625c5c3b2ae35c4570daf6ea554c0d1e4" + ) + + def test_plans_a_state_level_year_file_per_year_and_state(self, us_plan): + state_codes = sorted(state_code for state_code, _fips in US_STATE_FIPS) + assert len(us_plan.state_datasets) == 153 + assert [[entry.year, entry.state_code] for entry in us_plan.state_datasets] == [ + [year, state_code] for year in PLANNED_YEARS for state_code in state_codes + ] + for entry in us_plan.state_datasets: + assert entry.region == f"state/{entry.state_code.lower()}" + assert entry.dataset == STATE_LEVEL_DATASET + assert entry.filename == f"{STATE_LEVEL_DATASET}_year_{entry.year}.h5" + + def test_pins_every_state_level_year_file_identity(self, us_plan): + rows = _state_dataset_rows(us_plan) + assert rows[0] == [ + 2026, + "AK", + "state/ak", + STATE_LEVEL_DATASET, + "be2d28af31a275139be0a74a47d02582ca4f6cbfa10d956c3f3c4f227113bbbc", + "state-datasets/us/be2d28af31a275139be0a74a47d02582ca4f6cbfa10d956c3f3c4f227113bbbc/" + f"{STATE_LEVEL_DATASET}_year_2026.h5", + f"{STATE_LEVEL_DATASET}_year_2026.h5", + ] + assert _digest_of(rows) == ( + "e3184033236f38090b3b2d0de6aaa115a10647795bd8ea5e44d16998f2da84aa" + ) + + def test_records_the_installed_bundle_and_partition(self, us_plan): + assert us_plan.bundle == CacheBundleIdentity( + bundle_manifest_sha256="b" * 64, + policyengine_version="6.20.0", + core_package_version="3.33.3", + country_package_version="2.2.2", + data_package_version="1.4.0", + data_artifact_revision="rev-default", + default_dataset="populace_us_2024", + ) + assert us_plan.partition_sha256 == ( + "25f8ed5bbcbe25592433b8bda46d73a4597f960f79ae8058f4eef33ed1e0e615" + ) + assert us_plan.determinism_verified is False + assert us_plan.schema_version == 1 + + def test_names_the_determinism_record_by_the_planned_baselines(self, us_plan): + assert precompute.determinism_record(us_plan.baselines) == { + "schema": "stage12-dv1", + "baselines": [entry.digest for entry in us_plan.baselines], + } + assert precompute.determinism_record_path(us_plan.baselines) == ( + "determinism/us/" + "63f3756f4db271f26d4ed34ac49fb10609e00b05f2630b6e7cd7acc24f68a2aa.json" + ) + + def test_selects_every_entry_of_a_cold_plan_in_plan_order(self, us_plan): + work = precompute.select_work(us_plan) + + assert work.datasets == us_plan.datasets + assert work.baselines == us_plan.baselines + assert work.state_datasets == us_plan.state_datasets + + +class TestStateTargets: + """The US states whose requests load a non-default dataset.""" + + def test_targets_every_state_by_code_with_its_row_filter(self, us_inputs): + from policyengine_simulation_executor.stage12_cache.levels import ( + DatasetLevel, + prebuilt_for, + ) + + handler = prebuilt_for("us").handlers[DatasetLevel.STATE] + targets = handler.year_file_targets(2026) + + assert [ + [ + target.subset.region, + target.subset.code, + target.subset.value, + target.subset.variable, + target.dataset, + ] + for target in targets + ] == [ + [ + f"state/{state_code.lower()}", + state_code, + state_fips, + "state_fips", + STATE_LEVEL_DATASET, + ] + for state_code, state_fips in sorted(US_STATE_FIPS) + ] + assert all(target.subset.scoping_strategy is not None for target in targets) + + +def test_a_plan_marks_what_the_bucket_already_holds(monkeypatch): + """Each entry records its own presence; a stored record marks the plan verified.""" + inputs = install_v2_cache_us_inputs(monkeypatch) + enable_fixed_spm(inputs) + cold = precompute.plan_artifacts_impl(BUCKET) + stored_paths = [ + cold.datasets[1].path, + cold.baselines[21].path, + cold.state_datasets[100].path, + precompute.determinism_record_path(cold.baselines), + ] + for path in stored_paths: + inputs.cache_bucket.store(path, b"stored") + + warm = precompute.plan_artifacts_impl(BUCKET) + work = precompute.select_work(warm) + + assert [entry.exists for entry in warm.datasets] == [False, True, False] + assert [index for index, entry in enumerate(warm.baselines) if entry.exists] == [21] + assert [ + index for index, entry in enumerate(warm.state_datasets) if entry.exists + ] == [100] + assert warm.determinism_verified is True + assert len(work.datasets) == 2 + assert cold.baselines[21] not in work.baselines + assert len(work.baselines) == 59 + assert len(work.state_datasets) == 152 + + +class TestKeys: + """The ``stage12-ds1``, ``stage12-sds1`` and ``stage12-bl1`` keys and paths.""" + + def test_schema_labels(self): + assert keys.DATASET_SCHEMA == "stage12-ds1" + assert keys.STATE_DATASET_SCHEMA == "stage12-sds1" + assert keys.BASELINE_SCHEMA == "stage12-bl1" + assert keys.CURRENT_LAW_POLICY == "current-law" + + def test_year_file_key(self, us_inputs, us_plan): + identity = keys.collect_dataset_identity( + us_inputs.stage12_bundle, country="us", year=2026 + ) + + assert identity.payload == { + "schema": "stage12-ds1", + "country": "us", + "dataset": "populace_us_2024", + "year": 2026, + "source_sha256": "1" * 64, + "data_artifact_revision": "rev-default", + "data_package_version": "1.4.0", + "country_package_version": "2.2.2", + "core_package_version": "3.33.3", + "policyengine_version": "6.20.0", + "bundle_manifest_sha256": "b" * 64, + } + assert identity.digest == us_plan.datasets[0].digest + assert identity.store_path == ( + f"datasets/us/{identity.digest}/populace_us_2024_year_2026.h5" + ) + + def test_state_file_key(self, us_inputs): + identity = keys.collect_state_dataset_identity( + us_inputs.stage12_bundle, + country="us", + year=2026, + dataset=STATE_LEVEL_DATASET, + state_code="ca", + state_fips=6, + filter_variable="state_fips", + ) + + assert identity.payload == { + "schema": "stage12-sds1", + "country": "us", + "dataset": STATE_LEVEL_DATASET, + "year": 2026, + "source_sha256": "2" * 64, + "data_artifact_revision": "rev-local", + "data_package_version": "1.4.0", + "country_package_version": "2.2.2", + "core_package_version": "3.33.3", + "policyengine_version": "6.20.0", + "bundle_manifest_sha256": "b" * 64, + "state_code": "CA", + "state_fips": 6, + "filter_variable": "state_fips", + } + assert identity.digest == ( + "b22f793c5604bf27d05e39be7d37ffab7d7142c908106241889ddcdc2ac5a83e" + ) + assert identity.store_path == ( + f"state-datasets/us/{identity.digest}/{STATE_LEVEL_DATASET}_year_2026.h5" + ) + + def test_region_group_baseline_key(self, us_inputs, us_plan): + from policyengine_simulation_executor.stage12_cache import precompute_planning + + _simulation, identity = precompute_planning.baseline_identity( + 2026, tuple(US_REGION_GROUPS[0]) + ) + + assert identity.payload == { + "schema": "stage12-bl1", + "country": "us", + "dataset_digest": us_plan.datasets[0].digest, + "region_codes": ["state/hi", "state/ia", "state/wi"], + "scope_key": ( + "region_group:row_filter:state_fips=15" + "|row_filter:state_fips=19|row_filter:state_fips=55" + ), + "output_plan_sha256": OUTPUT_PLAN_SHA256, + "spm": FIXED_SPM_SELECTION, + "policy": "current-law", + } + assert identity.digest == us_plan.baselines[0].digest + assert identity.simulation_id == "stage12-bl1-88acdd57481da784" + # .py names a US baseline's file by its ID and its SPM selection. + assert identity.storage_id == f"stage12-bl1-88acdd57481da784{SPM_SUFFIX}" + assert f"-spm-{keys.canonical_digest(FIXED_SPM_SELECTION)}" == SPM_SUFFIX + assert identity.store_path == ( + f"baselines/us/{identity.digest}/{identity.storage_id}.h5" + ) + + +class TestImageFolders: + """Where each planned file sits in the worker image. + + Until 2026-11-27 (``main`` at 6865dc2c) a state file sat in + ``state-datasets//`` and year files and baselines named no + folder: they sat in the image data folder itself. Every file now sits in + its handler's ``prebuilt///`` folder, + and a baseline beside the year file it was computed on. + """ + + def test_state_files_land_in_their_state_folders(self, us_plan): + assert [entry.folder for entry in us_plan.state_datasets] == [ + f"prebuilt/us/{STATE_LEVEL_DATASET}/{entry.state_code}" + for entry in us_plan.state_datasets + ] + + def test_year_files_and_baselines_land_in_the_national_folder(self, us_plan): + assert {entry.folder for entry in (*us_plan.datasets, *us_plan.baselines)} == { + "prebuilt/us/populace_us_2024/all" + }