From 646963a39598eb816774c477aa1a76b4503decd8 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 18 Nov 2026 13:58:26 -0500 Subject: [PATCH 01/12] Add Microcosm dataset and certification selectors --- .../microcosm-dataset-selectors.added.md | 1 + docs/bundles.md | 6 +- .../build-m-us-populace-certification.md | 6 +- .../runbooks/canonical-spm-development.md | 2 +- docs/engineering/skills/data-certification.md | 14 ++-- docs/microsim.md | 15 ++-- docs/release-bundles.md | 2 +- scripts/bundle.py | 2 +- scripts/certify_data_release.py | 11 ++- src/policyengine/provenance/certification.py | 12 ++- .../provenance/dataset_materialization.py | 6 +- src/policyengine/provenance/manifest.py | 22 ++++- .../tax_benefit_models/us/datasets.py | 21 +++-- tests/test_certify_data_release.py | 19 +++-- tests/test_microcosm_compatibility.py | 82 ++++++++++++++++++- tests/test_us_legacy_spm_integration.py | 36 +++++--- 16 files changed, 198 insertions(+), 59 deletions(-) create mode 100644 changelog.d/microcosm-dataset-selectors.added.md 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/docs/bundles.md b/docs/bundles.md index acaf3ab39..09f3015e7 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) ``` @@ -202,7 +202,7 @@ To certify a new data release from a data-producer manifest, run: ```bash python scripts/bundle.py certify-data \ --country uk \ - --data-producer populace \ + --data-producer microcosm \ --manifest-uri hf://dataset/policyengine/populace-uk-private@/releases//release_manifest.json ``` @@ -211,7 +211,7 @@ For US Microcosm releases, certify the Microcosm release manifest directly: ```bash python scripts/bundle.py certify-data \ --country us \ - --data-producer populace \ + --data-producer microcosm \ --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 diff --git a/docs/engineering/runbooks/build-m-us-populace-certification.md b/docs/engineering/runbooks/build-m-us-populace-certification.md index c69f77986..99077ee2f 100644 --- a/docs/engineering/runbooks/build-m-us-populace-certification.md +++ b/docs/engineering/runbooks/build-m-us-populace-certification.md @@ -33,8 +33,8 @@ 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 +NATIONAL_RELEASE_ID = +LOCAL_AREA_RELEASE_ID = MODEL_VERSION = ``` @@ -47,7 +47,7 @@ artifact. ```bash python scripts/bundle.py certify-data \ --country us \ - --data-producer populace \ + --data-producer microcosm \ --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" diff --git a/docs/engineering/runbooks/canonical-spm-development.md b/docs/engineering/runbooks/canonical-spm-development.md index 4e094bc52..9437fe6dd 100644 --- a/docs/engineering/runbooks/canonical-spm-development.md +++ b/docs/engineering/runbooks/canonical-spm-development.md @@ -168,7 +168,7 @@ Ordinary `check` passes for the staged draft; this is metadata consistency only. 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 + --country us --data-producer microcosm --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. diff --git a/docs/engineering/skills/data-certification.md b/docs/engineering/skills/data-certification.md index 545b1aad4..91760940d 100644 --- a/docs/engineering/skills/data-certification.md +++ b/docs/engineering/skills/data-certification.md @@ -22,7 +22,7 @@ Open the work on a fresh branch from current `main` (use a clean worktree if the checkout is dirty). ```bash -python scripts/bundle.py certify-data --country uk --data-producer populace \ +python scripts/bundle.py certify-data --country uk --data-producer microcosm \ --manifest-uri "hf://dataset/policyengine/populace-uk-private@/releases//release_manifest.json" ``` @@ -46,7 +46,7 @@ its `release` and `build` as strings, for example its own folder, at the commit that published it: ```bash -python scripts/bundle.py certify-data --country uk --data-producer populace \ +python scripts/bundle.py certify-data --country uk --data-producer microcosm \ --manifest-uri "hf://dataset/policyengine/populace-uk-private@/releases///release_manifest.json" ``` @@ -104,7 +104,7 @@ Microcosm national release with one of: `dataset_role: non_default_local_area`, as for the US below. ```bash - python scripts/bundle.py certify-data --country uk --data-producer populace \ + python scripts/bundle.py certify-data --country uk --data-producer microcosm \ --manifest-uri "hf://dataset/policyengine/populace-uk-private@/releases/microcosm-uk-2024-25-national/release_manifest.json" \ --regional-manifest-uri "hf://dataset/policyengine/populace-uk-private@/releases//release_manifest.json" \ --model-version "" @@ -118,7 +118,7 @@ Microcosm national release with one of: release whose households carry area codes: ```bash - python scripts/bundle.py certify-data --country uk --data-producer populace \ + python scripts/bundle.py certify-data --country uk --data-producer microcosm \ --manifest-uri "hf://dataset/policyengine/populace-uk-private@/releases/microcosm-uk-2024-25-national/release_manifest.json" \ --regional-manifest-uri "hf://model/policyengine/policyengine-uk-data-private@/releases//release_manifest.json" \ --regional-release-kind area_coded_national \ @@ -152,7 +152,7 @@ Microcosm national release with one of: --limitation "the dense cut's VAT predates the policyengine-uk VAT factor fix (#2187, 2.135.7); the dashboard holds a VAT limit" \ --output regional-input-surface.json - .venv/bin/python scripts/bundle.py certify-data --country uk --data-producer populace \ + .venv/bin/python scripts/bundle.py certify-data --country uk --data-producer microcosm \ --manifest-uri "hf://dataset/policyengine/populace-uk-private@/releases/microcosm-uk-2024-25-national/release_manifest.json" \ --regional-manifest-uri "" \ --accept-regional-model-mismatch "" \ @@ -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..1d9787fd4 100644 --- a/docs/microsim.md +++ b/docs/microsim.md @@ -128,10 +128,11 @@ 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 ) -dataset = datasets["populace_us_2024_2026"] +dataset = datasets["microcosm_us_2024_2026"] ``` The default US dataset is **Microcosm US 2024** — a Microcosm-built dataset @@ -144,7 +145,9 @@ 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. +directory is reused only after hash verification. The original US selectors +`populace_us_2024` and `populace_us_2024_acs_local` remain supported and select +the same certified artifacts. List datasets already known to the country: @@ -155,7 +158,7 @@ pe.us.load_datasets() # or pe.uk.load_datasets() ### 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 +finer geographic work: `microcosm_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 @@ -170,14 +173,14 @@ Two-line load: ```python import policyengine as pe -sim = pe.us.managed_microsimulation(dataset="populace_us_2024_acs_local") +sim = pe.us.managed_microsimulation(dataset="microcosm_us_2024_acs_local") ``` Or materialize it as a `PolicyEngineUSDataset` for `Simulation`: ```python -datasets = pe.us.ensure_datasets(datasets=["populace_us_2024_acs_local"], years=[2024]) -dataset = datasets["populace_us_2024_acs_local_2024"] +datasets = pe.us.ensure_datasets(datasets=["microcosm_us_2024_acs_local"], years=[2024]) +dataset = datasets["microcosm_us_2024_acs_local_2024"] ``` Because this file carries PUMA-assigned district, county, and state identifiers diff --git a/docs/release-bundles.md b/docs/release-bundles.md index b4f8199ec..d9be2cdf3 100644 --- a/docs/release-bundles.md +++ b/docs/release-bundles.md @@ -199,7 +199,7 @@ python scripts/bundle.py certify-data --country us \ US Microcosm certification uses the Microcosm release manifest directly: ```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//release_manifest.json" \ --regional-manifest-uri "hf://dataset/policyengine/populace-us@/releases//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..6db8e5475 100644 --- a/scripts/certify_data_release.py +++ b/scripts/certify_data_release.py @@ -7,7 +7,7 @@ Usage:: - python scripts/bundle.py certify-data --country uk --data-producer populace \\ + python scripts/bundle.py certify-data --country uk --data-producer microcosm \\ --manifest-uri "hf://dataset/policyengine/populace-uk-private@/releases//release_manifest.json" Pin the cut tag, never a branch: each cut rewrites ``releases//``. @@ -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 microcosm for UK, legacy otherwise. " + "The previous name populace remains accepted." + ), ) parser.add_argument( "--manifest-uri", @@ -189,7 +192,7 @@ def main(argv=None) -> int: / f"certify-{args.country}-{result.build_id or 'data'}.changed.md" ) fragment.write_text( - f"Certify the {args.country.upper()} {result.data_producer} " + f"Certify the {args.country.upper()} {result.display_data_producer} " f"data release `{result.build_id}` ({result.default_dataset}, " f"{result.model_package} {result.model_version}) into the " "PolicyEngine bundle manifest.\n" diff --git a/src/policyengine/provenance/certification.py b/src/policyengine/provenance/certification.py index 72a278903..ed52b4825 100644 --- a/src/policyengine/provenance/certification.py +++ b/src/policyengine/provenance/certification.py @@ -17,7 +17,7 @@ result = certify_data_release( country="uk", - data_producer="populace", + data_producer="microcosm", manifest_uri=( "hf://dataset/policyengine/populace-uk-private" "@microcosm-uk-2024-25-national-20261002T230158Z-5c6b3f68" @@ -216,6 +216,10 @@ class CertificationResult: model_version: str warnings: list[str] = field(default_factory=list) + @property + def display_data_producer(self) -> str: + return "microcosm" if self.data_producer == "populace" else self.data_producer + def summary(self) -> str: lines = [ f"certified {self.country}: {self.default_dataset} " @@ -223,7 +227,7 @@ def summary(self) -> str: f" manifest: {self.manifest_uri}", f" manifest sha256: {self.manifest_sha256}", f" model: {self.model_package}=={self.model_version}", - f" data-producer: {self.data_producer}", + f" data-producer: {self.display_data_producer}", f" wrote: {self.bundle_path}", ] for warning in self.warnings: @@ -1769,8 +1773,8 @@ def certify( def certification_strategy( country: str, data_producer: Optional[str] = None ) -> DataProducerCertificationStrategy: - producer = data_producer or ("populace" if country == "uk" else "legacy") - if producer == "populace": + producer = data_producer or ("microcosm" if country == "uk" else "legacy") + if producer in ("microcosm", "populace"): return MicrocosmDataProducerCertificationStrategy() if producer == "legacy": return LegacyDataProducerCertificationStrategy() diff --git a/src/policyengine/provenance/dataset_materialization.py b/src/policyengine/provenance/dataset_materialization.py index 28e8f60b9..2d34f8080 100644 --- a/src/policyengine/provenance/dataset_materialization.py +++ b/src/policyengine/provenance/dataset_materialization.py @@ -123,7 +123,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( @@ -169,7 +171,7 @@ def materialize_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, diff --git a/src/policyengine/provenance/manifest.py b/src/policyengine/provenance/manifest.py index 9b3aa3827..601762482 100644 --- a/src/policyengine/provenance/manifest.py +++ b/src/policyengine/provenance/manifest.py @@ -27,6 +27,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 +468,14 @@ 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.""" + if self.country_id == "us" and dataset not in self.datasets: + alias = US_MICROCOSM_DATASET_ALIASES.get(dataset) + if alias is not None and alias in self.datasets: + return alias + return dataset + @property def default_dataset_uri(self) -> str: if ( @@ -1330,7 +1346,7 @@ def resolve_dataset_reference(country_id: str, dataset: str) -> str: 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, @@ -1366,7 +1382,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 +1392,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..287502a30 100644 --- a/src/policyengine/tax_benefit_models/us/datasets.py +++ b/src/policyengine/tax_benefit_models/us/datasets.py @@ -18,6 +18,7 @@ materialize_dataset, ) from policyengine.provenance.manifest import ( + US_MICROCOSM_DATASET_ALIASES, dataset_logical_name, get_release_manifest, resolve_dataset_reference, @@ -422,7 +423,8 @@ 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 selector and year for named Microcosm US datasets, + or by artifact filename stem and year otherwise. """ from policyengine_us import Microsimulation @@ -438,6 +440,9 @@ def create_datasets( data_dir=Path(data_folder), ) dataset_stem = source.name + result_stem = dataset_stem + if dataset is not None and dataset in US_MICROCOSM_DATASET_ALIASES: + result_stem = dataset sim = Microsimulation(dataset=source.path, spm=resolve_spm_selection()) # The register the mapping below uses, stamped into each year file. stamp = year_file_stamp() @@ -621,7 +626,7 @@ def create_datasets( # whose write stopped part-way has no stamp and is cut again. write_year_file_stamp(us_dataset.filepath, stamp) - dataset_key = f"{dataset_stem}_{year}" + dataset_key = f"{result_stem}_{year}" result[dataset_key] = us_dataset return result @@ -657,8 +662,8 @@ def _managed_source_sha256(dataset: Optional[str]) -> Optional[str]: 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 + elif (key := manifest.bundled_dataset_key(dataset)) in manifest.datasets: + name = key else: name = next( ( @@ -699,13 +704,17 @@ 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 selector and year for named Microcosm US datasets, + or by artifact filename stem and year otherwise. """ 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) + result_stem = ( + dataset if dataset in US_MICROCOSM_DATASET_ALIASES else dataset_stem + ) for year in years: filepath = f"{data_folder}/{dataset_stem}_year_{year}.h5" if Path(filepath).exists(): @@ -735,7 +744,7 @@ def load_datasets( ) us_dataset.load() - dataset_key = f"{dataset_stem}_{year}" + dataset_key = f"{result_stem}_{year}" result[dataset_key] = us_dataset return result diff --git a/tests/test_certify_data_release.py b/tests/test_certify_data_release.py index b3bc472b7..c81ac73eb 100644 --- a/tests/test_certify_data_release.py +++ b/tests/test_certify_data_release.py @@ -630,8 +630,9 @@ def test__given_unknown_regional_role__then_rejects_it(self): class TestCertifyDataRelease: + @pytest.mark.parametrize("data_producer", ["microcosm", "populace"]) 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 +668,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,6 +683,7 @@ 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: microcosm" in result.summary() assert result.dataset_count == 3 assert result.build_id == UK_TAG assert result.bundle_path == bundle_path @@ -771,8 +773,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 +794,7 @@ def fake_main(argv: list[str]) -> int: "--country", "us", "--data-producer", - "populace", + producer, "--manifest-uri", MANIFEST_URI, "--regional-manifest-uri", @@ -814,7 +817,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 +1637,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 +1677,8 @@ def certify_temporary_bundle(**kwargs): "certify-data", "--country", "uk", + "--data-producer", + data_producer, "--manifest-uri", UK_NATIONAL_URI, "--model-version", @@ -1691,6 +1697,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_microcosm_compatibility.py b/tests/test_microcosm_compatibility.py index 89f96a7ec..816396fc9 100644 --- a/tests/test_microcosm_compatibility.py +++ b/tests/test_microcosm_compatibility.py @@ -13,6 +13,18 @@ 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, +) @pytest.mark.parametrize( @@ -75,7 +87,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 +104,68 @@ 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 +): + from policyengine.provenance import dataset_materialization + + 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( "current_path,legacy_path,expected_path", [ diff --git a/tests/test_us_legacy_spm_integration.py b/tests/test_us_legacy_spm_integration.py index 7d4c8c776..fc100ae14 100644 --- a/tests/test_us_legacy_spm_integration.py +++ b/tests/test_us_legacy_spm_integration.py @@ -598,18 +598,24 @@ def __init__(self, source, requests): self.requests = requests -def test_year_files_carry_the_declarations_for_every_year(tmp_path, legacy_files): +@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=["populace_us_2024_acs_local"], years=years, data_folder=data_folder - ) + 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}"] + dataset = created[f"{selector}_{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 +636,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"{selector}_{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 +735,17 @@ 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, selector ): - simulation = pe.us.managed_microsimulation(dataset="populace_us_2024_acs_local") + simulation = pe.us.managed_microsimulation(dataset=selector) + assert legacy_files.requests == [selector, LIST_PIN.bundle_dataset] + 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() From cdb13de60e320dde3c5d6edbf3998780cfefd89c Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 30 Nov 2026 22:00:34 -0500 Subject: [PATCH 02/12] Preserve published dataset and producer names through Microcosm aliases Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- docs/bundles.md | 2 +- docs/engineering/skills/data-certification.md | 10 +-- docs/microsim.md | 13 +-- scripts/certify_data_release.py | 8 +- src/policyengine/provenance/certification.py | 10 +-- .../tax_benefit_models/us/datasets.py | 17 +--- tests/test_certify_data_release.py | 59 +++++++++--- tests/test_microcosm_compatibility.py | 47 +++++++++- tests/test_us_legacy_spm_integration.py | 89 ++++++++++++++++++- 9 files changed, 204 insertions(+), 51 deletions(-) diff --git a/docs/bundles.md b/docs/bundles.md index 09f3015e7..d6f6f2d58 100644 --- a/docs/bundles.md +++ b/docs/bundles.md @@ -202,7 +202,7 @@ To certify a new data release from a data-producer manifest, run: ```bash python scripts/bundle.py certify-data \ --country uk \ - --data-producer microcosm \ + --data-producer populace \ --manifest-uri hf://dataset/policyengine/populace-uk-private@/releases//release_manifest.json ``` diff --git a/docs/engineering/skills/data-certification.md b/docs/engineering/skills/data-certification.md index 91760940d..910c5b1f1 100644 --- a/docs/engineering/skills/data-certification.md +++ b/docs/engineering/skills/data-certification.md @@ -22,7 +22,7 @@ Open the work on a fresh branch from current `main` (use a clean worktree if the checkout is dirty). ```bash -python scripts/bundle.py certify-data --country uk --data-producer microcosm \ +python scripts/bundle.py certify-data --country uk --data-producer populace \ --manifest-uri "hf://dataset/policyengine/populace-uk-private@/releases//release_manifest.json" ``` @@ -46,7 +46,7 @@ its `release` and `build` as strings, for example its own folder, at the commit that published it: ```bash -python scripts/bundle.py certify-data --country uk --data-producer microcosm \ +python scripts/bundle.py certify-data --country uk --data-producer populace \ --manifest-uri "hf://dataset/policyengine/populace-uk-private@/releases///release_manifest.json" ``` @@ -104,7 +104,7 @@ Microcosm national release with one of: `dataset_role: non_default_local_area`, as for the US below. ```bash - python scripts/bundle.py certify-data --country uk --data-producer microcosm \ + python scripts/bundle.py certify-data --country uk --data-producer populace \ --manifest-uri "hf://dataset/policyengine/populace-uk-private@/releases/microcosm-uk-2024-25-national/release_manifest.json" \ --regional-manifest-uri "hf://dataset/policyengine/populace-uk-private@/releases//release_manifest.json" \ --model-version "" @@ -118,7 +118,7 @@ Microcosm national release with one of: release whose households carry area codes: ```bash - python scripts/bundle.py certify-data --country uk --data-producer microcosm \ + python scripts/bundle.py certify-data --country uk --data-producer populace \ --manifest-uri "hf://dataset/policyengine/populace-uk-private@/releases/microcosm-uk-2024-25-national/release_manifest.json" \ --regional-manifest-uri "hf://model/policyengine/policyengine-uk-data-private@/releases//release_manifest.json" \ --regional-release-kind area_coded_national \ @@ -152,7 +152,7 @@ Microcosm national release with one of: --limitation "the dense cut's VAT predates the policyengine-uk VAT factor fix (#2187, 2.135.7); the dashboard holds a VAT limit" \ --output regional-input-surface.json - .venv/bin/python scripts/bundle.py certify-data --country uk --data-producer microcosm \ + .venv/bin/python scripts/bundle.py certify-data --country uk --data-producer populace \ --manifest-uri "hf://dataset/policyengine/populace-uk-private@/releases/microcosm-uk-2024-25-national/release_manifest.json" \ --regional-manifest-uri "" \ --accept-regional-model-mismatch "" \ diff --git a/docs/microsim.md b/docs/microsim.md index 1d9787fd4..77cd204b4 100644 --- a/docs/microsim.md +++ b/docs/microsim.md @@ -132,7 +132,7 @@ datasets = pe.us.ensure_datasets( years=[2024, 2026], data_folder="./data", # local cache directory ) -dataset = datasets["microcosm_us_2024_2026"] +dataset = datasets["populace_us_2024_2026"] ``` The default US dataset is **Microcosm US 2024** — a Microcosm-built dataset @@ -145,9 +145,12 @@ 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. The original US selectors -`populace_us_2024` and `populace_us_2024_acs_local` remain supported and select -the same certified artifacts. +directory is reused only after hash verification. 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. +The returned dictionary keys use the artifact filename stem and year. List datasets already known to the country: @@ -180,7 +183,7 @@ Or materialize it as a `PolicyEngineUSDataset` for `Simulation`: ```python datasets = pe.us.ensure_datasets(datasets=["microcosm_us_2024_acs_local"], years=[2024]) -dataset = datasets["microcosm_us_2024_acs_local_2024"] +dataset = datasets["populace_us_2024_acs_local_2024"] ``` Because this file carries PUMA-assigned district, county, and state identifiers diff --git a/scripts/certify_data_release.py b/scripts/certify_data_release.py index 6db8e5475..35336ce1c 100644 --- a/scripts/certify_data_release.py +++ b/scripts/certify_data_release.py @@ -7,7 +7,7 @@ Usage:: - python scripts/bundle.py certify-data --country uk --data-producer microcosm \\ + python scripts/bundle.py certify-data --country uk --data-producer populace \\ --manifest-uri "hf://dataset/policyengine/populace-uk-private@/releases//release_manifest.json" Pin the cut tag, never a branch: each cut rewrites ``releases//``. @@ -49,8 +49,8 @@ def main(argv=None) -> int: default=None, choices=["legacy", "microcosm", "populace"], help=( - "Data-producer strategy. Defaults to microcosm for UK, legacy otherwise. " - "The previous name populace remains accepted." + "Data-producer strategy. Defaults to populace for UK, legacy otherwise. " + "Use microcosm as an alias for populace." ), ) parser.add_argument( @@ -192,7 +192,7 @@ def main(argv=None) -> int: / f"certify-{args.country}-{result.build_id or 'data'}.changed.md" ) fragment.write_text( - f"Certify the {args.country.upper()} {result.display_data_producer} " + f"Certify the {args.country.upper()} {result.data_producer} " f"data release `{result.build_id}` ({result.default_dataset}, " f"{result.model_package} {result.model_version}) into the " "PolicyEngine bundle manifest.\n" diff --git a/src/policyengine/provenance/certification.py b/src/policyengine/provenance/certification.py index ed52b4825..9c6219332 100644 --- a/src/policyengine/provenance/certification.py +++ b/src/policyengine/provenance/certification.py @@ -17,7 +17,7 @@ result = certify_data_release( country="uk", - data_producer="microcosm", + data_producer="populace", manifest_uri=( "hf://dataset/policyengine/populace-uk-private" "@microcosm-uk-2024-25-national-20261002T230158Z-5c6b3f68" @@ -216,10 +216,6 @@ class CertificationResult: model_version: str warnings: list[str] = field(default_factory=list) - @property - def display_data_producer(self) -> str: - return "microcosm" if self.data_producer == "populace" else self.data_producer - def summary(self) -> str: lines = [ f"certified {self.country}: {self.default_dataset} " @@ -227,7 +223,7 @@ def summary(self) -> str: f" manifest: {self.manifest_uri}", f" manifest sha256: {self.manifest_sha256}", f" model: {self.model_package}=={self.model_version}", - f" data-producer: {self.display_data_producer}", + f" data-producer: {self.data_producer}", f" wrote: {self.bundle_path}", ] for warning in self.warnings: @@ -1773,7 +1769,7 @@ def certify( def certification_strategy( country: str, data_producer: Optional[str] = None ) -> DataProducerCertificationStrategy: - producer = data_producer or ("microcosm" if country == "uk" else "legacy") + producer = data_producer or ("populace" if country == "uk" else "legacy") if producer in ("microcosm", "populace"): return MicrocosmDataProducerCertificationStrategy() if producer == "legacy": diff --git a/src/policyengine/tax_benefit_models/us/datasets.py b/src/policyengine/tax_benefit_models/us/datasets.py index 287502a30..7a3e02fc7 100644 --- a/src/policyengine/tax_benefit_models/us/datasets.py +++ b/src/policyengine/tax_benefit_models/us/datasets.py @@ -18,7 +18,6 @@ materialize_dataset, ) from policyengine.provenance.manifest import ( - US_MICROCOSM_DATASET_ALIASES, dataset_logical_name, get_release_manifest, resolve_dataset_reference, @@ -423,8 +422,7 @@ def create_datasets( data_folder: Directory to save the dataset files Returns: - Datasets keyed by selector and year for named Microcosm US datasets, - or by artifact filename stem and year otherwise. + Datasets keyed by artifact filename stem and year. """ from policyengine_us import Microsimulation @@ -440,9 +438,6 @@ def create_datasets( data_dir=Path(data_folder), ) dataset_stem = source.name - result_stem = dataset_stem - if dataset is not None and dataset in US_MICROCOSM_DATASET_ALIASES: - result_stem = dataset sim = Microsimulation(dataset=source.path, spm=resolve_spm_selection()) # The register the mapping below uses, stamped into each year file. stamp = year_file_stamp() @@ -626,7 +621,7 @@ def create_datasets( # whose write stopped part-way has no stamp and is cut again. write_year_file_stamp(us_dataset.filepath, stamp) - dataset_key = f"{result_stem}_{year}" + dataset_key = f"{dataset_stem}_{year}" result[dataset_key] = us_dataset return result @@ -704,17 +699,13 @@ def load_datasets( data_folder: Directory containing the dataset files Returns: - Datasets keyed by selector and year for named Microcosm US datasets, - or by artifact filename stem and year otherwise. + 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) - result_stem = ( - dataset if dataset in US_MICROCOSM_DATASET_ALIASES else dataset_stem - ) for year in years: filepath = f"{data_folder}/{dataset_stem}_year_{year}.h5" if Path(filepath).exists(): @@ -744,7 +735,7 @@ def load_datasets( ) us_dataset.load() - dataset_key = f"{result_stem}_{year}" + dataset_key = f"{dataset_stem}_{year}" result[dataset_key] = us_dataset return result diff --git a/tests/test_certify_data_release.py b/tests/test_certify_data_release.py index c81ac73eb..9ed499f91 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 @@ -630,7 +631,7 @@ def test__given_unknown_regional_role__then_rejects_it(self): class TestCertifyDataRelease: - @pytest.mark.parametrize("data_producer", ["microcosm", "populace"]) + @pytest.mark.parametrize("data_producer", ["microcosm", "populace", None]) def test__given_fetched_microcosm_manifest__then_updates_bundle_manifest( self, tmp_path, data_producer ): @@ -683,15 +684,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: microcosm" in result.summary() + 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 @@ -732,17 +739,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"] == { @@ -757,7 +793,6 @@ 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 def test__given_us_without_data_producer__then_legacy_update_is_explicitly_unsupported( self, tmp_path diff --git a/tests/test_microcosm_compatibility.py b/tests/test_microcosm_compatibility.py index 816396fc9..b2c72f697 100644 --- a/tests/test_microcosm_compatibility.py +++ b/tests/test_microcosm_compatibility.py @@ -9,6 +9,7 @@ import numpy as np import pytest +from policyengine.provenance import dataset_materialization, manifest from policyengine.provenance.certification import ( MicrocosmDataProducerCertificationStrategy, certification_strategy, @@ -25,6 +26,7 @@ from policyengine.tax_benefit_models.common.model_version import ( build_runtime_dataset_provenance, ) +from policyengine.utils.hashing import sha256_file @pytest.mark.parametrize( @@ -114,8 +116,6 @@ def test_current_certification_strategy_preserves_the_published_producer( def test_us_dataset_alias_preserves_bundle_provenance( monkeypatch, tmp_path, current_name, legacy_name ): - from policyengine.provenance import dataset_materialization - def verified_file(spec): return MaterializedDataset( data_package_name=spec.data_package_name, @@ -166,6 +166,49 @@ def test_previous_us_selector_resolves_when_bundle_uses_current_key(): 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[f"populace_{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 == tmp_path / reference.path + 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_spm_integration.py b/tests/test_us_legacy_spm_integration.py index fc100ae14..255a35ff8 100644 --- a/tests/test_us_legacy_spm_integration.py +++ b/tests/test_us_legacy_spm_integration.py @@ -41,6 +41,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, @@ -73,6 +74,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") @@ -598,6 +600,89 @@ def __init__(self, source, requests): self.requests = requests +@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[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.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.parametrize( "selector", ["populace_us_2024_acs_local", "microcosm_us_2024_acs_local"] ) @@ -612,7 +697,7 @@ def test_year_files_carry_the_declarations_for_every_year( LIST_PIN.bundle_dataset, ] for year in years: - dataset = created[f"{selector}_{year}"] + dataset = created[f"populace_us_2024_acs_local_{year}"] assert ( Path(dataset.filepath).name == f"populace_us_2024_acs_local_year_{year}.h5" ) @@ -638,7 +723,7 @@ def test_year_files_carry_the_declarations_for_every_year( loaded = ensure_datasets( datasets=[selector], years=[YEAR], data_folder=data_folder - )[f"{selector}_{YEAR}"] + )[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() From e54b0d892f7883840b964e8806e9e3037d4c3a1d Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 1 Dec 2026 07:00:45 -0500 Subject: [PATCH 03/12] Separate US year files for distinct same-stem bundle artefacts Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- .../tax_benefit_models/us/datasets.py | 112 ++++++++++++++---- tests/test_us_legacy_spm_integration.py | 106 ++++++++++++++++- 2 files changed, 191 insertions(+), 27 deletions(-) diff --git a/src/policyengine/tax_benefit_models/us/datasets.py b/src/policyengine/tax_benefit_models/us/datasets.py index 7a3e02fc7..1d3aafc16 100644 --- a/src/policyengine/tax_benefit_models/us/datasets.py +++ b/src/policyengine/tax_benefit_models/us/datasets.py @@ -410,11 +410,11 @@ 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. + Distinct bundle artefacts with the same stem use separate subdirectories. + Stamp each file last with the register of renamed stored inputs and the + year-file format revision (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 @@ -429,15 +429,40 @@ def create_datasets( from policyengine.tax_benefit_models.us.spm import resolve_spm_selection dataset_requests: list[Optional[str]] = datasets or [None] - result = {} - for dataset in dataset_requests: - source = materialize_dataset( + sources = [ + materialize_dataset( "us", dataset, allow_unmanaged=allow_unmanaged, data_dir=Path(data_folder), ) - dataset_stem = source.name + for dataset in dataset_requests + ] + source_references = [ + ( + source.source_uri, + source.bundle_dataset.sha256 + if source.bundle_dataset is not None + else _managed_source_sha256(source.source_uri), + ) + for source in sources + ] + locations = _year_file_locations(source_references, data_folder) + result = {} + for source, (_, digest), (dataset_stem, year_folder) in zip( + sources, source_references, locations, strict=True + ): + # An explicit URI can name a bundle artefact without using the verified + # materialiser. Check it before writing to that artefact's subdirectory. + if ( + year_folder != data_folder + and source.bundle_dataset is None + and digest is not None + and sha256_file(source.path) != digest + ): + raise ValueError( + f"US dataset {source.source_uri!r} does not match 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() @@ -602,7 +627,7 @@ def create_datasets( 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=f"{year_folder}/{dataset_stem}_year_{year}.h5", year=int(year), metadata=metadata, data=USYearData( @@ -678,6 +703,47 @@ def _expected_legacy_spm_profile(dataset: Optional[str]) -> Optional[LegacySPMPr return expected_profile(source) if source is not None else None +def _year_file_locations( + sources: list[tuple[str, Optional[str]]], data_folder: str +) -> list[tuple[str, str]]: + """Return the result stem and cache folder for each source in a batch.""" + bundled_digests: dict[str, set[Optional[str]]] = {} + for reference in get_release_manifest("us").datasets.values(): + bundled_digests.setdefault(Path(reference.path).stem, set()).add( + reference.sha256 + ) + + locations = [] + selected: dict[str, str] = {} + for uri, digest in sources: + stem = dataset_logical_name(uri) + identity = digest or uri + 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 + if len(bundled_digests.get(stem, ())) > 1: + # Use a directory per source once the stem becomes ambiguous. + directory = hashlib.sha256(identity.encode()).hexdigest() + folder = f"{data_folder}/.policyengine-us-year-files/{directory}" + locations.append((stem, folder)) + return locations + + +def _resolve_year_file_locations( + datasets: list[str], data_folder: str +) -> list[tuple[str, str]]: + return _year_file_locations( + [ + (resolve_dataset_reference("us", dataset), _managed_source_sha256(dataset)) + for dataset in datasets + ], + data_folder, + ) + + def load_datasets( datasets: Optional[list[str]] = None, years: list[int] = [2024, 2025, 2026, 2027, 2028], @@ -703,11 +769,10 @@ def load_datasets( """ 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 dataset, (dataset_stem, year_folder) in zip(datasets, locations, strict=True): for year in years: - filepath = f"{data_folder}/{dataset_stem}_year_{year}.h5" + filepath = f"{year_folder}/{dataset_stem}_year_{year}.h5" if Path(filepath).exists(): problem = year_file_stamp_problem(filepath) if problem is not None: @@ -1372,13 +1437,11 @@ 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. + 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 @@ -1394,11 +1457,10 @@ def ensure_datasets( # 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) + for dataset, (dataset_stem, year_folder) in zip(datasets, locations, strict=True): for year in years: - filepath = Path(f"{data_folder}/{dataset_stem}_year_{year}.h5") + filepath = Path(f"{year_folder}/{dataset_stem}_year_{year}.h5") if not filepath.exists(): all_current = False continue diff --git a/tests/test_us_legacy_spm_integration.py b/tests/test_us_legacy_spm_integration.py index 255a35ff8..c105b969d 100644 --- a/tests/test_us_legacy_spm_integration.py +++ b/tests/test_us_legacy_spm_integration.py @@ -20,6 +20,8 @@ from __future__ import annotations import importlib +import shutil +from functools import partial from pathlib import Path import h5py @@ -524,9 +526,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) @@ -634,6 +638,104 @@ def unexpected_download(*args, **kwargs): return suffix, stem +@pytest.fixture(params=["us_2024", "us_2024_acs_local"], ids=["national", "local-area"]) +def bundle_with_same_stem_sources(request, tmp_path, monkeypatch): + """Cache two distinct verified files whose paths have the same stem.""" + 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), + ) + monkeypatch.chdir(tmp_path) + bundled = manifest.get_release_manifest("us") + old, new = (f"{spelling}_{request.param}" for spelling in ("populace", "microcosm")) + 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] = bundled.datasets[old].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, references + + +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]) + + +def test_same_stem_batch_refuses_distinct_sources_before_writing( + bundle_with_same_stem_sources, +): + old, new, _ = bundle_with_same_stem_sources + + with pytest.raises(ValueError, match="share the year-file result stem 'source'"): + create_datasets(datasets=[old, new], years=[2024]) + + assert not list(Path("./data").rglob("*_year_*.h5")) + + +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", From ddac5afc9e67dba67920b700d0ea94594af9ca51 Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 1 Dec 2026 07:00:45 -0500 Subject: [PATCH 04/12] Warn only about certified dataset selectors that stop resolving Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- src/policyengine/provenance/certification.py | 11 +-- src/policyengine/provenance/manifest.py | 18 +++-- tests/test_certify_data_release.py | 72 ++++++++++++++++++++ 3 files changed, 91 insertions(+), 10 deletions(-) diff --git a/src/policyengine/provenance/certification.py b/src/policyengine/provenance/certification.py index 9c6219332..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, @@ -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/manifest.py b/src/policyengine/provenance/manifest.py index 601762482..a9cece186 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 @@ -470,11 +471,7 @@ class CountryReleaseManifest(BaseModel): def bundled_dataset_key(self, dataset: str) -> str: """Resolve a public selector to the key recorded in this bundle.""" - if self.country_id == "us" and dataset not in self.datasets: - alias = US_MICROCOSM_DATASET_ALIASES.get(dataset) - if alias is not None and alias in self.datasets: - return alias - return dataset + return resolve_bundled_dataset_key(self.country_id, dataset, self.datasets) @property def default_dataset_uri(self) -> str: @@ -1341,6 +1338,17 @@ 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 resolve_dataset_reference(country_id: str, dataset: str) -> str: if "://" in dataset: return dataset diff --git a/tests/test_certify_data_release.py b/tests/test_certify_data_release.py index 9ed499f91..5768a3d4d 100644 --- a/tests/test_certify_data_release.py +++ b/tests/test_certify_data_release.py @@ -10,6 +10,7 @@ import pytest +from policyengine.provenance import manifest as provenance_manifest from policyengine.provenance.certification import ( US_STATE_CODES, CertificationError, @@ -794,6 +795,77 @@ def test__given_us_local_area_manifest__then_certifies_shared_regional_dataset( ) assert release["regional_release_kind"] == "local_area" + @pytest.mark.parametrize("keep_local_as_overlay", [False, True]) + def test_recertification_warns_only_about_us_selectors_that_stop_resolving( + self, tmp_path, monkeypatch, keep_local_as_overlay + ): + old_national = "populace_us_2024" + old_local = "populace_us_2024_acs_local" + new_national = "microcosm_us_2024" + new_local = "microcosm_us_2024_acs_local" + unrelated = "retired_us_dataset" + bundle_path = tmp_path / "manifest.json" + bundle_path.write_text(json.dumps(_bundle_source_payload())) + national = _microcosm_manifest_payload_without_regions() + local = _local_area_release_manifest_payload() + + def certify(primary, regional=None): + responses = [_response(primary)] + if regional is not None: + 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 regional is not None else None + ), + drop_regional_release=regional is None, + model_version="1.723.0", + bundle_path=bundle_path, + check_artifacts=False, + ) + + certify(national, 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)) + + national["default_datasets"]["national"] = new_national + national["artifacts"][new_national] = national["artifacts"].pop(old_national) + local["artifacts"][new_local] = local["artifacts"].pop(old_local) + result = certify(national, None if keep_local_as_overlay else 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 ): From ada238e06ea397e5467e4c47d230074fff204679 Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 1 Dec 2026 07:00:45 -0500 Subject: [PATCH 05/12] Document indexed US certification and derived year-file reuse Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- docs/bundles.md | 16 ++++---- .../build-m-us-populace-certification.md | 39 +++++++------------ .../runbooks/canonical-spm-development.md | 18 ++++++--- docs/microsim.md | 31 ++++++++------- docs/release-bundles.md | 16 +++----- 5 files changed, 60 insertions(+), 60 deletions(-) diff --git a/docs/bundles.md b/docs/bundles.md index d6f6f2d58..92410fae5 100644 --- a/docs/bundles.md +++ b/docs/bundles.md @@ -203,18 +203,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 microcosm \ - --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 99077ee2f..aa544a7ba 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 = -LOCAL_AREA_RELEASE_ID = -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 microcosm \ - --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: @@ -58,10 +49,10 @@ This one command: - rewrites `data_releases.us` in `src/policyengine/data/bundle/manifest.json` from the national release manifest (default dataset, per-artifact repo/revision/sha256 pins, certified artifact, certification block); -- runs `generate(check=False)`, which re-normalizes `manifest.json` and +- runs `generate(check=False)`, which renormalises `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 9437fe6dd..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 microcosm --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/microsim.md b/docs/microsim.md index 77cd204b4..4e6f190a2 100644 --- a/docs/microsim.md +++ b/docs/microsim.md @@ -143,16 +143,21 @@ 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. For either US selector -pair, `populace_us_2024` and `microcosm_us_2024` or +PolicyEngine.py verifies cached source artefacts 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. When the +bundle contains distinct artefacts with the same filename stem, PolicyEngine.py +uses the source SHA-256 to keep their 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. -The returned dictionary keys use the artifact filename stem and year. +select the same artefact when the bundle lists just one of them. If the bundle +records both spellings, each exact key selects its own artefact. +`create_datasets`, `load_datasets` and `ensure_datasets` return dictionaries keyed +by artefact filename stem and year. Request distinct artefacts with the same +stem separately so their result keys stay unique. -List datasets already known to the country: +Load the default dataset's previously created year files with `load_datasets`. ```python pe.us.load_datasets() # or pe.uk.load_datasets() @@ -160,8 +165,8 @@ pe.us.load_datasets() # or pe.uk.load_datasets() ### US local-area dataset -Alongside the certified national default, the bundle registers a US dataset for -finer geographic work: `microcosm_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 @@ -176,13 +181,13 @@ Two-line load: ```python import policyengine as pe -sim = pe.us.managed_microsimulation(dataset="microcosm_us_2024_acs_local") +sim = pe.us.managed_microsimulation(dataset="populace_us_2024_acs_local") ``` -Or materialize it as a `PolicyEngineUSDataset` for `Simulation`: +Use `ensure_datasets` to materialise it as a `PolicyEngineUSDataset` for `Simulation`. ```python -datasets = pe.us.ensure_datasets(datasets=["microcosm_us_2024_acs_local"], years=[2024]) +datasets = pe.us.ensure_datasets(datasets=["populace_us_2024_acs_local"], years=[2024]) dataset = datasets["populace_us_2024_acs_local_2024"] ``` diff --git a/docs/release-bundles.md b/docs/release-bundles.md index d9be2cdf3..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: - -```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: +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 --data-producer microcosm \ - --manifest-uri "hf://dataset/policyengine/populace-us@/releases//release_manifest.json" \ - --regional-manifest-uri "hf://dataset/policyengine/populace-us@/releases//release_manifest.json" \ + --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 "" ``` From ed22ad6d30682cb9b200c6a910e8fb35ceac9d00 Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 1 Dec 2026 07:01:58 -0500 Subject: [PATCH 06/12] Serve recertification prerequisites from test fixtures Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- tests/test_certify_data_release.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/test_certify_data_release.py b/tests/test_certify_data_release.py index 5768a3d4d..5b52eb1a4 100644 --- a/tests/test_certify_data_release.py +++ b/tests/test_certify_data_release.py @@ -809,6 +809,15 @@ def test_recertification_warns_only_about_us_selectors_that_stop_resolving( national = _microcosm_manifest_payload_without_regions() local = _local_area_release_manifest_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(primary, regional=None): responses = [_response(primary)] if regional is not None: From 705324d8f4b817393d62e4605de9ec4be046ae76 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 1 Dec 2026 09:22:07 -0500 Subject: [PATCH 07/12] Use American spelling in the new docs and comments The repository spells artifact, materialize and normalize the American way. Co-Authored-By: Claude Opus 5.5 --- .../runbooks/build-m-us-populace-certification.md | 2 +- docs/microsim.md | 12 ++++++------ src/policyengine/tax_benefit_models/us/datasets.py | 6 +++--- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/engineering/runbooks/build-m-us-populace-certification.md b/docs/engineering/runbooks/build-m-us-populace-certification.md index aa544a7ba..58f7dcf5f 100644 --- a/docs/engineering/runbooks/build-m-us-populace-certification.md +++ b/docs/engineering/runbooks/build-m-us-populace-certification.md @@ -49,7 +49,7 @@ This one command: - rewrites `data_releases.us` in `src/policyengine/data/bundle/manifest.json` from the national release manifest (default dataset, per-artifact repo/revision/sha256 pins, certified artifact, certification block); -- runs `generate(check=False)`, which renormalises `manifest.json` and +- 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-.changed.md`. diff --git a/docs/microsim.md b/docs/microsim.md index 4e6f190a2..b3f9c308e 100644 --- a/docs/microsim.md +++ b/docs/microsim.md @@ -143,18 +143,18 @@ 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 verifies cached source artefacts against the installed bundle's +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. When the -bundle contains distinct artefacts with the same filename stem, PolicyEngine.py +bundle contains distinct artifacts with the same filename stem, PolicyEngine.py uses the source SHA-256 to keep their 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 artefact when the bundle lists just one of them. If the bundle -records both spellings, each exact key selects its own artefact. +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 artefact filename stem and year. Request distinct artefacts with the same +by artifact filename stem and year. Request distinct artifacts with the same stem separately so their result keys stay unique. Load the default dataset's previously created year files with `load_datasets`. @@ -184,7 +184,7 @@ import policyengine as pe sim = pe.us.managed_microsimulation(dataset="populace_us_2024_acs_local") ``` -Use `ensure_datasets` to materialise 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]) diff --git a/src/policyengine/tax_benefit_models/us/datasets.py b/src/policyengine/tax_benefit_models/us/datasets.py index 1d3aafc16..e696e3803 100644 --- a/src/policyengine/tax_benefit_models/us/datasets.py +++ b/src/policyengine/tax_benefit_models/us/datasets.py @@ -411,7 +411,7 @@ def create_datasets( """Create PolicyEngineUSDataset instances from logical dataset names or URLs. Write each ``{dataset_stem}_year_{year}.h5`` file under the data folder. - Distinct bundle artefacts with the same stem use separate subdirectories. + Distinct bundle artifacts with the same stem use separate subdirectories. Stamp each file last with the register of renamed stored inputs and the year-file format revision (see ``legacy_inputs.YEAR_FILE_STAMP_H5_DATASET``). Both ``ensure_datasets`` and ``load_datasets`` check the stamp. @@ -452,8 +452,8 @@ def create_datasets( for source, (_, digest), (dataset_stem, year_folder) in zip( sources, source_references, locations, strict=True ): - # An explicit URI can name a bundle artefact without using the verified - # materialiser. Check it before writing to that artefact's subdirectory. + # An explicit URI can name a bundle artifact without using the verified + # materializer. Check it before writing to that artifact's subdirectory. if ( year_folder != data_folder and source.bundle_dataset is None From 47eb2d63fe0154052b9830031834950da8c48c7d Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 2 Dec 2026 16:07:14 -0500 Subject: [PATCH 08/12] Use each dataset source before the next, bind flat files to source pins and match local path spellings Round 3 found that create materialized every source before using any, that an old flat year file could load after two stems' pins converged, and that two spellings of one local file were refused as different sources. Create now checks result-key collisions first and uses each source before materializing the next. Managed flat files carry their source SHA-256, and a file with a stale or missing hash is regenerated. Local sources compare by resolved path. Tests cover each case, batch refusal across create, load and ensure, and recertification in both rename directions. The microsim guide and changelog record the cache migration. Co-Authored-By: Claude Opus 5.5 --- .../microcosm-dataset-selectors.added.md | 2 + docs/microsim.md | 30 +-- .../tax_benefit_models/us/datasets.py | 148 +++++++------- .../tax_benefit_models/us/legacy_inputs.py | 47 +++-- tests/test_certify_data_release.py | 42 ++-- tests/test_us_legacy_spm_integration.py | 190 +++++++++++++++++- 6 files changed, 339 insertions(+), 120 deletions(-) diff --git a/changelog.d/microcosm-dataset-selectors.added.md b/changelog.d/microcosm-dataset-selectors.added.md index 1a7a08e28..464b36784 100644 --- a/changelog.d/microcosm-dataset-selectors.added.md +++ b/changelog.d/microcosm-dataset-selectors.added.md @@ -1 +1,3 @@ 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. + +Managed US flat year files now record the source SHA-256. `ensure_datasets` regenerates them when the recorded hash is missing or differs from the bundle's pin. diff --git a/docs/microsim.md b/docs/microsim.md index b3f9c308e..c53773a69 100644 --- a/docs/microsim.md +++ b/docs/microsim.md @@ -145,9 +145,10 @@ remain available as named, non-default bundle datasets. 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. When the -bundle contains distinct artifacts with the same filename stem, PolicyEngine.py -uses the source SHA-256 to keep their year files separate. +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 +contains distinct artifacts with the same filename stem, PolicyEngine.py uses +the source SHA-256 to keep their 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 @@ -157,7 +158,9 @@ records both spellings, each exact key selects its own artifact. by artifact filename stem and year. Request distinct artifacts with the same stem separately so their result keys stay unique. -Load the default dataset's previously created year files with `load_datasets`. +Load the default dataset's current year files with `load_datasets`. Use +`ensure_datasets` to regenerate managed flat year files that lack a source +SHA-256. ```python pe.us.load_datasets() # or pe.uk.load_datasets() @@ -497,14 +500,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: @@ -519,6 +523,8 @@ 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 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/src/policyengine/tax_benefit_models/us/datasets.py b/src/policyengine/tax_benefit_models/us/datasets.py index e696e3803..3b8346c25 100644 --- a/src/policyengine/tax_benefit_models/us/datasets.py +++ b/src/policyengine/tax_benefit_models/us/datasets.py @@ -21,6 +21,7 @@ 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, @@ -413,7 +414,8 @@ def create_datasets( Write each ``{dataset_stem}_year_{year}.h5`` file under the data folder. Distinct bundle artifacts with the same stem use separate subdirectories. Stamp each file last with the register of renamed stored inputs and the - year-file format revision (see ``legacy_inputs.YEAR_FILE_STAMP_H5_DATASET``). + 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: @@ -429,43 +431,36 @@ def create_datasets( from policyengine.tax_benefit_models.us.spm import resolve_spm_selection dataset_requests: list[Optional[str]] = datasets or [None] - sources = [ - materialize_dataset( + locations = _resolve_year_file_locations( + datasets or [get_release_manifest("us").default_dataset], + data_folder, + allow_unmanaged=allow_unmanaged, + ) + result = {} + for dataset, (dataset_stem, year_folder, digest) in zip( + dataset_requests, locations, strict=True + ): + source = materialize_dataset( "us", dataset, allow_unmanaged=allow_unmanaged, data_dir=Path(data_folder), ) - for dataset in dataset_requests - ] - source_references = [ - ( - source.source_uri, - source.bundle_dataset.sha256 - if source.bundle_dataset is not None - else _managed_source_sha256(source.source_uri), - ) - for source in sources - ] - locations = _year_file_locations(source_references, data_folder) - result = {} - for source, (_, digest), (dataset_stem, year_folder) in zip( - sources, source_references, locations, strict=True - ): - # An explicit URI can name a bundle artifact without using the verified - # materializer. Check it before writing to that artifact's subdirectory. - if ( - year_folder != data_folder - and source.bundle_dataset is None - and digest is not None - and sha256_file(source.path) != digest - ): - raise ValueError( - f"US dataset {source.source_uri!r} does not match its bundle SHA-256." + if digest is not None: + # Explicit URIs can name pinned artifacts without a verified download. + actual_digest = ( + source.bundle_dataset.sha256 + if source.bundle_dataset is not None + else sha256_file(source.path) ) + if actual_digest != digest: + raise ValueError( + f"US dataset {source.source_uri!r} does not match " + "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 year_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) @@ -705,8 +700,8 @@ def _expected_legacy_spm_profile(dataset: Optional[str]) -> Optional[LegacySPMPr def _year_file_locations( sources: list[tuple[str, Optional[str]]], data_folder: str -) -> list[tuple[str, str]]: - """Return the result stem and cache folder for each source in a batch.""" +) -> list[tuple[str, str, Optional[str]]]: + """Return the result stem, cache folder and bundle pin for each source.""" bundled_digests: dict[str, set[Optional[str]]] = {} for reference in get_release_manifest("us").datasets.values(): bundled_digests.setdefault(Path(reference.path).stem, set()).add( @@ -717,7 +712,7 @@ def _year_file_locations( selected: dict[str, str] = {} for uri, digest in sources: stem = dataset_logical_name(uri) - identity = digest or uri + identity = digest or (uri if "://" in uri else str(Path(uri).resolve())) if selected.setdefault(stem, identity) != identity: raise ValueError( f"Distinct US datasets share the year-file result stem {stem!r}. " @@ -728,19 +723,42 @@ def _year_file_locations( # Use a directory per source once the stem becomes ambiguous. directory = hashlib.sha256(identity.encode()).hexdigest() folder = f"{data_folder}/.policyengine-us-year-files/{directory}" - locations.append((stem, folder)) + locations.append((stem, folder, digest)) return locations def _resolve_year_file_locations( - datasets: list[str], data_folder: str -) -> list[tuple[str, str]]: - return _year_file_locations( - [ - (resolve_dataset_reference("us", dataset), _managed_source_sha256(dataset)) - for dataset in datasets - ], - data_folder, + datasets: list[str], data_folder: str, *, allow_unmanaged: Optional[bool] = None +) -> list[tuple[str, str, Optional[str]]]: + """Plan year-file locations without materializing any source artifacts.""" + manifest = get_release_manifest("us") + default_uri = manifest.default_dataset_uri + sources = [] + for dataset in datasets: + selector = manifest.default_dataset if dataset == default_uri else dataset + if allow_unmanaged is None: + uri = resolve_dataset_reference("us", selector) + else: + uri = resolve_managed_dataset_reference( + "us", selector, allow_unmanaged=allow_unmanaged + ) + digest = _managed_source_sha256(selector) + if digest is None and uri != selector and "://" in uri: + digest = _managed_source_sha256(uri) + sources.append((uri, digest)) + return _year_file_locations(sources, data_folder) + + +def _cached_year_file_problem( + filepath: str | Path, dataset: str, flat_source_sha256: Optional[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. + stamp_problem = year_file_stamp_problem( + filepath, expected_source_sha256=flat_source_sha256 + ) + return stamp_problem or year_file_problem( + filepath, _expected_legacy_spm_profile(dataset) ) @@ -757,7 +775,8 @@ 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. Args: datasets: List of HuggingFace dataset paths (used to derive file names) @@ -770,28 +789,21 @@ def load_datasets( datasets = datasets or [get_release_manifest("us").default_dataset] result = {} locations = _resolve_year_file_locations(datasets, data_folder) - for dataset, (dataset_stem, year_folder) in zip(datasets, locations, strict=True): + for dataset, (dataset_stem, year_folder, digest) in zip( + datasets, locations, strict=True + ): for year in years: filepath = f"{year_folder}/{dataset_stem}_year_{year}.h5" if Path(filepath).exists(): - problem = year_file_stamp_problem(filepath) + problem = _cached_year_file_problem( + filepath, dataset, digest if year_folder == data_folder else None + ) 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()." ) - # 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) - ) - 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}", @@ -1439,6 +1451,7 @@ def ensure_datasets( 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. 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. @@ -1458,13 +1471,17 @@ def ensure_datasets( # it is created again rather than reused. all_current = True locations = _resolve_year_file_locations(datasets, data_folder) - for dataset, (dataset_stem, year_folder) in zip(datasets, locations, strict=True): + for dataset, (dataset_stem, year_folder, digest) in zip( + datasets, locations, strict=True + ): for year in years: filepath = Path(f"{year_folder}/{dataset_stem}_year_{year}.h5") if not filepath.exists(): all_current = False continue - problem = year_file_stamp_problem(filepath) + problem = _cached_year_file_problem( + filepath, dataset, digest if year_folder == data_folder else None + ) if problem is not None: all_current = False logger.warning( @@ -1473,19 +1490,6 @@ 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) diff --git a/src/policyengine/tax_benefit_models/us/legacy_inputs.py b/src/policyengine/tax_benefit_models/us/legacy_inputs.py index f108ccd54..5264e7216 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,16 @@ 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 +) -> 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. 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 +215,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 +253,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 +274,20 @@ 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: + 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/tests/test_certify_data_release.py b/tests/test_certify_data_release.py index 5b52eb1a4..6042383f5 100644 --- a/tests/test_certify_data_release.py +++ b/tests/test_certify_data_release.py @@ -796,18 +796,20 @@ def test__given_us_local_area_manifest__then_certifies_shared_regional_dataset( assert release["regional_release_kind"] == "local_area" @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 + self, tmp_path, monkeypatch, keep_local_as_overlay, old_prefix, new_prefix ): - old_national = "populace_us_2024" - old_local = "populace_us_2024_acs_local" - new_national = "microcosm_us_2024" - new_local = "microcosm_us_2024_acs_local" + 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())) - national = _microcosm_manifest_payload_without_regions() - local = _local_area_release_manifest_payload() monkeypatch.setattr( "policyengine.provenance.certification.head_release_file", @@ -818,9 +820,20 @@ def test_recertification_warns_only_about_us_selectors_that_stop_resolving( lambda *args: {"sha256": "d" * 64, "url": "https://example.test/wheel"}, ) - def certify(primary, regional=None): + 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 regional is not None: + 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", @@ -831,15 +844,15 @@ def certify(primary, regional=None): data_producer="microcosm", manifest_uri=MANIFEST_URI, regional_manifest_uri=( - US_LOCAL_AREA_MANIFEST_URI if regional is not None else None + US_LOCAL_AREA_MANIFEST_URI if local_name is not None else None ), - drop_regional_release=regional is None, + drop_regional_release=local_name is None, model_version="1.723.0", bundle_path=bundle_path, check_artifacts=False, ) - certify(national, local) + certify(old_national, old_local) previous = json.loads(bundle_path.read_text()) previous_datasets = previous["data_releases"]["us"]["datasets"] previous_datasets[unrelated] = { @@ -852,10 +865,7 @@ def certify(primary, regional=None): } bundle_path.write_text(json.dumps(previous)) - national["default_datasets"]["national"] = new_national - national["artifacts"][new_national] = national["artifacts"].pop(old_national) - local["artifacts"][new_local] = local["artifacts"].pop(old_local) - result = certify(national, None if keep_local_as_overlay else local) + result = certify(new_national, None if keep_local_as_overlay else new_local) updated = json.loads(bundle_path.read_text()) manifest = CountryReleaseManifest.model_validate( diff --git a/tests/test_us_legacy_spm_integration.py b/tests/test_us_legacy_spm_integration.py index c105b969d..da7ee1f0d 100644 --- a/tests/test_us_legacy_spm_integration.py +++ b/tests/test_us_legacy_spm_integration.py @@ -23,6 +23,7 @@ import shutil from functools import partial from pathlib import Path +from unittest.mock import MagicMock import h5py import numpy as np @@ -56,6 +57,10 @@ ensure_datasets, load_datasets, ) +from policyengine.tax_benefit_models.us.legacy_inputs import ( # noqa: E402 + write_year_file_stamp, + year_file_stamp, +) from policyengine.tax_benefit_models.us.legacy_spm import ( # noqa: E402 INDEPENDENCE_ROLE, RECORD_H5_DATASET, @@ -638,9 +643,8 @@ def unexpected_download(*args, **kwargs): return suffix, stem -@pytest.fixture(params=["us_2024", "us_2024_acs_local"], ids=["national", "local-area"]) -def bundle_with_same_stem_sources(request, tmp_path, monkeypatch): - """Cache two distinct verified files whose paths have the same stem.""" +@pytest.fixture +def extend_only_through_2024(monkeypatch): from policyengine_us.data import economic_assumptions monkeypatch.setattr( @@ -648,6 +652,13 @@ def bundle_with_same_stem_sources(request, tmp_path, monkeypatch): "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")) @@ -678,7 +689,63 @@ 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, references + 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 def test_same_stem_year_files_retain_their_source(bundle_with_same_stem_sources): @@ -708,17 +775,128 @@ def test_load_requires_the_requested_same_stem_year_file(bundle_with_same_stem_s 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, + 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'"): - create_datasets(datasets=[old, new], years=[2024]) + 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, monkeypatch, stub_explicit_hf_download +): + old, new, references = bundle_with_same_stem_sources + old_reference = references[old] + references[old] = old_reference.model_copy( + update={"sha256": references[new].sha256} + ) + # This is the non-default URI, so the explicit downloader will serve it. + uri = manifest.resolve_dataset_reference("us", new) + response = stub_explicit_hf_download.return_value.__enter__.return_value + wrong_source = Path("data") / old_reference.path + response.iter_content.return_value = [wrong_source.read_bytes()] + monkeypatch.setattr( + dataset_materialization.requests, "get", stub_explicit_hf_download + ) + + with pytest.raises(ValueError, match="bundle SHA-256"): + create_datasets(datasets=[uri], years=[2024], allow_unmanaged=True) + + stub_explicit_hf_download.assert_called_once() + assert not Path("data/source_year_2024.h5").exists() + + +@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=[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_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("operation", [create_datasets, load_datasets, ensure_datasets]) +def test_same_local_source_spellings_share_year_file(tmp_path, monkeypatch, operation): + monkeypatch.chdir(tmp_path) + source = _write_source(tmp_path / "sample.h5") + 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=["sample.h5", source], **kwargs) + + assert list(result) == ["sample_2024"] + dataset = result["sample_2024"] + assert Path(dataset.filepath) == data_folder / "sample_year_2024.h5" + assert pd.DataFrame(dataset.data.household)["household_weight"].sum() == 4 + + def test_managed_microsimulation_uses_each_exact_same_stem_source( bundle_with_same_stem_sources, ): From 1e8b7898666e86ece2423c5da981e768a1c3e6a9 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 2 Dec 2026 16:40:40 -0500 Subject: [PATCH 09/12] Record the flat year file cache change as a changed entry load_datasets now refuses a managed US flat year file whose recorded source SHA-256 is missing or differs from the bundle's pin, so files written by earlier releases need regenerating once. The changelog lists this under changed, and the microsim guide defines flat year files and says that ensure_datasets regenerates them. Co-Authored-By: Claude Opus 5.5 --- changelog.d/microcosm-dataset-selectors.added.md | 2 -- changelog.d/microcosm-dataset-selectors.changed.md | 1 + docs/microsim.md | 9 ++++++--- 3 files changed, 7 insertions(+), 5 deletions(-) create mode 100644 changelog.d/microcosm-dataset-selectors.changed.md diff --git a/changelog.d/microcosm-dataset-selectors.added.md b/changelog.d/microcosm-dataset-selectors.added.md index 464b36784..1a7a08e28 100644 --- a/changelog.d/microcosm-dataset-selectors.added.md +++ b/changelog.d/microcosm-dataset-selectors.added.md @@ -1,3 +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. - -Managed US flat year files now record the source SHA-256. `ensure_datasets` regenerates them when the recorded hash is missing or differs from the bundle's pin. diff --git a/changelog.d/microcosm-dataset-selectors.changed.md b/changelog.d/microcosm-dataset-selectors.changed.md new file mode 100644 index 000000000..e9ac3431c --- /dev/null +++ b/changelog.d/microcosm-dataset-selectors.changed.md @@ -0,0 +1 @@ +Managed US flat year files now record their source SHA-256. `load_datasets` refuses a managed flat year file whose recorded hash is missing or differs from the bundle's pin, so year files written by earlier releases need regenerating once; `ensure_datasets` regenerates them. diff --git a/docs/microsim.md b/docs/microsim.md index c53773a69..ca001a0d0 100644 --- a/docs/microsim.md +++ b/docs/microsim.md @@ -158,9 +158,12 @@ records both spellings, each exact key selects its own artifact. by artifact filename stem and year. Request distinct artifacts with the same stem separately so their result keys stay unique. -Load the default dataset's current year files with `load_datasets`. Use -`ensure_datasets` to regenerate managed flat year files that lack a source -SHA-256. +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 lists two artifacts with the same 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, and +`ensure_datasets` regenerates it. ```python pe.us.load_datasets() # or pe.uk.load_datasets() From f416d83e40a8343e6b44978855db4f0088feac9c Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 2 Dec 2026 22:59:54 -0500 Subject: [PATCH 10/12] Rebuild pre-upgrade caches by exact pin, verify pinned downloads, defer local preflight - ensure_datasets maps an exact pinned URI to its bundle key and rebuilds a pre-upgrade flat year file through it; opt-in creation derives the legacy SPM declarations from the verified pin. load_datasets still refuses a pre-upgrade managed flat file until ensure_datasets rebuilds it. - A download whose URI exactly matches a pinned bundle artifact is verified before it replaces the raw cache, and year files are staged, stamped and validated before they replace a warm cache. - The batch planner treats absolute paths, symlinks and planned outputs as local inputs without resolving them, and checks each file when its request runs, so an earlier request in the batch can create it. - A flat file that records a source SHA-256 is refused for a request without an exact pin, conflicting URI pins are refused, and an unpinned same-stem entry no longer forces a split cache; the guide's split condition needs more than one distinct source SHA-256. Co-Authored-By: Claude Opus 5.5 --- .../microcosm-dataset-selectors.changed.md | 2 +- docs/microsim.md | 13 +- .../provenance/dataset_materialization.py | 33 +- src/policyengine/provenance/manifest.py | 53 +- .../tax_benefit_models/us/datasets.py | 294 ++++++---- .../tax_benefit_models/us/legacy_inputs.py | 8 +- tests/test_dataset_materialization.py | 57 ++ tests/test_us_legacy_inputs_integration.py | 59 +- tests/test_us_legacy_spm.py | 15 +- tests/test_us_legacy_spm_integration.py | 510 +++++++++++++++++- 10 files changed, 867 insertions(+), 177 deletions(-) diff --git a/changelog.d/microcosm-dataset-selectors.changed.md b/changelog.d/microcosm-dataset-selectors.changed.md index e9ac3431c..dd613a2e6 100644 --- a/changelog.d/microcosm-dataset-selectors.changed.md +++ b/changelog.d/microcosm-dataset-selectors.changed.md @@ -1 +1 @@ -Managed US flat year files now record their source SHA-256. `load_datasets` refuses a managed flat year file whose recorded hash is missing or differs from the bundle's pin, so year files written by earlier releases need regenerating once; `ensure_datasets` regenerates them. +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. diff --git a/docs/microsim.md b/docs/microsim.md index ca001a0d0..fe21f9319 100644 --- a/docs/microsim.md +++ b/docs/microsim.md @@ -147,8 +147,8 @@ 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 -contains distinct artifacts with the same filename stem, PolicyEngine.py uses -the source SHA-256 to keep their year files separate. +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 @@ -160,10 +160,11 @@ stem separately so their result keys stay unique. 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 lists two artifacts with the same 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, and -`ensure_datasets` regenerates it. +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. ```python pe.us.load_datasets() # or pe.uk.load_datasets() diff --git a/src/policyengine/provenance/dataset_materialization.py b/src/policyengine/provenance/dataset_materialization.py index 2d34f8080..db99523a5 100644 --- a/src/policyengine/provenance/dataset_materialization.py +++ b/src/policyengine/provenance/dataset_materialization.py @@ -161,10 +161,12 @@ def materialize_dataset( allow_unmanaged: bool = False, data_dir: Path = DEFAULT_DATA_DIR, ) -> DatasetSource: - """Select a dataset source and return the local file used for calculation.""" + """Select a local dataset, verifying the bytes of pinned bundle artifacts.""" 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, @@ -185,7 +187,18 @@ def materialize_dataset( allow_unmanaged=allow_unmanaged, ) if source_uri.startswith("hf://"): - return _download_hugging_face_dataset(source_uri, data_dir=data_dir) + key = manifest.bundled_dataset_key_for_uri(source_uri) + reference = manifest.datasets.get(key) if key is not None else None + return _download_hugging_face_dataset( + source_uri, + data_dir=data_dir, + expected_sha256=reference.sha256 if reference is not None else None, + pinned_repo_type=( + reference.repo_type or manifest.data_package.repo_type + if reference is not None + else None + ), + ) if "://" in source_uri: raise DatasetMaterializationError( f"Unsupported explicit dataset URI: {source_uri!r}." @@ -219,6 +232,8 @@ def _download_hugging_face_dataset( dataset_uri: str, *, data_dir: Path, + expected_sha256: Optional[str] = None, + pinned_repo_type: Optional[Literal["model", "dataset"]] = None, ) -> DatasetSource: path_with_repo, revision = ( dataset_uri[5:].rsplit("@", maxsplit=1) @@ -237,7 +252,10 @@ def _download_hugging_face_dataset( destination = data_dir / Path(repository_path).name destination.parent.mkdir(parents=True, exist_ok=True) - for repo_type in ("model", "dataset"): + repo_types = ( + (pinned_repo_type,) if pinned_repo_type is not None else ("model", "dataset") + ) + for repo_type in repo_types: file_descriptor, temp_name = tempfile.mkstemp( prefix=".policyengine-download-", suffix=destination.suffix or ".download", @@ -266,7 +284,7 @@ def _download_hugging_face_dataset( "access to the repository." ) if response.status_code == 404: - if repo_type == "model": + if pinned_repo_type is None and repo_type == "model": continue raise DatasetMaterializationError( f"Could not find explicit dataset {dataset_uri!r}." @@ -276,6 +294,13 @@ def _download_hugging_face_dataset( for chunk in response.iter_content(chunk_size=1024 * 1024): if chunk: output.write(chunk) + if ( + expected_sha256 is not None + and sha256_file(temporary_path) != expected_sha256 + ): + raise DatasetMaterializationError( + f"Dataset {dataset_uri!r} does not match its bundle SHA-256." + ) os.replace(temporary_path, destination) return DatasetSource(source_uri=dataset_uri, path=str(destination)) finally: diff --git a/src/policyengine/provenance/manifest.py b/src/policyengine/provenance/manifest.py index a9cece186..c1ed2096c 100644 --- a/src/policyengine/provenance/manifest.py +++ b/src/policyengine/provenance/manifest.py @@ -473,6 +473,49 @@ 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, + ) + 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 ( @@ -480,6 +523,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) @@ -1356,12 +1402,7 @@ def resolve_dataset_reference(country_id: str, dataset: str) -> str: manifest = get_release_manifest(country_id) 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(): diff --git a/src/policyengine/tax_benefit_models/us/datasets.py b/src/policyengine/tax_benefit_models/us/datasets.py index 3b8346c25..fe78b2618 100644 --- a/src/policyengine/tax_benefit_models/us/datasets.py +++ b/src/policyengine/tax_benefit_models/us/datasets.py @@ -2,10 +2,12 @@ import importlib.util import json import logging +import os 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 @@ -412,7 +414,7 @@ def create_datasets( """Create PolicyEngineUSDataset instances from logical dataset names or URLs. Write each ``{dataset_stem}_year_{year}.h5`` file under the data folder. - Distinct bundle artifacts with the same stem use separate subdirectories. + A stem with multiple distinct bundle pins uses separate subdirectories. 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``). @@ -435,11 +437,13 @@ def create_datasets( datasets or [get_release_manifest("us").default_dataset], data_folder, allow_unmanaged=allow_unmanaged, + years_to_create=years, ) result = {} - for dataset, (dataset_stem, year_folder, digest) in zip( - dataset_requests, locations, strict=True - ): + for dataset, location in zip(dataset_requests, locations, strict=True): + dataset_stem, year_folder, digest, source_uri = location + 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, @@ -447,7 +451,7 @@ def create_datasets( data_dir=Path(data_folder), ) if digest is not None: - # Explicit URIs can name pinned artifacts without a verified download. + # Confirm that the materialized source still matches the plan. actual_digest = ( source.bundle_dataset.sha256 if source.bundle_dataset is not None @@ -467,9 +471,7 @@ def create_datasets( # 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 @@ -618,11 +620,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"{year_folder}/{dataset_stem}_year_{year}.h5", + filepath=filepath, year=int(year), metadata=metadata, data=USYearData( @@ -636,10 +639,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 @@ -649,16 +662,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( @@ -668,97 +680,161 @@ 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 (key := manifest.bundled_dataset_key(dataset)) in manifest.datasets: - name = key + name: Optional[str] + if dataset is None: + name = manifest.default_dataset + elif "://" in dataset: + name = manifest.bundled_dataset_key_for_uri(dataset) else: - name = next( - ( - candidate - for candidate in manifest.datasets - if resolve_dataset_reference("us", candidate) == dataset - ), - None, - ) + name = manifest.bundled_dataset_key(dataset) reference = manifest.datasets.get(name) if name 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 -def _year_file_locations( - sources: list[tuple[str, Optional[str]]], data_folder: str -) -> list[tuple[str, str, Optional[str]]]: - """Return the result stem, cache folder and bundle pin for each source.""" - bundled_digests: dict[str, set[Optional[str]]] = {} - for reference in get_release_manifest("us").datasets.values(): - bundled_digests.setdefault(Path(reference.path).stem, set()).add( - reference.sha256 - ) +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" - locations = [] - selected: dict[str, str] = {} - for uri, digest in sources: - stem = dataset_logical_name(uri) - identity = digest or (uri if "://" in uri else str(Path(uri).resolve())) - 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 - if len(bundled_digests.get(stem, ())) > 1: - # Use a directory per source once the stem becomes ambiguous. - directory = hashlib.sha256(identity.encode()).hexdigest() - folder = f"{data_folder}/.policyengine-us-year-files/{directory}" - locations.append((stem, folder, digest)) - return locations + +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 -) -> list[tuple[str, str, Optional[str]]]: + 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 - sources = [] for dataset in datasets: selector = manifest.default_dataset if dataset == default_uri else dataset - if allow_unmanaged is None: + local_path = Path(selector).expanduser() + explicit_local = ( + allow_unmanaged is not False + and "://" not in selector + and manifest.bundled_dataset_key(selector) not in manifest.datasets + and ( + local_path.is_absolute() + or local_path.is_symlink() + or _cache_file_address(local_path) in planned_files + ) + ) + if explicit_local: + # A derived cache can outlive its raw file, and an earlier request + # may write this input. Check the raw file only when it is used. + 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 ) - digest = _managed_source_sha256(selector) + digest = _managed_source_sha256(dataset) if digest is None and uri != selector and "://" in uri: digest = _managed_source_sha256(uri) - sources.append((uri, digest)) - return _year_file_locations(sources, data_folder) + is_uri = "://" in uri + if is_uri: + stem = dataset_logical_name(uri) + identity = digest or uri + else: + stem = Path(uri).stem + identity = str(_local_identity(Path(uri), local_replacements)) + 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 + if len(bundled_digests.get(stem, ())) > 1: + # Use a directory per source once the stem becomes ambiguous. + 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://"): + reference = manifest.datasets.get(manifest.bundled_dataset_key(selector)) + raw_relative = ( + reference.path + if reference is not None + else Path(uri.rsplit("@", 1)[0]).name + ) + raw_path = Path(data_folder) / raw_relative + # Treat a managed link as replaceable when a predecessor may + # change the bytes behind it. Collision checks must finish before + # we download or write those bytes. + if ( + reference is None + or not raw_path.is_symlink() + or _local_identity(raw_path, planned_files) in planned_files + or not raw_path.is_file() + or sha256_file(raw_path) != reference.sha256 + ): + planned_files.add(_cache_file_address(raw_path)) + 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, dataset: str, flat_source_sha256: Optional[str] + 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_source_sha256 + 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(dataset) + filepath, _expected_legacy_spm_profile(location.source_sha256) ) @@ -789,21 +865,23 @@ def load_datasets( datasets = datasets or [get_release_manifest("us").default_dataset] result = {} locations = _resolve_year_file_locations(datasets, data_folder) - for dataset, (dataset_stem, year_folder, digest) in zip( - datasets, locations, strict=True - ): + for location in locations: + dataset_stem = location.stem for year in years: - filepath = f"{year_folder}/{dataset_stem}_year_{year}.h5" - if Path(filepath).exists(): - problem = _cached_year_file_problem( - filepath, dataset, digest if year_folder == data_folder else None + filepath = location.filepath(year) + try: + Path(filepath).stat() + 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(filepath, 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()." ) - 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()." - ) us_dataset = PolicyEngineUSDataset( name=f"{dataset_stem}-year-{year}", description=f"US Dataset for year {year} based on {dataset_stem}", @@ -1452,6 +1530,7 @@ def ensure_datasets( 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. + An exact URI for a pinned bundle artifact can rebuild through its key. 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. @@ -1464,24 +1543,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 - locations = _resolve_year_file_locations(datasets, data_folder) - for dataset, (dataset_stem, year_folder, digest) in zip( - datasets, locations, strict=True - ): + locations = _resolve_year_file_locations( + datasets, data_folder, years_to_create=years + ) + for location in locations: for year in years: - filepath = Path(f"{year_folder}/{dataset_stem}_year_{year}.h5") + filepath = Path(location.filepath(year)) if not filepath.exists(): all_current = False continue - problem = _cached_year_file_problem( - filepath, dataset, digest if year_folder == data_folder else None - ) + problem = _cached_year_file_problem(filepath, location, data_folder) if problem is not None: all_current = False logger.warning( @@ -1493,10 +1571,16 @@ def ensure_datasets( 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 = [ + 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 5264e7216..f2404a55b 100644 --- a/src/policyengine/tax_benefit_models/us/legacy_inputs.py +++ b/src/policyengine/tax_benefit_models/us/legacy_inputs.py @@ -184,7 +184,10 @@ def write_year_file_stamp(path: str | Path, stamp: Mapping[str, Any]) -> None: def year_file_stamp_problem( - path: str | Path, *, expected_source_sha256: str | None = None + 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``. @@ -193,6 +196,7 @@ def year_file_stamp_problem( - 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 @@ -276,6 +280,8 @@ def year_file_stamp_problem( ) 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 diff --git a/tests/test_dataset_materialization.py b/tests/test_dataset_materialization.py index f7dfa04fa..452658ea9 100644 --- a/tests/test_dataset_materialization.py +++ b/tests/test_dataset_materialization.py @@ -4,14 +4,17 @@ 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 +233,60 @@ 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" if valid_download else verified + 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) + assert source.path == str(destination) + assert source.bundle_dataset is None + else: + with pytest.raises(DatasetMaterializationError, match="bundle SHA-256"): + materialize_dataset("uk", uri, allow_unmanaged=True, data_dir=tmp_path) + + assert destination.read_bytes() == verified + assert len(session.calls) == 1 + assert session.calls[0][0].startswith("https://huggingface.co/datasets/") + + +@pytest.mark.parametrize("field", ["sha256", "repo_type", "metadata_sha256"]) +def test_explicit_default_uri_refuses_conflicting_bundle_artifacts( + monkeypatch, tmp_path, field +): + manifest = _manifest() + reference = manifest.datasets[manifest.default_dataset] + manifest.datasets["duplicate"] = reference.model_copy( + update={field: "dataset" if field == "repo_type" else "e" * 64} + ) + monkeypatch.setattr( + dataset_materialization, "get_release_manifest", lambda _: manifest + ) + session = _Session() + monkeypatch.setattr(dataset_materialization.requests, "get", session.get) + + with pytest.raises(ValueError, match="matches conflicting bundle artifacts"): + materialize_dataset("uk", manifest.default_dataset_uri, data_dir=tmp_path) + + assert session.calls == [] + assert not list(tmp_path.iterdir()) + + 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_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 da7ee1f0d..8d5b7732f 100644 --- a/tests/test_us_legacy_spm_integration.py +++ b/tests/test_us_legacy_spm_integration.py @@ -23,6 +23,7 @@ import shutil from functools import partial from pathlib import Path +from types import SimpleNamespace from unittest.mock import MagicMock import h5py @@ -58,6 +59,7 @@ load_datasets, ) from policyengine.tax_benefit_models.us.legacy_inputs import ( # noqa: E402 + read_year_file_stamp, write_year_file_stamp, year_file_stamp, ) @@ -70,6 +72,7 @@ declarations, expected_profile, record, + registry, runs, ) from policyengine.tax_benefit_models.us.legacy_spm.model_adapter import ( # noqa: E402 @@ -748,6 +751,85 @@ def test_same_stem_year_file_path_changes_when_its_source_pin_changes( 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()) + + 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 + ) + with pytest.raises(ValueError, match="missing a bundle SHA-256"): + load_datasets( + datasets=[manifest.resolve_dataset_reference("us", new)], years=[2024] + ) + + def test_same_stem_year_files_retain_their_source(bundle_with_same_stem_sources): old, new, _ = bundle_with_same_stem_sources key = "source_2024" @@ -806,26 +888,27 @@ def stub_explicit_hf_download(tmp_path, monkeypatch): def test_create_requires_matching_bytes_before_stamping_a_managed_flat_year_file( - bundle_with_same_stem_sources, monkeypatch, stub_explicit_hf_download + bundle_with_same_stem_sources, stub_explicit_hf_download ): old, new, references = bundle_with_same_stem_sources old_reference = references[old] - references[old] = old_reference.model_copy( - update={"sha256": references[new].sha256} - ) + new_reference = references[new] + cached = Path("data/source.h5") + shutil.copyfile(Path("data") / new_reference.path, 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}) # This is the non-default URI, so the explicit downloader will serve it. uri = manifest.resolve_dataset_reference("us", new) response = stub_explicit_hf_download.return_value.__enter__.return_value wrong_source = Path("data") / old_reference.path response.iter_content.return_value = [wrong_source.read_bytes()] - monkeypatch.setattr( - dataset_materialization.requests, "get", stub_explicit_hf_download - ) with pytest.raises(ValueError, match="bundle SHA-256"): 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() @@ -853,6 +936,147 @@ def test_create_uses_each_source_before_materializing_the_next( stub_explicit_hf_download.assert_called_once() +@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("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(FileNotFoundError, 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 ): @@ -878,10 +1102,13 @@ def test_create_refuses_colliding_downloads_before_touching_the_cache( @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): +def test_same_local_source_spellings_share_year_file( + tmp_path, monkeypatch, operation, filename +): monkeypatch.chdir(tmp_path) - source = _write_source(tmp_path / "sample.h5") + source = _write_source(tmp_path / filename) data_folder = tmp_path / "data" kwargs = {"years": [2024], "data_folder": str(data_folder)} if operation is load_datasets: @@ -889,14 +1116,37 @@ def test_same_local_source_spellings_share_year_file(tmp_path, monkeypatch, oper else: kwargs["allow_unmanaged"] = True - result = operation(datasets=["sample.h5", source], **kwargs) + result = operation(datasets=[filename, source], **kwargs) - assert list(result) == ["sample_2024"] - dataset = result["sample_2024"] - assert Path(dataset.filepath) == data_folder / "sample_year_2024.h5" + 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, ): @@ -963,6 +1213,95 @@ def unexpected_rebuild(*args, **kwargs): 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.usefixtures("extend_only_through_2024") +def test_unmanaged_local_source_does_not_reuse_a_managed_flat_file( + tmp_path, bundle_with_renamed_artifact +): + suffix, stem = bundle_with_renamed_artifact + managed = f"populace_{suffix}" + source = tmp_path / "unmanaged" / f"{stem}.h5" + source.parent.mkdir() + _write_source(source, household_weight=3.0) + kwargs = {"years": [2024], "data_folder": str(tmp_path)} + (created,) = create_datasets(datasets=[managed], **kwargs).values() + assert pd.DataFrame(created.data.household)["household_weight"].sum() == 4 + + with pytest.raises(ValueError, match="records a source SHA-256"): + load_datasets(datasets=[str(source)], **kwargs) + (rebuilt,) = ensure_datasets( + datasets=[str(source)], allow_unmanaged=True, **kwargs + ).values() + assert rebuilt.filepath == created.filepath + assert pd.DataFrame(rebuilt.data.household)["household_weight"].sum() == 12 + assert read_year_file_stamp(rebuilt.filepath) == year_file_stamp() + with pytest.raises(ValueError, match="no source SHA-256"): + load_datasets(datasets=[managed], **kwargs) + + @pytest.mark.parametrize( "selector", ["populace_us_2024_acs_local", "microcosm_us_2024_acs_local"] ) @@ -1123,26 +1462,139 @@ 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) + reference = bundle.datasets[key].model_copy( + update={ + "path": f"release/fixture/{source.name}", + "sha256": registered.source_sha256, + "metadata_sha256": None, + } + ) + bundle.datasets[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("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 + 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 + assert managed_raw.read_bytes() == source.read_bytes() + if seed == "uri": + download.assert_called_once() + assert explicit_raw.read_bytes() == source.read_bytes() + else: + 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() - assert legacy_files.requests == [] # current, so nothing is cut again - assert ensured.metadata[RECORD_KEY] == loaded.metadata[RECORD_KEY] + + 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 + + +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): From 62ca4d1da21e2293764f7d229a9c41471488b2ad Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 3 Dec 2026 00:00:28 -0500 Subject: [PATCH 11/12] Record provenance for exact pinned URIs, check local inputs at planning, document local keys - Materialization returns the bundle provenance after it verifies a download whose URI exactly matches a bundle pin, so managed microsimulation records verified provenance for that URI and US runs apply the legacy SPM declarations registered for the pin. - Opt-in creation raises ValueError during planning for an explicit local file that no earlier request in the batch can produce. - New unpinned year files go to a source-specific path when their stem has a bundle pin, so alternating managed and unpinned requests reuse their own files instead of overwriting one flat file. - The guide and changelog cover full local stems such as sample@local, unpinned requests refusing hash-stamped flat files, and moving to source-specific paths. Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- .../microcosm-dataset-selectors.changed.md | 6 + docs/microsim.md | 30 +++- .../provenance/dataset_materialization.py | 49 ++--- .../tax_benefit_models/us/datasets.py | 53 ++++-- tests/test_dataset_materialization.py | 5 +- tests/test_us_legacy_spm_integration.py | 169 ++++++++++++++---- 6 files changed, 248 insertions(+), 64 deletions(-) diff --git a/changelog.d/microcosm-dataset-selectors.changed.md b/changelog.d/microcosm-dataset-selectors.changed.md index dd613a2e6..a01beb8ea 100644 --- a/changelog.d/microcosm-dataset-selectors.changed.md +++ b/changelog.d/microcosm-dataset-selectors.changed.md @@ -1 +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. + +Unpinned US requests refuse hash-stamped flat year files. When the bundle has a pin for the same filename stem, new unpinned year files go into a subdirectory keyed by the resolved local path or URI and leave managed files available. If the stem has one bundled SHA-256 and the new file is absent, `load_datasets` and `ensure_datasets` can still reuse a current flat year file whose stamp has no source hash. + +`managed_microsimulation` records verified source provenance for explicit Hugging Face URIs that exactly match a bundle pin. US runs also apply any legacy SPM declarations registered for that pin, including those for the ACS-local release. Managed scoping is unavailable for sources that require these declarations. diff --git a/docs/microsim.md b/docs/microsim.md index fe21f9319..d406a88fa 100644 --- a/docs/microsim.md +++ b/docs/microsim.md @@ -158,6 +158,15 @@ records both spellings, each exact key selects its own artifact. 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 its absolute source path or 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 @@ -170,6 +179,18 @@ an exact URI identifying the pinned artifact. pe.us.load_datasets() # or pe.uk.load_datasets() ``` +An unpinned request, such as a local path to a cached source or a Hugging Face +URI at a different revision, cannot reuse a hash-stamped flat year file. +When the bundle has a pin for the same filename stem, PolicyEngine.py writes +new unpinned year files under `.policyengine-us-year-files/`, using a +subdirectory keyed by the resolved local path or the URI. A bare Hugging Face +URI and its `@main` spelling use different subdirectories. +If that stem has one pinned SHA-256 and the new file is absent, `load_datasets` +and `ensure_datasets` can still reuse a current flat year file with no source +hash. Use `ensure_datasets(..., allow_unmanaged=True)` to build a missing or +stale unpinned year file from its source. That build leaves the bundled year +files available for bundle-key requests. + ### US local-area dataset For finer geographic work, select the bundled US local-area dataset with @@ -454,7 +475,11 @@ 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. US `managed_microsimulation` applies any legacy SPM declarations +registered for that pin, including those for the ACS-local release. Managed +scoping is unavailable for sources that require legacy SPM declarations. ## Renamed inputs in stored data @@ -529,6 +554,9 @@ A year file is out of date when: 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, including an unpinned request looking for an older + flat year file; - 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/src/policyengine/provenance/dataset_materialization.py b/src/policyengine/provenance/dataset_materialization.py index db99523a5..1a843aeb9 100644 --- a/src/policyengine/provenance/dataset_materialization.py +++ b/src/policyengine/provenance/dataset_materialization.py @@ -188,16 +188,17 @@ def materialize_dataset( ) if source_uri.startswith("hf://"): key = manifest.bundled_dataset_key_for_uri(source_uri) - reference = manifest.datasets.get(key) if key is not None else None + bundle = ( + _resolve_bundle_dataset( + country_id, key, data_dir=data_dir, manifest=manifest + ) + if key is not None + else None + ) return _download_hugging_face_dataset( source_uri, data_dir=data_dir, - expected_sha256=reference.sha256 if reference is not None else None, - pinned_repo_type=( - reference.repo_type or manifest.data_package.repo_type - if reference is not None - else None - ), + bundle=bundle, ) if "://" in source_uri: raise DatasetMaterializationError( @@ -232,8 +233,7 @@ def _download_hugging_face_dataset( dataset_uri: str, *, data_dir: Path, - expected_sha256: Optional[str] = None, - pinned_repo_type: Optional[Literal["model", "dataset"]] = None, + bundle: Optional[_BundleDatasetSpec] = None, ) -> DatasetSource: path_with_repo, revision = ( dataset_uri[5:].rsplit("@", maxsplit=1) @@ -252,9 +252,7 @@ def _download_hugging_face_dataset( destination = data_dir / Path(repository_path).name destination.parent.mkdir(parents=True, exist_ok=True) - repo_types = ( - (pinned_repo_type,) if pinned_repo_type is not None else ("model", "dataset") - ) + repo_types = (bundle.repo_type,) if bundle is not None else ("model", "dataset") for repo_type in repo_types: file_descriptor, temp_name = tempfile.mkstemp( prefix=".policyengine-download-", @@ -284,7 +282,7 @@ def _download_hugging_face_dataset( "access to the repository." ) if response.status_code == 404: - if pinned_repo_type is None and repo_type == "model": + if bundle is None and repo_type == "model": continue raise DatasetMaterializationError( f"Could not find explicit dataset {dataset_uri!r}." @@ -294,15 +292,26 @@ def _download_hugging_face_dataset( for chunk in response.iter_content(chunk_size=1024 * 1024): if chunk: output.write(chunk) - if ( - expected_sha256 is not None - and sha256_file(temporary_path) != expected_sha256 - ): - raise DatasetMaterializationError( - f"Dataset {dataset_uri!r} does not match its bundle SHA-256." + materialized = None + if bundle is not None: + if sha256_file(temporary_path) != bundle.sha256: + raise DatasetMaterializationError( + f"Dataset {dataset_uri!r} does not match its bundle SHA-256." + ) + materialized = MaterializedDataset( + data_package_name=bundle.data_package_name, + repo_type=bundle.repo_type, + revision=bundle.revision, + source_uri=dataset_uri, + sha256=bundle.sha256, + path=destination, ) os.replace(temporary_path, destination) - return DatasetSource(source_uri=dataset_uri, path=str(destination)) + return DatasetSource( + source_uri=dataset_uri, + path=str(destination), + bundle_dataset=materialized, + ) finally: temporary_path.unlink(missing_ok=True) diff --git a/src/policyengine/tax_benefit_models/us/datasets.py b/src/policyengine/tax_benefit_models/us/datasets.py index fe78b2618..3f589a2f8 100644 --- a/src/policyengine/tax_benefit_models/us/datasets.py +++ b/src/policyengine/tax_benefit_models/us/datasets.py @@ -415,6 +415,7 @@ def create_datasets( 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``). @@ -441,7 +442,9 @@ def create_datasets( ) result = {} for dataset, location in zip(dataset_requests, locations, strict=True): - dataset_stem, year_folder, digest, source_uri = location + 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( @@ -463,7 +466,7 @@ def create_datasets( "its bundle SHA-256." ) sim = Microsimulation(dataset=source.path, spm=resolve_spm_selection()) - flat_source_sha256 = digest if year_folder == data_folder else None + 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. @@ -706,10 +709,19 @@ class _YearFileLocation(NamedTuple): folder: str source_sha256: Optional[str] source_uri: str + legacy_flat_folder: Optional[str] = None def filepath(self, year: int) -> str: return f"{self.folder}/{self.stem}_year_{year}.h5" + def cached_filepath(self, year: int) -> str: + filepath = self.filepath(year) + if self.legacy_flat_folder is not None and not Path(filepath).exists(): + legacy_path = f"{self.legacy_flat_folder}/{Path(filepath).name}" + if Path(legacy_path).exists(): + return legacy_path + return filepath + def _cache_file_address(path: Path) -> Path: return Path(os.path.realpath(path.parent)) / path.name @@ -764,8 +776,8 @@ def _resolve_year_file_locations( ) ) if explicit_local: - # A derived cache can outlive its raw file, and an earlier request - # may write this input. Check the raw file only when it is used. + # 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) @@ -781,19 +793,33 @@ def _resolve_year_file_locations( stem = dataset_logical_name(uri) identity = digest or uri else: - stem = Path(uri).stem - identity = str(_local_identity(Path(uri), local_replacements)) + 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 - if len(bundled_digests.get(stem, ())) > 1: - # Use a directory per source once the stem becomes ambiguous. + pin_count = len(bundled_digests.get(stem, ())) + legacy_flat_folder = None + 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) + if pin_count == 1: + # The readers still validate a legacy flat file as unbound. + legacy_flat_folder = data_folder + location = _YearFileLocation(stem, folder, digest, uri, legacy_flat_folder) locations.append(location) if allow_unmanaged and uri.startswith("hf://"): reference = manifest.datasets.get(manifest.bundled_dataset_key(selector)) @@ -852,7 +878,8 @@ def load_datasets( 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. A managed flat year file must also - record the source SHA-256 pinned by the bundle. + record the source SHA-256 pinned by the bundle. An unpinned request + refuses a hash-stamped file, including at the legacy flat path. Args: datasets: List of HuggingFace dataset paths (used to derive file names) @@ -868,7 +895,7 @@ def load_datasets( for location in locations: dataset_stem = location.stem for year in years: - filepath = location.filepath(year) + filepath = location.cached_filepath(year) try: Path(filepath).stat() except FileNotFoundError as error: @@ -1531,6 +1558,8 @@ def ensure_datasets( inputs, year-file format revision and any required legacy SPM declarations. Managed flat year files must also record the bundle's source SHA-256. An exact URI for a pinned bundle artifact can rebuild through its key. + 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. @@ -1555,7 +1584,7 @@ def ensure_datasets( ) for location in locations: for year in years: - filepath = Path(location.filepath(year)) + filepath = Path(location.cached_filepath(year)) if not filepath.exists(): all_current = False continue diff --git a/tests/test_dataset_materialization.py b/tests/test_dataset_materialization.py index 452658ea9..b75df75f0 100644 --- a/tests/test_dataset_materialization.py +++ b/tests/test_dataset_materialization.py @@ -255,7 +255,10 @@ def test_explicit_bundle_uri_checks_pin_before_updating_raw_cache( if valid_download: source = materialize_dataset("uk", uri, allow_unmanaged=True, data_dir=tmp_path) assert source.path == str(destination) - assert source.bundle_dataset is None + assert source.bundle_dataset is not None + assert source.bundle_dataset.sha256 == reference.sha256 + assert source.bundle_dataset.path == destination + assert source.bundle_dataset.source_uri == uri else: with pytest.raises(DatasetMaterializationError, match="bundle SHA-256"): materialize_dataset("uk", uri, allow_unmanaged=True, data_dir=tmp_path) diff --git a/tests/test_us_legacy_spm_integration.py b/tests/test_us_legacy_spm_integration.py index 8d5b7732f..c0eef7e52 100644 --- a/tests/test_us_legacy_spm_integration.py +++ b/tests/test_us_legacy_spm_integration.py @@ -972,6 +972,29 @@ def test_batch_accepts_local_input_materialized_by_earlier_request( catalog.assert_not_called() +@pytest.mark.usefixtures("extend_only_through_2024") +@pytest.mark.parametrize("operation", [create_datasets, ensure_datasets]) +def test_batch_rejects_missing_local_input_before_materializing( + tmp_path, monkeypatch, operation +): + 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) + + with pytest.raises(ValueError, match=r"US dataset file not found: .*missing\.h5"): + operation(datasets=[source, str(tmp_path / "missing.h5")], **kwargs) + + materialize.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]) @@ -1000,7 +1023,7 @@ def test_year_file_reopens_without_raw_local_source( for dataset in (reopened, ensured): assert pd.DataFrame(dataset.data.household)["household_weight"].sum() == 4 - with pytest.raises(FileNotFoundError, match="US dataset file not found"): + with pytest.raises(ValueError, match="US dataset file not found"): create_datasets(allow_unmanaged=True, **kwargs) catalog.assert_not_called() @@ -1277,31 +1300,6 @@ def test_unmanaged_year_file_migration_preserves_bundle_enforcement( assert reopened.metadata == rebuilt.metadata -@pytest.mark.usefixtures("extend_only_through_2024") -def test_unmanaged_local_source_does_not_reuse_a_managed_flat_file( - tmp_path, bundle_with_renamed_artifact -): - suffix, stem = bundle_with_renamed_artifact - managed = f"populace_{suffix}" - source = tmp_path / "unmanaged" / f"{stem}.h5" - source.parent.mkdir() - _write_source(source, household_weight=3.0) - kwargs = {"years": [2024], "data_folder": str(tmp_path)} - (created,) = create_datasets(datasets=[managed], **kwargs).values() - assert pd.DataFrame(created.data.household)["household_weight"].sum() == 4 - - with pytest.raises(ValueError, match="records a source SHA-256"): - load_datasets(datasets=[str(source)], **kwargs) - (rebuilt,) = ensure_datasets( - datasets=[str(source)], allow_unmanaged=True, **kwargs - ).values() - assert rebuilt.filepath == created.filepath - assert pd.DataFrame(rebuilt.data.household)["household_weight"].sum() == 12 - assert read_year_file_stamp(rebuilt.filepath) == year_file_stamp() - with pytest.raises(ValueError, match="no source SHA-256"): - load_datasets(datasets=[managed], **kwargs) - - @pytest.mark.parametrize( "selector", ["populace_us_2024_acs_local", "microcosm_us_2024_acs_local"] ) @@ -1513,6 +1511,9 @@ def test_year_files_load_by_the_sources_uri_as_well_as_its_name( 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() @@ -1575,6 +1576,68 @@ def test_explicit_pinned_legacy_uri_creates_reopenable_year_file( assert loaded.metadata == created.metadata +@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(ValueError, match="records a source SHA-256"): + 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 + + +def test_unpinned_request_reopens_an_existing_unbound_flat_file( + bundle_with_same_stem_sources, +): + _, other_key, references = bundle_with_same_stem_sources + other_reference = references.pop(other_key) + raw_path = (Path("data") / other_reference.path).resolve() + selector = str(raw_path) + created = create_datasets(datasets=[selector], years=[2024], allow_unmanaged=True) + path = Path(created["source_2024"].filepath) + legacy_flat = Path("data/source_year_2024.h5") + path.replace(legacy_flat) + raw_path.unlink() + + for operation in (load_datasets, ensure_datasets): + loaded = operation(datasets=[selector], years=[2024])["source_2024"] + assert Path(loaded.filepath) == legacy_flat + assert loaded.data.household["household_weight"].sum() == 12 + + def test_legacy_release_catalog_name_rebuilds_through_its_pinned_uri( tmp_path, monkeypatch, legacy_acs_uri ): @@ -1630,8 +1693,8 @@ 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 path = tmp_path / "populace_us_2024_acs_local.h5" @@ -1639,15 +1702,21 @@ def rebuild_files(tmp_path, monkeypatch): 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(): @@ -1716,3 +1785,43 @@ 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") +def test_managed_microsimulation_of_pinned_acs_local_uri_applies_declarations( + tmp_path, monkeypatch, rebuild_source +): + monkeypatch.chdir(tmp_path) + key = "populace_us_2024_acs_local" + bundle = manifest.get_release_manifest("us").model_copy(deep=True) + 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) + assert manifest.resolve_region_dataset_path("us", "state", state_code="CA") == uri + 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) + + simulation = pe.us.managed_microsimulation(dataset=uri, allow_unmanaged=True) + + 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 + thresholds = simulation.calculate("spm_unit_spm_threshold", 2024).values + assert np.isnan(thresholds[[1, 2]]).all() + assert np.isfinite(thresholds[[0, 3, 4]]).all() + in_poverty = simulation.calculate("spm_unit_is_in_spm_poverty", 2024).values + assert np.isnan(in_poverty[[1, 2]]).all() From fb3fcd5467763e42f3de7f0642fae7463ae6e2be Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 3 Dec 2026 00:24:31 -0500 Subject: [PATCH 12/12] Hand models pin-specific raw paths, drop the wrong-source flat fallback, read year files from one snapshot Round 5 found five P1s in the cache-identity and provenance code. Legacy SPM declarations now come from the full verified input and align to scoped regional runs. Models receive pin-specific raw paths that other downloads cannot replace. Unpinned requests for a stem with a bundle pin use only their source-specific year file. Opted-in URI rebuilds keep the ordered raw-cache updates. Stamp, SPM record and tables load from one file snapshot. Exact URIs verify pinned metadata sidecars, ambiguity checks include the package name, and explicit relative paths and unpinned bundle keys fail in preflight. Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- .../microcosm-dataset-selectors.changed.md | 4 +- docs/bundles.md | 4 +- docs/microsim.md | 49 +-- .../provenance/dataset_materialization.py | 231 +++++++++---- src/policyengine/provenance/manifest.py | 9 + .../tax_benefit_models/us/datasets.py | 198 ++++++----- .../tax_benefit_models/us/model.py | 35 +- tests/test_dataset_materialization.py | 232 ++++++++++++- tests/test_dataset_runtime.py | 1 + tests/test_dataset_source.py | 19 ++ tests/test_microcosm_compatibility.py | 5 +- tests/test_us_legacy_spm_integration.py | 317 +++++++++++++++--- tests/test_us_long_term_datasets.py | 34 ++ tests/test_us_managed_scope.py | 7 +- 14 files changed, 892 insertions(+), 253 deletions(-) diff --git a/changelog.d/microcosm-dataset-selectors.changed.md b/changelog.d/microcosm-dataset-selectors.changed.md index a01beb8ea..b0a53997a 100644 --- a/changelog.d/microcosm-dataset-selectors.changed.md +++ b/changelog.d/microcosm-dataset-selectors.changed.md @@ -2,6 +2,6 @@ Managed US flat year files now record their source SHA-256. `load_datasets` refu 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. -Unpinned US requests refuse hash-stamped flat year files. When the bundle has a pin for the same filename stem, new unpinned year files go into a subdirectory keyed by the resolved local path or URI and leave managed files available. If the stem has one bundled SHA-256 and the new file is absent, `load_datasets` and `ensure_datasets` can still reuse a current flat year file whose stamp has no source hash. +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. US runs also apply any legacy SPM declarations registered for that pin, including those for the ACS-local release. Managed scoping is unavailable for sources that require these declarations. +`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 92410fae5..957d8cf62 100644 --- a/docs/bundles.md +++ b/docs/bundles.md @@ -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. diff --git a/docs/microsim.md b/docs/microsim.md index d406a88fa..18ec3deec 100644 --- a/docs/microsim.md +++ b/docs/microsim.md @@ -164,8 +164,8 @@ 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 its absolute source path or source symlink -after the source file has been removed. +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 @@ -173,23 +173,20 @@ 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. +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() ``` -An unpinned request, such as a local path to a cached source or a Hugging Face -URI at a different revision, cannot reuse a hash-stamped flat year file. -When the bundle has a pin for the same filename stem, PolicyEngine.py writes -new unpinned year files under `.policyengine-us-year-files/`, using a -subdirectory keyed by the resolved local path or the URI. A bare Hugging Face -URI and its `@main` spelling use different subdirectories. -If that stem has one pinned SHA-256 and the new file is absent, `load_datasets` -and `ensure_datasets` can still reuse a current flat year file with no source -hash. Use `ensure_datasets(..., allow_unmanaged=True)` to build a missing or -stale unpinned year file from its source. That build leaves the bundled year -files available for bundle-key requests. +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 @@ -237,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 @@ -477,9 +488,10 @@ the response is calculated. For managed simulations, `sim.policyengine_bundle` records the actual source 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. US `managed_microsimulation` applies any legacy SPM declarations -registered for that pin, including those for the ACS-local release. Managed -scoping is unavailable for sources that require legacy SPM declarations. +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 @@ -555,8 +567,7 @@ A year file is out of date when: - 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, including an unpinned request looking for an older - flat year file; + 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/src/policyengine/provenance/dataset_materialization.py b/src/policyengine/provenance/dataset_materialization.py index 1a843aeb9..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 @@ -154,14 +170,41 @@ 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 local dataset, verifying the bytes of pinned bundle artifacts.""" + """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: @@ -188,18 +231,16 @@ def materialize_dataset( ) if source_uri.startswith("hf://"): key = manifest.bundled_dataset_key_for_uri(source_uri) - bundle = ( - _resolve_bundle_dataset( - country_id, key, data_dir=data_dir, manifest=manifest + 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, ) - if key is not None - else None - ) - return _download_hugging_face_dataset( - source_uri, - data_dir=data_dir, - bundle=bundle, - ) + return _download_hugging_face_dataset(source_uri, data_dir=data_dir) if "://" in source_uri: raise DatasetMaterializationError( f"Unsupported explicit dataset URI: {source_uri!r}." @@ -207,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,7 +313,6 @@ def _download_hugging_face_dataset( dataset_uri: str, *, data_dir: Path, - bundle: Optional[_BundleDatasetSpec] = None, ) -> DatasetSource: path_with_repo, revision = ( dataset_uri[5:].rsplit("@", maxsplit=1) @@ -250,24 +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) - - repo_types = (bundle.repo_type,) if bundle is not None else ("model", "dataset") - for repo_type in repo_types: - file_descriptor, temp_name = tempfile.mkstemp( - prefix=".policyengine-download-", - suffix=destination.suffix or ".download", - dir=destination.parent, + if destination.name.casefold() == _VERIFIED_CACHE_DIRECTORY: + raise DatasetMaterializationError( + f"Explicit dataset URI {dataset_uri!r} uses a reserved cache directory." ) - os.close(file_descriptor) - temporary_path = Path(temp_name) + + for repo_type in ("model", "dataset"): 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(), @@ -282,7 +356,7 @@ def _download_hugging_face_dataset( "access to the repository." ) if response.status_code == 404: - if bundle is None and repo_type == "model": + if repo_type == "model": continue raise DatasetMaterializationError( f"Could not find explicit dataset {dataset_uri!r}." @@ -292,28 +366,8 @@ def _download_hugging_face_dataset( for chunk in response.iter_content(chunk_size=1024 * 1024): if chunk: output.write(chunk) - materialized = None - if bundle is not None: - if sha256_file(temporary_path) != bundle.sha256: - raise DatasetMaterializationError( - f"Dataset {dataset_uri!r} does not match its bundle SHA-256." - ) - materialized = MaterializedDataset( - data_package_name=bundle.data_package_name, - repo_type=bundle.repo_type, - revision=bundle.revision, - source_uri=dataset_uri, - sha256=bundle.sha256, - path=destination, - ) os.replace(temporary_path, destination) - return DatasetSource( - source_uri=dataset_uri, - path=str(destination), - bundle_dataset=materialized, - ) - finally: - temporary_path.unlink(missing_ok=True) + return DatasetSource(source_uri=dataset_uri, path=str(destination)) raise DatasetMaterializationError( f"Could not download explicit dataset {dataset_uri!r}." @@ -324,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: @@ -333,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: @@ -342,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(), @@ -393,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 c1ed2096c..c3bbbb6cf 100644 --- a/src/policyengine/provenance/manifest.py +++ b/src/policyengine/provenance/manifest.py @@ -500,6 +500,7 @@ def bundled_dataset_key_for_uri(self, uri: str) -> Optional[str]: 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() } @@ -1395,6 +1396,12 @@ def resolve_bundled_dataset_key( 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 @@ -1407,6 +1414,8 @@ def resolve_dataset_reference(country_id: str, dataset: str) -> str: 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) diff --git a/src/policyengine/tax_benefit_models/us/datasets.py b/src/policyengine/tax_benefit_models/us/datasets.py index 3f589a2f8..35f06556a 100644 --- a/src/policyengine/tax_benefit_models/us/datasets.py +++ b/src/policyengine/tax_benefit_models/us/datasets.py @@ -3,6 +3,7 @@ import json import logging import os +import shutil import warnings from importlib import metadata as importlib_metadata from pathlib import Path @@ -17,9 +18,12 @@ 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, @@ -452,19 +456,15 @@ def create_datasets( dataset, allow_unmanaged=allow_unmanaged, data_dir=Path(data_folder), + publish_legacy_basename=allow_unmanaged, ) - if digest is not None: - # Confirm that the materialized source still matches the plan. - actual_digest = ( - source.bundle_dataset.sha256 - if source.bundle_dataset is not None - else sha256_file(source.path) + 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." ) - if actual_digest != digest: - raise ValueError( - f"US dataset {source.source_uri!r} does not match " - "its bundle SHA-256." - ) sim = Microsimulation(dataset=source.path, spm=resolve_spm_selection()) flat_source_sha256 = digest if location.folder == data_folder else None stamp = year_file_stamp(source_sha256=flat_source_sha256) @@ -685,14 +685,11 @@ def _legacy_spm_declarations( def _managed_source_sha256(dataset: Optional[str]) -> Optional[str]: """Return the bundle pin for a year-file source, when it has one.""" manifest = get_release_manifest("us") - name: Optional[str] - if dataset is None: - name = manifest.default_dataset - elif "://" in dataset: - name = manifest.bundled_dataset_key_for_uri(dataset) + if dataset is not None and "://" in dataset: + key = manifest.bundled_dataset_key_for_uri(dataset) else: - name = manifest.bundled_dataset_key(dataset) - 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 @@ -709,19 +706,10 @@ class _YearFileLocation(NamedTuple): folder: str source_sha256: Optional[str] source_uri: str - legacy_flat_folder: Optional[str] = None def filepath(self, year: int) -> str: return f"{self.folder}/{self.stem}_year_{year}.h5" - def cached_filepath(self, year: int) -> str: - filepath = self.filepath(year) - if self.legacy_flat_folder is not None and not Path(filepath).exists(): - legacy_path = f"{self.legacy_flat_folder}/{Path(filepath).name}" - if Path(legacy_path).exists(): - return legacy_path - return filepath - def _cache_file_address(path: Path) -> Path: return Path(os.path.realpath(path.parent)) / path.name @@ -763,14 +751,24 @@ def _resolve_year_file_locations( local_replacements = planned_files if allow_unmanaged else set() default_uri = manifest.default_dataset_uri for dataset in datasets: - selector = manifest.default_dataset if dataset == default_uri else dataset + 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 manifest.bundled_dataset_key(selector) not in manifest.datasets + and reference is None and ( - local_path.is_absolute() + _is_explicit_local_path(selector) or local_path.is_symlink() or _cache_file_address(local_path) in planned_files ) @@ -785,10 +783,13 @@ def _resolve_year_file_locations( uri = resolve_managed_dataset_reference( "us", selector, allow_unmanaged=allow_unmanaged ) - digest = _managed_source_sha256(dataset) - if digest is None and uri != selector and "://" in uri: - digest = _managed_source_sha256(uri) 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 @@ -811,35 +812,37 @@ def _resolve_year_file_locations( ) folder = data_folder pin_count = len(bundled_digests.get(stem, ())) - legacy_flat_folder = None 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}" - if pin_count == 1: - # The readers still validate a legacy flat file as unbound. - legacy_flat_folder = data_folder - location = _YearFileLocation(stem, folder, digest, uri, legacy_flat_folder) + location = _YearFileLocation(stem, folder, digest, uri) locations.append(location) if allow_unmanaged and uri.startswith("hf://"): - reference = manifest.datasets.get(manifest.bundled_dataset_key(selector)) - raw_relative = ( - reference.path - if reference is not None - else Path(uri.rsplit("@", 1)[0]).name - ) - raw_path = Path(data_folder) / raw_relative - # Treat a managed link as replaceable when a predecessor may - # change the bytes behind it. Collision checks must finish before - # we download or write those bytes. - if ( - reference is None - or not raw_path.is_symlink() - or _local_identity(raw_path, planned_files) in planned_files - or not raw_path.is_file() - or sha256_file(raw_path) != reference.sha256 - ): + 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))) @@ -879,7 +882,7 @@ def load_datasets( WIC take-up draw. The error says why, and names the renames the file may 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 hash-stamped file, including at the legacy flat path. + refuses a file with a source hash in its stamp. Args: datasets: List of HuggingFace dataset paths (used to derive file names) @@ -895,27 +898,37 @@ def load_datasets( for location in locations: dataset_stem = location.stem for year in years: - filepath = location.cached_filepath(year) - try: - Path(filepath).stat() - 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(filepath, 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()." + 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()." + ) + 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, ) - 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 @@ -1497,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, @@ -1557,7 +1582,8 @@ def ensure_datasets( 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. - An exact URI for a pinned bundle artifact can rebuild through its key. + 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 @@ -1584,7 +1610,7 @@ def ensure_datasets( ) for location in locations: for year in years: - filepath = Path(location.cached_filepath(year)) + filepath = Path(location.filepath(year)) if not filepath.exists(): all_current = False continue @@ -1601,12 +1627,14 @@ def ensure_datasets( if all_current: return load_datasets(datasets=datasets, years=years, data_folder=data_folder) - 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) - ] + 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, 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_dataset_materialization.py b/tests/test_dataset_materialization.py index b75df75f0..a5bf50525 100644 --- a/tests/test_dataset_materialization.py +++ b/tests/test_dataset_materialization.py @@ -1,4 +1,5 @@ import hashlib +from pathlib import Path from unittest.mock import patch import pytest @@ -246,48 +247,247 @@ def test_explicit_bundle_uri_checks_pin_before_updating_raw_cache( monkeypatch.setattr(module, "get_release_manifest", lambda country: manifest) uri = resolve_dataset_reference("uk", key) destination = tmp_path / reference.path - original = b"old" if valid_download else verified + 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) - assert source.path == str(destination) + 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 == destination + 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="bundle SHA-256"): - materialize_dataset("uk", uri, allow_unmanaged=True, data_dir=tmp_path) - - assert destination.read_bytes() == verified + 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("field", ["sha256", "repo_type", "metadata_sha256"]) -def test_explicit_default_uri_refuses_conflicting_bundle_artifacts( - monkeypatch, tmp_path, field +@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() - reference = manifest.datasets[manifest.default_dataset] + 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: "dataset" if field == "repo_type" else "e" * 64} + 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) - with pytest.raises(ValueError, match="matches conflicting bundle artifacts"): - materialize_dataset("uk", manifest.default_dataset_uri, data_dir=tmp_path) + 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 == [] - assert not list(tmp_path.iterdir()) + + +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): 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 b2c72f697..4ead51a7e 100644 --- a/tests/test_microcosm_compatibility.py +++ b/tests/test_microcosm_compatibility.py @@ -171,7 +171,7 @@ def test_exact_us_selectors_resolve_to_their_own_artifacts( monkeypatch, tmp_path, suffix ): bundled = get_release_manifest("us") - original = bundled.datasets[f"populace_{suffix}"] + original = bundled.datasets[bundled.bundled_dataset_key(f"microcosm_{suffix}")] references = {} for spelling in ("populace", "microcosm"): path = tmp_path / f"{spelling}.h5" @@ -201,7 +201,8 @@ def unexpected_download(*args, **kwargs): source = materialize_dataset("us", selector, data_dir=tmp_path) artifact = source.bundle_dataset assert artifact is not None - assert artifact.path == tmp_path / reference.path + 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 diff --git a/tests/test_us_legacy_spm_integration.py b/tests/test_us_legacy_spm_integration.py index c0eef7e52..496b9a847 100644 --- a/tests/test_us_legacy_spm_integration.py +++ b/tests/test_us_legacy_spm_integration.py @@ -601,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: @@ -622,7 +622,7 @@ def bundle_with_renamed_artifact(request, tmp_path, monkeypatch): key = f"populace_{suffix}" source = Path(_write_source(tmp_path / f"{stem}.h5")) bundled = manifest.get_release_manifest("us") - reference = bundled.datasets[key].model_copy( + reference = bundled.datasets[bundled.bundled_dataset_key(key)].model_copy( update={ "path": source.name, "sha256": sha256_file(source), @@ -665,13 +665,14 @@ def bundle_with_same_stem_sources( 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] = bundled.datasets[old].model_copy( + references[key] = original.model_copy( update={ "path": relative.as_posix(), "sha256": sha256_file(path), @@ -817,6 +818,13 @@ def test_a_same_stem_entry_without_a_pin_does_not_split_the_cache( 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() @@ -824,10 +832,6 @@ def test_a_same_stem_entry_without_a_pin_does_not_split_the_cache( assert read_year_file_stamp(rebuilt.filepath)["source_sha256"] == ( references[old].sha256 ) - with pytest.raises(ValueError, match="missing a bundle SHA-256"): - load_datasets( - datasets=[manifest.resolve_dataset_reference("us", new)], years=[2024] - ) def test_same_stem_year_files_retain_their_source(bundle_with_same_stem_sources): @@ -894,17 +898,17 @@ def test_create_requires_matching_bytes_before_stamping_a_managed_flat_year_file old_reference = references[old] new_reference = references[new] cached = Path("data/source.h5") - shutil.copyfile(Path("data") / new_reference.path, cached) + 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}) - # This is the non-default URI, so the explicit downloader will serve it. + # 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 - wrong_source = Path("data") / old_reference.path response.iter_content.return_value = [wrong_source.read_bytes()] - with pytest.raises(ValueError, match="bundle SHA-256"): + 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() @@ -912,6 +916,24 @@ def test_create_requires_matching_bytes_before_stamping_a_managed_flat_year_file 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 @@ -936,6 +958,47 @@ def test_create_uses_each_source_before_materializing_the_next( 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"]) @@ -974,9 +1037,15 @@ def test_batch_accepts_local_input_materialized_by_earlier_request( @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 + 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 = { @@ -988,11 +1057,14 @@ def test_batch_rejects_missing_local_input_before_materializing( 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, str(tmp_path / "missing.h5")], **kwargs) + operation(datasets=[source, missing_path], **kwargs) materialize.assert_not_called() + catalog.assert_not_called() @pytest.mark.usefixtures("extend_only_through_2024") @@ -1441,10 +1513,15 @@ def test_a_run_straight_over_a_legacy_source_derives_the_declarations( "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, selector + legacy_files, monkeypatch, selector ): + 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" ) @@ -1473,14 +1550,15 @@ def legacy_acs_uri(tmp_path, monkeypatch, extend_only_through_2024): lambda *args, **kwargs: _bundle_source(independence_list, LIST_PIN.sha256), ) bundle = manifest.get_release_manifest("us").model_copy(deep=True) - reference = bundle.datasets[key].model_copy( + 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[key] = reference + bundle.datasets[installed_key] = reference for module in (manifest, dataset_materialization, us_datasets): monkeypatch.setattr(module, "get_release_manifest", lambda country: bundle) @@ -1493,6 +1571,69 @@ def legacy_acs_uri(tmp_path, monkeypatch, extend_only_through_2024): 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( @@ -1532,11 +1673,15 @@ def test_year_files_load_by_the_sources_uri_as_well_as_its_name( ).values() assert rebuilt.filepath == initial.filepath - assert managed_raw.read_bytes() == source.read_bytes() 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 @@ -1576,6 +1721,41 @@ def test_explicit_pinned_legacy_uri_creates_reopenable_year_file( 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 @@ -1592,7 +1772,7 @@ def test_unpinned_year_files_do_not_replace_managed_flat_files( managed = ensure_datasets(datasets=[managed_key], years=[2024])[result_key] flat_path = Path(managed.filepath) flat_bytes = flat_path.read_bytes() - with pytest.raises(ValueError, match="records a source SHA-256"): + with pytest.raises(FileNotFoundError): load_datasets(datasets=[selector], years=[2024]) with pytest.raises(ValueError, match="bypass"): ensure_datasets(datasets=[selector], years=[2024]) @@ -1619,23 +1799,31 @@ def unexpected_rebuild(*args, **kwargs): assert loaded.data.household["household_weight"].sum() == weight -def test_unpinned_request_reopens_an_existing_unbound_flat_file( - bundle_with_same_stem_sources, +@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 ): - _, other_key, references = bundle_with_same_stem_sources + 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) - created = create_datasets(datasets=[selector], years=[2024], allow_unmanaged=True) - path = Path(created["source_2024"].filepath) - legacy_flat = Path("data/source_year_2024.h5") - path.replace(legacy_flat) - raw_path.unlink() + selector = str(raw_path) if selector_kind == "local" else uri - for operation in (load_datasets, ensure_datasets): - loaded = operation(datasets=[selector], years=[2024])["source_2024"] - assert Path(loaded.filepath) == legacy_flat - assert loaded.data.household["household_weight"].sum() == 12 + (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() + (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( @@ -1697,6 +1885,8 @@ 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(): @@ -1788,12 +1978,26 @@ def test_a_managed_simulation_of_the_rebuild_masks_group_quarters(rebuild_files) @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 + 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) - key = "populace_us_2024_acs_local" 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) @@ -1802,14 +2006,34 @@ def test_managed_microsimulation_of_pinned_acs_local_uri_applies_declarations( for module in (manifest, dataset_materialization): monkeypatch.setattr(module, "get_release_manifest", lambda country: bundle) uri = manifest.resolve_dataset_reference("us", key) - assert manifest.resolve_region_dataset_path("us", "state", state_code="CA") == uri + 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) - simulation = pe.us.managed_microsimulation(dataset=uri, allow_unmanaged=True) + 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 @@ -1820,8 +2044,17 @@ def test_managed_microsimulation_of_pinned_acs_local_uri_applies_declarations( assert recorded.model_mode == "override" assert recorded.outside_spm_units == 2 assert simulation.policyengine_bundle["runtime_dataset_sha256"] == reference.sha256 - thresholds = simulation.calculate("spm_unit_spm_threshold", 2024).values - assert np.isnan(thresholds[[1, 2]]).all() - assert np.isfinite(thresholds[[0, 3, 4]]).all() - in_poverty = simulation.calculate("spm_unit_is_in_spm_poverty", 2024).values - assert np.isnan(in_poverty[[1, 2]]).all() + 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])