diff --git a/changelog.d/microcosm-dataset-selectors.added.md b/changelog.d/microcosm-dataset-selectors.added.md new file mode 100644 index 000000000..1a7a08e28 --- /dev/null +++ b/changelog.d/microcosm-dataset-selectors.added.md @@ -0,0 +1 @@ +Add Microcosm selectors for the certified US national and local-area datasets and accept `--data-producer microcosm` in the release certification CLI. Existing selectors and certification metadata remain supported. diff --git a/changelog.d/microcosm-dataset-selectors.changed.md b/changelog.d/microcosm-dataset-selectors.changed.md new file mode 100644 index 000000000..b0a53997a --- /dev/null +++ b/changelog.d/microcosm-dataset-selectors.changed.md @@ -0,0 +1,7 @@ +Managed US flat year files now record their source SHA-256. `load_datasets` refuses a managed flat file whose recorded hash is missing or differs from the bundle's pin. `ensure_datasets` regenerates it when given the bundle key or an exact URI identifying the pinned artifact. + +US result keys and year filenames now use the full local filename stem. For `sample@local.h5`, the 2024 result is `sample@local_2024` and its file is `sample@local_year_2024.h5`. `create_datasets` raises `ValueError` for a missing explicit local file before writing any year files, except for inputs an earlier request can produce. + +When the bundle pins the same filename stem, unpinned US requests read and write year files only in a subdirectory keyed by the resolved local path or URI. Use `ensure_datasets(..., allow_unmanaged=True)` to build a missing source-specific year file. + +`managed_microsimulation` records verified source provenance for explicit Hugging Face URIs that exactly match a bundle pin. Pinned model inputs and any pinned metadata use a pin-specific cache. US managed state and district runs derive registered legacy SPM declarations from the full ACS-local source and align them to the scoped simulation and its branches. diff --git a/docs/bundles.md b/docs/bundles.md index acaf3ab39..957d8cf62 100644 --- a/docs/bundles.md +++ b/docs/bundles.md @@ -51,7 +51,7 @@ package scaffold: ```python from policyengine.provenance import materialize_dataset -result = materialize_dataset("us", "populace_us_2024") +result = materialize_dataset("us", "microcosm_us_2024") print(result.path) print(result.bundle_dataset.sha256) ``` @@ -59,7 +59,9 @@ print(result.bundle_dataset.sha256) `materialize_dataset` returns the selected source URI and local path. For a bundle-managed input, `bundle_dataset` also contains the selected source package, repository type, revision, verified SHA-256, and optional metadata -path. +path. Runtime materialization uses pin-specific paths for verified files. +Bundle keys and the default selection also populate the repository-relative raw +cache paths used by bundle installation. `policyengine-*-data` and `populace-data` artifacts use the repository type recorded in the bundle. Callers do not infer repository type from the repository name. @@ -203,18 +205,18 @@ To certify a new data release from a data-producer manifest, run: python scripts/bundle.py certify-data \ --country uk \ --data-producer populace \ - --manifest-uri hf://dataset/policyengine/populace-uk-private@/releases//release_manifest.json + --manifest-uri "hf://dataset/policyengine/populace-uk-private@/releases//release_manifest.json" ``` -For US Microcosm releases, certify the Microcosm release manifest directly: +For US Microcosm releases, use the commit that published each build. +Choose listed, non-withdrawn builds from the +[public release index](https://huggingface.co/datasets/policyengine/populace-us/resolve/main/releases.json). ```bash -python scripts/bundle.py certify-data \ - --country us \ - --data-producer populace \ - --manifest-uri hf://dataset/policyengine/populace-us@/releases//release_manifest.json \ - --regional-manifest-uri hf://dataset/policyengine/populace-us@/releases//release_manifest.json \ - --model-version +python scripts/bundle.py certify-data --country us --data-producer microcosm \ + --manifest-uri "hf://dataset/policyengine/populace-us@/releases/microcosm-us-2024-national//release_manifest.json" \ + --regional-manifest-uri "hf://dataset/policyengine/populace-us@/releases/microcosm-us-2024-local//release_manifest.json" \ + --model-version "" ``` US state and congressional-district regions scope one certified ACS-local diff --git a/docs/engineering/runbooks/build-m-us-populace-certification.md b/docs/engineering/runbooks/build-m-us-populace-certification.md index c69f77986..58f7dcf5f 100644 --- a/docs/engineering/runbooks/build-m-us-populace-certification.md +++ b/docs/engineering/runbooks/build-m-us-populace-certification.md @@ -1,9 +1,8 @@ # US Microcosm certification runbook Use this runbook to certify a new national US Microcosm release together with -the shared ACS-local release used for state and congressional-district -simulations. For now, state and district simulations use the national release -instead; see the interim exception in Step 2. Read the +the shared ACS-local release. State and congressional-district simulations use +the shared ACS-local release through the bundle's regional routes. Read the [data certification](../skills/data-certification.md) skill first for validation semantics. @@ -12,11 +11,10 @@ procedure itself is release-independent. ## When to use -Both release manifests have been published to `policyengine/populace-us`, and -the model version used by the national release is known. The national release -will remain the default dataset; the local-area release will remain -non-default and be selected only for supported regional runs (none while the -interim exception in Step 2 holds). +Use this procedure when both release manifests are available in +`policyengine/populace-us` and you know the policyengine-us version to certify. +The bundle selects the national release by default and routes supported +regional runs to the ACS-local release. ## Prerequisites @@ -29,14 +27,9 @@ interim exception in Step 2 holds). ## Step 1 — identify the releases -Set values from the two published release manifests rather than copying an -older certification: - -``` -NATIONAL_RELEASE_ID = populace-us-2024---Z -LOCAL_AREA_RELEASE_ID = populace-us-2024---Z -MODEL_VERSION = -``` +Choose a listed, non-withdrawn build for each release in the [public release index](https://huggingface.co/datasets/policyengine/populace-us/resolve/main/releases.json). +Use each build's identifier and its publishing commit in the command below. +Use the policyengine-us version that both builds support. The local-area manifest must declare `dataset_role: non_default_local_area`, `is_default: false`, no default datasets, and exactly one pinned H5 microdata @@ -45,12 +38,10 @@ artifact. ## Step 2 — certify both releases ```bash -python scripts/bundle.py certify-data \ - --country us \ - --data-producer populace \ - --model-version "$MODEL_VERSION" \ - --manifest-uri "hf://dataset/policyengine/populace-us@$NATIONAL_RELEASE_ID/releases/$NATIONAL_RELEASE_ID/release_manifest.json" \ - --regional-manifest-uri "hf://dataset/policyengine/populace-us@$LOCAL_AREA_RELEASE_ID/releases/$LOCAL_AREA_RELEASE_ID/release_manifest.json" +python scripts/bundle.py certify-data --country us --data-producer microcosm \ + --manifest-uri "hf://dataset/policyengine/populace-us@/releases/microcosm-us-2024-national//release_manifest.json" \ + --regional-manifest-uri "hf://dataset/policyengine/populace-us@/releases/microcosm-us-2024-local//release_manifest.json" \ + --model-version "" ``` This one command: @@ -61,7 +52,7 @@ This one command: - runs `generate(check=False)`, which re-normalizes `manifest.json` and updates `pyproject.toml` **only if the model pins moved**; - writes the changelog fragment - `changelog.d/certify-us-$NATIONAL_RELEASE_ID.changed.md`. + `changelog.d/certify-us-.changed.md`. ## Step 3 — regenerate TRACE sidecars diff --git a/docs/engineering/runbooks/canonical-spm-development.md b/docs/engineering/runbooks/canonical-spm-development.md index 4e094bc52..3a7f29661 100644 --- a/docs/engineering/runbooks/canonical-spm-development.md +++ b/docs/engineering/runbooks/canonical-spm-development.md @@ -167,11 +167,19 @@ Ordinary `check` passes for the staged draft; this is metadata consistency only. pass. Resolve the actual country/wrapper publication sequence with the coordinator; do not invent future versions to break that dependency. Refresh country and wrapper locks against real registry bytes. -5. Certify the published data release through `scripts/bundle.py certify-data - --country us --data-producer populace --model-version - "$PUBLISHED_COUNTRY_VERSION" --manifest-uri "$PUBLISHED_RELEASE_MANIFEST_URI"`. - The URI must identify the actual immutable producer release. This command - updates the country pin and data metadata from real compatibility evidence. +5. Certify the published national release with the ACS-local release that the + bundle will route regional simulations to. Use immutable producer manifest + URIs for both releases. + + ```bash + python scripts/bundle.py certify-data --country us --data-producer microcosm \ + --model-version "$PUBLISHED_COUNTRY_VERSION" \ + --manifest-uri "$PUBLISHED_RELEASE_MANIFEST_URI" \ + --regional-manifest-uri "$PUBLISHED_REGIONAL_RELEASE_MANIFEST_URI" + ``` + + This command updates the country pin and data metadata from the releases' + compatibility evidence. Regenerate bundle artifacts and TRACE sidecars, inspect full-manifest hash bindings, and run the required exact model/data tests. Staging an SPM hash changes the manifest bytes; old sidecar bindings cannot establish provenance diff --git a/docs/engineering/skills/data-certification.md b/docs/engineering/skills/data-certification.md index 545b1aad4..910c5b1f1 100644 --- a/docs/engineering/skills/data-certification.md +++ b/docs/engineering/skills/data-certification.md @@ -320,7 +320,7 @@ folder (it has `releases.json`), so give each manifest's folder at the commit that published it: ```bash -python scripts/bundle.py certify-data --country us --data-producer populace \ +python scripts/bundle.py certify-data --country us --data-producer microcosm \ --manifest-uri "hf://dataset/policyengine/populace-us@/releases/microcosm-us-2024-national//release_manifest.json" \ --regional-manifest-uri "hf://dataset/policyengine/populace-us@/releases/microcosm-us-2024-local//release_manifest.json" \ --model-version "" @@ -362,7 +362,7 @@ exact target installed, then certify with the reason and the evidence. --limitation "" \ --output regional-input-surface.json -.venv/bin/python scripts/bundle.py certify-data --country us --data-producer populace \ +.venv/bin/python scripts/bundle.py certify-data --country us --data-producer microcosm \ --manifest-uri "hf://dataset/policyengine/populace-us@/releases/microcosm-us-2024-national//release_manifest.json" \ --regional-manifest-uri "hf://dataset/policyengine/populace-us@/releases/microcosm-us-2024-local//release_manifest.json" \ --accept-regional-model-mismatch "" \ diff --git a/docs/microsim.md b/docs/microsim.md index 15b12ba25..18ec3deec 100644 --- a/docs/microsim.md +++ b/docs/microsim.md @@ -128,6 +128,7 @@ Microdata is stored as HDF5 on Hugging Face. `ensure_datasets` downloads, caches ```python datasets = pe.us.ensure_datasets( + datasets=["microcosm_us_2024"], years=[2024, 2026], data_folder="./data", # local cache directory ) @@ -142,20 +143,55 @@ local-authority regions use its local-area release. **Enhanced FRS 2024–25** (`enhanced_frs_2024_25`, policyengine-uk-data 1.58.1) and **Microcosm UK 2023** remain available as named, non-default bundle datasets. -PolicyEngine.py obtains the repository type, immutable revision, and SHA-256 -from the installed release bundle. An existing file in the configured data -directory is reused only after hash verification. - -List datasets already known to the country: +PolicyEngine.py verifies cached source artifacts against the installed bundle's +SHA-256. It checks derived US year files against the year-file format, the +input-renames register and any required legacy SPM declarations. Managed flat +year files also need the source SHA-256 pinned by the bundle. When the bundle +records more than one distinct source SHA-256 for a filename stem, +PolicyEngine.py uses the source SHA-256 to keep the year files separate. + +For either US selector pair, `populace_us_2024` and `microcosm_us_2024` or +`populace_us_2024_acs_local` and `microcosm_us_2024_acs_local`, the two names +select the same artifact when the bundle lists just one of them. If the bundle +records both spellings, each exact key selects its own artifact. +`create_datasets`, `load_datasets` and `ensure_datasets` return dictionaries keyed +by artifact filename stem and year. Request distinct artifacts with the same +stem separately so their result keys stay unique. + +For local paths, the result key and year filename use the full filename stem, +including any `@`. For example, `sample@local.h5` gives `sample@local_2024` +and `sample@local_year_2024.h5`. Use the full key in lookups and rebuild older +year files written under the shortened stem. `create_datasets` raises +`ValueError` for a missing explicit local file before doing any writes, except +when an earlier request can create the file or its symlink target. A current +year file can still be loaded by an absolute or explicit relative source path +or by its source symlink after the source file has been removed. + +Load the default dataset's current year files with `load_datasets`. For a +bundled US dataset, PolicyEngine.py writes year files straight into the data +folder unless the bundle records more than one distinct source SHA-256 for +that filename stem. Each of these flat year files records its source SHA-256. +`load_datasets` refuses one whose recorded hash is missing or differs from the +bundle's pin. `ensure_datasets` regenerates it when given the bundle key or +an exact URI identifying the pinned artifact. It uses the key by default and +keeps the explicit URI's ordered raw-cache updates with `allow_unmanaged=True`. +Validation and table loading use the same year-file snapshot. ```python pe.us.load_datasets() # or pe.uk.load_datasets() ``` +When the bundle pins an artifact with the same filename stem, an unpinned +request uses only its own subdirectory under `.policyengine-us-year-files/`, +keyed by the resolved local path or the URI. A bare Hugging Face URI and its +`@main` spelling use different subdirectories. Use +`ensure_datasets(..., allow_unmanaged=True)` to build a missing or stale +unpinned year file from its source. + ### US local-area dataset -Alongside the certified national default, the bundle registers a US dataset for -finer geographic work: `populace_us_2024_acs_local`. It is a +For finer geographic work, select the bundled US local-area dataset with +`populace_us_2024_acs_local`. It is a Microcosm US 2024 build of roughly **1.6 million households** on an **ACS 2024 multispine**, with each household **PUMA-assigned** to a 119th-Congress congressional district, county, and state, and calibrated to **state @@ -173,7 +209,7 @@ import policyengine as pe sim = pe.us.managed_microsimulation(dataset="populace_us_2024_acs_local") ``` -Or materialize it as a `PolicyEngineUSDataset` for `Simulation`: +Use `ensure_datasets` to materialize it as a `PolicyEngineUSDataset` for `Simulation`. ```python datasets = pe.us.ensure_datasets(datasets=["populace_us_2024_acs_local"], years=[2024]) @@ -198,6 +234,20 @@ ca = Simulation( ) ``` +For a native managed microsimulation, use the region's registered source and +row filter together. + +```python +region = pe.us.model.get_region("state/ca") +ca = pe.us.managed_microsimulation( + dataset=region.dataset_path, + scoping_strategy=region.scoping_strategy, + allow_unmanaged=True, +) +``` + +The same call works with a district such as `congressional_district/CA-01`. + ### UK private data and raw h5 access UK population data uses licensed Family Resources Survey inputs. The default @@ -436,7 +486,12 @@ Settings that conflict are recorded as an error for that year, and raise when the response is calculated. For managed simulations, `sim.policyengine_bundle` records the actual source -package, repository type, revision, verified SHA-256, and local path. +package, repository type, revision, verified SHA-256, and local path. It also +records this provenance when the explicit Hugging Face URI exactly matches a +bundle pin. The model uses a pin-specific cache path with verified source bytes +and any pinned metadata sidecar. US `managed_microsimulation` derives any +registered legacy SPM declarations from the full source, then aligns them to +the entity IDs in the selected cohort and its reform branches. ## Renamed inputs in stored data @@ -486,14 +541,15 @@ under. `create_datasets` stamps each year file, after writing everything else, with the register it was cut under and a year-file format revision (`legacy_inputs.YEAR_FILE_STAMP_H5_DATASET`, UTF-8 JSON -`{"register": {old: new, ...}, "revision": 1}`). `ensure_datasets` reuses a -year file only when its stamp equals this release's exactly and its renames -record lists only renames in the stamped register. Otherwise it logs why and -creates the year files again; `load_datasets` refuses the file with the same -reason, which names the renames the file may lack when its register is the -cause. To decide, both read only the stamp and the record, never the tables -or the source dataset. `legacy_inputs.year_file_stamp_problem(path)` returns -the reason, or `None` for a current year file. +`{"register": {old: new, ...}, "revision": 1}`). The stamp for a managed flat +year file also contains `source_sha256`. `ensure_datasets` checks that the +format revision and register match this release and that the renames record +lists only renames in the stamped register. For managed flat files, it also +checks that the stamp identifies the source pinned by the bundle. When a +check fails, it logs why and creates the year files again. `load_datasets` +refuses the file with the same reason, including any renames the file may +lack. Both decide from file metadata without reading the tables or the +source dataset. A year file is out of date when: @@ -508,6 +564,10 @@ A year file is out of date when: - its register has an entry this release lacks, or maps an old name to another new name. It may store a new name this release's engine does not define, and a run skips any column the engine does not define; +- it is a managed flat year file whose stored source SHA-256 is missing or + differs from the bundle's pin; +- it records a source SHA-256 for a request whose cache path requires a stamp + without a source hash; - it has another format revision, or its stamp or record cannot be read. So any change to `LEGACY_INPUT_RENAMES` makes every year file out of date, diff --git a/docs/release-bundles.md b/docs/release-bundles.md index b4f8199ec..9fc3921d8 100644 --- a/docs/release-bundles.md +++ b/docs/release-bundles.md @@ -189,19 +189,15 @@ It does not rebuild microdata artifacts. Certification runs in this repository: `src/policyengine/data/bundle/manifest.json` carries the certified `data_releases.{country}` entry derived directly from the country's published -data release manifest. The entrypoint is: +data release manifest. For US Microcosm certification, pin the commit that +published each build. Choose listed, non-withdrawn builds for the national +and ACS-local releases in the +[public release index](https://huggingface.co/datasets/policyengine/populace-us/resolve/main/releases.json). ```bash -python scripts/bundle.py certify-data --country us \ - --manifest-uri "hf://dataset/policyengine/populace-us@/releases//release_manifest.json" -``` - -US Microcosm certification uses the Microcosm release manifest directly: - -```bash -python scripts/bundle.py certify-data --country us --data-producer populace \ - --manifest-uri "hf://dataset/policyengine/populace-us@/releases//release_manifest.json" \ - --regional-manifest-uri "hf://dataset/policyengine/populace-us@/releases//release_manifest.json" \ +python scripts/bundle.py certify-data --country us --data-producer microcosm \ + --manifest-uri "hf://dataset/policyengine/populace-us@/releases/microcosm-us-2024-national//release_manifest.json" \ + --regional-manifest-uri "hf://dataset/policyengine/populace-us@/releases/microcosm-us-2024-local//release_manifest.json" \ --model-version "" ``` diff --git a/scripts/bundle.py b/scripts/bundle.py index b05ffa589..0cf097e9d 100644 --- a/scripts/bundle.py +++ b/scripts/bundle.py @@ -198,7 +198,7 @@ def _parser() -> argparse.ArgumentParser: certify.add_argument("--country", required=True, choices=["us", "uk"]) certify.add_argument( "--data-producer", - choices=["legacy", "populace"], + choices=["legacy", "microcosm", "populace"], help="Data-producer strategy. Defaults to the certification script default.", ) certify.add_argument( diff --git a/scripts/certify_data_release.py b/scripts/certify_data_release.py index 341297457..35336ce1c 100644 --- a/scripts/certify_data_release.py +++ b/scripts/certify_data_release.py @@ -47,8 +47,11 @@ def main(argv=None) -> int: parser.add_argument( "--data-producer", default=None, - choices=["legacy", "populace"], - help="Data-producer strategy. Defaults to populace for UK, legacy otherwise.", + choices=["legacy", "microcosm", "populace"], + help=( + "Data-producer strategy. Defaults to populace for UK, legacy otherwise. " + "Use microcosm as an alias for populace." + ), ) parser.add_argument( "--manifest-uri", diff --git a/src/policyengine/provenance/certification.py b/src/policyengine/provenance/certification.py index 72a278903..1f6d5ce35 100644 --- a/src/policyengine/provenance/certification.py +++ b/src/policyengine/provenance/certification.py @@ -76,6 +76,7 @@ fetch_pypi_wheel_metadata, read_build_folder, release_build_id, + resolve_bundled_dataset_key, ) from policyengine.provenance.manifest import ( RELEASE_SCOPED_ARTIFACT_KINDS as RELEASE_SCOPED_ARTIFACT_KINDS, @@ -1770,7 +1771,7 @@ def certification_strategy( country: str, data_producer: Optional[str] = None ) -> DataProducerCertificationStrategy: producer = data_producer or ("populace" if country == "uk" else "legacy") - if producer == "populace": + if producer in ("microcosm", "populace"): return MicrocosmDataProducerCertificationStrategy() if producer == "legacy": return LegacyDataProducerCertificationStrategy() @@ -1902,12 +1903,12 @@ def certify_data_release( f"Removed the dataset_overlays.{country} entries this release now " f"certifies: {', '.join(superseded)}.", ] - # A name the previous release certified, and neither the new release nor - # an overlay keeps, stops resolving. Say so, so that it can be re-added. + # Check the names against the bundle that readers will see, including aliases. + available = data_release["datasets"].keys() | overlays.keys() dropped = sorted( - set(previous_release.get("datasets") or {}) - - set(data_release["datasets"]) - - set(overlays) + name + for name in previous_release.get("datasets") or {} + if resolve_bundled_dataset_key(country, name, available) not in available ) if dropped: warnings = [ diff --git a/src/policyengine/provenance/dataset_materialization.py b/src/policyengine/provenance/dataset_materialization.py index 28e8f60b9..317963a5e 100644 --- a/src/policyengine/provenance/dataset_materialization.py +++ b/src/policyengine/provenance/dataset_materialization.py @@ -2,11 +2,15 @@ from __future__ import annotations +import hashlib +import json import os +import shutil import tempfile -from dataclasses import dataclass +from contextlib import contextmanager +from dataclasses import dataclass, replace from pathlib import Path, PurePosixPath, PureWindowsPath -from typing import Literal, Optional +from typing import Iterator, Literal, Optional import requests from pydantic import BaseModel, ConfigDict @@ -26,6 +30,7 @@ DEFAULT_DATA_DIR = Path("./data") DOWNLOAD_TIMEOUT_SECONDS = 60 +_VERIFIED_CACHE_DIRECTORY = ".policyengine-bundle-files" class DatasetMaterializationError(ValueError): @@ -74,6 +79,9 @@ class _BundleDatasetSpec: sha256: str destination: Path metadata_sha256: Optional[str] = None + cache_seed: Optional[Path] = None + publish_raw_to: Optional[Path] = None + publish_metadata_to: Optional[Path] = None @property def source_uri(self) -> str: @@ -112,6 +120,14 @@ def _bundle_destination(data_dir: Path, path: str) -> Path: raise DatasetMaterializationError( f"Bundle artifact path {path!r} must be relative to its repository." ) + verified_root = data_dir / _VERIFIED_CACHE_DIRECTORY + if ( + relative.parts[0].casefold() == _VERIFIED_CACHE_DIRECTORY + or destination.parent.resolve().is_relative_to(verified_root.resolve()) + ): + raise DatasetMaterializationError( + f"Bundle artifact path {path!r} uses a reserved cache directory." + ) return destination @@ -123,7 +139,9 @@ def _resolve_bundle_dataset( manifest: Optional[CountryReleaseManifest] = None, ) -> _BundleDatasetSpec: country_manifest = manifest or get_release_manifest(country_id) - dataset_name = dataset or country_manifest.default_dataset + dataset_name = country_manifest.bundled_dataset_key( + dataset or country_manifest.default_dataset + ) reference = country_manifest.datasets.get(dataset_name) if reference is None: raise DatasetMaterializationError( @@ -152,24 +170,53 @@ def _resolve_bundle_dataset( ) +def _explicit_bundle_raw_destination( + data_dir: Path, manifest: CountryReleaseManifest, key: str +) -> Optional[Path]: + """Return the old explicit URI destination if compatible with the bundle.""" + reference = manifest.datasets[key] + destination = _bundle_destination(data_dir, reference.path) + basename_path = data_dir / destination.name + for other in manifest.datasets.values(): + other_path = PurePosixPath(other.path) + if len(other_path.parts) != 1: + continue + if other_path.name == basename_path.name and other.sha256 != reference.sha256: + return None + if ( + other.metadata_sha256 is not None + and f"{other_path.name}.metadata.json" == basename_path.name + and other.metadata_sha256 != reference.sha256 + ): + return None + return basename_path + + def materialize_dataset( country_id: str, dataset: Optional[str] = None, *, allow_unmanaged: bool = False, data_dir: Path = DEFAULT_DATA_DIR, + publish_legacy_basename: bool = False, ) -> DatasetSource: - """Select a dataset source and return the local file used for calculation.""" + """Select a local dataset, verifying the bytes of pinned bundle artifacts. + + Year-file batches can also publish an explicit URI's compatibility copy + so later local inputs can read it in request order. + """ manifest = get_release_manifest(country_id) if dataset is None or dataset == manifest.default_dataset_uri: + if dataset is not None: + manifest.bundled_dataset_key_for_uri(dataset) return _use_bundle_dataset( country_id, manifest.default_dataset, data_dir=data_dir, manifest=manifest, ) - if dataset in manifest.datasets: + if manifest.bundled_dataset_key(dataset) in manifest.datasets: return _use_bundle_dataset( country_id, dataset, @@ -183,6 +230,16 @@ def materialize_dataset( allow_unmanaged=allow_unmanaged, ) if source_uri.startswith("hf://"): + key = manifest.bundled_dataset_key_for_uri(source_uri) + if key is not None: + return _use_bundle_dataset( + country_id, + key, + data_dir=data_dir, + manifest=manifest, + explicit_uri=True, + publish_legacy_basename=publish_legacy_basename, + ) return _download_hugging_face_dataset(source_uri, data_dir=data_dir) if "://" in source_uri: raise DatasetMaterializationError( @@ -191,19 +248,58 @@ def materialize_dataset( return _use_local_dataset(source_uri) +def _runtime_bundle_spec( + country_id: str, + dataset: str, + *, + data_dir: Path, + manifest: CountryReleaseManifest, + explicit_uri: bool = False, + publish_legacy_basename: bool = False, +) -> _BundleDatasetSpec: + spec = _resolve_bundle_dataset( + country_id, dataset, data_dir=data_dir, manifest=manifest + ) + # Distinct artifacts, including pins in different installed bundle versions, + # must never write to a path another verified source handed to a model. + pin = hashlib.sha256( + json.dumps( + (spec.source_uri, spec.repo_type, spec.sha256, spec.metadata_sha256) + ).encode() + ).hexdigest() + legacy_raw_path: Optional[Path] = spec.destination + if explicit_uri: + legacy_raw_path = ( + _explicit_bundle_raw_destination(data_dir, manifest, spec.dataset) + if publish_legacy_basename + else None + ) + return replace( + spec, + destination=data_dir / _VERIFIED_CACHE_DIRECTORY / pin / spec.destination.name, + cache_seed=spec.destination, + publish_raw_to=legacy_raw_path, + publish_metadata_to=spec.metadata_destination if not explicit_uri else None, + ) + + def _use_bundle_dataset( country_id: str, dataset: str, *, data_dir: Path, manifest: CountryReleaseManifest, + explicit_uri: bool = False, + publish_legacy_basename: bool = False, ) -> DatasetSource: bundle_dataset = _reuse_or_download_bundle_files( - _resolve_bundle_dataset( + _runtime_bundle_spec( country_id, dataset, data_dir=data_dir, manifest=manifest, + explicit_uri=explicit_uri, + publish_legacy_basename=publish_legacy_basename, ) ) return DatasetSource( @@ -233,23 +329,19 @@ def _download_hugging_face_dataset( repo_id = f"{parts[0]}/{parts[1]}" repository_path = parts[2] destination = data_dir / Path(repository_path).name - destination.parent.mkdir(parents=True, exist_ok=True) + if destination.name.casefold() == _VERIFIED_CACHE_DIRECTORY: + raise DatasetMaterializationError( + f"Explicit dataset URI {dataset_uri!r} uses a reserved cache directory." + ) for repo_type in ("model", "dataset"): - file_descriptor, temp_name = tempfile.mkstemp( - prefix=".policyengine-download-", - suffix=destination.suffix or ".download", - dir=destination.parent, - ) - os.close(file_descriptor) - temporary_path = Path(temp_name) url = https_dataset_uri( repo_id, repository_path, revision, repo_type=repo_type, ) - try: + with _temporary_cache_file(destination) as temporary_path: with requests.get( url, headers=hugging_face_auth_headers(), @@ -276,8 +368,6 @@ def _download_hugging_face_dataset( output.write(chunk) os.replace(temporary_path, destination) return DatasetSource(source_uri=dataset_uri, path=str(destination)) - finally: - temporary_path.unlink(missing_ok=True) raise DatasetMaterializationError( f"Could not download explicit dataset {dataset_uri!r}." @@ -288,6 +378,53 @@ def _use_local_dataset(dataset_path: str) -> DatasetSource: return DatasetSource(source_uri=dataset_path, path=dataset_path) +@contextmanager +def _temporary_cache_file(destination: Path) -> Iterator[Path]: + destination.parent.mkdir(parents=True, exist_ok=True) + file_descriptor, temp_name = tempfile.mkstemp( + prefix=".policyengine-download-", + suffix=destination.suffix or ".download", + dir=destination.parent, + ) + os.close(file_descriptor) + temporary_path = Path(temp_name) + try: + yield temporary_path + finally: + temporary_path.unlink(missing_ok=True) + + +def _has_expected_bytes(path: Path, expected_sha256: str) -> bool: + try: + return path.is_file() and sha256_file(path) == expected_sha256 + except FileNotFoundError: + return False + + +def _copy_seed(seed: Optional[Path], staged: Path, expected_sha256: str) -> bool: + if seed is None: + return False + try: + if not seed.is_file(): + return False + shutil.copyfile(seed, staged) + except FileNotFoundError: + return False + # Hash the copy so an intervening legacy cache replacement cannot supply + # different bytes after validation. + return _has_expected_bytes(staged, expected_sha256) + + +def _publish_legacy_copy( + verified: Path, destination: Optional[Path], expected_sha256: str +) -> None: + if destination is None or _has_expected_bytes(destination, expected_sha256): + return + with _temporary_cache_file(destination) as temporary_path: + shutil.copyfile(verified, temporary_path) + os.replace(temporary_path, destination) + + def _reuse_or_download_bundle_files( dataset: _BundleDatasetSpec, ) -> MaterializedDataset: @@ -297,6 +434,8 @@ def _reuse_or_download_bundle_files( dataset.destination, dataset.sha256, f"{dataset.country_id.upper()} dataset {dataset.dataset!r}", + dataset.cache_seed, + dataset.publish_raw_to, ) ] if dataset.metadata_sha256 is not None: @@ -306,28 +445,31 @@ def _reuse_or_download_bundle_files( dataset.metadata_destination, dataset.metadata_sha256, f"metadata for {dataset.dataset!r}", + ( + Path(f"{dataset.cache_seed}.metadata.json") + if dataset.cache_seed is not None + else None + ), + dataset.publish_metadata_to, ) ) - for repository_path, destination, expected_sha256, description in files: - if destination.is_file() and sha256_file(destination) == expected_sha256: + for repository_path, destination, expected_sha256, description, seed, _ in files: + if ( + dataset.cache_seed is None or not destination.is_symlink() + ) and _has_expected_bytes(destination, expected_sha256): continue - destination.parent.mkdir(parents=True, exist_ok=True) - file_descriptor, temp_name = tempfile.mkstemp( - prefix=".policyengine-download-", - suffix=destination.suffix or ".download", - dir=destination.parent, - ) - os.close(file_descriptor) - temporary_path = Path(temp_name) url = https_dataset_uri( dataset.repo_id, repository_path, dataset.revision, repo_type=dataset.repo_type, ) - try: + with _temporary_cache_file(destination) as temporary_path: + if _copy_seed(seed, temporary_path, expected_sha256): + os.replace(temporary_path, destination) + continue with requests.get( url, headers=hugging_face_auth_headers(), @@ -357,8 +499,9 @@ def _reuse_or_download_bundle_files( f"expected {expected_sha256}." ) os.replace(temporary_path, destination) - finally: - temporary_path.unlink(missing_ok=True) + + for _, verified, expected_sha256, _, _, legacy_path in files: + _publish_legacy_copy(verified, legacy_path, expected_sha256) return MaterializedDataset( data_package_name=dataset.data_package_name, diff --git a/src/policyengine/provenance/manifest.py b/src/policyengine/provenance/manifest.py index 9b3aa3827..c3bbbb6cf 100644 --- a/src/policyengine/provenance/manifest.py +++ b/src/policyengine/provenance/manifest.py @@ -2,6 +2,7 @@ import json import os import re +from collections.abc import Collection from functools import lru_cache from importlib.resources import files from pathlib import Path @@ -27,6 +28,14 @@ PYPI_REQUEST_TIMEOUT_SECONDS = 30 # Producer paths for these artifacts are relative to the release directory. RELEASE_SCOPED_ARTIFACT_KINDS = frozenset({"diagnostics", "evidence"}) +# Public selectors and their counterpart keys in earlier and newer bundles. +# This index is for lookup only. The manifest records the actual artifact key. +US_MICROCOSM_DATASET_ALIASES = { + "microcosm_us_2024": "populace_us_2024", + "populace_us_2024": "microcosm_us_2024", + "microcosm_us_2024_acs_local": "populace_us_2024_acs_local", + "populace_us_2024_acs_local": "microcosm_us_2024_acs_local", +} #: Microcosm publishes each build once, in its own folder #: ``releases///``, and never changes it afterwards; a root @@ -460,6 +469,54 @@ class CountryReleaseManifest(BaseModel): source_sha256: Optional[str] = Field(default=None, exclude=True) """Byte sha256 of the bundled manifest before Pydantic normalization.""" + def bundled_dataset_key(self, dataset: str) -> str: + """Resolve a public selector to the key recorded in this bundle.""" + return resolve_bundled_dataset_key(self.country_id, dataset, self.datasets) + + def _dataset_uri(self, reference: ArtifactPathReference) -> str: + return build_hf_uri( + repo_id=reference.repo_id or self.data_package.repo_id, + path_in_repo=reference.path, + revision=reference.revision or _artifact_revision(self.data_package), + ) + + def bundled_dataset_key_for_uri(self, uri: str) -> Optional[str]: + """Return the bundle key for an exact URI with an unambiguous pin.""" + if "://" not in uri: + return None + matches = { + key: reference + for key, reference in self.datasets.items() + if self._dataset_uri(reference) == uri + } + default_key = self.bundled_dataset_key(self.default_dataset) + if uri == self.default_dataset_uri and default_key in self.datasets: + matches[default_key] = self.datasets[default_key] + if not matches: + return None + + pins = { + ( + reference.sha256, + reference.repo_type or self.data_package.repo_type, + reference.metadata_sha256, + reference.data_package_name or self.data_package.name, + ) + for reference in matches.values() + } + country = self.country_id.upper() + if len(pins) > 1: + raise ValueError( + f"{country} dataset URI {uri!r} matches conflicting bundle artifacts. " + f"Select one by its bundle key: {', '.join(sorted(matches))}." + ) + key = default_key if default_key in matches else next(iter(matches)) + if not matches[key].sha256: + raise ValueError( + f"{country} dataset URI {uri!r} is missing a bundle SHA-256." + ) + return key + @property def default_dataset_uri(self) -> str: if ( @@ -467,6 +524,9 @@ def default_dataset_uri(self) -> str: and self.certified_data_artifact.dataset == self.default_dataset ): return self.certified_data_artifact.uri + reference = self.datasets.get(self.bundled_dataset_key(self.default_dataset)) + if reference is not None: + return self._dataset_uri(reference) return resolve_dataset_reference(self.country_id, self.default_dataset) @@ -1325,23 +1385,37 @@ def _certify_available_data_release( ) +def resolve_bundled_dataset_key( + country_id: str, dataset: str, keys: Collection[str] +) -> str: + """Prefer an exact key and fall back to its US alias when available.""" + if country_id == "us" and dataset not in keys: + alias = US_MICROCOSM_DATASET_ALIASES.get(dataset) + if alias is not None and alias in keys: + return alias + return dataset + + +def _is_explicit_local_path(dataset: str) -> bool: + return Path(dataset).expanduser().is_absolute() or dataset.startswith( + ("./", "../", f".{os.sep}", f"..{os.sep}") + ) + + def resolve_dataset_reference(country_id: str, dataset: str) -> str: if "://" in dataset: return dataset manifest = get_release_manifest(country_id) - path_reference = manifest.datasets.get(dataset) + path_reference = manifest.datasets.get(manifest.bundled_dataset_key(dataset)) if path_reference is not None: - return build_hf_uri( - repo_id=path_reference.repo_id or manifest.data_package.repo_id, - path_in_repo=path_reference.path, - revision=path_reference.revision - or _artifact_revision(manifest.data_package), - ) + return manifest._dataset_uri(path_reference) local_path = Path(dataset).expanduser() if local_path.exists(): return str(local_path) + if _is_explicit_local_path(dataset): + raise ValueError(f"{country_id.upper()} dataset file not found: {local_path}") data_release_manifest = get_data_release_manifest(country_id) artifact = data_release_manifest.artifacts.get(dataset) @@ -1366,7 +1440,7 @@ def resolve_managed_dataset_reference( release manifest. Callers can: - omit `dataset` to use the certified default dataset for the bundle - - pass a logical dataset name present in the bundled/data-release manifests + - pass a logical dataset name in the bundle or its supported alias Direct URLs or raw Hugging Face references are treated as unmanaged unless `allow_unmanaged=True` is set explicitly. @@ -1376,7 +1450,7 @@ def resolve_managed_dataset_reference( if dataset is None: return manifest.default_dataset_uri - if dataset in manifest.datasets: + if manifest.bundled_dataset_key(dataset) in manifest.datasets: return resolve_dataset_reference(country_id, dataset) local_path = Path(dataset).expanduser() diff --git a/src/policyengine/tax_benefit_models/us/datasets.py b/src/policyengine/tax_benefit_models/us/datasets.py index 320a538a9..35f06556a 100644 --- a/src/policyengine/tax_benefit_models/us/datasets.py +++ b/src/policyengine/tax_benefit_models/us/datasets.py @@ -2,10 +2,13 @@ import importlib.util import json import logging +import os +import shutil import warnings from importlib import metadata as importlib_metadata from pathlib import Path -from typing import Any, Optional +from tempfile import TemporaryDirectory +from typing import Any, NamedTuple, Optional import h5py import pandas as pd @@ -15,12 +18,16 @@ from policyengine.core import Dataset, YearData from policyengine.provenance.dataset_materialization import ( MaterializedDataset, + _bundle_destination, + _runtime_bundle_spec, materialize_dataset, ) from policyengine.provenance.manifest import ( + _is_explicit_local_path, dataset_logical_name, get_release_manifest, resolve_dataset_reference, + resolve_managed_dataset_reference, ) from policyengine.tax_benefit_models.common.model_version import ( build_runtime_dataset_provenance, @@ -410,11 +417,13 @@ def create_datasets( ) -> dict[str, PolicyEngineUSDataset]: """Create PolicyEngineUSDataset instances from logical dataset names or URLs. - Each year file is written to ``{data_folder}/{dataset_stem}_year_{year}.h5`` - and stamped last with the register of renamed stored inputs it was cut - under and the year-file format revision (see - ``legacy_inputs.YEAR_FILE_STAMP_H5_DATASET``), which ``ensure_datasets`` - and ``load_datasets`` check. + Write each ``{dataset_stem}_year_{year}.h5`` file under the data folder. + A stem with multiple distinct bundle pins uses separate subdirectories. + Unpinned sources also use a subdirectory when the stem has a bundle pin. + Stamp each file last with the register of renamed stored inputs and the + year-file format revision, and record the source SHA-256 for managed flat + files (see ``legacy_inputs.YEAR_FILE_STAMP_H5_DATASET``). + Both ``ensure_datasets`` and ``load_datasets`` check the stamp. Args: datasets: List of logical dataset names or HuggingFace dataset URLs @@ -422,34 +431,50 @@ def create_datasets( data_folder: Directory to save the dataset files Returns: - Dictionary mapping dataset keys (e.g., "populace_us_2024") to PolicyEngineUSDataset objects + Datasets keyed by artifact filename stem and year. """ from policyengine_us import Microsimulation from policyengine.tax_benefit_models.us.spm import resolve_spm_selection dataset_requests: list[Optional[str]] = datasets or [None] + locations = _resolve_year_file_locations( + datasets or [get_release_manifest("us").default_dataset], + data_folder, + allow_unmanaged=allow_unmanaged, + years_to_create=years, + ) result = {} - for dataset in dataset_requests: + for dataset, location in zip(dataset_requests, locations, strict=True): + dataset_stem = location.stem + digest = location.source_sha256 + source_uri = location.source_uri + if "://" not in source_uri and not Path(source_uri).is_file(): + raise FileNotFoundError(f"US dataset file not found: {source_uri}") source = materialize_dataset( "us", dataset, allow_unmanaged=allow_unmanaged, data_dir=Path(data_folder), + publish_legacy_basename=allow_unmanaged, ) - dataset_stem = source.name + if digest is not None and ( + source.bundle_dataset is None or source.bundle_dataset.sha256 != digest + ): + raise ValueError( + f"US dataset {source.source_uri!r} was not materialized " + "with its bundle SHA-256." + ) sim = Microsimulation(dataset=source.path, spm=resolve_spm_selection()) - # The register the mapping below uses, stamped into each year file. - stamp = year_file_stamp() + flat_source_sha256 = digest if location.folder == data_folder else None + stamp = year_file_stamp(source_sha256=flat_source_sha256) # Map stored inputs the engine has since renamed before extracting, # so each year's file stores the live input rather than dropping it. legacy_input_renames = apply_legacy_input_renames_to_microsimulation(sim) # BACKWARD COMPATIBILITY (#597, #598): a legacy certified source # carries no SPM declarations, so derive them while its stored # evidence is still available; year files keep model inputs only. - legacy_spm = _legacy_spm_declarations( - sim, source.bundle_dataset, Path(data_folder) - ) + legacy_spm = _legacy_spm_declarations(sim, digest, Path(data_folder)) for year in years: # Get all input variables from the simulation @@ -598,11 +623,12 @@ def create_datasets( mode="json" ) + filepath = location.filepath(year) us_dataset = PolicyEngineUSDataset( id=f"{dataset_stem}_year_{year}", name=f"{dataset_stem}-year-{year}", description=f"US Dataset for year {year} based on {dataset_stem}", - filepath=f"{data_folder}/{dataset_stem}_year_{year}.h5", + filepath=filepath, year=int(year), metadata=metadata, data=USYearData( @@ -616,10 +642,20 @@ def create_datasets( tax_unit=MicroDataFrame(tax_unit_df, weights="tax_unit_weight"), ), ) - us_dataset.save() - # Stamp last. ``save()`` truncates the file first, so a year file - # whose write stopped part-way has no stamp and is cut again. - write_year_file_stamp(us_dataset.filepath, stamp) + destination = Path(filepath) + destination.parent.mkdir(parents=True, exist_ok=True) + with TemporaryDirectory( + prefix=".policyengine-year-", dir=destination.parent + ) as staging_dir: + staged_path = str(Path(staging_dir) / destination.name) + us_dataset.model_copy(update={"filepath": staged_path}).save() + write_year_file_stamp(staged_path, stamp) + problem = _cached_year_file_problem(staged_path, location, data_folder) + if problem is not None: + raise ValueError( + f"US year file {filepath} failed validation because {problem}." + ) + os.replace(staged_path, destination) dataset_key = f"{dataset_stem}_{year}" result[dataset_key] = us_dataset @@ -629,16 +665,15 @@ def create_datasets( def _legacy_spm_declarations( sim: Any, - bundle_dataset: Optional[MaterializedDataset], + verified_sha256: Optional[str], data_folder: Path, ) -> Optional[LegacySPMDeclarations]: """Derive the SPM declarations a legacy certified source lacks. - BACKWARD COMPATIBILITY (#597, #598). Only a bundle dataset whose verified - SHA-256 is registered in ``legacy_spm.registry`` gets any; see - ``legacy_spm``. + BACKWARD COMPATIBILITY (#597, #598). Derive declarations only when the + verified bundle pin is registered in ``legacy_spm.registry``. """ - source = legacy_spm_source(bundle_dataset.sha256 if bundle_dataset else None) + source = legacy_spm_source(verified_sha256) if source is None: return None declarations, _ = derive_from_stored_tables( @@ -648,36 +683,190 @@ def _legacy_spm_declarations( def _managed_source_sha256(dataset: Optional[str]) -> Optional[str]: - """Return the certified SHA-256 of a managed bundle dataset reference. - - A managed dataset may be named by its manifest name or by the URI that - name resolves to (the form the region registry's dataset paths take). - Any other reference is unmanaged and has no certified hash. - """ + """Return the bundle pin for a year-file source, when it has one.""" manifest = get_release_manifest("us") - if dataset is None or dataset == manifest.default_dataset_uri: - name: Optional[str] = manifest.default_dataset - elif dataset in manifest.datasets: - name = dataset + if dataset is not None and "://" in dataset: + key = manifest.bundled_dataset_key_for_uri(dataset) else: - name = next( - ( - candidate - for candidate in manifest.datasets - if resolve_dataset_reference("us", candidate) == dataset - ), - None, - ) - reference = manifest.datasets.get(name) if name is not None else None + key = manifest.bundled_dataset_key(dataset or manifest.default_dataset) + reference = manifest.datasets.get(key) if key is not None else None return reference.sha256 if reference is not None else None -def _expected_legacy_spm_profile(dataset: Optional[str]) -> Optional[LegacySPMProfile]: - """Return the legacy SPM profile a dataset reference's year files need.""" - source = legacy_spm_source(_managed_source_sha256(dataset)) +def _expected_legacy_spm_profile( + source_sha256: Optional[str], +) -> Optional[LegacySPMProfile]: + """Return the legacy SPM profile for the planned source pin.""" + source = legacy_spm_source(source_sha256) return expected_profile(source) if source is not None else None +class _YearFileLocation(NamedTuple): + stem: str + folder: str + source_sha256: Optional[str] + source_uri: str + + def filepath(self, year: int) -> str: + return f"{self.folder}/{self.stem}_year_{year}.h5" + + +def _cache_file_address(path: Path) -> Path: + return Path(os.path.realpath(path.parent)) / path.name + + +def _local_identity(path: Path, replacements: set[Path]) -> Path: + """Resolve local links up to a file an earlier request will replace.""" + path = _cache_file_address(path) + seen = set() + while path not in replacements and path not in seen: + seen.add(path) + try: + target = path.readlink() + except OSError: + break + path = _cache_file_address(path.parent / target) + return path + + +def _resolve_year_file_locations( + datasets: list[str], + data_folder: str, + *, + allow_unmanaged: Optional[bool] = None, + years_to_create: Optional[list[int]] = None, +) -> list[_YearFileLocation]: + """Plan year-file locations without materializing any source artifacts.""" + manifest = get_release_manifest("us") + bundled_digests: dict[str, set[str]] = {} + for reference in manifest.datasets.values(): + if reference.sha256 is not None: + bundled_digests.setdefault(Path(reference.path).stem, set()).add( + reference.sha256 + ) + + locations = [] + selected: dict[str, str] = {} + planned_files: set[Path] = set() + local_replacements = planned_files if allow_unmanaged else set() + default_uri = manifest.default_dataset_uri + for dataset in datasets: + if dataset == default_uri: + # An explicit URI must identify one unambiguous artifact, even + # when it is also the managed default. + manifest.bundled_dataset_key_for_uri(dataset) + selector = manifest.default_dataset + else: + selector = dataset + bundle_key = manifest.bundled_dataset_key(selector) + reference = manifest.datasets.get(bundle_key) + if reference is not None and not reference.sha256: + raise ValueError(f"US dataset {dataset!r} is missing a bundle SHA-256.") + local_path = Path(selector).expanduser() + explicit_local = ( + allow_unmanaged is not False + and "://" not in selector + and reference is None + and ( + _is_explicit_local_path(selector) + or local_path.is_symlink() + or _cache_file_address(local_path) in planned_files + ) + ) + if explicit_local: + # Recognize local paths even when a derived cache has outlived + # its raw file or an earlier request will write the input. + uri = str(local_path) + elif allow_unmanaged is None: + uri = resolve_dataset_reference("us", selector) + else: + uri = resolve_managed_dataset_reference( + "us", selector, allow_unmanaged=allow_unmanaged + ) + is_uri = "://" in uri + uri_key = ( + manifest.bundled_dataset_key_for_uri(uri) + if is_uri and reference is None + else None + ) + digest = _managed_source_sha256(uri_key or bundle_key) + if is_uri: + stem = dataset_logical_name(uri) + identity = digest or uri + else: + source_path = Path(uri) + stem = source_path.stem + local_identity = _local_identity(source_path, local_replacements) + if ( + explicit_local + and allow_unmanaged + and local_identity not in planned_files + and not source_path.is_file() + ): + raise ValueError(f"US dataset file not found: {source_path}") + identity = str(local_identity) + if selected.setdefault(stem, identity) != identity: + raise ValueError( + f"Distinct US datasets share the year-file result stem {stem!r}. " + "Request them separately." + ) + folder = data_folder + pin_count = len(bundled_digests.get(stem, ())) + if pin_count > 1 or (pin_count == 1 and digest is None): + # Protect the flat managed cache from same-stem unpinned writes. + directory = hashlib.sha256(identity.encode()).hexdigest() + folder = f"{data_folder}/.policyengine-us-year-files/{directory}" + location = _YearFileLocation(stem, folder, digest, uri) + locations.append(location) + if allow_unmanaged and uri.startswith("hf://"): + key = bundle_key if reference is not None else uri_key + if key is None: + raw_path = Path(data_folder) / Path(uri.rsplit("@", 1)[0]).name + planned_files.add(_cache_file_address(raw_path)) + else: + raw_spec = _runtime_bundle_spec( + "us", + key, + data_dir=Path(data_folder), + manifest=manifest, + explicit_uri=reference is None, + publish_legacy_basename=True, + ) + for candidate in (raw_spec.destination, raw_spec.publish_raw_to): + # A managed symlink may be replaced if its target is + # scheduled for an earlier write in this batch. + if candidate is not None and ( + candidate == raw_spec.destination + or not candidate.is_symlink() + or _local_identity(candidate, planned_files) in planned_files + or not candidate.is_file() + or sha256_file(candidate) != raw_spec.sha256 + ): + planned_files.add(_cache_file_address(candidate)) + if allow_unmanaged is not False and years_to_create: + planned_files.update( + _cache_file_address(Path(location.filepath(year))) + for year in years_to_create + ) + return locations + + +def _cached_year_file_problem( + filepath: str | Path, location: _YearFileLocation, data_folder: str +) -> Optional[str]: + # Flat paths do not identify the source. In particular, when a split stem + # converges they can expose an old cache whose source pin is unknown. + flat_pin = location.source_sha256 if location.folder == data_folder else None + stamp_problem = year_file_stamp_problem( + filepath, + expected_source_sha256=flat_pin, + require_unbound_source=flat_pin is None, + ) + return stamp_problem or year_file_problem( + filepath, _expected_legacy_spm_profile(location.source_sha256) + ) + + def load_datasets( datasets: Optional[list[str]] = None, years: list[int] = [2024, 2025, 2026, 2027, 2028], @@ -691,7 +880,9 @@ def load_datasets( register entry was added may have lost that input, as files that policyengine.py 6.1.1 and earlier cut from the certified default lost the WIC take-up draw. The error says why, and names the renames the file may - lack when its register is the reason. + lack when its register is the reason. A managed flat year file must also + record the source SHA-256 pinned by the bundle. An unpinned request + refuses a file with a source hash in its stamp. Args: datasets: List of HuggingFace dataset paths (used to derive file names) @@ -699,41 +890,45 @@ def load_datasets( data_folder: Directory containing the dataset files Returns: - Dictionary mapping dataset keys (e.g., "populace_us_2024") to PolicyEngineUSDataset objects + Datasets keyed by artifact filename stem and year. """ datasets = datasets or [get_release_manifest("us").default_dataset] result = {} - for dataset in datasets: - resolved_dataset = resolve_dataset_reference("us", dataset) - dataset_stem = dataset_logical_name(resolved_dataset) + locations = _resolve_year_file_locations(datasets, data_folder) + for location in locations: + dataset_stem = location.stem for year in years: - filepath = f"{data_folder}/{dataset_stem}_year_{year}.h5" - if Path(filepath).exists(): - problem = year_file_stamp_problem(filepath) + filepath = location.filepath(year) + with TemporaryDirectory() as directory: + snapshot = Path(directory) / Path(filepath).name + try: + # Published year files are replaced atomically. Give the + # HDF5 and pandas readers a private name for the same inode. + source = Path(filepath).resolve(strict=True) + try: + os.link(source, snapshot) + except OSError: + # The system temporary directory can be on another + # filesystem, and some mounts do not allow hard links. + shutil.copyfile(source, snapshot) + except FileNotFoundError as error: + raise FileNotFoundError( + f"US year file {filepath} does not exist. " + "Create it with ensure_datasets() or create_datasets()." + ) from error + problem = _cached_year_file_problem(snapshot, location, data_folder) if problem is not None: raise ValueError( f"US year file {filepath} is out of date: {problem}. " - "Regenerate it with ensure_datasets() or " - "create_datasets()." + "Regenerate it with ensure_datasets() or create_datasets()." ) - # BACKWARD COMPATIBILITY (#597, #598): a legacy source's year - # file must carry exactly the declarations this release derives. - legacy_problem = year_file_problem( - filepath, _expected_legacy_spm_profile(dataset) + us_dataset = PolicyEngineUSDataset( + name=f"{dataset_stem}-year-{year}", + description=f"US Dataset for year {year} based on {dataset_stem}", + filepath=str(snapshot), + year=year, ) - if legacy_problem is not None: - raise ValueError( - f"US year file {filepath} is out of date: " - f"{legacy_problem}. Regenerate it with ensure_datasets() " - "or create_datasets()." - ) - us_dataset = PolicyEngineUSDataset( - name=f"{dataset_stem}-year-{year}", - description=f"US Dataset for year {year} based on {dataset_stem}", - filepath=filepath, - year=year, - ) - us_dataset.load() + us_dataset.filepath = filepath dataset_key = f"{dataset_stem}_{year}" result[dataset_key] = us_dataset @@ -1315,7 +1510,19 @@ def load_managed_long_term_datasets( ) dataset_uri = source.source_uri path = Path(source.path) - metadata, metadata_path = _load_dataset_metadata(path, require_metadata) + metadata_source = path + if ( + path_reference.metadata_sha256 is None + and not _metadata_path_for_h5(path).exists() + ): + # Older bundles allowed a locally supplied sidecar alongside + # the now separate, legacy dataset cache. + metadata_source = _bundle_destination( + Path(data_folder), path_reference.path + ) + metadata, metadata_path = _load_dataset_metadata( + metadata_source, require_metadata + ) _validate_loaded_long_term_metadata( metadata=metadata, metadata_path=metadata_path, @@ -1372,13 +1579,16 @@ def ensure_datasets( ) -> dict[str, PolicyEngineUSDataset]: """Ensure datasets exist, loading if available or creating if not. - Existing year files are reused only when ``create_datasets`` stamped them - with this release's register of renamed stored inputs and year-file format - revision (see ``legacy_inputs.year_file_stamp_problem``). Only each file's - stamp and renames record are read to decide, never its tables or the - source dataset. If any year file is missing or out of date, every - year file is created again from the source dataset, and each out-of-date - file is logged with the reason. + Reuse year files that carry this release's register of renamed stored + inputs, year-file format revision and any required legacy SPM declarations. + Managed flat year files must also record the bundle's source SHA-256. + Exact pinned URIs rebuild through the bundle key by default. With opt-in, + a rebuild follows the explicit URI's raw-cache publication order. + With opt-in, rebuilding an unpinned source with a managed stem writes to + a source-specific directory. + Inspect file metadata to make this decision. If any year file is missing + or out of date, recreate all requested year files from their sources and + log a reason for each out-of-date file. Args: datasets: List of HuggingFace dataset paths @@ -1388,21 +1598,23 @@ def ensure_datasets( Returns: Dictionary mapping dataset keys to PolicyEngineUSDataset objects """ - datasets = datasets or [get_release_manifest("us").default_dataset] + manifest = get_release_manifest("us") + datasets = datasets or [manifest.default_dataset] # Check that every year file exists and is current. A year file cut # under another register of renamed stored inputs may have lost one, so # it is created again rather than reused. all_current = True - for dataset in datasets: - resolved_dataset = resolve_dataset_reference("us", dataset) - dataset_stem = dataset_logical_name(resolved_dataset) + locations = _resolve_year_file_locations( + datasets, data_folder, years_to_create=years + ) + for location in locations: for year in years: - filepath = Path(f"{data_folder}/{dataset_stem}_year_{year}.h5") + filepath = Path(location.filepath(year)) if not filepath.exists(): all_current = False continue - problem = year_file_stamp_problem(filepath) + problem = _cached_year_file_problem(filepath, location, data_folder) if problem is not None: all_current = False logger.warning( @@ -1411,26 +1623,21 @@ def ensure_datasets( filepath, problem, ) - continue - # BACKWARD COMPATIBILITY (#597, #598): see ``legacy_spm.record``. - legacy_problem = year_file_problem( - filepath, _expected_legacy_spm_profile(dataset) - ) - if legacy_problem is not None: - all_current = False - logger.warning( - "US year file %s is out of date: %s. Creating the year " - "files again.", - filepath, - legacy_problem, - ) if all_current: return load_datasets(datasets=datasets, years=years, data_folder=data_folder) - else: - return create_datasets( - datasets=datasets, - years=years, - data_folder=data_folder, - allow_unmanaged=allow_unmanaged, - ) + + rebuild_requests = datasets + if not allow_unmanaged: + rebuild_requests = [ + dataset + if manifest.bundled_dataset_key(dataset) in manifest.datasets + else manifest.bundled_dataset_key_for_uri(location.source_uri) or dataset + for dataset, location in zip(datasets, locations, strict=True) + ] + return create_datasets( + datasets=rebuild_requests, + years=years, + data_folder=data_folder, + allow_unmanaged=allow_unmanaged, + ) diff --git a/src/policyengine/tax_benefit_models/us/legacy_inputs.py b/src/policyengine/tax_benefit_models/us/legacy_inputs.py index f108ccd54..f2404a55b 100644 --- a/src/policyengine/tax_benefit_models/us/legacy_inputs.py +++ b/src/policyengine/tax_benefit_models/us/legacy_inputs.py @@ -24,6 +24,7 @@ import inspect import json +import re from collections.abc import Iterable, Iterator, Mapping from pathlib import Path from typing import Any @@ -77,10 +78,11 @@ #: H5 dataset stamping a ``create_datasets`` year file, as UTF-8 JSON #: ``{"register": {legacy: live, ...}, "revision": int}``: the whole register #: the file was cut under and its year-file format revision (see -#: :func:`year_file_stamp`). ``create_datasets`` writes it after the tables and -#: the renames record, so a year file whose write stopped part-way has none. +#: :func:`year_file_stamp`). Managed flat files also store ``source_sha256``. +#: ``create_datasets`` writes the stamp after the tables and the renames record, +#: so a year file whose write stopped part-way has none. #: ``ensure_datasets`` cuts a year file again, and ``load_datasets`` refuses -#: it, unless its stamp equals this release's (see +#: it, unless its stamp matches the current requirements (see #: :func:`year_file_stamp_problem`). ``PolicyEngineUSDataset.save()`` neither #: writes nor keeps it, so saving a year file again drops the stamp. YEAR_FILE_STAMP_H5_DATASET = "policyengine_year_file_stamp" @@ -144,17 +146,20 @@ def write_renames_record(path: str | Path, record: Mapping[str, str]) -> None: _write_json_dataset(path, RENAMES_H5_DATASET, dict(record)) -def year_file_stamp() -> dict[str, Any]: +def year_file_stamp(*, source_sha256: str | None = None) -> dict[str, Any]: """Return the stamp for a year file cut now. It holds the whole register, not only the entries an engine needs mapped, so checking a stamp never imports policyengine-us. The register is read when this is called. """ - return { + stamp: dict[str, Any] = { "register": dict(sorted(LEGACY_INPUT_RENAMES.items())), "revision": YEAR_FILE_STAMP_REVISION, } + if source_sha256 is not None: + stamp["source_sha256"] = source_sha256 + return stamp def read_year_file_stamp(path: str | Path) -> Any | None: @@ -178,14 +183,20 @@ def write_year_file_stamp(path: str | Path, stamp: Mapping[str, Any]) -> None: _write_json_dataset(path, YEAR_FILE_STAMP_H5_DATASET, dict(stamp)) -def year_file_stamp_problem(path: str | Path) -> str | None: +def year_file_stamp_problem( + path: str | Path, + *, + expected_source_sha256: str | None = None, + require_unbound_source: bool = False, +) -> str | None: """Return why a ``create_datasets`` year file is out of date, or ``None``. - A year file is current only when both of these hold: + A year file is current only when these hold: - - its stamp equals :func:`year_file_stamp`: the same format revision and - the same register; - - it stores the renames record, listing only renames in that register. + - its stamp has the current format revision and register; + - it stores the renames record, listing only renames in that register; + - when an expected source SHA-256 is supplied, its stamp identifies that source. + - when an unbound stamp is required, it contains no source SHA-256. The register must match exactly. A file cut under a register that lacks an entry may have lost that entry's input, as year files that @@ -208,8 +219,7 @@ def year_file_stamp_problem(path: str | Path) -> str | None: """ import h5py - current = year_file_stamp() - register = current["register"] + register = year_file_stamp()["register"] try: with h5py.File(path, "r") as file: stamp = _read_json_dataset(file, YEAR_FILE_STAMP_H5_DATASET) @@ -247,7 +257,7 @@ def year_file_stamp_problem(path: str | Path) -> str | None: # ``True``, which equals 1. if not ( isinstance(stamp, dict) - and set(stamp) == {"register", "revision"} + and set(stamp) - {"source_sha256"} == {"register", "revision"} and type(revision) is int and _is_str_map(stamp["register"]) ): @@ -268,7 +278,22 @@ def year_file_stamp_problem(path: str | Path) -> str | None: "its record lists renames outside the register it was stamped " f"with: {_describe(outside)}" ) - if stamp == current: + if stamped == register: + if "source_sha256" in stamp: + if require_unbound_source: + return "it records a source SHA-256 where this cache path expects none" + source_sha256 = stamp["source_sha256"] + if not isinstance(source_sha256, str) or not re.fullmatch( + r"[0-9a-f]{64}", source_sha256 + ): + return "its source SHA-256 is malformed" + if ( + expected_source_sha256 is not None + and source_sha256 != expected_source_sha256 + ): + return "its source SHA-256 differs from the bundle's pin" + elif expected_source_sha256 is not None: + return "it has no source SHA-256 for the bundle's pinned artifact" return None missing = { legacy: live for legacy, live in register.items() if stamped.get(legacy) != live diff --git a/src/policyengine/tax_benefit_models/us/model.py b/src/policyengine/tax_benefit_models/us/model.py index bdda192dd..94a5d42d8 100644 --- a/src/policyengine/tax_benefit_models/us/model.py +++ b/src/policyengine/tax_benefit_models/us/model.py @@ -1,5 +1,4 @@ import datetime -from pathlib import Path from typing import TYPE_CHECKING, Optional import pandas as pd @@ -8,6 +7,7 @@ from policyengine.core import TaxBenefitModel from policyengine.core.scoping_strategy import RowFilterStrategy from policyengine.provenance.dataset_materialization import ( + DEFAULT_DATA_DIR, materialize_dataset, ) from policyengine.tax_benefit_models.common import MicrosimulationModelVersion @@ -590,23 +590,23 @@ def managed_microsimulation( "us", dataset, allow_unmanaged=allow_unmanaged, + data_dir=DEFAULT_DATA_DIR, ) - # BACKWARD COMPATIBILITY (#597, #598): a legacy certified source carries - # no SPM declarations, so derive them from its stored evidence and set - # them on the simulation and its branches (see ``legacy_spm``). - legacy_spm_record = None + if scoping_strategy is not None and type(scoping_strategy) is not RowFilterStrategy: + raise ValueError("Managed scoping supports only RowFilterStrategy.") + + microsim = Microsimulation(dataset=source.path, spm=selection, **kwargs) + # BACKWARD COMPATIBILITY (#597, #598): derive declarations from the full + # verified source, where the certified independence list matches the data. + # set_declarations aligns the results to the final simulation and branches. legacy_source = legacy_spm_source( source.bundle_dataset.sha256 if source.bundle_dataset else None ) - if scoping_strategy is not None: - if type(scoping_strategy) is not RowFilterStrategy: - raise ValueError("Managed scoping supports only RowFilterStrategy.") - if legacy_source is not None: - raise ValueError( - "Managed scoping does not support legacy SPM declarations." - ) - - microsim = Microsimulation(dataset=source.path, spm=selection, **kwargs) + legacy_spm = None + if legacy_source is not None: + legacy_spm = derive_from_stored_tables( + legacy_source, microsim.dataset, data_dir=DEFAULT_DATA_DIR + ) scoping_record = None if scoping_strategy is not None: import gc @@ -631,10 +631,9 @@ def managed_microsimulation( dataset=scoped_dataset, spm=selection, **scoped_kwargs ) legacy_input_renames = apply_legacy_input_renames_to_microsimulation(microsim) - if legacy_source is not None: - declarations, years = derive_from_stored_tables( - legacy_source, microsim.dataset, data_dir=Path(source.path).parent - ) + legacy_spm_record = None + if legacy_spm is not None: + declarations, years = legacy_spm mode = prepare_microsimulation(microsim) set_declarations(microsim, declarations, years) legacy_spm_record = declarations.record.model_copy( diff --git a/tests/test_certify_data_release.py b/tests/test_certify_data_release.py index b3bc472b7..6042383f5 100644 --- a/tests/test_certify_data_release.py +++ b/tests/test_certify_data_release.py @@ -1,5 +1,6 @@ """Tests for direct data-release certification.""" +import hashlib import importlib.util import json import sys @@ -9,6 +10,7 @@ import pytest +from policyengine.provenance import manifest as provenance_manifest from policyengine.provenance.certification import ( US_STATE_CODES, CertificationError, @@ -630,8 +632,9 @@ def test__given_unknown_regional_role__then_rejects_it(self): class TestCertifyDataRelease: + @pytest.mark.parametrize("data_producer", ["microcosm", "populace", None]) def test__given_fetched_microcosm_manifest__then_updates_bundle_manifest( - self, tmp_path + self, tmp_path, data_producer ): bundle_path = tmp_path / "manifest.json" bundle_path.write_text(json.dumps(_bundle_source_payload()) + "\n") @@ -667,7 +670,7 @@ def test__given_fetched_microcosm_manifest__then_updates_bundle_manifest( ): result = certify_data_release( country="uk", - data_producer="populace", + data_producer=data_producer, manifest_uri=UK_MANIFEST_URI, model_version="2.89.2", bundle_path=bundle_path, @@ -682,14 +685,21 @@ def test__given_fetched_microcosm_manifest__then_updates_bundle_manifest( assert release["source_manifest_uri"] == UK_MANIFEST_URI assert written["packages"]["policyengine-uk"]["version"] == "2.89.2" assert result.data_producer == "populace" + assert " data-producer: populace" in result.summary().splitlines() assert result.dataset_count == 3 assert result.build_id == UK_TAG assert result.bundle_path == bundle_path + @pytest.mark.parametrize("data_producer", ["populace", "microcosm"]) def test__given_us_local_area_manifest__then_certifies_shared_regional_dataset( - self, tmp_path + self, tmp_path, monkeypatch, capsys, data_producer ): - bundle_path = tmp_path / "manifest.json" + bundle_script = _load_bundle_script(monkeypatch) + import certify_data_release as certifier + + monkeypatch.setattr(certifier, "REPO_ROOT", tmp_path) + bundle_path = tmp_path / "src/policyengine/data/bundle/manifest.json" + bundle_path.parent.mkdir(parents=True) bundle_path.write_text(json.dumps(_bundle_source_payload()) + "\n") primary_response = MagicMock() primary_response.status_code = 200 @@ -730,17 +740,46 @@ def test__given_us_local_area_manifest__then_certifies_shared_regional_dataset( return_value="9.9.9", ), ): - result = certify_data_release( - country="us", - data_producer="populace", - manifest_uri=MANIFEST_URI, - regional_manifest_uri=US_LOCAL_AREA_MANIFEST_URI, - model_version="1.723.0", - bundle_path=bundle_path, + assert ( + bundle_script.main( + [ + "certify-data", + "--country", + "us", + "--data-producer", + data_producer, + "--manifest-uri", + MANIFEST_URI, + "--regional-manifest-uri", + US_LOCAL_AREA_MANIFEST_URI, + "--model-version", + "1.723.0", + "--no-generate", + ] + ) + == 0 ) + fragment = tmp_path / "changelog.d" / f"certify-us-{TAG}.changed.md" + manifest_sha256 = hashlib.sha256(primary_response.content).hexdigest() + assert capsys.readouterr().out == ( + f"certified us: populace_us_2024 (5 datasets, build {TAG})\n" + f" manifest: {MANIFEST_URI}\n" + f" manifest sha256: {manifest_sha256}\n" + " model: policyengine-us==1.723.0\n" + " data-producer: populace\n" + f" wrote: {bundle_path}\n" + f"changelog: {fragment}\n" + ) + assert fragment.read_text() == ( + f"Certify the US populace data release `{TAG}` (populace_us_2024, " + "policyengine-us 1.723.0) into the PolicyEngine bundle manifest.\n" + ) written = json.loads(bundle_path.read_text()) release = written["data_releases"]["us"] + assert release["data_producer"] == "populace" + assert release["default_dataset"] == "populace_us_2024" + assert release["certified_data_artifact"]["dataset"] == "populace_us_2024" assert release["source_manifest_uri"] == MANIFEST_URI assert release["regional_source_manifest_uri"] == US_LOCAL_AREA_MANIFEST_URI assert release["region_datasets"] == { @@ -755,7 +794,96 @@ def test__given_us_local_area_manifest__then_certifies_shared_regional_dataset( release["datasets"]["populace_us_2024_acs_local"]["repo_type"] == "dataset" ) assert release["regional_release_kind"] == "local_area" - assert result.dataset_count == 5 + + @pytest.mark.parametrize("keep_local_as_overlay", [False, True]) + @pytest.mark.parametrize( + ("old_prefix", "new_prefix"), + [("populace", "microcosm"), ("microcosm", "populace")], + ) + def test_recertification_warns_only_about_us_selectors_that_stop_resolving( + self, tmp_path, monkeypatch, keep_local_as_overlay, old_prefix, new_prefix + ): + old_national = f"{old_prefix}_us_2024" + old_local = f"{old_national}_acs_local" + new_national = f"{new_prefix}_us_2024" + new_local = f"{new_national}_acs_local" + unrelated = "retired_us_dataset" + bundle_path = tmp_path / "manifest.json" + bundle_path.write_text(json.dumps(_bundle_source_payload())) + + monkeypatch.setattr( + "policyengine.provenance.certification.head_release_file", + lambda *args, **kwargs: True, + ) + monkeypatch.setattr( + "policyengine.provenance.certification.fetch_pypi_wheel_metadata", + lambda *args: {"sha256": "d" * 64, "url": "https://example.test/wheel"}, + ) + + def certify(national_name, local_name=None): + primary = _microcosm_manifest_payload_without_regions() + primary["default_datasets"]["national"] = national_name + national_artifacts = primary["artifacts"] + national_artifacts[national_name] = national_artifacts.pop( + "populace_us_2024" + ) + responses = [_response(primary)] + if local_name is not None: + regional = _local_area_release_manifest_payload() + regional_artifacts = regional["artifacts"] + regional_artifacts[local_name] = regional_artifacts.pop( + "populace_us_2024_acs_local" + ) + responses.append(_response(regional)) + with patch( + "policyengine.provenance.certification.requests.get", + side_effect=_without_releases_record(responses), + ): + return certify_data_release( + country="us", + data_producer="microcosm", + manifest_uri=MANIFEST_URI, + regional_manifest_uri=( + US_LOCAL_AREA_MANIFEST_URI if local_name is not None else None + ), + drop_regional_release=local_name is None, + model_version="1.723.0", + bundle_path=bundle_path, + check_artifacts=False, + ) + + certify(old_national, old_local) + previous = json.loads(bundle_path.read_text()) + previous_datasets = previous["data_releases"]["us"]["datasets"] + previous_datasets[unrelated] = { + **previous_datasets[old_national], + "path": f"{unrelated}.h5", + } + if keep_local_as_overlay: + previous["dataset_overlays"] = { + "us": {new_local: previous_datasets[old_local]} + } + bundle_path.write_text(json.dumps(previous)) + + result = certify(new_national, None if keep_local_as_overlay else new_local) + + updated = json.loads(bundle_path.read_text()) + manifest = CountryReleaseManifest.model_validate( + _apply_dataset_overlays("us", updated["data_releases"]["us"], updated) + ) + monkeypatch.setattr( + provenance_manifest, "get_release_manifest", lambda _: manifest + ) + for old, new in [(old_national, new_national), (old_local, new_local)]: + assert old not in manifest.datasets + assert manifest.bundled_dataset_key(old) == new + assert provenance_manifest.resolve_managed_dataset_reference("us", old) == ( + provenance_manifest.resolve_managed_dataset_reference("us", new) + ) + assert [w for w in result.warnings if "no longer resolve" in w] == [ + f"These US datasets no longer resolve by name: {unrelated}. " + "Re-add any that must stay loadable under dataset_overlays.us." + ] def test__given_us_without_data_producer__then_legacy_update_is_explicitly_unsupported( self, tmp_path @@ -771,8 +899,9 @@ def test__given_us_without_data_producer__then_legacy_update_is_explicitly_unsup bundle_path=bundle_path, ) + @pytest.mark.parametrize("producer", ["populace", "microcosm"]) def test__given_bundle_wrapper_regional_args__then_forwards_to_certifier( - self, monkeypatch + self, monkeypatch, producer ): bundle_script = _load_bundle_script(monkeypatch) captured: dict[str, list[str]] = {} @@ -791,7 +920,7 @@ def fake_main(argv: list[str]) -> int: "--country", "us", "--data-producer", - "populace", + producer, "--manifest-uri", MANIFEST_URI, "--regional-manifest-uri", @@ -814,7 +943,7 @@ def fake_main(argv: list[str]) -> int: "--manifest-uri", MANIFEST_URI, "--data-producer", - "populace", + producer, "--model-version", "1.723.0", "--regional-manifest-uri", @@ -1634,8 +1763,9 @@ def fake_main(argv): == "regional-audit.json" ) + @pytest.mark.parametrize("data_producer", ["microcosm", "populace"]) def test__given_bundle_wrapper_empty_reason__then_certifier_refuses_it( - self, monkeypatch, tmp_path, capsys + self, monkeypatch, tmp_path, capsys, data_producer ): bundle_script = _load_bundle_script(monkeypatch) spec = importlib.util.spec_from_file_location( @@ -1673,6 +1803,8 @@ def certify_temporary_bundle(**kwargs): "certify-data", "--country", "uk", + "--data-producer", + data_producer, "--manifest-uri", UK_NATIONAL_URI, "--model-version", @@ -1691,6 +1823,7 @@ def certify_temporary_bundle(**kwargs): assert isinstance(error.value.__context__, CertificationError) assert "needs a reason" in str(error.value.__context__) assert capsys.readouterr().out == "" + assert captured["data_producer"] == data_producer assert captured["regional_model_mismatch_reason"] == "" assert bundle_path.read_bytes() == original_bundle diff --git a/tests/test_dataset_materialization.py b/tests/test_dataset_materialization.py index f7dfa04fa..a5bf50525 100644 --- a/tests/test_dataset_materialization.py +++ b/tests/test_dataset_materialization.py @@ -1,17 +1,21 @@ import hashlib +from pathlib import Path from unittest.mock import patch import pytest import policyengine.provenance.dataset_materialization as dataset_materialization +import policyengine.provenance.manifest as release_manifest from policyengine.provenance.dataset_materialization import ( DatasetMaterializationError, _resolve_bundle_dataset, _reuse_or_download_bundle_files, + materialize_dataset, ) from policyengine.provenance.manifest import ( CountryReleaseManifest, https_dataset_uri, + resolve_dataset_reference, ) @@ -230,6 +234,262 @@ def test_hash_failure_preserves_existing_destination(tmp_path): assert destination.read_bytes() == b"old" +@pytest.mark.parametrize("valid_download", [False, True], ids=["mismatch", "match"]) +def test_explicit_bundle_uri_checks_pin_before_updating_raw_cache( + monkeypatch, tmp_path, valid_download +): + manifest = _manifest() + key = "populace_uk_2023" + reference = manifest.datasets[key] + verified = b"certified" + reference.sha256 = _sha256(verified) + for module in (release_manifest, dataset_materialization): + monkeypatch.setattr(module, "get_release_manifest", lambda country: manifest) + uri = resolve_dataset_reference("uk", key) + destination = tmp_path / reference.path + original = b"old" + destination.write_bytes(original) + payload = verified if valid_download else b"wrong" + session = _Session(_Response(payload)) + monkeypatch.setattr(dataset_materialization.requests, "get", session.get) + + if valid_download: + source = materialize_dataset( + "uk", + uri, + allow_unmanaged=True, + data_dir=tmp_path, + publish_legacy_basename=True, + ) + assert source.bundle_dataset is not None + assert source.bundle_dataset.sha256 == reference.sha256 + assert source.bundle_dataset.path == Path(source.path) + assert source.bundle_dataset.path != destination + assert source.bundle_dataset.path.read_bytes() == verified + assert source.bundle_dataset.source_uri == uri + else: + with pytest.raises(DatasetMaterializationError, match="sha256"): + materialize_dataset( + "uk", + uri, + allow_unmanaged=True, + data_dir=tmp_path, + publish_legacy_basename=True, + ) + + assert destination.read_bytes() == (verified if valid_download else original) + assert len(session.calls) == 1 + assert session.calls[0][0].startswith("https://huggingface.co/datasets/") + + +@pytest.mark.parametrize("valid_metadata", [False, True], ids=["mismatch", "match"]) +def test_explicit_bundle_uri_verifies_its_metadata_sidecar( + monkeypatch, tmp_path, valid_metadata +): + manifest = _manifest() + key = "populace_uk_2023" + payload = b"certified" + metadata = b'{"year": 2023}' + reference = manifest.datasets[key] + reference.sha256 = _sha256(payload) + reference.metadata_sha256 = _sha256(metadata) + for module in (release_manifest, dataset_materialization): + monkeypatch.setattr(module, "get_release_manifest", lambda country: manifest) + uri = resolve_dataset_reference("uk", key) + session = _Session( + _Response(payload), + _Response(metadata if valid_metadata else b"wrong"), + ) + monkeypatch.setattr(dataset_materialization.requests, "get", session.get) + + if valid_metadata: + source = materialize_dataset("uk", uri, allow_unmanaged=True, data_dir=tmp_path) + assert source.bundle_dataset.metadata_path == Path( + f"{source.path}.metadata.json" + ) + assert source.bundle_dataset.metadata_path.read_bytes() == metadata + else: + with pytest.raises(DatasetMaterializationError, match="metadata.*sha256"): + materialize_dataset("uk", uri, allow_unmanaged=True, data_dir=tmp_path) + + assert session.calls[1][0].endswith(f"/{reference.path}.metadata.json") + assert not (tmp_path / reference.path).exists() + + +@pytest.mark.parametrize("use_default", [False, True], ids=["overlay", "default"]) +@pytest.mark.parametrize( + "field", ["sha256", "repo_type", "metadata_sha256", "data_package_name"] +) +def test_explicit_uri_refuses_conflicting_bundle_artifacts( + monkeypatch, tmp_path, field, use_default +): + manifest = _manifest() + key = manifest.default_dataset if use_default else "populace_uk_2023" + reference = manifest.datasets[key] + manifest.datasets["duplicate"] = reference.model_copy( + update={ + field: { + "repo_type": "dataset" if reference.repo_type != "dataset" else "model", + "data_package_name": "other-data", + }.get(field, "e" * 64) + } + ) + for module in (release_manifest, dataset_materialization): + monkeypatch.setattr(module, "get_release_manifest", lambda country: manifest) + session = _Session() + monkeypatch.setattr(dataset_materialization.requests, "get", session.get) + + with pytest.raises(ValueError, match="matches conflicting bundle artifacts"): + materialize_dataset( + "uk", + resolve_dataset_reference("uk", key), + data_dir=tmp_path, + allow_unmanaged=not use_default, + ) + + assert session.calls == [] + assert not list(tmp_path.iterdir()) + + +def test_same_basename_bundle_uris_preserve_each_pins_cache(tmp_path, monkeypatch): + payloads = [b"top level", b"first release", b"second release"] + manifest = _manifest_with_hash(_sha256(payloads[0])) + top = manifest.datasets[manifest.default_dataset] + keys = ["first", "second"] + for key, payload in zip(keys, payloads[1:], strict=True): + manifest.datasets[key] = top.model_copy( + update={"path": f"releases/{key}/{top.path}", "sha256": _sha256(payload)} + ) + for module in (release_manifest, dataset_materialization): + monkeypatch.setattr(module, "get_release_manifest", lambda country: manifest) + session = _Session(*(_Response(payload) for payload in payloads)) + monkeypatch.setattr(dataset_materialization.requests, "get", session.get) + + top_level = materialize_dataset("uk", data_dir=tmp_path) + first, second = [ + materialize_dataset( + "uk", + resolve_dataset_reference("uk", key), + allow_unmanaged=True, + data_dir=tmp_path, + ) + for key in keys + ] + + assert (tmp_path / top.path).read_bytes() == payloads[0] + assert len({top_level.path, first.path, second.path}) == 3 + for source, payload in zip((top_level, first, second), payloads, strict=True): + assert Path(source.path).read_bytes() == payload + assert source.bundle_dataset.sha256 == _sha256(payload) + + +@pytest.mark.parametrize("collision", ["raw", "sidecar"]) +def test_legacy_basename_publication_preserves_another_bundled_artifact( + tmp_path, monkeypatch, collision +): + top_payload, nested_payload = b"top level", b"nested release" + manifest = _manifest_with_hash(_sha256(top_payload)) + top = manifest.datasets[manifest.default_dataset] + basename = top.path + if collision == "sidecar": + basename += ".metadata.json" + top.metadata_sha256 = _sha256(top_payload) + legacy = tmp_path / basename + legacy.write_bytes(top_payload) + manifest.datasets["nested"] = top.model_copy( + update={ + "path": f"releases/nested/{basename}", + "sha256": _sha256(nested_payload), + "metadata_sha256": None, + } + ) + for module in (release_manifest, dataset_materialization): + monkeypatch.setattr(module, "get_release_manifest", lambda country: manifest) + session = _Session(_Response(nested_payload)) + monkeypatch.setattr(dataset_materialization.requests, "get", session.get) + + nested = materialize_dataset( + "uk", + resolve_dataset_reference("uk", "nested"), + allow_unmanaged=True, + data_dir=tmp_path, + publish_legacy_basename=True, + ) + + assert legacy.read_bytes() == top_payload + assert Path(nested.path).read_bytes() == nested_payload + + +def test_runtime_pins_survive_managed_cache_replacement(tmp_path, monkeypatch): + first_payload, second_payload = b"first release", b"second release" + manifest = _manifest_with_hash(_sha256(first_payload)) + reference = manifest.datasets[manifest.default_dataset] + for module in (release_manifest, dataset_materialization): + monkeypatch.setattr(module, "get_release_manifest", lambda country: manifest) + session = _Session(_Response(first_payload), _Response(second_payload)) + monkeypatch.setattr(dataset_materialization.requests, "get", session.get) + + first = materialize_dataset("uk", data_dir=tmp_path) + reference.sha256 = _sha256(second_payload) + second = materialize_dataset("uk", data_dir=tmp_path) + + assert (tmp_path / reference.path).read_bytes() == second_payload + assert Path(first.path).read_bytes() == first_payload + assert Path(second.path).read_bytes() == second_payload + + +def test_runtime_does_not_reuse_a_symlink_as_the_verified_cache_path( + tmp_path, monkeypatch +): + payload = b"verified" + manifest = _manifest_with_hash(_sha256(payload)) + reference = manifest.datasets[manifest.default_dataset] + legacy = tmp_path / reference.path + legacy.write_bytes(payload) + monkeypatch.setattr( + dataset_materialization, "get_release_manifest", lambda _: manifest + ) + session = _Session() + monkeypatch.setattr(dataset_materialization.requests, "get", session.get) + verified_path = Path(materialize_dataset("uk", data_dir=tmp_path).path) + target = tmp_path / "linked.h5" + target.write_bytes(payload) + verified_path.unlink() + verified_path.symlink_to(target) + + source = materialize_dataset("uk", data_dir=tmp_path) + target.write_bytes(b"changed") + + assert Path(source.path).read_bytes() == payload + assert not Path(source.path).is_symlink() + assert session.calls == [] + + +def test_legacy_directory_symlink_cannot_replace_a_verified_bundle_file( + tmp_path, monkeypatch +): + first_payload, nested_payload = b"verified", b"another artifact" + manifest = _manifest_with_hash(_sha256(first_payload)) + top = manifest.datasets[manifest.default_dataset] + manifest.datasets["nested"] = top.model_copy( + update={"path": f"releases/{top.path}", "sha256": _sha256(nested_payload)} + ) + monkeypatch.setattr( + dataset_materialization, "get_release_manifest", lambda _: manifest + ) + session = _Session(_Response(first_payload), _Response(nested_payload)) + monkeypatch.setattr(dataset_materialization.requests, "get", session.get) + + verified = Path(materialize_dataset("uk", data_dir=tmp_path).path) + (tmp_path / "releases").symlink_to(verified.parent, target_is_directory=True) + + with pytest.raises(DatasetMaterializationError, match="reserved cache directory"): + materialize_dataset("uk", "nested", data_dir=tmp_path) + + assert verified.read_bytes() == first_payload + assert len(session.calls) == 1 + + def test_download_passes_hugging_face_token(monkeypatch, tmp_path): monkeypatch.setenv("HUGGING_FACE_TOKEN", "secret-token") payload = b"certified" diff --git a/tests/test_dataset_runtime.py b/tests/test_dataset_runtime.py index 44083c06d..8834793b0 100644 --- a/tests/test_dataset_runtime.py +++ b/tests/test_dataset_runtime.py @@ -70,6 +70,7 @@ def test_us_create_datasets_passes_verified_bundle_source_to_country_package( "populace_us_2024", allow_unmanaged=False, data_dir=Path("./data"), + publish_legacy_basename=False, ) microsimulation.assert_called_once_with( dataset="/tmp/populace_us_2024.h5", spm=resolve_spm_selection() diff --git a/tests/test_dataset_source.py b/tests/test_dataset_source.py index 589325657..450ac4ff7 100644 --- a/tests/test_dataset_source.py +++ b/tests/test_dataset_source.py @@ -4,6 +4,7 @@ import pytest import policyengine.provenance.dataset_materialization as dataset_source +import policyengine.provenance.manifest as manifest from policyengine.provenance.dataset_materialization import ( DatasetMaterializationError, DatasetSource, @@ -138,3 +139,21 @@ def test_explicit_local_path_uses_local_strategy(tmp_path): path=str(local_path), ) assert DatasetSource.model_validate_json(result.model_dump_json()) == result + + +@pytest.mark.parametrize("relative_path", ["./missing.h5", "../missing.h5"]) +def test_missing_explicit_relative_path_never_uses_catalog( + monkeypatch, tmp_path, relative_path +): + work = tmp_path / "work" + work.mkdir() + monkeypatch.chdir(work) + + def unexpected_catalog(*args, **kwargs): + pytest.fail("Explicit local paths bypass catalog lookup") + + monkeypatch.setattr(manifest, "get_data_release_manifest", unexpected_catalog) + with pytest.raises(ValueError, match=r"US dataset file not found: .*missing\.h5"): + materialize_dataset( + "us", relative_path, allow_unmanaged=True, data_dir=tmp_path + ) diff --git a/tests/test_microcosm_compatibility.py b/tests/test_microcosm_compatibility.py index 89f96a7ec..4ead51a7e 100644 --- a/tests/test_microcosm_compatibility.py +++ b/tests/test_microcosm_compatibility.py @@ -9,10 +9,24 @@ import numpy as np import pytest +from policyengine.provenance import dataset_materialization, manifest from policyengine.provenance.certification import ( MicrocosmDataProducerCertificationStrategy, certification_strategy, ) +from policyengine.provenance.dataset_materialization import ( + MaterializedDataset, + materialize_dataset, +) +from policyengine.provenance.manifest import ( + get_release_manifest, + resolve_dataset_reference, + resolve_managed_dataset_reference, +) +from policyengine.tax_benefit_models.common.model_version import ( + build_runtime_dataset_provenance, +) +from policyengine.utils.hashing import sha256_file @pytest.mark.parametrize( @@ -75,7 +89,13 @@ def test_previous_public_names_resolve_to_current_objects( @pytest.mark.parametrize( "country,data_producer", - [("uk", None), ("uk", "populace"), ("us", "populace")], + [ + ("uk", None), + ("uk", "populace"), + ("us", "populace"), + ("uk", "microcosm"), + ("us", "microcosm"), + ], ) def test_current_certification_strategy_preserves_the_published_producer( country, data_producer @@ -86,6 +106,110 @@ def test_current_certification_strategy_preserves_the_published_producer( assert strategy.data_producer == "populace" +@pytest.mark.parametrize( + "current_name,legacy_name", + [ + ("microcosm_us_2024", "populace_us_2024"), + ("microcosm_us_2024_acs_local", "populace_us_2024_acs_local"), + ], +) +def test_us_dataset_alias_preserves_bundle_provenance( + monkeypatch, tmp_path, current_name, legacy_name +): + def verified_file(spec): + return MaterializedDataset( + data_package_name=spec.data_package_name, + repo_type=spec.repo_type, + revision=spec.revision, + source_uri=spec.source_uri, + sha256=spec.sha256, + path=spec.destination, + ) + + monkeypatch.setattr( + dataset_materialization, "_reuse_or_download_bundle_files", verified_file + ) + + manifest = get_release_manifest("us") + bundle_key = manifest.bundled_dataset_key(current_name) + reference = manifest.datasets[bundle_key] + source = materialize_dataset("us", current_name, data_dir=tmp_path) + existing = materialize_dataset("us", legacy_name, data_dir=tmp_path) + + assert source == existing + assert resolve_dataset_reference("us", current_name) == existing.source_uri + assert resolve_managed_dataset_reference("us", current_name) == existing.source_uri + assert source.bundle_dataset.sha256 == reference.sha256 + provenance = build_runtime_dataset_provenance( + source.source_uri, source.path, source.bundle_dataset + ) + assert provenance["runtime_dataset"] == bundle_key + assert provenance["runtime_dataset_sha256"] == reference.sha256 + if manifest.default_dataset == bundle_key: + assert materialize_dataset("us", data_dir=tmp_path) == source + + +def test_previous_us_selector_resolves_when_bundle_uses_current_key(): + manifest = get_release_manifest("us") + legacy = "populace_us_2024" + current = "microcosm_us_2024" + updated = manifest.model_copy( + update={ + "default_dataset": current, + "datasets": { + current: manifest.datasets[manifest.bundled_dataset_key(legacy)] + }, + } + ) + + assert updated.bundled_dataset_key(legacy) == current + assert updated.bundled_dataset_key(current) == current + + +@pytest.mark.parametrize("suffix", ["us_2024", "us_2024_acs_local"]) +def test_exact_us_selectors_resolve_to_their_own_artifacts( + monkeypatch, tmp_path, suffix +): + bundled = get_release_manifest("us") + original = bundled.datasets[bundled.bundled_dataset_key(f"microcosm_{suffix}")] + references = {} + for spelling in ("populace", "microcosm"): + path = tmp_path / f"{spelling}.h5" + path.write_bytes(spelling.encode()) + references[f"{spelling}_{suffix}"] = original.model_copy( + update={ + "path": path.name, + "sha256": sha256_file(path), + "metadata_sha256": None, + } + ) + bundle = bundled.model_copy( + update={ + "datasets": references, + "default_dataset": f"populace_{suffix}", + "certified_data_artifact": None, + } + ) + for module in (manifest, dataset_materialization): + monkeypatch.setattr(module, "get_release_manifest", lambda country: bundle) + + def unexpected_download(*args, **kwargs): + pytest.fail("Each source artifact is already in the local cache") + + monkeypatch.setattr(dataset_materialization.requests, "get", unexpected_download) + for selector, reference in references.items(): + source = materialize_dataset("us", selector, data_dir=tmp_path) + artifact = source.bundle_dataset + assert artifact is not None + assert artifact.path.name == reference.path + assert artifact.path.read_bytes() == (tmp_path / reference.path).read_bytes() + assert artifact.sha256 == reference.sha256 + expected_uri = f"hf://{reference.repo_id}/{reference.path}@{reference.revision}" + assert source.source_uri == expected_uri + assert resolve_dataset_reference("us", selector) == expected_uri + assert resolve_managed_dataset_reference("us", selector) == expected_uri + + @pytest.mark.parametrize( "current_path,legacy_path,expected_path", [ diff --git a/tests/test_us_legacy_inputs_integration.py b/tests/test_us_legacy_inputs_integration.py index 23a445123..3d118719d 100644 --- a/tests/test_us_legacy_inputs_integration.py +++ b/tests/test_us_legacy_inputs_integration.py @@ -13,6 +13,7 @@ from __future__ import annotations +from pathlib import Path from unittest.mock import patch import h5py @@ -796,37 +797,57 @@ def recording_stamp(path, value): ) paths = [dataset.filepath for dataset in created.values()] + staged_paths = [path for action, path in events if action == "save"] assert events == [ - ("save", paths[0]), - ("stamp", paths[0]), - ("save", paths[1]), - ("stamp", paths[1]), + ("save", staged_paths[0]), + ("stamp", staged_paths[0]), + ("save", staged_paths[1]), + ("stamp", staged_paths[1]), ] - for path in paths: + for path, staged_path in zip(paths, staged_paths, strict=True): + assert staged_path != path + assert not Path(staged_path).exists() assert year_file_stamp_problem(path) is None -def test_a_year_file_whose_stamp_was_never_written_is_out_of_date(tmp_path): +@pytest.mark.parametrize( + ("warm_cache", "interrupted"), + [(False, True), (True, True), (True, False)], + ids=["cold-interrupted", "warm-interrupted", "warm-missing-stamp"], +) +def test_year_file_stamp_failure_preserves_the_cache(tmp_path, warm_cache, interrupted): source = _write_entity_tables(tmp_path / "microcosm_layout.h5") - - def stop(path, value): - raise RuntimeError("stopped before stamping") - - with patch.object(us_datasets, "write_year_file_stamp", stop): - with pytest.raises(RuntimeError, match="stopped before stamping"): + data_folder = tmp_path / "data" + path = data_folder / f"microcosm_layout_year_{YEAR}.h5" + if warm_cache: + _ensure(source, data_folder) + original = path.read_bytes() + + def omit_stamp(staged_path, value): + assert read_renames_record(staged_path) == RENAME + if interrupted: + raise RuntimeError("stopped before stamping") + + error, message = ( + (RuntimeError, "stopped before stamping") + if interrupted + else (ValueError, "it has no stamp of the register") + ) + with patch.object(us_datasets, "write_year_file_stamp", omit_stamp): + with pytest.raises(error, match=message): create_datasets( datasets=[source], years=[YEAR], - data_folder=str(tmp_path / "data"), + data_folder=str(data_folder), allow_unmanaged=True, ) - (path,) = (tmp_path / "data").glob("*_year_*.h5") - # The tables and the record were written, but without the stamp the file - # is cut again. - assert read_renames_record(path) == RENAME - assert year_file_stamp_problem(path).startswith("it has no stamp") - assert _ensure(source, tmp_path / "data").filepath == str(path) + if warm_cache: + assert path.read_bytes() == original + else: + assert not path.exists() + assert not list(data_folder.glob(".policyengine-year-*")) + assert _ensure(source, data_folder).filepath == str(path) assert year_file_stamp_problem(path) is None diff --git a/tests/test_us_legacy_spm.py b/tests/test_us_legacy_spm.py index 3a78c5622..d7a9ef11d 100644 --- a/tests/test_us_legacy_spm.py +++ b/tests/test_us_legacy_spm.py @@ -516,10 +516,9 @@ def test_a_file_that_is_not_hdf5_is_out_of_date(tmp_path): def test_only_legacy_year_files_must_record_declarations(tmp_path): path = _empty_h5(tmp_path / "year.h5") - acs_local = us_datasets._expected_legacy_spm_profile("populace_us_2024_acs_local") + acs_local = us_datasets._expected_legacy_spm_profile(REBUILD.source_sha256) assert acs_local == expected_profile(REBUILD) - assert us_datasets._expected_legacy_spm_profile("populace_us_2024") is None - assert us_datasets._expected_legacy_spm_profile("hf://other/repo/x.h5") is None + assert us_datasets._expected_legacy_spm_profile(None) is None assert year_file_problem(path, acs_local) is not None # A Build O record is stale for the rebuild the bundle now certifies. write_record(path, _record()) @@ -541,9 +540,13 @@ def test_a_managed_dataset_is_recognised_by_its_uri_too(): uri = resolve_dataset_reference("us", "populace_us_2024_acs_local") assert uri.startswith("hf://") - assert us_datasets._expected_legacy_spm_profile(uri) == expected_profile(REBUILD) - default_uri = resolve_dataset_reference("us", "populace_us_2024") - assert us_datasets._expected_legacy_spm_profile(default_uri) is None + assert us_datasets._managed_source_sha256(uri) == REBUILD.source_sha256 + default_key = "populace_us_2024" + default_uri = resolve_dataset_reference("us", default_key) + assert us_datasets._managed_source_sha256(default_uri) == ( + us_datasets._managed_source_sha256(default_key) + ) + assert us_datasets._managed_source_sha256("hf://other/repo/x.h5") is None # --- Year-file frame guards ------------------------------------------------- diff --git a/tests/test_us_legacy_spm_integration.py b/tests/test_us_legacy_spm_integration.py index 7d4c8c776..496b9a847 100644 --- a/tests/test_us_legacy_spm_integration.py +++ b/tests/test_us_legacy_spm_integration.py @@ -20,7 +20,11 @@ from __future__ import annotations import importlib +import shutil +from functools import partial from pathlib import Path +from types import SimpleNamespace +from unittest.mock import MagicMock import h5py import numpy as np @@ -41,6 +45,7 @@ calculate_us_poverty_by_age, calculate_us_poverty_rates, ) +from policyengine.provenance import dataset_materialization, manifest # noqa: E402 from policyengine.provenance.dataset_materialization import ( # noqa: E402 DatasetSource, MaterializedDataset, @@ -53,6 +58,11 @@ ensure_datasets, load_datasets, ) +from policyengine.tax_benefit_models.us.legacy_inputs import ( # noqa: E402 + read_year_file_stamp, + write_year_file_stamp, + year_file_stamp, +) from policyengine.tax_benefit_models.us.legacy_spm import ( # noqa: E402 INDEPENDENCE_ROLE, RECORD_H5_DATASET, @@ -62,6 +72,7 @@ declarations, expected_profile, record, + registry, runs, ) from policyengine.tax_benefit_models.us.legacy_spm.model_adapter import ( # noqa: E402 @@ -73,6 +84,7 @@ MICROCOSM_US_2024_ACS_LOCAL_MICROCOSM_1263, ) from policyengine.tax_benefit_models.us.model import PolicyEngineUSLatest # noqa: E402 +from policyengine.utils.hashing import sha256_file # noqa: E402 # The ``us`` package's ``model`` attribute is the model version, not the module. us_model = importlib.import_module("policyengine.tax_benefit_models.us.model") @@ -522,9 +534,11 @@ def test_saved_outputs_are_reused_only_under_the_same_declarations(tmp_path): # --- Legacy source files: year files, raw runs, managed simulations ------- -def _write_source(path) -> str: +def _write_source(path, household_weight=1.0) -> str: + frames = _source_frames() + frames["household"]["household_weight"] = household_weight with pd.HDFStore(path, mode="w") as store: - for entity, frame in _source_frames().items(): + for entity, frame in frames.items(): store.put(entity, frame, format="table", data_columns=True) store.put("_time_period", pd.Series([2024]), format="table") return str(path) @@ -587,9 +601,9 @@ def build_o_identity(dataset): def _bundle_acs_local_sha256() -> str: - from policyengine.provenance.manifest import get_release_manifest - - return get_release_manifest("us").datasets["populace_us_2024_acs_local"].sha256 + bundled = manifest.get_release_manifest("us") + key = bundled.bundled_dataset_key("microcosm_us_2024_acs_local") + return bundled.datasets[key].sha256 class SimpleSources: @@ -598,18 +612,784 @@ def __init__(self, source, requests): self.requests = requests -def test_year_files_carry_the_declarations_for_every_year(tmp_path, legacy_files): - data_folder = str(tmp_path / "data") - years = [2025, 2026, 2027] +@pytest.fixture( + params=[("us_2024", "national"), ("us_2024_acs_local", "local_area")], + ids=["national", "local-area"], +) +def bundle_with_renamed_artifact(request, tmp_path, monkeypatch): + """Cache a synthetic artifact whose filename differs from its bundle key.""" + suffix, stem = request.param + key = f"populace_{suffix}" + source = Path(_write_source(tmp_path / f"{stem}.h5")) + bundled = manifest.get_release_manifest("us") + reference = bundled.datasets[bundled.bundled_dataset_key(key)].model_copy( + update={ + "path": source.name, + "sha256": sha256_file(source), + "metadata_sha256": None, + } + ) + bundle = bundled.model_copy( + update={ + "datasets": {key: reference}, + "default_dataset": key, + "certified_data_artifact": None, + } + ) + for module in (manifest, dataset_materialization, us_datasets): + monkeypatch.setattr(module, "get_release_manifest", lambda country: bundle) + + def unexpected_download(*args, **kwargs): + pytest.fail("The source artifact is already in the local cache") + + monkeypatch.setattr(dataset_materialization.requests, "get", unexpected_download) + return suffix, stem + + +@pytest.fixture +def extend_only_through_2024(monkeypatch): + from policyengine_us.data import economic_assumptions + + monkeypatch.setattr( + economic_assumptions, + "extend_single_year_dataset", + partial(economic_assumptions.extend_single_year_dataset, end_year=2024), + ) + + +@pytest.fixture(params=["us_2024", "us_2024_acs_local"], ids=["national", "local-area"]) +def bundle_with_same_stem_sources( + request, tmp_path, monkeypatch, extend_only_through_2024 +): + """Cache two distinct verified files whose paths have the same stem.""" + monkeypatch.chdir(tmp_path) + bundled = manifest.get_release_manifest("us") + old, new = (f"{spelling}_{request.param}" for spelling in ("populace", "microcosm")) + original = bundled.datasets[bundled.bundled_dataset_key(new)] + references = {} + for key, folder, weight in [(old, "old", 1.0), (new, "new", 3.0)]: + relative = Path(folder) / "source.h5" + path = tmp_path / "data" / relative + path.parent.mkdir(parents=True) + _write_source(path, household_weight=weight) + references[key] = original.model_copy( + update={ + "path": relative.as_posix(), + "sha256": sha256_file(path), + "metadata_sha256": None, + } + ) + bundle = bundled.model_copy( + update={ + "datasets": references, + "default_dataset": old, + "certified_data_artifact": None, + } + ) + for module in (manifest, dataset_materialization, us_datasets): + monkeypatch.setattr(module, "get_release_manifest", lambda country: bundle) + + def unexpected_download(*args, **kwargs): + pytest.fail("Both verified sources are already in the local cache") + + monkeypatch.setattr(dataset_materialization.requests, "get", unexpected_download) + return old, new, bundle.datasets + + +@pytest.mark.parametrize("legacy_flat_file", [False, True], ids=["bound", "legacy"]) +def test_old_flat_year_file_is_refused_when_same_stem_pins_converge( + bundle_with_same_stem_sources, legacy_flat_file +): + old, new, references = bundle_with_same_stem_sources + new_reference = references.pop(new) + key = "source_2024" + flat = create_datasets(datasets=[old], years=[2024])[key] + flat_path = Path(flat.filepath) + assert flat_path == Path("data/source_year_2024.h5") + assert pd.DataFrame(flat.data.household)["household_weight"].sum() == 4 + + references[new] = new_reference + split = ensure_datasets(datasets=[new], years=[2024])[key] + assert Path(split.filepath) != flat_path + assert pd.DataFrame(split.data.household)["household_weight"].sum() == 12 + + if legacy_flat_file: + write_year_file_stamp(flat_path, year_file_stamp()) + old_reference = references[old] + old_source_path = Path("data") / old_reference.path + shutil.copyfile(Path("data") / new_reference.path, old_source_path) + references[old] = old_reference.model_copy(update={"sha256": new_reference.sha256}) + assert flat_path.exists() + + with pytest.raises(ValueError, match="source SHA-256"): + load_datasets(datasets=[old], years=[2024]) + + rebuilt = ensure_datasets(datasets=[old], years=[2024])[key] + assert Path(rebuilt.filepath) == flat_path + assert pd.DataFrame(rebuilt.data.household)["household_weight"].sum() == 12 + reopened = load_datasets(datasets=[old], years=[2024])[key] + assert pd.DataFrame(reopened.data.household)["household_weight"].sum() == 12 + + +def test_same_stem_year_file_path_changes_when_its_source_pin_changes( + bundle_with_same_stem_sources, +): + _, new, references = bundle_with_same_stem_sources + key = "source_2024" + before = create_datasets(datasets=[new], years=[2024])[key] + uri = manifest.resolve_dataset_reference("us", new) + reference = references[new] + source_path = Path("data") / reference.path + _write_source(source_path, household_weight=4.0) + references[new] = reference.model_copy(update={"sha256": sha256_file(source_path)}) + assert manifest.resolve_dataset_reference("us", new) == uri + + with pytest.raises(FileNotFoundError): + load_datasets(datasets=[new], years=[2024]) + + after = ensure_datasets(datasets=[new], years=[2024])[key] + assert before.filepath != after.filepath + assert pd.DataFrame(after.data.household)["household_weight"].sum() == 16 + + +@pytest.mark.parametrize("allow_unmanaged", [False, True]) +def test_old_flat_file_is_rebuilt_in_split_cache_by_uri( + bundle_with_same_stem_sources, allow_unmanaged +): + old, new, references = bundle_with_same_stem_sources + new_reference = references.pop(new) + (flat,) = create_datasets(datasets=[old], years=[2024]).values() + write_year_file_stamp(flat.filepath, year_file_stamp()) + references[new] = new_reference + uri = manifest.resolve_dataset_reference("us", new) + + with pytest.raises(FileNotFoundError): + load_datasets(datasets=[uri], years=[2024]) + (split,) = ensure_datasets( + datasets=[uri], years=[2024], allow_unmanaged=allow_unmanaged + ).values() + assert split.filepath != flat.filepath + assert read_year_file_stamp(split.filepath) == year_file_stamp() + assert Path(flat.filepath).exists() + assert pd.DataFrame(split.data.household)["household_weight"].sum() == 12 + + stale_stamp = year_file_stamp() + stale_stamp["revision"] -= 1 + write_year_file_stamp(split.filepath, stale_stamp) + with pytest.raises(ValueError, match="year-file format revision"): + load_datasets(datasets=[new], years=[2024]) + (rebuilt,) = ensure_datasets( + datasets=[uri], years=[2024], allow_unmanaged=allow_unmanaged + ).values() + assert rebuilt.filepath == split.filepath + (reopened,) = load_datasets(datasets=[new], years=[2024]).values() + assert pd.DataFrame(reopened.data.household)["household_weight"].sum() == 12 + + +def test_ambiguous_uri_refuses_until_an_exact_bundle_key_is_used( + bundle_with_same_stem_sources, +): + old, new, references = bundle_with_same_stem_sources + uri = manifest.resolve_dataset_reference("us", new) + references["duplicate"] = references[new].model_copy( + update={"sha256": references[old].sha256} + ) + (created,) = create_datasets(datasets=[new], years=[2024]).values() + write_year_file_stamp(created.filepath, year_file_stamp()) + for operation in (load_datasets, ensure_datasets, create_datasets): + kwargs = {} if operation is load_datasets else {"allow_unmanaged": True} + with pytest.raises(ValueError, match="conflicting bundle artifacts"): + operation(datasets=[uri], years=[2024], **kwargs) + + (reopened,) = load_datasets(datasets=[new], years=[2024]).values() + assert pd.DataFrame(reopened.data.household)["household_weight"].sum() == 12 + references["duplicate"] = references[new] + assert load_datasets(datasets=[uri], years=[2024])["source_2024"].filepath == ( + created.filepath + ) + + +def test_a_same_stem_entry_without_a_pin_does_not_split_the_cache( + bundle_with_same_stem_sources, +): + old, new, references = bundle_with_same_stem_sources + references[new] = references[new].model_copy(update={"sha256": None}) + (flat,) = create_datasets(datasets=[old], years=[2024]).values() + assert Path(flat.filepath) == Path("data/source_year_2024.h5") + write_year_file_stamp(flat.filepath, year_file_stamp()) + + uri = manifest.resolve_dataset_reference("us", new) + for request in (new, uri): + for operation in (load_datasets, ensure_datasets, create_datasets): + options = {} if operation is load_datasets else {"allow_unmanaged": True} + with pytest.raises(ValueError, match="missing a bundle SHA-256"): + operation(datasets=[request], years=[2024], **options) + + with pytest.raises(ValueError, match="no source SHA-256"): + load_datasets(datasets=[old], years=[2024]) + (rebuilt,) = ensure_datasets(datasets=[old], years=[2024]).values() + assert rebuilt.filepath == flat.filepath + assert read_year_file_stamp(rebuilt.filepath)["source_sha256"] == ( + references[old].sha256 + ) + + +def test_same_stem_year_files_retain_their_source(bundle_with_same_stem_sources): + old, new, _ = bundle_with_same_stem_sources + key = "source_2024" + old_dataset = create_datasets(datasets=[old], years=[2024])[key] + new_dataset = ensure_datasets(datasets=[new], years=[2024])[key] + + assert pd.DataFrame(old_dataset.data.household)["household_weight"].sum() == 4 + assert pd.DataFrame(new_dataset.data.household)["household_weight"].sum() == 12 + assert old_dataset.filepath != new_dataset.filepath + for selector, expected in [(old, 4), (new, 12)]: + reopened = load_datasets(datasets=[selector], years=[2024])[key] + assert ( + pd.DataFrame(reopened.data.household)["household_weight"].sum() == expected + ) + + +def test_load_requires_the_requested_same_stem_year_file(bundle_with_same_stem_sources): + old, new, _ = bundle_with_same_stem_sources + (created,) = create_datasets(datasets=[old], years=[2024]).values() + legacy_path = Path("data/source_year_2024.h5") + if Path(created.filepath) != legacy_path: + shutil.copyfile(created.filepath, legacy_path) + + with pytest.raises(FileNotFoundError): + load_datasets(datasets=[new], years=[2024]) + + +@pytest.mark.parametrize("operation", [create_datasets, load_datasets, ensure_datasets]) +def test_same_stem_batch_refuses_distinct_sources_before_writing( + bundle_with_same_stem_sources, monkeypatch, operation +): + old, new, _ = bundle_with_same_stem_sources + + if operation is ensure_datasets: + unexpected_delegation = MagicMock( + side_effect=AssertionError("Ensure must reject before delegating") + ) + monkeypatch.setattr(us_datasets, "create_datasets", unexpected_delegation) + monkeypatch.setattr(us_datasets, "load_datasets", unexpected_delegation) + + with pytest.raises(ValueError, match="share the year-file result stem 'source'"): + operation(datasets=[old, new], years=[2024]) + + assert not list(Path("./data").rglob("*_year_*.h5")) + + +@pytest.fixture +def stub_explicit_hf_download(tmp_path, monkeypatch): + payload = Path(_write_source(tmp_path / "download.h5", household_weight=3.0)) + response = MagicMock(status_code=200) + response.__enter__.return_value = response + response.iter_content.return_value = [payload.read_bytes()] + download = MagicMock(return_value=response) + monkeypatch.setattr(dataset_materialization.requests, "get", download) + return download + + +def test_create_requires_matching_bytes_before_stamping_a_managed_flat_year_file( + bundle_with_same_stem_sources, stub_explicit_hf_download +): + old, new, references = bundle_with_same_stem_sources + old_reference = references[old] + new_reference = references[new] + cached = Path("data/source.h5") + wrong_source = Path("data") / old_reference.path + shutil.copyfile(wrong_source, cached) + original = cached.read_bytes() + references[new] = new_reference.model_copy(update={"path": cached.name}) + references[old] = old_reference.model_copy(update={"sha256": new_reference.sha256}) + # The wrong bytes already cached at the top-level path cannot seed the pin. + uri = manifest.resolve_dataset_reference("us", new) + response = stub_explicit_hf_download.return_value.__enter__.return_value + response.iter_content.return_value = [wrong_source.read_bytes()] + + with pytest.raises(ValueError, match="Downloaded .* has sha256 .* expected"): + create_datasets(datasets=[uri], years=[2024], allow_unmanaged=True) + + stub_explicit_hf_download.assert_called_once() + assert cached.read_bytes() == original + assert not Path("data/source_year_2024.h5").exists() + + +def test_pinned_year_file_requires_a_verified_model_input( + bundle_with_same_stem_sources, monkeypatch +): + old, _, references = bundle_with_same_stem_sources + raw = Path("data") / references[old].path + assert sha256_file(raw) == references[old].sha256 + monkeypatch.setattr( + us_datasets, + "materialize_dataset", + lambda *args, **kwargs: DatasetSource(source_uri=str(raw), path=str(raw)), + ) + + with pytest.raises( + ValueError, match="was not materialized with its bundle SHA-256" + ): + create_datasets(datasets=[old], years=[2024]) + + +@pytest.mark.usefixtures("extend_only_through_2024") +def test_create_uses_each_source_before_materializing_the_next( + tmp_path, stub_explicit_hf_download +): + data_folder = tmp_path / "data" + data_folder.mkdir() + cached = Path(_write_source(data_folder / "two.h5")) + local = tmp_path / "one.h5" + local.symlink_to(cached) + created = create_datasets( - datasets=["populace_us_2024_acs_local"], years=years, data_folder=data_folder + datasets=[str(local), "hf://policyengine/example/two.h5"], + years=[2024], + data_folder=str(data_folder), + allow_unmanaged=True, ) + + assert { + key: pd.DataFrame(dataset.data.household)["household_weight"].sum() + for key, dataset in created.items() + } == {"one_2024": 4, "two_2024": 12} + stub_explicit_hf_download.assert_called_once() + + +def test_create_uses_verified_raw_bytes_after_a_same_basename_download( + bundle_with_same_stem_sources, monkeypatch +): + old, new, references = bundle_with_same_stem_sources + # Give both sources nondefault URIs so each uses exact-URI materialization. + bundle = manifest.get_release_manifest("us") + references["other"] = references[old].model_copy(update={"path": "other.h5"}) + monkeypatch.setattr(bundle, "default_dataset", "other") + uris = {key: manifest.resolve_dataset_reference("us", key) for key in (old, new)} + + def download(url, **kwargs): + (raw,) = ( + Path("data") / reference.path + for key, reference in references.items() + if key != "other" and url.endswith(f"/{reference.path}") + ) + response = MagicMock(status_code=200) + response.__enter__.return_value = response + response.iter_content.return_value = [raw.read_bytes()] + return response + + monkeypatch.setattr(dataset_materialization.requests, "get", download) + materialize = dataset_materialization.materialize_dataset + + def materialize_and_replace_legacy_basename(country, dataset, **kwargs): + source = materialize(country, dataset, **kwargs) + competitor = materialize(country, uris[old], **kwargs) + assert sha256_file(competitor.path) == references[old].sha256 + assert sha256_file(Path("data/source.h5")) == references[old].sha256 + return source + + monkeypatch.setattr( + us_datasets, "materialize_dataset", materialize_and_replace_legacy_basename + ) + (created,) = create_datasets( + datasets=[uris[new]], years=[2024], allow_unmanaged=True + ).values() + + assert pd.DataFrame(created.data.household)["household_weight"].sum() == 12 + + +@pytest.mark.usefixtures("extend_only_through_2024") +@pytest.mark.parametrize("operation", [create_datasets, ensure_datasets]) +@pytest.mark.parametrize("later_source", ["symlink", "symlink-loop", "year-file"]) +def test_batch_accepts_local_input_materialized_by_earlier_request( + tmp_path, monkeypatch, stub_explicit_hf_download, operation, later_source +): + monkeypatch.chdir(tmp_path) + data_folder = tmp_path / "data" + data_folder.mkdir() + if later_source == "year-file": + local = data_folder / "two_year_2024.h5" + else: + local = tmp_path / "one.h5" + cached = data_folder / "two.h5" + local.symlink_to(cached) + if later_source == "symlink-loop": + cached.symlink_to(local) + assert not local.exists() + + catalog = MagicMock(side_effect=AssertionError("The second input is local")) + monkeypatch.setattr(manifest, "get_data_release_manifest", catalog) + result = operation( + datasets=["hf://policyengine/example/two.h5", str(local.relative_to(tmp_path))], + years=[2024], + data_folder=str(data_folder), + allow_unmanaged=True, + ) + + assert { + key: pd.DataFrame(dataset.data.household)["household_weight"].sum() + for key, dataset in result.items() + } == {"two_2024": 12, f"{local.stem}_2024": 12} + stub_explicit_hf_download.assert_called_once() + catalog.assert_not_called() + + +@pytest.mark.usefixtures("extend_only_through_2024") +@pytest.mark.parametrize("operation", [create_datasets, ensure_datasets]) +@pytest.mark.parametrize("missing_path", ["absolute", "./missing.h5", "../missing.h5"]) +def test_batch_rejects_missing_local_input_before_materializing( + tmp_path, monkeypatch, operation, missing_path +): + work = tmp_path / "work" + work.mkdir() + monkeypatch.chdir(work) + if missing_path == "absolute": + missing_path = str(tmp_path / "missing.h5") + source = _write_source(tmp_path / "source.h5") + data_folder = tmp_path / "data" + kwargs = { + "years": [2024], + "data_folder": str(data_folder), + "allow_unmanaged": True, + } + if operation is ensure_datasets: + create_datasets(datasets=[source], **kwargs) + materialize = MagicMock(side_effect=AssertionError("Must reject during planning")) + monkeypatch.setattr(us_datasets, "materialize_dataset", materialize) + catalog = MagicMock(side_effect=AssertionError("Must not query the catalog")) + monkeypatch.setattr(manifest, "get_data_release_manifest", catalog) + + with pytest.raises(ValueError, match=r"US dataset file not found: .*missing\.h5"): + operation(datasets=[source, missing_path], **kwargs) + + materialize.assert_not_called() + catalog.assert_not_called() + + +@pytest.mark.usefixtures("extend_only_through_2024") +@pytest.mark.parametrize("symlink", [False, True], ids=["path", "symlink"]) +@pytest.mark.parametrize("allow_unmanaged", [False, True]) +def test_year_file_reopens_without_raw_local_source( + tmp_path, monkeypatch, symlink, allow_unmanaged +): + monkeypatch.chdir(tmp_path) + source = Path(_write_source(tmp_path / "source.h5")) + local = tmp_path / "link.h5" if symlink else source + if symlink: + local.symlink_to(source) + key = f"{local.stem}_2024" + kwargs = { + "datasets": [local.name if symlink else str(local)], + "years": [2024], + "data_folder": str(tmp_path / "data"), + } + created = create_datasets(allow_unmanaged=True, **kwargs)[key] + write_year_file_stamp(created.filepath, year_file_stamp()) + source.unlink() + + catalog = MagicMock(side_effect=AssertionError("The input is a local file")) + monkeypatch.setattr(manifest, "get_data_release_manifest", catalog) + reopened = load_datasets(**kwargs)[key] + ensured = ensure_datasets(allow_unmanaged=allow_unmanaged, **kwargs)[key] + for dataset in (reopened, ensured): + assert pd.DataFrame(dataset.data.household)["household_weight"].sum() == 4 + + with pytest.raises(ValueError, match="US dataset file not found"): + create_datasets(allow_unmanaged=True, **kwargs) + catalog.assert_not_called() + + +@pytest.mark.parametrize("operation", [create_datasets, ensure_datasets]) +@pytest.mark.parametrize("cache_replacement", ["two.h5", "two_year_2024.h5"]) +def test_batch_rejects_local_aliases_that_diverge_after_replacement( + tmp_path, stub_explicit_hf_download, operation, cache_replacement +): + data_folder = tmp_path / "data" + data_folder.mkdir() + source = Path(_write_source(tmp_path / "original.h5")) + cached = data_folder / cache_replacement + cached.symlink_to(source) + local_a = tmp_path / "first" / "one.h5" + local_b = tmp_path / "second" / "one.h5" + local_a.parent.mkdir() + local_b.parent.mkdir() + local_a.symlink_to(cached) + local_b.symlink_to(source) + assert local_a.resolve() == local_b.resolve() + + with pytest.raises(ValueError, match="share the year-file result stem 'one'"): + operation( + datasets=["hf://policyengine/example/two.h5", str(local_a), str(local_b)], + years=[2024], + data_folder=str(data_folder), + allow_unmanaged=True, + ) + + stub_explicit_hf_download.assert_not_called() + assert list(data_folder.iterdir()) == [cached] + assert cached.is_symlink() + + +@pytest.mark.parametrize("prior_download", [False, True], ids=["stale", "conditional"]) +def test_batch_rejects_divergence_after_replacing_managed_raw_cache( + tmp_path, bundle_with_same_stem_sources, stub_explicit_hf_download, prior_download +): + old, _, references = bundle_with_same_stem_sources + cached = tmp_path / "data" / references[old].path + datasets = [old] + if prior_download: + source = tmp_path / "data" / "two.h5" + cached.rename(source) + assert sha256_file(source) == references[old].sha256 + datasets.insert(0, "hf://policyengine/example/two.h5") + pinned_response = MagicMock(status_code=200) + pinned_response.__enter__.return_value = pinned_response + pinned_response.iter_content.return_value = [source.read_bytes()] + stub_explicit_hf_download.side_effect = [ + stub_explicit_hf_download.return_value, + pinned_response, + ] + else: + cached.unlink() + source = Path(_write_source(tmp_path / "original.h5", household_weight=3.0)) + cached.symlink_to(source) + local_a = tmp_path / "first" / "one.h5" + local_b = tmp_path / "second" / "one.h5" + local_a.parent.mkdir() + local_b.parent.mkdir() + local_a.symlink_to(cached) + local_b.symlink_to(source) + + with pytest.raises(ValueError, match="share the year-file result stem 'one'"): + create_datasets( + datasets=[*datasets, str(local_a), str(local_b)], + years=[2024], + allow_unmanaged=True, + ) + + stub_explicit_hf_download.assert_not_called() + assert cached.is_symlink() + + +def test_create_refuses_colliding_downloads_before_touching_the_cache( + tmp_path, stub_explicit_hf_download +): + data_folder = tmp_path / "data" + data_folder.mkdir() + cached = Path(_write_source(data_folder / "source.h5")) + original = cached.read_bytes() + + with pytest.raises(ValueError, match="share the year-file result stem 'source'"): + create_datasets( + datasets=[ + "hf://policyengine/example/a/source.h5", + "hf://policyengine/example/b/source.h5", + ], + years=[2024], + data_folder=str(data_folder), + allow_unmanaged=True, + ) + + stub_explicit_hf_download.assert_not_called() + assert list(data_folder.iterdir()) == [cached] + assert cached.read_bytes() == original + + +@pytest.mark.usefixtures("extend_only_through_2024") +@pytest.mark.parametrize("filename", ["sample.h5", "sample@local.h5"]) +@pytest.mark.parametrize("operation", [create_datasets, load_datasets, ensure_datasets]) +def test_same_local_source_spellings_share_year_file( + tmp_path, monkeypatch, operation, filename +): + monkeypatch.chdir(tmp_path) + source = _write_source(tmp_path / filename) + data_folder = tmp_path / "data" + kwargs = {"years": [2024], "data_folder": str(data_folder)} + if operation is load_datasets: + create_datasets(datasets=[source], allow_unmanaged=True, **kwargs) + else: + kwargs["allow_unmanaged"] = True + + result = operation(datasets=[filename, source], **kwargs) + + stem = Path(filename).stem + assert list(result) == [f"{stem}_2024"] + dataset = result[f"{stem}_2024"] + assert Path(dataset.filepath) == data_folder / f"{stem}_year_2024.h5" + assert pd.DataFrame(dataset.data.household)["household_weight"].sum() == 4 + + +@pytest.mark.usefixtures("extend_only_through_2024") +def test_ensure_rebuilds_local_at_filename_from_its_full_stem(tmp_path): + source = _write_source(tmp_path / "sample@local.h5") + cache = tmp_path / "data" + kwargs = {"datasets": [source], "years": [2024], "data_folder": str(cache)} + (initial,) = create_datasets(allow_unmanaged=True, **kwargs).values() + legacy_path = cache / "sample_year_2024.h5" + if Path(initial.filepath) != legacy_path: + Path(initial.filepath).rename(legacy_path) + write_year_file_stamp(legacy_path, year_file_stamp()) + + with pytest.raises(FileNotFoundError, match="sample@local_year_2024.h5"): + load_datasets(**kwargs) + with pytest.raises(ValueError, match="Explicit local dataset paths bypass"): + ensure_datasets(**kwargs) + + result = ensure_datasets(allow_unmanaged=True, **kwargs) + assert list(result) == ["sample@local_2024"] + assert list(load_datasets(**kwargs)) == ["sample@local_2024"] + assert read_year_file_stamp(legacy_path) == year_file_stamp() + + +def test_managed_microsimulation_uses_each_exact_same_stem_source( + bundle_with_same_stem_sources, +): + old, new, references = bundle_with_same_stem_sources + for selector, weight in [(old, 4), (new, 12)]: + simulation = pe.us.managed_microsimulation(dataset=selector) + + assert simulation.calculate("household_weight", 2024).values.sum() == weight + assert simulation.policyengine_bundle["runtime_dataset"] == "source" + assert simulation.policyengine_bundle["runtime_dataset_uri"] == ( + manifest.resolve_dataset_reference("us", selector) + ) + assert simulation.policyengine_bundle["runtime_dataset_sha256"] == ( + references[selector].sha256 + ) + + +@pytest.mark.parametrize("operation", [create_datasets, load_datasets]) +@pytest.mark.parametrize( + "spelling", + ["populace", "microcosm", None], + ids=["populace", "microcosm", "default"], +) +def test_year_files_use_artifact_stem_keys( + tmp_path, bundle_with_renamed_artifact, operation, spelling +): + suffix, stem = bundle_with_renamed_artifact + kwargs = {"years": [YEAR], "data_folder": str(tmp_path)} + if operation is load_datasets: + create_datasets(**kwargs) + if spelling is not None: + kwargs["datasets"] = [f"{spelling}_{suffix}"] + + result = operation(**kwargs) + + assert list(result) == [f"{stem}_{YEAR}"] + assert ( + Path(result[f"{stem}_{YEAR}"].filepath) == tmp_path / f"{stem}_year_{YEAR}.h5" + ) + + +@pytest.mark.parametrize( + "build_as,load_as", [("populace", "microcosm"), ("microcosm", "populace")] +) +def test_year_files_are_reused_across_selectors( + tmp_path, monkeypatch, bundle_with_renamed_artifact, build_as, load_as +): + suffix, stem = bundle_with_renamed_artifact + kwargs = {"years": [YEAR], "data_folder": str(tmp_path)} + (created,) = create_datasets(datasets=[f"{build_as}_{suffix}"], **kwargs).values() + + def unexpected_rebuild(*args, **kwargs): + pytest.fail("The other selector must reuse the existing year file") + + monkeypatch.setattr(us_datasets, "create_datasets", unexpected_rebuild) + (loaded,) = ensure_datasets(datasets=[f"{load_as}_{suffix}"], **kwargs).values() + + assert ( + Path(loaded.filepath) + == Path(created.filepath) + == tmp_path / f"{stem}_year_{YEAR}.h5" + ) + assert loaded.metadata == created.metadata + pd.testing.assert_frame_equal(loaded.data.household, created.data.household) + + +@pytest.mark.usefixtures("extend_only_through_2024") +def test_ensure_migrates_the_default_cache_across_selector_spellings( + tmp_path, bundle_with_renamed_artifact +): + suffix, stem = bundle_with_renamed_artifact + key = f"populace_{suffix}" + alias = f"microcosm_{suffix}" + uri = manifest.resolve_dataset_reference("us", key) + kwargs = {"years": [2024], "data_folder": str(tmp_path)} + (initial,) = create_datasets(**kwargs).values() + for request, allow_unmanaged in [(None, False), ([alias], True), ([uri], False)]: + write_year_file_stamp(initial.filepath, year_file_stamp()) + with pytest.raises(ValueError, match="no source SHA-256"): + load_datasets(datasets=request, **kwargs) + result = ensure_datasets( + datasets=request, allow_unmanaged=allow_unmanaged, **kwargs + ) + assert result[f"{stem}_2024"].filepath == initial.filepath + assert read_year_file_stamp(initial.filepath)["source_sha256"] == ( + us_datasets._managed_source_sha256(key) + ) + assert load_datasets(datasets=[alias], **kwargs)[f"{stem}_2024"].filepath == ( + initial.filepath + ) + + +@pytest.mark.usefixtures("extend_only_through_2024") +@pytest.mark.parametrize("source_kind", ["local", "symlink"]) +def test_unmanaged_year_file_migration_preserves_bundle_enforcement( + tmp_path, source_kind +): + source = Path(_write_source(tmp_path / "raw.h5")) + if source_kind == "symlink": + source, target = tmp_path / "link.h5", source + source.symlink_to(target) + kwargs = { + "datasets": [str(source)], + "years": [2024], + "data_folder": str(tmp_path / "data"), + } + (initial,) = create_datasets(allow_unmanaged=True, **kwargs).values() + write_year_file_stamp(initial.filepath, year_file_stamp()) + for operation in (load_datasets, ensure_datasets): + (reopened,) = operation(**kwargs).values() + assert reopened.filepath == initial.filepath + assert RECORD_KEY not in reopened.metadata + assert read_year_file_stamp(initial.filepath) == year_file_stamp() + + stale_stamp = year_file_stamp() + stale_stamp["revision"] -= 1 + write_year_file_stamp(initial.filepath, stale_stamp) + with pytest.raises(ValueError, match="year-file format revision"): + load_datasets(**kwargs) + for operation in (ensure_datasets, create_datasets): + with pytest.raises(ValueError, match="Explicit local dataset paths bypass"): + operation(**kwargs) + assert read_year_file_stamp(initial.filepath) == stale_stamp + + (rebuilt,) = ensure_datasets(allow_unmanaged=True, **kwargs).values() + assert read_year_file_stamp(rebuilt.filepath) == year_file_stamp() + (reopened,) = load_datasets(**kwargs).values() + assert reopened.metadata == rebuilt.metadata + + +@pytest.mark.parametrize( + "selector", ["populace_us_2024_acs_local", "microcosm_us_2024_acs_local"] +) +def test_year_files_carry_the_declarations_for_every_year( + tmp_path, legacy_files, selector +): + data_folder = str(tmp_path / "data") + years = [2025, 2026, 2027] + created = create_datasets(datasets=[selector], years=years, data_folder=data_folder) assert legacy_files.requests == [ - "populace_us_2024_acs_local", + selector, LIST_PIN.bundle_dataset, ] for year in years: dataset = created[f"populace_us_2024_acs_local_{year}"] + assert ( + Path(dataset.filepath).name == f"populace_us_2024_acs_local_year_{year}.h5" + ) spm_unit = pd.DataFrame(dataset.data.spm_unit).set_index("spm_unit_id") person = pd.DataFrame(dataset.data.person).set_index("person_id") assert spm_unit[UNIVERSE_VARIABLE].tolist() == [ @@ -630,9 +1410,10 @@ def test_year_files_carry_the_declarations_for_every_year(tmp_path, legacy_files ] assert LegacySPMRecord.model_validate(dataset.metadata[RECORD_KEY]) == _record() - (loaded,) = load_datasets( - datasets=["populace_us_2024_acs_local"], years=[YEAR], data_folder=data_folder - ).values() + loaded = ensure_datasets( + datasets=[selector], years=[YEAR], data_folder=data_folder + )[f"populace_us_2024_acs_local_{YEAR}"] + assert legacy_files.requests == [selector, LIST_PIN.bundle_dataset] simulation = Simulation(dataset=loaded, tax_benefit_model_version=pe.us.model) simulation.run() spm_unit = _frame(simulation, "spm_unit") @@ -728,10 +1509,22 @@ def test_a_run_straight_over_a_legacy_source_derives_the_declarations( assert restored.output_dataset.metadata[RECORD_KEY]["model_mode"] == "override" +@pytest.mark.parametrize( + "selector", ["populace_us_2024_acs_local", "microcosm_us_2024_acs_local"] +) def test_a_managed_simulation_of_a_legacy_source_applies_the_declarations( - legacy_files, + legacy_files, monkeypatch, selector ): - simulation = pe.us.managed_microsimulation(dataset="populace_us_2024_acs_local") + materialize_list = MagicMock(wraps=declarations.materialize_dataset) + monkeypatch.setattr(declarations, "materialize_dataset", materialize_list) + simulation = pe.us.managed_microsimulation(dataset=selector) + assert legacy_files.requests == [selector, LIST_PIN.bundle_dataset] + materialize_list.assert_called_once_with( + "us", LIST_PIN.bundle_dataset, data_dir=dataset_materialization.DEFAULT_DATA_DIR + ) + assert simulation.policyengine_bundle["runtime_dataset"] == ( + "populace_us_2024_acs_local" + ) thresholds = simulation.calculate("spm_unit_spm_threshold", YEAR).values assert np.isnan(thresholds[[1, 2]]).all() assert np.isfinite(thresholds[[0, 3, 4]]).all() @@ -744,26 +1537,315 @@ def test_a_managed_simulation_of_a_legacy_source_applies_the_declarations( assert recorded.outside_spm_units == 2 -def test_year_files_load_by_the_sources_uri_as_well_as_its_name(tmp_path, legacy_files): - """The region registry names the source by URI; that form must work too.""" - from policyengine.provenance.manifest import resolve_dataset_reference - - data_folder = str(tmp_path / "data") - create_datasets( - datasets=["populace_us_2024_acs_local"], years=[YEAR], data_folder=data_folder +@pytest.fixture +def legacy_acs_uri(tmp_path, monkeypatch, extend_only_through_2024): + key = "populace_us_2024_acs_local" + source = Path(_write_source(tmp_path / f"{key}.h5")) + registered = BUILD_O.model_copy(update={"source_sha256": sha256_file(source)}) + monkeypatch.setattr(registry, "LEGACY_SPM_SOURCES", (registered,)) + independence_list = _write_list(tmp_path / "source_spm_person_independence.csv") + monkeypatch.setattr( + declarations, + "materialize_dataset", + lambda *args, **kwargs: _bundle_source(independence_list, LIST_PIN.sha256), ) - uri = resolve_dataset_reference("us", "populace_us_2024_acs_local") - (loaded,) = load_datasets( - datasets=[uri], years=[YEAR], data_folder=data_folder + bundle = manifest.get_release_manifest("us").model_copy(deep=True) + installed_key = bundle.bundled_dataset_key(key) + reference = bundle.datasets[installed_key].model_copy( + update={ + "path": f"release/fixture/{source.name}", + "sha256": registered.source_sha256, + "metadata_sha256": None, + } + ) + bundle.datasets[installed_key] = reference + for module in (manifest, dataset_materialization, us_datasets): + monkeypatch.setattr(module, "get_release_manifest", lambda country: bundle) + + response = MagicMock(status_code=200) + response.__enter__.return_value = response + response.iter_content.return_value = [source.read_bytes()] + download = MagicMock(return_value=response) + monkeypatch.setattr(dataset_materialization.requests, "get", download) + uri = manifest.resolve_dataset_reference("us", key) + return key, uri, reference, source, registered, download + + +@pytest.mark.parametrize("operation", [load_datasets, ensure_datasets]) +@pytest.mark.parametrize("force_copy", [False, True], ids=["link", "copy-fallback"]) +def test_year_file_hydrates_the_validated_snapshot( + tmp_path, monkeypatch, legacy_acs_uri, operation, force_copy +): + key, _, _, _, _, _ = legacy_acs_uri + kwargs = {"datasets": [key], "years": [2024], "data_folder": str(tmp_path / "data")} + (created,) = create_datasets(**kwargs).values() + shared_path = Path(created.filepath) + replacement_path = shared_path.with_name("replacement.h5") + other_record = _record() + different_households = pd.DataFrame(created.data.household).assign( + household_weight=3.0 + ) + replacement = created.model_copy( + update={ + "filepath": str(replacement_path), + "metadata": { + **created.metadata, + RECORD_KEY: other_record.model_dump(mode="json"), + }, + "data": created.data.model_copy( + update={ + "household": MicroDataFrame( + different_households, weights="household_weight" + ) + } + ), + } + ) + replacement.save() + replacement_stamp = year_file_stamp( + source_sha256=other_record.profile.source.source_sha256 + ) + write_year_file_stamp(replacement_path, replacement_stamp) + + if force_copy: + monkeypatch.setattr( + us_datasets.os, + "link", + MagicMock(side_effect=OSError("test cache does not support hard links")), + ) + + load = PolicyEngineUSDataset.load + loads = 0 + + def replace_before_loading(dataset): + nonlocal loads + if loads == 0: + replacement_path.replace(shared_path) + loads += 1 + load(dataset) + + monkeypatch.setattr(PolicyEngineUSDataset, "load", replace_before_loading) + (loaded,) = operation(**kwargs).values() + + assert read_year_file_stamp(shared_path) == replacement_stamp + assert loaded.filepath == created.filepath + assert loaded.metadata[RECORD_KEY] == created.metadata[RECORD_KEY] + pd.testing.assert_frame_equal(loaded.data.household, created.data.household) + assert loads == 1 + + +@pytest.mark.parametrize("allow_unmanaged", [False, True]) +@pytest.mark.parametrize("seed", ["key", "uri", "old-revision", "old-register"]) +def test_year_files_load_by_the_sources_uri_as_well_as_its_name( + tmp_path, legacy_acs_uri, seed, allow_unmanaged +): + key, uri, reference, source, registered, download = legacy_acs_uri + cache = tmp_path / "data" + kwargs = {"years": [2024], "data_folder": str(cache)} + explicit_raw = cache / source.name + managed_raw = cache / reference.path + if seed == "uri": + # Model the old explicit URI path: flat raw bytes and no SPM record. + cache.mkdir() + shutil.copyfile(source, explicit_raw) + (initial,) = create_datasets( + datasets=[str(explicit_raw)], allow_unmanaged=True, **kwargs + ).values() + assert RECORD_KEY not in initial.metadata + legacy_flat = cache / f"{source.stem}_year_2024.h5" + Path(initial.filepath).replace(legacy_flat) + initial.filepath = str(legacy_flat) + else: + (initial,) = create_datasets(datasets=[key], **kwargs).values() + assert managed_raw.read_bytes() == source.read_bytes() + stamp = year_file_stamp() + if seed == "old-revision": + stamp["revision"] -= 1 + elif seed == "old-register": + stamp["register"] = {} + write_year_file_stamp(initial.filepath, stamp) + download.reset_mock() + + with pytest.raises(ValueError, match="out of date"): + load_datasets(datasets=[uri], **kwargs) + (rebuilt,) = ensure_datasets( + datasets=[uri], allow_unmanaged=allow_unmanaged, **kwargs ).values() - assert LegacySPMRecord.model_validate(loaded.metadata[RECORD_KEY]) == _record() - legacy_files.requests.clear() - (ensured,) = ensure_datasets( - datasets=[uri], years=[YEAR], data_folder=data_folder + assert rebuilt.filepath == initial.filepath + if seed == "uri": + download.assert_called_once() + if allow_unmanaged: + assert not managed_raw.exists() + else: + assert managed_raw.read_bytes() == source.read_bytes() + assert explicit_raw.read_bytes() == source.read_bytes() + else: + assert managed_raw.read_bytes() == source.read_bytes() + download.assert_not_called() + assert read_year_file_stamp(rebuilt.filepath)["source_sha256"] == reference.sha256 + + for selector in (uri, key, "microcosm_us_2024_acs_local"): + (loaded,) = load_datasets(datasets=[selector], **kwargs).values() + assert loaded.filepath == rebuilt.filepath + assert loaded.metadata == rebuilt.metadata + assert LegacySPMRecord.model_validate( + loaded.metadata[RECORD_KEY] + ).profile == expected_profile(registered) + download.reset_mock() + (ensured,) = ensure_datasets(datasets=[uri], **kwargs).values() + assert ensured.metadata == rebuilt.metadata + download.assert_not_called() + + +def test_explicit_pinned_legacy_uri_creates_reopenable_year_file( + tmp_path, legacy_acs_uri +): + key, uri, _, source, registered, download = legacy_acs_uri + cache = tmp_path / "data" + kwargs = {"years": [2024], "data_folder": str(cache)} + with pytest.raises(ValueError, match="Explicit dataset URIs bypass"): + create_datasets(datasets=[uri], **kwargs) + download.assert_not_called() + + (created,) = create_datasets( + datasets=[uri], allow_unmanaged=True, **kwargs + ).values() + + download.assert_called_once() + assert (cache / source.name).read_bytes() == source.read_bytes() + assert LegacySPMRecord.model_validate( + created.metadata[RECORD_KEY] + ).profile == expected_profile(registered) + (loaded,) = load_datasets(datasets=[key], **kwargs).values() + assert loaded.metadata == created.metadata + + +@pytest.mark.parametrize("operation", [create_datasets, ensure_datasets]) +@pytest.mark.parametrize("stale", [False, True], ids=["dangling", "stale"]) +def test_pinned_uri_updates_legacy_raw_before_later_local_input( + tmp_path, monkeypatch, legacy_acs_uri, operation, stale +): + _, uri, _, source, _, download = legacy_acs_uri + monkeypatch.chdir(tmp_path) + cache = tmp_path / "data" + cache.mkdir() + raw = cache / source.name + local = Path("local.h5") + local.symlink_to(raw) + if stale: + _write_source(raw, household_weight=7.0) + else: + assert not local.exists() + + catalog = MagicMock(side_effect=AssertionError("The second input is local")) + monkeypatch.setattr(manifest, "get_data_release_manifest", catalog) + datasets = operation( + datasets=[uri, str(local)], + years=[2024], + data_folder=str(cache), + allow_unmanaged=True, + ) + + assert raw.read_bytes() == source.read_bytes() + assert { + key: dataset.data.household["household_weight"].sum() + for key, dataset in datasets.items() + } == {f"{source.stem}_2024": 4, "local_2024": 4} + download.assert_called_once() + catalog.assert_not_called() + + +@pytest.mark.parametrize("selector_kind", ["local", "bare-uri", "main-uri"]) +def test_unpinned_year_files_do_not_replace_managed_flat_files( + bundle_with_same_stem_sources, stub_explicit_hf_download, monkeypatch, selector_kind +): + managed_key, other_key, references = bundle_with_same_stem_sources + other_reference = references.pop(other_key) + if selector_kind == "local": + selector = str((Path("data") / other_reference.path).resolve()) + else: + uri = manifest.resolve_dataset_reference("us", managed_key).rsplit("@", 1)[0] + selector = f"{uri}@main" if selector_kind == "main-uri" else uri + + result_key = "source_2024" + managed = ensure_datasets(datasets=[managed_key], years=[2024])[result_key] + flat_path = Path(managed.filepath) + flat_bytes = flat_path.read_bytes() + with pytest.raises(FileNotFoundError): + load_datasets(datasets=[selector], years=[2024]) + with pytest.raises(ValueError, match="bypass"): + ensure_datasets(datasets=[selector], years=[2024]) + stub_explicit_hf_download.assert_not_called() + + unpinned = ensure_datasets(datasets=[selector], years=[2024], allow_unmanaged=True)[ + result_key + ] + assert unpinned.filepath != managed.filepath + assert flat_path.read_bytes() == flat_bytes + assert read_year_file_stamp(unpinned.filepath) == year_file_stamp() + + def unexpected_rebuild(*args, **kwargs): + pytest.fail("Both year-file caches should be reusable") + + monkeypatch.setattr(us_datasets, "create_datasets", unexpected_rebuild) + for request, cached, weight in [ + (managed_key, managed, 4), + (selector, unpinned, 12), + ]: + for operation in (load_datasets, ensure_datasets): + loaded = operation(datasets=[request], years=[2024])[result_key] + assert loaded.filepath == cached.filepath + assert loaded.data.household["household_weight"].sum() == weight + + +@pytest.mark.parametrize("selector_kind", ["local", "uri"]) +def test_unpinned_request_refuses_an_unrelated_legacy_flat_file( + bundle_with_same_stem_sources, stub_explicit_hf_download, selector_kind +): + managed_key, other_key, references = bundle_with_same_stem_sources + uri = manifest.resolve_dataset_reference("us", other_key) + other_reference = references.pop(other_key) + raw_path = (Path("data") / other_reference.path).resolve() + selector = str(raw_path) if selector_kind == "local" else uri + + (legacy,) = create_datasets(datasets=[managed_key], years=[2024]).values() + write_year_file_stamp(legacy.filepath, year_file_stamp()) + assert legacy.data.household["household_weight"].sum() == 4 + legacy_flat = Path(legacy.filepath) + legacy_bytes = legacy_flat.read_bytes() + with pytest.raises(FileNotFoundError): + load_datasets(datasets=[selector], years=[2024]) + + (rebuilt,) = ensure_datasets( + datasets=[selector], years=[2024], allow_unmanaged=True ).values() - assert legacy_files.requests == [] # current, so nothing is cut again - assert ensured.metadata[RECORD_KEY] == loaded.metadata[RECORD_KEY] + (reopened,) = load_datasets(datasets=[selector], years=[2024]).values() + assert reopened.filepath == rebuilt.filepath != legacy.filepath + assert reopened.data.household["household_weight"].sum() == 12 + assert legacy_flat.read_bytes() == legacy_bytes + + +def test_legacy_release_catalog_name_rebuilds_through_its_pinned_uri( + tmp_path, monkeypatch, legacy_acs_uri +): + key, uri, _, _, registered, download = legacy_acs_uri + alias = "fixture_catalog_dataset" + catalog = SimpleNamespace(artifacts={alias: SimpleNamespace(uri=uri)}) + monkeypatch.setattr(manifest, "get_data_release_manifest", lambda country: catalog) + kwargs = {"years": [2024], "data_folder": str(tmp_path / "data")} + (initial,) = create_datasets(datasets=[key], **kwargs).values() + write_year_file_stamp(initial.filepath, year_file_stamp()) + download.reset_mock() + + (rebuilt,) = ensure_datasets(datasets=[alias], **kwargs).values() + (reopened,) = load_datasets(datasets=[alias], **kwargs).values() + + assert reopened.filepath == rebuilt.filepath == initial.filepath + assert LegacySPMRecord.model_validate( + reopened.metadata[RECORD_KEY] + ).profile == expected_profile(registered) + download.assert_not_called() def test_a_year_without_a_declaration_is_refused_not_guessed(legacy_files): @@ -799,24 +1881,32 @@ def test_other_sources_get_no_declarations(tmp_path): @pytest.fixture -def rebuild_files(tmp_path, monkeypatch): - """Serve a synthetic source as the bundle's certified ACS-local file.""" +def rebuild_source(tmp_path): + """Store the rebuilt source's SPM roles and raw measurement evidence.""" frames = _source_frames() frames["person"][INDEPENDENCE_ROLE] = REBUILD_ROLES + frames["household"]["state_fips"] = [53, 6, 6, 6] + frames["household"]["congressional_district_geoid"] = [5301, 601, 602, 601] path = tmp_path / "populace_us_2024_acs_local.h5" with pd.HDFStore(path, mode="w") as store: for entity, frame in frames.items(): store.put(entity, frame, format="table", data_columns=True) store.put("_time_period", pd.Series([2024]), format="table") + return path + + +@pytest.fixture +def rebuild_files(rebuild_source, monkeypatch): + """Serve a synthetic source as the bundle's certified ACS-local file.""" requests = [] def materialize(country, dataset=None, **kwargs): requests.append(dataset) - return _bundle_source(path, REBUILD.source_sha256) + return _bundle_source(rebuild_source, REBUILD.source_sha256) for module in (us_datasets, us_model, declarations): monkeypatch.setattr(module, "materialize_dataset", materialize) - return SimpleSources(source=str(path), requests=requests) + return SimpleSources(source=str(rebuild_source), requests=requests) def test_the_bundle_certifies_the_rebuild(): @@ -885,3 +1975,86 @@ def test_a_managed_simulation_of_the_rebuild_masks_group_quarters(rebuild_files) assert recorded.model_mode == "override" assert recorded.outside_spm_units == 2 assert recorded.independence_list_people is None + + +@pytest.mark.usefixtures("extend_only_through_2024") +@pytest.mark.parametrize( + ("region_code", "expected_spm_units"), + [ + (None, [1, 2, 3, 4, 5]), + ("state/ca", [2, 3, 4, 5]), + ("congressional_district/CA-01", [2, 4, 5]), + ], + ids=["unscoped", "state", "district"], +) +def test_managed_microsimulation_of_pinned_acs_local_uri_applies_declarations( + tmp_path, monkeypatch, rebuild_source, region_code, expected_spm_units +): + from policyengine_core.reforms import Reform + + from policyengine.countries.us import us_region_registry + + monkeypatch.chdir(tmp_path) + bundle = manifest.get_release_manifest("us").model_copy(deep=True) + key = bundle.bundled_dataset_key("populace_us_2024_acs_local") + assert key is not None + reference = bundle.datasets[key] + assert reference.sha256 == REBUILD.source_sha256 + reference.sha256 = sha256_file(rebuild_source) + source = REBUILD.model_copy(update={"source_sha256": reference.sha256}) + monkeypatch.setattr(registry, "LEGACY_SPM_SOURCES", (source,)) + for module in (manifest, dataset_materialization): + monkeypatch.setattr(module, "get_release_manifest", lambda country: bundle) + uri = manifest.resolve_dataset_reference("us", key) + scoping_strategy = None + if region_code is not None: + region = us_region_registry.get(region_code) + assert region is not None + assert region.dataset_path == uri + assert region.scoping_strategy is not None + uri = region.dataset_path + scoping_strategy = region.scoping_strategy + response = MagicMock(status_code=200) + response.__enter__.return_value = response + response.iter_content.return_value = [rebuild_source.read_bytes()] + download = MagicMock(return_value=response) + monkeypatch.setattr(dataset_materialization.requests, "get", download) + + reform = Reform.from_dict( + { + "gov.irs.deductions.standard.amount.SINGLE": { + "2024-01-01.2100-12-31": 100_000 + } + }, + country_id="us", + ) + simulation = pe.us.managed_microsimulation( + dataset=uri, + allow_unmanaged=True, + scoping_strategy=scoping_strategy, + reform=reform, + ) + + download.assert_called_once() + assert RECORD_KEY in simulation.policyengine_bundle + recorded = LegacySPMRecord.model_validate( + simulation.policyengine_bundle[RECORD_KEY] + ) + assert recorded.profile == expected_profile(source) + assert recorded.model_mode == "override" + assert recorded.outside_spm_units == 2 + assert simulation.policyengine_bundle["runtime_dataset_sha256"] == reference.sha256 + if scoping_strategy is not None: + assert ( + simulation.policyengine_bundle["scoping"]["cache_key"] + == scoping_strategy.cache_key + ) + outside = np.isin(expected_spm_units, OUTSIDE_UNITS) + for branch in (simulation, simulation.baseline): + assert branch.calculate("spm_unit_id", 2024).tolist() == expected_spm_units + assert np.isfinite(branch.calculate("income_tax", 2024).values).all() + thresholds = branch.calculate("spm_unit_spm_threshold", 2024).values + np.testing.assert_array_equal(np.isnan(thresholds), outside) + assert np.isfinite(thresholds[~outside]).all() + in_poverty = branch.calculate("spm_unit_is_in_spm_poverty", 2024).values + np.testing.assert_array_equal(np.isnan(in_poverty), outside) diff --git a/tests/test_us_long_term_datasets.py b/tests/test_us_long_term_datasets.py index db5237846..4cba963c1 100644 --- a/tests/test_us_long_term_datasets.py +++ b/tests/test_us_long_term_datasets.py @@ -10,11 +10,13 @@ from microdf import MicroDataFrame import policyengine.tax_benefit_models.us.datasets as us_datasets_module +from policyengine.provenance import dataset_materialization from policyengine.provenance.dataset_materialization import ( DatasetMaterializationError, DatasetSource, MaterializedDataset, ) +from policyengine.provenance.manifest import ArtifactPathReference, get_release_manifest from policyengine.tax_benefit_models.us.datasets import ( PolicyEngineUSDataset, USYearData, @@ -440,6 +442,38 @@ def test__load_managed_long_term_datasets__requests_file_in_data_folder( ) +def test_managed_long_term_reads_local_metadata_with_a_verified_raw_copy( + monkeypatch, tmp_path +): + h5_path = tmp_path / "long_term" / "2100.h5" + h5_path.parent.mkdir() + _write_us_h5(h5_path, 2100) + _write_metadata(h5_path, 2100) + bundle = get_release_manifest("us").model_copy(deep=True) + key = "long_term_cps_2100" + bundle.datasets[key] = ArtifactPathReference( + path=h5_path.relative_to(tmp_path).as_posix(), + sha256=_sha256(h5_path), + ) + for module in (dataset_materialization, us_datasets_module): + monkeypatch.setattr(module, "get_release_manifest", lambda country: bundle) + download = Mock(side_effect=AssertionError("The verified inputs are already local")) + monkeypatch.setattr(dataset_materialization.requests, "get", download) + + dataset = load_managed_long_term_datasets( + [2100], + data_folder=str(tmp_path), + required_policyengine_us_version="1.691.10", + require_runtime_policyengine_us_match=False, + )[key] + + assert Path(dataset.filepath) != h5_path + assert _sha256(Path(dataset.filepath)) == _sha256(h5_path) + assert dataset.metadata_filepath == f"{h5_path}.metadata.json" + assert dataset.metadata["profile"]["name"] == "ss-payroll-tob" + download.assert_not_called() + + def test__load_long_term_datasets__rejects_policyengine_us_version_mismatch( tmp_path, ): diff --git a/tests/test_us_managed_scope.py b/tests/test_us_managed_scope.py index 0ed8646db..4344d416a 100644 --- a/tests/test_us_managed_scope.py +++ b/tests/test_us_managed_scope.py @@ -160,9 +160,7 @@ def test_refuses_conflicting_eternity_inputs_and_orphan_groups(): scope_native_history(native, strategy) -def test_unsupported_strategy_and_legacy_spm_fail_before_country_construction( - monkeypatch, -): +def test_unsupported_strategy_fails_before_country_construction(monkeypatch): import policyengine_us from policyengine.core.scoping_strategy import RegionGroupStrategy @@ -176,9 +174,6 @@ def forbidden_constructor(*args, **kwargs): strategy = RowFilterStrategy(variable_name="state_fips", variable_value=41) with pytest.raises(ValueError, match="only RowFilterStrategy"): _managed(scoping_strategy=RegionGroupStrategy(members=[strategy])) - monkeypatch.setattr(us_model, "legacy_spm_source", lambda *args: object()) - with pytest.raises(ValueError, match="legacy SPM"): - _managed(scoping_strategy=strategy) @pytest.mark.parametrize("reform", [False, True])