diff --git a/changelog.d/prebuilt-level-handlers.changed.md b/changelog.d/prebuilt-level-handlers.changed.md new file mode 100644 index 000000000..7721108c1 --- /dev/null +++ b/changelog.d/prebuilt-level-handlers.changed.md @@ -0,0 +1 @@ +The run_simulation app's precomputed year files and current-law baselines are now planned, built and looked up through handlers that take a country and a dataset level (national, group of states, state, district, UK nation, UK local area). US results and the set of US files built are unchanged, but the files have new keys (`yf1` year files, `bl3` baselines, including the policyengine-core version), sit under `prebuilt////` in the image, and are listed in one `mf2` manifest per country, whose recorded SHA-256 and size the image build checks for each file. The precompute takes `--country` (default `us`). The first release with this change recomputes every US file once, as a .py version update does. diff --git a/projects/policyengine-simulation-executor/README.md b/projects/policyengine-simulation-executor/README.md index 6e2e21a41..8a8d61da6 100644 --- a/projects/policyengine-simulation-executor/README.md +++ b/projects/policyengine-simulation-executor/README.md @@ -276,14 +276,17 @@ an operator repairs them by hand. ## Baseline artifact pipeline (precompute → store → image fetch) -The precompute app fills a content-addressed GCS store with single-year US -datasets (2026, 2027, 2025), the 20 per-cohort national baseline -simulations per year, and per-state datasets: for each state region whose -requests load a dataset other than the bundle default (the ACS-local -dataset since policyengine 6.7), that dataset's year file filtered to the -state's households, one file per state and year. The deploy bakes them into -the image, and the runtime loads baselines instead of computing them. Library logic lives in -`src/policyengine_simulation_executor/precompute.py` (keys: +The precompute app fills a content-addressed GCS store for one country +(`--country`, default `us`), planned by that country's level handlers +(`src/policyengine_simulation_executor/stage12_cache/levels*.py`). For the +US it builds the default dataset's year file for 2026, 2027 and 2025, the +current-law baseline of each of the 20 groups of states per year, and state +year files: for each state region whose requests load a dataset other than +the bundle default (the ACS-local dataset since policyengine 6.7), that +dataset's year file filtered to the state's households, one file per state +and year. The UK builds nothing yet. The deploy copies the files into the +image, and the runtime loads them instead of computing them. Library logic +lives in `src/policyengine_simulation_executor/precompute.py` (keys: `artifact_keys.py`, store client: `artifact_store.py`); the Modal app (`src/modal/precompute_app.py`) is plumbing only. @@ -300,17 +303,20 @@ Manual runs remain valid for ad-hoc warming: The deploy job consumes the precompute job's manifest digest: `src/modal/app.py` resolves the manifest from GCS on the deploying machine and passes its content as the `fetch_artifacts` image layer's -args (`src/modal/_image_setup.py`). The layer downloads the full -artifact set into `POLICYENGINE_DATA_FOLDER`: about 430 MB of national -datasets and baselines, plus several GB of per-state datasets, each placed -in `state-datasets///` under the year file's own name. It -sits between -the version env and the source mount — do not reorder. Because the -manifest is content-addressed and rides in the layer args, Modal's layer -cache busts exactly when the artifact set changes and never otherwise; -there is no force-rebuild ritual. A freshness gate inside the layer -refuses to bake artifacts computed for versions other than the image's -own, and any missing store object fails the build loudly. +args (`src/modal/_image_setup.py`); each country with a manifest gets one +such layer, US only today. The layer downloads the country's full file set +under `POLICYENGINE_DATA_FOLDER`, each file in +`prebuilt////` under its own name: for +the US, about 430 MB of national year files and group-of-states baselines in +`prebuilt/us//all/`, plus several GB of state year files in +`prebuilt/us///`. It sits between the version +env and the source mount — do not reorder. Because the manifest is +content-addressed and rides in the layer args, Modal's layer cache rebuilds +the layer exactly when the file set changes and never otherwise; there is no +forced rebuild to run. The layer refuses a manifest of another schema or one +computed for package versions other than the image's own, checks each +downloaded file's SHA-256 and size against the manifest, refuses a file +already in the image, and fails the build on any missing store object. After the health check, each deploy leg writes a `deployed/.json` marker (`deployed/beta.json`, @@ -343,20 +349,24 @@ Operational notes: precompute — deletion turns the key back into an ordinary miss, and the next deploy's precompute job recomputes it before the deploy leg builds the image. -- A determinism gate runs whenever baselines were computed: one cohort's - uploaded artifact is compared frame-by-frame against an independent - fresh run. The run fails if they differ. +- A determinism check runs whenever baselines were computed: for each + level that computed any, one uploaded baseline is compared column by + column against an independent fresh run. The run fails if they differ. - The final stdout line `MANIFEST_DIGEST=` names the published deploy manifest; the deploy pipeline consumes exactly that line. - Only pure default requests read the baked folder: any request naming an explicit `data` dataset or pinning a `data_version` bypasses it (see `_load_dataset` in `simulation_runtime.py`). -- A US state or congressional-district request whose region loads a - non-default dataset reads its state's baked file when the image has one for - the requested year and .py's year-file reuse checks accept it (see - `state_datasets.baked_state_data_folder`). Otherwise it prepares the full - regional dataset during the request, as before. The run records which in - its `dataset_source` attribute: `baked_state` or `on_demand`. +- Every run whose region has a dataset level (US national, group of states, + state or congressional district) reads its year file from its prebuilt + folder when the image has one for the requested year and .py's year-file + reuse checks accept it (see `prebuilt_dataset_folder` in + `stage12_cache/levels.py`). A district reads its state's file. Otherwise + the run uses the folder it used before the prebuilt files: the data + folder's root for the default dataset, or a temporary folder where it + prepares the full state-level dataset. A run on a non-default dataset + records which in its `dataset_source` attribute: `baked_state` or + `on_demand`. - Known residual, inherited rather than introduced: a data re-release under the same revision labels leaves the cached bundle-install layer — and therefore the receipt every artifact key derives from — unchanged. diff --git a/projects/policyengine-simulation-executor/fixtures/identity_stubs.py b/projects/policyengine-simulation-executor/fixtures/identity_stubs.py index bbd7b7f8c..23d31b01c 100644 --- a/projects/policyengine-simulation-executor/fixtures/identity_stubs.py +++ b/projects/policyengine-simulation-executor/fixtures/identity_stubs.py @@ -1,16 +1,17 @@ -"""Shared stubs for ``collect_dataset_identity``'s input seams. +"""Shared stubs for the input seams of ``artifact_keys.year_file_identity``. -The key-discipline tests (test_artifact_keys) and the writer==reader -contract tests (test_precompute) must stub the SAME seam list — -``release_bundle.get_country_release_bundle``, -``release_bundle._receipt_dataset``, +The key tests (test_prebuilt_identities, test_artifact_keys) and the +writer==reader contract tests (test_prebuilt_plan) must stub the SAME seam +list — ``release_bundle.get_country_release_bundle``, ``manifest.resolve_dataset_reference``, ``manifest.dataset_logical_name``, -``manifest.get_release_manifest``, ``spm.runtime_spm_capability`` — or one -suite silently tests a stale list when identity collection grows a seam. -This is that list's one home. +``manifest.get_release_manifest``, ``spm.runtime_spm_capability``, +``artifact_keys._installed_package_versions`` — or one suite silently tests +a stale list when identity collection grows a seam. This is that list's one +home. ``release_bundle._receipt_dataset`` is stubbed too, for the bundle +helpers that read the install receipt; no identity reads it. -The SPM capability is a seam because ``collect_dataset_identity`` resolves -the installed bundle's SPM selection into the dataset identity. The default +The SPM capability is a seam because ``year_file_identity`` resolves the +installed bundle's SPM selection into the year-file identity. The default stub has no capability so fixed identifier tests remain tied to their synthetic inputs instead of whichever PolicyEngine release is installed. """ @@ -31,7 +32,8 @@ def install_identity_stubs(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: SPM-capability state, plus a handle to the installed capability resolver for tests that intentionally exercise the installed release. The bundle has one non-default dataset, ``populace_cps_local``, for the per-state - dataset identities. + dataset identities. ``core_version`` is the policyengine-core version the + installed-package stub reports. """ # This module imports ``get_release_manifest`` by value while constructing # country models. Import it before replacing the manifest module's function @@ -62,6 +64,7 @@ def install_identity_stubs(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: }, ) release_datasets = { + "populace_cps": SimpleNamespace(sha256="d00dfeed" * 8), "populace_cps_local": SimpleNamespace(sha256="c0ffee00" * 8), } receipt_entry = { @@ -74,6 +77,7 @@ def install_identity_stubs(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: receipt_entry=receipt_entry, release_datasets=release_datasets, spm_capability=None, + core_version="3.33.3", ) monkeypatch.setattr( @@ -101,6 +105,27 @@ def install_identity_stubs(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: ), ) + from policyengine_simulation_executor import ( # noqa: PLC0415 # patch target, imported when the stubs are installed + artifact_keys, + ) + + def installed_package_versions(country: str) -> dict[str, str]: + country_bundle = release_bundle.get_country_release_bundle(country) + return { + "policyengine": country_bundle.policyengine_version, + "policyengine-core": state.core_version, + f"policyengine-{country.lower()}": country_bundle.model_version, + } + + # Year-file keys name the installed packages; the stub pins them to the + # bundle's versions and a fixed policyengine-core version. + monkeypatch.setattr( + artifact_keys, + "_installed_package_versions", + installed_package_versions, + raising=False, + ) + from policyengine_simulation_executor import ( spm as executor_spm, ) diff --git a/projects/policyengine-simulation-executor/fixtures/us_prebuilt_inputs.py b/projects/policyengine-simulation-executor/fixtures/us_prebuilt_inputs.py new file mode 100644 index 000000000..18279e8b8 --- /dev/null +++ b/projects/policyengine-simulation-executor/fixtures/us_prebuilt_inputs.py @@ -0,0 +1,287 @@ +"""Fixed inputs for the tests that pin what the US precompute produces today. + +The precompute, the deploy manifest and the runtime lookup read the release +bundle, the bundle receipt, .py's release manifest, the SPM capability, the US +country model's regions and the artifact store. ``install_us_prebuilt_inputs`` +replaces each with a fixed stand-in, so the plan, the manifest and the lookup +outcomes are pure functions of the values below and can be compared with +recorded values exactly: + +* the identity seams use ``identity_stubs``' synthetic version-set, with a + default dataset ``populace_cps`` and a state-level dataset + ``populace_cps_local``; +* 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 and loading the + state-level dataset, as today's US model's states are; +* the artifact store is a fake GCS client that records every upload. + +The national partition is NOT replaced: plans use the real 20 region groups. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +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_executor import ( + artifact_store, + region_resolution, + release_bundle, +) +from policyengine_simulation_executor import simulation_runtime as runtime + +from fixtures.identity_stubs import install_identity_stubs + +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_cps" +STATE_LEVEL_DATASET = "populace_cps_local" +UK_DEFAULT_DATASET = "enhanced_frs" + + +@dataclass +class RecordingGcsClient: + """A fake GCS client: ``objects`` maps paths to bytes, ``uploads`` records writes. + + Each entry of ``uploads`` is ``(bucket, path, data, keyword arguments)``. + ``object_metadata`` holds each object's custom metadata, as set on the + blob before its upload. A write with ``if_generation_match=0`` to an + existing path leaves the object unchanged and raises + ``PreconditionFailed``, as GCS does. + """ + + objects: dict[str, bytes] = field(default_factory=dict) + object_metadata: dict[str, dict[str, str]] = field(default_factory=dict) + uploads: list[tuple[str, str, bytes, dict[str, Any]]] = field(default_factory=list) + + def bucket(self, bucket_name: str) -> SimpleNamespace: + """Return a bucket handle whose blobs read and write ``objects``.""" + return SimpleNamespace( + blob=lambda path: _RecordingBlob(self, bucket_name, path) + ) + + +@dataclass +class _RecordingBlob: + client: RecordingGcsClient + bucket_name: str + path: str + metadata: dict[str, str] | None = None + + def exists(self) -> bool: + return self.path in self.client.objects + + def reload(self) -> None: + if self.path not in self.client.objects: + raise NotFound(self.path) + self.metadata = dict(self.client.object_metadata.get(self.path, {})) or None + + def _write(self, payload: bytes, keyword_arguments: dict[str, Any]) -> None: + self.client.uploads.append( + (self.bucket_name, self.path, payload, dict(keyword_arguments)) + ) + if ( + keyword_arguments.get("if_generation_match") == 0 + and self.path in self.client.objects + ): + msg = f"object exists: {self.path}" + raise PreconditionFailed(msg) + self.client.objects[self.path] = payload + self.client.object_metadata[self.path] = dict(self.metadata or {}) + + def upload_from_string(self, data: str | bytes, **keyword_arguments: Any) -> None: # noqa: ANN401 # mirrors google.cloud.storage.Blob's keyword arguments + payload = data.encode() if isinstance(data, str) else data + self._write(payload, keyword_arguments) + + def upload_from_filename(self, filename: str, **keyword_arguments: Any) -> None: # noqa: ANN401 # mirrors google.cloud.storage.Blob's keyword arguments + self._write(Path(filename).read_bytes(), keyword_arguments) + + def download_to_filename(self, filename: str) -> None: + if self.path not in self.client.objects: + raise NotFound(self.path) + Path(filename).write_bytes(self.client.objects[self.path]) + + def download_as_bytes(self) -> bytes: + if self.path not in self.client.objects: + raise NotFound(self.path) + return self.client.objects[self.path] + + +def us_state_regions(dataset_uri: str) -> list[SimpleNamespace]: + """Return stand-ins for the US model's 51 state regions, loading ``dataset_uri``.""" + return [ + SimpleNamespace( + code=f"state/{state_code.lower()}", + label=state_code, + dataset_path=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 _uk_bundle() -> SimpleNamespace: + return SimpleNamespace( + country="uk", + policyengine_version="4.22.0", + model_version="2.0.0", + data_version="3.4.5", + data_package_version="3.4.5", + data_artifact_revision="rev-uk", + default_dataset=UK_DEFAULT_DATASET, + dataset_uris={ + UK_DEFAULT_DATASET: "hf://org/uk-repo/enhanced_frs.h5@rev-uk", + }, + ) + + +def install_us_prebuilt_inputs( + monkeypatch: pytest.MonkeyPatch, +) -> SimpleNamespace: + """Replace every input of the US precompute and lookup with a fixed stand-in. + + Returns the identity stub state (``identity``, whose ``spm_capability`` a + test may set), the US and UK bundles, the 51 state regions, the stand-in + US country module (``us_module``, to which a test may add + ``ensure_datasets``), and the fake GCS client every ``ArtifactStore`` + built without a client uses. + """ + identity = install_identity_stubs(monkeypatch) + us_bundle = identity.bundle + # Region resolution re-pins a region's dataset path with these revisions. + us_bundle.data_package_version = us_bundle.data_version + uk_bundle = _uk_bundle() + + def country_bundle(country: str) -> SimpleNamespace: + return uk_bundle if country.lower() == "uk" else us_bundle + + for module in (release_bundle, runtime, region_resolution): + monkeypatch.setattr(module, "get_country_release_bundle", country_bundle) + + regions = us_state_regions(us_bundle.dataset_uris[STATE_LEVEL_DATASET]) + regions_by_code = {region.code: region for region in regions} + us_module = SimpleNamespace( + model=SimpleNamespace( + get_region=regions_by_code.get, + region_registry=SimpleNamespace( + get_by_type=lambda region_type: ( + list(regions) if region_type == "state" else [] + ) + ), + ) + ) + monkeypatch.setattr(runtime, "_country_module", lambda _country: us_module) + + gcs_client = RecordingGcsClient() + monkeypatch.setattr(artifact_store, "_default_client", lambda: gcs_client) + return SimpleNamespace( + identity=identity, + us_bundle=us_bundle, + uk_bundle=uk_bundle, + regions=regions, + us_module=us_module, + gcs_client=gcs_client, + ) + + +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, + } + } + ) + + +def enable_fixed_spm_capability( + monkeypatch: pytest.MonkeyPatch, inputs: SimpleNamespace +) -> None: + """Make the US bundle offer ``fixed_spm_capability`` and skip forecast checks. + + ``_prevalidate_selection`` reads the installed forecast to prove a + selection can be measured; the synthetic hash names no real forecast. + """ + from policyengine_simulation_executor import spm as executor_spm + + inputs.identity.spm_capability = fixed_spm_capability() + monkeypatch.setattr( + executor_spm, + "_prevalidate_selection", + lambda _selection_json, _start_year, _window_size: None, + ) diff --git a/projects/policyengine-simulation-executor/fixtures/wrapper_spm.py b/projects/policyengine-simulation-executor/fixtures/wrapper_spm.py index b5643c223..965c2f907 100644 --- a/projects/policyengine-simulation-executor/fixtures/wrapper_spm.py +++ b/projects/policyengine-simulation-executor/fixtures/wrapper_spm.py @@ -1,6 +1,6 @@ """PolicyEngine 6's SPM-aware ``storage_id`` expression for test doubles. -Precompute plans a store path from ``BaselineArtifactIdentity.storage_id`` +Precompute plans a store path from ``BaselineIdentity.storage_id`` and the in-container worker aborts when the wrapper's value disagrees, so the two derivations have to be one identifier reached down two paths. diff --git a/projects/policyengine-simulation-executor/src/modal/_image_setup.py b/projects/policyengine-simulation-executor/src/modal/_image_setup.py index c1de4b183..a4ca3e8e2 100644 --- a/projects/policyengine-simulation-executor/src/modal/_image_setup.py +++ b/projects/policyengine-simulation-executor/src/modal/_image_setup.py @@ -12,6 +12,7 @@ # wherever the app loads; any other package loads only inside the function # that needs it. Annotation-only imports sit under TYPE_CHECKING, so the # annotations that use them are quoted. +import hashlib import json import logging import os @@ -25,13 +26,20 @@ from google.cloud import storage +# The manifest schema this step reads (precompute_models.MANIFEST_SCHEMA; +# this module cannot import it). +_MANIFEST_SCHEMA = "mf2" +_PREBUILT_DIRECTORY = "prebuilt" +_HASH_CHUNK_BYTES = 1024 * 1024 + + def fetch_artifacts( bucket: str, manifest: "Mapping[str, Any] | None", *, client: "storage.Client | None" = None, ) -> None: - """Download every manifest-listed artifact into the image data folder. + """Download every artifact one country's manifest lists into its prebuilt folder. Runs as an image-build layer between ``.env(VERSION_ENV)`` and ``add_local_python_source``, so it must stay self-contained (no @@ -68,21 +76,33 @@ def fetch_artifacts( ) data_folder.mkdir(parents=True, exist_ok=True) _download_manifest_artifacts( - client.bucket(bucket), manifest["artifacts"], data_folder + client.bucket(bucket), + manifest["artifacts"], + data_folder, + country=str(manifest["country"]), ) def _require_manifest_matches_image(manifest: "Mapping[str, Any]") -> None: - """Freshness gate: refuse artifacts computed for another version-set. + """Freshness check: refuse artifacts computed for another version-set. - The image's policyengine and country model versions must equal the + The manifest must have the schema this step reads, and the image's + policyengine, policyengine-core and country model versions must equal the manifest receipt's, and so must the installed data version when the bundle receipt records one. """ + if manifest.get("schema") != _MANIFEST_SCHEMA: + msg = ( + f"The artifact manifest has schema {manifest.get('schema')!r}; this " + f"image reads {_MANIFEST_SCHEMA!r}. Re-run the precompute for the " + "current code." + ) + raise RuntimeError(msg) country = str(manifest["country"]) receipt = manifest["receipt"] expected_env = { "POLICYENGINE_VERSION": receipt["policyengine_version"], + "POLICYENGINE_CORE_VERSION": receipt["policyengine_core_version"], f"POLICYENGINE_{country.upper()}_VERSION": receipt["model_version"], } for env_var, manifest_value in expected_env.items(): @@ -178,13 +198,15 @@ def _service_account_credentials(blob: str) -> "dict[str, Any]": } -def _artifact_target(data_folder: "Path", artifact: "Mapping[str, Any]") -> "Path": - """Return where an artifact lands: its ``folder`` (if any) under the data folder. +def _artifact_target( + data_folder: "Path", artifact: "Mapping[str, Any]", *, country: str +) -> "Path": + """Return where an artifact lands: its ``folder`` under the data folder. - Per-state datasets share one ``filename`` and differ by ``folder``, a - relative path such as ``state-datasets//``. Anything that - could leave the data folder, or name a different file than intended, is - refused. + Every folder sits under ``prebuilt//``, so prebuilt files never + land beside the source datasets the bundle install writes into the data + folder's root. Anything that could leave that folder, or name a different + file than intended, is refused. """ filename = artifact.get("filename") if ( @@ -196,40 +218,89 @@ def _artifact_target(data_folder: "Path", artifact: "Mapping[str, Any]") -> "Pat msg = f"Artifact {artifact.get('path')!r} has an unsafe filename {filename!r}" raise RuntimeError(msg) folder = artifact.get("folder") - if folder is None: - return data_folder / filename - parts = ( - PurePosixPath(folder).parts - if isinstance(folder, str) and folder and "\\" not in folder - else () - ) + if not isinstance(folder, str) or not folder or "\\" in folder: + msg = f"Artifact {artifact.get('path')!r} has an unsafe folder {folder!r}" + raise RuntimeError(msg) + parts = PurePosixPath(folder).parts if ( - not parts + len(parts) < 3 # noqa: PLR2004 # prebuilt, the country, and at least the dataset or PurePosixPath(folder).is_absolute() or any(part in {".", ".."} for part in parts) or "/".join(parts) != folder + or parts[:2] != (_PREBUILT_DIRECTORY, country.lower()) ): msg = f"Artifact {artifact.get('path')!r} has an unsafe folder {folder!r}" raise RuntimeError(msg) return data_folder.joinpath(*parts, filename) +def _file_sha256(path: "Path") -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + while chunk := stream.read(_HASH_CHUNK_BYTES): + digest.update(chunk) + return digest.hexdigest() + + +def _download_checked( + bucket_handle: "storage.Bucket", artifact: "Mapping[str, Any]", target: "Path" +) -> None: + """Download one artifact beside ``target`` and move it into place once checked. + + The downloaded file's size and SHA-256 must equal the manifest's, so a + failed or altered download leaves nothing at ``target``. + """ + target.parent.mkdir(parents=True, exist_ok=True) + partial = target.with_name(target.name + ".partial") + try: + bucket_handle.blob(artifact["path"]).download_to_filename(str(partial)) + if not partial.exists(): + msg = f"Downloading {artifact['path']} wrote no file for {target.name}" + raise RuntimeError(msg) + if partial.stat().st_size != artifact["size_bytes"]: + msg = ( + f"{target.name} from {artifact['path']} has {partial.stat().st_size} " + f"bytes, not the manifest's {artifact['size_bytes']}" + ) + raise RuntimeError(msg) + if _file_sha256(partial) != artifact["sha256"]: + msg = ( + f"{target.name} from {artifact['path']} does not have the " + "manifest's SHA-256" + ) + raise RuntimeError(msg) + partial.replace(target) + finally: + partial.unlink(missing_ok=True) + + def _download_manifest_artifacts( bucket_handle: "storage.Bucket", artifacts: "Sequence[Mapping[str, Any]]", data_folder: "Path", + *, + country: str, ) -> None: - """Download every artifact to its runtime location, failing on any gap. + """Download every artifact to its prebuilt folder, failing on any gap. - Every target and store object is checked before anything downloads, and - every expected file is checked after. + Every target and store object is checked before anything downloads: a + target listed twice, or already in the image (another country's step + must never replace the first's files), stops the build. Every expected + file is checked after. """ logger = logging.getLogger(__name__) - targets = [_artifact_target(data_folder, artifact) for artifact in artifacts] + targets = [ + _artifact_target(data_folder, artifact, country=country) + for artifact in artifacts + ] repeated = sorted({str(target) for target in targets if targets.count(target) > 1}) if repeated: msg = f"The manifest lists these files more than once: {repeated}" raise RuntimeError(msg) + existing = [str(target) for target in targets if target.exists()] + if existing: + msg = f"These files are already in the image: {existing}" + raise RuntimeError(msg) missing = [ artifact["path"] for artifact in artifacts @@ -244,12 +315,8 @@ def _download_manifest_artifacts( + ", ".join(missing) ) - # Unconditional downloads: a same-named stale file must never - # survive into the image, and the layer starts empty of these - # files anyway. for artifact, target in zip(artifacts, targets, strict=True): - target.parent.mkdir(parents=True, exist_ok=True) - bucket_handle.blob(artifact["path"]).download_to_filename(str(target)) + _download_checked(bucket_handle, artifact, target) logger.info("Fetched %s (%.1f MB)", target, target.stat().st_size / 1e6) absent = [str(target) for target in targets if not target.exists()] diff --git a/projects/policyengine-simulation-executor/src/modal/app.py b/projects/policyengine-simulation-executor/src/modal/app.py index d65b9798d..605410f70 100644 --- a/projects/policyengine-simulation-executor/src/modal/app.py +++ b/projects/policyengine-simulation-executor/src/modal/app.py @@ -178,8 +178,14 @@ def get_app_name(policyengine_version: str) -> str: _UV_PROJECT_DIR = str(Path(__file__).resolve().parents[2]) if modal.is_local() else "." -def _deploy_time_artifact_inputs() -> tuple[str, dict | None]: - """Resolve the artifact bucket and deploy manifest on the deploying machine. +# The deploy-time variable naming each country's precomputed manifest. Only +# the US has prebuilt files today; a country is added here when its +# precompute publishes a manifest. +MANIFEST_DIGEST_VARIABLES = {"us": "POLICYENGINE_MANIFEST_DIGEST"} + + +def _deploy_time_artifact_inputs(country: str = "us") -> tuple[str, dict | None]: + """Resolve the bucket and a country's deploy manifest on the deploying machine. The manifest content rides into the fetch layer's args, so Modal's layer cache busts exactly when the deployed artifact set changes. @@ -197,7 +203,7 @@ def _deploy_time_artifact_inputs() -> tuple[str, dict | None]: """ if not modal.is_local(): return "", None - digest = os.environ.get("POLICYENGINE_MANIFEST_DIGEST") + digest = os.environ.get(MANIFEST_DIGEST_VARIABLES[country]) bucket = os.environ.get("POLICYENGINE_ARTIFACT_BUCKET", "") if not digest: return bucket, None @@ -219,10 +225,19 @@ def _deploy_time_artifact_inputs() -> tuple[str, dict | None]: # Validate on the runner so a corrupt or foreign manifest fails the # deploy here, not mid-image-build. manifest = ArtifactManifest.model_validate(payload) + if manifest.country != country: + msg = ( + f"{MANIFEST_DIGEST_VARIABLES[country]} names a {manifest.country} " + f"manifest, not a {country} one." + ) + raise RuntimeError(msg) return store.bucket_name, manifest.canonical_payload() -_ARTIFACT_BUCKET, _DEPLOY_MANIFEST = _deploy_time_artifact_inputs() +_ARTIFACT_INPUTS = { + country: _deploy_time_artifact_inputs(country) + for country in MANIFEST_DIGEST_VARIABLES +} def build_runtime_simulation_image() -> modal.Image: @@ -268,27 +283,29 @@ def build_runtime_simulation_image() -> modal.Image: def build_base_simulation_image() -> modal.Image: - """Runtime image layers plus the artifact fetch.""" - return ( - build_runtime_simulation_image() - # Bake the precomputed store artifacts (single-year US datasets - # and cohort baselines) into the image. This layer MUST stay - # before add_local_python_source — that layer is keyed on source - # file hashes, so anything after it rebuilds on every code - # change. Its args carry the content-addressed manifest, so the - # cache busts exactly when the artifact set changes and never - # otherwise. UK requests still build datasets at request time. - .run_function( + """Runtime image layers plus one artifact download step per country, US first.""" + image = build_runtime_simulation_image() + # Bake each country's precomputed files (year files and current-law + # baselines) into the image's prebuilt folders. These layers MUST stay + # before add_local_python_source — that layer is keyed on source file + # hashes, so anything after it rebuilds on every code change. Each + # layer's args carry its country's content-addressed manifest, so its + # cache busts exactly when that country's file set changes, and a later + # country's change rebuilds only its own step and the ones after it. UK + # requests still build datasets at request time. + for country in MANIFEST_DIGEST_VARIABLES: + bucket, manifest = _ARTIFACT_INPUTS[country] + image = image.run_function( fetch_artifacts, - args=(_ARTIFACT_BUCKET, _DEPLOY_MANIFEST), + args=(bucket, manifest), secrets=[gcp_secret], cpu=2.0, memory=4096, - # The national files and baselines are about 430 MB; the - # per-state datasets (51 states for each year) add several GB. + # The US national files and baselines are about 430 MB; the + # per-state year files (51 states for each year) add several GB. timeout=3600, ) - ) + return image # Heavy image for the simulation workers. Its last layer checks that both diff --git a/projects/policyengine-simulation-executor/src/modal/precompute_app.py b/projects/policyengine-simulation-executor/src/modal/precompute_app.py index b486631be..abcfe807d 100644 --- a/projects/policyengine-simulation-executor/src/modal/precompute_app.py +++ b/projects/policyengine-simulation-executor/src/modal/precompute_app.py @@ -7,14 +7,14 @@ uv run modal run --env=staging src/modal/precompute_app.py uv run modal run --env=staging src/modal/precompute_app.py --force - -Wave 1 builds the single-year US datasets (one container per year), wave 2 -computes the 20 per-cohort national baselines per year (one container per -cohort, requesting 8 CPUs and 32 GiB). -Alongside both waves, one container per year and dataset filters the -regional dataset that state regions load into one year file per state. See -the library module for the idempotency, ``--force``, and determinism-gate -semantics. + uv run modal run --env=staging src/modal/precompute_app.py --country uk + +``--country`` (default ``us``) picks the country whose level handlers plan +the run. Each whole dataset's year file is built in one container, and each +year's subset year files of one dataset (for the US, the 51 state files) in +another; each current-law baseline is computed in its own container, +requesting 8 CPUs and 32 GiB. See the library module for the idempotency, +``--force``, and determinism-check semantics. """ from __future__ import annotations @@ -59,13 +59,13 @@ timeout=1800, secrets=_worker_secrets, ) -def plan_artifacts(bucket: str) -> dict: - """Return the dumped ``PrecomputePlan``: expected artifacts and store presence.""" +def plan_artifacts(bucket: str, country: str) -> dict: + """Return a country's dumped ``PrecomputePlan``: its files and their presence.""" from policyengine_simulation_executor.precompute import ( # noqa: PLC0415 # Modal function body: loaded in the precompute worker, not at deploy time plan_artifacts_impl, ) - return plan_artifacts_impl(bucket).model_dump() + return plan_artifacts_impl(bucket, country).model_dump() @app.function( @@ -76,21 +76,21 @@ def plan_artifacts(bucket: str) -> dict: secrets=_worker_secrets, ) def build_dataset(bucket: str, expected: dict) -> dict: - """Build and upload one single-year US dataset (wave 1). + """Build and upload one whole dataset's year file. - Raises if the dataset identity resolved in this container differs from the - planned one, so planner/worker drift cannot upload under the wrong key. + Raises if the year file's identity resolved in this container differs from + the planned one, so planner/worker drift cannot upload under the wrong key. """ from policyengine_simulation_executor.precompute import ( # noqa: PLC0415 # Modal function body: loaded in the precompute worker, not at deploy time - build_dataset_impl, + build_year_files_impl, ) from policyengine_simulation_executor.precompute_models import ( # noqa: PLC0415 # Modal function body: loaded in the precompute worker, not at deploy time - DatasetPlanEntry, + YearFilePlanEntry, ) - return build_dataset_impl( - bucket, DatasetPlanEntry.model_validate(expected) - ).model_dump() + entry = YearFilePlanEntry.model_validate(expected) + (result,) = build_year_files_impl(bucket, entry.year, [entry]) + return result.model_dump() @app.function( @@ -103,22 +103,21 @@ def build_dataset(bucket: str, expected: dict) -> dict: secrets=_worker_secrets, ) def build_state_datasets(bucket: str, year: int, expected: list[dict]) -> list[dict]: - """Build and upload one year's per-state datasets. + """Build and upload a year's subset year files of one dataset, such as the states'. - Raises if a state's key resolved in this container differs from the + Raises if a file's key resolved in this container differs from the planned one, so planner/worker drift cannot upload under the wrong key. """ from policyengine_simulation_executor.precompute import ( # noqa: PLC0415 # Modal function body: loaded in the precompute worker, not at deploy time - build_state_datasets_impl, + build_year_files_impl, ) from policyengine_simulation_executor.precompute_models import ( # noqa: PLC0415 # Modal function body: loaded in the precompute worker, not at deploy time - StateDatasetPlanEntry, + YearFilePlanEntry, ) - entries = [StateDatasetPlanEntry.model_validate(entry) for entry in expected] + entries = [YearFilePlanEntry.model_validate(entry) for entry in expected] return [ - result.model_dump() - for result in build_state_datasets_impl(bucket, year, entries) + result.model_dump() for result in build_year_files_impl(bucket, year, entries) ] @@ -130,7 +129,7 @@ def build_state_datasets(bucket: str, year: int, expected: list[dict]) -> list[d secrets=_worker_secrets, ) def compute_baseline(bucket: str, expected: dict) -> dict: - """Compute and upload one cohort's national baseline output (wave 2).""" + """Compute and upload one current-law baseline's output.""" from policyengine_simulation_executor.precompute import ( # noqa: PLC0415 # Modal function body: loaded in the precompute worker, not at deploy time compute_baseline_impl, ) @@ -151,7 +150,7 @@ def compute_baseline(bucket: str, expected: dict) -> dict: secrets=_worker_secrets, ) def verify_determinism(bucket: str, expected: dict) -> dict: - """Recompute one stored cohort baseline afresh and report columns that differ.""" + """Recompute one stored baseline afresh and report columns that differ.""" from policyengine_simulation_executor.precompute import ( # noqa: PLC0415 # Modal function body: loaded in the precompute worker, not at deploy time verify_determinism_impl, ) @@ -184,8 +183,8 @@ def publish_manifest(bucket: str, plan: dict) -> str: @app.local_entrypoint() -def main(*, force: bool = False) -> None: - """Fill the store for the installed bundle; ``--force`` recomputes stored ones.""" +def main(*, force: bool = False, country: str = "us") -> None: + """Fill the store for a country's bundle; ``--force`` recomputes stored files.""" from policyengine_simulation_executor.artifact_store import ( # noqa: PLC0415 # local entrypoint: loaded only when the precompute runs resolve_bucket_name, ) @@ -196,6 +195,7 @@ def main(*, force: bool = False) -> None: run_precompute( resolve_bucket_name(), + country=country, force=force, # Pyright types each decorated function as a modal.Function whose # `remote` and `spawn` take that function's own parameters, which it diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/artifact_keys.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/artifact_keys.py index f80b4920b..e982eee3d 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/artifact_keys.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/artifact_keys.py @@ -1,52 +1,51 @@ -"""Content-addressed identity for precomputed simulation artifacts. - -The artifact pipeline caches three artifact types in a shared store: single-year -dataset files, per-state single-year dataset files (a regional dataset's -year file filtered to one state's households) and precomputed baseline -simulation outputs. An artifact's key is -a sha256 digest over the FULL closure of inputs that determine its bytes, so -"is it cached?" and "is it stale?" are the same question, answered by key -equality: same key implies a byte-identical artifact; any input change rotates -the key and the old object simply stops being referenced (garbage collection -deletes by key with no correctness risk — a wrongly deleted artifact costs a -recompute, never a wrong answer). - -Key discipline: every field that can change an artifact's bytes must appear in -its payload. Version labels alone are not enough — a data re-release under an -unchanged version label is a known event — so the payloads also carry the -receipt's content sha256 and the certification data-build fingerprint when -available. ``None`` fields are serialized as explicit nulls, so presence and -absence are distinct identities. Bump the schema constants when the payload -shape or the artifact format itself changes. - -The baseline payload nests the dataset digest, so anything that rotates a -dataset key transitively rotates every baseline built on it. ``country`` and -``region`` are partially redundant with ``scope_key`` and the nested dataset -key; the redundancy is deliberate — for a cache key, explicitness only ever -makes identity more specific, and it means UK or single-state baselines need -no schema change later. - -This module is the single source of truth for keys, ids, and store paths: the -precompute writer, the runtime reader, and the GC planner all import it, so a -drift between writer and reader is a code-review diff here, not a silent -cache miss in production. +"""Content-addressed identity of the run_simulation app's prebuilt files. + +The precompute stores three kinds of file: year files (a dataset's single-year +file, or one subset's rows of it), current-law baselines computed on a year +file, and source files copied as they are. Each file's key is a SHA-256 digest +over every input that determines its bytes, so "is it stored?" and "is it +stale?" are the same question, answered by key equality: the same key means a +byte-identical file, and any input change rotates the key, so the old object +simply stops being referenced. + +There is one identity per kind for every dataset level: ``yf1`` year files, +``bl3`` baselines and ``sf1`` source files. A ``None`` input is written as an +explicit null, so presence and absence are distinct keys. The baseline key +nests its year file's digest, so anything that rotates a year file rotates +every baseline on it. Bump a schema label when its payload or the file +format changes. + +The level handlers (``stage12_cache.levels``) say which files to build; +this module turns their targets into keys and store paths. The precompute +writer, the runtime reader and the download step all take keys and paths from +here, so a drift between writer and reader is a review diff here, not a +silent miss in production. """ from __future__ import annotations import hashlib import json -from collections.abc import Mapping -from dataclasses import dataclass -from typing import Any +from dataclasses import dataclass, field +from importlib.metadata import version +from typing import TYPE_CHECKING, Any -DATASET_KEY_SCHEMA = "ds1" -STATE_DATASET_KEY_SCHEMA = "sds1" -BASELINE_KEY_SCHEMA = "bl1" +if TYPE_CHECKING: + from collections.abc import Mapping -# Length of the digest prefix used in simulation ids and store paths. 16 hex -# chars (64 bits) is far beyond collision range for this population while -# keeping filenames readable in logs. + from policyengine_simulation_executor.stage12_cache.levels import ( + BaselineScope, + SourceFileTarget, + YearFileTarget, + ) + +YEAR_FILE_KEY_SCHEMA = "yf1" +BASELINE_KEY_SCHEMA = "bl3" +SOURCE_FILE_KEY_SCHEMA = "sf1" + +# Length of the digest prefix in simulation IDs: 16 hex characters (64 bits) +# is far beyond collision range for this population while keeping file names +# readable in logs. _ID_DIGEST_CHARS = 16 CURRENT_LAW_POLICY = "current-law" @@ -54,7 +53,7 @@ def canonical_digest(payload: Mapping[str, Any]) -> str: - """sha256 over the canonical JSON encoding of ``payload``. + """Return the SHA-256 of the canonical JSON encoding of ``payload``. Canonical means: keys sorted, no whitespace, ASCII-only escapes. Any nested structure must itself be JSON-serializable with deterministic @@ -66,199 +65,31 @@ def canonical_digest(payload: Mapping[str, Any]) -> str: return hashlib.sha256(encoded.encode("utf-8")).hexdigest() -@dataclass(frozen=True) -class DatasetKeyInputs: - """Every input that can change one single-year dataset artifact's bytes. - - ``model_version`` and ``policyengine_version`` belong here because the - single-year build runs a full Microsimulation pass — its output depends - on model code, not just source data. ``source_sha256`` is the installed - multi-year source's content hash from the bundle receipt (byte identity; - closes the same-version re-release hole), ``data_build_fingerprint`` the - certification fingerprint; both may be None when unavailable. - """ - - country: str - dataset: str - year: int - data_version: str - data_artifact_revision: str - source_sha256: str | None - data_build_fingerprint: str | None - model_version: str - policyengine_version: str - spm: dict | None = None - - -def dataset_key(inputs: DatasetKeyInputs) -> str: - """Digest identifying one single-year dataset artifact.""" - return canonical_digest( - { - "schema": DATASET_KEY_SCHEMA if inputs.spm is None else "ds2-spm", - **({"spm": inputs.spm} if inputs.spm is not None else {}), - "country": inputs.country.lower(), - "dataset": inputs.dataset, - "year": int(inputs.year), - "data_version": inputs.data_version, - "data_artifact_revision": inputs.data_artifact_revision, - "source_sha256": inputs.source_sha256, - "data_build_fingerprint": inputs.data_build_fingerprint, - "model_version": inputs.model_version, - "policyengine_version": inputs.policyengine_version, - } - ) - - -@dataclass(frozen=True) -class StateDatasetKeyInputs: - """Every input that can change one per-state single-year dataset's bytes. - - The file is the regional dataset's year file (built by a full - Microsimulation pass, so model and .py versions matter) filtered to the - households whose ``filter_variable`` equals ``state_fips``. - ``dataset_uri`` pins the source to its Hugging Face revision and - ``source_sha256`` is the bundle's certified hash of that source, which may - be None when the bundle has none. - """ - - country: str - dataset: str - dataset_uri: str - source_sha256: str | None - year: int - state_code: str - state_fips: int - filter_variable: str - model_version: str - policyengine_version: str - spm: dict | None = None - - -def state_dataset_key(inputs: StateDatasetKeyInputs) -> str: - """Digest identifying one per-state single-year dataset artifact.""" - return canonical_digest( - { - "schema": STATE_DATASET_KEY_SCHEMA, - "spm": inputs.spm, - "country": inputs.country.lower(), - "dataset": inputs.dataset, - "dataset_uri": inputs.dataset_uri, - "source_sha256": inputs.source_sha256, - "year": int(inputs.year), - "state_code": inputs.state_code.upper(), - "state_fips": int(inputs.state_fips), - "filter_variable": inputs.filter_variable, - "model_version": inputs.model_version, - "policyengine_version": inputs.policyengine_version, - } - ) - - -@dataclass(frozen=True) -class BaselineKeyInputs: - """Every input that can change one precomputed baseline artifact's bytes. - - ``scope_key`` is the ``ScopingStrategy.cache_key`` string (None for an - unscoped national run); ``region`` is the human-readable label - ("national", "state/ca", ...). The simulation year rides in via - ``dataset_digest``. - """ - - country: str - region: str - scope_key: str | None - dataset_digest: str - model_version: str - policyengine_version: str - spm: dict | None = None - policy: str = CURRENT_LAW_POLICY - - -def baseline_key(inputs: BaselineKeyInputs) -> str: - """Digest identifying one precomputed baseline simulation artifact.""" - return canonical_digest( - { - "schema": BASELINE_KEY_SCHEMA if inputs.spm is None else "bl2-spm", - **({"spm": inputs.spm} if inputs.spm is not None else {}), - "country": inputs.country.lower(), - "region": inputs.region, - "scope_key": inputs.scope_key, - "dataset_key": inputs.dataset_digest, - "policy": inputs.policy, - "model_version": inputs.model_version, - "policyengine_version": inputs.policyengine_version, - } - ) - - -def baseline_simulation_id(baseline_digest: str) -> str: - """Return the deterministic ``Simulation.id`` for a baseline artifact. - - The id doubles as the artifact filename stem (``{id}.h5`` beside the - dataset — the path ``Simulation.ensure()`` already loads from), so it - must be filename-safe and must not collide with the dataset filename - pattern ``{stem}_year_{year}.h5``. - """ - return f"{BASELINE_KEY_SCHEMA}-{baseline_digest[:_ID_DIGEST_CHARS]}" - - # --- Store layout --------------------------------------------------------- # -# datasets///_year_.h5 -# state-datasets///_year_.h5 -# baselines///.h5 +# year-files///_year_.h5 +# baselines///.h5 +# sources/// # manifests/.json # deployed/.json # -# The filename inside a dataset object's path is EXACTLY the name the -# runtime's ensure_datasets existence check resolves — the fetch layer -# downloads each object under its basename, into POLICYENGINE_DATA_FOLDER or, -# for a per-state dataset, into its state's folder there, so the object -# basename IS the runtime filename contract. +# A file's basename is the name the runtime resolves: the download step puts +# each object under its basename in its prebuilt folder. -def dataset_artifact_filename(stem: str, year: int) -> str: - """Return the single-year dataset basename the runtime's existence check expects.""" - return f"{stem}_year_{year}.h5" +def year_file_artifact_path(country: str, digest: str, filename: str) -> str: + """Return the store key ``year-files///``.""" + return f"year-files/{country.lower()}/{digest}/{filename}" -def baseline_artifact_filename(simulation_id: str) -> str: - """Return the ``{id}.h5`` basename ``Simulation.ensure()`` loads a baseline from.""" - return f"{simulation_id}.h5" +def baseline_artifact_path(country: str, digest: str, storage_id: str) -> str: + """Return the store key ``baselines///.h5``.""" + return f"baselines/{country.lower()}/{digest}/{storage_id}.h5" -def dataset_artifact_path( - country: str, dataset_digest: str, stem: str, year: int -) -> str: - """Return the store key ``datasets///_year_.h5``.""" - return ( - f"datasets/{country.lower()}/{dataset_digest}/" - f"{dataset_artifact_filename(stem, year)}" - ) - - -def state_dataset_artifact_path( - country: str, state_dataset_digest: str, stem: str, year: int -) -> str: - """Return the store key ``state-datasets///_year_.h5``. - - Every state's file has the same basename, the one the runtime's - ``ensure_datasets`` resolves; the image keeps them apart by folder. - """ - return ( - f"state-datasets/{country.lower()}/{state_dataset_digest}/" - f"{dataset_artifact_filename(stem, year)}" - ) - - -def baseline_artifact_path( - country: str, baseline_digest: str, simulation_id: str -) -> str: - """Return the store key ``baselines///.h5``.""" - return ( - f"baselines/{country.lower()}/{baseline_digest}/" - f"{baseline_artifact_filename(simulation_id)}" - ) +def source_file_artifact_path(country: str, sha256: str, filename: str) -> str: + """Return the store key ``sources///``.""" + return f"sources/{country.lower()}/{sha256}/{filename}" def manifest_path(manifest_digest: str) -> str: @@ -271,138 +102,111 @@ def deployed_marker_path(environment: str) -> str: return f"deployed/{environment}.json" -# --- Version-identity collection ------------------------------------------ +# --- Identities ----------------------------------------------------------- @dataclass(frozen=True) -class DatasetArtifactIdentity: - """Everything needed to key and name one single-year dataset artifact.""" +class YearFileIdentity: + """Everything that can change one year file's bytes, and where it is kept. + + ``subset`` names the rows a per-subset file keeps (``region``, + ``variable``, ``value``), or is None for a whole dataset. ``packages`` maps + each installed package that builds the file to its version. ``stem`` and + ``folder`` name the file and its image folder; they follow from the + dataset and subset, so they are not in the key. + """ country: str dataset: str - stem: str - year: int + dataset_sha256: str | None data_version: str data_artifact_revision: str - source_sha256: str | None - data_build_fingerprint: str | None - model_version: str - policyengine_version: str - spm: dict | None = None - - @property - def digest(self) -> str: - """Content key over every input that can change this dataset's bytes.""" - return dataset_key( - DatasetKeyInputs( - country=self.country, - spm=self.spm, - dataset=self.dataset, - year=self.year, - data_version=self.data_version, - data_artifact_revision=self.data_artifact_revision, - source_sha256=self.source_sha256, - data_build_fingerprint=self.data_build_fingerprint, - model_version=self.model_version, - policyengine_version=self.policyengine_version, - ) - ) - - @property - def filename(self) -> str: - """Basename the runtime resolves under ``POLICYENGINE_DATA_FOLDER``.""" - return dataset_artifact_filename(self.stem, self.year) - - @property - def store_path(self) -> str: - """Store key of this dataset artifact.""" - return dataset_artifact_path(self.country, self.digest, self.stem, self.year) - - -@dataclass(frozen=True) -class StateDatasetArtifactIdentity: - """Everything needed to key and name one per-state single-year dataset.""" - - country: str - dataset: str - dataset_uri: str - source_sha256: str | None - stem: str + certification_fingerprint: str | None year: int - state_code: str - state_fips: int - filter_variable: str - model_version: str - policyengine_version: str - spm: dict | None = None + subset: Mapping[str, Any] | None = field(hash=False) + packages: Mapping[str, str] = field(hash=False) + spm: Mapping[str, Any] | None = field(hash=False) + stem: str + folder: str + + def payload(self) -> dict[str, Any]: + """Return the ``yf1`` payload the digest is computed from.""" + return { + "schema": YEAR_FILE_KEY_SCHEMA, + "country": self.country.lower(), + "dataset": self.dataset, + "dataset_sha256": self.dataset_sha256, + "data_version": self.data_version, + "data_artifact_revision": self.data_artifact_revision, + "certification_fingerprint": self.certification_fingerprint, + "year": int(self.year), + "subset": None if self.subset is None else dict(self.subset), + "packages": dict(self.packages), + "spm": None if self.spm is None else dict(self.spm), + } @property def digest(self) -> str: """Content key over every input that can change this file's bytes.""" - return state_dataset_key( - StateDatasetKeyInputs( - country=self.country, - dataset=self.dataset, - dataset_uri=self.dataset_uri, - source_sha256=self.source_sha256, - year=self.year, - state_code=self.state_code, - state_fips=self.state_fips, - filter_variable=self.filter_variable, - model_version=self.model_version, - policyengine_version=self.policyengine_version, - spm=self.spm, - ) - ) + return canonical_digest(self.payload()) @property def filename(self) -> str: - """Basename the runtime resolves inside the state's folder.""" - return dataset_artifact_filename(self.stem, self.year) + """Basename .py's ``ensure_datasets`` resolves in the file's folder.""" + return f"{self.stem}_year_{self.year}.h5" @property def store_path(self) -> str: - """Store key of this per-state dataset artifact.""" - return state_dataset_artifact_path( - self.country, self.digest, self.stem, self.year - ) + """Store key of this year file.""" + return year_file_artifact_path(self.country, self.digest, self.filename) @dataclass(frozen=True) -class BaselineArtifactIdentity: - """Everything needed to key, id, and name one baseline artifact.""" +class BaselineIdentity: + """Everything that can change one current-law baseline's bytes. - country: str + ``scope_key`` is the scoping strategy's ``cache_key`` (None for a run of + the whole dataset) and ``region`` its readable label (``national``, + ``region_group/…``). ``spm`` is the request's normalised SPM selection. + """ + + year_file: YearFileIdentity region: str scope_key: str | None - dataset: DatasetArtifactIdentity - spm: dict | None = None + spm: Mapping[str, Any] | None = field(default=None, hash=False) + policy: str = CURRENT_LAW_POLICY + + def payload(self) -> dict[str, Any]: + """Return the ``bl3`` payload the digest is computed from.""" + return { + "schema": BASELINE_KEY_SCHEMA, + "year_file": self.year_file.digest, + "region": self.region, + "scope_key": self.scope_key, + "policy": self.policy, + "spm": None if self.spm is None else dict(self.spm), + } + + @property + def country(self) -> str: + """The year file's country.""" + return self.year_file.country.lower() @property def digest(self) -> str: - """Content key; nests the dataset digest, so a dataset change rotates it.""" - return baseline_key( - BaselineKeyInputs( - country=self.country, - region=self.region, - spm=self.spm, - scope_key=self.scope_key, - dataset_digest=self.dataset.digest, - model_version=self.dataset.model_version, - policyengine_version=self.dataset.policyengine_version, - ) - ) + """Content key; nests the year file's digest.""" + return canonical_digest(self.payload()) @property def simulation_id(self) -> str: """``Simulation.id`` the runtime assigns to this baseline.""" - return baseline_simulation_id(self.digest) + return f"{BASELINE_KEY_SCHEMA}-{self.digest[:_ID_DIGEST_CHARS]}" @property def storage_id(self) -> str: - """Artifact filename stem: the simulation id, plus the SPM digest when set. + """File stem .py's ``Simulation.storage_id`` gives: the ID, plus the SPM digest. - The suffix keeps SPM and non-SPM baselines that share a simulation id + The suffix keeps SPM and non-SPM baselines that share a simulation ID from overwriting each other. """ if self.spm is None: @@ -411,87 +215,57 @@ def storage_id(self) -> str: @property def store_path(self) -> str: - """Store key of this baseline artifact, named by ``storage_id``.""" + """Store key of this baseline, named by ``storage_id``.""" return baseline_artifact_path(self.country, self.digest, self.storage_id) -def _receipt_source_sha256(country: str, data_version: str) -> str | None: - """Content hash of the installed multi-year source, when certifiable. +@dataclass(frozen=True) +class SourceFileIdentity: + """A certified source dataset copied into the image byte for byte.""" - Only trusted when the receipt entry's version matches the bundle's data - version (mirroring ``resolve_local_bundle_dataset_path``) — a receipt - left over from a different install must not leak into the key. - """ - from policyengine_simulation_executor.release_bundle import ( # noqa: PLC0415 # identity seam: resolved per call so tests can patch release_bundle._receipt_dataset - _receipt_dataset, - ) + country: str + dataset: str + dataset_sha256: str + filename: str + folder: str + + def payload(self) -> dict[str, Any]: + """Return the ``sf1`` payload the digest is computed from.""" + return { + "schema": SOURCE_FILE_KEY_SCHEMA, + "country": self.country.lower(), + "dataset": self.dataset, + "dataset_sha256": self.dataset_sha256, + } - entry = _receipt_dataset(country) - if not isinstance(entry, Mapping): - return None - if entry.get("version") != data_version: - return None - for field in ("installed_sha256", "expected_sha256"): - value = entry.get(field) - if isinstance(value, str) and value: - return value - return None + @property + def digest(self) -> str: + """Content key of the copied file.""" + return canonical_digest(self.payload()) + @property + def store_path(self) -> str: + """Store key of the copy, addressed by the certified SHA-256.""" + return source_file_artifact_path( + self.country, self.dataset_sha256, self.filename + ) -def _certification_fingerprint(country: str) -> str | None: - from policyengine.provenance.manifest import ( - get_release_manifest, - ) - certification = getattr(get_release_manifest(country), "certification", None) - fingerprint = getattr(certification, "data_build_fingerprint", None) - return fingerprint if isinstance(fingerprint, str) and fingerprint else None +# --- Collecting identities in the container -------------------------------- -def collect_dataset_identity(country: str, year: int) -> DatasetArtifactIdentity: - """Identity of the default single-year dataset for this installed bundle. +def _installed_package_versions(country: str) -> dict[str, str]: + """Return the installed versions of .py, policyengine-core and the country package. - Reads the same sources the runtime trusts: the release bundle (versions), - the bundle receipt (content sha), and the manifest certification - (fingerprint). The stem comes through the same manifest helpers the - runtime lookup uses, so filename coupling is inherited, not - re-derived. + Read where the identity is collected, inside the image, so they are the + versions that build the file. """ - from policyengine.provenance.manifest import ( - dataset_logical_name, - resolve_dataset_reference, - ) - - from policyengine_simulation_executor.release_bundle import ( # noqa: PLC0415 # identity seam: resolved per call so tests can patch release_bundle - get_country_release_bundle, - ) - - bundle = get_country_release_bundle(country) - stem = dataset_logical_name( - resolve_dataset_reference(bundle.country, bundle.default_dataset) - ) - from policyengine_simulation_executor.spm import ( - normalize_runtime_spm, - ) - - selection = normalize_runtime_spm({"country": country, "time_period": year}) - return DatasetArtifactIdentity( - spm=selection, - country=bundle.country, - dataset=bundle.default_dataset, - stem=stem, - year=int(year), - data_version=bundle.data_version, - data_artifact_revision=bundle.data_artifact_revision, - source_sha256=_receipt_source_sha256(bundle.country, bundle.data_version), - data_build_fingerprint=_certification_fingerprint(bundle.country), - model_version=bundle.model_version, - policyengine_version=bundle.policyengine_version, - ) + names = ("policyengine", "policyengine-core", f"policyengine-{country.lower()}") + return {name: version(name) for name in names} def _release_dataset_sha256(country: str, dataset: str) -> str | None: - """Certified SHA-256 of a bundle dataset, from the .py release manifest.""" + """Return a bundle dataset's certified SHA-256 from the .py release manifest.""" from policyengine.provenance.manifest import ( get_release_manifest, ) @@ -501,27 +275,33 @@ def _release_dataset_sha256(country: str, dataset: str) -> str | None: return digest.lower() if isinstance(digest, str) and digest else None -def collect_state_dataset_identity( # noqa: PLR0913 # one keyword per input of the per-state key - country: str, - year: int, - *, - dataset: str, - state_code: str, - state_fips: int, - filter_variable: str, -) -> StateDatasetArtifactIdentity: - """Identity of one state's year file filtered from a bundle dataset. - - ``dataset`` names a non-default bundle dataset, such as the regional - dataset state regions load. Versions and the revision-pinned URI come from - the release bundle, the source hash from the .py release manifest, and the - stem through the same manifest helpers the runtime lookup uses. - """ +def _certification_fingerprint(country: str) -> str | None: + from policyengine.provenance.manifest import ( + get_release_manifest, + ) + + certification = getattr(get_release_manifest(country), "certification", None) + fingerprint = getattr(certification, "data_build_fingerprint", None) + return fingerprint if isinstance(fingerprint, str) and fingerprint else None + + +def _dataset_stem(country: str, dataset: str) -> str: from policyengine.provenance.manifest import ( dataset_logical_name, resolve_dataset_reference, ) + return dataset_logical_name(resolve_dataset_reference(country, dataset)) + + +def year_file_identity(target: YearFileTarget) -> YearFileIdentity: + """Return the ``yf1`` identity of a handler's year-file target. + + Versions come from the release bundle, the source's certified hash and + the certification fingerprint from the .py release manifest, the package + versions from the installed packages, and the SPM selection from the + image's capability for the year. + """ from policyengine_simulation_executor.release_bundle import ( # noqa: PLC0415 # identity seam: resolved per call so tests can patch release_bundle get_country_release_bundle, ) @@ -529,51 +309,86 @@ def collect_state_dataset_identity( # noqa: PLR0913 # one keyword per input of normalize_runtime_spm, ) + country = target.country.lower() bundle = get_country_release_bundle(country) - dataset_uri = bundle.dataset_uris.get(dataset) - if dataset_uri is None: - msg = f"Dataset {dataset!r} is not in the {country} release bundle" - raise ValueError(msg) - return StateDatasetArtifactIdentity( - country=bundle.country, - dataset=dataset, - dataset_uri=dataset_uri, - source_sha256=_release_dataset_sha256(bundle.country, dataset), - stem=dataset_logical_name(resolve_dataset_reference(bundle.country, dataset)), - year=int(year), - state_code=state_code.upper(), - state_fips=int(state_fips), - filter_variable=filter_variable, - model_version=bundle.model_version, - policyengine_version=bundle.policyengine_version, - spm=normalize_runtime_spm({"country": country, "time_period": year}), + subset = target.subset + return YearFileIdentity( + country=country, + dataset=target.dataset, + dataset_sha256=_release_dataset_sha256(country, target.dataset), + data_version=bundle.data_version, + data_artifact_revision=bundle.data_artifact_revision, + certification_fingerprint=_certification_fingerprint(country), + year=int(target.year), + subset=( + None + if subset is None + else { + "region": subset.region, + "variable": subset.variable, + "value": subset.value, + } + ), + packages=_installed_package_versions(country), + spm=normalize_runtime_spm({"country": country, "time_period": target.year}), + stem=_dataset_stem(country, target.dataset), + folder=target.folder, ) -def collect_baseline_identity( - country: str, - year: int, - *, - region: str, - scope_key: str | None, - spm: dict | None = None, -) -> BaselineArtifactIdentity: - """Return the identity of this bundle's baseline for one region and year. +def baseline_identity( + year_file: YearFileIdentity, + scope: BaselineScope, + spm: Mapping[str, Any] | None = None, +) -> BaselineIdentity: + """Return the ``bl3`` identity of a current-law baseline on ``year_file``. - ``spm`` is normalized against the installed image's capability first, so - a request that omits it still keys to the image's default SPM selection. + ``spm`` is normalised against the image's capability first, so a request + that omits it still keys to the image's default SPM selection. """ from policyengine_simulation_executor.spm import ( normalize_runtime_spm, ) selection = normalize_runtime_spm( - {"country": country, "time_period": year, "spm": spm} + { + "country": year_file.country, + "time_period": year_file.year, + "spm": None if spm is None else dict(spm), + } ) - return BaselineArtifactIdentity( + return BaselineIdentity( + year_file=year_file, + region=scope.region, + scope_key=scope.scope_key, spm=selection, - country=country.lower(), - region=region, - scope_key=scope_key, - dataset=collect_dataset_identity(country, year), + ) + + +def source_file_identity(target: SourceFileTarget) -> SourceFileIdentity: + """Return the ``sf1`` identity of a source dataset copied into the image. + + Raises ``ValueError`` when the release manifest certifies no SHA-256 for + it: a copy is addressed by that hash. + """ + from policyengine.provenance.manifest import ( + resolve_dataset_reference, + ) + + country = target.country.lower() + sha256 = _release_dataset_sha256(country, target.dataset) + if sha256 is None: + msg = ( + f"The {country} release manifest has no certified SHA-256 for " + f"{target.dataset}" + ) + raise ValueError(msg) + reference = resolve_dataset_reference(country, target.dataset) + filename = reference.split("@", 1)[0].rsplit("/", 1)[-1] + return SourceFileIdentity( + country=country, + dataset=target.dataset, + dataset_sha256=sha256, + filename=filename, + folder=target.folder, ) diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/artifact_store.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/artifact_store.py index bcf95f524..38b854486 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/artifact_store.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/artifact_store.py @@ -20,9 +20,11 @@ from __future__ import annotations +import hashlib import json import os from collections.abc import Mapping +from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, Any @@ -34,6 +36,23 @@ from google.cloud import storage ARTIFACT_BUCKET_ENV = "POLICYENGINE_ARTIFACT_BUCKET" +_HASH_CHUNK_BYTES = 1024 * 1024 + + +@dataclass(frozen=True) +class StoredObject: + """A stored object's content SHA-256 and size, which the manifest records.""" + + sha256: str + size_bytes: int + + +def _file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + while chunk := stream.read(_HASH_CHUNK_BYTES): + digest.update(chunk) + return digest.hexdigest() def resolve_bucket_name(explicit: str | None = None) -> str: @@ -90,18 +109,44 @@ def exists(self, path: str) -> bool: def upload_file(self, path: str, local_path: str | Path) -> bool: """Upload a local file write-once; return whether this call created the object. - False means an object already existed at that key, which counts as - success because keys digest the full input closure (see the module - docstring). + The object records the file's SHA-256 and size as metadata, which the + manifest copies. False means an object already existed at that key, + which counts as success because keys digest the full input closure + (see the module docstring). """ + source = Path(local_path) + blob = self._blob(path) + blob.metadata = { + "sha256": _file_sha256(source), + "size_bytes": str(source.stat().st_size), + } try: - self._blob(path).upload_from_filename( - str(local_path), if_generation_match=0 - ) + blob.upload_from_filename(str(source), if_generation_match=0) except PreconditionFailed: return False return True + def describe(self, path: str) -> StoredObject: + """Return the stored object's SHA-256 and size. + + Uses the object's metadata, or hashes its content when the metadata + lacks them. Raises ``FileNotFoundError`` when there is no object. + """ + blob = self._blob(path) + try: + blob.reload() + except NotFound: + raise FileNotFoundError(path) from None + metadata = blob.metadata or {} + sha256 = metadata.get("sha256") + size_bytes = metadata.get("size_bytes") + if isinstance(sha256, str) and isinstance(size_bytes, str): + return StoredObject(sha256=sha256, size_bytes=int(size_bytes)) + payload = blob.download_as_bytes() + return StoredObject( + sha256=hashlib.sha256(payload).hexdigest(), size_bytes=len(payload) + ) + def upload_bytes( self, path: str, diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/baseline_artifacts.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/baseline_artifacts.py index c0e54e47d..81b2eaf77 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/baseline_artifacts.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/baseline_artifacts.py @@ -1,11 +1,12 @@ """Deterministic baseline simulation ids and the validate-on-load guard. -The runtime read path of the artifact pipeline. A baseline simulation whose -identity is fully determined by the installed version-set (current-law -policy, default data, national or region-group scope) gets a deterministic -``Simulation.id`` from ``artifact_keys``; ``Simulation.ensure()`` then finds -``{id}.h5`` beside the dataset when a precomputed artifact was baked into -the image, and loads in seconds instead of running the model. +The runtime read path of the artifact pipeline. A current-law baseline whose +identity is fully determined by the installed version-set gets a +deterministic ``Simulation.id`` from ``artifact_keys``: its level handler +(``stage12_cache.levels``) decides which runs qualify. ``Simulation.ensure()`` +then finds ``{storage id}.h5`` beside the year file when a precomputed +baseline was baked into the image's prebuilt folder, and loads in seconds +instead of running the model. Safety inversion: a load is trusted only after validation. Requests can demand output columns beyond what an artifact was built with (cliff @@ -24,12 +25,13 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Final, Protocol, runtime_checkable -from policyengine.core.scoping_strategy import RegionGroupStrategy from policyengine_simulation_contract.spm import SPMInputError, spm_error_detail from pydantic import PrivateAttr from policyengine_simulation_executor import artifact_keys from policyengine_simulation_executor.precompute_models import ArtifactOutcome +from policyengine_simulation_executor.region_resolution import RegionResolution +from policyengine_simulation_executor.stage12_cache import levels from policyengine_simulation_executor.stage_reporting_simulation import ( StageReportingSimulation, ) @@ -38,6 +40,8 @@ from policyengine.core import Simulation from policyengine.core.scoping_strategy import ScopingStrategy + from policyengine_simulation_executor.simulation_runtime import DatasetSelection + logger = logging.getLogger(__name__) # Artifact outcomes reported via the `baseline_artifact` observability @@ -68,53 +72,49 @@ def resolve_entity_variables(self, simulation: Simulation) -> dict[str, list[str class BaselineIdentityRequest: """The request facts that decide whether a baseline has a deterministic id. - ``region_code`` is the normalized region (None when unresolved) and + ``region_code`` is the normalized region (None when unresolved), ``scoping_strategy`` narrows the simulation to it (None for a whole - dataset, as a national run is). + dataset, as a national run is), ``state_code`` is the US state a state or + district region lies in, and ``dataset`` is the selected dataset. """ params: dict[str, Any] country: str - dataset_is_default: bool + dataset: DatasetSelection policy: object region_code: str | None scoping_strategy: ScopingStrategy | None year: int + state_code: str | None = None - -def _artifact_scope( - request: BaselineIdentityRequest, -) -> tuple[str, str | None] | None: - """Return the artifact's region label and scope key, or None if unsupported. - - Supported scopes are an unscoped national run and a region group. - """ - if request.region_code is None: - return None - if request.scoping_strategy is None: - if request.region_code != request.country.lower(): + def run_scope(self) -> levels.RunScope | None: + """Return the run the level handlers look at; None for an unresolved region.""" + if self.region_code is None: return None - return artifact_keys.NATIONAL_REGION, None - if isinstance(request.scoping_strategy, RegionGroupStrategy): - return request.region_code, request.scoping_strategy.cache_key - return None + return levels.RunScope( + country=self.country.lower(), + year=self.year, + region=RegionResolution( + code=self.region_code, + scoping_strategy=self.scoping_strategy, + state_code=self.state_code, + ), + dataset=self.dataset, + ) def qualifying_baseline_identity( request: BaselineIdentityRequest, -) -> artifact_keys.BaselineArtifactIdentity | None: +) -> artifact_keys.BaselineIdentity | None: """Full artifact identity for a qualifying baseline, else None. Qualifying means the simulation's bytes are a pure function of the - installed version-set: current-law policy, macro scope, the resolved - default dataset, and a scope the pipeline produces - artifacts for — unscoped national or a region group. Single states stay - on random ids in v1. - - Deliberately broader than what the store contains: UK national and - off-precompute years qualify too, get deterministic ids, miss, and - compute — a free in-process-cache win for warm containers, and their - artifacts appear automatically if the precompute ever produces them. + installed version-set: current-law policy, macro scope, and a run whose + level handler gives a baseline scope (today the unscoped US and UK + national runs and the US groups of states). The handler decides by the + run alone, never by the precomputed years: a qualifying run in a year that + is not precomputed still gets a fixed ID, misses, and computes — a free + in-process-cache win for warm containers. Both the runtime reader (via ``deterministic_baseline_id``) and the precompute writer derive identity through THIS function, so writer and @@ -122,23 +122,19 @@ def qualifying_baseline_identity( propagate: the writer must fail loudly on them. """ params = request.params - if request.policy is not None: - return None - if str(params.get("scope") or "").lower() != "macro": + if request.policy is not None or str(params.get("scope") or "").lower() != "macro": return None - if not request.dataset_is_default: + run = request.run_scope() + prebuilt = None if run is None else levels.prebuilt_for(run.country) + handler = None if run is None or prebuilt is None else prebuilt.handler_for_run(run) + if run is None or handler is None: return None - scope = _artifact_scope(request) - if scope is None: + scope = handler.baseline_scope(run) + year_file = None if scope is None else handler.year_file_for(run) + if scope is None or year_file is None: return None - region, scope_key = scope - - return artifact_keys.collect_baseline_identity( - request.country.lower(), - request.year, - region=region, - scope_key=scope_key, - **({"spm": params["spm"]} if params.get("spm") is not None else {}), + return artifact_keys.baseline_identity( + artifact_keys.year_file_identity(year_file), scope, params.get("spm") ) diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/national_partition.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/national_partition.py index c3bd64b9a..980e2cf06 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/national_partition.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/national_partition.py @@ -13,29 +13,15 @@ membership changes alter per-child runtimes, not correctness. """ -US_NATIONAL_REGION_GROUPS: tuple[tuple[str, ...], ...] = ( - ("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"), +from policyengine_simulation_executor.stage12_cache.partition import ( + US_REGION_GROUPS, ) +# Stage 12's partition is the one list of the 20 groups: the precomputed +# group baselines are built from it (``stage12_cache.levels_us``), so the +# segmented runs that read them must use the same groups. +US_NATIONAL_REGION_GROUPS: tuple[tuple[str, ...], ...] = US_REGION_GROUPS + def national_region_groups(country: str) -> list[list[str]] | None: """Return the region-group partition for a country's segmented national run. diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute.py index 03602e712..1625d461f 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute.py @@ -20,11 +20,13 @@ existing store objects (uploads are write-once) — healing a bad artifact means deleting its object first, then re-running. -Cohort baselines are built through the executor's own request path -(``resolve_region`` + ``_build_simulation`` on a synthetic child request), -so scoping, extra variables, and the deterministic simulation id match the -production child's by construction, not by convention — and a regression -test asserts the writer and reader derive identical identities. All +Baselines are built through the executor's own request path +(``resolve_region`` + ``_build_simulation`` on each level handler's +synthetic request), so scoping, extra variables, and the deterministic +simulation id match a production run's by construction, not by convention — +and a regression test asserts the writer and reader derive identical +identities. Which years, files and baselines a country builds comes from its +level handlers (``stage12_cache.levels``). All identity collection and store I/O must run inside containers: the bundle receipt that the keys digest lives in the image, not on the deploying machine. @@ -38,69 +40,59 @@ import logging from dataclasses import dataclass -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any from policyengine_simulation_executor.precompute_baselines import ( compute_baseline_impl, verify_determinism_impl, ) from policyengine_simulation_executor.precompute_datasets import ( - build_dataset_impl, - build_state_datasets_impl, + build_year_files_impl, ) from policyengine_simulation_executor.precompute_models import ( + MANIFEST_SCHEMA, ArtifactManifest, BaselineComputeResult, - DatasetBuildResult, + BaselinePlanEntry, DeterminismVerdict, - ManifestArtifact, ManifestEntry, PrecomputePlan, RemoteFunction, - StateDatasetArtifact, - StateDatasetBuildResult, + YearFileBuildResult, + YearFilePlanEntry, ) from policyengine_simulation_executor.precompute_planning import ( - PRECOMPUTE_COUNTRY, - PRECOMPUTE_YEARS, - StateDatasetTarget, - cohort_identity, - cohort_params, + baseline_target_identity, + country_prebuilt, plan_artifacts_impl, select_work, - state_dataset_targets, ) if TYPE_CHECKING: - from collections.abc import Callable + from collections.abc import Callable, Mapping + + from policyengine_simulation_executor.artifact_store import StoredObject __all__ = [ "MANIFEST_DIGEST_PREFIX", "MANIFEST_SCHEMA", - "PRECOMPUTE_COUNTRY", - "PRECOMPUTE_YEARS", "PrecomputeFunctions", - "StateDatasetTarget", - "build_dataset_impl", + "baseline_target_identity", "build_manifest", - "build_state_datasets_impl", - "cohort_identity", - "cohort_params", + "build_year_files_impl", "compute_baseline_impl", + "country_prebuilt", "logger", "manifest_digest_line", "plan_artifacts_impl", "publish_manifest_impl", "run_precompute", "select_work", - "state_dataset_targets", "verify_determinism_impl", ] logger = logging.getLogger(__name__) -MANIFEST_SCHEMA = "mf1" - # The stdout contract the CI deploy job parses; keep format changes in # lockstep with the workflow side (covered by a regression test). MANIFEST_DIGEST_PREFIX = "MANIFEST_DIGEST=" @@ -111,62 +103,88 @@ def manifest_digest_line(digest: str) -> str: return f"{MANIFEST_DIGEST_PREFIX}{digest}" -def build_manifest(plan: PrecomputePlan) -> ArtifactManifest: - """Build the deploy manifest: the receipt and each artifact the image must fetch. +def build_manifest( + plan: PrecomputePlan, stored: Mapping[str, StoredObject] +) -> ArtifactManifest: + """Build a country's deploy manifest: the receipt and every file the image fetches. - Datasets, then baselines, then per-state datasets, each in plan order, so - a plan without per-state datasets keeps the manifest it always had. + Year files, then baselines, then source files, each in plan order. + ``stored`` maps each planned path to the SHA-256 and size the store holds + for it, which the image's download step checks. """ - artifacts: list[ManifestEntry] = [ - ManifestArtifact( - type="dataset", + artifacts = [ + ManifestEntry( + kind="year_file", + level=entry.level, + region=entry.region, path=entry.path, filename=entry.filename, + folder=entry.folder, year=entry.year, digest=entry.digest, + sha256=stored[entry.path].sha256, + size_bytes=stored[entry.path].size_bytes, ) - for entry in plan.datasets + for entry in plan.year_files ] artifacts += [ - ManifestArtifact( - type="baseline", + ManifestEntry( + kind="baseline", + level=entry.level, + region=entry.region, path=entry.path, - filename=entry.path.rsplit("/", maxsplit=1)[-1], + filename=f"{entry.storage_id}.h5", + folder=entry.folder, year=entry.year, digest=entry.digest, + sha256=stored[entry.path].sha256, + size_bytes=stored[entry.path].size_bytes, ) for entry in plan.baselines ] artifacts += [ - StateDatasetArtifact( - type="state_dataset", + ManifestEntry( + kind="source_file", + level=entry.level, + region=None, path=entry.path, filename=entry.filename, folder=entry.folder, - state_code=entry.state_code, - year=entry.year, + year=None, digest=entry.digest, + sha256=stored[entry.path].sha256, + size_bytes=stored[entry.path].size_bytes, ) - for entry in plan.state_datasets + for entry in plan.source_files ] return ArtifactManifest( # The field's alias, which Pydantic accepts (and which its type # checker support knows) at construction. schema=MANIFEST_SCHEMA, - country=PRECOMPUTE_COUNTRY, + country=plan.country, receipt=plan.receipt, artifacts=artifacts, ) def publish_manifest_impl(bucket: str, plan: PrecomputePlan) -> str: - """Store the plan's manifest write-once and return its content digest.""" + """Store the plan's manifest write-once and return its content digest. + + Reads each planned object's SHA-256 and size from the store first, so a + missing object fails the publish (``FileNotFoundError``) before anything + is written. + """ from policyengine_simulation_executor.artifact_store import ( # noqa: PLC0415 # resolved per call so tests can patch artifact_store.ArtifactStore ArtifactStore, ) - manifest = build_manifest(plan) - return ArtifactStore(bucket).write_manifest(manifest.canonical_payload()) + store = ArtifactStore(bucket) + paths = [ + entry.path for entry in [*plan.year_files, *plan.baselines, *plan.source_files] + ] + stored = {path: store.describe(path) for path in paths} + manifest = build_manifest(plan, stored) + return store.write_manifest(manifest.canonical_payload()) @dataclass(frozen=True) @@ -181,95 +199,157 @@ class PrecomputeFunctions: publish_manifest: RemoteFunction +@dataclass(frozen=True) +class _SubsetBuild: + """One running build of a year's subset year files of one dataset.""" + + label: str + paths: frozenset[str] + handle: Any + + +def _wait_for_subset_builds( + builds: list[_SubsetBuild], echo: Callable[[str], None] +) -> None: + for build in builds: + results = [ + YearFileBuildResult.model_validate(item) for item in build.handle.get() + ] + uploaded = [result for result in results if result.uploaded] + echo( + f"{build.label}: {len(results)} built, {len(uploaded)} uploaded " + f"({sum(result.size_bytes for result in uploaded)} bytes) in " + f"{max((result.build_seconds for result in results), default=0.0)} s" + ) + + +def _start_year_file_builds( + bucket: str, entries: list[YearFilePlanEntry], functions: PrecomputeFunctions +) -> tuple[list[tuple[YearFilePlanEntry, Any]], list[_SubsetBuild]]: + """Start a build per whole-dataset year file and per year and subset dataset.""" + whole = [ + (entry, functions.build_dataset.spawn(bucket, entry.model_dump())) + for entry in entries + if entry.subset_code is None + ] + grouped: dict[tuple[int, str], list[YearFilePlanEntry]] = {} + for entry in entries: + if entry.subset_code is not None: + grouped.setdefault((entry.year, entry.dataset), []).append(entry) + subsets = [ + _SubsetBuild( + label=f"Year files {year} {dataset}", + paths=frozenset(entry.path for entry in group), + handle=functions.build_state_datasets.spawn( + bucket, year, [entry.model_dump() for entry in group] + ), + ) + for (year, dataset), group in grouped.items() + ] + return whole, subsets + + +def _check_determinism( + bucket: str, + computed: list[BaselinePlanEntry], + functions: PrecomputeFunctions, + echo: Callable[[str], None], +) -> None: + """Recompute the first computed baseline of each level; stop on any difference.""" + probes: dict[str, BaselinePlanEntry] = {} + for entry in computed: + probes.setdefault(entry.level, entry) + for probe in probes.values(): + echo(f"Determinism check: recomputing {probe.year} {probe.label}") + verdict = DeterminismVerdict.model_validate( + functions.verify_determinism.remote(bucket, probe.model_dump()) + ) + if not verdict.equal: + raise SystemExit( + "Determinism check FAILED: " + "; ".join(verdict.differences) + ) + echo("Determinism check passed") + + def run_precompute( bucket: str, *, + country: str = "us", force: bool, functions: PrecomputeFunctions, echo: Callable[[str], None] = print, ) -> str: - """Orchestrate the local entrypoint: plan, spawn misses, gate, publish. + """Orchestrate one country's precompute: plan, build misses, check, publish. Takes the six Modal function handles as ``functions`` (each offering - ``.remote``/``.spawn``) so the flow is testable with plain fakes. - Per-state dataset builds (one container per year and dataset) start with - the dataset builds and are waited for only before the manifest is - published, so the baselines never wait for them. + ``.remote``/``.spawn``) so the flow is testable with plain fakes. A + whole dataset's year file is one ``build_dataset`` call; subset year + files are one ``build_state_datasets`` call per year and dataset. Each + baseline starts once the build of the year file it reads has finished, + when this run builds that file, and publishing waits for every build. Everything crossing a handle is a plain dict (Modal's serialization boundary); it is validated back into models immediately on return. - The determinism gate runs only when baselines were actually computed - (a no-op run must stay a no-op). Returns the manifest digest; the - LAST echoed line is the ``MANIFEST_DIGEST=`` contract the deploy job - parses. + The determinism check recomputes the first computed baseline of each + level that computed any (a no-op run stays a no-op). A plan that needs a + source file stops before any build, since nothing copies one into the + store yet. Returns the manifest + digest; the LAST echoed line is the ``MANIFEST_DIGEST=`` contract the + deploy job parses. """ - echo(f"Planning against gs://{bucket} (force={force})") - plan = PrecomputePlan.model_validate(functions.plan_artifacts.remote(bucket)) + echo(f"Planning {country} against gs://{bucket} (force={force})") + plan = PrecomputePlan.model_validate( + functions.plan_artifacts.remote(bucket, country) + ) work = select_work(plan, force=force) + if work.source_files: + missing = ", ".join(entry.path for entry in work.source_files) + msg = ( + "This precompute cannot copy source files into the store yet, and " + f"the plan needs these source files: {missing}" + ) + raise SystemExit(msg) echo( - f"Plan: {len(plan.datasets)} datasets ({len(work.datasets)} to " - f"build), {len(plan.state_datasets)} state datasets " - f"({len(work.state_datasets)} to build), {len(plan.baselines)} baselines " - f"({len(work.baselines)} to compute)" + f"Plan: {len(plan.year_files)} year files ({len(work.year_files)} to " + f"build), {len(plan.baselines)} baselines ({len(work.baselines)} to compute)" ) - dataset_handles = [ - functions.build_dataset.spawn(bucket, entry.model_dump()) - for entry in work.datasets - ] - # One build prepares one dataset's year file, so builds are per year and - # dataset. - state_builds: dict[tuple[int, str], list[dict]] = {} - for entry in work.state_datasets: - state_builds.setdefault((entry.year, entry.dataset), []).append( - entry.model_dump() - ) - state_handles = [ - (year, dataset, functions.build_state_datasets.spawn(bucket, year, entries)) - for (year, dataset), entries in state_builds.items() - ] - for handle in dataset_handles: - result = DatasetBuildResult.model_validate(handle.get()) + whole_builds, subset_builds = _start_year_file_builds( + bucket, work.year_files, functions + ) + for entry, handle in whole_builds: + result = YearFileBuildResult.model_validate(handle.get()) echo( - f"dataset year={result.year} built in " + f"year file {entry.dataset} {result.year} built in " f"{result.build_seconds}s ({result.size_bytes} bytes, " f"uploaded={result.uploaded})" ) + subset_paths = {path for build in subset_builds for path in build.paths} + on_subset_files = [ + entry for entry in work.baselines if entry.year_file_path in subset_paths + ] baseline_handles = [ functions.compute_baseline.spawn(bucket, entry.model_dump()) for entry in work.baselines + if entry.year_file_path not in subset_paths ] + if on_subset_files: + _wait_for_subset_builds(subset_builds, echo) + subset_builds = [] + baseline_handles += [ + functions.compute_baseline.spawn(bucket, entry.model_dump()) + for entry in on_subset_files + ] for handle in baseline_handles: result = BaselineComputeResult.model_validate(handle.get()) echo( - f"baseline year={result.year} id={result.simulation_id} " + f"baseline year={result.year} {result.label} id={result.simulation_id} " f"outcome={result.outcome} in {result.compute_seconds}s " f"(uploaded={result.uploaded})" ) - if work.baselines: - probe = work.baselines[0] - echo(f"Determinism gate: recomputing year={probe.year} group={probe.group}") - verdict = DeterminismVerdict.model_validate( - functions.verify_determinism.remote(bucket, probe.model_dump()) - ) - if not verdict.equal: - raise SystemExit( - "Determinism gate FAILED: " + "; ".join(verdict.differences) - ) - echo("Determinism gate passed") - - for year, dataset, handle in state_handles: - results = [ - StateDatasetBuildResult.model_validate(result) for result in handle.get() - ] - uploaded = [result for result in results if result.uploaded] - echo( - f"State datasets {year} {dataset}: {len(results)} built, " - f"{len(uploaded)} uploaded " - f"({sum(result.size_bytes for result in uploaded)} bytes) in " - f"{max((result.build_seconds for result in results), default=0.0)} s" - ) + _check_determinism(bucket, work.baselines, functions, echo) + _wait_for_subset_builds(subset_builds, echo) manifest_digest = functions.publish_manifest.remote(bucket, plan.model_dump()) echo(manifest_digest_line(manifest_digest)) diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute_baselines.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute_baselines.py index f0a5b827f..52206022d 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute_baselines.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute_baselines.py @@ -1,4 +1,4 @@ -"""Compute the precompute's cohort baselines, and check that they are deterministic.""" +"""Compute the precompute's current-law baselines and check they are deterministic.""" from __future__ import annotations @@ -6,16 +6,17 @@ from pathlib import Path from typing import TYPE_CHECKING -from policyengine_simulation_executor.artifact_keys import baseline_artifact_filename from policyengine_simulation_executor.output_frames import EntityFrames from policyengine_simulation_executor.precompute_models import ( BaselineComputeResult, BaselinePlanEntry, DeterminismVerdict, ) -from policyengine_simulation_executor.precompute_planning import ( - PRECOMPUTE_COUNTRY, - cohort_resolution, +from policyengine_simulation_executor.precompute_planning import country_prebuilt +from policyengine_simulation_executor.request_policy import parse_year +from policyengine_simulation_executor.stage12_cache.levels import ( + RunScope, + prebuilt_dataset_folder, ) if TYPE_CHECKING: @@ -24,37 +25,63 @@ from policyengine_simulation_executor.artifact_store import ArtifactStore -def _prepare_cohort_baseline( +def _prepare_baseline( bucket: str, expected: BaselinePlanEntry ) -> tuple[ArtifactStore, Path, Simulation]: - """Shared by compute and verify: dataset download + simulation build.""" - from policyengine_simulation_executor.artifact_keys import ( # noqa: PLC0415 # resolved per call so tests can patch artifact_keys.collect_dataset_identity - collect_dataset_identity, - ) + """Shared by compute and verify: year-file download and simulation build. + + Downloads the entry's year file into its prebuilt folder when it is + missing, then resolves the entry's request exactly as the runtime + resolves a request and loads the year file through the level's prebuilt + lookup, so the baseline is computed on, and saved beside, the file the + image holds. Returns the store, the folder the baseline lands in and the + simulation. + """ from policyengine_simulation_executor.artifact_store import ( # noqa: PLC0415 # resolved per call so tests can patch artifact_store.ArtifactStore ArtifactStore, ) from policyengine_simulation_executor.simulation_runtime import ( # noqa: PLC0415 # resolved per call so tests can patch simulation_runtime helpers _build_simulation, + _country_module, _load_dataset, _resolve_dataset_selection, resolve_data_folder, + resolve_region, ) store = ArtifactStore(bucket) - data_folder = Path(resolve_data_folder()) - - dataset_identity = collect_dataset_identity(PRECOMPUTE_COUNTRY, expected.year) - local_dataset = data_folder / dataset_identity.filename - if not local_dataset.exists(): - store.download_file(dataset_identity.store_path, local_dataset) - - params, country_module, resolution = cohort_resolution( - expected.year, expected.group + data_folder = resolve_data_folder() + folder = Path(data_folder) / expected.folder + local_year_file = folder / expected.year_file_filename + if not local_year_file.exists(): + store.download_file(expected.year_file_path, local_year_file) + + params = dict(expected.request) + country_module = _country_module(expected.country) + resolution = resolve_region( + country_module=country_module, country=expected.country, params=params ) dataset_selection = _resolve_dataset_selection(params, region_resolution=resolution) + prebuilt = prebuilt_dataset_folder( + RunScope( + country=expected.country, + year=parse_year(params), + region=resolution, + dataset=dataset_selection, + ), + data_folder, + ) + if prebuilt is None or Path(prebuilt.folder) != folder: + msg = ( + f"The {expected.label} baseline's year file {local_year_file} is not " + "one its run would read; refusing to compute it elsewhere." + ) + raise RuntimeError(msg) dataset = _load_dataset( - params, country_module=country_module, selection=dataset_selection + params, + country_module=country_module, + selection=dataset_selection, + data_folder=prebuilt.folder, ) baseline = _build_simulation( params, @@ -70,40 +97,32 @@ def _prepare_cohort_baseline( "under a mismatched key." ) raise RuntimeError(msg) - planned_storage_id = Path(expected.path).stem storage_id = getattr(baseline, "storage_id", baseline.id) - if storage_id != planned_storage_id: + if storage_id != expected.storage_id: msg = ( "Planned and in-container baseline storage ids disagree " - f"({planned_storage_id} != {storage_id}); refusing to act " + f"({expected.storage_id} != {storage_id}); refusing to act " "under a mismatched key." ) raise RuntimeError(msg) - # The extras economic_impact_analysis applies unconditionally before - # ensure(); the artifact must carry them or every request would fail - # the column guard and recompute. - from policyengine.tax_benefit_models.us.analysis import ( - configure_budgetary_impact_variables, - ) - - configure_budgetary_impact_variables(baseline, baseline) - return store, data_folder, baseline + country_prebuilt(expected.country).prepare_baseline_outputs(baseline) + return store, folder, baseline def compute_baseline_impl( bucket: str, expected: BaselinePlanEntry ) -> BaselineComputeResult: - """Wave 2: compute one cohort baseline and upload its output.""" + """Compute one current-law baseline and upload its output.""" from policyengine_simulation_executor.baseline_artifacts import ( ArtifactBaselineSimulation, ) - store, data_folder, baseline = _prepare_cohort_baseline(bucket, expected) + store, folder, baseline = _prepare_baseline(bucket, expected) if not isinstance(baseline, ArtifactBaselineSimulation): msg = ( "Precompute built a plain Simulation — the qualifying predicate " - "rejected the cohort request shape." + "rejected the baseline request." ) raise RuntimeError(msg) # noqa: TRY004 # a precompute invariant failure, not a bad argument; raised across the compute_baseline Modal boundary and asserted by test_precompute @@ -111,16 +130,14 @@ def compute_baseline_impl( baseline.ensure() compute_seconds = time.monotonic() - started - artifact_file = data_folder / baseline_artifact_filename( - getattr(baseline, "storage_id", baseline.id) - ) + artifact_file = folder / f"{expected.storage_id}.h5" if not artifact_file.exists(): msg = f"ensure() left no artifact at {artifact_file}" raise RuntimeError(msg) uploaded = store.upload_file(expected.path, artifact_file) return BaselineComputeResult( year=expected.year, - group=list(expected.group), + label=expected.label, simulation_id=baseline.id, outcome=baseline.artifact_outcome, uploaded=uploaded, @@ -149,14 +166,12 @@ def verify_determinism_impl( OUTCOME_HIT, ) - store, data_folder, baseline = _prepare_cohort_baseline(bucket, expected) - artifact_file = data_folder / baseline_artifact_filename( - getattr(baseline, "storage_id", baseline.id) - ) + store, folder, baseline = _prepare_baseline(bucket, expected) + artifact_file = folder / f"{expected.storage_id}.h5" if not artifact_file.exists(): store.download_file(expected.path, artifact_file) baseline.ensure() - # A cohort baseline is an ArtifactBaselineSimulation, which records the + # A planned baseline is an ArtifactBaselineSimulation, which records the # outcome; the attribute isn't on the Simulation type it is declared as. outcome = getattr(baseline, "artifact_outcome", None) if outcome != OUTCOME_HIT: diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute_datasets.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute_datasets.py index 9682fc68d..67dcfac18 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute_datasets.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute_datasets.py @@ -1,272 +1,115 @@ -"""Build the precompute's national and per-state datasets.""" +"""Build and upload one country's year files through its level handlers.""" from __future__ import annotations -import gc import tempfile import time from pathlib import Path from typing import TYPE_CHECKING from policyengine_simulation_executor.precompute_models import ( - DatasetBuildResult, - DatasetPlanEntry, - StateDatasetBuildResult, - StateDatasetPlanEntry, -) -from policyengine_simulation_executor.precompute_planning import ( - PRECOMPUTE_COUNTRY, - state_dataset_targets, -) -from policyengine_simulation_executor.state_datasets import ( - state_dataset_relative_folder, - year_file_reuse_problem, + YearFileBuildResult, + YearFilePlanEntry, ) +from policyengine_simulation_executor.precompute_planning import country_prebuilt if TYPE_CHECKING: - from types import ModuleType - - from microdf import MicroDataFrame - from policyengine.core.scoping_strategy import RowFilterStrategy - - -def build_dataset_impl(bucket: str, expected: DatasetPlanEntry) -> DatasetBuildResult: - """Wave 1: build one single-year dataset and upload it.""" - from policyengine_simulation_executor.artifact_keys import ( # noqa: PLC0415 # resolved per call so tests can patch artifact_keys.collect_dataset_identity - collect_dataset_identity, - ) - from policyengine_simulation_executor.artifact_store import ( # noqa: PLC0415 # resolved per call so tests can patch artifact_store.ArtifactStore - ArtifactStore, - ) - from policyengine_simulation_executor.release_bundle import ( # noqa: PLC0415 # resolved per call so tests can patch release_bundle.get_country_release_bundle - get_country_release_bundle, - ) - from policyengine_simulation_executor.simulation_runtime import ( # noqa: PLC0415 # resolved per call so tests can patch simulation_runtime helpers - _country_module, - resolve_data_folder, - ) - - identity = collect_dataset_identity(PRECOMPUTE_COUNTRY, expected.year) - if identity.store_path != expected.path: - msg = ( - "Planned and in-container dataset identities disagree " - f"({expected.path} != {identity.store_path}); refusing to upload " - "under a mismatched key." - ) - raise RuntimeError(msg) + from policyengine_simulation_executor.stage12_cache.levels import YearFileTarget - data_folder = resolve_data_folder() - country_module = _country_module(PRECOMPUTE_COUNTRY) - started = time.monotonic() - country_module.ensure_datasets( - datasets=[get_country_release_bundle(PRECOMPUTE_COUNTRY).default_dataset], - years=[expected.year], - data_folder=data_folder, - ) - build_seconds = time.monotonic() - started - local_file = Path(data_folder) / identity.filename - if not local_file.exists(): - msg = f"ensure_datasets produced no file at {local_file}" - raise RuntimeError(msg) - uploaded = ArtifactStore(bucket).upload_file(identity.store_path, local_file) - return DatasetBuildResult( - year=expected.year, - path=identity.store_path, - uploaded=uploaded, - build_seconds=round(build_seconds, 1), - size_bytes=local_file.stat().st_size, - ) +def _checked_targets( + year: int, expected: list[YearFilePlanEntry] +) -> list[YearFileTarget]: + """Return the handler's target for each planned entry, after re-deriving its key. - -def _checked_state_targets( - year: int, expected: list[StateDatasetPlanEntry] -) -> dict[str, RowFilterStrategy]: - """Return each planned state's row filter, after re-deriving its key here. - - The planner and this builder run in different containers; both derive a - state's key from the installed bundle. A disagreement means they see + The planner and this builder run in different containers; both derive + each key from the installed bundle. A disagreement means they see different bundles, so nothing is built rather than uploading a file under - a key that does not describe it. A state without a row filter is refused - here too, before anything is prepared. + a key that does not describe it. """ - from policyengine_simulation_executor.artifact_keys import ( # noqa: PLC0415 # resolved per call so tests can patch artifact_keys.collect_state_dataset_identity - collect_state_dataset_identity, + from policyengine_simulation_executor.artifact_keys import ( # noqa: PLC0415 # resolved per call so tests can patch artifact_keys.year_file_identity + year_file_identity, ) - targets = {target.region: target for target in state_dataset_targets()} - datasets = set() + countries = {entry.country for entry in expected} + levels = {entry.level for entry in expected} + datasets = {entry.dataset for entry in expected} + if len(countries) > 1 or len(levels) > 1 or len(datasets) > 1: + msg = ( + "One year-file build covers one country, level and dataset, not " + f"{sorted(countries)}, {sorted(levels)}, {sorted(datasets)}" + ) + raise ValueError(msg) + (country,), (level,) = countries, levels + handler = country_prebuilt(country).handlers[level] + targets_by_key = { + (target.dataset, None if target.subset is None else target.subset.code): target + for target in handler.year_file_targets(year) + } + targets = [] for entry in expected: if entry.year != year: - msg = ( - f"State dataset entry for {entry.state_code} is for year " - f"{entry.year}, not {year}" - ) + msg = f"Year file entry {entry.path} is for {entry.year}, not {year}" raise ValueError(msg) - target = targets.get(entry.region) + target = targets_by_key.get((entry.dataset, entry.subset_code)) if target 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" + msg = ( + f"No {country} {level} year file target for {entry.dataset} " + f"{entry.subset_code or 'all'} in this container" + ) raise RuntimeError(msg) - identity = collect_state_dataset_identity( - PRECOMPUTE_COUNTRY, - year, - dataset=target.dataset, - state_code=target.state_code, - state_fips=target.state_fips, - filter_variable=target.filter_variable, - ) - folder = state_dataset_relative_folder(target.dataset, target.state_code) - if (identity.store_path, identity.filename, folder) != ( + identity = year_file_identity(target) + if (identity.store_path, identity.filename, identity.folder) != ( entry.path, entry.filename, entry.folder, ): msg = ( - f"Planned and in-container identities of {entry.region} {year} " - f"disagree ({entry.path} != {identity.store_path}); refusing to " - "build under a mismatched key." + f"Planned and in-container identities of {entry.dataset} " + f"{entry.subset_code or 'all'} {year} disagree ({entry.path} != " + f"{identity.store_path}); refusing to build under a mismatched key." ) 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 + targets.append(target) + return targets -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 household whose code names a district of another state would - be missing from that district's results, so the build stops instead. A - code that names no district, such as an unassigned 0, matches no district - request on either path 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) - - -def build_state_datasets_impl( +def build_year_files_impl( bucket: str, year: int, - expected: list[StateDatasetPlanEntry], + expected: list[YearFilePlanEntry], *, work_folder: Path | None = None, -) -> list[StateDatasetBuildResult]: - """Build, check and upload one year's per-state datasets. +) -> list[YearFileBuildResult]: + """Build, check and upload one year's year files of one level and dataset. - Prepares 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 level's handler writes the files; each is uploaded write-once under + its planned key, with its SHA-256 and size recorded on the stored object. """ - 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 - from policyengine_simulation_executor.artifact_store import ( # noqa: PLC0415 # resolved per call so tests can patch artifact_store.ArtifactStore ArtifactStore, ) - from policyengine_simulation_executor.simulation_runtime import ( # noqa: PLC0415 # resolved per call so tests can patch simulation_runtime helpers - _country_module, - ) if not expected: return [] started = time.monotonic() - strategies = _checked_state_targets(year, expected) - dataset = expected[0].dataset + targets = _checked_targets(year, expected) + handler = country_prebuilt(expected[0].country).handlers[expected[0].level] work_folder = work_folder or Path( - tempfile.mkdtemp(prefix="policyengine-state-datasets-") - ) - source_folder = str(work_folder / "source") - country_module = _country_module(PRECOMPUTE_COUNTRY) - - # 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) + tempfile.mkdtemp(prefix="policyengine-year-files-") ) + written = handler.write_year_files(year, targets, work_folder) store = ArtifactStore(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}" + for entry, target in zip(expected, targets, strict=True): + local_file = written.get(target) + if local_file is None or not local_file.exists(): + msg = f"The {entry.level} handler wrote no file for {entry.path}" raise RuntimeError(msg) results.append( - StateDatasetBuildResult( + YearFileBuildResult( year=year, - state_code=entry.state_code, path=entry.path, uploaded=store.upload_file(entry.path, local_file), size_bytes=local_file.stat().st_size, diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute_models.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute_models.py index 282639668..0479df3e6 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute_models.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute_models.py @@ -12,22 +12,26 @@ worker fails loudly at the edge instead of surfacing as a KeyError mid-computation. -Wire-compatibility constraint: ``ArtifactManifest.canonical_payload()`` -must keep producing the exact key/value shape the store already holds — -the manifest is content-addressed, so any change here rotates published -digests. A regression test locks the digest of a fixed payload. +Plans are not stored, so their shape may change freely. The manifest is: +``ArtifactManifest.canonical_payload()`` is what gets digested and stored, +and the digest names the deployed file set, so any change to its shape +rotates published digests. """ from __future__ import annotations -from typing import Annotated, Any, Literal, Protocol +from typing import Any, Literal, Protocol from pydantic import BaseModel, ConfigDict, Field +from policyengine_simulation_executor.stage12_cache.levels import DatasetLevel + # Mirrors baseline_artifacts.OUTCOME_*; the artifact outcome a worker # observed when ensuring a baseline. ArtifactOutcome = Literal["hit", "incomplete", "miss"] +MANIFEST_SCHEMA = "mf2" + class _StrictModel(BaseModel): model_config = ConfigDict(extra="forbid") @@ -36,122 +40,136 @@ class _StrictModel(BaseModel): class BundleVersionIdentity(_StrictModel): """The version identity of the installed bundle a plan was made for. - Travels under the frozen wire key ``receipt``, but is deliberately NOT - the install receipt file (``.policyengine-bundle-receipt.json``): that + Travels under the wire key ``receipt``, but is deliberately NOT the + install receipt file (``.policyengine-bundle-receipt.json``): that carries per-dataset content hashes, which live inside the artifact - digests here, not in this version tuple. + digests here, not in this version tuple. The image's download step + refuses a manifest whose versions differ from the image's. """ policyengine_version: str + policyengine_core_version: str model_version: str data_version: str data_artifact_revision: str default_dataset: str -class DatasetPlanEntry(_StrictModel): - """One single-year dataset artifact: identity plus store presence.""" +class YearFilePlanEntry(_StrictModel): + """One year file: its level, identity, image folder and store presence. + + ``region`` and ``subset_code`` name a per-subset file's rows (``state/ca``, + ``CA``); both are None for a whole dataset's year file. + """ + country: str + level: DatasetLevel year: int + dataset: str + region: str | None + subset_code: str | None digest: str path: str filename: str + folder: str exists: bool -class StateDatasetPlanEntry(_StrictModel): - """One state's year file filtered from a regional dataset: identity plus presence. +class BaselinePlanEntry(_StrictModel): + """One current-law baseline: the request it answers and the year file it reads. - ``folder`` is where the image places the file, relative to its data folder; - every state's file has the same ``filename``. + ``request`` is the synthetic request the runtime would receive. + ``year_file_path`` and ``year_file_filename`` name the year file it runs on, + which the builder downloads into ``folder`` when it is missing; the + baseline lands beside it. """ + country: str + level: DatasetLevel year: int - state_code: str region: str - dataset: str + label: str + request: dict[str, Any] + year_file_path: str + year_file_filename: str + folder: str digest: str path: str - filename: str - folder: str + simulation_id: str + storage_id: str exists: bool -class BaselinePlanEntry(_StrictModel): - """One cohort baseline artifact: identity plus store presence.""" +class SourceFilePlanEntry(_StrictModel): + """A source dataset copied into the image as is, addressed by its certified hash. - year: int - group: list[str] - region: str + ``digest`` is its ``sf1`` identity digest, which the manifest records. + """ + + country: str + level: DatasetLevel + dataset: str digest: str + sha256: str path: str - simulation_id: str + filename: str + folder: str exists: bool class PrecomputePlan(_StrictModel): - """Everything the store should contain for the installed bundle.""" + """Everything the store should contain for one country's installed bundle.""" - datasets: list[DatasetPlanEntry] + country: str + year_files: list[YearFilePlanEntry] baselines: list[BaselinePlanEntry] + source_files: list[SourceFilePlanEntry] = Field(default_factory=list) receipt: BundleVersionIdentity - state_datasets: list[StateDatasetPlanEntry] = Field(default_factory=list) class WorkSelection(_StrictModel): """The subset of a plan that actually needs computing.""" - datasets: list[DatasetPlanEntry] + year_files: list[YearFilePlanEntry] baselines: list[BaselinePlanEntry] - state_datasets: list[StateDatasetPlanEntry] = Field(default_factory=list) + source_files: list[SourceFilePlanEntry] = Field(default_factory=list) -class ManifestArtifact(_StrictModel): - """One artifact the deploy image must fetch into its data folder.""" +class ManifestEntry(_StrictModel): + """One file the deploy image must fetch into its prebuilt folder. - type: Literal["dataset", "baseline"] - path: str - filename: str - year: int - digest: str - - -class StateDatasetArtifact(_StrictModel): - """One state's year file, which the image fetches into the state's ``folder``. - - Its own model, rather than optional fields on ``ManifestArtifact``, so the - dataset and baseline entries keep exactly their published wire shape. + ``sha256`` and ``size_bytes`` are the stored object's, which the download + step checks. ``year`` is None for a source file, and ``region`` for a + whole dataset's year file. """ - type: Literal["state_dataset"] + kind: Literal["year_file", "baseline", "source_file"] + level: DatasetLevel + region: str | None path: str filename: str folder: str - state_code: str - year: int + year: int | None digest: str - - -ManifestEntry = Annotated[ - ManifestArtifact | StateDatasetArtifact, Field(discriminator="type") -] + sha256: str + size_bytes: int class ArtifactManifest(_StrictModel): - """The published deploy manifest (content-addressed in the store).""" + """One country's published deploy manifest (content-addressed in the store).""" model_config = ConfigDict(extra="forbid", populate_by_name=True) # "schema" is the wire key; the Python name avoids shadowing # BaseModel's deprecated .schema attribute. - manifest_schema: str = Field(alias="schema") + manifest_schema: Literal["mf2"] = Field(alias="schema") country: str receipt: BundleVersionIdentity artifacts: list[ManifestEntry] def canonical_payload(self) -> dict[str, Any]: """Return the exact dict that gets digested and stored, keyed by wire alias.""" - return self.model_dump(by_alias=True) + return self.model_dump(by_alias=True, mode="json") class DeployedMarker(_StrictModel): @@ -177,25 +195,14 @@ class DeployedMarker(_StrictModel): deployed_at: str -class DatasetBuildResult(_StrictModel): - """Result of one dataset build; ``uploaded`` is False if the key existed.""" - - year: int - path: str - uploaded: bool - build_seconds: float - size_bytes: int - - -class StateDatasetBuildResult(_StrictModel): - """Result of one state's dataset build; ``uploaded`` is False if the key existed. +class YearFileBuildResult(_StrictModel): + """Result of one year file's build; ``uploaded`` is False if the key existed. - ``build_seconds`` is how long the year's build had run when this state's - file was uploaded, so the last result of a build gives its whole duration. + ``build_seconds`` is how long the build had run when this file was + uploaded, so the last result of a build gives its whole duration. """ year: int - state_code: str path: str uploaded: bool size_bytes: int @@ -210,7 +217,7 @@ class BaselineComputeResult(_StrictModel): """ year: int - group: list[str] + label: str simulation_id: str outcome: ArtifactOutcome | None uploaded: bool diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute_planning.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute_planning.py index bafb11cd2..a058b0bd8 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute_planning.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/precompute_planning.py @@ -1,271 +1,231 @@ -"""Plan the artifact precompute: cohorts, state dataset targets and the work to do.""" +"""Plan one country's precompute through its level handlers. + +The country's settings (``stage12_cache.levels.prebuilt_for``) name the years +and the levels whose year files and baselines are built. Each level's handler +returns its targets for a year; this module keys each target with the +run_simulation app's identities and checks the store for it. +""" from __future__ import annotations -from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING from policyengine_simulation_executor.precompute_models import ( BaselinePlanEntry, BundleVersionIdentity, - DatasetPlanEntry, PrecomputePlan, - StateDatasetPlanEntry, + SourceFilePlanEntry, WorkSelection, + YearFilePlanEntry, ) -from policyengine_simulation_executor.state_datasets import ( - state_dataset_relative_folder, +from policyengine_simulation_executor.stage12_cache.levels import ( + BaselineTarget, + CountryPrebuilt, + prebuilt_for, ) if TYPE_CHECKING: - from types import ModuleType - - from policyengine.core.scoping_strategy import RowFilterStrategy - - from policyengine_simulation_executor.artifact_keys import BaselineArtifactIdentity - from policyengine_simulation_executor.simulation_runtime import RegionResolution + from policyengine_simulation_executor.artifact_keys import BaselineIdentity + from policyengine_simulation_executor.artifact_store import ArtifactStore -PRECOMPUTE_COUNTRY = "us" -# The user-facing priority order (2026 first); with parallel waves it only -# orders spawn submission, but keep it intentional. -PRECOMPUTE_YEARS = [2026, 2027, 2025] +def country_prebuilt(country: str) -> CountryPrebuilt: + """Return a country's prebuilt-file settings; ``ValueError`` when it has none.""" + prebuilt = prebuilt_for(country) + if prebuilt is None: + msg = f"No prebuilt-file settings for country {country!r}" + raise ValueError(msg) + return prebuilt -def cohort_params(year: int, group: list[str]) -> dict: - """Return the synthetic request a segmented-national child would receive.""" - return { - "country": PRECOMPUTE_COUNTRY, - "scope": "macro", - "region_group": list(group), - "time_period": year, - } +def baseline_target_identity(target: BaselineTarget) -> BaselineIdentity | None: + """Return a baseline target's identity, derived as a run of its request is. -def cohort_resolution( - year: int, group: list[str] -) -> tuple[dict[str, Any], ModuleType, RegionResolution]: - """Cohort request params, country module, and region resolution. - - The planner's identity (``cohort_identity``) and the worker's - simulation (``_prepare_cohort_baseline``) must derive from ONE - resolution or the in-container id checks abort the run; sharing this - prologue removes the drift surface. + The request goes through the runtime's own region and dataset resolution + and ``qualifying_baseline_identity``, so the writer and the reader cannot + disagree by construction. """ - from policyengine_simulation_executor.simulation_runtime import ( # noqa: PLC0415 # resolved per call so tests can patch simulation_runtime helpers - _country_module, - resolve_region, - ) - - params = cohort_params(year, group) - country_module = _country_module(PRECOMPUTE_COUNTRY) - resolution = resolve_region( - country_module=country_module, - country=PRECOMPUTE_COUNTRY, - params=params, - ) - return params, country_module, resolution - - -def cohort_identity(year: int, group: list[str]) -> BaselineArtifactIdentity: - """Identity via the executor's own resolution path (writer==reader).""" from policyengine_simulation_executor.baseline_artifacts import ( BaselineIdentityRequest, qualifying_baseline_identity, ) from policyengine_simulation_executor.simulation_runtime import ( # noqa: PLC0415 # resolved per call so tests can patch simulation_runtime helpers + _country_module, _resolve_dataset_selection, + resolve_region, ) - params, _, resolution = cohort_resolution(year, group) - dataset_selection = _resolve_dataset_selection(params, region_resolution=resolution) - identity = qualifying_baseline_identity( + params = dict(target.request) + region = resolve_region( + country_module=_country_module(target.country), + country=target.country, + params=params, + ) + dataset = _resolve_dataset_selection(params, region_resolution=region) + return qualifying_baseline_identity( BaselineIdentityRequest( params, - country=PRECOMPUTE_COUNTRY, - dataset_is_default=dataset_selection.is_default, + country=target.country, + dataset=dataset, policy=None, - region_code=resolution.code, - scoping_strategy=resolution.scoping_strategy, - year=year, + region_code=region.code, + scoping_strategy=region.scoping_strategy, + year=target.year, + state_code=region.state_code, ) ) - if identity is None: - msg = ( - f"Cohort request for year {year} group {group} does not qualify " - "for a deterministic baseline id — writer and reader predicates " - "have diverged." - ) - raise RuntimeError(msg) - return identity - - -@dataclass(frozen=True) -class StateDatasetTarget: - """A US state whose requests load a non-default dataset, and its row filter. - - The precompute 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, so a baked file holds exactly the rows the request - would keep. - """ - - region: str - state_code: str - state_fips: int - filter_variable: str - dataset: str - scoping_strategy: RowFilterStrategy | None = field( - default=None, compare=False, repr=False - ) - - -def state_dataset_targets() -> list[StateDatasetTarget]: - """Return every US state region that loads a non-default dataset, by state code. - - Each state is resolved exactly as a request for it is (``resolve_region`` - then ``_resolve_dataset_selection``), so a bundle that sends states back to - the default dataset gets no state files. - """ - from policyengine_simulation_executor.simulation_runtime import ( # noqa: PLC0415 # resolved per call so tests can patch simulation_runtime helpers - _country_module, - _resolve_dataset_selection, - resolve_region, - ) - - country_module = _country_module(PRECOMPUTE_COUNTRY) - targets = [] - for region in country_module.model.region_registry.get_by_type("state"): - params = { - "country": PRECOMPUTE_COUNTRY, - "region": region.code, - "time_period": PRECOMPUTE_YEARS[0], - } - resolution = resolve_region( - country_module=country_module, country=PRECOMPUTE_COUNTRY, params=params - ) - 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, - ) - ) - return sorted(targets, key=lambda target: target.state_code) def select_work(plan: PrecomputePlan, *, force: bool) -> WorkSelection: """Which plan entries need computing.""" return WorkSelection( - datasets=[entry for entry in plan.datasets if force or not entry.exists], + year_files=[entry for entry in plan.year_files if force or not entry.exists], baselines=[entry for entry in plan.baselines if force or not entry.exists], - state_datasets=[ - entry for entry in plan.state_datasets if force or not entry.exists + source_files=[ + entry for entry in plan.source_files if force or not entry.exists ], ) -def plan_artifacts_impl(bucket: str) -> PrecomputePlan: - """Compute every expected artifact identity and its store presence.""" - from policyengine_simulation_executor.artifact_keys import ( # noqa: PLC0415 # resolved per call so tests can patch artifact_keys.collect_dataset_identity - collect_dataset_identity, - collect_state_dataset_identity, - ) - from policyengine_simulation_executor.artifact_store import ( # noqa: PLC0415 # resolved per call so tests can patch artifact_store.ArtifactStore - ArtifactStore, - ) - from policyengine_simulation_executor.national_partition import ( # noqa: PLC0415 # resolved per call so tests can patch national_partition.national_region_groups - national_region_groups, - ) - from policyengine_simulation_executor.release_bundle import ( # noqa: PLC0415 # resolved per call so tests can patch release_bundle.get_country_release_bundle - get_country_release_bundle, +def _year_file_entries( + prebuilt: CountryPrebuilt, year: int, store: ArtifactStore +) -> list[YearFilePlanEntry]: + from policyengine_simulation_executor.artifact_keys import ( # noqa: PLC0415 # resolved per call so tests can patch artifact_keys + year_file_identity, ) - store = ArtifactStore(bucket) - groups = national_region_groups(PRECOMPUTE_COUNTRY) - if not groups: - msg = f"No national partition for {PRECOMPUTE_COUNTRY!r}" - raise RuntimeError(msg) - - targets = state_dataset_targets() - datasets: list[DatasetPlanEntry] = [] - baselines: list[BaselinePlanEntry] = [] - state_datasets: list[StateDatasetPlanEntry] = [] - for year in PRECOMPUTE_YEARS: - dataset_identity = collect_dataset_identity(PRECOMPUTE_COUNTRY, year) - datasets.append( - DatasetPlanEntry( - year=year, - digest=dataset_identity.digest, - path=dataset_identity.store_path, - filename=dataset_identity.filename, - exists=store.exists(dataset_identity.store_path), + entries = [] + for level in prebuilt.year_file_levels: + for target in prebuilt.handlers[level].year_file_targets(year): + identity = year_file_identity(target) + entries.append( + YearFilePlanEntry( + country=prebuilt.country, + level=target.level, + year=target.year, + dataset=target.dataset, + region=None if target.subset is None else target.subset.region, + subset_code=None if target.subset is None else target.subset.code, + digest=identity.digest, + path=identity.store_path, + filename=identity.filename, + folder=identity.folder, + exists=store.exists(identity.store_path), + ) ) - ) - for group in groups: - identity = cohort_identity(year, group) - baselines.append( + return entries + + +def _baseline_entries( + prebuilt: CountryPrebuilt, year: int, store: ArtifactStore +) -> list[BaselinePlanEntry]: + entries = [] + for level in prebuilt.baseline_levels: + for target in prebuilt.handlers[level].baseline_targets(year): + identity = baseline_target_identity(target) + if identity is None: + msg = ( + f"The {target.country} {target.level} baseline {target.label} " + f"for {year} gets no fixed ID: the writer and reader rules " + "have diverged." + ) + raise RuntimeError(msg) + if identity.year_file.folder != target.year_file.folder: + msg = ( + f"The {target.label} baseline reads {identity.year_file.folder}, " + f"not its target's {target.year_file.folder}" + ) + raise RuntimeError(msg) + entries.append( BaselinePlanEntry( - year=year, - group=list(group), + country=prebuilt.country, + level=target.level, + year=target.year, region=identity.region, + label=target.label, + request=dict(target.request), + year_file_path=identity.year_file.store_path, + year_file_filename=identity.year_file.filename, + folder=identity.year_file.folder, digest=identity.digest, path=identity.store_path, simulation_id=identity.simulation_id, + storage_id=identity.storage_id, exists=store.exists(identity.store_path), ) ) - for target in targets: - state_identity = collect_state_dataset_identity( - PRECOMPUTE_COUNTRY, - 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, + return entries + + +def _source_file_entries( + prebuilt: CountryPrebuilt, store: ArtifactStore +) -> list[SourceFilePlanEntry]: + from policyengine_simulation_executor.artifact_keys import ( # noqa: PLC0415 # resolved per call so tests can patch artifact_keys + source_file_identity, + ) + + entries = [] + levels = dict.fromkeys((*prebuilt.year_file_levels, *prebuilt.baseline_levels)) + for level in levels: + for target in prebuilt.handlers[level].source_file_targets(): + identity = source_file_identity(target) + entries.append( + SourceFilePlanEntry( + country=prebuilt.country, + level=target.level, 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), + digest=identity.digest, + sha256=identity.dataset_sha256, + path=identity.store_path, + filename=identity.filename, + folder=identity.folder, + exists=store.exists(identity.store_path), ) ) + return entries + + +def _receipt(country: str) -> BundleVersionIdentity: + from policyengine_simulation_executor import ( # noqa: PLC0415 # resolved per call so tests can patch artifact_keys._installed_package_versions + artifact_keys, + ) + from policyengine_simulation_executor.release_bundle import ( # noqa: PLC0415 # resolved per call so tests can patch release_bundle.get_country_release_bundle + get_country_release_bundle, + ) - bundle = get_country_release_bundle(PRECOMPUTE_COUNTRY) - receipt = BundleVersionIdentity( + bundle = get_country_release_bundle(country) + packages = artifact_keys._installed_package_versions(country) # noqa: SLF001 # the one installed-package reader, shared with the year-file keys + return BundleVersionIdentity( policyengine_version=bundle.policyengine_version, + policyengine_core_version=packages["policyengine-core"], model_version=bundle.model_version, data_version=bundle.data_version, data_artifact_revision=bundle.data_artifact_revision, default_dataset=bundle.default_dataset, ) + + +def plan_artifacts_impl(bucket: str, country: str = "us") -> PrecomputePlan: + """Compute every file one country's precompute builds, and its store presence. + + Year-major: for each year, the year files of each level in the settings' + order, then the baselines of each level. Source files follow. + """ + from policyengine_simulation_executor.artifact_store import ( # noqa: PLC0415 # resolved per call so tests can patch artifact_store.ArtifactStore + ArtifactStore, + ) + + prebuilt = country_prebuilt(country) + store = ArtifactStore(bucket) + year_files: list[YearFilePlanEntry] = [] + baselines: list[BaselinePlanEntry] = [] + for year in prebuilt.years: + year_files += _year_file_entries(prebuilt, year, store) + baselines += _baseline_entries(prebuilt, year, store) return PrecomputePlan( - datasets=datasets, + country=prebuilt.country, + year_files=year_files, baselines=baselines, - receipt=receipt, - state_datasets=state_datasets, + source_files=_source_file_entries(prebuilt, store), + receipt=_receipt(prebuilt.country), ) diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/simulation_runtime.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/simulation_runtime.py index 2c80fc062..709711dfe 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/simulation_runtime.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/simulation_runtime.py @@ -22,7 +22,6 @@ from policyengine_simulation_observability.stages import ANNUAL_IMPACT_STAGES, Stage from policyengine_simulation_observability.telemetry import split_internal_payload -from policyengine_simulation_executor import state_datasets from policyengine_simulation_executor.dataset_download_retry import ( load_with_download_retry, ) @@ -51,6 +50,7 @@ from policyengine_simulation_executor.simulation_output_local_areas import ( LocalAreaBreakdownBuilder, ) +from policyengine_simulation_executor.stage12_cache import levels if TYPE_CHECKING: from types import ModuleType @@ -224,6 +224,22 @@ def _manifest_dataset_revision(country: str, name: str) -> str | None: return revision if isinstance(revision, str) and revision else None +def _prebuilt_folder( + country: str, + region: RegionResolution, + selection: DatasetSelection, + year: int, +) -> levels.PrebuiltFolder | None: + """Return the image's prebuilt folder holding this run's year file, or None. + + None keeps the folder ``_load_dataset`` would otherwise use. + """ + return levels.prebuilt_dataset_folder( + levels.RunScope(country=country, year=year, region=region, dataset=selection), + resolve_data_folder(), + ) + + def _load_dataset( params: dict[str, Any], *, @@ -324,11 +340,12 @@ def _build_simulation( BaselineIdentityRequest( params, country=country, - dataset_is_default=dataset_selection.is_default, + dataset=dataset_selection, policy=runtime_policy, region_code=region.code, scoping_strategy=scoping_strategy, year=parse_year(params), + state_code=region.state_code, ) ) if simulation_id is not None: @@ -392,8 +409,14 @@ def _uk_area_simulations( with runtime.span( ANNUAL_IMPACT_STAGES.name(Stage.DATASET_LOAD), attributes=area_role ): + prebuilt = _prebuilt_folder( + params.get("country", "uk").lower(), region, selection, parse_year(params) + ) dataset = _load_dataset_retrying_downloads( - params, selection=selection, country_module=country_module + params, + selection=selection, + country_module=country_module, + data_folder=None if prebuilt is None else prebuilt.folder, ) local_authority_metadata = detect_uk_area_dataset_metadata( dataset, dataset_name=selection.name @@ -529,26 +552,25 @@ def _run_simulation_impl_core( simulation_params, region_resolution=region_resolution ) with runtime.span(ANNUAL_IMPACT_STAGES.name(Stage.DATASET_LOAD)): - baked_folder = state_datasets.baked_state_data_folder( - country=country, - selection=dataset_selection, - state_code=region_resolution.state_code, - year=parse_year(simulation_params), - data_folder=resolve_data_folder(), + prebuilt = _prebuilt_folder( + country, + region_resolution, + dataset_selection, + parse_year(simulation_params), ) if not dataset_selection.is_default: runtime.set_context( dataset_source=( - state_datasets.BAKED_STATE_DATASET_SOURCE - if baked_folder - else state_datasets.ON_DEMAND_DATASET_SOURCE + prebuilt.dataset_source + if prebuilt is not None and prebuilt.dataset_source + else levels.ON_DEMAND_DATASET_SOURCE ) ) dataset = _load_dataset_retrying_downloads( simulation_params, selection=dataset_selection, country_module=country_module, - data_folder=baked_folder, + data_folder=None if prebuilt is None else prebuilt.folder, ) from policyengine_simulation_executor.uk_local_authority_metadata import ( # noqa: PLC0415 # the UK metadata module is not loaded at import; loaded per call detect_uk_run_dataset_metadata, diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/levels.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/levels.py new file mode 100644 index 000000000..66ce6ff83 --- /dev/null +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/levels.py @@ -0,0 +1,319 @@ +"""Prebuilt year files and baselines, by country and dataset level. + +A dataset level names one kind of run by the households it simulates: a US +national, group-of-states, state or congressional-district run, or a UK +national, nation or local-area run. One handler per country and level says +which year files and current-law baselines the precompute builds for a year, +how to write those year files, which year file a run reads, which prebuilt +folder holds it, and whether the run's current-law baseline gets a fixed ID. +Each country's settings say which years and levels are precomputed. + +The handlers never build a key, touch the store or read a manifest: each app +turns a ``YearFileTarget`` into its own identity. The run_simulation app +imports these modules; Stage 12 modules must not import the run_simulation +feature modules (``tests/test_stage12_segmentation_foundation.py``), so +nothing here does either. + +Every prebuilt file lands under the image data folder at +``prebuilt////``: year files as +``_year_.h5`` and baselines beside the year file they were +computed on, which is where .py's ``Simulation.ensure()`` looks for them. +""" + +from __future__ import annotations + +import logging +from dataclasses import dataclass, field +from enum import StrEnum +from typing import TYPE_CHECKING, Any, Protocol + +if TYPE_CHECKING: + from collections.abc import Callable, Mapping, Sequence + from pathlib import Path + + from policyengine.core import Simulation + from policyengine.core.scoping_strategy import RowFilterStrategy + + from policyengine_simulation_executor.region_resolution import RegionResolution + from policyengine_simulation_executor.simulation_runtime import DatasetSelection + +logger = logging.getLogger(__name__) + +PREBUILT_DIRECTORY = "prebuilt" +WHOLE_DATASET_FOLDER = "all" +# Values of the run's ``dataset_source`` attribute when its region loads a +# non-default dataset: read from the image's prebuilt file, or prepared from +# the full dataset during the request. +BAKED_STATE_DATASET_SOURCE = "baked_state" +ON_DEMAND_DATASET_SOURCE = "on_demand" + + +class DatasetLevel(StrEnum): + """The kinds of run a prebuilt file can serve, named by the households simulated.""" + + NATIONAL = "national" + STATE_GROUP = "state_group" + STATE = "state" + DISTRICT = "district" + NATION = "nation" + LOCAL_AREA = "local_area" + + +def prebuilt_folder(country: str, dataset: str, subset_code: str | None = None) -> str: + """Return a prebuilt folder relative to the image data folder.""" + return ( + f"{PREBUILT_DIRECTORY}/{country.lower()}/{dataset}/" + f"{subset_code or WHOLE_DATASET_FOLDER}" + ) + + +@dataclass(frozen=True) +class SubsetFilter: + """The households a subset's year file keeps: rows where ``variable`` is ``value``. + + ``code`` names the subset's image folder, such as ``CA``. + """ + + region: str + code: str + variable: str + value: int + scoping_strategy: RowFilterStrategy = field(compare=False, repr=False) + + +@dataclass(frozen=True) +class YearFileTarget: + """One year file a level owns: a dataset's whole year, or one subset's rows of it. + + ``folder`` is where the image keeps it, relative to the data folder. + """ + + country: str + level: DatasetLevel + dataset: str + year: int + subset: SubsetFilter | None + folder: str + + +@dataclass(frozen=True) +class RunScope: + """The resolved facts of one run that the handlers look at.""" + + country: str + year: int + region: RegionResolution + dataset: DatasetSelection + + +@dataclass(frozen=True) +class BaselineScope: + """The region label and scoping key a fixed baseline ID is computed from. + + ``scope_key`` is the scoping strategy's ``cache_key``; None for a run of a + whole dataset. + """ + + region: str + scope_key: str | None + + +@dataclass(frozen=True) +class BaselineTarget: + """One current-law baseline the precompute builds. + + ``request`` is the request the runtime would receive for it, with scope + ``macro`` and no policy; ``year_file`` is the file it runs on, and so the + folder it lands in. + """ + + country: str + level: DatasetLevel + year: int + request: Mapping[str, Any] = field(compare=False) + year_file: YearFileTarget + label: str + + +@dataclass(frozen=True) +class SourceFileTarget: + """A bundle dataset the image holds as is, in ``folder``.""" + + country: str + level: DatasetLevel + dataset: str + folder: str + + +@dataclass(frozen=True) +class PrebuiltFolder: + """The prebuilt folder a run reads, and the ``dataset_source`` it reports. + + ``dataset_source`` is None for a run of the default dataset, which + reports none. + """ + + folder: str + dataset_source: str | None + + +class LevelHandler(Protocol): + """What one country and dataset level builds, and what its runs read.""" + + @property + def country(self) -> str: + """The country, such as ``us``.""" + ... + + @property + def level(self) -> DatasetLevel: + """The dataset level this handler covers.""" + ... + + @property + def baked_dataset_source(self) -> str | None: + """The ``dataset_source`` a run reports when it reads a prebuilt file.""" + ... + + def year_file_targets(self, year: int) -> Sequence[YearFileTarget]: + """Return the year files this level owns for ``year``.""" + ... + + def baseline_targets(self, year: int) -> Sequence[BaselineTarget]: + """Return the current-law baselines this level precomputes for ``year``.""" + ... + + def source_file_targets(self) -> Sequence[SourceFileTarget]: + """Return the bundle datasets this level copies into the image.""" + ... + + def write_year_files( + self, year: int, targets: Sequence[YearFileTarget], work_folder: Path + ) -> Mapping[YearFileTarget, Path]: + """Write ``targets`` (all this level's, for ``year``) and return each file.""" + ... + + def year_file_for(self, run: RunScope) -> YearFileTarget | None: + """Return the year file ``run`` reads, or None when none applies.""" + ... + + def baked_data_folder(self, run: RunScope, data_folder: str) -> str | None: + """Return the prebuilt folder holding ``run``'s usable year file, or None.""" + ... + + def baseline_scope(self, run: RunScope) -> BaselineScope | None: + """Return the scope of ``run``'s fixed baseline ID, or None for a random ID.""" + ... + + +@dataclass(frozen=True) +class CountryPrebuilt: + """One country's handlers and the years and levels its precompute builds. + + ``years`` are in submission order. ``classify`` names a run's level and + ``baseline_output_preparer`` adds the output variables a precomputed + baseline must carry. + """ + + country: str + years: tuple[int, ...] + year_file_levels: tuple[DatasetLevel, ...] + baseline_levels: tuple[DatasetLevel, ...] + handlers: Mapping[DatasetLevel, LevelHandler] + classify: Callable[[RunScope], DatasetLevel | None] = field(repr=False) + baseline_output_preparer: Callable[[Simulation], None] = field(repr=False) + + def level_of(self, run: RunScope) -> DatasetLevel | None: + """Return ``run``'s level, or None when no handler covers it. + + Never raises: it runs on the request path, where a failure to + classify means only that nothing prebuilt applies. + """ + try: + level = self.classify(run) + except Exception: # noqa: BLE001 # the request path never fails over a prebuilt-file lookup; the failure is logged + logger.warning( + "Could not name the dataset level of %s region %s; reading no " + "prebuilt file", + run.country, + run.region.code, + exc_info=True, + ) + return None + return level if level in self.handlers else None + + def handler_for_run(self, run: RunScope) -> LevelHandler | None: + """Return the handler of ``run``'s level, or None.""" + level = self.level_of(run) + return None if level is None else self.handlers[level] + + def prepare_baseline_outputs(self, baseline: Simulation) -> None: + """Add the output variables a precomputed baseline must carry.""" + self.baseline_output_preparer(baseline) + + +def prebuilt_for(country: str) -> CountryPrebuilt | None: + """Return a country's prebuilt-file settings, or None for another country.""" + normalized = country.lower() + if normalized == "us": + from policyengine_simulation_executor.stage12_cache import ( # noqa: PLC0415 # the US handlers load the US registry helpers; loaded per call + levels_us, + ) + + return levels_us.us_prebuilt() + if normalized == "uk": + from policyengine_simulation_executor.stage12_cache import ( # noqa: PLC0415 # the UK handlers load the UK metadata helpers; loaded per call + levels_uk, + ) + + return levels_uk.uk_prebuilt() + return None + + +def handler_for(country: str, level: DatasetLevel) -> LevelHandler: + """Return one country's handler for ``level``; ``KeyError`` when it has none.""" + prebuilt = prebuilt_for(country) + if prebuilt is None: + raise KeyError(country) + return prebuilt.handlers[level] + + +def year_file_name(target: YearFileTarget) -> str: + """Return the basename .py's ``ensure_datasets`` resolves for a year file.""" + from policyengine.provenance.manifest import ( + dataset_logical_name, + resolve_dataset_reference, + ) + + stem = dataset_logical_name( + resolve_dataset_reference(target.country, target.dataset) + ) + return f"{stem}_year_{target.year}.h5" + + +def prebuilt_dataset_folder(run: RunScope, data_folder: str) -> PrebuiltFolder | None: + """Return the prebuilt folder ``run`` reads its year file from, or None. + + None, for a run no handler covers, a year file the image lacks or one .py + would not reuse, keeps today's folders: the data folder's root for the + default dataset and a temporary folder for any other. Never raises, so a + lookup failure costs a dataset build, never a request. + """ + try: + prebuilt = prebuilt_for(run.country) + handler = None if prebuilt is None else prebuilt.handler_for_run(run) + folder = ( + None if handler is None else handler.baked_data_folder(run, data_folder) + ) + except Exception: # noqa: BLE001 # the request path never fails over a prebuilt-file lookup; the failure is logged + logger.warning( + "Could not look up the prebuilt year file of %s region %s; " + "preparing the dataset instead", + run.country, + run.region.code, + exc_info=True, + ) + return None + if handler is None or folder is None: + return None + return PrebuiltFolder(folder=folder, dataset_source=handler.baked_dataset_source) diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/levels_uk.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/levels_uk.py new file mode 100644 index 000000000..bc42af07f --- /dev/null +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/levels_uk.py @@ -0,0 +1,184 @@ +"""The UK level handlers: national, nation and local-area runs. + +Nothing UK is prebuilt yet, so every UK handler builds nothing and finds no +prebuilt folder. UK-wide runs keep the fixed baseline ID they have today; 2.2's +tasks add the UK years, year files and baselines through these handlers. +""" + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING + +from policyengine.core.scoping_strategy import RegionGroupStrategy + +from policyengine_simulation_executor.stage12_cache.levels import ( + BaselineScope, + BaselineTarget, + CountryPrebuilt, + DatasetLevel, + RunScope, + SourceFileTarget, + YearFileTarget, + prebuilt_folder, +) + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + from pathlib import Path + + from policyengine.core import Simulation + +logger = logging.getLogger(__name__) + +UK = "uk" +_NATION_PREFIX = "country/" + + +def _whole_dataset_year_file( + level: DatasetLevel, year: int, dataset: str +) -> YearFileTarget: + return YearFileTarget( + country=UK, + level=level, + dataset=dataset, + year=year, + subset=None, + folder=prebuilt_folder(UK, dataset), + ) + + +class _UkLevel: + """What every UK level shares today: nothing built, nothing prebuilt.""" + + country = UK + level: DatasetLevel + baked_dataset_source: str | None = None + + def year_file_targets(self, year: int) -> Sequence[YearFileTarget]: # noqa: ARG002 # no UK year file is prebuilt yet + """Return no year files.""" + return [] + + def baseline_targets(self, year: int) -> Sequence[BaselineTarget]: # noqa: ARG002 # no UK baseline is precomputed yet + """Return no baselines.""" + return [] + + def source_file_targets(self) -> Sequence[SourceFileTarget]: + """Return no source files.""" + return [] + + def write_year_files( + self, + year: int, # noqa: ARG002 # the protocol's signature + targets: Sequence[YearFileTarget], + work_folder: Path, # noqa: ARG002 # the protocol's signature + ) -> Mapping[YearFileTarget, Path]: + """Refuse targets: no UK year file is built yet.""" + if targets: + msg = f"The UK {self.level} level builds no year files yet" + raise ValueError(msg) + return {} + + def year_file_for(self, run: RunScope) -> YearFileTarget | None: + """Return the default dataset's year file, which UK and nation runs read.""" + if not run.dataset.is_default: + return None + return _whole_dataset_year_file( + DatasetLevel.NATIONAL, run.year, run.dataset.name + ) + + def baked_data_folder(self, run: RunScope, data_folder: str) -> str | None: # noqa: ARG002 # no UK file is prebuilt yet + """Return no folder: no UK file is prebuilt.""" + return None + + def baseline_scope(self, run: RunScope) -> BaselineScope | None: # noqa: ARG002 # overridden by the national level + """Return no scope: these baselines get random IDs.""" + return None + + +class UkNationalHandler(_UkLevel): + """A UK-wide run, or a run over a group of nations, on the default dataset.""" + + level = DatasetLevel.NATIONAL + + def baseline_scope(self, run: RunScope) -> BaselineScope | None: + """Give an unscoped UK-wide run or a group of nations a fixed ID. + + A group's scope is its strategy's cache key, as it was before the + handlers; both read the UK national year file. + """ + if not run.dataset.is_default: + return None + strategy = run.region.scoping_strategy + if run.region.code == UK and strategy is None: + return BaselineScope(region="national", scope_key=None) + if isinstance(strategy, RegionGroupStrategy): + return BaselineScope(region=run.region.code, scope_key=strategy.cache_key) + return None + + +class UkNationHandler(_UkLevel): + """A run of one of the four nations, a row filter on the default dataset.""" + + level = DatasetLevel.NATION + + +class UkLocalAreaHandler(_UkLevel): + """A run on the dataset the bundle routes UK area regions to.""" + + level = DatasetLevel.LOCAL_AREA + + def year_file_for(self, run: RunScope) -> YearFileTarget | None: + """Return the local-area dataset's whole year file.""" + if run.dataset.is_default: + return None + return _whole_dataset_year_file(self.level, run.year, run.dataset.name) + + +def _routed_area_dataset_name() -> str | None: + from policyengine_simulation_executor import ( # noqa: PLC0415 # resolved per call so tests can patch the routing helper + uk_local_authority_metadata, + ) + + try: + return uk_local_authority_metadata.routed_uk_area_dataset_name() + except ValueError: + return None + + +def uk_level_of(run: RunScope) -> DatasetLevel | None: + """Return a UK run's level: local area, national, nation, or None. + + The local-area dataset comes first, because a breakdown run's region is + ``uk`` or a nation. A dataset other than the default that the bundle does + not route area regions to has no level. A group of nations reads the + national year file, so it is a national run. + """ + if not run.dataset.is_default: + routed = _routed_area_dataset_name() + return DatasetLevel.LOCAL_AREA if run.dataset.name == routed else None + if run.region.code == UK or isinstance( + run.region.scoping_strategy, RegionGroupStrategy + ): + return DatasetLevel.NATIONAL + if run.region.code.startswith(_NATION_PREFIX): + return DatasetLevel.NATION + return None + + +def _prepare_uk_baseline_outputs(baseline: Simulation) -> None: + """Add nothing: UK analyses request no extra baseline outputs.""" + + +def uk_prebuilt() -> CountryPrebuilt: + """Return the UK settings: no prebuilt files yet, and the UK-wide fixed ID.""" + handlers = (UkNationalHandler(), UkNationHandler(), UkLocalAreaHandler()) + return CountryPrebuilt( + country=UK, + years=(), + year_file_levels=(), + baseline_levels=(), + handlers={handler.level: handler for handler in handlers}, + classify=uk_level_of, + baseline_output_preparer=_prepare_uk_baseline_outputs, + ) diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/levels_us.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/levels_us.py new file mode 100644 index 000000000..883466c2e --- /dev/null +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/levels_us.py @@ -0,0 +1,521 @@ +"""The US level handlers: national, group-of-states, state and district runs. + +The US precompute builds the default dataset's year file and each state's +rows of the state-level dataset (ACS-local) for 2026, 2027 and 2025, and the +current-law baseline of each of the 20 groups of states a segmented +nationwide run splits into. A national, group or state run reads its year +file from its prebuilt folder; a district reads its state's file. +""" + +from __future__ import annotations + +import gc +import logging +from pathlib import Path +from typing import TYPE_CHECKING + +from policyengine.core.scoping_strategy import RegionGroupStrategy, RowFilterStrategy + +from policyengine_simulation_executor.stage12_cache.levels import ( + BAKED_STATE_DATASET_SOURCE, + BaselineScope, + BaselineTarget, + CountryPrebuilt, + DatasetLevel, + RunScope, + SourceFileTarget, + SubsetFilter, + YearFileTarget, + prebuilt_folder, + year_file_name, +) +from policyengine_simulation_executor.stage12_cache.partition import ( + US_REGION_GROUPS, +) +from policyengine_simulation_executor.stage12_cache.state_datasets import ( + year_file_reuse_problem, +) + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + from types import ModuleType + + from microdf import MicroDataFrame + from policyengine.core import Simulation + +logger = logging.getLogger(__name__) + +US = "us" +# The user-facing priority order (2026 first); with parallel builds it only +# orders submission, but keep it intentional. +US_PREBUILT_YEARS = (2026, 2027, 2025) +_STATE_PREFIX = "state/" +_DISTRICT_PREFIX = "congressional_district/" + + +def _default_dataset() -> str: + from policyengine_simulation_executor.release_bundle import ( # noqa: PLC0415 # resolved per call so tests can patch release_bundle.get_country_release_bundle + get_country_release_bundle, + ) + + return get_country_release_bundle(US).default_dataset + + +def _us_country_module() -> ModuleType: + from policyengine_simulation_executor.simulation_runtime import ( # noqa: PLC0415 # resolved per call so tests can patch simulation_runtime._country_module + _country_module, + ) + + return _country_module(US) + + +def national_year_file(year: int, dataset: str | None = None) -> YearFileTarget: + """Return the whole default dataset's year file for ``year``.""" + name = dataset or _default_dataset() + return YearFileTarget( + country=US, + level=DatasetLevel.NATIONAL, + dataset=name, + year=year, + subset=None, + folder=prebuilt_folder(US, name), + ) + + +def _subset_from_row_filter( + region: str, state_code: str, strategy: object +) -> SubsetFilter | None: + if not isinstance(strategy, RowFilterStrategy): + return None + value = strategy.variable_value + if not strategy.variable_name or value is None or isinstance(value, list): + return None + return SubsetFilter( + region=region, + code=state_code.upper(), + variable=strategy.variable_name, + value=int(value), + scoping_strategy=strategy, + ) + + +def _state_year_file(year: int, dataset: str, subset: SubsetFilter) -> YearFileTarget: + return YearFileTarget( + country=US, + level=DatasetLevel.STATE, + dataset=dataset, + year=year, + subset=subset, + folder=prebuilt_folder(US, dataset, subset.code), + ) + + +class _UsLevel: + """What every US level shares: no targets by default, and the baked-folder rule.""" + + country = US + level: DatasetLevel + baked_dataset_source: str | None = None + + def year_file_targets(self, year: int) -> Sequence[YearFileTarget]: # noqa: ARG002 # a level that owns no year files + """Return no year files: this level reads another level's.""" + return [] + + def baseline_targets(self, year: int) -> Sequence[BaselineTarget]: # noqa: ARG002 # a level without precomputed baselines + """Return no baselines: none are precomputed at this level.""" + return [] + + def source_file_targets(self) -> Sequence[SourceFileTarget]: + """Return no source files: the US image copies none.""" + return [] + + def write_year_files( + self, + year: int, # noqa: ARG002 # the protocol's signature + targets: Sequence[YearFileTarget], + work_folder: Path, # noqa: ARG002 # the protocol's signature + ) -> Mapping[YearFileTarget, Path]: + """Refuse targets: this level owns no year files.""" + if targets: + msg = f"The US {self.level} level owns no year files" + raise ValueError(msg) + return {} + + def year_file_for(self, run: RunScope) -> YearFileTarget | None: # noqa: ARG002 # overridden by every level + """Return no year file.""" + return None + + def baked_data_folder(self, run: RunScope, data_folder: str) -> str | None: + """Return the folder of ``run``'s year file if it is there and .py reuses it. + + A file that fails .py's reuse checks would make ``ensure_datasets`` + rebuild the whole dataset inside the prebuilt folder, so the run + reads today's folders instead. + """ + target = self.year_file_for(run) + if target is None: + return None + folder = Path(data_folder) / target.folder + year_file = folder / year_file_name(target) + if not year_file.is_file(): + return None + try: + problem = year_file_reuse_problem(year_file, target.dataset) + except ImportError: + # The reuse checks read private .py helpers. If an upgrade moves + # one, the request prepares its dataset instead of failing. + logger.warning( + "Not reading the prebuilt year 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 prebuilt year file %s: %s", year_file, problem + ) + return None + return str(folder) + + def baseline_scope(self, run: RunScope) -> BaselineScope | None: # noqa: ARG002 # overridden by the levels with fixed baseline IDs + """Return no scope: this level's baselines get random IDs.""" + return None + + +class UsNationalHandler(_UsLevel): + """The unscoped nationwide run on the default dataset.""" + + level = DatasetLevel.NATIONAL + + def year_file_targets(self, year: int) -> Sequence[YearFileTarget]: + """Return the default dataset's year file.""" + return [national_year_file(year)] + + def write_year_files( + self, + year: int, + targets: Sequence[YearFileTarget], + work_folder: Path, # noqa: ARG002 # the default dataset's source file sits in the image data folder + ) -> Mapping[YearFileTarget, Path]: + """Prepare each year file in the image data folder, beside its source file.""" + from policyengine_simulation_executor.simulation_runtime import ( # noqa: PLC0415 # resolved per call so tests can patch resolve_data_folder + resolve_data_folder, + ) + + data_folder = resolve_data_folder() + written: dict[YearFileTarget, Path] = {} + for target in targets: + if target.level != self.level or target.subset is not None: + msg = f"Not a whole-dataset national year file: {target}" + raise ValueError(msg) + _us_country_module().ensure_datasets( + datasets=[target.dataset], years=[year], data_folder=data_folder + ) + year_file = Path(data_folder) / year_file_name(target) + if not year_file.exists(): + msg = f"ensure_datasets produced no file at {year_file}" + raise RuntimeError(msg) + written[target] = year_file + return written + + def year_file_for(self, run: RunScope) -> YearFileTarget | None: + """Return the default dataset's year file.""" + if not run.dataset.is_default: + return None + return national_year_file(run.year, run.dataset.name) + + def baseline_scope(self, run: RunScope) -> BaselineScope | None: + """Give the unscoped nationwide run on the default dataset a fixed ID.""" + if ( + run.region.code == US + and run.region.scoping_strategy is None + and run.dataset.is_default + ): + return BaselineScope(region="national", scope_key=None) + return None + + +class UsStateGroupHandler(_UsLevel): + """The 20 groups of states a segmented nationwide run splits into.""" + + level = DatasetLevel.STATE_GROUP + + def baseline_targets(self, year: int) -> Sequence[BaselineTarget]: + """Return each group's current-law baseline, on the national year file.""" + year_file = national_year_file(year) + return [ + BaselineTarget( + country=US, + level=self.level, + year=year, + request={ + "country": US, + "scope": "macro", + "region_group": list(group), + "time_period": year, + }, + year_file=year_file, + label=f"group {index} of {len(US_REGION_GROUPS)}", + ) + for index, group in enumerate(US_REGION_GROUPS, start=1) + ] + + def year_file_for(self, run: RunScope) -> YearFileTarget | None: + """Return the national year file, which a group's rows are filtered from.""" + if not run.dataset.is_default: + return None + return national_year_file(run.year, run.dataset.name) + + def baseline_scope(self, run: RunScope) -> BaselineScope | None: + """Give a group run on the default dataset a fixed ID.""" + strategy = run.region.scoping_strategy + if isinstance(strategy, RegionGroupStrategy) and run.dataset.is_default: + return BaselineScope(region=run.region.code, scope_key=strategy.cache_key) + return None + + +class UsStateHandler(_UsLevel): + """A single-state run: its state's rows of the state-level dataset.""" + + level = DatasetLevel.STATE + baked_dataset_source = BAKED_STATE_DATASET_SOURCE + + def year_file_targets(self, year: int) -> Sequence[YearFileTarget]: + """Return each state's year file, for states whose runs load another dataset. + + Each state is resolved exactly as a request for it is + (``resolve_region`` then ``_resolve_dataset_selection``), so a bundle + that sends states back to the default dataset gets no state files. + """ + from policyengine_simulation_executor.simulation_runtime import ( # noqa: PLC0415 # resolved per call so tests can patch simulation_runtime helpers + _resolve_dataset_selection, + resolve_region, + ) + + country_module = _us_country_module() + targets = [] + for region in country_module.model.region_registry.get_by_type("state"): + params = {"country": US, "region": region.code, "time_period": year} + resolution = resolve_region( + country_module=country_module, country=US, params=params + ) + selection = _resolve_dataset_selection(params, region_resolution=resolution) + if selection.is_default: + continue + subset = ( + _subset_from_row_filter( + resolution.code, resolution.state_code, resolution.scoping_strategy + ) + if resolution.state_code + else None + ) + if subset is None: + 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(_state_year_file(year, selection.name, subset)) + return sorted( + targets, + key=lambda target: target.subset.code if target.subset else "", + ) + + def write_year_files( + self, year: int, targets: Sequence[YearFileTarget], work_folder: Path + ) -> Mapping[YearFileTarget, Path]: + """Write each state's rows of one dataset's year file, checked as .py reuses it. + + Prepares the dataset's full-country year file once, then for each + target keeps the rows its region's own scoping strategy keeps, writes + them with .py's ``save()``, copies the year-file stamp and confirms + that .py's reuse checks accept the file. + """ + 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 targets: + return {} + datasets = {target.dataset for target in targets} + if len(datasets) > 1: + msg = f"One state file build covers one dataset, not {sorted(datasets)}" + raise ValueError(msg) + for target in targets: + if target.year != year or target.level != self.level or not target.subset: + msg = f"Not a {year} state year file: {target}" + raise ValueError(msg) + (dataset,) = datasets + source_folder = str(work_folder / "source") + country_module = _us_country_module() + + # 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) + ) + + written: dict[YearFileTarget, Path] = {} + for target in targets: + subset = target.subset + if subset is None: # checked above; narrows the type + continue + rows = subset.scoping_strategy.apply( + entity_data=source.data.entity_data, + group_entities=US_GROUP_ENTITIES, + year=year, + ) + year_file = work_folder / target.folder / year_file_name(target) + PolicyEngineUSDataset( + name=f"{dataset}-{subset.code.lower()}-year-{year}", + description=f"{subset.region} rows of {dataset} for {year}", + filepath=str(year_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(year_file, stamp) + problem = year_file_reuse_problem(year_file, dataset) + if problem is not None: + msg = f"ensure_datasets would not reuse {year_file}: {problem}" + raise RuntimeError(msg) + written[target] = year_file + return written + + def year_file_for(self, run: RunScope) -> YearFileTarget | None: + """Return the state's year file, or the national one on the default dataset.""" + if run.dataset.is_default: + return national_year_file(run.year, run.dataset.name) + if not run.region.state_code: + return None + subset = _subset_from_row_filter( + run.region.code, run.region.state_code, run.region.scoping_strategy + ) + if subset is None: + return None + return _state_year_file(run.year, run.dataset.name, subset) + + +class UsDistrictHandler(_UsLevel): + """A congressional-district run: its state's year file, filtered at run time.""" + + level = DatasetLevel.DISTRICT + baked_dataset_source = BAKED_STATE_DATASET_SOURCE + + def year_file_for(self, run: RunScope) -> YearFileTarget | None: + """Return the district's state's year file (the national one on the default).""" + if run.dataset.is_default: + return national_year_file(run.year, run.dataset.name) + state_code = run.region.state_code + if not state_code: + return None + state_region = f"{_STATE_PREFIX}{state_code.lower()}" + region = _us_country_module().model.get_region(state_region) + subset = _subset_from_row_filter( + state_region, state_code, getattr(region, "scoping_strategy", None) + ) + if subset is None: + return None + return _state_year_file(run.year, run.dataset.name, subset) + + +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 household whose code names a district of another state would + be missing from that district's results, so the build stops instead. A + code that names no district, such as an unassigned 0, matches no district + request on either path 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) + + +def us_level_of(run: RunScope) -> DatasetLevel | None: + """Return a US run's level: group, national, state, district, or None.""" + if isinstance(run.region.scoping_strategy, RegionGroupStrategy): + return DatasetLevel.STATE_GROUP + code = run.region.code + if code == US: + return DatasetLevel.NATIONAL + if code.startswith(_STATE_PREFIX): + return DatasetLevel.STATE + if code.startswith(_DISTRICT_PREFIX): + return DatasetLevel.DISTRICT + return None + + +def _prepare_us_baseline_outputs(baseline: Simulation) -> None: + # The extras economic_impact_analysis applies unconditionally before + # ensure(); a precomputed baseline must carry them, or every request + # would fail the column check and recompute. + from policyengine.tax_benefit_models.us.analysis import ( + configure_budgetary_impact_variables, + ) + + configure_budgetary_impact_variables(baseline, baseline) + + +def us_prebuilt() -> CountryPrebuilt: + """Return the US settings: today's files, through the four US handlers.""" + handlers = ( + UsNationalHandler(), + UsStateGroupHandler(), + UsStateHandler(), + UsDistrictHandler(), + ) + return CountryPrebuilt( + country=US, + years=US_PREBUILT_YEARS, + year_file_levels=(DatasetLevel.NATIONAL, DatasetLevel.STATE), + baseline_levels=(DatasetLevel.STATE_GROUP,), + handlers={handler.level: handler for handler in handlers}, + classify=us_level_of, + baseline_output_preparer=_prepare_us_baseline_outputs, + ) diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/partition.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/partition.py new file mode 100644 index 000000000..6c0b64075 --- /dev/null +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_cache/partition.py @@ -0,0 +1,41 @@ +"""The household-balanced 20-way US partition for segmented national calculations. + +One list for both apps: Stage 12 segments national runs by it +(``stage12_runtime.partition``), the run_simulation app's segmented national +runs use it (``national_partition``), and the US level handlers precompute one +current-law baseline per group (``levels_us``). It lives here, rather than in +``stage12_runtime``, because that package's ``__init__`` imports the v2 +database code, which the run_simulation app's images don't install. + +Provenance: computed from the dataset's household counts per state (LPT +greedy over per-state rows; no state needed splitting into districts). +Groups hold 2,440-3,042 of the 57,240 sample households each. Rebalance only +with a measured partition; group count and membership changes alter +per-child runtimes and every precomputed group baseline's key, not +correctness. +""" + +from __future__ import annotations + +US_REGION_GROUPS: tuple[tuple[str, ...], ...] = ( + ("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"), +) diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/partition.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/partition.py index f7821ec3d..8a0da3371 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/partition.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/partition.py @@ -4,41 +4,20 @@ from typing import TYPE_CHECKING +# The 20 groups live in stage12_cache, whose package imports no database +# code, so the run_simulation app's images can load them too. +from policyengine_simulation_executor.stage12_cache.partition import ( + US_REGION_GROUPS, +) + if TYPE_CHECKING: from policyengine_simulation_contract.stage12_execution import ( PlannedSimulationExecutionInput, ) -# This is an independent snapshot of the measured 20-way partition used by -# the v1 runner when Stage 12 segmentation was introduced. Stage 12 must not -# import the v1 partition: either execution path can now evolve without -# changing the other one implicitly. # Every national partition has this many region groups. NATIONAL_PARTITION_GROUP_COUNT = 20 -US_REGION_GROUPS: tuple[tuple[str, ...], ...] = ( - ("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 stage12_region_groups(country: str) -> list[list[str]] | None: """Return a mutable copy of the Stage 12 partition when supported.""" diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/state_datasets.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/state_datasets.py deleted file mode 100644 index 5b2adcfe1..000000000 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/state_datasets.py +++ /dev/null @@ -1,112 +0,0 @@ -"""Where the main path's worker image keeps baked per-state datasets. - -State and congressional-district regions load a regional dataset and keep -one state's rows. The precompute writes each state's filtered year file and -the image places it at ``/state-datasets///``, -under the basename the dataset's own year file has. Every state therefore -gets its own folder, and ``ensure_datasets`` called on that folder finds the -state's file where it would look for the full year file. - -The manifest builder and the runtime lookup both take folders from here, so -the folder an artifact is copied into is the folder a request reads. -""" - -from __future__ import annotations - -import logging -from pathlib import Path -from typing import TYPE_CHECKING - -from policyengine_simulation_executor.artifact_keys import dataset_artifact_filename - -if TYPE_CHECKING: - from policyengine_simulation_executor.simulation_runtime import DatasetSelection - -logger = logging.getLogger(__name__) - -STATE_DATASETS_DIRECTORY = "state-datasets" -# Values of the run's ``dataset_source`` attribute when its region loads a -# non-default dataset: read from the image's baked state file, or prepared -# from the full regional dataset during the request. -BAKED_STATE_DATASET_SOURCE = "baked_state" -ON_DEMAND_DATASET_SOURCE = "on_demand" - - -def state_dataset_relative_folder(dataset: str, state_code: str) -> str: - """Return a state's folder relative to the image 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)) - - -def year_file_reuse_problem(path: str | Path, dataset: str) -> str | None: - """Return why ``ensure_datasets`` would rebuild this year file, or None. - - These are the two checks .py's ``ensure_datasets`` and ``load_datasets`` - run before reusing a year file of ``dataset``: the year-file stamp and - renames record, then the legacy SPM record against the profile this - release expects for the dataset. - """ - from policyengine.tax_benefit_models.us.datasets import ( - _expected_legacy_spm_profile, - ) - from policyengine.tax_benefit_models.us.legacy_inputs import ( - year_file_stamp_problem, - ) - from policyengine.tax_benefit_models.us.legacy_spm.record import ( - year_file_problem, - ) - - problem = year_file_stamp_problem(path) - 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 request should load, or None. - - A request 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``. The file must also pass .py's reuse checks: - otherwise ``ensure_datasets`` would rebuild the full regional dataset - inside the baked folder, so the request goes to the on-demand path - instead. - """ - if country.lower() != "us" or selection.is_default or not state_code: - 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) / dataset_artifact_filename(stem, year) - 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 request prepares its dataset on demand 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/tests/test_artifact_keys.py b/projects/policyengine-simulation-executor/tests/test_artifact_keys.py index a0cbadddf..f6baa0cc5 100644 --- a/projects/policyengine-simulation-executor/tests/test_artifact_keys.py +++ b/projects/policyengine-simulation-executor/tests/test_artifact_keys.py @@ -1,12 +1,10 @@ -"""Artifact key discipline tests. - -The content-addressed store's whole correctness story rests on three -properties locked in here: (1) digests are canonical (field order never -matters), (2) every payload field independently rotates the digest (no -input silently outside the key), and (3) the digests and the upstream -``ScopingStrategy.cache_key`` strings are STABLE — the golden tests turn -any change into a conscious, reviewable diff instead of silent cache -churn (or, worse, a writer/reader mismatch). +"""Artifact key discipline tests that hold whatever the identity schema. + +The content-addressed store's correctness story rests on canonical digests +(field order never matters), on the upstream ``ScopingStrategy.cache_key`` +strings the baseline key embeds being stable, and on the planner's storage +ID naming the same file .py's wrapper saves. The ``yf1`` and ``bl3`` payload +goldens live in ``test_prebuilt_identities``. """ from types import SimpleNamespace @@ -18,134 +16,31 @@ ) from policyengine_simulation_executor import artifact_keys as ak -_DATASET_KWARGS = { - "country": "us", - "dataset": "populace_cps", - "year": 2026, - "data_version": "1.2.3", - "data_artifact_revision": "rev-abc", - "source_sha256": "feedbead" * 8, - "data_build_fingerprint": "fp-123", - "model_version": "9.9.9", - "policyengine_version": "4.22.0", -} - -_DATASET_GOLDEN = "183ffe49d74669b653fb408b0b7298128ba7c6e990f4479487712a5d79553be3" -_DATASET_NO_SHA_GOLDEN = ( - "25dded8192092f477e4502dae07709e72b6e579f372a9f8346b5eabce07d91b6" -) - -_BASELINE_KWARGS = { - "country": "us", - "region": "national", - "scope_key": "region_group:row_filter:state_code=CA|row_filter:state_code=WV", - "dataset_digest": _DATASET_GOLDEN, - "model_version": "9.9.9", - "policyengine_version": "4.22.0", - # Explicit (== the default) so the perturbation matrix proves the - # policy field participates in the digest. - "policy": ak.CURRENT_LAW_POLICY, -} - -_BASELINE_GOLDEN = "f9cac05d94509895eb48ea33ea5f72d40eb9b954989df05ca6506009d8dedae2" - -_STATE_DATASET_KWARGS = { - "country": "us", - "dataset": "populace_cps_local", - "dataset_uri": "hf://org/repo/populace_cps_local.h5@rev-local", - "source_sha256": "c0ffee00" * 8, - "year": 2026, - "state_code": "UT", - "state_fips": 49, - "filter_variable": "state_fips", - "model_version": "9.9.9", - "policyengine_version": "4.22.0", -} - -_STATE_DATASET_GOLDEN = ( - "e1f1f9f7573eb090ef887967a49314c1cbf0fb20c8021779bf3804b26b24117f" -) - - -class TestDigests: - def test_dataset_key_golden(self): - assert ak.dataset_key(ak.DatasetKeyInputs(**_DATASET_KWARGS)) == _DATASET_GOLDEN - - def test_none_field_is_a_distinct_identity(self): - digest = ak.dataset_key( - ak.DatasetKeyInputs(**{**_DATASET_KWARGS, "source_sha256": None}) - ) - assert digest == _DATASET_NO_SHA_GOLDEN - assert digest != _DATASET_GOLDEN - - def test_baseline_key_golden(self): - assert ( - ak.baseline_key(ak.BaselineKeyInputs(**_BASELINE_KWARGS)) - == _BASELINE_GOLDEN - ) - - @pytest.mark.parametrize("field", sorted(_DATASET_KWARGS)) - def test_every_dataset_field_perturbs_digest(self, field): - perturbed = {**_DATASET_KWARGS, field: 2027 if field == "year" else "other"} - assert ak.dataset_key(ak.DatasetKeyInputs(**perturbed)) != _DATASET_GOLDEN - - @pytest.mark.parametrize("field", sorted(_BASELINE_KWARGS)) - def test_every_baseline_field_perturbs_digest(self, field): - perturbed = {**_BASELINE_KWARGS, field: "other"} - assert ak.baseline_key(ak.BaselineKeyInputs(**perturbed)) != _BASELINE_GOLDEN - - def test_canonical_digest_ignores_insertion_order(self): - forward = {"a": 1, "b": {"c": 2, "d": None}} - backward = {"b": {"d": None, "c": 2}, "a": 1} - assert ak.canonical_digest(forward) == ak.canonical_digest(backward) - - def test_state_dataset_key_golden(self): - assert ( - ak.state_dataset_key(ak.StateDatasetKeyInputs(**_STATE_DATASET_KWARGS)) - == _STATE_DATASET_GOLDEN - ) - - @pytest.mark.parametrize("field", sorted(_STATE_DATASET_KWARGS)) - def test_every_state_dataset_field_perturbs_digest(self, field): - replacement = {"year": 2027, "state_fips": 56}.get(field, "other") - perturbed = {**_STATE_DATASET_KWARGS, field: replacement} - assert ( - ak.state_dataset_key(ak.StateDatasetKeyInputs(**perturbed)) - != _STATE_DATASET_GOLDEN - ) - - def test_state_dataset_spm_selection_is_part_of_the_key(self): - with_spm = ak.StateDatasetKeyInputs( - **_STATE_DATASET_KWARGS, spm={"forecast": "x"} - ) - assert ak.state_dataset_key(with_spm) != _STATE_DATASET_GOLDEN - - def test_simulation_id_shape(self): - sim_id = ak.baseline_simulation_id(_BASELINE_GOLDEN) - assert sim_id == "bl1-f9cac05d94509895" - # Filename-safe and disjoint from the dataset filename pattern. - assert "/" not in sim_id - assert "_year_" not in sim_id +_GROUP_SCOPE_KEY = "region_group:row_filter:state_code=CA|row_filter:state_code=WV" -class TestStoreLayout: - def test_dataset_path(self): - path = ak.dataset_artifact_path("US", "d" * 64, "populace_cps", 2026) - assert path == f"datasets/us/{'d' * 64}/populace_cps_year_2026.h5" +def test_canonical_digest_ignores_insertion_order(): + forward = {"a": 1, "b": {"c": 2, "d": None}} + backward = {"b": {"d": None, "c": 2}, "a": 1} + assert ak.canonical_digest(forward) == ak.canonical_digest(backward) - def test_baseline_path(self): - path = ak.baseline_artifact_path("us", "b" * 64, "bl1-abc") - assert path == f"baselines/us/{'b' * 64}/bl1-abc.h5" - def test_state_dataset_path(self): - path = ak.state_dataset_artifact_path( - "US", "s" * 64, "populace_cps_local", 2026 - ) - assert path == (f"state-datasets/us/{'s' * 64}/populace_cps_local_year_2026.h5") +def test_simulation_id_shape(monkeypatch): + from policyengine_simulation_executor.stage12_cache.levels import BaselineScope + from policyengine_simulation_executor.stage12_cache.levels_us import ( + national_year_file, + ) - def test_manifest_and_marker_paths(self): - assert ak.manifest_path("m" * 64) == f"manifests/{'m' * 64}.json" - assert ak.deployed_marker_path("beta") == "deployed/beta.json" + install_identity_stubs(monkeypatch) + identity = ak.baseline_identity( + ak.year_file_identity(national_year_file(2026)), + BaselineScope(region="national", scope_key=None), + ) + simulation_id = identity.simulation_id + assert simulation_id == f"bl3-{identity.digest[:16]}" + # Filename-safe and disjoint from the year-file name pattern. + assert "/" not in simulation_id + assert "_year_" not in simulation_id class TestUpstreamCacheKeyGoldens: @@ -178,95 +73,10 @@ def test_region_group_cache_key_golden_and_order_invariance(self): @pytest.fixture def stub_identity_sources(monkeypatch): - """Stub the bundle/manifest/receipt seams collect_dataset_identity reads.""" + """Stub the bundle/manifest/receipt seams the identity collectors read.""" return install_identity_stubs(monkeypatch) -class TestIdentityCollection: - @pytest.mark.usefixtures("stub_identity_sources") - def test_collected_identity_matches_golden(self): - identity = ak.collect_dataset_identity("us", 2026) - assert identity.digest == _DATASET_GOLDEN - assert identity.filename == "populace_cps_year_2026.h5" - assert identity.store_path == ( - f"datasets/us/{_DATASET_GOLDEN}/populace_cps_year_2026.h5" - ) - - def test_receipt_version_mismatch_drops_source_sha(self, stub_identity_sources): - stub_identity_sources.receipt_entry = { - "country": "us", - "version": "0.0.1", - "installed_sha256": "feedbead" * 8, - } - identity = ak.collect_dataset_identity("us", 2026) - assert identity.source_sha256 is None - assert identity.digest == _DATASET_NO_SHA_GOLDEN - - def test_missing_receipt_falls_back_to_none(self, stub_identity_sources): - stub_identity_sources.receipt_entry = None - identity = ak.collect_dataset_identity("us", 2026) - assert identity.source_sha256 is None - assert identity.digest == _DATASET_NO_SHA_GOLDEN - - def test_expected_sha_used_when_installed_absent(self, stub_identity_sources): - stub_identity_sources.receipt_entry = { - "country": "us", - "version": "1.2.3", - "expected_sha256": "feedbead" * 8, - } - assert ak.collect_dataset_identity("us", 2026).digest == _DATASET_GOLDEN - - @pytest.mark.usefixtures("stub_identity_sources") - def test_baseline_identity_composes(self): - identity = ak.collect_baseline_identity( - "us", - 2026, - region="national", - scope_key=_BASELINE_KWARGS["scope_key"], - ) - assert identity.digest == _BASELINE_GOLDEN - assert identity.simulation_id == "bl1-f9cac05d94509895" - assert identity.store_path == ( - f"baselines/us/{_BASELINE_GOLDEN}/bl1-f9cac05d94509895.h5" - ) - - def test_installed_spm_defaults_enter_dataset_identity( - self, - stub_identity_sources, - monkeypatch, - ): - """PolicyEngine 6's bundle-selected SPM inputs rotate artifact keys.""" - from policyengine_simulation_executor import spm as executor_spm - - class _StubForecast: - years = (2026,) - - def entry(self, year, *, scenario, as_of): - return {"year": year, "scenario": scenario, "as_of": as_of} - - monkeypatch.setattr( - executor_spm, "_forecast", lambda _expected_sha256: _StubForecast() - ) - monkeypatch.setattr( - executor_spm, - "_prevalidate_selection", - lambda _selection_json, _start_year, _window_size: None, - ) - - capability = stub_identity_sources.installed_spm_capability() - assert capability is not None - stub_identity_sources.spm_capability = capability - - identity = ak.collect_dataset_identity("us", 2026) - expected_selection = capability.defaults.model_dump(mode="json") - - assert identity.spm == expected_selection - assert identity.digest == ak.dataset_key( - ak.DatasetKeyInputs(**_DATASET_KWARGS, spm=expected_selection) - ) - assert identity.digest != _DATASET_GOLDEN - - _SPM_SELECTION = { "forecast_content_sha256": "a" * 64, "scenario": "ce_trend", @@ -276,7 +86,7 @@ def entry(self, year, *, scenario, as_of): "as_of": None, } _SPM_STORAGE_GOLDEN = ( - "bl1-21f52b30719e20bb-spm-" + "bl3-3afa7cef3a4c4d91-spm-" "7396bf5f4876c42bb6cba0f9533478098edc0861cc3657bd0d60f88dbb26ac39" ) @@ -284,7 +94,7 @@ def entry(self, year, *, scenario, as_of): class TestWrapperStorageIdAgreement: """The planner's storage id against PolicyEngine 6, which names the file. - Precompute plans a store path from ``BaselineArtifactIdentity.storage_id`` + Precompute plans a store path from ``BaselineIdentity.storage_id`` and the in-container worker refuses to publish when the wrapper's own ``Simulation.storage_id`` disagrees. The wrapper's value also names the saved ``.h5``, so the two derivations are not merely compared — they are @@ -302,19 +112,21 @@ class TestWrapperStorageIdAgreement: def identity(self, stub_identity_sources): """Build the identity directly from an already-resolved selection. - ``collect_baseline_identity`` resolves the selection through the - installed bundle first; that resolution is the contract suite's - subject. What is under test here is only what the identity then - does with the resolved dict. + ``baseline_identity`` resolves the selection through the installed + bundle first; that resolution is the contract suite's subject. What + is under test here is only what the identity then does with the + resolved dict. """ + from policyengine_simulation_executor.stage12_cache.levels_us import ( + national_year_file, + ) def _identity(spm=None): - return ak.BaselineArtifactIdentity( + return ak.BaselineIdentity( spm=spm, - country="us", region="national", - scope_key=_BASELINE_KWARGS["scope_key"], - dataset=ak.collect_dataset_identity("us", 2026), + scope_key=_GROUP_SCOPE_KEY, + year_file=ak.year_file_identity(national_year_file(2026)), ) return _identity @@ -409,43 +221,3 @@ def test_spm_arm_matches_the_installed_wrapper( tax_benefit_model_version=SimpleNamespace(country_code="us"), ) assert wrapper.storage_id == built.storage_id - - -class TestStateDatasetIdentityCollection: - def test_collected_identity_matches_golden(self, stub_identity_sources): - identity = ak.collect_state_dataset_identity( - "us", - 2026, - dataset="populace_cps_local", - state_code="UT", - state_fips=49, - filter_variable="state_fips", - ) - - assert identity.digest == _STATE_DATASET_GOLDEN - assert identity.filename == "populace_cps_local_year_2026.h5" - assert identity.store_path == ( - f"state-datasets/us/{_STATE_DATASET_GOLDEN}/populace_cps_local_year_2026.h5" - ) - - def test_a_dataset_without_a_certified_sha_is_a_distinct_identity( - self, stub_identity_sources - ): - stub_identity_sources.release_datasets["populace_cps_local"] = SimpleNamespace( - sha256=None - ) - - identity = ak.collect_state_dataset_identity( - "us", - 2026, - dataset="populace_cps_local", - state_code="UT", - state_fips=49, - filter_variable="state_fips", - ) - - assert identity.source_sha256 is None - assert identity.digest != _STATE_DATASET_GOLDEN - - def test_the_default_dataset_identity_is_unchanged(self, stub_identity_sources): - assert ak.collect_dataset_identity("us", 2026).digest == _DATASET_GOLDEN diff --git a/projects/policyengine-simulation-executor/tests/test_baseline_artifacts.py b/projects/policyengine-simulation-executor/tests/test_baseline_artifacts.py index 402cb199b..24af4575a 100644 --- a/projects/policyengine-simulation-executor/tests/test_baseline_artifacts.py +++ b/projects/policyengine-simulation-executor/tests/test_baseline_artifacts.py @@ -32,30 +32,45 @@ def _region_group(): ) +_DEFAULT_DATASET = SimpleNamespace(name="populace_us_2024", is_default=True) +_STATE_LEVEL_DATASET = SimpleNamespace( + name="populace_us_2024_acs_local", is_default=False +) + + +def _record_identity_collection(monkeypatch, calls, simulation_id): + """Replace the identity collectors with ones that record what they were asked.""" + + def year_file_identity(target): + return SimpleNamespace(target=target) + + def baseline_identity(year_file, scope, spm=None): + calls.append( + { + "country": year_file.target.country, + "year": year_file.target.year, + "region": scope.region, + "scope_key": scope.scope_key, + } + ) + return SimpleNamespace(simulation_id=simulation_id) + + monkeypatch.setattr(ak, "year_file_identity", year_file_identity) + monkeypatch.setattr(ak, "baseline_identity", baseline_identity) + + class TestDeterministicBaselineId: @pytest.fixture def collected(self, monkeypatch): calls = [] - - def fake_collect(country, year, *, region, scope_key): - calls.append( - { - "country": country, - "year": year, - "region": region, - "scope_key": scope_key, - } - ) - return SimpleNamespace(simulation_id="bl1-deadbeefdeadbeef") - - monkeypatch.setattr(ak, "collect_baseline_identity", fake_collect) + _record_identity_collection(monkeypatch, calls, "bl3-deadbeefdeadbeef") return calls def _id(self, _collected, **overrides): kwargs = { "params": {"scope": "macro"}, "country": "us", - "dataset_is_default": True, + "dataset": _DEFAULT_DATASET, "policy": None, "region_code": "us", "scoping_strategy": None, @@ -65,7 +80,7 @@ def _id(self, _collected, **overrides): return ba.deterministic_baseline_id(ba.BaselineIdentityRequest(**kwargs)) def test_national_baseline_qualifies(self, collected): - assert self._id(collected) == "bl1-deadbeefdeadbeef" + assert self._id(collected) == "bl3-deadbeefdeadbeef" assert collected == [ {"country": "us", "year": 2026, "region": "national", "scope_key": None} ] @@ -77,7 +92,7 @@ def test_region_group_qualifies_with_cache_key(self, collected): region_code="region_group/state/ca+state/wv", scoping_strategy=group, ) - assert sim_id == "bl1-deadbeefdeadbeef" + assert sim_id == "bl3-deadbeefdeadbeef" assert collected[0]["region"] == "region_group/state/ca+state/wv" assert collected[0]["scope_key"] == group.cache_key @@ -97,7 +112,7 @@ def test_reforms_keep_current_law_artifact_identity_separate(self, collected, ki elif kind == "scalar": policy = {path: 0.21} - assert self._id(collected) == "bl1-deadbeefdeadbeef" + assert self._id(collected) == "bl3-deadbeefdeadbeef" baseline_calls = list(collected) assert self._id(collected, policy=policy) is None assert ( @@ -105,7 +120,7 @@ def test_reforms_keep_current_law_artifact_identity_separate(self, collected, ki ba.BaselineIdentityRequest( {"scope": "macro"}, country="us", - dataset_is_default=True, + dataset=_DEFAULT_DATASET, policy=policy, region_code="us", scoping_strategy=None, @@ -122,7 +137,7 @@ def test_non_macro_scope_disqualifies(self, collected, scope): assert self._id(collected, params=params) is None def test_nondefault_dataset_disqualifies(self, collected): - assert self._id(collected, dataset_is_default=False) is None + assert self._id(collected, dataset=_STATE_LEVEL_DATASET) is None def test_a_uk_local_area_baseline_gets_no_deterministic_id(self, collected): # A UK-wide local-area breakdown simulates the whole local-area @@ -130,7 +145,10 @@ def test_a_uk_local_area_baseline_gets_no_deterministic_id(self, collected): # never load the national file's precomputed artifact. assert ( self._id( - collected, country="uk", region_code="uk", dataset_is_default=False + collected, + country="uk", + region_code="uk", + dataset=SimpleNamespace(name="microcosm_dense", is_default=False), ) is None ) @@ -156,13 +174,13 @@ def boom(*_args, **_kwargs): msg = "manifest unavailable" raise RuntimeError(msg) - monkeypatch.setattr(ak, "collect_baseline_identity", boom) + monkeypatch.setattr(ak, "year_file_identity", boom) assert ( ba.deterministic_baseline_id( ba.BaselineIdentityRequest( {"scope": "macro"}, country="us", - dataset_is_default=True, + dataset=_DEFAULT_DATASET, policy=None, region_code="us", scoping_strategy=None, @@ -430,16 +448,17 @@ def fake_deterministic_id(request): def test_qualifying_baseline_uses_artifact_class(self, wired): from policyengine_simulation_executor import simulation_runtime as sr - wired.id = "bl1-deadbeefdeadbeef" + wired.id = "bl3-deadbeefdeadbeef" + wired.dataset_selection = SimpleNamespace(is_default=True) sr._build_simulation( {"country": "us", "scope": "macro"}, dataset="dataset", - dataset_selection=SimpleNamespace(is_default=True), + dataset_selection=wired.dataset_selection, policy=None, region=sr.RegionResolution(code="us"), ) assert wired.plain_kwargs is None - assert wired.artifact_kwargs["id"] == "bl1-deadbeefdeadbeef" + assert wired.artifact_kwargs["id"] == "bl3-deadbeefdeadbeef" assert wired.artifact_kwargs["dataset"] == "dataset" expected_selection = ( None if wired.capability is None else wired.capability.defaults.model_dump() @@ -455,11 +474,12 @@ def test_qualifying_baseline_uses_artifact_class(self, wired): assert wired.id_kwargs == { "params": expected_params, "country": "us", - "dataset_is_default": True, + "dataset": wired.dataset_selection, "policy": None, "region_code": "us", "scoping_strategy": None, "year": sr.DEFAULT_YEAR, + "state_code": None, } def test_non_qualifying_uses_plain_simulation(self, wired): @@ -502,12 +522,7 @@ def test_bounded_reform_build_keeps_current_law_artifact_reuse(monkeypatch): lambda **kwargs: SimpleNamespace(kind="plain", **kwargs), ) identities = [] - - def collect_identity(*args, **kwargs): - identities.append((args, kwargs)) - return SimpleNamespace(simulation_id="bl1-current-law") - - monkeypatch.setattr(ak, "collect_baseline_identity", collect_identity) + _record_identity_collection(monkeypatch, identities, "bl3-current-law") kwargs = { "dataset": "dataset", "dataset_selection": sr.DatasetSelection("default", "default", is_default=True), @@ -524,7 +539,7 @@ def collect_identity(*args, **kwargs): ) assert baseline.kind == "artifact" - assert baseline.id == "bl1-current-law" + assert baseline.id == "bl3-current-law" assert baseline.policy is None assert reform.kind == "plain" assert isinstance(reform.policy, policyengine_core.Policy) @@ -542,7 +557,7 @@ def _kwargs(self): return { "params": {"scope": "macro"}, "country": "us", - "dataset_is_default": True, + "dataset": _DEFAULT_DATASET, "policy": None, "region_code": "us", "scoping_strategy": None, @@ -554,7 +569,7 @@ def boom(*_args, **_kwargs): msg = "receipt unreadable" raise RuntimeError(msg) - monkeypatch.setattr(ak, "collect_baseline_identity", boom) + monkeypatch.setattr(ak, "year_file_identity", boom) with pytest.raises(RuntimeError, match="receipt unreadable"): ba.qualifying_baseline_identity( ba.BaselineIdentityRequest(**self._kwargs()) @@ -565,7 +580,7 @@ def boom(*_args, **_kwargs): msg = "receipt unreadable" raise RuntimeError(msg) - monkeypatch.setattr(ak, "collect_baseline_identity", boom) + monkeypatch.setattr(ak, "year_file_identity", boom) assert ( ba.deterministic_baseline_id(ba.BaselineIdentityRequest(**self._kwargs())) is None diff --git a/projects/policyengine-simulation-executor/tests/test_canonical_spm.py b/projects/policyengine-simulation-executor/tests/test_canonical_spm.py index ed388f3ad..5ad58c479 100644 --- a/projects/policyengine-simulation-executor/tests/test_canonical_spm.py +++ b/projects/policyengine-simulation-executor/tests/test_canonical_spm.py @@ -460,33 +460,37 @@ def test_an_unusable_year_alone_is_a_settings_error(self, monkeypatch): def test_collecting_a_baseline_identity_prevalidates_once(self, monkeypatch): """The repeat the review counted, through the real collectors. - ``collect_baseline_identity`` normalizes the request's selection and - then ``collect_dataset_identity`` normalizes the bundle's default for - the same year. When both resolve to the same selection that is one - prevalidation for the pair, and repeating the collection -- as a - request does -- adds none. + ``year_file_identity`` normalizes the bundle's default selection for + the year and ``baseline_identity`` the request's. When both resolve + to the same selection that is one prevalidation for the pair, and + repeating the collection -- as a request does -- adds none. """ from fixtures.identity_stubs import install_identity_stubs + from policyengine_simulation_executor.stage12_cache.levels import ( + BaselineScope, + ) + from policyengine_simulation_executor.stage12_cache.levels_us import ( + national_year_file, + ) install_identity_stubs(monkeypatch) stubs = self._stub_provider(monkeypatch) + national = BaselineScope(region="national", scope_key=None) - first = artifact_keys.collect_baseline_identity( - "us", 2026, region="us", scope_key=None, spm={"geography_kind": "national"} - ) + def collect(spm): + year_file = artifact_keys.year_file_identity(national_year_file(2026)) + return artifact_keys.baseline_identity(year_file, national, spm) + + first = collect({"geography_kind": "national"}) assert first.spm == SELECTION assert stubs.constructions.call_count == 1 - second = artifact_keys.collect_baseline_identity( - "us", 2026, region="us", scope_key=None, spm={"geography_kind": "national"} - ) + second = collect({"geography_kind": "national"}) assert second.storage_id == first.storage_id assert stubs.constructions.call_count == 1 # A request that differs from the bundle default still resolves both. - county = artifact_keys.collect_baseline_identity( - "us", 2026, region="us", scope_key=None, spm={"geography_kind": "county"} - ) + county = collect({"geography_kind": "county"}) assert county.storage_id != first.storage_id assert stubs.constructions.call_count == 2 @@ -558,34 +562,35 @@ def test_actual_http_formula_error_contract(monkeypatch, code, observability_run ], ) def test_each_setting_rotates_artifact_identity(key, value): - common = { - "country": "us", - "region": "national", - "scope_key": None, - "dataset_digest": "d" * 64, - "model_version": "test", - "policyengine_version": "test", - } changed = {**SELECTION, key: value} - assert artifact_keys.baseline_key( - artifact_keys.BaselineKeyInputs(**common, spm=SELECTION) - ) != artifact_keys.baseline_key( - artifact_keys.BaselineKeyInputs(**common, spm=changed) - ) - ds = { - "country": "us", - "dataset": "test", - "year": 2026, - "data_version": "test", - "data_artifact_revision": "test", - "source_sha256": None, - "data_build_fingerprint": None, - "model_version": "test", - "policyengine_version": "test", - } - assert artifact_keys.dataset_key( - artifact_keys.DatasetKeyInputs(**ds, spm=SELECTION) - ) != artifact_keys.dataset_key(artifact_keys.DatasetKeyInputs(**ds, spm=changed)) + + def year_file(spm): + return artifact_keys.YearFileIdentity( + country="us", + dataset="test", + dataset_sha256=None, + data_version="test", + data_artifact_revision="test", + certification_fingerprint=None, + year=2026, + subset=None, + packages={"policyengine": "test"}, + spm=spm, + stem="test", + folder="prebuilt/us/test/all", + ) + + def baseline(spm): + return artifact_keys.BaselineIdentity( + year_file=year_file(SELECTION), + region="national", + scope_key=None, + spm=spm, + ) + + assert year_file(SELECTION).digest != year_file(changed).digest + assert baseline(SELECTION).digest != baseline(changed).digest + assert baseline(SELECTION).storage_id != baseline(changed).storage_id def test_fanout_and_budget_window_preserve_settings_and_receipts(): @@ -658,6 +663,7 @@ def test_worker_build_passes_selection_to_baseline_and_reform(monkeypatch): def test_identity_errors_do_not_degrade_to_an_unidentified_baseline(monkeypatch): from policyengine_simulation_executor import baseline_artifacts + from policyengine_simulation_executor.simulation_runtime import DatasetSelection monkeypatch.setattr( baseline_artifacts, @@ -669,7 +675,9 @@ def test_identity_errors_do_not_degrade_to_an_unidentified_baseline(monkeypatch) baseline_artifacts.BaselineIdentityRequest( {}, country="us", - dataset_is_default=True, + dataset=DatasetSelection( + "populace_cps", "hf://default", is_default=True + ), policy=None, region_code="us", scoping_strategy=None, diff --git a/projects/policyengine-simulation-executor/tests/test_dataset_download_retry.py b/projects/policyengine-simulation-executor/tests/test_dataset_download_retry.py index 5e4d91246..dd8f00820 100644 --- a/projects/policyengine-simulation-executor/tests/test_dataset_download_retry.py +++ b/projects/policyengine-simulation-executor/tests/test_dataset_download_retry.py @@ -399,11 +399,12 @@ def stop_after_loading(*_args, **_kwargs): def test_the_annual_runtime_retries_its_dataset_load(monkeypatch): - from policyengine_simulation_executor import simulation_runtime, state_datasets + from policyengine_simulation_executor import simulation_runtime from policyengine_simulation_executor.simulation_runtime import ( RegionResolution, _run_simulation_impl_core, ) + from policyengine_simulation_executor.stage12_cache import levels from test_simulation_output_fakes import TrackingRuntime recorded = _RecordedTiming() @@ -446,7 +447,7 @@ def stop_after_loading(*_args, **_kwargs): ) monkeypatch.setattr(simulation_runtime, "_load_dataset", flaky_load_dataset) monkeypatch.setattr( - state_datasets, "baked_state_data_folder", lambda **_kwargs: None + levels, "prebuilt_dataset_folder", lambda _run, _data_folder: None ) monkeypatch.setattr(simulation_runtime, "_build_simulation", stop_after_loading) diff --git a/projects/policyengine-simulation-executor/tests/test_image_setup_fetch.py b/projects/policyengine-simulation-executor/tests/test_image_setup_fetch.py index 0cb9ee80a..2e6401c39 100644 --- a/projects/policyengine-simulation-executor/tests/test_image_setup_fetch.py +++ b/projects/policyengine-simulation-executor/tests/test_image_setup_fetch.py @@ -9,6 +9,7 @@ """ import ast +import hashlib import json import sys from pathlib import Path @@ -44,7 +45,31 @@ def bucket(self, name): return SimpleNamespace(blob=lambda path: FakeBlob(self, path)) -def _manifest(): +def _content(digest): + return f"bytes-{digest}".encode() + + +def _artifact(kind, digest, *, filename, folder, **placement): + content = _content(digest) + prefix = "year-files" if kind == "year_file" else "baselines" + return { + "kind": kind, + "level": placement.get("level", "national"), + "region": placement.get("region"), + "path": f"{prefix}/us/{digest}/{filename}", + "filename": filename, + "folder": folder, + "year": 2026, + "digest": digest, + "sha256": hashlib.sha256(content).hexdigest(), + "size_bytes": len(content), + } + + +NATIONAL_FOLDER = "prebuilt/us/populace/all" + + +def _manifest(*extra_artifacts): """Return the wire shape fetch_artifacts consumes, derived from the schema. The layer itself cannot import the model, so it speaks the canonical @@ -52,40 +77,46 @@ def _manifest(): """ return ArtifactManifest.model_validate( { - "schema": "mf1", + "schema": "mf2", "country": "us", "receipt": { "policyengine_version": "4.22.0", + "policyengine_core_version": "3.33.3", "model_version": "1.3.0", "data_version": "1.2.3", "data_artifact_revision": "rev-abc", - "default_dataset": "populace_cps", + "default_dataset": "populace", }, "artifacts": [ - { - "type": "dataset", - "path": "datasets/us/d1/populace_year_2026.h5", - "filename": "populace_year_2026.h5", - "year": 2026, - "digest": "d1", - }, - { - "type": "baseline", - "path": "baselines/us/b1/bl1-aaaa.h5", - "filename": "bl1-aaaa.h5", - "year": 2026, - "digest": "b1", - }, + _artifact( + "year_file", + "d1", + filename="populace_year_2026.h5", + folder=NATIONAL_FOLDER, + ), + _artifact( + "baseline", + "b1", + filename="bl3-aaaa.h5", + folder=NATIONAL_FOLDER, + level="state_group", + region="region_group/state/ca", + ), + *extra_artifacts, ], } ).canonical_payload() +def _store_every_artifact(client, manifest): + for artifact in manifest["artifacts"]: + client.objects[artifact["path"]] = _content(artifact["digest"]) + + @pytest.fixture def fake_client(): client = FakeGcsClient() - for artifact in _manifest()["artifacts"]: - client.objects[artifact["path"]] = f"bytes-{artifact['digest']}".encode() + _store_every_artifact(client, _manifest()) return client @@ -94,20 +125,22 @@ def data_folder(monkeypatch, tmp_path): folder = tmp_path / "data" monkeypatch.setenv("POLICYENGINE_DATA_FOLDER", str(folder)) monkeypatch.setenv("POLICYENGINE_VERSION", "4.22.0") + monkeypatch.setenv("POLICYENGINE_CORE_VERSION", "3.33.3") monkeypatch.setenv("POLICYENGINE_US_VERSION", "1.3.0") monkeypatch.delenv("POLICYENGINE_BUNDLE_RECEIPT", raising=False) return folder class TestFetchArtifacts: - def test_downloads_every_artifact_under_its_runtime_filename( + def test_downloads_every_artifact_into_its_prebuilt_folder( self, fake_client, data_folder ): fetch_artifacts("test-bucket", _manifest(), client=fake_client) assert "test-bucket" in fake_client.bucket_names for artifact in _manifest()["artifacts"]: - target = data_folder / artifact["filename"] - assert target.read_bytes() == f"bytes-{artifact['digest']}".encode() + target = data_folder / NATIONAL_FOLDER / artifact["filename"] + assert target.read_bytes() == _content(artifact["digest"]) + assert not (data_folder / "populace_year_2026.h5").exists() @pytest.mark.usefixtures("data_folder") def test_missing_store_object_fails_before_any_download(self, fake_client): @@ -123,76 +156,79 @@ def test_unresolved_manifest_fails_with_the_digest_env_var_named(self, fake_clie fetch_artifacts("test-bucket", None, client=fake_client) assert fake_client.downloads == [] - def test_overwrites_a_preexisting_same_named_file(self, fake_client, data_folder): - """No skip-if-exists: stale same-named bytes must never reach the image.""" - data_folder.mkdir(parents=True) - stale = data_folder / "populace_year_2026.h5" - stale.write_bytes(b"stale") - fetch_artifacts("test-bucket", _manifest(), client=fake_client) - assert stale.read_bytes() == b"bytes-d1" - - -def _state_dataset_artifact(state_code, *, folder=None, filename=None): - digest = f"s-{state_code}" - return { - "type": "state_dataset", - "path": f"state-datasets/us/{digest}/populace_local_year_2026.h5", - "filename": filename or "populace_local_year_2026.h5", - "folder": folder or f"state-datasets/populace_local/{state_code}", - "state_code": state_code, - "year": 2026, - "digest": digest, - } - + def test_refuses_a_file_already_in_the_image_before_any_download( + self, fake_client, data_folder + ): + """A second country's download step must never replace the first's files.""" + existing = data_folder / NATIONAL_FOLDER / "populace_year_2026.h5" + existing.parent.mkdir(parents=True) + existing.write_bytes(b"earlier") -def _manifest_with_state_datasets(*state_artifacts): - manifest = _manifest() - manifest["artifacts"] = [*manifest["artifacts"], *state_artifacts] - return manifest + with pytest.raises(RuntimeError, match="already"): + fetch_artifacts("test-bucket", _manifest(), client=fake_client) + assert fake_client.downloads == [] + assert existing.read_bytes() == b"earlier" + @pytest.mark.parametrize("field", ["sha256", "size_bytes"]) + def test_refuses_a_file_whose_content_differs( + self, fake_client, data_folder, field + ): + manifest = _manifest() + manifest["artifacts"][1][field] = ( + "0" * 64 if field == "sha256" else manifest["artifacts"][1][field] + 1 + ) -def _store_every_artifact(client, manifest): - for artifact in manifest["artifacts"]: - client.objects[artifact["path"]] = f"bytes-{artifact['digest']}".encode() + with pytest.raises(RuntimeError, match=r"bl3-aaaa\.h5"): + fetch_artifacts("test-bucket", manifest, client=fake_client) + folder = data_folder / NATIONAL_FOLDER + assert not (folder / "bl3-aaaa.h5").exists() + assert not list(folder.glob("*.partial")) + + +def _state_year_file(state_code, *, folder=None, filename=None): + return _artifact( + "year_file", + f"s-{state_code}", + filename=filename or "populace_local_year_2026.h5", + folder=folder or f"prebuilt/us/populace_local/{state_code}", + level="state", + region=f"state/{state_code.lower()}", + ) -class TestStateDatasetPlacement: - """Entries with a ``folder`` land in it; every state shares one filename.""" +class TestStateFilePlacement: + """Every state's year file has one filename and lands in its own folder.""" def test_places_each_state_file_in_its_own_folder(self, fake_client, data_folder): - manifest = _manifest_with_state_datasets( - _state_dataset_artifact("UT"), _state_dataset_artifact("WY") - ) + manifest = _manifest(_state_year_file("UT"), _state_year_file("WY")) _store_every_artifact(fake_client, manifest) fetch_artifacts("test-bucket", manifest, client=fake_client) - state_folder = data_folder / "state-datasets" / "populace_local" + state_folder = data_folder / "prebuilt" / "us" / "populace_local" assert (state_folder / "UT" / "populace_local_year_2026.h5").read_bytes() == ( b"bytes-s-UT" ) assert (state_folder / "WY" / "populace_local_year_2026.h5").read_bytes() == ( b"bytes-s-WY" ) - assert (data_folder / "populace_year_2026.h5").read_bytes() == b"bytes-d1" - assert not (data_folder / "populace_local_year_2026.h5").exists() @pytest.mark.parametrize( "folder", [ - "/abs/state-datasets/UT", - "state-datasets/../../escape", - "state-datasets/./UT", - "state-datasets//UT", - "state-datasets\\UT", + "/abs/prebuilt/us/UT", + "prebuilt/us/../../escape", + "prebuilt/us/./UT", + "prebuilt/us//UT", + "prebuilt\\us\\UT", + "state-datasets/populace_local/UT", + "prebuilt/uk/populace_local/UT", "", ], ) @pytest.mark.usefixtures("data_folder") def test_refuses_an_unsafe_folder_before_any_download(self, fake_client, folder): - manifest = _manifest_with_state_datasets( - _state_dataset_artifact("UT", folder=folder or None) - ) + manifest = _manifest(_state_year_file("UT")) manifest["artifacts"][-1]["folder"] = folder _store_every_artifact(fake_client, manifest) @@ -207,9 +243,7 @@ def test_refuses_an_unsafe_folder_before_any_download(self, fake_client, folder) def test_refuses_an_unsafe_filename_before_any_download( self, fake_client, filename ): - manifest = _manifest_with_state_datasets( - _state_dataset_artifact("UT", filename=filename) - ) + manifest = _manifest(_state_year_file("UT", filename=filename)) _store_every_artifact(fake_client, manifest) with pytest.raises(RuntimeError, match="filename"): @@ -218,10 +252,8 @@ def test_refuses_an_unsafe_filename_before_any_download( @pytest.mark.usefixtures("data_folder") def test_refuses_two_entries_for_one_file_before_any_download(self, fake_client): - repeated = _state_dataset_artifact("UT") - manifest = _manifest_with_state_datasets( - repeated, {**repeated, "path": "state-datasets/us/other/x.h5"} - ) + repeated = _state_year_file("UT") + manifest = _manifest(repeated, {**repeated, "path": "year-files/us/other/x.h5"}) _store_every_artifact(fake_client, manifest) with pytest.raises(RuntimeError, match="more than once"): @@ -230,6 +262,22 @@ def test_refuses_two_entries_for_one_file_before_any_download(self, fake_client) class TestFreshnessGate: + @pytest.mark.usefixtures("data_folder") + def test_rejects_a_policyengine_core_version_mismatch( + self, monkeypatch, fake_client + ): + monkeypatch.setenv("POLICYENGINE_CORE_VERSION", "3.34.0") + with pytest.raises(RuntimeError, match="POLICYENGINE_CORE_VERSION"): + fetch_artifacts("test-bucket", _manifest(), client=fake_client) + assert fake_client.downloads == [] + + @pytest.mark.usefixtures("data_folder") + def test_rejects_a_manifest_of_another_schema(self, fake_client): + manifest = {**_manifest(), "schema": "mf1"} + with pytest.raises(RuntimeError, match="mf1"): + fetch_artifacts("test-bucket", manifest, client=fake_client) + assert fake_client.downloads == [] + @pytest.mark.usefixtures("data_folder") def test_rejects_a_policyengine_version_mismatch(self, monkeypatch, fake_client): monkeypatch.setenv("POLICYENGINE_VERSION", "4.99.0") @@ -507,11 +555,11 @@ def download_to_filename(self, filename): blob=lambda path: SilentBlob(fake_client, path) ) - with pytest.raises(FileNotFoundError): + with pytest.raises(RuntimeError, match="wrote no file"): fetch_artifacts("test-bucket", _manifest(), client=fake_client) assert fake_client.downloads == [ - ("datasets/us/d1/populace_year_2026.h5", "populace_year_2026.h5") + ("year-files/us/d1/populace_year_2026.h5", "populace_year_2026.h5.partial") ] def test_files_missing_after_every_download_fail_the_build( @@ -519,7 +567,7 @@ def test_files_missing_after_every_download_fail_the_build( ): class ReplacingBlob(FakeBlob): def download_to_filename(self, filename): - for existing in data_folder.iterdir(): + for existing in Path(filename).parent.iterdir(): existing.unlink() super().download_to_filename(filename) @@ -530,7 +578,7 @@ def download_to_filename(self, filename): with pytest.raises(RuntimeError) as error: fetch_artifacts("test-bucket", _manifest(), client=fake_client) - missing = str(data_folder / "populace_year_2026.h5") + missing = str(data_folder / NATIONAL_FOLDER / "populace_year_2026.h5") assert str(error.value) == ( f"Artifact fetch did not produce expected files: [{missing!r}]" ) @@ -549,4 +597,4 @@ def test_logs_each_fetched_artifact(self, fake_client, caplog): ] assert len(fetched) == 2 assert fetched[0].endswith("populace_year_2026.h5 (0.0 MB)") - assert fetched[1].endswith("bl1-aaaa.h5 (0.0 MB)") + assert fetched[1].endswith("bl3-aaaa.h5 (0.0 MB)") diff --git a/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py b/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py index 4f6f158be..ad315a306 100644 --- a/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py +++ b/projects/policyengine-simulation-executor/tests/test_modal_bundle_image.py @@ -330,10 +330,11 @@ def _fake_manifest(): return ArtifactManifest.model_validate( { - "schema": "mf1", + "schema": "mf2", "country": "us", "receipt": { "policyengine_version": "4.19.1", + "policyengine_core_version": "3.27.1", "model_version": "1.700.0", "data_version": "1.2.3", "data_artifact_revision": "rev-abc", @@ -341,11 +342,16 @@ def _fake_manifest(): }, "artifacts": [ { - "type": "dataset", - "path": "datasets/us/d1/populace_year_2026.h5", + "kind": "year_file", + "level": "national", + "region": None, + "path": "year-files/us/d1/populace_year_2026.h5", "filename": "populace_year_2026.h5", + "folder": "prebuilt/us/populace_cps/all", "year": 2026, "digest": "d1", + "sha256": "1" * 64, + "size_bytes": 100, }, ], } @@ -457,13 +463,16 @@ def test_a_manifest_listing_state_datasets_reaches_the_fetch_layer(monkeypatch): manifest = _fake_manifest() manifest["artifacts"].append( { - "type": "state_dataset", - "path": "state-datasets/us/s1/populace_local_year_2026.h5", + "kind": "year_file", + "level": "state", + "region": "state/ut", + "path": "year-files/us/s1/populace_local_year_2026.h5", "filename": "populace_local_year_2026.h5", - "folder": "state-datasets/populace_local/UT", - "state_code": "UT", + "folder": "prebuilt/us/populace_local/UT", "year": 2026, "digest": "s1", + "sha256": "2" * 64, + "size_bytes": 200, } ) diff --git a/projects/policyengine-simulation-executor/tests/test_prebuilt_identities.py b/projects/policyengine-simulation-executor/tests/test_prebuilt_identities.py new file mode 100644 index 000000000..361c0208d --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_prebuilt_identities.py @@ -0,0 +1,273 @@ +"""Golden tests of the run_simulation app's prebuilt-file identities. + +Every year file has one ``yf1`` identity, whatever its dataset level, and +every baseline one ``bl3`` identity nesting its year file's digest. The +expected digests are SHA-256 hashes of the payloads in the 1.6 · 1 design, +section 2.2, computed from those payloads alone. A change to any of them +rotates every stored key, so it must be deliberate. +""" + +from __future__ import annotations + +import pytest +from fixtures.identity_stubs import install_identity_stubs +from fixtures.wrapper_spm import wrapper_storage_id +from policyengine.core.scoping_strategy import RowFilterStrategy +from policyengine_simulation_executor import artifact_keys +from policyengine_simulation_executor.stage12_cache.levels import ( + BaselineScope, + DatasetLevel, + SourceFileTarget, + SubsetFilter, + YearFileTarget, +) + +PACKAGES = { + "policyengine": "4.22.0", + "policyengine-core": "3.33.3", + "policyengine-us": "9.9.9", +} +NATIONAL_PAYLOAD = { + "schema": "yf1", + "country": "us", + "dataset": "populace_cps", + "dataset_sha256": "d00dfeed" * 8, + "data_version": "1.2.3", + "data_artifact_revision": "rev-abc", + "certification_fingerprint": "fp-123", + "year": 2026, + "subset": None, + "packages": PACKAGES, + "spm": None, +} +NATIONAL_DIGEST = "56982f3075d99409fc40edca6e1b9265feef6442a2c881fe2962d865db806f55" +UTAH_DIGEST = "9dea291f0277414d0ef6703007e3ca4213cb685b2d693388a37f114fa90b19f6" +NATIONAL_BASELINE_DIGEST = ( + "48380a609a4e26de1ed026e587f1feb69797c06f35de82e024d3c8d10f9bac1e" +) +CALIFORNIA_GROUP_BASELINE_DIGEST = ( + "ef3ab6b4dce1d62a796e1410f82c985c73133b69358aacac50eb046f2c5af4da" +) +SOURCE_FILE_DIGEST = "1994a44b4e38bc9f862602a4614ee509e81442e4cd4f3e973083dbcf36ff9b47" + + +@pytest.fixture +def identity_sources(monkeypatch): + return install_identity_stubs(monkeypatch) + + +def _national_target(year=2026): + return YearFileTarget( + country="us", + level=DatasetLevel.NATIONAL, + dataset="populace_cps", + year=year, + subset=None, + folder="prebuilt/us/populace_cps/all", + ) + + +def _utah_target(): + return YearFileTarget( + country="us", + level=DatasetLevel.STATE, + dataset="populace_cps_local", + year=2026, + subset=SubsetFilter( + region="state/ut", + code="UT", + variable="state_fips", + value=49, + scoping_strategy=RowFilterStrategy( + variable_name="state_fips", variable_value=49 + ), + ), + folder="prebuilt/us/populace_cps_local/UT", + ) + + +def test_schema_labels(): + assert artifact_keys.YEAR_FILE_KEY_SCHEMA == "yf1" + assert artifact_keys.BASELINE_KEY_SCHEMA == "bl3" + assert artifact_keys.SOURCE_FILE_KEY_SCHEMA == "sf1" + + +@pytest.mark.usefixtures("identity_sources") +class TestYearFileIdentity: + def test_whole_dataset_payload_and_digest(self): + identity = artifact_keys.year_file_identity(_national_target()) + + assert identity.payload() == NATIONAL_PAYLOAD + assert identity.digest == NATIONAL_DIGEST + assert identity.filename == "populace_cps_year_2026.h5" + assert identity.folder == "prebuilt/us/populace_cps/all" + assert identity.store_path == ( + f"year-files/us/{NATIONAL_DIGEST}/populace_cps_year_2026.h5" + ) + + def test_subset_payload_and_digest(self): + identity = artifact_keys.year_file_identity(_utah_target()) + + assert identity.payload() == { + **NATIONAL_PAYLOAD, + "dataset": "populace_cps_local", + "dataset_sha256": "c0ffee00" * 8, + "subset": {"region": "state/ut", "variable": "state_fips", "value": 49}, + } + assert identity.digest == UTAH_DIGEST + assert identity.filename == "populace_cps_local_year_2026.h5" + assert identity.store_path == ( + f"year-files/us/{UTAH_DIGEST}/populace_cps_local_year_2026.h5" + ) + + def test_a_dataset_without_a_certified_hash_keys_a_null(self, identity_sources): + identity_sources.release_datasets.pop("populace_cps") + + identity = artifact_keys.year_file_identity(_national_target()) + + assert identity.payload()["dataset_sha256"] is None + assert identity.digest != NATIONAL_DIGEST + + @pytest.mark.parametrize( + ("field", "replacement"), + [ + ("data_version", "1.2.4"), + ("data_artifact_revision", "rev-other"), + ("model_version", "9.9.10"), + ("policyengine_version", "4.22.1"), + ], + ) + def test_bundle_versions_rotate_the_digest( + self, identity_sources, field, replacement + ): + setattr(identity_sources.bundle, field, replacement) + + assert artifact_keys.year_file_identity(_national_target()).digest != ( + NATIONAL_DIGEST + ) + + def test_the_core_version_rotates_the_digest(self, identity_sources): + identity_sources.core_version = "3.34.0" + + identity = artifact_keys.year_file_identity(_national_target()) + + assert identity.payload()["packages"]["policyengine-core"] == "3.34.0" + assert identity.digest != NATIONAL_DIGEST + + def test_the_year_rotates_the_digest(self): + assert artifact_keys.year_file_identity(_national_target(2027)).digest != ( + NATIONAL_DIGEST + ) + + +@pytest.mark.usefixtures("identity_sources") +class TestBaselineIdentity: + def test_national_payload_digest_and_names(self): + year_file = artifact_keys.year_file_identity(_national_target()) + + identity = artifact_keys.baseline_identity( + year_file, BaselineScope(region="national", scope_key=None) + ) + + assert identity.payload() == { + "schema": "bl3", + "year_file": NATIONAL_DIGEST, + "region": "national", + "scope_key": None, + "policy": "current-law", + "spm": None, + } + assert identity.digest == NATIONAL_BASELINE_DIGEST + assert identity.simulation_id == f"bl3-{NATIONAL_BASELINE_DIGEST[:16]}" + assert identity.storage_id == identity.simulation_id + assert identity.store_path == ( + f"baselines/us/{NATIONAL_BASELINE_DIGEST}/{identity.storage_id}.h5" + ) + assert identity.country == "us" + assert identity.year_file == year_file + + def test_region_group_payload_and_digest(self): + year_file = artifact_keys.year_file_identity(_national_target()) + + identity = artifact_keys.baseline_identity( + year_file, + BaselineScope( + region="region_group/state/ca", + scope_key="region_group:row_filter:state_fips=6", + ), + ) + + assert identity.digest == CALIFORNIA_GROUP_BASELINE_DIGEST + + def test_a_year_file_change_rotates_the_baseline(self, identity_sources): + identity_sources.core_version = "3.34.0" + year_file = artifact_keys.year_file_identity(_national_target()) + + identity = artifact_keys.baseline_identity( + year_file, BaselineScope(region="national", scope_key=None) + ) + + assert identity.payload()["year_file"] == year_file.digest + assert identity.digest != NATIONAL_BASELINE_DIGEST + + def test_an_spm_selection_names_the_storage_id(self): + selection = { + "forecast_content_sha256": "a" * 64, + "scenario": "ce_trend", + "geography_kind": "national", + "geography_id": None, + "county_vintage": "2020", + "as_of": None, + } + year_file = artifact_keys.year_file_identity(_national_target()) + + identity = artifact_keys.BaselineIdentity( + year_file=year_file, region="national", scope_key=None, spm=selection + ) + + assert identity.payload()["spm"] == selection + assert identity.simulation_id.startswith("bl3-") + assert identity.storage_id == wrapper_storage_id( + identity.simulation_id, selection + ) + assert identity.store_path.endswith(f"/{identity.storage_id}.h5") + + +def test_source_file_payload_digest_and_path(): + identity = artifact_keys.SourceFileIdentity( + country="uk", + dataset="microcosm_uk_2024_25_dense", + dataset_sha256="ab" * 32, + filename="microcosm_uk_2024_25_dense.h5", + folder="prebuilt/uk/microcosm_uk_2024_25_dense/all", + ) + + assert identity.payload() == { + "schema": "sf1", + "country": "uk", + "dataset": "microcosm_uk_2024_25_dense", + "dataset_sha256": "ab" * 32, + } + assert identity.digest == SOURCE_FILE_DIGEST + assert identity.store_path == ( + f"sources/uk/{'ab' * 32}/microcosm_uk_2024_25_dense.h5" + ) + + +def test_a_source_file_needs_a_certified_hash(monkeypatch): + install_identity_stubs(monkeypatch) + + with pytest.raises(ValueError, match="certified"): + artifact_keys.source_file_identity( + SourceFileTarget( + country="us", + level=DatasetLevel.NATIONAL, + dataset="not_in_the_release", + folder="prebuilt/us/not_in_the_release/all", + ) + ) + + +def test_manifest_and_deployed_marker_paths(): + assert artifact_keys.manifest_path("m" * 64) == f"manifests/{'m' * 64}.json" + assert artifact_keys.deployed_marker_path("prod") == "deployed/prod.json" diff --git a/projects/policyengine-simulation-executor/tests/test_prebuilt_imports.py b/projects/policyengine-simulation-executor/tests/test_prebuilt_imports.py new file mode 100644 index 000000000..0e49a1bf1 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_prebuilt_imports.py @@ -0,0 +1,79 @@ +"""The level handlers import without the v2 database packages. + +The run_simulation app's images (the executor, the precompute and the image +smoke) install neither ``policyengine_stage12_persistence`` nor +``policyengine_simulation_persistence``, but they load the handlers. Each +check runs in a fresh interpreter with both packages blocked, so a module +cached by an earlier test cannot hide an import that needs them. +""" + +from __future__ import annotations + +import subprocess +import sys +from pathlib import Path + +import pytest + +SOURCE_FOLDER = Path(__file__).resolve().parents[1] / "src" +BLOCKED_PACKAGES = ( + "policyengine_stage12_persistence", + "policyengine_simulation_persistence", +) +_BLOCKING_PRELUDE = """ +import importlib +import importlib.abc +import sys + +blocked = {blocked!r} + + +class BlockDatabasePackages(importlib.abc.MetaPathFinder): + def find_spec(self, name, path=None, target=None): + if name.split(".")[0] in blocked: + raise ModuleNotFoundError(f"No module named {{name!r}}") + return None + + +sys.meta_path.insert(0, BlockDatabasePackages()) +""" + + +def _run_without_database_packages(code: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [ + sys.executable, + "-c", + _BLOCKING_PRELUDE.format(blocked=BLOCKED_PACKAGES) + code, + ], + cwd=SOURCE_FOLDER, + capture_output=True, + text=True, + check=False, + ) + + +@pytest.mark.parametrize( + "module", + [ + "policyengine_simulation_executor.stage12_cache.levels_us", + "policyengine_simulation_executor.stage12_cache.levels_uk", + "policyengine_simulation_executor.national_partition", + "policyengine_simulation_executor.simulation_runtime", + "policyengine_simulation_executor.baseline_artifacts", + "policyengine_simulation_executor.precompute", + ], +) +def test_imports_without_the_database_packages(module): + result = _run_without_database_packages(f"importlib.import_module({module!r})\n") + + assert result.returncode == 0, result.stderr + + +def test_the_us_settings_load_without_the_database_packages(): + result = _run_without_database_packages( + "from policyengine_simulation_executor.stage12_cache import levels\n" + "assert len(levels.prebuilt_for('us').handlers) == 4\n" + ) + + assert result.returncode == 0, result.stderr diff --git a/projects/policyengine-simulation-executor/tests/test_prebuilt_levels.py b/projects/policyengine-simulation-executor/tests/test_prebuilt_levels.py new file mode 100644 index 000000000..ed854feea --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_prebuilt_levels.py @@ -0,0 +1,643 @@ +"""The level handlers: which runs each covers, its targets, and what a run reads. + +A handler takes a country and a dataset level and answers four questions +without building any key: which year files and baselines the precompute +builds for a year, which year file a run reads, which prebuilt folder holds +it, and whether the run's current-law baseline gets a fixed ID. The fixed +inputs come from ``fixtures.us_prebuilt_inputs``. +""" + +from __future__ import annotations + +import ast +from pathlib import Path +from types import SimpleNamespace + +import pytest +from fixtures.us_prebuilt_inputs import US_STATE_FIPS, install_us_prebuilt_inputs +from policyengine.core.scoping_strategy import RegionGroupStrategy, RowFilterStrategy +from policyengine_simulation_executor import national_partition +from policyengine_simulation_executor.region_resolution import RegionResolution +from policyengine_simulation_executor.simulation_runtime import DatasetSelection +from policyengine_simulation_executor.stage12_cache import ( + levels, + levels_uk, + levels_us, + partition, +) +from policyengine_simulation_executor.stage12_cache.levels import ( + BaselineScope, + DatasetLevel, + RunScope, + SubsetFilter, + YearFileTarget, +) +from policyengine_simulation_executor.stage12_runtime.partition import ( + US_REGION_GROUPS, +) +from test_stage12_segmentation_foundation import FORBIDDEN_IMPORTS + +US = "us" +UK = "uk" + + +@pytest.fixture +def inputs(monkeypatch): + return install_us_prebuilt_inputs(monkeypatch) + + +@pytest.fixture +def default_dataset(inputs): + return DatasetSelection( + name="populace_cps", + uri=inputs.us_bundle.dataset_uris["populace_cps"], + is_default=True, + ) + + +@pytest.fixture +def state_level_dataset(inputs): + return DatasetSelection( + name="populace_cps_local", + uri=inputs.us_bundle.dataset_uris["populace_cps_local"], + is_default=False, + ) + + +def _state_filter(state_fips): + return RowFilterStrategy(variable_name="state_fips", variable_value=state_fips) + + +def _run(country, region, dataset, *, year=2026): + return RunScope(country=country, year=year, region=region, dataset=dataset) + + +def _national_target(year=2026): + return YearFileTarget( + country=US, + level=DatasetLevel.NATIONAL, + dataset="populace_cps", + year=year, + subset=None, + folder="prebuilt/us/populace_cps/all", + ) + + +def _state_target(state_code, state_fips, year=2026): + return YearFileTarget( + country=US, + level=DatasetLevel.STATE, + dataset="populace_cps_local", + year=year, + subset=SubsetFilter( + region=f"state/{state_code.lower()}", + code=state_code, + variable="state_fips", + value=state_fips, + scoping_strategy=_state_filter(state_fips), + ), + folder=f"prebuilt/us/populace_cps_local/{state_code}", + ) + + +def _group_region(group): + return RegionResolution( + code="region_group/" + "+".join(sorted(group)), + scoping_strategy=RegionGroupStrategy( + members=[_state_filter(0) for _code in group] + ), + ) + + +def test_dataset_levels(): + assert [level.value for level in DatasetLevel] == [ + "national", + "state_group", + "state", + "district", + "nation", + "local_area", + ] + + +class TestCountrySettings: + def test_us_builds_todays_files(self): + prebuilt = levels.prebuilt_for("us") + + assert prebuilt.country == US + assert prebuilt.years == (2026, 2027, 2025) + assert prebuilt.year_file_levels == (DatasetLevel.NATIONAL, DatasetLevel.STATE) + assert prebuilt.baseline_levels == (DatasetLevel.STATE_GROUP,) + assert set(prebuilt.handlers) == { + DatasetLevel.NATIONAL, + DatasetLevel.STATE_GROUP, + DatasetLevel.STATE, + DatasetLevel.DISTRICT, + } + for level, handler in prebuilt.handlers.items(): + assert (handler.country, handler.level) == (US, level) + + def test_uk_builds_nothing_yet(self): + prebuilt = levels.prebuilt_for("UK") + + assert prebuilt.country == UK + assert prebuilt.years == () + assert prebuilt.year_file_levels == () + assert prebuilt.baseline_levels == () + assert set(prebuilt.handlers) == { + DatasetLevel.NATIONAL, + DatasetLevel.NATION, + DatasetLevel.LOCAL_AREA, + } + + def test_another_country_has_no_prebuilt_files(self): + assert levels.prebuilt_for("fr") is None + + def test_handler_for(self): + assert levels.handler_for("us", DatasetLevel.STATE).level == DatasetLevel.STATE + with pytest.raises(KeyError): + levels.handler_for("uk", DatasetLevel.STATE) + + def test_prebuilt_folder(self): + assert levels.prebuilt_folder("US", "populace_cps") == ( + "prebuilt/us/populace_cps/all" + ) + assert levels.prebuilt_folder("us", "populace_cps_local", "CA") == ( + "prebuilt/us/populace_cps_local/CA" + ) + + +@pytest.mark.usefixtures("inputs") +class TestLevelOfARun: + def test_us_runs(self, default_dataset, state_level_dataset): + prebuilt = levels.prebuilt_for("us") + group = _group_region(["state/ca"]) + + assert prebuilt.level_of(_run(US, group, default_dataset)) == ( + DatasetLevel.STATE_GROUP + ) + assert prebuilt.level_of( + _run(US, RegionResolution(code="us"), default_dataset) + ) == (DatasetLevel.NATIONAL) + assert prebuilt.level_of( + _run(US, RegionResolution(code="state/ca"), state_level_dataset) + ) == (DatasetLevel.STATE) + assert prebuilt.level_of( + _run( + US, + RegionResolution(code="congressional_district/CA-01"), + state_level_dataset, + ) + ) == (DatasetLevel.DISTRICT) + assert ( + prebuilt.level_of( + _run(US, RegionResolution(code="place/CA-44000"), default_dataset) + ) + is None + ) + + def test_uk_runs(self, monkeypatch): + from policyengine_simulation_executor import uk_local_authority_metadata + + monkeypatch.setattr( + uk_local_authority_metadata, + "routed_uk_area_dataset_name", + lambda: "microcosm_dense", + ) + prebuilt = levels.prebuilt_for("uk") + uk_default = DatasetSelection("enhanced_frs", "hf://uk", is_default=True) + dense = DatasetSelection("microcosm_dense", "hf://dense", is_default=False) + + assert prebuilt.level_of(_run(UK, RegionResolution(code="uk"), dense)) == ( + DatasetLevel.LOCAL_AREA + ) + assert prebuilt.level_of(_run(UK, RegionResolution(code="uk"), uk_default)) == ( + DatasetLevel.NATIONAL + ) + assert prebuilt.level_of( + _run(UK, RegionResolution(code="country/wales"), uk_default) + ) == (DatasetLevel.NATION) + assert ( + prebuilt.level_of( + _run(UK, RegionResolution(code="constituency/E1"), uk_default) + ) + is None + ) + + def test_a_uk_group_of_nations_is_a_national_run(self): + uk_default = DatasetSelection("enhanced_frs", "hf://uk", is_default=True) + group = RegionResolution( + code="region_group/country/england+country/wales", + scoping_strategy=RegionGroupStrategy( + members=[ + RowFilterStrategy(variable_name="region", variable_value="ENGLAND"), + RowFilterStrategy(variable_name="region", variable_value="WALES"), + ] + ), + ) + run = _run(UK, group, uk_default) + handler = levels.handler_for("uk", DatasetLevel.NATIONAL) + + assert levels.prebuilt_for("uk").level_of(run) == DatasetLevel.NATIONAL + assert handler.baseline_scope(run) == BaselineScope( + region=group.code, scope_key=group.scoping_strategy.cache_key + ) + assert handler.year_file_for(run).subset is None + + def test_an_unrouted_uk_dataset_has_no_level(self, monkeypatch): + from policyengine_simulation_executor import uk_local_authority_metadata + + def not_routed(): + msg = "the bundle routes no area regions" + raise ValueError(msg) + + monkeypatch.setattr( + uk_local_authority_metadata, "routed_uk_area_dataset_name", not_routed + ) + other = DatasetSelection("microcosm_dense", "hf://dense", is_default=False) + + assert ( + levels.prebuilt_for("uk").level_of( + _run(UK, RegionResolution(code="uk"), other) + ) + is None + ) + + def test_a_failing_classification_means_no_level( + self, monkeypatch, default_dataset + ): + def failing_classification(_run): + msg = "registry unavailable" + raise RuntimeError(msg) + + monkeypatch.setattr(levels_us, "us_level_of", failing_classification) + + assert ( + levels.prebuilt_for("us").level_of( + _run(US, RegionResolution(code="us"), default_dataset) + ) + is None + ) + + +@pytest.mark.usefixtures("inputs") +class TestTargets: + def test_national_year_file(self): + handler = levels.handler_for("us", DatasetLevel.NATIONAL) + + assert handler.year_file_targets(2027) == [_national_target(2027)] + assert handler.baseline_targets(2027) == [] + assert handler.source_file_targets() == [] + + def test_state_year_files_sorted_by_state_code(self): + handler = levels.handler_for("us", DatasetLevel.STATE) + + targets = handler.year_file_targets(2026) + + assert targets == [ + _state_target(state_code, state_fips) + for state_code, state_fips in sorted(US_STATE_FIPS) + ] + assert handler.baseline_targets(2026) == [] + + def test_states_on_the_default_dataset_get_no_state_file(self, inputs): + for region in inputs.regions: + if region.state_code != "WY": + region.dataset_path = inputs.us_bundle.dataset_uris["populace_cps"] + + targets = levels.handler_for("us", DatasetLevel.STATE).year_file_targets(2026) + + assert [target.subset.code for target in targets] == ["WY"] + + def test_a_state_without_a_row_filter_is_refused(self, inputs): + inputs.regions[0].scoping_strategy = None + + with pytest.raises(RuntimeError, match="state/al"): + levels.handler_for("us", DatasetLevel.STATE).year_file_targets(2026) + + def test_group_baselines(self): + handler = levels.handler_for("us", DatasetLevel.STATE_GROUP) + + targets = handler.baseline_targets(2025) + + assert handler.year_file_targets(2025) == [] + assert [target.request for target in targets] == [ + { + "country": "us", + "scope": "macro", + "region_group": list(group), + "time_period": 2025, + } + for group in US_REGION_GROUPS + ] + assert {target.year_file for target in targets} == {_national_target(2025)} + assert [target.label for target in targets[:2]] == [ + "group 1 of 20", + "group 2 of 20", + ] + assert {(target.country, target.level, target.year) for target in targets} == { + (US, DatasetLevel.STATE_GROUP, 2025) + } + + def test_districts_and_uk_levels_build_nothing(self): + for country, level in [ + ("us", DatasetLevel.DISTRICT), + ("uk", DatasetLevel.NATIONAL), + ("uk", DatasetLevel.NATION), + ("uk", DatasetLevel.LOCAL_AREA), + ]: + handler = levels.handler_for(country, level) + assert handler.year_file_targets(2026) == [] + assert handler.baseline_targets(2026) == [] + assert handler.source_file_targets() == [] + + def test_national_partition_is_stage12s(self): + assert national_partition.national_region_groups("us") == [ + list(group) for group in US_REGION_GROUPS + ] + assert national_partition.national_region_groups("uk") is None + + +@pytest.mark.usefixtures("inputs") +class TestWhatARunReads: + def test_year_file_of_each_us_level(self, default_dataset, state_level_dataset): + utah = RegionResolution( + code="state/ut", scoping_strategy=_state_filter(49), state_code="UT" + ) + utah_district = RegionResolution( + code="congressional_district/UT-01", + scoping_strategy=RowFilterStrategy( + variable_name="congressional_district_geoid", variable_value=4901 + ), + state_code="UT", + ) + + def year_file(level, region, dataset): + return levels.handler_for("us", level).year_file_for( + _run(US, region, dataset) + ) + + assert year_file( + DatasetLevel.NATIONAL, RegionResolution(code="us"), default_dataset + ) == (_national_target()) + assert year_file( + DatasetLevel.STATE_GROUP, _group_region(["state/ca"]), default_dataset + ) == (_national_target()) + assert year_file(DatasetLevel.STATE, utah, state_level_dataset) == ( + _state_target("UT", 49) + ) + assert year_file(DatasetLevel.DISTRICT, utah_district, state_level_dataset) == ( + _state_target("UT", 49) + ) + assert year_file(DatasetLevel.STATE, utah, default_dataset) == ( + _national_target() + ) + + def test_baseline_scope_of_each_level( + self, default_dataset, state_level_dataset, monkeypatch + ): + group = _group_region(["state/ca", "state/wv"]) + utah = RegionResolution( + code="state/ut", scoping_strategy=_state_filter(49), state_code="UT" + ) + uk_default = DatasetSelection("enhanced_frs", "hf://uk", is_default=True) + + def scope(country, level, region, dataset): + return levels.handler_for(country, level).baseline_scope( + _run(country, region, dataset) + ) + + assert scope( + "us", DatasetLevel.NATIONAL, RegionResolution(code="us"), default_dataset + ) == BaselineScope(region="national", scope_key=None) + assert scope( + "us", DatasetLevel.STATE_GROUP, group, default_dataset + ) == BaselineScope( + region=group.code, scope_key=group.scoping_strategy.cache_key + ) + assert scope("us", DatasetLevel.STATE_GROUP, group, state_level_dataset) is None + assert scope("us", DatasetLevel.STATE, utah, state_level_dataset) is None + assert scope("us", DatasetLevel.DISTRICT, utah, state_level_dataset) is None + assert scope( + "uk", DatasetLevel.NATIONAL, RegionResolution(code="uk"), uk_default + ) == BaselineScope(region="national", scope_key=None) + assert ( + scope( + "uk", + DatasetLevel.NATION, + RegionResolution(code="country/wales"), + uk_default, + ) + is None + ) + assert ( + scope( + "uk", + DatasetLevel.LOCAL_AREA, + RegionResolution(code="uk"), + DatasetSelection("microcosm_dense", "hf://dense", is_default=False), + ) + is None + ) + + +@pytest.fixture +def prebuilt_data_folder(inputs, tmp_path, monkeypatch): + """Return a data folder holding the national and Utah 2026 year files.""" + national = tmp_path / "prebuilt" / "us" / "populace_cps" / "all" + utah = tmp_path / "prebuilt" / "us" / "populace_cps_local" / "UT" + for folder, filename in [ + (national, "populace_cps_year_2026.h5"), + (utah, "populace_cps_local_year_2026.h5"), + ]: + folder.mkdir(parents=True) + (folder / filename).write_bytes(b"year file") + reuse_checks = SimpleNamespace(problem=None, checked=[]) + + def year_file_reuse_problem(path, dataset): + reuse_checks.checked.append((Path(path), dataset)) + if isinstance(reuse_checks.problem, Exception): + raise reuse_checks.problem + return reuse_checks.problem + + monkeypatch.setattr(levels_us, "year_file_reuse_problem", year_file_reuse_problem) + return SimpleNamespace( + root=str(tmp_path), national=national, utah=utah, reuse_checks=reuse_checks + ) + + +class TestPrebuiltDatasetFolder: + def _lookup(self, region, dataset, data_folder, *, country=US, year=2026): + return levels.prebuilt_dataset_folder( + _run(country, region, dataset, year=year), data_folder + ) + + def test_a_national_run_reads_the_prebuilt_national_folder( + self, prebuilt_data_folder, default_dataset + ): + found = self._lookup( + RegionResolution(code="us"), default_dataset, prebuilt_data_folder.root + ) + + assert found.folder == str(prebuilt_data_folder.national) + assert found.dataset_source is None + assert prebuilt_data_folder.reuse_checks.checked == [ + ( + prebuilt_data_folder.national / "populace_cps_year_2026.h5", + "populace_cps", + ) + ] + + def test_a_group_run_reads_the_prebuilt_national_folder( + self, prebuilt_data_folder, default_dataset + ): + found = self._lookup( + _group_region(["state/ca"]), default_dataset, prebuilt_data_folder.root + ) + + assert found.folder == str(prebuilt_data_folder.national) + + def test_state_and_district_runs_read_their_states_folder( + self, prebuilt_data_folder, state_level_dataset + ): + for region in [ + RegionResolution( + code="state/ut", scoping_strategy=_state_filter(49), state_code="UT" + ), + RegionResolution( + code="congressional_district/UT-01", + scoping_strategy=RowFilterStrategy( + variable_name="congressional_district_geoid", variable_value=4901 + ), + state_code="UT", + ), + ]: + found = self._lookup(region, state_level_dataset, prebuilt_data_folder.root) + + assert found.folder == str(prebuilt_data_folder.utah) + assert found.dataset_source == "baked_state" + + def test_runs_without_a_prebuilt_file_read_nothing_prebuilt( + self, prebuilt_data_folder, default_dataset, state_level_dataset + ): + wyoming = RegionResolution( + code="state/wy", scoping_strategy=_state_filter(56), state_code="WY" + ) + + assert ( + self._lookup( + RegionResolution(code="us"), + default_dataset, + prebuilt_data_folder.root, + year=2028, + ) + is None + ) + assert ( + self._lookup(wyoming, state_level_dataset, prebuilt_data_folder.root) + is None + ) + assert ( + self._lookup( + RegionResolution(code="place/CA-44000"), + default_dataset, + prebuilt_data_folder.root, + ) + is None + ) + assert ( + self._lookup( + RegionResolution(code="uk"), + DatasetSelection("enhanced_frs", "hf://uk", is_default=True), + prebuilt_data_folder.root, + country=UK, + ) + is None + ) + + def test_settings_that_fail_to_load_read_nothing_prebuilt( + self, prebuilt_data_folder, default_dataset, monkeypatch + ): + def failing_settings(): + msg = "No module named 'policyengine_stage12_persistence'" + raise ModuleNotFoundError(msg) + + monkeypatch.setattr(levels_us, "us_prebuilt", failing_settings) + + assert ( + self._lookup( + RegionResolution(code="us"), default_dataset, prebuilt_data_folder.root + ) + is None + ) + + @pytest.mark.parametrize( + "problem", ["year-file stamp is missing", ImportError("moved helper")] + ) + def test_a_file_that_fails_the_reuse_checks_is_not_read( + self, prebuilt_data_folder, default_dataset, problem + ): + prebuilt_data_folder.reuse_checks.problem = problem + + assert ( + self._lookup( + RegionResolution(code="us"), default_dataset, prebuilt_data_folder.root + ) + is None + ) + + +@pytest.mark.usefixtures("inputs") +class TestWritingWholeDatasetYearFiles: + def test_national_year_file_is_prepared_in_the_data_folder( + self, inputs, tmp_path, monkeypatch + ): + monkeypatch.setenv("POLICYENGINE_DATA_FOLDER", str(tmp_path)) + calls = [] + + def ensure_datasets(**keyword_arguments): + calls.append(keyword_arguments) + (tmp_path / "populace_cps_year_2026.h5").write_bytes(b"year file") + + inputs.us_module.ensure_datasets = ensure_datasets + target = _national_target() + + written = levels.handler_for("us", DatasetLevel.NATIONAL).write_year_files( + 2026, [target], tmp_path / "work" + ) + + assert calls == [ + { + "datasets": ["populace_cps"], + "years": [2026], + "data_folder": str(tmp_path), + } + ] + assert written == {target: tmp_path / "populace_cps_year_2026.h5"} + + def test_a_missing_year_file_fails(self, inputs, tmp_path, monkeypatch): + monkeypatch.setenv("POLICYENGINE_DATA_FOLDER", str(tmp_path)) + inputs.us_module.ensure_datasets = lambda **_keyword_arguments: None + + with pytest.raises(RuntimeError, match="no file"): + levels.handler_for("us", DatasetLevel.NATIONAL).write_year_files( + 2026, [_national_target()], tmp_path / "work" + ) + + +def test_year_file_name(inputs): + assert levels.year_file_name(_state_target("UT", 49)) == ( + "populace_cps_local_year_2026.h5" + ) + + +def test_handler_modules_import_no_run_simulation_feature_module(): + for module in (levels, levels_us, levels_uk, partition): + tree = ast.parse(Path(module.__file__).read_text()) + imported = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imported.update(alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom): + imported.add(node.module or "") + assert not imported & FORBIDDEN_IMPORTS, module.__name__ diff --git a/projects/policyengine-simulation-executor/tests/test_prebuilt_plan.py b/projects/policyengine-simulation-executor/tests/test_prebuilt_plan.py new file mode 100644 index 000000000..3742c9145 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_prebuilt_plan.py @@ -0,0 +1,465 @@ +"""The per-country precompute plan through the level handlers, and its mf2 manifest. + +``plan_artifacts_impl(bucket, country)`` asks each level handler of the +country's settings for its year files and baselines, keys each with the +run_simulation app's identities, and checks the store for each. The US plan +lists the same files as before the handlers: 3 national year files, 153 state +year files and 60 group baselines. The manifest lists every planned file with +the SHA-256 and size the store recorded for it. +""" + +from __future__ import annotations + +import hashlib +import json +from collections import Counter + +import pytest +from fixtures.us_prebuilt_inputs import US_STATE_FIPS, install_us_prebuilt_inputs +from policyengine_simulation_executor import artifact_keys, precompute +from policyengine_simulation_executor import simulation_runtime as runtime +from policyengine_simulation_executor.artifact_store import ArtifactStore +from policyengine_simulation_executor.baseline_artifacts import ( + BaselineIdentityRequest, + deterministic_baseline_id, +) +from policyengine_simulation_executor.precompute_models import ( + BaselinePlanEntry, + BundleVersionIdentity, + PrecomputePlan, + YearFilePlanEntry, +) +from policyengine_simulation_executor.stage12_cache.levels import DatasetLevel +from policyengine_simulation_executor.stage12_runtime.partition import ( + US_REGION_GROUPS, +) + +BUCKET = "bucket-plan" +YEARS = [2026, 2027, 2025] +STATE_CODES = sorted(state_code for state_code, _fips in US_STATE_FIPS) + + +@pytest.fixture +def inputs(monkeypatch): + return install_us_prebuilt_inputs(monkeypatch) + + +@pytest.fixture +def us_plan(inputs): + return precompute.plan_artifacts_impl(BUCKET, "us") + + +class TestUsPlan: + def test_year_files_per_year_national_first_then_states(self, us_plan): + assert us_plan.country == "us" + assert [ + (entry.year, entry.level, entry.subset_code) for entry in us_plan.year_files + ] == [ + row + for year in YEARS + for row in [ + (year, DatasetLevel.NATIONAL, None), + *[(year, DatasetLevel.STATE, code) for code in STATE_CODES], + ] + ] + assert us_plan.source_files == [] + + def test_every_file_planned_before_the_handlers_is_planned_once(self, us_plan): + before_the_handlers = Counter( + [("populace_cps", year, None, None) for year in YEARS] + + [ + ("populace_cps_local", year, code, f"state/{code.lower()}") + for year in YEARS + for code in STATE_CODES + ] + ) + + assert ( + Counter( + (entry.dataset, entry.year, entry.subset_code, entry.region) + for entry in us_plan.year_files + ) + == before_the_handlers + ) + + def test_year_file_entries_carry_their_identity(self, us_plan): + national, utah = ( + us_plan.year_files[0], + next(entry for entry in us_plan.year_files if entry.subset_code == "UT"), + ) + + for entry in (national, utah): + assert entry.country == "us" + assert entry.path == ( + f"year-files/us/{entry.digest}/{entry.dataset}_year_{entry.year}.h5" + ) + assert entry.filename == f"{entry.dataset}_year_{entry.year}.h5" + assert entry.exists is False + assert national.folder == "prebuilt/us/populace_cps/all" + assert national.region is None + assert utah.folder == "prebuilt/us/populace_cps_local/UT" + assert utah.region == "state/ut" + + def test_group_baselines_in_order(self, us_plan): + national_by_year = { + entry.year: entry + for entry in us_plan.year_files + if entry.level == DatasetLevel.NATIONAL + } + + assert [ + (entry.year, entry.request["region_group"]) for entry in us_plan.baselines + ] == [(year, list(group)) for year in YEARS for group in US_REGION_GROUPS] + for entry in us_plan.baselines: + national = national_by_year[entry.year] + assert entry.level == DatasetLevel.STATE_GROUP + assert entry.region == "region_group/" + "+".join( + sorted(entry.request["region_group"]) + ) + assert entry.request["scope"] == "macro" + assert entry.year_file_path == national.path + assert entry.year_file_filename == national.filename + assert entry.folder == national.folder + assert entry.simulation_id.startswith("bl3-") + assert entry.path == (f"baselines/us/{entry.digest}/{entry.storage_id}.h5") + assert us_plan.baselines[15].label == "group 16 of 20" + + def test_the_planned_id_is_the_id_a_run_gets(self, us_plan): + entry = us_plan.baselines[15] + params = dict(entry.request) + region = runtime.resolve_region( + country_module=runtime._country_module("us"), country="us", params=params + ) + dataset = runtime._resolve_dataset_selection(params, region_resolution=region) + + assert ( + deterministic_baseline_id( + BaselineIdentityRequest( + params, + country="us", + dataset=dataset, + policy=None, + region_code=region.code, + scoping_strategy=region.scoping_strategy, + year=entry.year, + ) + ) + == entry.simulation_id + ) + + def test_receipt(self, us_plan): + assert us_plan.receipt == BundleVersionIdentity( + policyengine_version="4.22.0", + policyengine_core_version="3.33.3", + model_version="9.9.9", + data_version="1.2.3", + data_artifact_revision="rev-abc", + default_dataset="populace_cps", + ) + + def test_stored_files_are_marked_and_not_selected(self, inputs): + first_plan = precompute.plan_artifacts_impl(BUCKET, "us") + stored = [first_plan.year_files[0].path, first_plan.baselines[0].path] + inputs.gcs_client.objects.update(dict.fromkeys(stored, b"stored")) + + plan = precompute.plan_artifacts_impl(BUCKET, "us") + work = precompute.select_work(plan, force=False) + + assert [entry.exists for entry in plan.year_files[:2]] == [True, False] + assert work.year_files == plan.year_files[1:] + assert work.baselines == plan.baselines[1:] + assert precompute.select_work(plan, force=True).year_files == plan.year_files + + def test_a_baseline_without_a_fixed_id_stops_the_plan(self, inputs, monkeypatch): + from policyengine_simulation_executor import baseline_artifacts + + monkeypatch.setattr( + baseline_artifacts, + "qualifying_baseline_identity", + lambda _request: None, + ) + + with pytest.raises(RuntimeError, match="diverged"): + precompute.plan_artifacts_impl(BUCKET, "us") + + +@pytest.mark.usefixtures("inputs") +def test_the_uk_plan_is_empty(): + plan = precompute.plan_artifacts_impl(BUCKET, "uk") + + assert plan.country == "uk" + assert (plan.year_files, plan.baselines, plan.source_files) == ([], [], []) + assert plan.receipt.default_dataset == "enhanced_frs" + assert plan.receipt.model_version == "2.0.0" + + +@pytest.mark.usefixtures("inputs") +def test_a_country_without_settings_is_refused(): + with pytest.raises(ValueError, match="fr"): + precompute.plan_artifacts_impl(BUCKET, "fr") + + +SMALL_MANIFEST_JSON = """\ +{ + "artifacts": [ + { + "digest": "national-digest", + "filename": "populace_cps_year_2026.h5", + "folder": "prebuilt/us/populace_cps/all", + "kind": "year_file", + "level": "national", + "path": "year-files/us/national-digest/populace_cps_year_2026.h5", + "region": null, + "sha256": "1111111111111111111111111111111111111111111111111111111111111111", + "size_bytes": 100, + "year": 2026 + }, + { + "digest": "utah-digest", + "filename": "populace_cps_local_year_2026.h5", + "folder": "prebuilt/us/populace_cps_local/UT", + "kind": "year_file", + "level": "state", + "path": "year-files/us/utah-digest/populace_cps_local_year_2026.h5", + "region": "state/ut", + "sha256": "2222222222222222222222222222222222222222222222222222222222222222", + "size_bytes": 200, + "year": 2026 + }, + { + "digest": "group-digest", + "filename": "bl3-0123456789abcdef.h5", + "folder": "prebuilt/us/populace_cps/all", + "kind": "baseline", + "level": "state_group", + "path": "baselines/us/group-digest/bl3-0123456789abcdef.h5", + "region": "region_group/state/ca", + "sha256": "3333333333333333333333333333333333333333333333333333333333333333", + "size_bytes": 300, + "year": 2026 + } + ], + "country": "us", + "receipt": { + "data_artifact_revision": "rev-abc", + "data_version": "1.2.3", + "default_dataset": "populace_cps", + "model_version": "9.9.9", + "policyengine_core_version": "3.33.3", + "policyengine_version": "4.22.0" + }, + "schema": "mf2" +}""" +SMALL_MANIFEST_DIGEST = ( + "17d18b695fc75de7224cec15f59e68e3390218f6b62d3718faf9c72913cb4e4b" +) + + +def _small_plan() -> PrecomputePlan: + national_path = "year-files/us/national-digest/populace_cps_year_2026.h5" + return PrecomputePlan( + country="us", + year_files=[ + YearFilePlanEntry( + country="us", + level=DatasetLevel.NATIONAL, + year=2026, + dataset="populace_cps", + region=None, + subset_code=None, + digest="national-digest", + path=national_path, + filename="populace_cps_year_2026.h5", + folder="prebuilt/us/populace_cps/all", + exists=True, + ), + YearFilePlanEntry( + country="us", + level=DatasetLevel.STATE, + year=2026, + dataset="populace_cps_local", + region="state/ut", + subset_code="UT", + digest="utah-digest", + path="year-files/us/utah-digest/populace_cps_local_year_2026.h5", + filename="populace_cps_local_year_2026.h5", + folder="prebuilt/us/populace_cps_local/UT", + exists=False, + ), + ], + baselines=[ + BaselinePlanEntry( + country="us", + level=DatasetLevel.STATE_GROUP, + year=2026, + region="region_group/state/ca", + label="group 16 of 20", + request={ + "country": "us", + "scope": "macro", + "region_group": ["state/ca"], + "time_period": 2026, + }, + year_file_path=national_path, + year_file_filename="populace_cps_year_2026.h5", + folder="prebuilt/us/populace_cps/all", + digest="group-digest", + path="baselines/us/group-digest/bl3-0123456789abcdef.h5", + simulation_id="bl3-0123456789abcdef", + storage_id="bl3-0123456789abcdef", + exists=False, + ) + ], + receipt=BundleVersionIdentity( + policyengine_version="4.22.0", + policyengine_core_version="3.33.3", + model_version="9.9.9", + data_version="1.2.3", + data_artifact_revision="rev-abc", + default_dataset="populace_cps", + ), + ) + + +def _store_with_metadata(inputs, path, sha256, size_bytes): + inputs.gcs_client.objects[path] = b"x" * size_bytes + inputs.gcs_client.object_metadata[path] = { + "sha256": sha256, + "size_bytes": str(size_bytes), + } + + +class TestManifest: + def test_published_text_and_digest(self, inputs): + plan = _small_plan() + for entry, (fill, size) in zip( + [*plan.year_files, *plan.baselines], + [("1", 100), ("2", 200), ("3", 300)], + strict=True, + ): + _store_with_metadata(inputs, entry.path, fill * 64, size) + + digest = precompute.publish_manifest_impl(BUCKET, plan) + + assert digest == SMALL_MANIFEST_DIGEST + _bucket, path, data, keyword_arguments = inputs.gcs_client.uploads[-1] + assert path == f"manifests/{SMALL_MANIFEST_DIGEST}.json" + assert data.decode() == SMALL_MANIFEST_JSON + assert keyword_arguments == { + "content_type": "application/json", + "if_generation_match": 0, + } + + def test_an_object_without_recorded_metadata_is_hashed(self, inputs): + plan = _small_plan() + for entry in [*plan.year_files, *plan.baselines]: + inputs.gcs_client.objects[entry.path] = entry.path.encode() + + digest = precompute.publish_manifest_impl(BUCKET, plan) + + manifest = json.loads(inputs.gcs_client.objects[f"manifests/{digest}.json"]) + first = manifest["artifacts"][0] + assert first["sha256"] == hashlib.sha256(first["path"].encode()).hexdigest() + assert first["size_bytes"] == len(first["path"]) + + def test_a_missing_object_stops_the_publish(self, inputs): + with pytest.raises(FileNotFoundError): + precompute.publish_manifest_impl(BUCKET, _small_plan()) + assert inputs.gcs_client.uploads == [] + + def test_the_us_manifest_lists_every_planned_file(self, inputs, us_plan): + for entry in [*us_plan.year_files, *us_plan.baselines]: + _store_with_metadata(inputs, entry.path, "f" * 64, 10) + + digest = precompute.publish_manifest_impl(BUCKET, us_plan) + + manifest = json.loads(inputs.gcs_client.objects[f"manifests/{digest}.json"]) + assert manifest["schema"] == "mf2" + assert manifest["country"] == "us" + assert manifest["receipt"] == us_plan.receipt.model_dump() + assert [artifact["kind"] for artifact in manifest["artifacts"]] == ( + ["year_file"] * 156 + ["baseline"] * 60 + ) + assert [artifact["path"] for artifact in manifest["artifacts"]] == [ + entry.path for entry in [*us_plan.year_files, *us_plan.baselines] + ] + assert digest == artifact_keys.canonical_digest(manifest) + + def test_upload_records_the_files_hash_and_size(self, inputs, tmp_path): + local_file = tmp_path / "year.h5" + local_file.write_bytes(b"year file bytes") + + assert ArtifactStore(BUCKET).upload_file("year-files/us/d/f.h5", local_file) + + assert inputs.gcs_client.object_metadata["year-files/us/d/f.h5"] == { + "sha256": hashlib.sha256(b"year file bytes").hexdigest(), + "size_bytes": str(len(b"year file bytes")), + } + + def test_a_source_file_entry_carries_its_sf1_digest(self, inputs): + from policyengine_simulation_executor.precompute_models import ( + SourceFilePlanEntry, + ) + + plan = _small_plan().model_copy( + update={ + "source_files": [ + SourceFilePlanEntry( + country="us", + level=DatasetLevel.NATIONAL, + dataset="populace_cps_local", + digest="sf1-digest", + sha256="ab" * 32, + path=f"sources/us/{'ab' * 32}/populace_cps_local.h5", + filename="populace_cps_local.h5", + folder="prebuilt/us/populace_cps_local/all", + exists=True, + ) + ] + } + ) + for entry in [*plan.year_files, *plan.baselines, *plan.source_files]: + _store_with_metadata(inputs, entry.path, "4" * 64, 400) + + digest = precompute.publish_manifest_impl(BUCKET, plan) + + manifest = json.loads(inputs.gcs_client.objects[f"manifests/{digest}.json"]) + source = manifest["artifacts"][-1] + assert (source["kind"], source["digest"], source["sha256"], source["year"]) == ( + "source_file", + "sf1-digest", + "4" * 64, + None, + ) + + def test_planned_source_files_are_keyed_by_their_sf1_identity( + self, inputs, monkeypatch + ): + from policyengine_simulation_executor.stage12_cache import levels_us + from policyengine_simulation_executor.stage12_cache.levels import ( + SourceFileTarget, + ) + + target = SourceFileTarget( + country="us", + level=DatasetLevel.NATIONAL, + dataset="populace_cps_local", + folder="prebuilt/us/populace_cps_local/all", + ) + monkeypatch.setattr( + levels_us.UsNationalHandler, + "source_file_targets", + lambda _handler: [target], + ) + + (entry,) = precompute.plan_artifacts_impl(BUCKET, "us").source_files + + identity = artifact_keys.source_file_identity(target) + assert (entry.digest, entry.sha256, entry.path) == ( + identity.digest, + identity.dataset_sha256, + identity.store_path, + ) + + def test_the_digest_output_line(self): + assert precompute.manifest_digest_line("abc") == "MANIFEST_DIGEST=abc" diff --git a/projects/policyengine-simulation-executor/tests/test_prebuilt_precompute_run.py b/projects/policyengine-simulation-executor/tests/test_prebuilt_precompute_run.py new file mode 100644 index 000000000..5215849a1 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_prebuilt_precompute_run.py @@ -0,0 +1,313 @@ +"""The precompute run for one country: which builds it starts, and in what order. + +``run_precompute`` takes the six Modal function handles as plain fakes here. +Each fake records its calls in one shared event list, so the tests can check +that a baseline starts only after the build of the year file it reads, and +that publishing waits for every build. +""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass, field +from typing import Any + +import pytest +from policyengine_simulation_executor import precompute +from policyengine_simulation_executor.precompute_models import ( + BaselinePlanEntry, + BundleVersionIdentity, + PrecomputePlan, + YearFilePlanEntry, +) +from policyengine_simulation_executor.stage12_cache.levels import DatasetLevel + +BUCKET = "bucket-run" + + +def _year_file(year, *, level=DatasetLevel.NATIONAL, code=None, exists=False): + dataset = "populace_cps" if code is None else "populace_cps_local" + folder = f"prebuilt/us/{dataset}/{code or 'all'}" + return YearFilePlanEntry( + country="us", + level=level, + year=year, + dataset=dataset, + region=None if code is None else f"state/{code.lower()}", + subset_code=code, + digest=f"yf-{year}-{code or 'all'}", + path=f"year-files/us/yf-{year}-{code or 'all'}/{dataset}_year_{year}.h5", + filename=f"{dataset}_year_{year}.h5", + folder=folder, + exists=exists, + ) + + +def _baseline(year_file, *, level=DatasetLevel.STATE_GROUP, label="group 1 of 20"): + simulation_id = ( + "bl3-" + hashlib.sha256(f"{year_file.path} {label}".encode()).hexdigest()[:16] + ) + return BaselinePlanEntry( + country="us", + level=level, + year=year_file.year, + region="region_group/state/ca", + label=label, + request={"country": "us", "scope": "macro", "time_period": year_file.year}, + year_file_path=year_file.path, + year_file_filename=year_file.filename, + folder=year_file.folder, + digest=f"bl-{simulation_id}", + path=f"baselines/us/bl-{simulation_id}/{simulation_id}.h5", + simulation_id=simulation_id, + storage_id=simulation_id, + exists=False, + ) + + +def _plan(year_files, baselines, country="us"): + return PrecomputePlan( + country=country, + year_files=year_files, + baselines=baselines, + receipt=BundleVersionIdentity( + policyengine_version="4.22.0", + policyengine_core_version="3.33.3", + model_version="9.9.9", + data_version="1.2.3", + data_artifact_revision="rev-abc", + default_dataset="populace_cps", + ), + ) + + +@dataclass +class _Handle: + name: str + events: list[tuple[str, ...]] + result: Any + + def get(self): + self.events.append(("get", self.name)) + return self.result + + +@dataclass +class _RecordingFunction: + name: str + events: list[tuple[str, ...]] + respond: Any + calls: list[tuple[Any, ...]] = field(default_factory=list) + + def remote(self, *arguments): + self.calls.append(arguments) + self.events.append(("remote", self.name)) + return self.respond(*arguments) + + def spawn(self, *arguments): + self.calls.append(arguments) + label = f"{self.name}#{len(self.calls)}" + self.events.append(("spawn", label)) + return _Handle(label, self.events, self.respond(*arguments)) + + +def _year_file_result(entry): + return { + "year": entry["year"], + "path": entry["path"], + "uploaded": True, + "size_bytes": 10, + "build_seconds": 1.0, + } + + +def _functions(plan, *, determinism_equal=True): + events: list[tuple[str, ...]] = [] + functions = precompute.PrecomputeFunctions( + plan_artifacts=_RecordingFunction( + "plan_artifacts", events, lambda _bucket, _country: plan.model_dump() + ), + build_dataset=_RecordingFunction( + "build_dataset", + events, + lambda _bucket, entry: _year_file_result(entry), + ), + build_state_datasets=_RecordingFunction( + "build_state_datasets", + events, + lambda _bucket, _year, entries: [ + _year_file_result(entry) for entry in entries + ], + ), + compute_baseline=_RecordingFunction( + "compute_baseline", + events, + lambda _bucket, entry: { + "year": entry["year"], + "label": entry["label"], + "simulation_id": entry["simulation_id"], + "outcome": "miss", + "uploaded": True, + "compute_seconds": 2.0, + "size_bytes": 20, + }, + ), + verify_determinism=_RecordingFunction( + "verify_determinism", + events, + lambda _bucket, _entry: { + "equal": determinism_equal, + "differences": [] + if determinism_equal + else ["person.age: values differ"], + }, + ), + publish_manifest=_RecordingFunction( + "publish_manifest", events, lambda _bucket, _plan: "manifest-digest" + ), + ) + return functions, events + + +def _run(plan, **keyword_arguments): + functions, events = _functions(plan, **keyword_arguments) + echoed: list[str] = [] + digest = precompute.run_precompute( + BUCKET, + country=plan.country, + force=False, + functions=functions, + echo=echoed.append, + ) + return functions, events, echoed, digest + + +def test_plans_for_the_requested_country(): + functions, _events, _echoed, _digest = _run(_plan([], [], country="uk")) + + assert functions.plan_artifacts.calls == [(BUCKET, "uk")] + + +def test_builds_only_missing_files_and_groups_subset_builds(): + national_2026 = _year_file(2026, exists=True) + national_2027 = _year_file(2027) + states = [ + _year_file(year, level=DatasetLevel.STATE, code=code) + for year in (2026, 2027) + for code in ("UT", "WY") + ] + functions, _events, _echoed, _digest = _run( + _plan([national_2026, national_2027, *states], []) + ) + + assert [call[1]["path"] for call in functions.build_dataset.calls] == [ + national_2027.path + ] + assert [ + (call[1], [entry["subset_code"] for entry in call[2]]) + for call in functions.build_state_datasets.calls + ] == [(2026, ["UT", "WY"]), (2027, ["UT", "WY"])] + + +def test_baselines_wait_for_whole_dataset_builds_and_publishing_waits_for_all(): + national = _year_file(2026) + utah = _year_file(2026, level=DatasetLevel.STATE, code="UT") + group = _baseline(national) + _functions_used, events, echoed, digest = _run(_plan([national, utah], [group])) + + def position(event): + return events.index(event) + + assert position(("get", "build_dataset#1")) < position( + ("spawn", "compute_baseline#1") + ) + assert position(("get", "build_state_datasets#1")) < position( + ("remote", "publish_manifest") + ) + assert position(("spawn", "build_state_datasets#1")) < position( + ("get", "build_dataset#1") + ) + assert digest == "manifest-digest" + assert echoed[-1] == "MANIFEST_DIGEST=manifest-digest" + + +def test_a_baseline_on_a_subset_file_waits_for_that_build(): + utah = _year_file(2026, level=DatasetLevel.STATE, code="UT") + state_baseline = _baseline(utah, level=DatasetLevel.STATE, label="state/ut") + _functions_used, events, _echoed, _digest = _run(_plan([utah], [state_baseline])) + + assert events.index(("get", "build_state_datasets#1")) < events.index( + ("spawn", "compute_baseline#1") + ) + + +def test_one_determinism_check_per_level_that_computed_baselines(): + national = _year_file(2026, exists=True) + utah = _year_file(2026, level=DatasetLevel.STATE, code="UT", exists=True) + groups = [_baseline(national, label=f"group {index} of 20") for index in (1, 2)] + state_baseline = _baseline(utah, level=DatasetLevel.STATE, label="state/ut") + functions, _events, _echoed, _digest = _run( + _plan([national, utah], [*groups, state_baseline]) + ) + + assert [call[1]["label"] for call in functions.verify_determinism.calls] == [ + "group 1 of 20", + "state/ut", + ] + + +def test_a_run_with_nothing_missing_starts_nothing(): + national = _year_file(2026, exists=True) + stored_group = _baseline(national).model_copy(update={"exists": True}) + functions, _events, _echoed, digest = _run(_plan([national], [stored_group])) + + assert functions.build_dataset.calls == [] + assert functions.build_state_datasets.calls == [] + assert functions.compute_baseline.calls == [] + assert functions.verify_determinism.calls == [] + assert digest == "manifest-digest" + + +def test_a_failed_determinism_check_stops_before_publishing(): + national = _year_file(2026) + functions, events = _functions( + _plan([national], [_baseline(national)]), determinism_equal=False + ) + + with pytest.raises(SystemExit, match=r"person\.age"): + precompute.run_precompute( + BUCKET, country="us", force=False, functions=functions, echo=lambda _: None + ) + assert ("remote", "publish_manifest") not in events + + +def test_a_plan_with_source_files_to_copy_stops_before_any_build(): + """Nothing copies source files yet, so a plan that needs one fails first. + + Otherwise the run would build every file and then fail to publish a + manifest listing a source file that was never stored. + """ + from policyengine_simulation_executor.precompute_models import SourceFilePlanEntry + + national = _year_file(2026) + source = SourceFilePlanEntry( + country="us", + level=DatasetLevel.NATIONAL, + dataset="populace_cps_local", + digest="sf1-digest", + sha256="ab" * 32, + path=f"sources/us/{'ab' * 32}/populace_cps_local.h5", + filename="populace_cps_local.h5", + folder="prebuilt/us/populace_cps_local/all", + exists=False, + ) + plan = _plan([national], [_baseline(national)]).model_copy( + update={"source_files": [source]} + ) + functions, events = _functions(plan) + + with pytest.raises(SystemExit, match="source file"): + precompute.run_precompute( + BUCKET, country="us", force=False, functions=functions, echo=lambda _: None + ) + assert events == [("remote", "plan_artifacts")] diff --git a/projects/policyengine-simulation-executor/tests/test_state_datasets.py b/projects/policyengine-simulation-executor/tests/test_prebuilt_state_files.py similarity index 68% rename from projects/policyengine-simulation-executor/tests/test_state_datasets.py rename to projects/policyengine-simulation-executor/tests/test_prebuilt_state_files.py index 24d705fc6..1aa2126f3 100644 --- a/projects/policyengine-simulation-executor/tests/test_state_datasets.py +++ b/projects/policyengine-simulation-executor/tests/test_prebuilt_state_files.py @@ -1,29 +1,26 @@ -"""The main path's baked per-state datasets: their folders and the runtime lookup.""" +"""A state or district run reads its state's prebuilt year file, as .py would reuse it. + +These use the installed bundle's state-level dataset and real year files +written with .py's own ``save()`` and year-file stamp, so .py's real reuse +checks decide. +""" import contextlib from pathlib import Path from types import SimpleNamespace import pytest -from policyengine_simulation_executor import state_datasets +from policyengine.core.scoping_strategy import RowFilterStrategy +from policyengine_simulation_executor.region_resolution import RegionResolution from policyengine_simulation_executor.release_bundle import get_country_release_bundle from policyengine_simulation_executor.simulation_runtime import DatasetSelection +from policyengine_simulation_executor.stage12_cache import levels +STATE_FIPS = {"UT": 49, "WY": 56} -def test_state_dataset_relative_folder_names_the_dataset_and_the_state(): - assert ( - state_datasets.state_dataset_relative_folder("populace_us_2024_acs_local", "ut") - == "state-datasets/populace_us_2024_acs_local/UT" - ) - -def test_state_dataset_folder_sits_under_the_data_folder(): - assert ( - state_datasets.state_dataset_folder( - "/opt/policyengine/data", "populace_us_2024_acs_local", "UT" - ) - == "/opt/policyengine/data/state-datasets/populace_us_2024_acs_local/UT" - ) +def _state_folder(data_folder, dataset, state_code): + return Path(data_folder) / levels.prebuilt_folder("us", dataset, state_code) @pytest.fixture @@ -42,9 +39,7 @@ def regional_selection(): def baked_utah(tmp_path): from fixtures.state_dataset_sources import REGIONAL_DATASET, write_year_file - folder = Path( - state_datasets.state_dataset_folder(str(tmp_path), REGIONAL_DATASET, "UT") - ) + folder = _state_folder(tmp_path, REGIONAL_DATASET, "UT") folder.mkdir(parents=True) return SimpleNamespace( data_folder=str(tmp_path), @@ -54,53 +49,49 @@ def baked_utah(tmp_path): def _lookup(baked, selection, *, state_code="UT", year=2026, country="us"): - return state_datasets.baked_state_data_folder( - country=country, - selection=selection, + region = RegionResolution( + code=f"state/{(state_code or 'xx').lower()}", + scoping_strategy=RowFilterStrategy( + variable_name="state_fips", variable_value=STATE_FIPS.get(state_code, 0) + ), state_code=state_code, - year=year, - data_folder=baked.data_folder, ) + found = levels.prebuilt_dataset_folder( + levels.RunScope(country=country, year=year, region=region, dataset=selection), + baked.data_folder, + ) + return None if found is None else found.folder -def test_a_state_reads_its_baked_folder(baked_utah, regional_selection): +def test_a_state_reads_its_prebuilt_folder(baked_utah, regional_selection): assert _lookup(baked_utah, regional_selection) == str(baked_utah.folder) -def test_a_year_without_a_baked_file_reads_nothing_baked( +def test_a_year_without_a_prebuilt_file_reads_nothing_prebuilt( baked_utah, regional_selection ): assert _lookup(baked_utah, regional_selection, year=2028) is None -def test_a_state_without_a_baked_folder_reads_nothing_baked( +def test_a_state_without_a_prebuilt_folder_reads_nothing_prebuilt( baked_utah, regional_selection ): assert _lookup(baked_utah, regional_selection, state_code="WY") is None -def test_an_unstamped_file_reads_nothing_baked(tmp_path, regional_selection): +def test_an_unstamped_file_reads_nothing_prebuilt(tmp_path, regional_selection): from fixtures.state_dataset_sources import REGIONAL_DATASET, write_year_file - folder = Path( - state_datasets.state_dataset_folder(str(tmp_path), REGIONAL_DATASET, "UT") - ) + folder = _state_folder(tmp_path, REGIONAL_DATASET, "UT") folder.mkdir(parents=True) write_year_file(folder, year=2026, stamp=False) assert ( - state_datasets.baked_state_data_folder( - country="us", - selection=regional_selection, - state_code="UT", - year=2026, - data_folder=str(tmp_path), - ) - is None + _lookup(SimpleNamespace(data_folder=str(tmp_path)), regional_selection) is None ) -def test_a_file_with_another_spm_profile_reads_nothing_baked( +def test_a_file_with_another_spm_profile_reads_nothing_prebuilt( baked_utah, regional_selection ): from policyengine.tax_benefit_models.us.legacy_spm.record import ( @@ -124,7 +115,7 @@ def test_a_file_with_another_spm_profile_reads_nothing_baked( assert _lookup(baked_utah, regional_selection) is None -def test_the_default_dataset_reads_nothing_baked(baked_utah): +def test_the_default_dataset_reads_nothing_prebuilt(baked_utah): bundle = get_country_release_bundle("us") default = DatasetSelection( name=bundle.default_dataset, uri=bundle.default_dataset_uri, is_default=True @@ -133,16 +124,17 @@ def test_the_default_dataset_reads_nothing_baked(baked_utah): assert _lookup(baked_utah, default) is None -def test_a_region_without_a_state_reads_nothing_baked(baked_utah, regional_selection): +def test_a_region_without_a_state_reads_nothing_prebuilt( + baked_utah, regional_selection +): assert _lookup(baked_utah, regional_selection, state_code=None) is None assert _lookup(baked_utah, regional_selection, country="uk") is None -def test_a_district_request_loads_its_states_baked_file( +def test_a_district_request_loads_its_states_prebuilt_file( monkeypatch, baked_utah, regional_selection ): """A district resolves to its state's code and reads the state's file.""" - from policyengine.core.scoping_strategy import RowFilterStrategy from policyengine_simulation_executor import simulation_runtime district = SimpleNamespace( @@ -153,10 +145,18 @@ def test_a_district_request_loads_its_states_baked_file( parent_code="state/ut", state_code="UT", ) + utah = SimpleNamespace( + scoping_strategy=RowFilterStrategy( + variable_name="state_fips", variable_value=49 + ) + ) country_module = SimpleNamespace( model=SimpleNamespace( version="2.2.1", - get_region={"congressional_district/UT-01": district}.get, + get_region={ + "congressional_district/UT-01": district, + "state/ut": utah, + }.get, ) ) loads = [] diff --git a/projects/policyengine-simulation-executor/tests/test_precompute.py b/projects/policyengine-simulation-executor/tests/test_precompute.py index 29e90d210..e553ed4a8 100644 --- a/projects/policyengine-simulation-executor/tests/test_precompute.py +++ b/projects/policyengine-simulation-executor/tests/test_precompute.py @@ -1,102 +1,71 @@ -"""Tests for the precompute library's planning, manifests and orchestration. +"""Tests for the precompute's typed schemas at the Modal serialization boundary. -They also pin the writer==reader identity contract. No Modal involved — -the library takes function handles as parameters, so the orchestration runs -against plain fakes here. Everything structured is a strict model from -precompute_models; the fakes speak dicts, exactly like Modal's -serialization boundary does. +The plan, manifest and orchestration through the level handlers are tested +in ``test_prebuilt_plan`` and ``test_prebuilt_precompute_run``. """ import pytest from policyengine_simulation_executor import precompute -from policyengine_simulation_executor.artifact_keys import canonical_digest from policyengine_simulation_executor.precompute_models import ( - ArtifactManifest, BaselinePlanEntry, BundleVersionIdentity, - DatasetPlanEntry, PrecomputePlan, - StateDatasetPlanEntry, + YearFilePlanEntry, ) +from policyengine_simulation_executor.stage12_cache.levels import DatasetLevel from pydantic import ValidationError -def _receipt() -> BundleVersionIdentity: - return BundleVersionIdentity( - policyengine_version="4.22.0", - model_version="1.0.0", - data_version="1.2.3", - data_artifact_revision="rev-abc", - default_dataset="populace_cps", - ) - - def _plan() -> PrecomputePlan: + national_path = "year-files/us/d1/populace_year_2026.h5" return PrecomputePlan( - datasets=[ - DatasetPlanEntry( + country="us", + year_files=[ + YearFilePlanEntry( + country="us", + level=DatasetLevel.NATIONAL, year=2026, + dataset="populace", + region=None, + subset_code=None, digest="d1", - path="datasets/us/d1/populace_year_2026.h5", + path=national_path, filename="populace_year_2026.h5", - exists=True, - ), - DatasetPlanEntry( - year=2027, - digest="d2", - path="datasets/us/d2/populace_year_2027.h5", - filename="populace_year_2027.h5", + folder="prebuilt/us/populace/all", exists=False, - ), + ) ], baselines=[ BaselinePlanEntry( + country="us", + level=DatasetLevel.STATE_GROUP, year=2026, - group=["state/ca"], region="region_group/state/ca", + label="group 16 of 20", + request={ + "country": "us", + "scope": "macro", + "region_group": ["state/ca"], + "time_period": 2026, + }, + year_file_path=national_path, + year_file_filename="populace_year_2026.h5", + folder="prebuilt/us/populace/all", digest="b1", - path="baselines/us/b1/bl1-aaaa.h5", - simulation_id="bl1-aaaa", - exists=True, - ), - BaselinePlanEntry( - year=2027, - group=["state/ca"], - region="region_group/state/ca", - digest="b2", - path="baselines/us/b2/bl1-bbbb.h5", - simulation_id="bl1-bbbb", + path="baselines/us/b1/bl3-aaaa.h5", + simulation_id="bl3-aaaa", + storage_id="bl3-aaaa", exists=False, - ), + ) ], - receipt=_receipt(), - ) - - -def _state_dataset_entry(year: int, state_code: str, *, exists: bool): - digest = f"sd-{year}-{state_code}" - return StateDatasetPlanEntry( - year=year, - state_code=state_code, - region=f"state/{state_code.lower()}", - dataset="populace_local", - digest=digest, - path=f"state-datasets/us/{digest}/populace_local_year_{year}.h5", - filename=f"populace_local_year_{year}.h5", - folder=f"state-datasets/populace_local/{state_code}", - exists=exists, - ) - - -def _plan_with_state_datasets() -> PrecomputePlan: - return _plan().model_copy( - update={ - "state_datasets": [ - _state_dataset_entry(2026, "UT", exists=True), - _state_dataset_entry(2026, "WY", exists=False), - _state_dataset_entry(2027, "UT", exists=False), - ] - } + receipt=BundleVersionIdentity( + policyengine_version="4.22.0", + policyengine_core_version="3.33.3", + model_version="1.0.0", + data_version="1.2.3", + data_artifact_revision="rev-abc", + default_dataset="populace", + ), ) @@ -117,6 +86,12 @@ def test_missing_keys_are_rejected(self): with pytest.raises(ValidationError): PrecomputePlan.model_validate(payload) + def test_an_unknown_level_is_rejected(self): + payload = _plan().model_dump() + payload["year_files"][0]["level"] = "county" + with pytest.raises(ValidationError): + PrecomputePlan.model_validate(payload) + def test_artifact_outcome_mirrors_runtime_constants(self): """The outcome Literal must track baseline_artifacts.OUTCOME_*. @@ -134,442 +109,52 @@ def test_artifact_outcome_mirrors_runtime_constants(self): ba.OUTCOME_MISS, } + def test_the_manifest_schema_label(self): + assert precompute.MANIFEST_SCHEMA == "mf2" -class TestPlanning: - def test_select_work_computes_only_misses(self): - work = precompute.select_work(_plan(), force=False) - assert [entry.year for entry in work.datasets] == [2027] - assert [entry.simulation_id for entry in work.baselines] == ["bl1-bbbb"] - - def test_force_selects_everything(self): - work = precompute.select_work(_plan(), force=True) - assert len(work.datasets) == 2 - assert len(work.baselines) == 2 - - def test_select_work_computes_only_missing_state_datasets(self): - work = precompute.select_work(_plan_with_state_datasets(), force=False) - assert [(entry.year, entry.state_code) for entry in work.state_datasets] == [ - (2026, "WY"), - (2027, "UT"), - ] - - def test_force_selects_every_state_dataset(self): - work = precompute.select_work(_plan_with_state_datasets(), force=True) - assert len(work.state_datasets) == 3 - - def test_a_plan_without_state_datasets_selects_none(self): - assert precompute.select_work(_plan(), force=False).state_datasets == [] - - def test_plan_with_state_datasets_round_trips_through_the_modal_boundary(self): - plan = _plan_with_state_datasets() - assert PrecomputePlan.model_validate(plan.model_dump()) == plan - - def test_years_are_in_priority_order(self): - assert precompute.PRECOMPUTE_YEARS == [2026, 2027, 2025] - - def test_precompute_years_cover_runtime_default_year(self): - """The runtime default year must be one of the precomputed years. - - The image bakes exactly the precomputed years, so otherwise every - default request pays a runtime dataset build. - """ - from policyengine_simulation_executor.simulation_runtime import DEFAULT_YEAR - - assert DEFAULT_YEAR in precompute.PRECOMPUTE_YEARS - - def test_manifest_lists_every_artifact_with_runtime_filenames(self): - manifest = precompute.build_manifest(_plan()) - assert manifest.manifest_schema == precompute.MANIFEST_SCHEMA - assert manifest.receipt == _receipt() - by_type: dict[str, list] = {} - for artifact in manifest.artifacts: - by_type.setdefault(artifact.type, []).append(artifact) - assert [a.filename for a in by_type["dataset"]] == [ - "populace_year_2026.h5", - "populace_year_2027.h5", - ] - # Baseline runtime filename is {simulation_id}.h5 — the exact name - # Simulation.ensure() resolves beside the dataset. - assert [a.filename for a in by_type["baseline"]] == [ - "bl1-aaaa.h5", - "bl1-bbbb.h5", - ] - - def test_manifest_lists_state_datasets_after_the_others_in_plan_order(self): - plan = _plan_with_state_datasets() - - manifest = precompute.build_manifest(plan) - - assert [artifact.type for artifact in manifest.artifacts] == [ - "dataset", - "dataset", - "baseline", - "baseline", - "state_dataset", - "state_dataset", - "state_dataset", - ] - state_artifacts = [ - artifact.model_dump() - for artifact in manifest.artifacts - if artifact.type == "state_dataset" - ] - assert state_artifacts == [ - { - "type": "state_dataset", - "path": entry.path, - "filename": entry.filename, - "folder": entry.folder, - "state_code": entry.state_code, - "year": entry.year, - "digest": entry.digest, - } - for entry in plan.state_datasets - ] - - def test_manifest_with_state_datasets_round_trips_its_wire_shape(self): - payload = precompute.build_manifest( - _plan_with_state_datasets() - ).canonical_payload() - - assert ArtifactManifest.model_validate(payload).canonical_payload() == payload - - def test_a_state_dataset_entry_must_name_its_folder_and_state(self): - payload = precompute.build_manifest( - _plan_with_state_datasets() - ).canonical_payload() - del payload["artifacts"][-1]["folder"] - - with pytest.raises(ValidationError): - ArtifactManifest.model_validate(payload) - - def test_manifest_payload_is_wire_compatible(self): - """The typed manifest must digest identically to the published dict shape. - - The manifest is content-addressed, so key names matter too — note - "schema", not "manifest_schema". - """ - raw = { - "schema": "mf1", - "country": "us", - "receipt": { - "policyengine_version": "4.22.0", - "model_version": "1.0.0", - "data_version": "1.2.3", - "data_artifact_revision": "rev-abc", - "default_dataset": "populace_cps", - }, - "artifacts": [ - { - "type": "dataset", - "path": "datasets/us/d1/populace_year_2026.h5", - "filename": "populace_year_2026.h5", - "year": 2026, - "digest": "d1", - }, - { - "type": "dataset", - "path": "datasets/us/d2/populace_year_2027.h5", - "filename": "populace_year_2027.h5", - "year": 2027, - "digest": "d2", - }, - { - "type": "baseline", - "path": "baselines/us/b1/bl1-aaaa.h5", - "filename": "bl1-aaaa.h5", - "year": 2026, - "digest": "b1", - }, - { - "type": "baseline", - "path": "baselines/us/b2/bl1-bbbb.h5", - "filename": "bl1-bbbb.h5", - "year": 2027, - "digest": "b2", - }, - ], - } - payload = precompute.build_manifest(_plan()).canonical_payload() - assert payload == raw - assert canonical_digest(payload) == canonical_digest(raw) - # And the wire shape validates back into the model. - assert ArtifactManifest.model_validate(raw).canonical_payload() == raw - - -class FakeHandle: - def __init__(self, result): - self._result = result - def get(self): - return self._result +def test_us_years_are_in_priority_order_and_cover_the_runtime_default_year(): + """The runtime default year must be one of the precomputed years. - -class FakeFunction: - """Stands in for a Modal function handle (.remote / .spawn). - - Speaks dicts only, as the real boundary does. - """ - - def __init__(self, result=None, results_by_year=None): - self.result = result - self.results_by_year = results_by_year or {} - self.remote_calls = [] - self.spawn_calls = [] - - def remote(self, *args): - self.remote_calls.append(args) - return self.result - - def spawn(self, *args): - self.spawn_calls.append(args) - year = args[1]["year"] if len(args) > 1 else None - return FakeHandle(self.results_by_year.get(year, self.result)) - - -def _dataset_result(year): - return { - "year": year, - "path": f"datasets/us/d/populace_year_{year}.h5", - "uploaded": True, - "build_seconds": 1.0, - "size_bytes": 10, - } - - -def _baseline_result(year): - return { - "year": year, - "group": ["state/ca"], - "simulation_id": f"bl1-{year}", - "outcome": "miss", - "uploaded": True, - "compute_seconds": 2.0, - "size_bytes": 10, - } - - -class RecordingFunction: - """A Modal handle fake that logs, in one shared list, when it is used. - - ``results`` maps the spawned year to the result returned. The year is the - second argument itself (a state build) or that plan entry's ``year``. + The image bakes exactly the precomputed years, so otherwise every + default request pays a runtime dataset build. """ + from policyengine_simulation_executor.simulation_runtime import DEFAULT_YEAR + from policyengine_simulation_executor.stage12_cache.levels_us import ( + US_PREBUILT_YEARS, + ) - def __init__(self, name, log, results): - self.name = name - self.log = log - self.results = results - self.spawn_calls = [] - - def spawn(self, *args): - self.spawn_calls.append(args) - year = args[1] if isinstance(args[1], int) else args[1]["year"] - self.log.append(("spawn", self.name, year)) - log, name, result = self.log, self.name, self.results[year] + assert US_PREBUILT_YEARS == (2026, 2027, 2025) + assert DEFAULT_YEAR in US_PREBUILT_YEARS - class Handle: - def get(self): - log.append(("get", name, year)) - return result - return Handle() +def test_a_malformed_worker_result_fails_loudly(): + plan = _plan() + class _Handle: + def get(self): + return {"year": 2026, "unexpected": "shape"} -def _state_build_result( - year, state_code, *, uploaded=True, size_bytes=100, build_seconds=30.0 -): - return { - "year": year, - "state_code": state_code, - "path": ( - f"state-datasets/us/sd-{year}-{state_code}/populace_local_year_{year}.h5" - ), - "uploaded": uploaded, - "size_bytes": size_bytes, - "build_seconds": build_seconds, - } + class _Function: + def remote(self, *_arguments): + return plan.model_dump() + def spawn(self, *_arguments): + return _Handle() -class TestRunPrecompute: - def _functions(self, verify_result=None): - return { - "plan_artifacts": FakeFunction(result=_plan().model_dump()), - "build_dataset": FakeFunction( - results_by_year={2027: _dataset_result(2027)} - ), - "build_state_datasets": RecordingFunction("build_state_datasets", [], {}), - "compute_baseline": FakeFunction( - results_by_year={2027: _baseline_result(2027)} - ), - "verify_determinism": FakeFunction( - result=verify_result or {"equal": True, "differences": []} - ), - "publish_manifest": FakeFunction(result="digest-123"), - } - - def _run(self, functions, *, force=False): - lines = [] - digest = precompute.run_precompute( + function = _Function() + with pytest.raises(ValidationError): + precompute.run_precompute( "bucket-x", - force=force, - functions=precompute.PrecomputeFunctions(**functions), - echo=lines.append, - ) - return digest, lines - - def test_spawns_only_misses_and_gates_on_first_computed(self): - functions = self._functions() - digest, _lines = self._run(functions) - - (dataset_spawn,) = functions["build_dataset"].spawn_calls - assert dataset_spawn[0] == "bucket-x" - assert dataset_spawn[1] == _plan().datasets[1].model_dump() - (baseline_spawn,) = functions["compute_baseline"].spawn_calls - assert baseline_spawn[1] == _plan().baselines[1].model_dump() - # The gate probes the first computed baseline, with its plan entry. - (verify_call,) = functions["verify_determinism"].remote_calls - assert verify_call[1]["simulation_id"] == "bl1-bbbb" - assert digest == "digest-123" - # The manifest publishes the FULL plan, never the miss-only work - # subset: the fetch layer needs every artifact listed. - assert functions["publish_manifest"].remote_calls == [ - ("bucket-x", _plan().model_dump()) - ] - - def test_last_echo_line_is_the_digest_contract(self): - _, lines = self._run(self._functions()) - assert lines[-1] == "MANIFEST_DIGEST=digest-123" - assert lines[-1].startswith(precompute.MANIFEST_DIGEST_PREFIX) - - def test_noop_run_spawns_nothing_and_skips_the_gate(self): - functions = self._functions() - noop_plan = _plan() - for entry in noop_plan.datasets + noop_plan.baselines: - entry.exists = True - functions["plan_artifacts"] = FakeFunction(result=noop_plan.model_dump()) - - digest, lines = self._run(functions) - assert functions["build_dataset"].spawn_calls == [] - assert functions["compute_baseline"].spawn_calls == [] - assert functions["verify_determinism"].remote_calls == [] - # The manifest still publishes — the full plan — because a no-op - # run must refresh nothing but the deploy still needs a digest. - assert digest == "digest-123" - assert lines[-1] == "MANIFEST_DIGEST=digest-123" - assert functions["publish_manifest"].remote_calls == [ - ("bucket-x", noop_plan.model_dump()) - ] - - def test_failed_gate_aborts_before_publishing(self): - functions = self._functions( - verify_result={"equal": False, "differences": ["person.age: values differ"]} - ) - with pytest.raises(SystemExit, match="values differ"): - self._run(functions) - assert functions["publish_manifest"].remote_calls == [] - - def _state_run(self, *, uploaded_wyoming=True): - log = [] - functions = self._functions() - functions["plan_artifacts"] = FakeFunction( - result=_plan_with_state_datasets().model_dump() - ) - functions["build_state_datasets"] = RecordingFunction( - "build_state_datasets", - log, - { - 2026: [ - _state_build_result( - 2026, "WY", uploaded=uploaded_wyoming, build_seconds=40.5 - ), - ], - 2027: [_state_build_result(2027, "UT", size_bytes=250)], - }, - ) - functions["compute_baseline"] = RecordingFunction( - "compute_baseline", log, {2027: _baseline_result(2027)} - ) - publish = functions["publish_manifest"] - - def publish_remote(*args): - log.append(("remote", "publish_manifest", None)) - return FakeFunction.remote(publish, *args) - - publish.remote = publish_remote - digest, lines = self._run(functions) - return functions, log, digest, lines - - def test_spawns_one_state_build_per_year_with_its_missing_entries(self): - functions, _log, _digest, _lines = self._state_run() - - plan = _plan_with_state_datasets() - assert functions["build_state_datasets"].spawn_calls == [ - ("bucket-x", 2026, [plan.state_datasets[1].model_dump()]), - ("bucket-x", 2027, [plan.state_datasets[2].model_dump()]), - ] - - def test_waits_for_state_builds_only_before_publishing(self): - _functions, log, _digest, _lines = self._state_run() - - first_state_get = log.index(("get", "build_state_datasets", 2026)) - assert log.index(("spawn", "build_state_datasets", 2026)) < log.index( - ("spawn", "compute_baseline", 2027) - ) - assert log.index(("get", "compute_baseline", 2027)) < first_state_get - assert first_state_get < log.index(("remote", "publish_manifest", None)) - - def test_reports_each_builds_uploads_bytes_and_time(self): - _functions, _log, _digest, lines = self._state_run(uploaded_wyoming=False) - - assert ( - "State datasets 2026 populace_local: 1 built, 0 uploaded " - "(0 bytes) in 40.5 s" - ) in lines - assert ( - "State datasets 2027 populace_local: 1 built, 1 uploaded " - "(250 bytes) in 30.0 s" - ) in lines - assert lines[-1] == "MANIFEST_DIGEST=digest-123" - - def test_spawns_one_state_build_per_year_and_dataset(self): - log = [] - functions = self._functions() - other = _state_dataset_entry(2026, "ID", exists=False).model_copy( - update={"dataset": "populace_other", "folder": "state-datasets/o/ID"} - ) - plan = _plan_with_state_datasets() - plan = plan.model_copy(update={"state_datasets": [*plan.state_datasets, other]}) - functions["plan_artifacts"] = FakeFunction(result=plan.model_dump()) - functions["build_state_datasets"] = RecordingFunction( - "build_state_datasets", - log, - { - 2026: [_state_build_result(2026, "WY")], - 2027: [_state_build_result(2027, "UT")], - }, - ) - - self._run(functions) - - assert [ - (args[1], [entry["dataset"] for entry in args[2]]) - for args in functions["build_state_datasets"].spawn_calls - ] == [ - (2026, ["populace_local"]), - (2027, ["populace_local"]), - (2026, ["populace_other"]), - ] - - def test_a_run_without_state_datasets_spawns_no_state_build(self): - functions = self._functions() - self._run(functions) - assert functions["build_state_datasets"].spawn_calls == [] - - def test_malformed_worker_result_fails_loudly(self): - functions = self._functions() - functions["build_dataset"] = FakeFunction( - results_by_year={2027: {"year": 2027, "unexpected": "shape"}} + country="us", + force=False, + functions=precompute.PrecomputeFunctions( + plan_artifacts=function, + build_dataset=function, + build_state_datasets=function, + compute_baseline=function, + verify_determinism=function, + publish_manifest=function, + ), + echo=lambda _line: None, ) - with pytest.raises(ValidationError): - self._run(functions) diff --git a/projects/policyengine-simulation-executor/tests/test_precompute_app.py b/projects/policyengine-simulation-executor/tests/test_precompute_app.py index 3dc5874f6..beb30a144 100644 --- a/projects/policyengine-simulation-executor/tests/test_precompute_app.py +++ b/projects/policyengine-simulation-executor/tests/test_precompute_app.py @@ -103,36 +103,33 @@ def test_state_dataset_wrapper_validates_entries_in_and_dumps_results_out( ): from policyengine_simulation_executor import precompute as lib from policyengine_simulation_executor.precompute_models import ( - StateDatasetBuildResult, - StateDatasetPlanEntry, + YearFileBuildResult, + YearFilePlanEntry, ) - entry = StateDatasetPlanEntry( + entry = YearFilePlanEntry( + country="us", + level="state", year=2026, - state_code="UT", - region="state/ut", dataset="populace_local", - digest="sd1", - path="state-datasets/us/sd1/populace_local_year_2026.h5", + region="state/ut", + subset_code="UT", + digest="yf1", + path="year-files/us/yf1/populace_local_year_2026.h5", filename="populace_local_year_2026.h5", - folder="state-datasets/populace_local/UT", + folder="prebuilt/us/populace_local/UT", exists=False, ) - result = StateDatasetBuildResult( - year=2026, - state_code="UT", - path=entry.path, - uploaded=True, - size_bytes=5, - build_seconds=1.0, + result = YearFileBuildResult( + year=2026, path=entry.path, uploaded=True, size_bytes=5, build_seconds=1.0 ) seen = {} - def fake_build_state_datasets(bucket, year, expected): + def fake_build_year_files(bucket, year, expected): seen["call"] = (bucket, year, expected) return [result] - monkeypatch.setattr(lib, "build_state_datasets_impl", fake_build_state_datasets) + monkeypatch.setattr(lib, "build_year_files_impl", fake_build_year_files) assert precompute_module.build_state_datasets( "bucket-x", 2026, [entry.model_dump()] @@ -159,32 +156,52 @@ def _sample_plan(): return PrecomputePlan.model_validate( { - "datasets": [ + "country": "us", + "year_files": [ { + "country": "us", + "level": "national", "year": 2026, + "dataset": "populace", + "region": None, + "subset_code": None, "digest": "d1", - "path": "datasets/us/d1/populace_year_2026.h5", + "path": "year-files/us/d1/populace_year_2026.h5", "filename": "populace_year_2026.h5", + "folder": "prebuilt/us/populace/all", "exists": False, } ], "baselines": [ { + "country": "us", + "level": "state_group", "year": 2026, - "group": ["state/ca"], - "region": "state/ca", + "region": "region_group/state/ca", + "label": "group 16 of 20", + "request": { + "country": "us", + "scope": "macro", + "region_group": ["state/ca"], + "time_period": 2026, + }, + "year_file_path": "year-files/us/d1/populace_year_2026.h5", + "year_file_filename": "populace_year_2026.h5", + "folder": "prebuilt/us/populace/all", "digest": "b1", - "path": "baselines/us/b1/bl1-aaaa.h5", - "simulation_id": "bl1-aaaa", + "path": "baselines/us/b1/bl3-aaaa.h5", + "simulation_id": "bl3-aaaa", + "storage_id": "bl3-aaaa", "exists": False, } ], "receipt": { "policyengine_version": "4.22.0", + "policyengine_core_version": "3.33.3", "model_version": "1.0.0", "data_version": "1.2.3", "data_artifact_revision": "rev-abc", - "default_dataset": "populace_cps", + "default_dataset": "populace", }, } ) @@ -198,35 +215,40 @@ def test_wrappers_validate_dicts_in_and_dump_models_out(precompute_module, monke from policyengine_simulation_executor import precompute as lib from policyengine_simulation_executor.precompute_models import ( BaselineComputeResult, - DatasetBuildResult, DeterminismVerdict, + YearFileBuildResult, ) plan = _sample_plan() seen = {} - monkeypatch.setattr(lib, "plan_artifacts_impl", lambda _bucket: plan) - assert precompute_module.plan_artifacts("bucket-x") == plan.model_dump() + def fake_plan_artifacts(bucket, country): + seen["plan"] = (bucket, country) + return plan + + monkeypatch.setattr(lib, "plan_artifacts_impl", fake_plan_artifacts) + assert precompute_module.plan_artifacts("bucket-x", "us") == plan.model_dump() + assert seen["plan"] == ("bucket-x", "us") - dataset_result = DatasetBuildResult( + dataset_result = YearFileBuildResult( year=2026, path="p", uploaded=True, build_seconds=1.0, size_bytes=3 ) - def fake_build_dataset(bucket, expected): - seen["dataset"] = (bucket, expected) - return dataset_result + def fake_build_year_files(bucket, year, expected): + seen["dataset"] = (bucket, year, expected) + return [dataset_result] - monkeypatch.setattr(lib, "build_dataset_impl", fake_build_dataset) + monkeypatch.setattr(lib, "build_year_files_impl", fake_build_year_files) assert ( - precompute_module.build_dataset("bucket-x", plan.datasets[0].model_dump()) + precompute_module.build_dataset("bucket-x", plan.year_files[0].model_dump()) == dataset_result.model_dump() ) - assert seen["dataset"] == ("bucket-x", plan.datasets[0]) + assert seen["dataset"] == ("bucket-x", 2026, [plan.year_files[0]]) baseline_result = BaselineComputeResult( year=2026, - group=["state/ca"], - simulation_id="bl1-aaaa", + label="group 16 of 20", + simulation_id="bl3-aaaa", outcome="miss", uploaded=True, compute_seconds=2.0, @@ -281,8 +303,9 @@ def test_local_entrypoint_wires_bucket_force_and_handles( captured = {} - def fake_run_precompute(bucket, *, force, functions): + def fake_run_precompute(bucket, *, country, force, functions): captured["bucket"] = bucket + captured["country"] = country captured["force"] = force captured["handles"] = vars(functions) return "digest" @@ -294,7 +317,11 @@ def fake_run_precompute(bucket, *, force, functions): precompute_module.main(force=True) assert captured["bucket"] == "bucket-env" + assert captured["country"] == "us" assert captured["force"] is True + precompute_module.main(country="uk") + assert captured["country"] == "uk" + assert captured["force"] is False assert captured["handles"] == { "plan_artifacts": precompute_module.plan_artifacts, "build_dataset": precompute_module.build_dataset, diff --git a/projects/policyengine-simulation-executor/tests/test_precompute_baselines.py b/projects/policyengine-simulation-executor/tests/test_precompute_baselines.py index 0e6be4ff1..7b8d388c7 100644 --- a/projects/policyengine-simulation-executor/tests/test_precompute_baselines.py +++ b/projects/policyengine-simulation-executor/tests/test_precompute_baselines.py @@ -1,4 +1,4 @@ -"""Tests for computing the precompute's cohort baselines and checking determinism.""" +"""Tests for computing the precompute's baselines and checking their determinism.""" import sys from pathlib import Path @@ -11,25 +11,72 @@ from policyengine_simulation_executor import precompute, precompute_baselines from policyengine_simulation_executor.artifact_keys import canonical_digest from policyengine_simulation_executor.precompute_models import BaselinePlanEntry +from policyengine_simulation_executor.stage12_cache.levels import ( + DatasetLevel, + PrebuiltFolder, +) + + +def _recording_lookup(state): + """Return a prebuilt-folder lookup that records calls and finds ``state.folder``.""" + + def prebuilt_dataset_folder(run, data_folder): + state.lookups.append((run, data_folder)) + if state.prebuilt_folder is None: + return None + return PrebuiltFolder(folder=state.prebuilt_folder, dataset_source=None) + + return prebuilt_dataset_folder + + +def _baseline_entry(simulation_id, storage_id=None): + return BaselinePlanEntry( + country="us", + level=DatasetLevel.STATE_GROUP, + year=2026, + region="region_group/state/ca+state/wv", + label="group 1 of 20", + request={ + "country": "us", + "scope": "macro", + "region_group": ["state/ca", "state/wv"], + "time_period": 2026, + }, + year_file_path="year-files/us/yf-2026/populace_year_2026.h5", + year_file_filename="populace_year_2026.h5", + folder="prebuilt/us/populace_cps/all", + digest="bl-d", + path=f"baselines/us/bl-d/{storage_id or simulation_id}.h5", + simulation_id=simulation_id, + storage_id=storage_id or simulation_id, + exists=False, + ) class TestComputeBaselineImpl: @pytest.fixture def cohort_stubs(self, monkeypatch, tmp_path): - from policyengine_simulation_executor import artifact_keys, artifact_store + from policyengine_simulation_executor import artifact_store from policyengine_simulation_executor import simulation_runtime as sr from policyengine_simulation_executor.baseline_artifacts import ( ArtifactBaselineSimulation, ) + folder = tmp_path / "prebuilt" / "us" / "populace_cps" / "all" state = SimpleNamespace( - folder=tmp_path, downloads=[], uploads=[], configured=[] + folder=folder, + data_folder=tmp_path, + downloads=[], + uploads=[], + configured=[], + lookups=[], + prebuilt_folder=str(folder), ) class StubBaseline(ArtifactBaselineSimulation): def ensure(self): self._artifact_outcome = "miss" - (tmp_path / f"{self.id}.h5").write_bytes(b"artifact-bytes") + (folder / f"{self.id}.h5").write_bytes(b"artifact-bytes") class SilentBaseline(ArtifactBaselineSimulation): def ensure(self): @@ -55,12 +102,12 @@ def storage_id(self): def ensure(self): self._artifact_outcome = "miss" - (tmp_path / f"{self.storage_id}.h5").write_bytes(b"artifact-bytes") + (folder / f"{self.storage_id}.h5").write_bytes(b"artifact-bytes") state.spm = None - state.baseline = StubBaseline.model_construct(id="bl1-cohort") - state.make_silent = lambda: SilentBaseline.model_construct(id="bl1-cohort") - state.make_spm = lambda sim_id="bl1-cohort": SPMStubBaseline.model_construct( + state.baseline = StubBaseline.model_construct(id="bl3-cohort") + state.make_silent = lambda: SilentBaseline.model_construct(id="bl3-cohort") + state.make_spm = lambda sim_id="bl3-cohort": SPMStubBaseline.model_construct( id=sim_id ) @@ -86,12 +133,7 @@ def upload_file(self, path, local_path): ) monkeypatch.setattr( - artifact_keys, - "collect_dataset_identity", - lambda _country, year: SimpleNamespace( - store_path=f"datasets/us/ds-{year}/populace_year_{year}.h5", - filename=f"populace_year_{year}.h5", - ), + precompute_baselines, "prebuilt_dataset_folder", _recording_lookup(state) ) monkeypatch.setattr(artifact_store, "ArtifactStore", FakeStore) monkeypatch.setattr(sr, "resolve_data_folder", lambda: str(tmp_path)) @@ -105,35 +147,33 @@ def upload_file(self, path, local_path): dataset_reference=None, ), ) - monkeypatch.setattr( - sr, - "_load_dataset", - lambda _params, country_module, selection: "dataset", - ) + + def load_dataset(_params, *, country_module, selection, data_folder): + state.load_folder = data_folder + return "dataset" + + monkeypatch.setattr(sr, "_load_dataset", load_dataset) monkeypatch.setattr( sr, "_build_simulation", lambda _params, **_kwargs: state.baseline ) return state - def _entry(self, sim_id="bl1-cohort"): - return BaselinePlanEntry( - year=2026, - group=["state/ca", "state/wv"], - region="state/ca+state/wv", - digest="bl-d", - path=f"baselines/us/bl-d/{sim_id}.h5", - simulation_id=sim_id, - exists=False, - ) + def _entry(self, sim_id="bl3-cohort", storage_id=None): + return _baseline_entry(sim_id, storage_id) def test_downloads_dataset_configures_extras_and_uploads(self, cohort_stubs): result = precompute.compute_baseline_impl("bucket-x", self._entry()) assert cohort_stubs.downloads == [ ( - "datasets/us/ds-2026/populace_year_2026.h5", + "year-files/us/yf-2026/populace_year_2026.h5", str(cohort_stubs.folder / "populace_year_2026.h5"), ) ] + # The year file is read from the prebuilt folder its run reads. + assert cohort_stubs.load_folder == str(cohort_stubs.folder) + assert [data_folder for _run, data_folder in cohort_stubs.lookups] == [ + str(cohort_stubs.data_folder) + ] # The extras configuration is load-bearing: without it every # production request fails the column guard and recomputes. assert cohort_stubs.configured == [ @@ -141,37 +181,43 @@ def test_downloads_dataset_configures_extras_and_uploads(self, cohort_stubs): ] assert cohort_stubs.uploads == [ ( - "baselines/us/bl-d/bl1-cohort.h5", - str(cohort_stubs.folder / "bl1-cohort.h5"), + "baselines/us/bl-d/bl3-cohort.h5", + str(cohort_stubs.folder / "bl3-cohort.h5"), ) ] - assert result.simulation_id == "bl1-cohort" + assert result.simulation_id == "bl3-cohort" assert result.outcome == "miss" assert result.uploaded is True assert result.size_bytes == len(b"artifact-bytes") def test_present_local_dataset_skips_download(self, cohort_stubs): + cohort_stubs.folder.mkdir(parents=True) (cohort_stubs.folder / "populace_year_2026.h5").write_bytes(b"already-here") precompute.compute_baseline_impl("bucket-x", self._entry()) assert cohort_stubs.downloads == [] def test_refuses_to_act_under_a_mismatched_id(self, cohort_stubs): with pytest.raises(RuntimeError, match="refusing to act"): - precompute.compute_baseline_impl("bucket-x", self._entry("bl1-other")) + precompute.compute_baseline_impl("bucket-x", self._entry("bl3-other")) + assert cohort_stubs.uploads == [] + + def test_refuses_a_year_file_its_run_would_not_read(self, cohort_stubs): + cohort_stubs.prebuilt_folder = None + with pytest.raises(RuntimeError, match="not one its run would read"): + precompute.compute_baseline_impl("bucket-x", self._entry()) assert cohort_stubs.uploads == [] def test_refuses_a_mismatched_planned_storage_id(self, cohort_stubs): - entry = self._entry() - entry.path = "baselines/us/bl-d/bl1-cohort-spm-planned.h5" + entry = self._entry(storage_id="bl3-cohort-spm-planned") with pytest.raises(RuntimeError, match="storage ids disagree"): precompute.compute_baseline_impl("bucket-x", entry) assert cohort_stubs.configured == [] assert cohort_stubs.uploads == [] - assert not (cohort_stubs.folder / "bl1-cohort.h5").exists() + assert not (cohort_stubs.folder / "bl3-cohort.h5").exists() @staticmethod def _planned_identity(selection): - """Return a real ``BaselineArtifactIdentity``, not a restated expression. + """Return a real ``BaselineIdentity``, not a restated expression. The plan the deploy publishes comes from this object's properties, so keying the test off them is what makes the write path a @@ -180,27 +226,27 @@ def _planned_identity(selection): longer names the planned file. """ from policyengine_simulation_executor.artifact_keys import ( - BaselineArtifactIdentity, - DatasetArtifactIdentity, + BaselineIdentity, + YearFileIdentity, ) - return BaselineArtifactIdentity( + return BaselineIdentity( spm=selection, - country="us", - region="state/ca+state/wv", + region="region_group/state/ca+state/wv", scope_key="scoping", - dataset=DatasetArtifactIdentity( - spm=selection, + year_file=YearFileIdentity( country="us", dataset="populace_cps", - stem="populace", - year=2026, + dataset_sha256=None, data_version="1.2.3", data_artifact_revision="rev-abc", - source_sha256=None, - data_build_fingerprint=None, - model_version="9.9.9", - policyengine_version="4.22.0", + certification_fingerprint=None, + year=2026, + subset=None, + packages={"policyengine": "4.22.0"}, + spm=selection, + stem="populace", + folder="prebuilt/us/populace_cps/all", ), ) @@ -212,7 +258,7 @@ def test_publishes_a_selection_scoped_artifact_under_the_planned_path( Nothing else in hermetic CI runs ``compute_baseline_impl`` with a selection: the identity's storage id was only ever compared to itself, and the one case that reached the guard covered the abort. - Here the plan is the planner's own ``BaselineArtifactIdentity`` and + Here the plan is the planner's own ``BaselineIdentity`` and the container names its artifact the wrapper's way, so the guard passing at all is the claim -- if the two derivations differed, no canonical artifact could be published and the deploy would be @@ -230,7 +276,7 @@ def test_publishes_a_selection_scoped_artifact_under_the_planned_path( cohort_stubs.spm = selection cohort_stubs.baseline = cohort_stubs.make_spm(planned.simulation_id) - entry = self._entry(planned.simulation_id) + entry = self._entry(planned.simulation_id, planned.storage_id) entry.digest = planned.digest entry.path = planned.store_path @@ -263,10 +309,8 @@ def test_refuses_a_selection_scoped_plan_the_container_does_not_share( """ cohort_stubs.spm = {"scenario": "zero_real"} cohort_stubs.baseline = cohort_stubs.make_spm() - entry = self._entry() - entry.path = ( - f"baselines/us/bl-d/bl1-cohort-spm-" - f"{canonical_digest({'scenario': 'ce_trend'})}.h5" + entry = self._entry( + storage_id=f"bl3-cohort-spm-{canonical_digest({'scenario': 'ce_trend'})}" ) with pytest.raises(RuntimeError, match="storage ids disagree"): precompute.compute_baseline_impl("bucket-x", entry) @@ -274,7 +318,7 @@ def test_refuses_a_selection_scoped_plan_the_container_does_not_share( assert cohort_stubs.uploads == [] def test_refuses_a_plain_simulation(self, cohort_stubs): - cohort_stubs.baseline = SimpleNamespace(id="bl1-cohort") + cohort_stubs.baseline = SimpleNamespace(id="bl3-cohort") with pytest.raises(RuntimeError, match="plain Simulation"): precompute.compute_baseline_impl("bucket-x", self._entry()) assert cohort_stubs.uploads == [] @@ -306,7 +350,7 @@ def download_file(self, path, local_path): Path(local_path).write_bytes(b"artifact") class FakeBaseline: - id = "bl1-verify" + id = "bl3-verify" dataset = "dataset" tax_benefit_model_version = "model-version" scoping_strategy = "scoping" @@ -330,20 +374,14 @@ def run(self): monkeypatch.setattr( precompute_baselines, - "_prepare_cohort_baseline", + "_prepare_baseline", lambda _bucket, _expected: (FakeStore(), tmp_path, FakeBaseline()), ) monkeypatch.setattr("policyengine.core.Simulation", FakeFresh) if on_disk: - (tmp_path / "bl1-verify.h5").write_bytes(b"artifact") - entry = BaselinePlanEntry( - year=2026, - group=["state/ca"], - region="state/ca", - digest="d", - path="baselines/us/d/bl1-verify.h5", - simulation_id="bl1-verify", - exists=True, + (tmp_path / "bl3-verify.h5").write_bytes(b"artifact") + entry = _baseline_entry("bl3-verify").model_copy( + update={"digest": "d", "path": "baselines/us/d/bl3-verify.h5"} ) verdict = precompute.verify_determinism_impl("bucket-x", entry) return verdict, downloads, captured @@ -401,7 +439,7 @@ def test_absent_artifact_is_downloaded_first(self, run_verification): verdict, downloads, _ = run_verification( self._frames(), self._frames(), on_disk=False ) - assert downloads == ["baselines/us/d/bl1-verify.h5"] + assert downloads == ["baselines/us/d/bl3-verify.h5"] assert verdict.equal is True def test_fresh_run_reuses_the_baseline_inputs(self, run_verification): diff --git a/projects/policyengine-simulation-executor/tests/test_precompute_datasets.py b/projects/policyengine-simulation-executor/tests/test_precompute_datasets.py index baad2b383..8fbba78dd 100644 --- a/projects/policyengine-simulation-executor/tests/test_precompute_datasets.py +++ b/projects/policyengine-simulation-executor/tests/test_precompute_datasets.py @@ -1,110 +1,96 @@ -"""Tests for building the precompute's national and per-state datasets.""" +"""Tests for building the precompute's year files through the level handlers.""" from pathlib import Path from types import SimpleNamespace import pytest -from policyengine_simulation_executor import precompute, precompute_datasets -from policyengine_simulation_executor.precompute_models import ( - DatasetPlanEntry, - StateDatasetPlanEntry, +from fixtures.us_prebuilt_inputs import install_us_prebuilt_inputs +from policyengine_simulation_executor import artifact_keys, precompute +from policyengine_simulation_executor.precompute_models import YearFilePlanEntry +from policyengine_simulation_executor.stage12_cache import levels_us +from policyengine_simulation_executor.stage12_cache.levels import ( + DatasetLevel, + SubsetFilter, + YearFileTarget, + prebuilt_folder, ) -class TestBuildDatasetImpl: - @pytest.fixture - def dataset_stubs(self, monkeypatch, tmp_path): - from policyengine_simulation_executor import ( - artifact_keys, - artifact_store, - release_bundle, - ) - from policyengine_simulation_executor import simulation_runtime as sr +def _entry_for(identity, target): + return YearFilePlanEntry( + country="us", + level=target.level, + year=target.year, + dataset=target.dataset, + region=None if target.subset is None else target.subset.region, + subset_code=None if target.subset is None else target.subset.code, + digest=identity.digest, + path=identity.store_path, + filename=identity.filename, + folder=identity.folder, + exists=False, + ) - state = SimpleNamespace( - folder=tmp_path, - uploads=[], - ensure_calls=[], - write_file=True, - identity=SimpleNamespace( - digest="ds-2026", - store_path="datasets/us/ds-2026/populace_year_2026.h5", - filename="populace_year_2026.h5", - ), - ) - - class FakeStore: - def __init__(self, bucket): - self.bucket = bucket - def upload_file(self, path, local_path): - state.uploads.append((path, str(local_path))) - return True +class TestBuildingAWholeDatasetYearFile: + @pytest.fixture + def national_build(self, monkeypatch, tmp_path): + inputs = install_us_prebuilt_inputs(monkeypatch) + monkeypatch.setenv("POLICYENGINE_DATA_FOLDER", str(tmp_path)) + state = SimpleNamespace(ensure_calls=[], write_file=True, inputs=inputs) - def fake_ensure_datasets(*, datasets, years, data_folder): + def ensure_datasets(*, datasets, years, data_folder): state.ensure_calls.append((datasets, years, data_folder)) if state.write_file: - (tmp_path / state.identity.filename).write_bytes(b"h5-bytes") + (tmp_path / "populace_cps_year_2026.h5").write_bytes(b"h5-bytes") - monkeypatch.setattr( - artifact_keys, - "collect_dataset_identity", - lambda _country, _year: state.identity, - ) - monkeypatch.setattr(artifact_store, "ArtifactStore", FakeStore) - monkeypatch.setattr(sr, "resolve_data_folder", lambda: str(tmp_path)) - monkeypatch.setattr( - sr, - "_country_module", - lambda _country: SimpleNamespace(ensure_datasets=fake_ensure_datasets), - ) - monkeypatch.setattr( - release_bundle, - "get_country_release_bundle", - lambda _country: SimpleNamespace(default_dataset="populace_cps"), - ) + inputs.us_module.ensure_datasets = ensure_datasets + target = levels_us.national_year_file(2026) + state.entry = _entry_for(artifact_keys.year_file_identity(target), target) + state.folder = tmp_path return state - def _entry(self, path="datasets/us/ds-2026/populace_year_2026.h5"): - return DatasetPlanEntry( - year=2026, - digest="ds-2026", - path=path, - filename="populace_year_2026.h5", - exists=False, + def test_builds_and_uploads_under_the_planned_key(self, national_build): + (result,) = precompute.build_year_files_impl( + "bucket-x", 2026, [national_build.entry] ) - def test_builds_and_uploads_under_the_planned_key(self, dataset_stubs): - result = precompute.build_dataset_impl("bucket-x", self._entry()) - assert dataset_stubs.ensure_calls == [ - (["populace_cps"], [2026], str(dataset_stubs.folder)) + assert national_build.ensure_calls == [ + (["populace_cps"], [2026], str(national_build.folder)) ] - assert dataset_stubs.uploads == [ - ( - "datasets/us/ds-2026/populace_year_2026.h5", - str(dataset_stubs.folder / "populace_year_2026.h5"), - ) + uploads = national_build.inputs.gcs_client.uploads + assert [(path, data) for _bucket, path, data, _kwargs in uploads] == [ + (national_build.entry.path, b"h5-bytes") ] assert result.year == 2026 + assert result.path == national_build.entry.path assert result.uploaded is True assert result.size_bytes == len(b"h5-bytes") - def test_refuses_to_upload_under_a_mismatched_key(self, dataset_stubs): - with pytest.raises(RuntimeError, match="refusing to upload"): - precompute.build_dataset_impl( - "bucket-x", self._entry(path="datasets/us/OTHER/file.h5") - ) - assert dataset_stubs.uploads == [] + def test_refuses_to_build_under_a_mismatched_key(self, national_build): + mismatched = national_build.entry.model_copy( + update={"path": "year-files/us/OTHER/file.h5"} + ) + + with pytest.raises(RuntimeError, match="refusing to build"): + precompute.build_year_files_impl("bucket-x", 2026, [mismatched]) + assert national_build.ensure_calls == [] + assert national_build.inputs.gcs_client.uploads == [] + + def test_fails_loudly_when_no_file_is_produced(self, national_build): + national_build.write_file = False - def test_fails_loudly_when_no_file_is_produced(self, dataset_stubs): - dataset_stubs.write_file = False with pytest.raises(RuntimeError, match="produced no file"): - precompute.build_dataset_impl("bucket-x", self._entry()) - assert dataset_stubs.uploads == [] + precompute.build_year_files_impl("bucket-x", 2026, [national_build.entry]) + assert national_build.inputs.gcs_client.uploads == [] + def test_an_empty_build_does_nothing(self, national_build): + assert precompute.build_year_files_impl("bucket-x", 2026, []) == [] + assert national_build.ensure_calls == [] -class TestBuildStateDatasetsImpl: - """Building, checking and uploading one year's per-state datasets.""" + +class TestBuildingStateYearFiles: + """Building, checking and uploading one year's state year files.""" YEAR = 2026 @@ -113,10 +99,7 @@ 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 import ( - artifact_keys, - artifact_store, - ) + from policyengine_simulation_executor import artifact_store from policyengine_simulation_executor import simulation_runtime as sr state = SimpleNamespace( @@ -128,37 +111,47 @@ def state_build(self, monkeypatch, tmp_path): ) 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", + return YearFileTarget( + country="us", + level=DatasetLevel.STATE, dataset=sources.REGIONAL_DATASET, - scoping_strategy=RowFilterStrategy( - variable_name="state_fips", variable_value=fips + year=self.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.target = target state.targets = [ target("UT", sources.UTAH_FIPS), target("WY", sources.WYOMING_FIPS), ] monkeypatch.setattr( - precompute_datasets, "state_dataset_targets", lambda: list(state.targets) + levels_us.UsStateHandler, + "year_file_targets", + lambda _handler, _year: list(state.targets), ) - def fake_state_identity( - _country, year, *, dataset, state_code, state_fips, filter_variable - ): - digest = f"sd-{year}-{state_code}-{state_fips}-{filter_variable}" + def fake_year_file_identity(target): + digest = f"yf-{target.year}-{target.subset.code}-{target.subset.value}" return SimpleNamespace( digest=digest, - store_path=f"state-datasets/us/{digest}/{dataset}_year_{year}.h5", - filename=f"{dataset}_year_{year}.h5", + store_path=( + f"year-files/us/{digest}/{target.dataset}_year_{target.year}.h5" + ), + filename=f"{target.dataset}_year_{target.year}.h5", + folder=target.folder, ) monkeypatch.setattr( - artifact_keys, "collect_state_dataset_identity", fake_state_identity + artifact_keys, "year_file_identity", fake_year_file_identity ) class FakeStore: @@ -208,36 +201,13 @@ def fake_ensure_datasets(*, datasets, years, data_folder): ), ) state.sources = sources - state.entry = lambda state_code, fips: self._entry( - fake_state_identity, state_code, fips + state.entry = lambda state_code, fips: _entry_for( + fake_year_file_identity(target(state_code, fips)), target(state_code, fips) ) return state - def _entry(self, identity_for, state_code, fips): - from fixtures.state_dataset_sources import REGIONAL_DATASET - - identity = identity_for( - "us", - self.YEAR, - dataset=REGIONAL_DATASET, - state_code=state_code, - state_fips=fips, - filter_variable="state_fips", - ) - return StateDatasetPlanEntry( - year=self.YEAR, - state_code=state_code, - region=f"state/{state_code.lower()}", - dataset=REGIONAL_DATASET, - digest=identity.digest, - path=identity.store_path, - filename=identity.filename, - folder=f"state-datasets/{REGIONAL_DATASET}/{state_code}", - exists=False, - ) - def _build(self, state_build, entries): - return precompute.build_state_datasets_impl( + return precompute.build_year_files_impl( "bucket-x", self.YEAR, entries, work_folder=state_build.work_folder ) @@ -260,9 +230,8 @@ def test_writes_each_state_file_with_only_its_households(self, state_build): assert sources.stored_ids(wyoming, "household") == [3] assert sources.stored_ids(wyoming, "person") == [4] assert sources.stored_ids(wyoming, "spm_unit") == [3] - assert [(result.state_code, result.year) for result in results] == [ - ("UT", 2026), - ("WY", 2026), + assert [(result.path, result.year) for result in results] == [ + (entry.path, 2026) for entry in self._both_states(state_build) ] def test_keeps_every_weight_unchanged(self, state_build): @@ -330,7 +299,7 @@ def test_each_state_file_holds_exactly_the_rows_its_filter_keeps(self, state_bui stored = dict(state_build.uploads) for target, entry in zip(state_build.targets, entries, strict=True): - expected = target.scoping_strategy.apply( + expected = target.subset.scoping_strategy.apply( entity_data=state_build.sources.source_entity_frames(), group_entities=US_GROUP_ENTITIES, year=self.YEAR, @@ -338,7 +307,7 @@ def test_each_state_file_holds_exactly_the_rows_its_filter_keeps(self, state_bui for entity, frame in expected.items(): assert state_build.sources.stored_ids(stored[entry.path], entity) == [ int(value) for value in frame[f"{entity}_id"] - ], (target.state_code, entity) + ], (target.subset.code, entity) def test_prepares_the_full_country_year_file_once(self, state_build): self._build(state_build, self._both_states(state_build)) @@ -384,33 +353,10 @@ def test_a_household_without_a_district_code_does_not_stop_the_build( results = self._build(state_build, self._both_states(state_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._both_states(state_build)) - assert state_build.uploads == [] - assert state_build.ensure_calls == [] + assert len(results) == 2 def test_refuses_a_state_with_no_households(self, state_build): - from policyengine.core.scoping_strategy import RowFilterStrategy - - state_build.targets.append( - precompute.StateDatasetTarget( - region="state/id", - state_code="ID", - state_fips=16, - filter_variable="state_fips", - dataset=state_build.sources.REGIONAL_DATASET, - scoping_strategy=RowFilterStrategy( - variable_name="state_fips", variable_value=16 - ), - ) - ) + state_build.targets.append(state_build.target("ID", 16)) with pytest.raises(ValueError, match="No households"): self._build(state_build, [state_build.entry("ID", 16)]) @@ -418,7 +364,7 @@ def test_refuses_a_state_with_no_households(self, state_build): def test_refuses_a_plan_entry_whose_key_differs_in_the_container(self, state_build): entry = state_build.entry("UT", state_build.sources.UTAH_FIPS) - mismatched = entry.model_copy(update={"path": "state-datasets/us/OTHER/x.h5"}) + mismatched = entry.model_copy(update={"path": "year-files/us/OTHER/x.h5"}) with pytest.raises(RuntimeError, match="refusing to build"): self._build(state_build, [mismatched]) @@ -427,7 +373,7 @@ def test_refuses_a_plan_entry_whose_key_differs_in_the_container(self, state_bui def test_refuses_a_state_the_container_does_not_target(self, state_build): state_build.targets = state_build.targets[:1] - with pytest.raises(RuntimeError, match="state/wy"): + with pytest.raises(RuntimeError, match="WY"): self._build(state_build, self._both_states(state_build)) assert state_build.ensure_calls == [] @@ -435,7 +381,7 @@ def test_refuses_entries_for_another_year(self, state_build): entry = state_build.entry("UT", state_build.sources.UTAH_FIPS) with pytest.raises(ValueError, match="2027"): - precompute.build_state_datasets_impl( + precompute.build_year_files_impl( "bucket-x", 2027, [entry], diff --git a/projects/policyengine-simulation-executor/tests/test_precompute_planning.py b/projects/policyengine-simulation-executor/tests/test_precompute_planning.py index f4c6c3b5a..b8284bd9f 100644 --- a/projects/policyengine-simulation-executor/tests/test_precompute_planning.py +++ b/projects/policyengine-simulation-executor/tests/test_precompute_planning.py @@ -1,435 +1,38 @@ -"""Tests for planning the artifact precompute, and its writer and reader identities.""" +"""The planned year file's name against the installed release. -from types import SimpleNamespace +The plan through the level handlers is tested in ``test_prebuilt_plan`` and +the handlers' targets in ``test_prebuilt_levels``; this one check needs the +real release manifest. +""" -import pytest -from fixtures.identity_stubs import install_identity_stubs -from policyengine_simulation_executor import precompute, precompute_planning -from policyengine_simulation_executor.precompute_models import BundleVersionIdentity +def test_year_file_name_matches_runtime_stem_lookup(monkeypatch): + """The national year file's name is the name the runtime looks for. -class TestWriterReaderContract: - """The writer and the runtime reader must derive identical identities.""" - - @pytest.fixture - def identity_stubs(self, monkeypatch): - from policyengine_simulation_executor import region_resolution - from policyengine_simulation_executor import simulation_runtime as sr - - state = install_identity_stubs(monkeypatch) - # Both modules read the release bundle: dataset selection and regions. - monkeypatch.setattr( - sr, "get_country_release_bundle", lambda _country: state.bundle - ) - monkeypatch.setattr( - region_resolution, - "get_country_release_bundle", - lambda _country: state.bundle, - ) - - @pytest.fixture - def fake_regions(self, monkeypatch): - from policyengine.core.scoping_strategy import RowFilterStrategy - from policyengine_simulation_executor import simulation_runtime as sr - - def get_region(code): - state = code.split("/")[-1].upper() - return SimpleNamespace( - code=code, - scoping_strategy=RowFilterStrategy( - variable_name="state_code", variable_value=state - ), - ) - - monkeypatch.setattr( - sr, - "_country_module", - lambda _country: SimpleNamespace( - model=SimpleNamespace(get_region=get_region) - ), - ) - - @pytest.mark.usefixtures("identity_stubs", "fake_regions") - def test_precompute_identity_equals_runtime_id(self): - from policyengine_simulation_executor import simulation_runtime as sr - from policyengine_simulation_executor.baseline_artifacts import ( - BaselineIdentityRequest, - deterministic_baseline_id, - ) - - group = ["state/ca", "state/wv"] - writer_identity = precompute.cohort_identity(2026, group) - - params = precompute.cohort_params(2026, group) - resolution = sr.resolve_region( - country_module=sr._country_module("us"), country="us", params=params - ) - dataset_selection = sr._resolve_dataset_selection( - params, region_resolution=resolution - ) - reader_id = deterministic_baseline_id( - BaselineIdentityRequest( - params, - country="us", - dataset_is_default=dataset_selection.is_default, - policy=None, - region_code=resolution.code, - scoping_strategy=resolution.scoping_strategy, - year=2026, - ) - ) - assert writer_identity.simulation_id == reader_id - assert writer_identity.store_path.endswith(f"/{writer_identity.storage_id}.h5") - - def test_dataset_filename_matches_runtime_stem_lookup(self, monkeypatch): - """The dataset artifact filename is the name the runtime looks for. - - Real-manifest coverage: it equals the exact name the runtime's - ensure_datasets existence check resolves. - """ - from policyengine.provenance.manifest import ( - dataset_logical_name, - resolve_dataset_reference, - ) - from policyengine_simulation_executor.artifact_keys import ( - collect_dataset_identity, - ) - from policyengine_simulation_executor.release_bundle import ( - get_country_release_bundle, - resolve_bundle_dataset_name, - ) - from policyengine_simulation_executor.simulation_runtime import DEFAULT_YEAR - - monkeypatch.delenv("POLICYENGINE_BUNDLE_RECEIPT", raising=False) - get_country_release_bundle.cache_clear() - try: - expected_stem = dataset_logical_name( - resolve_dataset_reference("us", resolve_bundle_dataset_name("us", None)) - ) - identity = collect_dataset_identity("us", DEFAULT_YEAR) - finally: - get_country_release_bundle.cache_clear() - assert identity.filename == f"{expected_stem}_year_{DEFAULT_YEAR}.h5" - - -class TestPlanArtifactsImpl: - """The 63-identity planner: enumeration, presence flags, receipt.""" - - @pytest.fixture - def planning_stubs(self, monkeypatch): - from policyengine_simulation_executor import ( - artifact_keys, - artifact_store, - national_partition, - release_bundle, - ) - - existing = { - "datasets/us/ds-2026/populace_year_2026.h5", - "baselines/us/bl-2026-1/bl1-2026-1.h5", - } - - class FakeStore: - def __init__(self, bucket): - self.bucket = bucket - - def exists(self, path): - return path in existing - - monkeypatch.setattr(artifact_store, "ArtifactStore", FakeStore) - monkeypatch.setattr( - national_partition, - "national_region_groups", - lambda _country: [["state/ca"], ["state/ny", "state/wv"]], - ) - monkeypatch.setattr( - artifact_keys, - "collect_dataset_identity", - lambda _country, year: SimpleNamespace( - digest=f"ds-{year}", - store_path=f"datasets/us/ds-{year}/populace_year_{year}.h5", - filename=f"populace_year_{year}.h5", - ), - ) - - def fake_cohort_identity(year, group): - tag = f"{year}-{len(group)}" - return SimpleNamespace( - region="+".join(group), - digest=f"bl-{tag}", - store_path=f"baselines/us/bl-{tag}/bl1-{tag}.h5", - simulation_id=f"bl1-{tag}", - ) - - monkeypatch.setattr( - precompute_planning, "cohort_identity", fake_cohort_identity - ) - targets = [ - precompute.StateDatasetTarget( - region="state/ut", - state_code="UT", - state_fips=49, - filter_variable="state_fips", - dataset="populace_local", - ), - precompute.StateDatasetTarget( - region="state/wy", - state_code="WY", - state_fips=56, - filter_variable="state_fips", - dataset="populace_local", - ), - ] - monkeypatch.setattr( - precompute_planning, "state_dataset_targets", lambda: list(targets) - ) - existing.add("state-datasets/us/sd-2026-UT/populace_local_year_2026.h5") - - def fake_state_identity( - _country, year, *, dataset, state_code, state_fips, filter_variable - ): - assert (state_fips, filter_variable) in { - (49, "state_fips"), - (56, "state_fips"), - } - digest = f"sd-{year}-{state_code}" - return SimpleNamespace( - digest=digest, - store_path=f"state-datasets/us/{digest}/{dataset}_year_{year}.h5", - filename=f"{dataset}_year_{year}.h5", - ) - - monkeypatch.setattr( - artifact_keys, "collect_state_dataset_identity", fake_state_identity - ) - monkeypatch.setattr( - release_bundle, - "get_country_release_bundle", - lambda _country: SimpleNamespace( - policyengine_version="4.22.0", - model_version="1.0.0", - data_version="1.2.3", - data_artifact_revision="rev-abc", - default_dataset="populace_cps", - ), - ) - return SimpleNamespace(existing=existing, targets=targets) - - @pytest.mark.usefixtures("planning_stubs") - def test_plan_lists_every_state_dataset_year_major_with_presence(self): - plan = precompute.plan_artifacts_impl("bucket-x") - - 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 == "populace_local" - assert first.digest == "sd-2026-UT" - assert first.path == "state-datasets/us/sd-2026-UT/populace_local_year_2026.h5" - assert first.filename == "populace_local_year_2026.h5" - assert first.folder == "state-datasets/populace_local/UT" - work = precompute.select_work(plan, force=False) - assert len(work.state_datasets) == 5 - - def test_states_on_the_default_dataset_add_no_state_datasets( - self, planning_stubs, monkeypatch - ): - monkeypatch.setattr(precompute_planning, "state_dataset_targets", list) - - plan = precompute.plan_artifacts_impl("bucket-x") - - assert plan.state_datasets == [] - assert len(plan.datasets) == 3 - - @pytest.mark.usefixtures("planning_stubs") - def test_plan_enumerates_years_and_cohorts_with_presence(self): - plan = precompute.plan_artifacts_impl("bucket-x") - - assert [entry.year for entry in plan.datasets] == [2026, 2027, 2025] - assert [entry.exists for entry in plan.datasets] == [True, False, False] - assert plan.datasets[0].digest == "ds-2026" - assert plan.datasets[0].path == "datasets/us/ds-2026/populace_year_2026.h5" - assert plan.datasets[0].filename == "populace_year_2026.h5" - - # Year-major, partition order inside each year. - assert [entry.simulation_id for entry in plan.baselines] == [ - "bl1-2026-1", - "bl1-2026-2", - "bl1-2027-1", - "bl1-2027-2", - "bl1-2025-1", - "bl1-2025-2", - ] - assert [entry.exists for entry in plan.baselines] == [ - True, - False, - False, - False, - False, - False, - ] - assert plan.baselines[0].group == ["state/ca"] - assert plan.baselines[1].group == ["state/ny", "state/wv"] - assert plan.baselines[1].path == "baselines/us/bl-2026-2/bl1-2026-2.h5" - - assert plan.receipt == BundleVersionIdentity( - policyengine_version="4.22.0", - model_version="1.0.0", - data_version="1.2.3", - data_artifact_revision="rev-abc", - default_dataset="populace_cps", - ) - # An exists-flag inversion would make select_work recompute (or, - # worse, skip) the wrong entries — lock the wiring end to end. - work = precompute.select_work(plan, force=False) - assert [entry.year for entry in work.datasets] == [2027, 2025] - assert len(work.baselines) == 5 - - @pytest.mark.usefixtures("planning_stubs") - def test_empty_partition_fails_loudly(self, monkeypatch): - from policyengine_simulation_executor import national_partition - - monkeypatch.setattr( - national_partition, "national_region_groups", lambda _country: [] - ) - with pytest.raises(RuntimeError, match="No national partition"): - precompute.plan_artifacts_impl("bucket-x") - - -def _us_state_region(state_code: str, state_fips: int, dataset_path: str): - from policyengine.core.scoping_strategy import RowFilterStrategy - - return SimpleNamespace( - code=f"state/{state_code.lower()}", - dataset_path=dataset_path, - scoping_strategy=RowFilterStrategy( - variable_name="state_fips", variable_value=state_fips - ), - parent_code="us", - state_code=state_code, + Real-manifest coverage: it equals the exact name the runtime's + ensure_datasets existence check resolves. + """ + from policyengine.provenance.manifest import ( + dataset_logical_name, + resolve_dataset_reference, + ) + from policyengine_simulation_executor.artifact_keys import year_file_identity + from policyengine_simulation_executor.release_bundle import ( + get_country_release_bundle, + resolve_bundle_dataset_name, + ) + from policyengine_simulation_executor.simulation_runtime import DEFAULT_YEAR + from policyengine_simulation_executor.stage12_cache.levels_us import ( + national_year_file, ) - -class TestStateDatasetTargets: - """Which states get baked files, resolved the way a request resolves them.""" - - @pytest.fixture - def regional_bundle(self): - from policyengine_simulation_executor.release_bundle import ( - get_country_release_bundle, - ) - - bundle = get_country_release_bundle("us") - regional = next( - name for name in bundle.dataset_uris if name.endswith("_acs_local") - ) - return SimpleNamespace( - default_uri=bundle.default_dataset_uri, - regional=regional, - regional_uri=bundle.dataset_uris[regional], - ) - - def _install_regions(self, monkeypatch, regions): - from policyengine_simulation_executor import simulation_runtime - - by_code = {region.code: region for region in regions} - country_module = SimpleNamespace( - model=SimpleNamespace( - get_region=by_code.get, - region_registry=SimpleNamespace( - get_by_type=lambda region_type: ( - list(regions) if region_type == "state" else [] - ) - ), - ) - ) - monkeypatch.setattr( - simulation_runtime, "_country_module", lambda _country: country_module - ) - - def test_targets_states_whose_requests_load_a_regional_dataset( - self, monkeypatch, regional_bundle - ): - self._install_regions( - monkeypatch, - [ - _us_state_region("WY", 56, regional_bundle.regional_uri), - _us_state_region("UT", 49, regional_bundle.regional_uri), - ], - ) - - targets = precompute.state_dataset_targets() - - assert targets == [ - precompute.StateDatasetTarget( - region="state/ut", - state_code="UT", - state_fips=49, - filter_variable="state_fips", - dataset=regional_bundle.regional, - ), - precompute.StateDatasetTarget( - region="state/wy", - state_code="WY", - state_fips=56, - filter_variable="state_fips", - dataset=regional_bundle.regional, - ), - ] - - def test_skips_states_whose_requests_load_the_default_dataset( - self, monkeypatch, regional_bundle - ): - self._install_regions( - monkeypatch, - [ - _us_state_region("UT", 49, regional_bundle.default_uri), - _us_state_region("WY", 56, regional_bundle.regional_uri), - ], - ) - - assert [target.state_code for target in precompute.state_dataset_targets()] == [ - "WY" - ] - - def test_refuses_a_state_without_a_row_filter(self, monkeypatch, regional_bundle): - unfiltered = _us_state_region("UT", 49, regional_bundle.regional_uri) - unfiltered.scoping_strategy = None - self._install_regions(monkeypatch, [unfiltered]) - - with pytest.raises(RuntimeError, match="state/ut"): - precompute.state_dataset_targets() - - -class TestCohortIdentityGuard: - def test_diverged_predicates_fail_loudly(self, monkeypatch): - from policyengine_simulation_executor import baseline_artifacts as ba - from policyengine_simulation_executor import simulation_runtime as sr - - monkeypatch.setattr(sr, "_country_module", lambda _country: SimpleNamespace()) - monkeypatch.setattr( - sr, - "resolve_region", - lambda **_kwargs: SimpleNamespace( - code="x", dataset_reference=None, scoping_strategy=None - ), + monkeypatch.delenv("POLICYENGINE_BUNDLE_RECEIPT", raising=False) + get_country_release_bundle.cache_clear() + try: + expected_stem = dataset_logical_name( + resolve_dataset_reference("us", resolve_bundle_dataset_name("us", None)) ) - monkeypatch.setattr( - ba, "qualifying_baseline_identity", lambda *_args, **_kwargs: None - ) - with pytest.raises(RuntimeError, match="diverged"): - precompute.cohort_identity(2026, ["state/ca"]) + identity = year_file_identity(national_year_file(DEFAULT_YEAR)) + finally: + get_country_release_bundle.cache_clear() + assert identity.filename == f"{expected_stem}_year_{DEFAULT_YEAR}.h5" diff --git a/projects/policyengine-simulation-executor/tests/test_simulation_output_dataset_loading.py b/projects/policyengine-simulation-executor/tests/test_simulation_output_dataset_loading.py index 27b498778..f4155ee5b 100644 --- a/projects/policyengine-simulation-executor/tests/test_simulation_output_dataset_loading.py +++ b/projects/policyengine-simulation-executor/tests/test_simulation_output_dataset_loading.py @@ -23,7 +23,7 @@ def _load_through_runtime( monkeypatch, *, region_resolution, selection, baked_folder, time_period=2026 ): """Run the annual runtime up to its dataset load and return what it did.""" - from policyengine_simulation_executor import state_datasets + from policyengine_simulation_executor.stage12_cache import levels load_calls = [] lookups = [] @@ -32,8 +32,8 @@ def fake_load_dataset(_params, *, country_module, selection, data_folder=None): load_calls.append({"selection": selection, "data_folder": data_folder}) return object() - def fake_baked_state_data_folder(**kwargs): - lookups.append(kwargs) + def fake_prebuilt_dataset_folder(run, data_folder): + lookups.append({"run": run, "data_folder": data_folder}) return baked_folder def stop_after_loading(*_args, **_kwargs): @@ -55,9 +55,7 @@ def stop_after_loading(*_args, **_kwargs): "policyengine_simulation_executor.simulation_runtime._load_dataset", fake_load_dataset, ) - monkeypatch.setattr( - state_datasets, "baked_state_data_folder", fake_baked_state_data_folder - ) + monkeypatch.setattr(levels, "prebuilt_dataset_folder", fake_prebuilt_dataset_folder) monkeypatch.setattr( "policyengine_simulation_executor.simulation_runtime._build_simulation", stop_after_loading, @@ -87,31 +85,38 @@ def _regional_selection(): ) +def _prebuilt(folder, dataset_source=None): + from policyengine_simulation_executor.stage12_cache.levels import PrebuiltFolder + + return PrebuiltFolder(folder=folder, dataset_source=dataset_source) + + def test_runtime_loads_a_state_from_its_baked_folder(monkeypatch): + utah = RegionResolution(code="state/ut", dataset_reference="ref", state_code="UT") loaded = _load_through_runtime( monkeypatch, - region_resolution=RegionResolution( - code="state/ut", dataset_reference="ref", state_code="UT" - ), + region_resolution=utah, selection=_regional_selection(), - baked_folder="/opt/policyengine/data/state-datasets/acs/UT", + baked_folder=_prebuilt( + "/opt/policyengine/data/prebuilt/us/acs/UT", "baked_state" + ), ) assert loaded.load_calls == [ { "selection": _regional_selection(), - "data_folder": "/opt/policyengine/data/state-datasets/acs/UT", - } - ] - assert loaded.lookups == [ - { - "country": "us", - "selection": _regional_selection(), - "state_code": "UT", - "year": 2026, - "data_folder": resolve_data_folder(), + "data_folder": "/opt/policyengine/data/prebuilt/us/acs/UT", } ] + assert len(loaded.lookups) == 1 + run = loaded.lookups[0]["run"] + assert (run.country, run.year, run.region, run.dataset) == ( + "us", + 2026, + utah, + _regional_selection(), + ) + assert loaded.lookups[0]["data_folder"] == resolve_data_folder() assert loaded.context["dataset_source"] == "baked_state" @@ -129,20 +134,38 @@ def test_runtime_prepares_a_state_on_demand_without_a_baked_file(monkeypatch): ) assert loaded.load_calls[0]["data_folder"] is None - assert loaded.lookups[0]["year"] == 2028 + assert loaded.lookups[0]["run"].year == 2028 assert loaded.context["dataset_source"] == "on_demand" -def test_runtime_loads_a_national_run_from_the_default_folder(monkeypatch): +def _default_selection(): bundle = get_country_release_bundle("us") + return DatasetSelection( + name=bundle.default_dataset, + uri=bundle.default_dataset_uri, + is_default=True, + ) + + +def test_runtime_loads_a_national_run_from_its_prebuilt_folder(monkeypatch): loaded = _load_through_runtime( monkeypatch, region_resolution=RegionResolution(code="us"), - selection=DatasetSelection( - name=bundle.default_dataset, - uri=bundle.default_dataset_uri, - is_default=True, - ), + selection=_default_selection(), + baked_folder=_prebuilt("/opt/policyengine/data/prebuilt/us/populace/all"), + ) + + assert loaded.load_calls[0]["data_folder"] == ( + "/opt/policyengine/data/prebuilt/us/populace/all" + ) + assert "dataset_source" not in loaded.context + + +def test_runtime_loads_a_national_run_from_the_default_folder(monkeypatch): + loaded = _load_through_runtime( + monkeypatch, + region_resolution=RegionResolution(code="us"), + selection=_default_selection(), baked_folder=None, ) @@ -152,7 +175,7 @@ def test_runtime_loads_a_national_run_from_the_default_folder(monkeypatch): def _builder_data_version(monkeypatch, *, region_resolution, dataset_selection): """Run the annual runtime and return the data version it gives the builder.""" - from policyengine_simulation_executor import state_datasets + from policyengine_simulation_executor.stage12_cache import levels selection = installed_spm_selection() simulations = [spm_capable_simulation(selection), spm_capable_simulation(selection)] @@ -178,7 +201,7 @@ def serialize(self): lambda _params, *, region_resolution: dataset_selection, ) monkeypatch.setattr( - state_datasets, "baked_state_data_folder", lambda **_kwargs: None + levels, "prebuilt_dataset_folder", lambda _run, _data_folder: None ) monkeypatch.setattr( "policyengine_simulation_executor.simulation_runtime._load_dataset", diff --git a/projects/policyengine-simulation-executor/tests/test_us_artifact_lookup_pins.py b/projects/policyengine-simulation-executor/tests/test_us_artifact_lookup_pins.py new file mode 100644 index 000000000..98baf8c16 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_us_artifact_lookup_pins.py @@ -0,0 +1,453 @@ +"""Pins of the runtime lookup of prebuilt US baselines and state-level year files. + +Three lookups decide whether a request reads a prebuilt file: which requests +get a fixed baseline ID (``qualifying_baseline_identity`` and +``deterministic_baseline_id``), which outcome ``ArtifactBaselineSimulation`` +records when it loads one (``hit``, ``incomplete`` or ``miss``, reported as +the run's ``baseline_artifact`` attribute), and which folder a run reads its +year file from (``prebuilt_dataset_folder``, which replaced +``baked_state_data_folder``). + +Which requests get a fixed ID, the outcomes and the rule a prebuilt file must +pass are what ``main`` did on 2026-11-25 (commit 544ff628), for the fixed +inputs in ``fixtures.us_prebuilt_inputs``, and must not change. The approved +1.6 · 1 design (section 2) replaced the ``bl1`` IDs with ``bl3`` ones and moved +image files to ``prebuilt/``, so the IDs, store paths and folders were +recorded from the new code. +""" + +from __future__ import annotations + +from pathlib import Path +from types import SimpleNamespace + +import pandas as pd +import pytest +from fixtures.us_prebuilt_inputs import ( + enable_fixed_spm_capability, + install_us_prebuilt_inputs, +) +from policyengine.core.scoping_strategy import RegionGroupStrategy, RowFilterStrategy +from policyengine_simulation_contract.spm import SPMInputError +from policyengine_simulation_executor import baseline_artifacts, precompute +from policyengine_simulation_executor import simulation_runtime as runtime +from policyengine_simulation_executor.region_resolution import RegionResolution +from policyengine_simulation_executor.simulation_runtime import DatasetSelection +from policyengine_simulation_executor.stage12_cache import levels, levels_us + +US_NATIONAL_2026_ID = "bl3-48380a609a4e26de" +US_CALIFORNIA_GROUP_2026_ID = "bl3-ef3ab6b4dce1d62a" +DEFAULT_DATASET = DatasetSelection( + "populace_cps", "hf://org/repo/populace_cps.h5@rev-abc", is_default=True +) +STATE_LEVEL_DATASET = DatasetSelection( + "populace_cps_local", + "hf://org/repo/populace_cps_local.h5@rev-local", + is_default=False, +) +UK_DEFAULT_DATASET = DatasetSelection( + "enhanced_frs", "hf://org/uk-repo/enhanced_frs.h5@rev-uk", is_default=True +) + + +@pytest.fixture +def us_inputs(monkeypatch): + return install_us_prebuilt_inputs(monkeypatch) + + +def _identity_request(**overrides): + request_facts = { + "params": {"country": "us", "scope": "macro", "time_period": 2026}, + "country": "us", + "dataset": DEFAULT_DATASET, + "policy": None, + "region_code": "us", + "scoping_strategy": None, + "year": 2026, + } + request_facts.update(overrides) + return baseline_artifacts.BaselineIdentityRequest(**request_facts) + + +def _region_group_request(group, year=2026): + params = { + "country": "us", + "scope": "macro", + "region_group": list(group), + "time_period": year, + } + resolution = runtime.resolve_region( + country_module=runtime._country_module("us"), country="us", params=params + ) + return _identity_request( + params=params, + region_code=resolution.code, + scoping_strategy=resolution.scoping_strategy, + year=year, + ) + + +@pytest.mark.usefixtures("us_inputs") +class TestRequestsWithAFixedBaselineId: + @pytest.mark.parametrize( + ("year", "expected_id", "expected_path"), + [ + ( + 2026, + US_NATIONAL_2026_ID, + "baselines/us/48380a609a4e26de1ed026e587f1feb69797c06f35de82e024d3c8d10f9bac1e/bl3-48380a609a4e26de.h5", + ), + ( + 2027, + "bl3-9f55154c42502ec9", + "baselines/us/9f55154c42502ec96b358b6ae0a0a5b44d3bc66a84c3bc151dad17dd764993d9/bl3-9f55154c42502ec9.h5", + ), + ( + 2025, + "bl3-81070e29653b2b5e", + "baselines/us/81070e29653b2b5e8ef8c6f2f3c1b09b085e5df12fddfc60d7c4adf73744a572/bl3-81070e29653b2b5e.h5", + ), + ], + ids=["2026", "2027", "2025"], + ) + def test_us_national_current_law(self, year, expected_id, expected_path): + params = {"country": "us", "scope": "macro", "time_period": year} + request = _identity_request(params=params, year=year) + + identity = baseline_artifacts.qualifying_baseline_identity(request) + + assert identity.region == "national" + assert identity.scope_key is None + assert identity.simulation_id == expected_id + assert identity.store_path == expected_path + assert baseline_artifacts.deterministic_baseline_id(request) == expected_id + + def test_us_region_group_matches_the_planned_baseline(self): + request = _region_group_request(["state/ca"]) + + identity = baseline_artifacts.qualifying_baseline_identity(request) + + assert identity.region == "region_group/state/ca" + assert identity.scope_key == "region_group:row_filter:state_fips=6" + assert identity.simulation_id == US_CALIFORNIA_GROUP_2026_ID + california = levels.handler_for( + "us", levels.DatasetLevel.STATE_GROUP + ).baseline_targets(2026)[15] + planned = precompute.baseline_target_identity(california) + assert planned.simulation_id == US_CALIFORNIA_GROUP_2026_ID + assert planned.store_path == identity.store_path + + def test_uk_national_current_law(self): + request = _identity_request( + params={"country": "uk", "scope": "macro"}, + country="uk", + region_code="uk", + dataset=UK_DEFAULT_DATASET, + ) + + identity = baseline_artifacts.qualifying_baseline_identity(request) + + assert identity.simulation_id == "bl3-83544ee09deea7e0" + assert identity.store_path == ( + "baselines/uk/83544ee09deea7e005e67260e709d95791ae00eff91e1ac4297205b675f1a98b/bl3-83544ee09deea7e0.h5" + ) + assert identity.year_file.store_path == ( + "year-files/uk/a911bc00e6d82eb65c2e72c65c3a01732f4b7b79d84ada654700445ff5c3cd0e/enhanced_frs_year_2026.h5" + ) + + def test_uk_group_of_nations_current_law(self): + """As on main: a UK region group on the default dataset keeps a fixed ID. + + It reads the UK national year file, keyed by the group's scope. + """ + group = RegionGroupStrategy( + members=[ + RowFilterStrategy(variable_name="region", variable_value="ENGLAND"), + RowFilterStrategy(variable_name="region", variable_value="WALES"), + ] + ) + request = _identity_request( + params={"country": "uk", "scope": "macro"}, + country="uk", + region_code="region_group/country/england+country/wales", + scoping_strategy=group, + dataset=UK_DEFAULT_DATASET, + ) + + identity = baseline_artifacts.qualifying_baseline_identity(request) + + assert identity.region == "region_group/country/england+country/wales" + assert identity.scope_key == group.cache_key + assert identity.year_file.store_path.endswith("/enhanced_frs_year_2026.h5") + assert identity.year_file.subset is None + assert baseline_artifacts.deterministic_baseline_id(request) == ( + identity.simulation_id + ) + + def test_us_national_with_the_spm_capability(self, monkeypatch, us_inputs): + enable_fixed_spm_capability(monkeypatch, us_inputs) + + identity = baseline_artifacts.qualifying_baseline_identity(_identity_request()) + + assert identity.simulation_id == "bl3-a19ba492ccb50823" + assert identity.storage_id == ( + "bl3-a19ba492ccb50823-spm-7396bf5f4876c42bb6cba0f9533478098edc0861cc3657bd0d60f88dbb26ac39" + ) + assert identity.store_path == ( + "baselines/us/a19ba492ccb50823fe231bc62a5da265a82a53bc3907de616f3334eb82ca20e8/" + "bl3-a19ba492ccb50823-spm-7396bf5f4876c42bb6cba0f9533478098edc0861cc3657bd0d60f88dbb26ac39.h5" + ) + + @pytest.mark.parametrize( + "overrides", + [ + pytest.param({"policy": {"gov.irs.credits.ctc.amount": 1}}, id="reform"), + pytest.param( + {"params": {"country": "us", "scope": "household"}}, id="household" + ), + pytest.param({"params": {"country": "us"}}, id="no-scope"), + pytest.param({"dataset": STATE_LEVEL_DATASET}, id="state-level-dataset"), + pytest.param({"region_code": None}, id="unresolved-region"), + pytest.param({"region_code": "state/ca"}, id="unscoped-state"), + pytest.param( + { + "region_code": "state/ca", + "scoping_strategy": RowFilterStrategy( + variable_name="state_fips", variable_value=6 + ), + }, + id="single-state", + ), + pytest.param( + { + "country": "uk", + "region_code": "uk", + "dataset": DatasetSelection( + "dense", "hf://dense", is_default=False + ), + }, + id="uk-local-area", + ), + ], + ) + def test_requests_without_a_fixed_id(self, overrides): + request = _identity_request(**overrides) + + assert baseline_artifacts.qualifying_baseline_identity(request) is None + assert baseline_artifacts.deterministic_baseline_id(request) is None + + def test_identity_collection_failure(self, monkeypatch): + from policyengine_simulation_executor import artifact_keys + + def failing_collection(*_arguments, **_keyword_arguments): + msg = "release manifest unavailable" + raise RuntimeError(msg) + + monkeypatch.setattr(artifact_keys, "year_file_identity", failing_collection) + + with pytest.raises(RuntimeError, match="release manifest unavailable"): + baseline_artifacts.qualifying_baseline_identity(_identity_request()) + assert baseline_artifacts.deterministic_baseline_id(_identity_request()) is None + + def test_an_spm_selection_without_a_capability_is_refused(self): + params = { + "country": "us", + "scope": "macro", + "time_period": 2026, + "spm": {"scenario": "ce_trend"}, + } + + with pytest.raises(SPMInputError): + baseline_artifacts.deterministic_baseline_id( + _identity_request(params=params) + ) + + +class _LoadingModelVersion: + """A model version whose ``load`` finds a complete, incomplete or no artifact.""" + + required_columns = ("age", "income") + + def __init__(self, stored_artifact: str) -> None: + self.stored_artifact = stored_artifact + self.calls: list[str] = [] + + def resolve_entity_variables(self, _simulation): + return {"person": list(self.required_columns)} + + def load(self, simulation): + self.calls.append("load") + if self.stored_artifact == "absent": + msg = "no artifact" + raise FileNotFoundError(msg) + if self.stored_artifact == "unreadable": + msg = "corrupt h5" + raise OSError(msg) + columns = ( + self.required_columns + if self.stored_artifact == "complete" + else self.required_columns[:1] + ) + simulation.output_dataset = _output_with_columns(columns) + + def run(self, simulation): + self.calls.append("run") + simulation.output_dataset = _output_with_columns(self.required_columns) + + def save(self, _simulation): + self.calls.append("save") + + +def _output_with_columns(columns): + frame = pd.DataFrame({column: [1.0] for column in columns}) + return SimpleNamespace(data=SimpleNamespace(entity_data={"person": frame})) + + +@pytest.fixture +def empty_simulation_cache(monkeypatch): + from policyengine.core import simulation as simulation_module + from policyengine.core.cache import LRUCache + + monkeypatch.setattr(simulation_module, "_cache", LRUCache(max_size=10)) + + +@pytest.mark.usefixtures("empty_simulation_cache") +class TestBaselineArtifactOutcomes: + @pytest.mark.parametrize( + ("stored_artifact", "expected_outcome", "expected_calls"), + [ + ("complete", "hit", ["load"]), + ("incomplete", "incomplete", ["load", "run", "save"]), + ("absent", "miss", ["load", "run", "save"]), + ("unreadable", "miss", ["load", "run", "save"]), + ], + ) + def test_outcome_of_the_first_ensure( + self, stored_artifact, expected_outcome, expected_calls + ): + model_version = _LoadingModelVersion(stored_artifact) + simulation = baseline_artifacts.ArtifactBaselineSimulation.model_construct( + id=US_NATIONAL_2026_ID, + dataset=None, + tax_benefit_model_version=model_version, + policy=None, + dynamic=None, + scoping_strategy=None, + extra_variables={}, + output_dataset=None, + ) + + simulation.ensure() + simulation.ensure() + + assert simulation.artifact_outcome == expected_outcome + assert model_version.calls == expected_calls + + def test_outcome_labels(self): + assert ( + baseline_artifacts.OUTCOME_HIT, + baseline_artifacts.OUTCOME_INCOMPLETE, + baseline_artifacts.OUTCOME_MISS, + ) == ("hit", "incomplete", "miss") + + +@pytest.fixture +def baked_utah_folder(us_inputs, tmp_path, monkeypatch): + """Return a data folder holding Utah's 2026 state-level year file. + + The file passes the reuse checks until a test sets ``reuse_checks.problem``. + """ + folder = tmp_path / "prebuilt" / "us" / "populace_cps_local" / "UT" + folder.mkdir(parents=True) + (folder / "populace_cps_local_year_2026.h5").write_bytes(b"year file") + reuse_checks = SimpleNamespace(problem=None, checked=[]) + + def year_file_reuse_problem(path, dataset): + reuse_checks.checked.append((Path(path), dataset)) + if isinstance(reuse_checks.problem, Exception): + raise reuse_checks.problem + return reuse_checks.problem + + monkeypatch.setattr(levels_us, "year_file_reuse_problem", year_file_reuse_problem) + return SimpleNamespace( + data_folder=str(tmp_path), + folder=folder, + reuse_checks=reuse_checks, + state_level=STATE_LEVEL_DATASET, + default=DEFAULT_DATASET, + ) + + +def _baked_folder(baked, **overrides): + lookup = { + "country": "us", + "selection": baked.state_level, + "state_code": "UT", + "year": 2026, + } + lookup.update(overrides) + state_code = lookup["state_code"] + region = RegionResolution( + code=f"state/{(state_code or 'xx').lower()}", + scoping_strategy=RowFilterStrategy( + variable_name="state_fips", + variable_value={"UT": 49, "ut": 49, "WY": 56}.get(state_code, 0), + ), + state_code=state_code, + ) + found = levels.prebuilt_dataset_folder( + levels.RunScope( + country=lookup["country"], + year=lookup["year"], + region=region, + dataset=lookup["selection"], + ), + baked.data_folder, + ) + return None if found is None else found.folder + + +class TestBakedStateDataFolder: + def test_a_state_reads_its_baked_folder(self, baked_utah_folder): + assert _baked_folder(baked_utah_folder) == str(baked_utah_folder.folder) + assert baked_utah_folder.reuse_checks.checked == [ + ( + baked_utah_folder.folder / "populace_cps_local_year_2026.h5", + "populace_cps_local", + ) + ] + + def test_a_lower_case_state_code_reads_the_same_folder(self, baked_utah_folder): + assert _baked_folder(baked_utah_folder, state_code="ut") == str( + baked_utah_folder.folder + ) + + @pytest.mark.parametrize( + "overrides", + [ + pytest.param({"country": "uk"}, id="uk"), + pytest.param({"state_code": None}, id="no-state"), + pytest.param({"state_code": "WY"}, id="state-without-a-file"), + pytest.param({"year": 2027}, id="year-without-a-file"), + ], + ) + def test_requests_that_read_nothing_baked(self, baked_utah_folder, overrides): + assert _baked_folder(baked_utah_folder, **overrides) is None + + def test_the_default_dataset_reads_nothing_baked(self, baked_utah_folder): + assert ( + _baked_folder(baked_utah_folder, selection=baked_utah_folder.default) + is None + ) + + def test_a_file_that_fails_the_reuse_checks_reads_nothing_baked( + self, baked_utah_folder + ): + baked_utah_folder.reuse_checks.problem = "year-file stamp is missing" + + assert _baked_folder(baked_utah_folder) is None + + def test_unimportable_reuse_checks_read_nothing_baked(self, baked_utah_folder): + baked_utah_folder.reuse_checks.problem = ImportError("moved helper") + + assert _baked_folder(baked_utah_folder) is None diff --git a/projects/policyengine-simulation-executor/tests/test_us_manifest_pins.py b/projects/policyengine-simulation-executor/tests/test_us_manifest_pins.py new file mode 100644 index 000000000..51df88124 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_us_manifest_pins.py @@ -0,0 +1,166 @@ +"""Pins of the US deploy manifest: its entries, its bytes and its digest. + +The manifest is content-addressed: its digest names the store object +``manifests/.json`` and reaches the deploy as +``POLICYENGINE_MANIFEST_DIGEST``, so the same plan must keep giving +byte-identical manifest JSON. The approved 1.6 · 1 design (section 4) +replaced the ``mf1`` manifest with one ``mf2`` manifest per country, whose +entries share one shape and record each file's SHA-256 and size, so the +order, bytes and digests below were recorded from the new code for the fixed +inputs in ``fixtures.us_prebuilt_inputs``. Write-once publishing, the +``MANIFEST_DIGEST=`` output line and the deployed marker are unchanged from +``main`` before the handlers (commit 544ff628). +""" + +from __future__ import annotations + +import hashlib + +import pytest +from fixtures.us_prebuilt_inputs import ( + enable_fixed_spm_capability, + install_us_prebuilt_inputs, +) +from policyengine_simulation_executor import artifact_keys, precompute +from policyengine_simulation_executor.artifact_store import ArtifactStore + +BUCKET = "bucket-pins" + +US_MANIFEST_DIGEST = "1461437612f03df403013e98fa10dfd65609ae828f31a79bf7adc899513a6d57" +US_MANIFEST_BYTES_SHA256 = ( + "0713954874042dfa47bc7a9cd717f0e174c78128e57d5b13c3c83afb37cca8e9" +) +US_SPM_MANIFEST_DIGEST = ( + "fced66e5754bd8bfae462e806d5215234eedc1ad69cfb78eba1e774c92b9d0b0" +) +US_SPM_MANIFEST_BYTES_SHA256 = ( + "dce59ab37a9b46a91cea3fee94980efba2f865ce3c3b634a95ad7d63480affb2" +) + + +def _store_every_planned_file(inputs, plan): + """Store each planned file, its path as its bytes, with its hash and size.""" + for entry in [*plan.year_files, *plan.baselines]: + content = entry.path.encode() + inputs.gcs_client.objects[entry.path] = content + inputs.gcs_client.object_metadata[entry.path] = { + "sha256": hashlib.sha256(content).hexdigest(), + "size_bytes": str(len(content)), + } + + +@pytest.fixture +def us_inputs(monkeypatch): + return install_us_prebuilt_inputs(monkeypatch) + + +@pytest.fixture +def us_plan(us_inputs): + plan = precompute.plan_artifacts_impl(BUCKET, "us") + _store_every_planned_file(us_inputs, plan) + return plan + + +@pytest.fixture +def us_spm_plan(monkeypatch, us_inputs): + enable_fixed_spm_capability(monkeypatch, us_inputs) + plan = precompute.plan_artifacts_impl(BUCKET, "us") + _store_every_planned_file(us_inputs, plan) + return plan + + +def _stored(inputs, plan): + store = ArtifactStore(BUCKET) + return { + entry.path: store.describe(entry.path) + for entry in [*plan.year_files, *plan.baselines] + } + + +class TestManifestOfTheUsPlan: + def test_lists_each_years_files_then_the_baselines(self, us_inputs, us_plan): + manifest = precompute.build_manifest(us_plan, _stored(us_inputs, us_plan)) + + assert manifest.manifest_schema == "mf2" + assert manifest.country == "us" + assert manifest.receipt == us_plan.receipt + assert [ + (artifact.kind, artifact.level, artifact.year) + for artifact in manifest.artifacts + ] == [ + *[ + (kind, level, year) + for year in (2026, 2027, 2025) + for kind, level in [("year_file", "national")] + + [("year_file", "state")] * 51 + ], + *[ + ("baseline", "state_group", year) + for year in (2026, 2027, 2025) + for _group in range(20) + ], + ] + assert [artifact.path for artifact in manifest.artifacts] == [ + entry.path for entry in [*us_plan.year_files, *us_plan.baselines] + ] + + def test_manifest_digest(self, us_inputs, us_plan): + payload = precompute.build_manifest( + us_plan, _stored(us_inputs, us_plan) + ).canonical_payload() + + assert artifact_keys.canonical_digest(payload) == US_MANIFEST_DIGEST + + def test_published_manifest_bytes_and_digest(self, us_inputs, us_plan): + digest = precompute.publish_manifest_impl(BUCKET, us_plan) + + assert digest == US_MANIFEST_DIGEST + bucket, path, data, keyword_arguments = us_inputs.gcs_client.uploads[-1] + assert bucket == BUCKET + assert path == f"manifests/{US_MANIFEST_DIGEST}.json" + assert keyword_arguments == { + "content_type": "application/json", + "if_generation_match": 0, + } + assert hashlib.sha256(data).hexdigest() == US_MANIFEST_BYTES_SHA256 + + def test_spm_manifest_bytes_and_digest(self, us_inputs, us_spm_plan): + digest = precompute.publish_manifest_impl(BUCKET, us_spm_plan) + + assert digest == US_SPM_MANIFEST_DIGEST + _bucket, path, data, _keyword_arguments = us_inputs.gcs_client.uploads[-1] + assert path == f"manifests/{US_SPM_MANIFEST_DIGEST}.json" + assert hashlib.sha256(data).hexdigest() == US_SPM_MANIFEST_BYTES_SHA256 + + def test_republishing_keeps_the_stored_manifest(self, us_inputs, us_plan): + first_digest = precompute.publish_manifest_impl(BUCKET, us_plan) + stored = dict(us_inputs.gcs_client.objects) + + assert precompute.publish_manifest_impl(BUCKET, us_plan) == first_digest + assert us_inputs.gcs_client.objects == stored + + +def test_digest_output_line(): + assert precompute.MANIFEST_DIGEST_PREFIX == "MANIFEST_DIGEST=" + assert ( + precompute.manifest_digest_line(US_MANIFEST_DIGEST) + == f"MANIFEST_DIGEST={US_MANIFEST_DIGEST}" + ) + + +class TestDeployedMarker: + def test_marker_overwrites_its_environment_path(self, us_inputs): + store = ArtifactStore(BUCKET) + + store.write_deployed_marker("prod", {"manifest_digest": "first"}) + store.write_deployed_marker("prod", {"manifest_digest": US_MANIFEST_DIGEST}) + + uploads = us_inputs.gcs_client.uploads + assert [(bucket, path) for bucket, path, _data, _kwargs in uploads] == [ + (BUCKET, "deployed/prod.json"), + (BUCKET, "deployed/prod.json"), + ] + assert uploads[-1][3] == {"content_type": "application/json"} + assert us_inputs.gcs_client.objects["deployed/prod.json"] == ( + f'{{\n "manifest_digest": "{US_MANIFEST_DIGEST}"\n}}'.encode() + ) diff --git a/projects/policyengine-simulation-executor/tests/test_us_precompute_plan_pins.py b/projects/policyengine-simulation-executor/tests/test_us_precompute_plan_pins.py new file mode 100644 index 000000000..c269a09a1 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_us_precompute_plan_pins.py @@ -0,0 +1,389 @@ +"""Pins of the US precompute plan, and of the keys and store paths it uses. + +Two kinds of pin, for the fixed inputs in ``fixtures.us_prebuilt_inputs``: + +* **What is built**, recorded from ``main`` on 2026-11-25 (commit 544ff628) + before the level handlers: the years, the 20 groups of states in order, the + 51 states sorted by code, each file's dataset, year, state and region, and + which entries ``select_work`` picks. These must not change. +* **How it is named** — every digest, store path, simulation ID and image + folder. The approved 1.6 · 1 design (section 2) replaced the ``ds1``, + ``sds1`` and ``bl1`` keys with ``yf1`` and ``bl3`` and moved image files to + ``prebuilt/``, so these values were recorded from the new code, and pin + that layout from here on. + +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.us_prebuilt_inputs import ( + US_STATE_FIPS, + enable_fixed_spm_capability, + install_us_prebuilt_inputs, +) +from policyengine_simulation_executor import artifact_keys, precompute +from policyengine_simulation_executor.precompute_models import BundleVersionIdentity + +if TYPE_CHECKING: + from policyengine_simulation_executor.precompute_models import PrecomputePlan + +BUCKET = "bucket-pins" +PLANNED_YEARS = [2026, 2027, 2025] + +# 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"], +] +STATE_CODES = sorted(state_code for state_code, _fips in US_STATE_FIPS) + +# Recorded from the new code on 2026-11-26 for the fixed inputs. +RECORDED_NATIONAL_ROWS = [ + [ + 2026, + "56982f3075d99409fc40edca6e1b9265feef6442a2c881fe2962d865db806f55", + "year-files/us/56982f3075d99409fc40edca6e1b9265feef6442a2c881fe2962d865db806f55/populace_cps_year_2026.h5", + "populace_cps_year_2026.h5", + "prebuilt/us/populace_cps/all", + ], + [ + 2027, + "a220e74587d1eecb46e395d6a6a71423f5494f6eee298b8c5658eadaa28cd786", + "year-files/us/a220e74587d1eecb46e395d6a6a71423f5494f6eee298b8c5658eadaa28cd786/populace_cps_year_2027.h5", + "populace_cps_year_2027.h5", + "prebuilt/us/populace_cps/all", + ], + [ + 2025, + "c7de61261d1ddd0fffe81153bb7604a1690aad7b9041b5a7aaa6be740b21eefa", + "year-files/us/c7de61261d1ddd0fffe81153bb7604a1690aad7b9041b5a7aaa6be740b21eefa/populace_cps_year_2025.h5", + "populace_cps_year_2025.h5", + "prebuilt/us/populace_cps/all", + ], +] +RECORDED_FIRST_STATE = [ + 2026, + "AK", + "state/ak", + "populace_cps_local", + "305094a4f28987777a645186f82d63e241ac509df152bd91b4eb45c2cdbf8e2f", + "year-files/us/305094a4f28987777a645186f82d63e241ac509df152bd91b4eb45c2cdbf8e2f/populace_cps_local_year_2026.h5", + "populace_cps_local_year_2026.h5", + "prebuilt/us/populace_cps_local/AK", +] +RECORDED_STATES_DIGEST = ( + "831e5d6d2d23002da88592cc25d6fa5b25c0e4e3530864ead465cd3726d80afe" +) +RECORDED_FIRST_BASELINE = [ + 2026, + ["state/hi", "state/ia", "state/wi"], + "region_group/state/hi+state/ia+state/wi", + "a58482ed86d0ff70024ed01b7a3d35ab0c4feef23d4dd01d1d5d2ff1b67aa9f5", + "baselines/us/a58482ed86d0ff70024ed01b7a3d35ab0c4feef23d4dd01d1d5d2ff1b67aa9f5/bl3-a58482ed86d0ff70.h5", + "bl3-a58482ed86d0ff70", + "bl3-a58482ed86d0ff70", + "year-files/us/56982f3075d99409fc40edca6e1b9265feef6442a2c881fe2962d865db806f55/populace_cps_year_2026.h5", + "prebuilt/us/populace_cps/all", +] +RECORDED_BASELINES_DIGEST = ( + "39d0efc104687538bc8373996a33cbb8ff7da7beb44efc54326c93119687ccd4" +) +RECORDED_SPM_NATIONAL_ROWS = [ + [ + 2026, + "8370022a270fea66460788e1f282dbabc281a82fb1864ae9eed57ecb8be96186", + "year-files/us/8370022a270fea66460788e1f282dbabc281a82fb1864ae9eed57ecb8be96186/populace_cps_year_2026.h5", + "populace_cps_year_2026.h5", + "prebuilt/us/populace_cps/all", + ], + [ + 2027, + "7a4fd448280a04398768d1f3860902847a17048ae65fb2f25997094f1f2841dd", + "year-files/us/7a4fd448280a04398768d1f3860902847a17048ae65fb2f25997094f1f2841dd/populace_cps_year_2027.h5", + "populace_cps_year_2027.h5", + "prebuilt/us/populace_cps/all", + ], + [ + 2025, + "f15bd311ac06202000ca60537dcc5403f67793da52d364b45271c5a8a7744561", + "year-files/us/f15bd311ac06202000ca60537dcc5403f67793da52d364b45271c5a8a7744561/populace_cps_year_2025.h5", + "populace_cps_year_2025.h5", + "prebuilt/us/populace_cps/all", + ], +] +RECORDED_SPM_FIRST_STATE = [ + 2026, + "AK", + "state/ak", + "populace_cps_local", + "52fa02df9d44edafdd94bf984bb1e44d9c03522f0d928252e0465220e06adfbe", + "year-files/us/52fa02df9d44edafdd94bf984bb1e44d9c03522f0d928252e0465220e06adfbe/populace_cps_local_year_2026.h5", + "populace_cps_local_year_2026.h5", + "prebuilt/us/populace_cps_local/AK", +] +RECORDED_SPM_STATES_DIGEST = ( + "0f0ad34015581add61ba29f23bd9b1c5931ddebcc55719d7306870e5dc10ca4b" +) +RECORDED_SPM_FIRST_BASELINE = [ + 2026, + ["state/hi", "state/ia", "state/wi"], + "region_group/state/hi+state/ia+state/wi", + "dca23ffa8f9b5872e827326f17d1844f01a7c423a651b4fb12fce0b293874648", + "baselines/us/dca23ffa8f9b5872e827326f17d1844f01a7c423a651b4fb12fce0b293874648/bl3-dca23ffa8f9b5872-spm-7396bf5f4876c42bb6cba0f9533478098edc0861cc3657bd0d60f88dbb26ac39.h5", + "bl3-dca23ffa8f9b5872", + "bl3-dca23ffa8f9b5872-spm-7396bf5f4876c42bb6cba0f9533478098edc0861cc3657bd0d60f88dbb26ac39", + "year-files/us/8370022a270fea66460788e1f282dbabc281a82fb1864ae9eed57ecb8be96186/populace_cps_year_2026.h5", + "prebuilt/us/populace_cps/all", +] +RECORDED_SPM_BASELINES_DIGEST = ( + "92ed00e683059d0d81c8b6678f83046fbd5bfd8f48414fe4c39f01d67bb97d53" +) + + +def _digest_of(entries: list) -> str: + return artifact_keys.canonical_digest({"entries": entries}) + + +def _national_rows(plan: PrecomputePlan) -> list[list]: + return [ + [entry.year, entry.digest, entry.path, entry.filename, entry.folder] + for entry in plan.year_files + if entry.subset_code is None + ] + + +def _state_rows(plan: PrecomputePlan) -> list[list]: + return [ + [ + entry.year, + entry.subset_code, + entry.region, + entry.dataset, + entry.digest, + entry.path, + entry.filename, + entry.folder, + ] + for entry in plan.year_files + if entry.subset_code is not None + ] + + +def _baseline_rows(plan: PrecomputePlan) -> list[list]: + return [ + [ + entry.year, + entry.request["region_group"], + entry.region, + entry.digest, + entry.path, + entry.simulation_id, + entry.storage_id, + entry.year_file_path, + entry.folder, + ] + for entry in plan.baselines + ] + + +@pytest.fixture +def us_inputs(monkeypatch): + return install_us_prebuilt_inputs(monkeypatch) + + +@pytest.fixture +def us_plan(us_inputs): + return precompute.plan_artifacts_impl(BUCKET, "us") + + +@pytest.fixture +def us_spm_plan(monkeypatch, us_inputs): + enable_fixed_spm_capability(monkeypatch, us_inputs) + return precompute.plan_artifacts_impl(BUCKET, "us") + + +class TestWhatTheUsPlanBuilds: + """Unchanged from ``main`` before the handlers.""" + + def test_the_default_dataset_year_file_for_each_year(self, us_plan): + national = [entry for entry in us_plan.year_files if entry.subset_code is None] + + assert [(entry.year, entry.dataset) for entry in national] == [ + (year, "populace_cps") for year in PLANNED_YEARS + ] + assert [entry.filename for entry in national] == [ + f"populace_cps_year_{year}.h5" for year in PLANNED_YEARS + ] + + def test_one_baseline_per_year_and_region_group_in_order(self, us_plan): + assert [ + [entry.year, entry.request["region_group"]] for entry in us_plan.baselines + ] == [[year, group] for year in PLANNED_YEARS for group in US_REGION_GROUPS] + assert [entry.region for entry in us_plan.baselines] == [ + "region_group/" + "+".join(sorted(group)) + for _year in PLANNED_YEARS + for group in US_REGION_GROUPS + ] + + def test_a_state_level_year_file_per_year_and_state(self, us_plan): + states = [entry for entry in us_plan.year_files if entry.subset_code] + + assert [[entry.year, entry.subset_code] for entry in states] == [ + [year, state_code] for year in PLANNED_YEARS for state_code in STATE_CODES + ] + for entry in states: + assert entry.region == f"state/{entry.subset_code.lower()}" + assert entry.dataset == "populace_cps_local" + assert entry.filename == f"populace_cps_local_year_{entry.year}.h5" + + def test_records_the_bundle_version_identity(self, us_plan): + assert us_plan.receipt == BundleVersionIdentity( + policyengine_version="4.22.0", + policyengine_core_version="3.33.3", + model_version="9.9.9", + data_version="1.2.3", + data_artifact_revision="rev-abc", + default_dataset="populace_cps", + ) + + +class TestUsPlanNamesWithoutSpm: + """``yf1`` and ``bl3`` names for a bundle without an SPM capability.""" + + def test_national_year_files(self, us_plan): + assert _national_rows(us_plan) == RECORDED_NATIONAL_ROWS + + def test_every_baseline_identity(self, us_plan): + rows = _baseline_rows(us_plan) + + assert rows[0] == RECORDED_FIRST_BASELINE + assert _digest_of(rows) == RECORDED_BASELINES_DIGEST + + def test_every_state_level_year_file_identity(self, us_plan): + rows = _state_rows(us_plan) + + assert rows[0] == RECORDED_FIRST_STATE + assert _digest_of(rows) == RECORDED_STATES_DIGEST + + +class TestUsPlanNamesWithSpm: + """With an SPM capability, as production's bundle has, every key carries it. + + Each baseline file is named by its simulation ID plus the SPM digest. + """ + + def test_national_year_files(self, us_spm_plan): + assert _national_rows(us_spm_plan) == RECORDED_SPM_NATIONAL_ROWS + + def test_every_baseline_identity(self, us_spm_plan): + rows = _baseline_rows(us_spm_plan) + + assert rows[0] == RECORDED_SPM_FIRST_BASELINE + assert _digest_of(rows) == RECORDED_SPM_BASELINES_DIGEST + + def test_every_state_level_year_file_identity(self, us_spm_plan): + rows = _state_rows(us_spm_plan) + + assert rows[0] == RECORDED_SPM_FIRST_STATE + assert _digest_of(rows) == RECORDED_SPM_STATES_DIGEST + + +class TestUsWorkSelection: + """Which plan entries a run computes, from the store's presence checks.""" + + @pytest.fixture + def plan_with_some_objects_stored(self, us_inputs): + first_plan = precompute.plan_artifacts_impl(BUCKET, "us") + first_state = next( + entry for entry in first_plan.year_files if entry.subset_code + ) + stored_paths = [ + first_plan.year_files[0].path, + first_plan.baselines[0].path, + first_state.path, + ] + us_inputs.gcs_client.objects.update(dict.fromkeys(stored_paths, b"stored")) + return precompute.plan_artifacts_impl(BUCKET, "us") + + def test_an_empty_store_selects_every_entry(self, us_plan): + work = precompute.select_work(us_plan, force=False) + + assert len([entry for entry in work.year_files if not entry.subset_code]) == 3 + assert len(work.baselines) == 60 + assert len([entry for entry in work.year_files if entry.subset_code]) == 153 + + def test_stored_objects_are_not_selected(self, plan_with_some_objects_stored): + plan = plan_with_some_objects_stored + work = precompute.select_work(plan, force=False) + stored = [entry for entry in plan.year_files if entry.exists] + + assert [(entry.year, entry.subset_code) for entry in stored] == [ + (2026, None), + (2026, "AK"), + ] + assert [ + entry.year for entry in work.year_files if entry.subset_code is None + ] == [2027, 2025] + assert work.baselines == plan.baselines[1:] + assert len([entry for entry in work.year_files if entry.subset_code]) == 152 + + def test_force_selects_stored_objects_too(self, plan_with_some_objects_stored): + plan = plan_with_some_objects_stored + work = precompute.select_work(plan, force=True) + + assert work.year_files == plan.year_files + assert work.baselines == plan.baselines + + +class TestKeysAndStorePaths: + """Key schema labels and the store layout every path follows.""" + + def test_key_schema_labels(self): + assert artifact_keys.YEAR_FILE_KEY_SCHEMA == "yf1" + assert artifact_keys.BASELINE_KEY_SCHEMA == "bl3" + assert artifact_keys.SOURCE_FILE_KEY_SCHEMA == "sf1" + assert precompute.MANIFEST_SCHEMA == "mf2" + + def test_artifact_store_paths(self): + assert ( + artifact_keys.year_file_artifact_path( + "US", "y" * 64, "populace_cps_year_2026.h5" + ) + == f"year-files/us/{'y' * 64}/populace_cps_year_2026.h5" + ) + assert ( + artifact_keys.baseline_artifact_path("US", "b" * 64, "bl3-0123456789abcdef") + == f"baselines/us/{'b' * 64}/bl3-0123456789abcdef.h5" + ) + assert ( + artifact_keys.source_file_artifact_path("UK", "s" * 64, "dense.h5") + == f"sources/uk/{'s' * 64}/dense.h5" + ) + + def test_manifest_and_deployed_marker_paths(self): + assert artifact_keys.manifest_path("m" * 64) == f"manifests/{'m' * 64}.json" + assert artifact_keys.deployed_marker_path("prod") == "deployed/prod.json" + assert artifact_keys.deployed_marker_path("beta") == "deployed/beta.json"