From 5ea3885d3ac94626e49c37ee2129d12a5d092939 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 16 Nov 2026 23:38:32 -0500 Subject: [PATCH 01/20] Allow explicit local US data without unused bundle certification (#760) [skip ci] --- changelog.d/760.fixed.md | 1 + .../provenance/dataset_materialization.py | 11 + .../common/model_version.py | 38 +++- .../tax_benefit_models/us/datasets.py | 6 + .../tax_benefit_models/us/model.py | 74 ++++++- tests/test_us_unmanaged_runtime.py | 201 ++++++++++++++++++ 6 files changed, 315 insertions(+), 16 deletions(-) create mode 100644 changelog.d/760.fixed.md create mode 100644 tests/test_us_unmanaged_runtime.py diff --git a/changelog.d/760.fixed.md b/changelog.d/760.fixed.md new file mode 100644 index 000000000..707736f98 --- /dev/null +++ b/changelog.d/760.fixed.md @@ -0,0 +1 @@ +Allow explicit local US datasets with `allow_unmanaged=True` to record unverified runtime provenance without certifying the unused default data bundle. Keep certification on bundled data, cached year files and managed simulation entrypoints. diff --git a/src/policyengine/provenance/dataset_materialization.py b/src/policyengine/provenance/dataset_materialization.py index 28e8f60b9..174f04ea4 100644 --- a/src/policyengine/provenance/dataset_materialization.py +++ b/src/policyengine/provenance/dataset_materialization.py @@ -152,6 +152,13 @@ def _resolve_bundle_dataset( ) +def _require_us_data_certification(): + """US data entrypoints call this before selecting any bundled data.""" + from policyengine.tax_benefit_models.us.model import us_latest + + return us_latest.require_data_certification() + + def materialize_dataset( country_id: str, dataset: Optional[str] = None, @@ -183,6 +190,8 @@ def materialize_dataset( allow_unmanaged=allow_unmanaged, ) if source_uri.startswith("hf://"): + if country_id == "us": + _require_us_data_certification() return _download_hugging_face_dataset(source_uri, data_dir=data_dir) if "://" in source_uri: raise DatasetMaterializationError( @@ -198,6 +207,8 @@ def _use_bundle_dataset( data_dir: Path, manifest: CountryReleaseManifest, ) -> DatasetSource: + if country_id == "us": + _require_us_data_certification() bundle_dataset = _reuse_or_download_bundle_files( _resolve_bundle_dataset( country_id, diff --git a/src/policyengine/tax_benefit_models/common/model_version.py b/src/policyengine/tax_benefit_models/common/model_version.py index 31fcc7eac..0b9d02a9b 100644 --- a/src/policyengine/tax_benefit_models/common/model_version.py +++ b/src/policyengine/tax_benefit_models/common/model_version.py @@ -130,6 +130,9 @@ class MicrosimulationModelVersion(TaxBenefitModelVersion): entity_variables: dict[str, list[str]] = {} """Variables to materialise per entity when writing output datasets.""" + defer_data_certification: ClassVar[bool] = False + """US may certify bundled data when selected; other countries stay eager.""" + # --- Construction ------------------------------------------------------ def __init__(self, **kwargs: Any) -> None: if not self.country_code or not self.package_name: @@ -161,14 +164,16 @@ def __init__(self, **kwargs: Any) -> None: stacklevel=2, ) - model_build_metadata = self._get_runtime_data_build_metadata() - data_certification = certify_data_release_compatibility( - self.country_code, - runtime_model_version=installed_model_version, - runtime_data_build_fingerprint=model_build_metadata.get( - "data_build_fingerprint" - ), - ) + data_certification = None + if not self.defer_data_certification: + model_build_metadata = self._get_runtime_data_build_metadata() + data_certification = certify_data_release_compatibility( + self.country_code, + runtime_model_version=installed_model_version, + runtime_data_build_fingerprint=model_build_metadata.get( + "data_build_fingerprint" + ), + ) super().__init__(**kwargs) self.release_manifest = manifest @@ -184,6 +189,23 @@ def __init__(self, **kwargs: Any) -> None: self._populate_variables(system) self._populate_parameters(system) + def require_data_certification(self): + """Certify the bundled data against the loaded runtime before using it.""" + from policyengine.provenance.loaded import loaded_versions + + installed = metadata.version(self.package_name) + loaded = loaded_versions().get(self.package_name) + if loaded is not None and loaded != installed: + raise ValueError("Installed country version changed after import") + build = self._get_runtime_data_build_metadata() + certification = certify_data_release_compatibility( + self.country_code, + runtime_model_version=installed, + runtime_data_build_fingerprint=build.get("data_build_fingerprint"), + ) + self.data_certification = certification + return certification + # --- Hooks ------------------------------------------------------------ @classmethod def _get_runtime_data_build_metadata(cls) -> dict[str, Optional[str]]: diff --git a/src/policyengine/tax_benefit_models/us/datasets.py b/src/policyengine/tax_benefit_models/us/datasets.py index 320a538a9..b935f0e6d 100644 --- a/src/policyengine/tax_benefit_models/us/datasets.py +++ b/src/policyengine/tax_benefit_models/us/datasets.py @@ -15,6 +15,7 @@ from policyengine.core import Dataset, YearData from policyengine.provenance.dataset_materialization import ( MaterializedDataset, + _require_us_data_certification, materialize_dataset, ) from policyengine.provenance.manifest import ( @@ -424,6 +425,7 @@ def create_datasets( Returns: Dictionary mapping dataset keys (e.g., "populace_us_2024") to PolicyEngineUSDataset objects """ + _require_us_data_certification() from policyengine_us import Microsimulation from policyengine.tax_benefit_models.us.spm import resolve_spm_selection @@ -701,6 +703,7 @@ def load_datasets( Returns: Dictionary mapping dataset keys (e.g., "populace_us_2024") to PolicyEngineUSDataset objects """ + _require_us_data_certification() datasets = datasets or [get_release_manifest("us").default_dataset] result = {} for dataset in datasets: @@ -1194,6 +1197,7 @@ def load_long_term_datasets( artifacts with sidecar metadata validation, including optional checks that the installed ``policyengine-us`` runtime matches the H5 build metadata. """ + _require_us_data_certification() result = {} root = Path(data_folder).expanduser() @@ -1282,6 +1286,7 @@ def load_managed_long_term_datasets( bundle-certified Hugging Face artifact and its certified metadata sidecar are downloaded there. """ + _require_us_data_certification() manifest = get_release_manifest("us") if required_policyengine_us_version is None: @@ -1388,6 +1393,7 @@ def ensure_datasets( Returns: Dictionary mapping dataset keys to PolicyEngineUSDataset objects """ + _require_us_data_certification() datasets = datasets or [get_release_manifest("us").default_dataset] # Check that every year file exists and is current. A year file cut diff --git a/src/policyengine/tax_benefit_models/us/model.py b/src/policyengine/tax_benefit_models/us/model.py index bdda192dd..b65145643 100644 --- a/src/policyengine/tax_benefit_models/us/model.py +++ b/src/policyengine/tax_benefit_models/us/model.py @@ -1,6 +1,7 @@ import datetime +from importlib import metadata from pathlib import Path -from typing import TYPE_CHECKING, Optional +from typing import TYPE_CHECKING, ClassVar, Optional import pandas as pd from microdf import MicroDataFrame @@ -65,6 +66,7 @@ class PolicyEngineUSLatest(MicrosimulationModelVersion): country_code = "us" package_name = "policyengine-us" group_entities = US_GROUP_ENTITIES + defer_data_certification: ClassVar[bool] = True model: TaxBenefitModel = us_model version: str = None @@ -148,6 +150,9 @@ def _get_runtime_data_build_metadata(cls) -> dict[str, Optional[str]]: return get_data_build_metadata() or {} def _load_system(self): + from policyengine.provenance.loaded import record_loaded_versions + + record_loaded_versions(("spm-calculator",)) from policyengine_us.system import system return system @@ -161,8 +166,20 @@ def _load_region_registry(self): def _dataset_class(self): return PolicyEngineUSDataset + @property + def release_bundle(self): + # A bundle receipt must never borrow the configured certificate when + # this runtime has not been checked against its bundled data. + self.require_data_certification() + return super().release_bundle + + def load(self, simulation): + self.require_data_certification() + return super().load(simulation) + # --- run ------------------------------------------------------------- def run(self, simulation: "Simulation") -> "Simulation": + self.require_data_certification() from policyengine_us import Microsimulation from policyengine.utils.parametric_reforms import ( @@ -553,6 +570,32 @@ def _build_simulation_from_dataset(self, microsim, dataset, system): return apply_legacy_input_renames(microsim, {dataset.year: stored_tables}) +def _unmanaged_local_runtime_provenance(source): + """Bind local data and actual runtime; assert no bundle certification.""" + from policyengine.provenance.loaded import loaded_versions + from policyengine.utils.hashing import sha256_file + + names = ("policyengine", "policyengine-us", "policyengine-core", "spm-calculator") + versions = {name: metadata.version(name) for name in names} + loaded = loaded_versions() + if any( + name in loaded and loaded[name] != version for name, version in versions.items() + ): + raise ValueError("Installed runtime changed after import") + provenance = build_runtime_dataset_provenance(source.source_uri, source.path, None) + provenance.update( + data_selection="explicit_local_unmanaged", + compatibility_basis="unverified_explicit_local_unmanaged", + certified_by=None, + model_package="policyengine-us", + model_version=versions["policyengine-us"], + policyengine_version=versions["policyengine"], + runtime_packages=versions, + runtime_dataset_sha256=sha256_file(Path(source.path)), + ) + return provenance + + def managed_microsimulation( *, dataset: Optional[str] = None, @@ -606,6 +649,16 @@ def managed_microsimulation( "Managed scoping does not support legacy SPM declarations." ) + explicit_local = ( + allow_unmanaged + and dataset is not None + and source.bundle_dataset is None + and "://" not in source.source_uri + and Path(source.path).is_file() + ) + local_provenance = ( + _unmanaged_local_runtime_provenance(source) if explicit_local else None + ) microsim = Microsimulation(dataset=source.path, spm=selection, **kwargs) scoping_record = None if scoping_strategy is not None: @@ -640,14 +693,19 @@ def managed_microsimulation( legacy_spm_record = declarations.record.model_copy( update={"model_mode": mode} ).model_dump(mode="json") - microsim.policyengine_bundle = dict(us_latest.release_bundle) - microsim.policyengine_bundle.update( - build_runtime_dataset_provenance( - source.source_uri, - source.path, - source.bundle_dataset, + if explicit_local: + if _unmanaged_local_runtime_provenance(source) != local_provenance: + raise ValueError( + "Unmanaged local data or runtime changed during construction" + ) + microsim.policyengine_bundle = local_provenance + else: + microsim.policyengine_bundle = dict(us_latest.release_bundle) + microsim.policyengine_bundle.update( + build_runtime_dataset_provenance( + source.source_uri, source.path, source.bundle_dataset + ) ) - ) microsim.policyengine_bundle["spm"] = dict(microsim.spm_config) microsim.policyengine_bundle[RENAMES_RECORD_KEY] = dict( sorted(legacy_input_renames.items()) diff --git a/tests/test_us_unmanaged_runtime.py b/tests/test_us_unmanaged_runtime.py new file mode 100644 index 000000000..37621ee43 --- /dev/null +++ b/tests/test_us_unmanaged_runtime.py @@ -0,0 +1,201 @@ +"""Keep managed US data strict while supporting explicit local experiments. + +The constructor tests use inert stubs and byte fixtures, not population data. +""" + +import hashlib +import importlib +from importlib import metadata +from types import SimpleNamespace + +import pytest + +import policyengine.provenance.dataset_materialization as materialization +import policyengine.tax_benefit_models.common.model_version as common +from policyengine.provenance import loaded +from policyengine.provenance.manifest import get_release_manifest + +us_model = importlib.import_module("policyengine.tax_benefit_models.us.model") +us_datasets = importlib.import_module("policyengine.tax_benefit_models.us.datasets") + + +def refuse_certification(*args, **kwargs): + raise ValueError("test incompatible bundled data") + + +@pytest.mark.parametrize("allow_unmanaged", [False, True]) +@pytest.mark.parametrize("selection", [None, "name", "uri"]) +def test_managed_selection_certifies_before_cache_or_download( + monkeypatch, selection, allow_unmanaged +): + manifest = get_release_manifest("us") + selected = {"name": manifest.default_dataset, "uri": manifest.default_dataset_uri} + monkeypatch.setattr( + materialization, "_require_us_data_certification", refuse_certification + ) + reuse = [] + monkeypatch.setattr( + materialization, "_reuse_or_download_bundle_files", lambda *a: reuse.append(a) + ) + + with pytest.raises(ValueError, match="incompatible bundled data"): + materialization.materialize_dataset( + "us", selected.get(selection), allow_unmanaged=allow_unmanaged + ) + + assert reuse == [] + + +def test_remote_unmanaged_source_keeps_certification(monkeypatch): + monkeypatch.setattr( + materialization, "_require_us_data_certification", refuse_certification + ) + with pytest.raises(ValueError, match="incompatible bundled data"): + materialization.materialize_dataset( + "us", "hf://example/other/fixture.h5@revision", allow_unmanaged=True + ) + + +def test_local_source_requires_opt_in_and_avoids_unused_bundle(monkeypatch, tmp_path): + path = tmp_path / "inert-local-fixture.bin" + path.write_bytes(b"test source plumbing only") + monkeypatch.setattr( + materialization, "_require_us_data_certification", refuse_certification + ) + with pytest.raises(ValueError, match="allow_unmanaged"): + materialization.materialize_dataset("us", str(path)) + + source = materialization.materialize_dataset("us", str(path), allow_unmanaged=True) + assert source.path == str(path) + assert source.bundle_dataset is None + + +@pytest.mark.parametrize( + "name", + [ + "create_datasets", + "load_datasets", + "load_long_term_datasets", + "load_managed_long_term_datasets", + "ensure_datasets", + ], +) +def test_year_helpers_certify_before_cached_data(monkeypatch, name): + monkeypatch.setattr( + us_datasets, "_require_us_data_certification", refuse_certification + ) + with pytest.raises(ValueError, match="incompatible bundled data"): + getattr(us_datasets, name)(years=[2017]) + + +@pytest.mark.parametrize("entry", ["run", "load", "release_bundle"]) +def test_managed_simulation_and_cached_output_keep_guard(monkeypatch, entry): + monkeypatch.setattr( + us_model.PolicyEngineUSLatest, + "require_data_certification", + refuse_certification, + ) + with pytest.raises(ValueError, match="incompatible bundled data"): + if entry == "release_bundle": + us_model.us_latest.release_bundle + else: + getattr(us_model.us_latest, entry)(None) + + +def test_only_us_defers_the_initial_certification(monkeypatch): + cls = us_model.PolicyEngineUSLatest + monkeypatch.setattr( + common, "certify_data_release_compatibility", refuse_certification + ) + monkeypatch.setattr(cls, "_load_region_registry", lambda self: None) + monkeypatch.setattr(cls, "_load_system", lambda self: None) + for name in ("_populate_entities", "_populate_variables", "_populate_parameters"): + monkeypatch.setattr(cls, name, lambda *args: None) + + model = cls() + assert model.data_certification is None + assert cls.defer_data_certification is True + assert common.MicrosimulationModelVersion.defer_data_certification is False + + +def test_uk_initialization_keeps_eager_certification(monkeypatch): + pytest.importorskip("policyengine_uk") + uk_model = importlib.import_module("policyengine.tax_benefit_models.uk.model") + monkeypatch.setattr( + common, "certify_data_release_compatibility", refuse_certification + ) + with pytest.raises(ValueError, match="incompatible bundled data"): + uk_model.PolicyEngineUKLatest() + + +def local_factory_fixture(monkeypatch, tmp_path, *, mutate=False): + """Return an explicit local source and a constructor that never loads it.""" + import policyengine_us + + path = tmp_path / "inert-local-fixture.bin" + path.write_bytes(b"test source plumbing only") + sim = SimpleNamespace(spm_config={}) + + def constructor(**kwargs): + assert kwargs["dataset"] == str(path) + if mutate: + path.write_bytes(b"different fixture bytes") + return sim + + monkeypatch.setattr(policyengine_us, "Microsimulation", constructor) + monkeypatch.setattr(us_model, "resolve_spm_selection", lambda spm: {}) + monkeypatch.setattr( + us_model, "apply_legacy_input_renames_to_microsimulation", lambda sim: {} + ) + monkeypatch.setattr( + us_model.PolicyEngineUSLatest, + "require_data_certification", + refuse_certification, + ) + return path, sim + + +def test_local_factory_records_actual_runtime_without_certificate( + monkeypatch, tmp_path +): + path, expected = local_factory_fixture(monkeypatch, tmp_path) + sim = us_model.managed_microsimulation(dataset=str(path), allow_unmanaged=True) + receipt = sim.policyengine_bundle + + assert sim is expected + assert receipt["compatibility_basis"] == "unverified_explicit_local_unmanaged" + assert receipt["certified_by"] is None + assert receipt["runtime_packages"] == { + name: metadata.version(name) + for name in ( + "policyengine", + "policyengine-us", + "policyengine-core", + "spm-calculator", + ) + } + assert ( + receipt["runtime_dataset_sha256"] + == hashlib.sha256(path.read_bytes()).hexdigest() + ) + assert not any(key.startswith("certified_data") for key in receipt) + + +def test_local_factory_refuses_source_changes_during_construction( + monkeypatch, tmp_path +): + path, _ = local_factory_fixture(monkeypatch, tmp_path, mutate=True) + with pytest.raises(ValueError, match="changed during construction"): + us_model.managed_microsimulation(dataset=str(path), allow_unmanaged=True) + + +def test_local_provenance_refuses_installed_loaded_drift(monkeypatch, tmp_path): + path = tmp_path / "inert-local-fixture.bin" + path.write_bytes(b"fixture") + original = loaded.loaded_versions() + monkeypatch.setattr( + loaded, "loaded_versions", lambda: {**original, "policyengine-us": "changed"} + ) + source = materialization.DatasetSource(source_uri=str(path), path=str(path)) + with pytest.raises(ValueError, match="changed after import"): + us_model._unmanaged_local_runtime_provenance(source) From 8ab66b5ca1746e2df3ac40c4c68b532a77bc9d2e Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 16 Nov 2026 23:50:11 -0500 Subject: [PATCH 02/20] Bind explicit native input periods before US construction (#760) [skip ci] --- changelog.d/760.fixed.md | 2 + docs/microsim.md | 18 ++- docs/receipts.md | 2 +- .../tax_benefit_models/us/model.py | 80 +++++++++++- tests/test_us_unmanaged_runtime.py | 122 ++++++++++++++++++ 5 files changed, 219 insertions(+), 5 deletions(-) diff --git a/changelog.d/760.fixed.md b/changelog.d/760.fixed.md index 707736f98..70262b54e 100644 --- a/changelog.d/760.fixed.md +++ b/changelog.d/760.fixed.md @@ -1 +1,3 @@ Allow explicit local US datasets with `allow_unmanaged=True` to record unverified runtime provenance without certifying the unused default data bundle. Keep certification on bundled data, cached year files and managed simulation entrypoints. + +Add `native_input_period` for explicit local TIME_PERIOD_ARRAYS files so callers can bind the input clock before the first country constructor while preserving each stored period. diff --git a/docs/microsim.md b/docs/microsim.md index 15b12ba25..bc26caa41 100644 --- a/docs/microsim.md +++ b/docs/microsim.md @@ -414,7 +414,7 @@ These run in seconds and are fine for integration tests. Don't use them for prod ## Managed microsimulation -`managed_microsimulation` constructs a country-package `Microsimulation` pinned to the `policyengine.py` release bundle (so the dataset selection is certified, not ad-hoc): +`managed_microsimulation()` selects the certified default dataset when callers omit `dataset`: ```python from policyengine.tax_benefit_models.us import managed_microsimulation @@ -427,6 +427,22 @@ Pass `allow_unmanaged=True` with a custom `dataset=` to opt out of the release bundle. Explicit local paths and Hugging Face URIs remain supported in this mode. GCS dataset URIs are not supported. +An explicit local US file records its SHA-256 and the installed wrapper, country, +Core and SPM versions in `sim.policyengine_bundle`. Its `compatibility_basis` +records `unverified_explicit_local_unmanaged`, and `certified_by` records `None`. +Importing the US wrapper and constructing this local simulation do not certify +the unused default dataset. Bundled and named data, year-file caches, managed +simulation runs and cached output loads retain their certification checks. + +For a local TIME_PERIOD_ARRAYS file, pass `native_input_period="2017"` to set the +Core Dataset descriptor's annual clock before the first country constructor. +The wrapper preserves stored period keys, including monthly inputs and earlier +lookbacks. This option requires `allow_unmanaged=True`, an existing local file +and a four-digit annual period. It rejects scoping, `dataset_end_year` and +conflicting default input or calculation periods. The caller still selects the +tax-benefit system and structural start date; this keyword selects the input +clock. + A UK managed microsimulation also records, in `sim.policyengine_bundle["capital_gains_responses"]`, the capital gains realisation response it applies in each year of its dataset (see diff --git a/docs/receipts.md b/docs/receipts.md index 42930b5da..fbcfaf7c9 100644 --- a/docs/receipts.md +++ b/docs/receipts.md @@ -46,7 +46,7 @@ print(receipt.certification_status, receipt.execution_identity_sha256) receipt_json = receipt.to_canonical_json() ``` -For a country `Microsimulation` built with `managed_microsimulation()`, call `build_execution_receipt_for_microsimulation(sim, years=..., reform=..., baseline=...)`. It reads the dataset that was loaded from `sim.policyengine_bundle`. The file must still hash to the SHA-256 verified when it was loaded, and the receipt must name the dataset, URI, revision and package recorded then; otherwise it is refused, because it would describe bytes that did not run. A simulation loaded from an unmanaged file or URI recorded no load-time hash, so it cannot be receipted. The microsimulation does not record its reform, so pass the reform you built it with. +For a UK `Microsimulation` from `managed_microsimulation()`, call `build_execution_receipt_for_microsimulation(sim, years=..., reform=..., baseline=...)`. It reads the runtime dataset from `sim.policyengine_bundle`. The file must still match the SHA-256 that the wrapper verified at load time, and the receipt must name the same dataset, URI, revision and package. The builder refuses a UK simulation whose unmanaged source records no load-time hash. Pass the reform and baseline explicitly, since the microsimulation does not record them. Receipt schema v1 covers UK results only; a US local-runtime provenance record does not extend that schema or certify compatibility. With `POLICYENGINE_UK_DATA_MANIFEST_FILE` enabled, a packaged-bundle receipt rechecks runtime certification using the local file and records its distinct diff --git a/src/policyengine/tax_benefit_models/us/model.py b/src/policyengine/tax_benefit_models/us/model.py index b65145643..1f802cec2 100644 --- a/src/policyengine/tax_benefit_models/us/model.py +++ b/src/policyengine/tax_benefit_models/us/model.py @@ -11,6 +11,7 @@ from policyengine.provenance.dataset_materialization import ( materialize_dataset, ) +from policyengine.provenance.manifest import get_release_manifest from policyengine.tax_benefit_models.common import MicrosimulationModelVersion from policyengine.tax_benefit_models.common.model_version import ( build_runtime_dataset_provenance, @@ -596,15 +597,44 @@ def _unmanaged_local_runtime_provenance(source): return provenance +def _native_local_dataset(source, native_input_period): + """Set a native descriptor's clock before country input migrations.""" + from policyengine_core.data import Dataset as CoreDataset + from policyengine_core.periods import ETERNITY, MONTH, YEAR, period + + descriptor = CoreDataset.from_file(source.path) + if descriptor.data_format != CoreDataset.TIME_PERIOD_ARRAYS: + raise ValueError("native_input_period requires TIME_PERIOD_ARRAYS data") + # Core infers the clock from the first field. Inspect the native structure + # without reading vector payloads, then replace that inference explicitly. + with descriptor.load() as arrays: + if len(arrays) == 0: + raise ValueError("Native input data cannot be empty") + for name, values in arrays.items(): + if not hasattr(values, "keys") or len(values) == 0: + raise ValueError(f"Native input {name!r} must contain period arrays") + for key, vector in values.items(): + declared = period(key) + if declared.unit not in (YEAR, MONTH, ETERNITY) or ( + declared.unit != ETERNITY and declared.size != 1 + ): + raise ValueError(f"Unsupported native input period {key!r}") + if not hasattr(vector, "shape") or len(vector.shape) != 1: + raise ValueError(f"Native input {name!r}/{key} must be a vector") + descriptor.time_period = native_input_period + return descriptor + + def managed_microsimulation( *, dataset: Optional[str] = None, allow_unmanaged: bool = False, spm: Optional[SPMSelection] = None, scoping_strategy: Optional[RowFilterStrategy] = None, + native_input_period: Optional[str] = None, **kwargs, ): - """Construct a country-package Microsimulation pinned to this bundle. + """Construct a US microsimulation from managed or explicit local data. By default this enforces the dataset selection from the bundled ``policyengine.py`` release manifest. Arbitrary dataset URIs require @@ -618,6 +648,11 @@ def managed_microsimulation( household cohort from every native projected year before financial calculations. This retains earlier supplied income for lookbacks. The unscoped constructor continues to own projection and reform timing. + + ``native_input_period="2017"`` binds the input clock before the first + country constructor for an explicit local TIME_PERIOD_ARRAYS file. It + preserves each array's period and does not project or rescope the file. + The caller still selects the tax-benefit system and structural start date. """ from policyengine_us import Microsimulation @@ -628,6 +663,34 @@ def managed_microsimulation( "**kwargs, so policyengine.py can enforce the release bundle." ) + if native_input_period is not None: + if ( + type(native_input_period) is not str + or len(native_input_period) != 4 + or not native_input_period.isascii() + or not native_input_period.isdigit() + or not 1 <= int(native_input_period) <= 9999 + ): + raise ValueError("native_input_period must be a four-digit annual period") + if ( + not allow_unmanaged + or type(dataset) is not str + or "://" in dataset + or dataset in get_release_manifest("us").datasets + or not Path(dataset).expanduser().is_file() + ): + raise ValueError( + "native_input_period requires an explicit local unmanaged file" + ) + if scoping_strategy is not None or "dataset_end_year" in kwargs: + raise ValueError( + "native_input_period cannot project or scope its input data" + ) + for option in ("default_input_period", "default_calculation_period"): + if option in kwargs and kwargs[option] != native_input_period: + raise ValueError(f"{option} must match native_input_period") + kwargs[option] = native_input_period + selection = resolve_spm_selection(spm) source = materialize_dataset( "us", @@ -659,7 +722,15 @@ def managed_microsimulation( local_provenance = ( _unmanaged_local_runtime_provenance(source) if explicit_local else None ) - microsim = Microsimulation(dataset=source.path, spm=selection, **kwargs) + constructor_dataset = source.path + if native_input_period is not None: + if not explicit_local: + raise ValueError( + "native_input_period requires an explicit local unmanaged file" + ) + constructor_dataset = _native_local_dataset(source, native_input_period) + local_provenance["native_input_period"] = native_input_period + microsim = Microsimulation(dataset=constructor_dataset, spm=selection, **kwargs) scoping_record = None if scoping_strategy is not None: import gc @@ -694,7 +765,10 @@ def managed_microsimulation( update={"model_mode": mode} ).model_dump(mode="json") if explicit_local: - if _unmanaged_local_runtime_provenance(source) != local_provenance: + after_provenance = _unmanaged_local_runtime_provenance(source) + if native_input_period is not None: + after_provenance["native_input_period"] = native_input_period + if after_provenance != local_provenance: raise ValueError( "Unmanaged local data or runtime changed during construction" ) diff --git a/tests/test_us_unmanaged_runtime.py b/tests/test_us_unmanaged_runtime.py index 37621ee43..45bbfe93f 100644 --- a/tests/test_us_unmanaged_runtime.py +++ b/tests/test_us_unmanaged_runtime.py @@ -5,6 +5,7 @@ import hashlib import importlib +from contextlib import nullcontext from importlib import metadata from types import SimpleNamespace @@ -199,3 +200,124 @@ def test_local_provenance_refuses_installed_loaded_drift(monkeypatch, tmp_path): source = materialization.DatasetSource(source_uri=str(path), path=str(path)) with pytest.raises(ValueError, match="changed after import"): us_model._unmanaged_local_runtime_provenance(source) + + +@pytest.mark.parametrize("period", [True, 2017, "2017-01", "2017", "0000", "2017:2"]) +def test_native_clock_requires_one_canonical_annual_period(period): + with pytest.raises(ValueError, match="four-digit annual period"): + us_model.managed_microsimulation(native_input_period=period) + + +@pytest.mark.parametrize( + "source", [None, "populace_us_2024", "hf://example/fixture.h5@v1"] +) +def test_native_clock_rejects_managed_and_remote_sources(source): + with pytest.raises(ValueError, match="explicit local unmanaged file"): + us_model.managed_microsimulation( + dataset=source, allow_unmanaged=True, native_input_period="2017" + ) + + +def test_native_clock_requires_existing_local_opt_in(tmp_path): + path = tmp_path / "fixture.bin" + with pytest.raises(ValueError, match="explicit local unmanaged file"): + us_model.managed_microsimulation( + dataset=str(path), allow_unmanaged=True, native_input_period="2017" + ) + path.write_bytes(b"fixture") + with pytest.raises(ValueError, match="explicit local unmanaged file"): + us_model.managed_microsimulation(dataset=str(path), native_input_period="2017") + + +@pytest.mark.parametrize( + "options", + [ + {"dataset_end_year": 2017}, + {"scoping_strategy": object()}, + {"default_input_period": "2015"}, + {"default_calculation_period": "2015"}, + ], +) +def test_native_clock_rejects_projection_scoping_and_conflicting_defaults( + tmp_path, options +): + path = tmp_path / "fixture.bin" + path.write_bytes(b"fixture") + with pytest.raises(ValueError, match="cannot project or scope|must match"): + us_model.managed_microsimulation( + dataset=str(path), + allow_unmanaged=True, + native_input_period="2017", + **options, + ) + + +def test_native_descriptor_reaches_first_constructor_with_declared_clock( + monkeypatch, tmp_path +): + import policyengine_us + from policyengine_core.data import Dataset as CoreDataset + + path, expected = local_factory_fixture(monkeypatch, tmp_path) + arrays = { + "annual_lookback_fixture": {"2015": SimpleNamespace(shape=(1,))}, + "monthly_fixture": {"2017-01": SimpleNamespace(shape=(1,))}, + } + descriptor = SimpleNamespace( + data_format=CoreDataset.TIME_PERIOD_ARRAYS, + time_period="2015", + load=lambda: nullcontext(arrays), + ) + monkeypatch.setattr(CoreDataset, "from_file", lambda path: descriptor) + calls = [] + + def constructor(**kwargs): + calls.append(kwargs) + assert kwargs["dataset"] is descriptor + assert descriptor.time_period == "2017" + assert kwargs["default_input_period"] == "2017" + assert kwargs["default_calculation_period"] == "2017" + return expected + + monkeypatch.setattr(policyengine_us, "Microsimulation", constructor) + sim = us_model.managed_microsimulation( + dataset=str(path), allow_unmanaged=True, native_input_period="2017" + ) + assert len(calls) == 1 + assert sim.policyengine_bundle["native_input_period"] == "2017" + assert list(arrays["annual_lookback_fixture"]) == ["2015"] + assert list(arrays["monthly_fixture"]) == ["2017-01"] + + +@pytest.mark.parametrize( + "data_format, arrays, message", + [ + ("arrays", {}, "TIME_PERIOD_ARRAYS"), + ("time_period_arrays", {}, "cannot be empty"), + ("time_period_arrays", {"fixture": {}}, "period arrays"), + ( + "time_period_arrays", + {"fixture": {"2017": SimpleNamespace(shape=())}}, + "must be a vector", + ), + ( + "time_period_arrays", + {"fixture": {"year:2017:2": SimpleNamespace(shape=(1,))}}, + "Unsupported native input period", + ), + ], +) +def test_native_descriptor_rejects_other_layouts( + monkeypatch, data_format, arrays, message +): + from policyengine_core.data import Dataset as CoreDataset + + descriptor = SimpleNamespace( + data_format=data_format, time_period="2015", load=lambda: nullcontext(arrays) + ) + monkeypatch.setattr(CoreDataset, "from_file", lambda path: descriptor) + with pytest.raises(ValueError, match=message): + us_model._native_local_dataset( + SimpleNamespace(path="inert-fixture.bin"), "2017" + ) + assert descriptor.time_period == "2015" From 681f81ee2ff7f9c08e352db8090227742bd4ff59 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 17 Nov 2026 03:12:47 -0500 Subject: [PATCH 03/20] Validate US certification before provenance exports [skip ci] --- changelog.d/760.fixed.md | 2 +- .../tax_benefit_models/us/model.py | 12 +++ tests/test_release_manifests.py | 4 +- tests/test_us_unmanaged_runtime.py | 77 +++++++++++++++++++ 4 files changed, 93 insertions(+), 2 deletions(-) diff --git a/changelog.d/760.fixed.md b/changelog.d/760.fixed.md index 70262b54e..16676cf05 100644 --- a/changelog.d/760.fixed.md +++ b/changelog.d/760.fixed.md @@ -1,3 +1,3 @@ Allow explicit local US datasets with `allow_unmanaged=True` to record unverified runtime provenance without certifying the unused default data bundle. Keep certification on bundled data, cached year files and managed simulation entrypoints. -Add `native_input_period` for explicit local TIME_PERIOD_ARRAYS files so callers can bind the input clock before the first country constructor while preserving each stored period. +Add `native_input_period` for explicit local TIME_PERIOD_ARRAYS files so callers can bind the input clock before the first country constructor while preserving each stored period. Require current US data certification before exporting bundle provenance. diff --git a/src/policyengine/tax_benefit_models/us/model.py b/src/policyengine/tax_benefit_models/us/model.py index 1f802cec2..a824a1098 100644 --- a/src/policyengine/tax_benefit_models/us/model.py +++ b/src/policyengine/tax_benefit_models/us/model.py @@ -64,6 +64,12 @@ class PolicyEngineUS(TaxBenefitModel): class PolicyEngineUSLatest(MicrosimulationModelVersion): + """US runtime metadata with certification deferred until selected. + + ``data_certification`` stays unset at import. Certified operations validate + the current runtime before exposing bundle provenance or using bundled data. + """ + country_code = "us" package_name = "policyengine-us" group_entities = US_GROUP_ENTITIES @@ -139,6 +145,12 @@ class PolicyEngineUSLatest(MicrosimulationModelVersion): ], } + @property + def trace_tro(self) -> dict: + """Export bundle provenance only after current runtime certification.""" + self.require_data_certification() + return super().trace_tro + # --- Hooks ----------------------------------------------------------- @classmethod def _get_runtime_data_build_metadata(cls) -> dict[str, Optional[str]]: diff --git a/tests/test_release_manifests.py b/tests/test_release_manifests.py index 70bb32254..8cd9d71ab 100644 --- a/tests/test_release_manifests.py +++ b/tests/test_release_manifests.py @@ -947,7 +947,7 @@ def test__given_manifest_fetch_failure_and_version_mismatch__then_fallback_is_un assert certification.certified_for_model_version == "1.602.0" assert certification.certified_by == US_CERTIFICATION_SOURCE - def test__given_offline_hf__then_us_import_uses_bundled_certification( + def test__given_offline_hf__then_us_import_defers_until_certification( self, tmp_path, ): @@ -979,6 +979,8 @@ def test__given_offline_hf__then_us_import_uses_bundled_certification( "-c", ( "import policyengine.tax_benefit_models.us as us; " + "assert us.model.data_certification is None; " + "us.model.require_data_certification(); " "print(us.model.data_certification.certified_by)" ), ], diff --git a/tests/test_us_unmanaged_runtime.py b/tests/test_us_unmanaged_runtime.py index 45bbfe93f..d3bd41ea8 100644 --- a/tests/test_us_unmanaged_runtime.py +++ b/tests/test_us_unmanaged_runtime.py @@ -321,3 +321,80 @@ def test_native_descriptor_rejects_other_layouts( SimpleNamespace(path="inert-fixture.bin"), "2017" ) assert descriptor.time_period == "2015" + + +@pytest.mark.parametrize("cached_certification", [None, "old_test_certificate"]) +def test_trace_export_requires_current_certification_before_builder( + monkeypatch, cached_certification +): + """A cached or absent certificate cannot substitute for runtime validation.""" + from policyengine.core.tax_benefit_model_version import TaxBenefitModelVersion + + model = us_model.PolicyEngineUSLatest.model_construct( + data_certification=cached_certification + ) + calls = [] + + def refuse(self): + calls.append("certification") + raise ValueError("test incompatible current runtime") + + def unexpected_builder(self): + pytest.fail("An uncertified export reached the bundle TRACE builder") + + monkeypatch.setattr( + us_model.PolicyEngineUSLatest, "require_data_certification", refuse + ) + monkeypatch.setattr( + TaxBenefitModelVersion, "trace_tro", property(unexpected_builder) + ) + with pytest.raises(ValueError, match="incompatible current runtime"): + _ = model.trace_tro + assert calls == ["certification"] + + +def test_trace_export_uses_newly_validated_certificate(monkeypatch): + """The builder receives the fresh synthetic certificate, not manifest fallback.""" + from policyengine.core.tax_benefit_model_version import TaxBenefitModelVersion + + model = us_model.PolicyEngineUSLatest.model_construct(data_certification=None) + fresh_test_certificate = object() + calls = [] + + def certify(self): + calls.append("certification") + self.data_certification = fresh_test_certificate + return fresh_test_certificate + + def builder(self): + calls.append("TRACE") + assert self.data_certification is fresh_test_certificate + return {"synthetic_fixture_only": True} + + monkeypatch.setattr( + us_model.PolicyEngineUSLatest, "require_data_certification", certify + ) + monkeypatch.setattr(TaxBenefitModelVersion, "trace_tro", property(builder)) + assert model.trace_tro == {"synthetic_fixture_only": True} + assert calls == ["certification", "TRACE"] + + +def test_automatic_run_record_fallback_refuses_before_output_write( + monkeypatch, tmp_path +): + """Automatic provenance lookup propagates refusal before recording anything.""" + from policyengine.core.run_record import write_simulation_run_record + + model = us_model.PolicyEngineUSLatest.model_construct(data_certification=None) + + def refuse(self): + raise ValueError("test incompatible current runtime") + + monkeypatch.setattr( + us_model.PolicyEngineUSLatest, "require_data_certification", refuse + ) + output = tmp_path / "must-not-be-created" + simulation = SimpleNamespace(tax_benefit_model_version=model) + with pytest.raises(ValueError, match="incompatible current runtime"): + write_simulation_run_record(simulation, output) + assert not output.exists() From 69b2607489e5e6183729c8e52fe6bcf18c9d56ab Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 17 Nov 2026 04:20:15 -0500 Subject: [PATCH 04/20] fix: reject invalid native dataset files [skip ci] --- changelog.d/760.fixed.md | 2 +- .../tax_benefit_models/us/model.py | 15 ++++-- tests/test_us_unmanaged_runtime.py | 54 ++++++++++++++++--- 3 files changed, 60 insertions(+), 11 deletions(-) diff --git a/changelog.d/760.fixed.md b/changelog.d/760.fixed.md index 16676cf05..8b1fa1cb2 100644 --- a/changelog.d/760.fixed.md +++ b/changelog.d/760.fixed.md @@ -1,3 +1,3 @@ Allow explicit local US datasets with `allow_unmanaged=True` to record unverified runtime provenance without certifying the unused default data bundle. Keep certification on bundled data, cached year files and managed simulation entrypoints. -Add `native_input_period` for explicit local TIME_PERIOD_ARRAYS files so callers can bind the input clock before the first country constructor while preserving each stored period. Require current US data certification before exporting bundle provenance. +Add `native_input_period` for explicit local TIME_PERIOD_ARRAYS files so callers can bind the input clock before the first country constructor while preserving each stored period. Require current US data certification before exporting bundle provenance. Reject non-H5 native paths and report empty native files with a clear value error. diff --git a/src/policyengine/tax_benefit_models/us/model.py b/src/policyengine/tax_benefit_models/us/model.py index a824a1098..f4ba41c51 100644 --- a/src/policyengine/tax_benefit_models/us/model.py +++ b/src/policyengine/tax_benefit_models/us/model.py @@ -614,7 +614,13 @@ def _native_local_dataset(source, native_input_period): from policyengine_core.data import Dataset as CoreDataset from policyengine_core.periods import ETERNITY, MONTH, YEAR, period - descriptor = CoreDataset.from_file(source.path) + if Path(source.path).suffix != ".h5": + raise ValueError("native_input_period requires a .h5 TIME_PERIOD_ARRAYS file") + try: + descriptor = CoreDataset.from_file(source.path) + except IndexError as error: + # Core probes the first H5 root key before returning a descriptor. + raise ValueError("Native input data cannot be empty") from error if descriptor.data_format != CoreDataset.TIME_PERIOD_ARRAYS: raise ValueError("native_input_period requires TIME_PERIOD_ARRAYS data") # Core infers the clock from the first field. Inspect the native structure @@ -661,9 +667,10 @@ def managed_microsimulation( calculations. This retains earlier supplied income for lookbacks. The unscoped constructor continues to own projection and reform timing. - ``native_input_period="2017"`` binds the input clock before the first - country constructor for an explicit local TIME_PERIOD_ARRAYS file. It - preserves each array's period and does not project or rescope the file. + ``native_input_period="2017"`` binds both input and calculation defaults + before the first country constructor for an explicit local ``.h5`` + TIME_PERIOD_ARRAYS file. It preserves each array's period and does not + project or rescope the file. The caller still selects the tax-benefit system and structural start date. """ diff --git a/tests/test_us_unmanaged_runtime.py b/tests/test_us_unmanaged_runtime.py index d3bd41ea8..75376eab5 100644 --- a/tests/test_us_unmanaged_runtime.py +++ b/tests/test_us_unmanaged_runtime.py @@ -129,11 +129,11 @@ def test_uk_initialization_keeps_eager_certification(monkeypatch): uk_model.PolicyEngineUKLatest() -def local_factory_fixture(monkeypatch, tmp_path, *, mutate=False): +def local_factory_fixture(monkeypatch, tmp_path, *, mutate=False, suffix=".bin"): """Return an explicit local source and a constructor that never loads it.""" import policyengine_us - path = tmp_path / "inert-local-fixture.bin" + path = tmp_path / f"inert-local-fixture{suffix}" path.write_bytes(b"test source plumbing only") sim = SimpleNamespace(spm_config={}) @@ -258,7 +258,7 @@ def test_native_descriptor_reaches_first_constructor_with_declared_clock( import policyengine_us from policyengine_core.data import Dataset as CoreDataset - path, expected = local_factory_fixture(monkeypatch, tmp_path) + path, expected = local_factory_fixture(monkeypatch, tmp_path, suffix=".h5") arrays = { "annual_lookback_fixture": {"2015": SimpleNamespace(shape=(1,))}, "monthly_fixture": {"2017-01": SimpleNamespace(shape=(1,))}, @@ -317,9 +317,7 @@ def test_native_descriptor_rejects_other_layouts( ) monkeypatch.setattr(CoreDataset, "from_file", lambda path: descriptor) with pytest.raises(ValueError, match=message): - us_model._native_local_dataset( - SimpleNamespace(path="inert-fixture.bin"), "2017" - ) + us_model._native_local_dataset(SimpleNamespace(path="inert-fixture.h5"), "2017") assert descriptor.time_period == "2015" @@ -398,3 +396,47 @@ def refuse(self): with pytest.raises(ValueError, match="incompatible current runtime"): write_simulation_run_record(simulation, output) assert not output.exists() + + +def test_native_descriptor_requires_h5_suffix_before_core_file_open(monkeypatch): + from policyengine_core.data import Dataset as CoreDataset + + def unexpected_open(path): + pytest.fail("A non-H5 native path reached the Core file loader") + + monkeypatch.setattr(CoreDataset, "from_file", unexpected_open) + with pytest.raises(ValueError, match=r"requires a \.h5 TIME_PERIOD_ARRAYS file"): + us_model._native_local_dataset( + SimpleNamespace(path="inert-fixture.bin"), "2017" + ) + + +def test_native_descriptor_translates_empty_h5_root_refusal(monkeypatch): + from policyengine_core.data import Dataset as CoreDataset + + original = IndexError("list index out of range") + calls = [] + + def empty_root(path): + calls.append(path) + raise original + + monkeypatch.setattr(CoreDataset, "from_file", empty_root) + with pytest.raises(ValueError, match="cannot be empty") as caught: + us_model._native_local_dataset(SimpleNamespace(path="inert-fixture.h5"), "2017") + assert calls == ["inert-fixture.h5"] + assert caught.value.__cause__ is original + + +def test_native_descriptor_preserves_unrelated_core_io_failure(monkeypatch): + from policyengine_core.data import Dataset as CoreDataset + + original = OSError("inert non-HDF5 fixture") + + def io_failure(path): + raise original + + monkeypatch.setattr(CoreDataset, "from_file", io_failure) + with pytest.raises(OSError) as caught: + us_model._native_local_dataset(SimpleNamespace(path="inert-fixture.h5"), "2017") + assert caught.value is original From 5f51b00f332786084d658aca5e04ea409b445eca Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 17 Nov 2026 04:22:08 -0500 Subject: [PATCH 05/20] docs: clarify native input file and clock requirements [skip ci] --- docs/microsim.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/microsim.md b/docs/microsim.md index bc26caa41..00ac2e3e5 100644 --- a/docs/microsim.md +++ b/docs/microsim.md @@ -434,14 +434,14 @@ Importing the US wrapper and constructing this local simulation do not certify the unused default dataset. Bundled and named data, year-file caches, managed simulation runs and cached output loads retain their certification checks. -For a local TIME_PERIOD_ARRAYS file, pass `native_input_period="2017"` to set the -Core Dataset descriptor's annual clock before the first country constructor. -The wrapper preserves stored period keys, including monthly inputs and earlier -lookbacks. This option requires `allow_unmanaged=True`, an existing local file +For a local `.h5` TIME_PERIOD_ARRAYS file, pass `native_input_period="2017"` to +set the Core Dataset descriptor's annual clock and both default input and +calculation periods before the first country constructor. The wrapper preserves +stored period keys, including monthly inputs and earlier lookbacks. This option +requires `allow_unmanaged=True`, an existing nonempty file with the `.h5` suffix and a four-digit annual period. It rejects scoping, `dataset_end_year` and conflicting default input or calculation periods. The caller still selects the -tax-benefit system and structural start date; this keyword selects the input -clock. +tax-benefit system and structural start date. A UK managed microsimulation also records, in `sim.policyengine_bundle["capital_gains_responses"]`, the capital gains From 21bf0a328f6967862fb1cf7b5e3c77bf4e8b7bce Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 17 Nov 2026 05:21:05 -0500 Subject: [PATCH 06/20] docs: clarify deferred US certification and native file refusals [skip ci] --- changelog.d/760.fixed.md | 2 +- .../runbooks/canonical-spm-development.md | 25 +++++++++++-------- src/policyengine/provenance/receipt.py | 24 ++++++++++-------- 3 files changed, 28 insertions(+), 23 deletions(-) diff --git a/changelog.d/760.fixed.md b/changelog.d/760.fixed.md index 8b1fa1cb2..65c9465a5 100644 --- a/changelog.d/760.fixed.md +++ b/changelog.d/760.fixed.md @@ -1,3 +1,3 @@ Allow explicit local US datasets with `allow_unmanaged=True` to record unverified runtime provenance without certifying the unused default data bundle. Keep certification on bundled data, cached year files and managed simulation entrypoints. -Add `native_input_period` for explicit local TIME_PERIOD_ARRAYS files so callers can bind the input clock before the first country constructor while preserving each stored period. Require current US data certification before exporting bundle provenance. Reject non-H5 native paths and report empty native files with a clear value error. +Add `native_input_period` for explicit local TIME_PERIOD_ARRAYS files so callers can bind the input clock before the first country constructor while preserving each stored period. Require current US data certification before exporting bundle provenance. Reject non-H5 native paths and report empty native HDF5 roots with a clear value error. diff --git a/docs/engineering/runbooks/canonical-spm-development.md b/docs/engineering/runbooks/canonical-spm-development.md index 4e094bc52..89ed8b395 100644 --- a/docs/engineering/runbooks/canonical-spm-development.md +++ b/docs/engineering/runbooks/canonical-spm-development.md @@ -48,12 +48,14 @@ reference-only. It records the real local wheel names, versions, file URIs and SHA-256 hashes. UK release metadata is retained unchanged. It refuses to overwrite the packaged manifest. -Country model initialization requires a data compatibility receipt even for -household-only tests. An explicitly enabled pytest plugin supplies the -`unverified_development_fixture` receipt and disables remote data-manifest -fetches for that test process. It does not add a compatibility claim, certify a -dataset, or install a production environment-variable override. Its existing -receipt field `certified_for_model_version` names the tested runtime; the +US initialization defers data certification until code requests certification +or uses bundled data. UK initialization continues to require a compatibility +receipt. An explicitly enabled pytest plugin supplies the +`unverified_development_fixture` receipt when those US entrypoints request +certification and disables remote data-manifest fetches for that test process. +It does not add a compatibility claim, certify a dataset, or install a production +environment-variable override. Its existing receipt field +`certified_for_model_version` names the tested runtime; the `unverified_development_fixture` basis explicitly denies certification. ```bash @@ -90,16 +92,17 @@ development = activate_spm_development_manifest( import policyengine as pe assert development["development"]["promotion_status"] == "pending" -assert pe.us.model.data_certification.compatibility_basis == ( - "unverified_development_fixture" -) +certification = pe.us.model.require_data_certification() +assert certification.compatibility_basis == "unverified_development_fixture" ``` Run such a script from the wrapper worktree with the isolated interpreter and `uv run --python "$SPM_PYTHON" --no-sync`. The final acceptance worker can then call `pe.us.managed_microsimulation(dataset=LOCAL_H5, -allow_unmanaged=True, spm={...})`, reporting the explicit development receipt. -Only that worker is authorized for the heavy population process. +allow_unmanaged=True, spm={...})`. That local-data call records +`compatibility_basis="unverified_explicit_local_unmanaged"` and +`certified_by=None`; it does not attach the development certificate to the local +file. Only that worker is authorized for the heavy population process. Bundle-only tests avoid the country bootstrap entirely: diff --git a/src/policyengine/provenance/receipt.py b/src/policyengine/provenance/receipt.py index f82778945..2044edcc9 100644 --- a/src/policyengine/provenance/receipt.py +++ b/src/policyengine/provenance/receipt.py @@ -4440,17 +4440,19 @@ def build_execution_receipt_for_microsimulation( outputs: Optional[Any] = None, **kwargs: Any, ) -> ExecutionReceipt: - """Receipt for a country Microsimulation built by ``managed_microsimulation``. - - Reads the dataset that was loaded from ``microsimulation.policyengine_bundle``. - The bytes on disk must still be the bytes verified when it was loaded - (``runtime_dataset_sha256``), and the receipt must name the dataset, - artifact URI, revision and package recorded at load time; otherwise the - receipt would describe a file that did not run, so it is refused. A - simulation loaded from an unmanaged file or URI recorded no load-time - hash and cannot be receipted. ``reform`` and ``baseline`` must describe - what the microsimulation was built with (``scenario_reform_identity`` or - ``reform_identity``); the microsimulation itself does not record them. + """Build a schema-v1 execution receipt for a managed UK Microsimulation. + + Read the dataset from ``microsimulation.policyengine_bundle``. Require + its current bytes to match the load-time ``runtime_dataset_sha256``. + The receipt must name the dataset, artifact URI, revision and package + from that load; otherwise it would describe a file that did not run. + + Unmanaged UK file or URI loads record no load-time hash and cannot supply + this receipt. Explicit local US loads record a hash and unverified + provenance, but schema v1 still refuses US results. ``reform`` and + ``baseline`` must describe the microsimulation's construction + (``scenario_reform_identity`` or ``reform_identity``); the microsimulation + itself does not record them. """ bundle_fields = getattr(microsimulation, "policyengine_bundle", None) From 439126c31d44a37d4344da8b0da940e2f6d6ef75 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 30 Nov 2026 14:02:50 -0500 Subject: [PATCH 07/20] Defer country imports and guard managed US reuse Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- docs/microsim.md | 9 +- src/policyengine/__init__.py | 36 ++++-- src/policyengine/core/simulation.py | 1 + .../core/tax_benefit_model_version.py | 3 + .../provenance/dataset_materialization.py | 12 +- .../common/model_version.py | 7 ++ .../tax_benefit_models/us/model.py | 9 +- tests/test_us_unmanaged_runtime.py | 103 +++++++++++++++++- 8 files changed, 162 insertions(+), 18 deletions(-) diff --git a/docs/microsim.md b/docs/microsim.md index 00ac2e3e5..273126663 100644 --- a/docs/microsim.md +++ b/docs/microsim.md @@ -430,9 +430,12 @@ mode. GCS dataset URIs are not supported. An explicit local US file records its SHA-256 and the installed wrapper, country, Core and SPM versions in `sim.policyengine_bundle`. Its `compatibility_basis` records `unverified_explicit_local_unmanaged`, and `certified_by` records `None`. -Importing the US wrapper and constructing this local simulation do not certify -the unused default dataset. Bundled and named data, year-file caches, managed -simulation runs and cached output loads retain their certification checks. +A bare `import policyengine` defers both country namespaces until they are +accessed. Accessing the UK namespace still certifies data during initialisation. +The US wrapper certifies at first managed use, including bundled and named data, +year-file caches, managed simulation runs, cached outputs, bundle receipts and +TRACE exports. Constructing an explicit local US simulation bypasses that +certification. For a local `.h5` TIME_PERIOD_ARRAYS file, pass `native_input_period="2017"` to set the Core Dataset descriptor's annual clock and both default input and diff --git a/src/policyengine/__init__.py b/src/policyengine/__init__.py index 55af19472..83af8a193 100644 --- a/src/policyengine/__init__.py +++ b/src/policyengine/__init__.py @@ -30,25 +30,43 @@ """ import os +from importlib import import_module, metadata from importlib.util import find_spec +from typing import TYPE_CHECKING from policyengine import outputs as outputs from policyengine.core import Simulation as Simulation -_SKIP_COUNTRY_IMPORTS = os.environ.get("POLICYENGINE_SKIP_COUNTRY_IMPORTS") == "1" - -if not _SKIP_COUNTRY_IMPORTS and find_spec("policyengine_us") is not None: +if TYPE_CHECKING: + from policyengine.tax_benefit_models import uk as uk from policyengine.tax_benefit_models import us as us -else: # pragma: no cover - us = None # type: ignore[assignment] -if not _SKIP_COUNTRY_IMPORTS and find_spec("policyengine_uk") is not None: - from policyengine.tax_benefit_models import uk as uk -else: # pragma: no cover - uk = None # type: ignore[assignment] +_SKIP_COUNTRY_IMPORTS = os.environ.get("POLICYENGINE_SKIP_COUNTRY_IMPORTS") == "1" + +try: + __version__ = metadata.version("policyengine") +except metadata.PackageNotFoundError: + __version__ = "0+unknown" __all__ = ["Simulation", "outputs", "uk", "us"] + +def __getattr__(name: str): + """Initialise a country when the caller first accesses its namespace.""" + if name not in ("uk", "us"): + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + country = None + if not _SKIP_COUNTRY_IMPORTS and find_spec(f"policyengine_{name}") is not None: + country = import_module(f"policyengine.tax_benefit_models.{name}") + globals()[name] = country + return country + + +def __dir__() -> list[str]: + return sorted(globals().keys() | set(__all__)) + + # The wrapper's own version as imported, for receipts to compare with what is # installed when they are built. from policyengine.provenance.loaded import ( # noqa: E402 diff --git a/src/policyengine/core/simulation.py b/src/policyengine/core/simulation.py index c506da826..74a00e018 100644 --- a/src/policyengine/core/simulation.py +++ b/src/policyengine/core/simulation.py @@ -195,6 +195,7 @@ def ensure(self): cache_key = self.storage_id cached_result = _cache.get(cache_key) if cached_result: + self.tax_benefit_model_version._validate_cached_output() self.output_dataset = cached_result.output_dataset self.spm = cached_result.spm self.spm_receipt = ( diff --git a/src/policyengine/core/tax_benefit_model_version.py b/src/policyengine/core/tax_benefit_model_version.py index dc7a2de4e..70237d783 100644 --- a/src/policyengine/core/tax_benefit_model_version.py +++ b/src/policyengine/core/tax_benefit_model_version.py @@ -105,6 +105,9 @@ def load(self, simulation: "Simulation"): "The TaxBenefitModel class must define a method to load simulations." ) + def _validate_cached_output(self) -> None: + """Check model-specific requirements before reusing a cached output.""" + def add_parameter(self, param: "Parameter") -> None: """Add a parameter and index it for fast lookup.""" self.parameters.append(param) diff --git a/src/policyengine/provenance/dataset_materialization.py b/src/policyengine/provenance/dataset_materialization.py index 174f04ea4..bb2cba757 100644 --- a/src/policyengine/provenance/dataset_materialization.py +++ b/src/policyengine/provenance/dataset_materialization.py @@ -184,14 +184,22 @@ def materialize_dataset( manifest=manifest, ) + if ( + country_id == "us" + and allow_unmanaged + and isinstance(dataset, str) + and ( + dataset.startswith("hf://") + or ("://" not in dataset and not Path(dataset).expanduser().exists()) + ) + ): + _require_us_data_certification() source_uri = resolve_managed_dataset_reference( country_id, dataset, allow_unmanaged=allow_unmanaged, ) if source_uri.startswith("hf://"): - if country_id == "us": - _require_us_data_certification() return _download_hugging_face_dataset(source_uri, data_dir=data_dir) if "://" in source_uri: raise DatasetMaterializationError( diff --git a/src/policyengine/tax_benefit_models/common/model_version.py b/src/policyengine/tax_benefit_models/common/model_version.py index 0b9d02a9b..56f997b83 100644 --- a/src/policyengine/tax_benefit_models/common/model_version.py +++ b/src/policyengine/tax_benefit_models/common/model_version.py @@ -203,6 +203,13 @@ def require_data_certification(self): runtime_model_version=installed, runtime_data_build_fingerprint=build.get("data_build_fingerprint"), ) + if certification.compatibility_basis == ( + "unverified_data_release_manifest_unavailable" + ): + raise ValueError( + f"Cannot certify the bundled {self.country_code.upper()} data for " + f"{self.package_name} {installed} without its data release manifest." + ) self.data_certification = certification return certification diff --git a/src/policyengine/tax_benefit_models/us/model.py b/src/policyengine/tax_benefit_models/us/model.py index f4ba41c51..7a9bf3d29 100644 --- a/src/policyengine/tax_benefit_models/us/model.py +++ b/src/policyengine/tax_benefit_models/us/model.py @@ -66,8 +66,8 @@ class PolicyEngineUS(TaxBenefitModel): class PolicyEngineUSLatest(MicrosimulationModelVersion): """US runtime metadata with certification deferred until selected. - ``data_certification`` stays unset at import. Certified operations validate - the current runtime before exposing bundle provenance or using bundled data. + ``data_certification`` starts unset. Managed operations validate the current + runtime before exposing bundle provenance or using bundled data. """ country_code = "us" @@ -186,8 +186,11 @@ def release_bundle(self): self.require_data_certification() return super().release_bundle - def load(self, simulation): + def _validate_cached_output(self) -> None: self.require_data_certification() + + def load(self, simulation): + self._validate_cached_output() return super().load(simulation) # --- run ------------------------------------------------------------- diff --git a/tests/test_us_unmanaged_runtime.py b/tests/test_us_unmanaged_runtime.py index 75376eab5..ede8336e3 100644 --- a/tests/test_us_unmanaged_runtime.py +++ b/tests/test_us_unmanaged_runtime.py @@ -5,6 +5,10 @@ import hashlib import importlib +import os +import subprocess +import sys +import textwrap from contextlib import nullcontext from importlib import metadata from types import SimpleNamespace @@ -14,7 +18,10 @@ import policyengine.provenance.dataset_materialization as materialization import policyengine.tax_benefit_models.common.model_version as common from policyengine.provenance import loaded -from policyengine.provenance.manifest import get_release_manifest +from policyengine.provenance.manifest import ( + DataReleaseManifestUnavailableError, + get_release_manifest, +) us_model = importlib.import_module("policyengine.tax_benefit_models.us.model") us_datasets = importlib.import_module("policyengine.tax_benefit_models.us.datasets") @@ -24,6 +31,51 @@ def refuse_certification(*args, **kwargs): raise ValueError("test incompatible bundled data") +def test_package_import_is_offline_with_an_out_of_range_us_version(): + script = textwrap.dedent( + """ + import sys + from importlib import metadata + from importlib.util import find_spec + + assert find_spec("policyengine_us") is not None + installed_version = metadata.version + + def mock_version(name): + return "2.3.0" if name == "policyengine-us" else installed_version(name) + + metadata.version = mock_version + attempts = [] + + def guard(event, args): + if event in {"socket.connect", "socket.getaddrinfo", "socket.gethostbyname"}: + attempts.append(event) + raise OSError("network blocked") + + sys.addaudithook(guard) + import policyengine + + assert attempts == [], attempts + assert "policyengine_us" not in sys.modules + assert "policyengine_uk" not in sys.modules + assert {"us", "uk"} <= set(dir(policyengine)) + assert policyengine.__version__ == installed_version("policyengine") + """ + ) + env = os.environ.copy() + env.pop("POLICYENGINE_SKIP_COUNTRY_IMPORTS", None) + env.pop("PYTHONPATH", None) + result = subprocess.run( + [sys.executable, "-c", script], + capture_output=True, + text=True, + timeout=60, + check=False, + env=env, + ) + assert result.returncode == 0, result.stderr + + @pytest.mark.parametrize("allow_unmanaged", [False, True]) @pytest.mark.parametrize("selection", [None, "name", "uri"]) def test_managed_selection_certifies_before_cache_or_download( @@ -57,6 +109,19 @@ def test_remote_unmanaged_source_keeps_certification(monkeypatch): ) +def test_unlisted_name_certifies_before_resolving_remote_data(monkeypatch): + monkeypatch.setattr( + materialization, "_require_us_data_certification", refuse_certification + ) + monkeypatch.setattr( + materialization, + "resolve_managed_dataset_reference", + lambda *args, **kwargs: pytest.fail("Resolved a name before certification"), + ) + with pytest.raises(ValueError, match="incompatible bundled data"): + materialization.materialize_dataset("us", "unlisted", allow_unmanaged=True) + + def test_local_source_requires_opt_in_and_avoids_unused_bundle(monkeypatch, tmp_path): path = tmp_path / "inert-local-fixture.bin" path.write_bytes(b"test source plumbing only") @@ -103,6 +168,42 @@ def test_managed_simulation_and_cached_output_keep_guard(monkeypatch, entry): getattr(us_model.us_latest, entry)(None) +def test_managed_in_memory_output_rechecks_certification(monkeypatch): + from policyengine.core import Simulation + from policyengine.core.simulation import _cache + + simulation = Simulation(tax_benefit_model_version=us_model.us_latest) + monkeypatch.setattr(_cache, "get", lambda key: simulation.model_copy()) + monkeypatch.setattr( + us_model.PolicyEngineUSLatest, + "require_data_certification", + refuse_certification, + ) + with pytest.raises(ValueError, match="incompatible bundled data"): + simulation.ensure() + + +def test_managed_use_refuses_unverified_offline_fallback(monkeypatch): + from policyengine.provenance import manifest + + def offline(country): + raise DataReleaseManifestUnavailableError("test offline manifest") + + monkeypatch.setattr(manifest, "get_data_release_manifest", offline) + monkeypatch.setattr(metadata, "version", lambda name: "2.3.0") + monkeypatch.setattr(loaded, "loaded_versions", lambda: {"policyengine-us": "2.3.0"}) + monkeypatch.setattr( + us_model.PolicyEngineUSLatest, + "_get_runtime_data_build_metadata", + lambda self: {}, + ) + model = us_model.PolicyEngineUSLatest.model_construct(data_certification=None) + + with pytest.raises(ValueError, match="Cannot certify the bundled US data"): + _ = model.release_bundle + assert model.data_certification is None + + def test_only_us_defers_the_initial_certification(monkeypatch): cls = us_model.PolicyEngineUSLatest monkeypatch.setattr( From de6b233481560ff09de5eb6ab1da5bd1cb48e143 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 30 Nov 2026 14:02:50 -0500 Subject: [PATCH 08/20] Require PR code checks and verify wheels before publishing Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- .github/workflows/certify-uk-release.yaml | 16 +-- .github/workflows/pr_agent_notes.yaml | 10 +- .github/workflows/pr_code_changes.yaml | 87 ++++++++++-- .github/workflows/push.yaml | 14 +- changelog.d/761.changed.md | 3 + docs/engineering/runbooks/uk-qualification.md | 15 ++- tests/test_pr_code_checks.py | 125 ++++++++++++++++++ tests/test_spm_bundle_bootstrap.py | 21 +++ tests/test_uk_qualification_workflow.py | 4 +- 9 files changed, 258 insertions(+), 37 deletions(-) create mode 100644 changelog.d/761.changed.md create mode 100644 tests/test_pr_code_checks.py diff --git a/.github/workflows/certify-uk-release.yaml b/.github/workflows/certify-uk-release.yaml index 1ea4ed688..09794dabc 100644 --- a/.github/workflows/certify-uk-release.yaml +++ b/.github/workflows/certify-uk-release.yaml @@ -1,29 +1,25 @@ -# Qualify each new policyengine-uk wheel or uk-data release before promotion. +# Run UK qualification manually from 30 November 2026. This workflow reads +# only the retired uk-data line. A UK pair check will replace it. # # A candidate pair (newest model wheel, the core it needs, newest data # release) is resolved and deduplicated against the ledger, certified into a # candidate commit on candidate/uk/- (manifest, pins, uv.lock, # TRO, test constants and snapshots regenerated together), qualified by the # mandatory gates on that exact commit, replayed by policyengine-scorecard, -# and recorded in the uk-qualification-ledger branch. Promotion is -# serialized: it readies the newest promotable candidate PR that advances +# and recorded in the uk-qualification-ledger branch. Promotion runs +# serially. It readies the newest promotable candidate PR that advances # main, closes superseded ones and those of pairs from another data line # (which are never promoted), and (cos d1344) fast-forwards main to its # qualified commit once every check on it has passed, which succeeds only # while main is still the commit it was built on; otherwise the catch-up # requalifies it on current main. # -# Triggers: a policyengine-uk publish or uk-data release (repository -# dispatch), a two-hourly catch-up, or a manual run. A manual run with -# accept_pair_id records a reviewer's acceptance of a needs-review receipt. +# A manual run with accept_pair_id records a reviewer's acceptance of a +# needs-review receipt. name: Certify UK release candidates on: - repository_dispatch: - types: [policyengine-uk-release, policyengine-uk-data-release] - schedule: - - cron: "23 */2 * * *" workflow_dispatch: inputs: model_version: diff --git a/.github/workflows/pr_agent_notes.yaml b/.github/workflows/pr_agent_notes.yaml index 2f479a627..12a91a792 100644 --- a/.github/workflows/pr_agent_notes.yaml +++ b/.github/workflows/pr_agent_notes.yaml @@ -5,12 +5,10 @@ # on 23 October 2026. .github/check-agent-notes.sh lists the paths it # rejects. # -# pr_code_changes.yaml has a path filter, so a pull request that adds only -# such files runs none of its jobs. This workflow has no path or branch -# filter. It checks the pull request's head commit, fetched as data, not the -# merge with the base, so the base cannot change the result. Main has none -# of these paths, so a pull request based on main fails exactly when it adds -# one. "edited" covers a retarget: a stacked pull request whose old base had +# This workflow checks every pull request's head commit as fetched, so the +# base cannot change the result. Main has none of these paths, so a pull +# request based on main fails exactly when it adds one. +# "edited" covers a retarget: a stacked pull request whose old base had # no guard first gets one when it is retargeted to main. Every edit runs the # full check, so a title edit cannot replace a failure with a skipped run. # diff --git a/.github/workflows/pr_code_changes.yaml b/.github/workflows/pr_code_changes.yaml index 98b4d1e7b..cfb1714e4 100644 --- a/.github/workflows/pr_code_changes.yaml +++ b/.github/workflows/pr_code_changes.yaml @@ -1,4 +1,5 @@ -# Workflow that runs on code changes to a pull request. +# Report PR code checks on every pull request. Run the code jobs when the +# changes include files outside the documentation or when dispatched manually. # # Runners. These jobs, the docs build, and Lint and Test on pushes to main # run on ubuntu-latest unless a repository variable names another runner @@ -23,15 +24,7 @@ name: Code changes on: pull_request: - paths: - - src/** - - tests/** - - scripts/** - - .github/** - - changelog.d/** - - pyproject.toml - - uv.lock - - src/policyengine/data/bundle/manifest.json + types: [opened, synchronize, reopened, edited] workflow_dispatch: concurrency: @@ -39,8 +32,44 @@ concurrency: cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: + Changes: + name: Detect code changes + runs-on: ubuntu-latest + permissions: + contents: read + timeout-minutes: 10 + outputs: + code: ${{ steps.paths.outputs.code }} + steps: + - uses: actions/checkout@v6 + if: github.event_name == 'pull_request' + with: + fetch-depth: 0 + persist-credentials: false + - name: Check changed paths + id: paths + env: + EVENT: ${{ github.event_name }} + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + status=1 + if [[ "$EVENT" == pull_request ]]; then + status=0 + git diff --quiet "$BASE_SHA...$HEAD_SHA" -- . ':(exclude)docs/**' \ + ':(exclude)README.md' ':(exclude)CONTRIBUTING.md' \ + ':(exclude)CHANGELOG.md' ':(exclude)CODE_OF_CONDUCT.md' || status=$? + fi + case "$status" in + 0) echo "code=false" >> "$GITHUB_OUTPUT" ;; + 1) echo "code=true" >> "$GITHUB_OUTPUT" ;; + *) exit "$status" ;; + esac + check-changelog: name: Check changelog fragment + needs: Changes + if: needs.Changes.outputs.code == 'true' runs-on: ${{ vars.CI_RUNNER_X64 != '' && (vars.CI_RUNNER_EVENTS == '' || contains(format(',{0},', vars.CI_RUNNER_EVENTS), format(',{0},', github.event_name))) && vars.CI_RUNNER_X64 || 'ubuntu-latest' }} permissions: contents: read @@ -54,6 +83,8 @@ jobs: - name: Check for changelog fragment run: .github/check-changelog.sh Lint: + needs: Changes + if: needs.Changes.outputs.code == 'true' runs-on: ${{ vars.CI_RUNNER_X64 != '' && (vars.CI_RUNNER_EVENTS == '' || contains(format(',{0},', vars.CI_RUNNER_EVENTS), format(',{0},', github.event_name))) && vars.CI_RUNNER_X64 || 'ubuntu-latest' }} permissions: contents: read @@ -69,6 +100,8 @@ jobs: - name: Run ruff check run: ruff check . Mypy: + needs: Changes + if: needs.Changes.outputs.code == 'true' runs-on: ${{ vars.CI_RUNNER_X64 != '' && (vars.CI_RUNNER_EVENTS == '' || contains(format(',{0},', vars.CI_RUNNER_EVENTS), format(',{0},', github.event_name))) && vars.CI_RUNNER_X64 || 'ubuntu-latest' }} permissions: contents: read @@ -89,6 +122,8 @@ jobs: run: mypy src/policyengine || echo "mypy found errors (non-blocking until codebase is clean)" Python-Compat: name: Install + smoke-import (py${{ matrix.python-version }}) + needs: Changes + if: needs.Changes.outputs.code == 'true' runs-on: ${{ vars.CI_RUNNER_X64 != '' && (vars.CI_RUNNER_EVENTS == '' || contains(format(',{0},', vars.CI_RUNNER_EVENTS), format(',{0},', github.event_name))) && vars.CI_RUNNER_X64 || 'ubuntu-latest' }} permissions: contents: read @@ -114,8 +149,9 @@ jobs: run: python -c "import policyengine; from policyengine.core import Dataset, Policy, Simulation; from policyengine.outputs import aggregate, poverty, inequality; print('import OK')" BundleVerification: name: Verify release inputs and bundle packages + needs: Changes # Private manifest credentials are available only to trusted repository PRs. - if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository + if: needs.Changes.outputs.code == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) runs-on: ${{ vars.CI_RUNNER_X64 != '' && (vars.CI_RUNNER_EVENTS == '' || contains(format(',{0},', vars.CI_RUNNER_EVENTS), format(',{0},', github.event_name))) && vars.CI_RUNNER_X64 || 'ubuntu-latest' }} permissions: contents: read @@ -170,6 +206,8 @@ jobs: - name: Verify bundle packages run: policyengine bundle verify --country us --country uk --packages-only --json Test: + needs: Changes + if: needs.Changes.outputs.code == 'true' runs-on: ${{ vars.CI_RUNNER_X64 != '' && (vars.CI_RUNNER_EVENTS == '' || contains(format(',{0},', vars.CI_RUNNER_EVENTS), format(',{0},', github.event_name))) && vars.CI_RUNNER_X64 || 'ubuntu-latest' }} permissions: contents: read @@ -209,3 +247,30 @@ jobs: run: make test env: HUGGING_FACE_TOKEN: ${{ secrets.HUGGING_FACE_TOKEN }} + + PR-Checks: + name: PR code checks + if: always() + needs: [Changes, check-changelog, Lint, Mypy, Python-Compat, BundleVerification, Test] + runs-on: ubuntu-latest + permissions: {} + timeout-minutes: 5 + steps: + - name: Fail when a dependency failed or was cancelled + if: failure() || cancelled() + run: exit 1 + - name: Check code job results + env: + RESULTS: ${{ toJSON(needs) }} + VERIFY_BUNDLE: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }} + run: | + jq -e --arg verify_bundle "$VERIFY_BUNDLE" ' + .Changes as $changes | + $changes.result == "success" and + ($changes.outputs.code == "true" or $changes.outputs.code == "false") and + all(del(.Changes) | to_entries[]; + .value.result == + (if $changes.outputs.code == "false" or + (.key == "BundleVerification" and $verify_bundle == "false") + then "skipped" else "success" end)) + ' <<< "$RESULTS" diff --git a/.github/workflows/push.yaml b/.github/workflows/push.yaml index 33e0e82bf..812f2f163 100644 --- a/.github/workflows/push.yaml +++ b/.github/workflows/push.yaml @@ -176,9 +176,8 @@ jobs: Publish: runs-on: ubuntu-latest if: github.event.head_commit.message == 'Update package version' - # PyPI trusted publishing: PyPI accepts uploads only from this workflow in - # the pypi environment, which is limited to main. id-token: write comes - # from the workflow-level permissions. No stored PyPI token. + # PyPI accepts uploads from this workflow through trusted publishing. + # The pypi environment allows main and release/uk-autumn-budget-2026. environment: pypi env: GH_TOKEN: ${{ github.token }} @@ -217,6 +216,15 @@ jobs: run: ".github/publish-git-tag.sh" - name: Build package run: python -m build + - name: Smoke-test the built wheel + run: | + smoke_dir=$(mktemp -d "$RUNNER_TEMP/policyengine-wheel.XXXXXX") + python -m venv "$smoke_dir/venv" + "$smoke_dir/venv/bin/python" -m pip install dist/*.whl + cd "$smoke_dir" + unset PYTHONPATH + "$smoke_dir/venv/bin/python" -c "import policyengine; print(policyengine.__version__)" + "$smoke_dir/venv/bin/policyengine" bundle manifest > /dev/null - name: Export bundle release assets run: python scripts/export_bundle_release_assets.py --dist-dir release-assets - name: Verify bundle package metadata diff --git a/changelog.d/761.changed.md b/changelog.d/761.changed.md new file mode 100644 index 000000000..bf375e82b --- /dev/null +++ b/changelog.d/761.changed.md @@ -0,0 +1,3 @@ +Report PR code checks on every pull request and skip the code jobs for documentation-only changes. +Run the legacy UK qualification workflow only on manual dispatch. +Document both branches that can publish to PyPI and install and smoke-test the built wheel before upload. diff --git a/docs/engineering/runbooks/uk-qualification.md b/docs/engineering/runbooks/uk-qualification.md index 9392e340c..062c8c3ea 100644 --- a/docs/engineering/runbooks/uk-qualification.md +++ b/docs/engineering/runbooks/uk-qualification.md @@ -1,10 +1,13 @@ # UK candidate qualification: what the ledger shows, and reproducing a gate -The `certify-uk-release` workflow qualifies each new policyengine-uk wheel -or uk-data release before promotion (`scripts/check_uk_candidate.py`, -`policyengine.provenance.uk_candidate`). Each attempt's gate results and -evidence are written to the `uk-qualification-ledger` branch, which is -public, so the evidence keeps nothing from the survey data that could +From 30 November 2026, start the `certify-uk-release` workflow manually. +It reads only the retired uk-data line, so it no longer runs on a schedule +or on release dispatches. A UK pair check will replace it. + +The workflow qualifies candidate policyengine-uk and uk-data pairs before +promotion (`scripts/check_uk_candidate.py`, `policyengine.provenance.uk_candidate`). +It writes each attempt's gate results and evidence to the public +`uk-qualification-ledger` branch and withholds any survey data that could identify a record. ## What the ledger withholds @@ -76,7 +79,7 @@ job fails with `::error:: waits on runs refresh will not re-run`, naming each run, its result and its attempts. That covers a run at four attempts, one older than 30 days, and one whose result refresh never re-runs (`action_required`, `skipped`, `stale`, `startup_failure` and the like). The -job fails on every scheduled run until one of these clears it: +job fails on each run until one of these clears it: - Fix the cause, then re-run the named run by hand (`gh run rerun --repo PolicyEngine/policyengine.py`); a passing diff --git a/tests/test_pr_code_checks.py b/tests/test_pr_code_checks.py new file mode 100644 index 000000000..a3e20c3d5 --- /dev/null +++ b/tests/test_pr_code_checks.py @@ -0,0 +1,125 @@ +"""Exercise the PR code path check and the required job's result handling.""" + +import json +import os +import subprocess +from pathlib import Path + +import pytest +import yaml + +WORKFLOW = ( + Path(__file__).resolve().parents[1] / ".github/workflows/pr_code_changes.yaml" +) + + +def test_code_checks_run_for_every_pull_request(): + workflow = yaml.safe_load(WORKFLOW.read_text()) + triggers = workflow.get("on", workflow.get(True)) + assert set(triggers["pull_request"]) == {"types"} + assert set(triggers["pull_request"]["types"]) == { + "opened", + "synchronize", + "reopened", + "edited", + } + assert "workflow_dispatch" in triggers + jobs = workflow["jobs"] + required = jobs["PR-Checks"] + assert required["name"] == "PR code checks" + assert required["if"] == "always()" + assert required["steps"][0]["if"] == "failure() || cancelled()" + assert required["steps"][0]["run"] == "exit 1" + assert set(required["needs"]) == set(jobs) - {"PR-Checks"} + for name in set(required["needs"]) - {"Changes"}: + assert jobs[name]["needs"] == "Changes" + assert "needs.Changes.outputs.code == 'true'" in jobs[name]["if"] + + +def test_classifies_docs_only_and_checks_manually_dispatched_runs(tmp_path): + command = yaml.safe_load(WORKFLOW.read_text())["jobs"]["Changes"]["steps"][-1][ + "run" + ] + + def git(*args): + return subprocess.check_output( + ["git", *args], + cwd=tmp_path, + text=True, + ).strip() + + git("init", "-q") + git("config", "user.name", "Test") + git("config", "user.email", "test@example.org") + git("commit", "--allow-empty", "-qm", "Base") + base = git("rev-parse", "HEAD") + output = tmp_path / "output" + + def classify(event): + output.write_text("") + result = subprocess.run( + ["bash", "-ec", command], + cwd=tmp_path, + env={ + **os.environ, + "EVENT": event, + "BASE_SHA": base, + "HEAD_SHA": git("rev-parse", "HEAD"), + "GITHUB_OUTPUT": str(output), + }, + check=False, + ) + assert result.returncode == 0 + return output.read_text().strip() + + (tmp_path / "docs").mkdir() + (tmp_path / "docs/overview.md").write_text("Overview") + (tmp_path / "README.md").write_text("Read me") + git("add", "docs", "README.md") + git("commit", "-qm", "Update documentation") + assert classify("pull_request") == "code=false" + assert classify("workflow_dispatch") == "code=true" + + (tmp_path / "code.py").write_text("pass") + git("add", "code.py") + git("commit", "-qm", "Add code") + assert classify("pull_request") == "code=true" + + +@pytest.mark.parametrize( + "code, trusted, changes, lint, bundle, passes", + [ + ("false", True, "success", "skipped", "skipped", True), + ("true", True, "success", "success", "success", True), + ("true", False, "success", "success", "skipped", True), + ("true", True, "success", "failure", "success", False), + ("true", True, "success", "cancelled", "success", False), + ("true", True, "success", "skipped", "success", False), + ("true", True, "success", "success", "skipped", False), + ("false", True, "failure", "skipped", "skipped", False), + ], +) +def test_required_job_reports_only_expected_results( + code, trusted, changes, lint, bundle, passes +): + job = yaml.safe_load(WORKFLOW.read_text())["jobs"]["PR-Checks"] + results = { + name: {"result": "success" if code == "true" else "skipped"} + for name in job["needs"] + } + results["Changes"] = {"result": changes, "outputs": {"code": code}} + results["Lint"] = {"result": lint} + results["BundleVerification"] = {"result": bundle} + result = subprocess.run( + ["bash", "-ec", job["steps"][-1]["run"]], + env={ + **os.environ, + "RESULTS": json.dumps(results), + "VERIFY_BUNDLE": json.dumps(trusted), + }, + capture_output=True, + text=True, + check=False, + ) + assert result.returncode in (0, 1), result.stderr + assert (result.returncode == 0) is passes, result.stderr diff --git a/tests/test_spm_bundle_bootstrap.py b/tests/test_spm_bundle_bootstrap.py index bb17c402a..640a9e589 100644 --- a/tests/test_spm_bundle_bootstrap.py +++ b/tests/test_spm_bundle_bootstrap.py @@ -123,3 +123,24 @@ def test_release_checks_published_spm_before_publication_and_after_pypi_visibili strict_gate = runs.index("python -S scripts/bundle.py check --published-spm") dispatch = runs.index("bash .github/dispatch-policyengine-release.sh") assert wait < strict_gate < dispatch + + +def test_publish_smoke_tests_the_wheel_before_upload(): + source = (REPO_ROOT / ".github/workflows/push.yaml").read_text() + publish = yaml.safe_load(source)["jobs"]["Publish"] + assert publish["environment"] == "pypi" + assert ( + "The pypi environment allows main and release/uk-autumn-budget-2026." in source + ) + + steps = publish["steps"] + names = [step["name"] for step in steps] + smoke = names.index("Smoke-test the built wheel") + assert names.index("Build package") < smoke + assert smoke < names.index("Publish a Python distribution to PyPI") + + command = steps[smoke]["run"] + assert "python -m venv" in command + assert 'venv/bin/python" -m pip install dist/*.whl' in command + assert "import policyengine; print(policyengine.__version__)" in command + assert 'venv/bin/policyengine" bundle manifest' in command diff --git a/tests/test_uk_qualification_workflow.py b/tests/test_uk_qualification_workflow.py index 1e07a780e..2ba1fc96b 100644 --- a/tests/test_uk_qualification_workflow.py +++ b/tests/test_uk_qualification_workflow.py @@ -128,7 +128,9 @@ def test_every_dispatch_names_the_exact_pair(): its place.""" workflow = _workflow() - inputs = workflow[True]["workflow_dispatch"]["inputs"] + triggers = workflow[True] + assert set(triggers) == {"workflow_dispatch"} + inputs = triggers["workflow_dispatch"]["inputs"] assert {"core_version", "pair_id"} <= set(inputs) resolve = next( step From 7060037c79d9562ef1c73c1f54bd51ff6ac58ffb Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 30 Nov 2026 14:26:49 -0500 Subject: [PATCH 09/20] Isolate explicit US download tests from certification Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- tests/test_dataset_source.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/test_dataset_source.py b/tests/test_dataset_source.py index 589325657..67ae9d0c2 100644 --- a/tests/test_dataset_source.py +++ b/tests/test_dataset_source.py @@ -42,7 +42,10 @@ def get(self, url, **kwargs): def _download(uri, tmp_path, session): - with patch.object(dataset_source.requests, "get", side_effect=session.get): + with ( + patch.object(dataset_source, "_require_us_data_certification", autospec=True), + patch.object(dataset_source.requests, "get", side_effect=session.get), + ): return materialize_dataset( "us", uri, From 7aec0df9bea3337534ea78cc50604ffb5ba0780a Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 30 Nov 2026 14:33:40 -0500 Subject: [PATCH 10/20] Keep UK qualification preparation tests offline Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- tests/test_uk_qualification_pipeline.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/test_uk_qualification_pipeline.py b/tests/test_uk_qualification_pipeline.py index ea07e2d0f..ec1d58b9d 100644 --- a/tests/test_uk_qualification_pipeline.py +++ b/tests/test_uk_qualification_pipeline.py @@ -655,6 +655,8 @@ def data_manifest(country=None): certification.parse_manifest_uri(uri), ), ) + # The tagged fixture's repository has no release index at main. + monkeypatch.setattr(certification, "_releases_record_at_main", lambda *args: None) monkeypatch.setattr( certification, "fetch_pypi_wheel_metadata", From da6a4cb01c9a3dbbadcd643e3bb36905065d114d Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 22:48:41 -0500 Subject: [PATCH 11/20] Record the local US source and preserve native period inputs Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- changelog.d/760.added.md | 1 + changelog.d/760.fixed.md | 4 +- docs/microsim.md | 10 +++-- .../tax_benefit_models/us/model.py | 12 +++--- tests/test_dataset_source.py | 10 ++++- tests/test_us_unmanaged_runtime.py | 39 +++++++++++++++++++ 6 files changed, 62 insertions(+), 14 deletions(-) create mode 100644 changelog.d/760.added.md diff --git a/changelog.d/760.added.md b/changelog.d/760.added.md new file mode 100644 index 000000000..be90ee180 --- /dev/null +++ b/changelog.d/760.added.md @@ -0,0 +1 @@ +Add `native_input_period` for explicit local TIME_PERIOD_ARRAYS files. A four-digit year string sets the input and calculation defaults before the country constructor while preserving each stored period. The option requires a nonempty `.h5` file. diff --git a/changelog.d/760.fixed.md b/changelog.d/760.fixed.md index 65c9465a5..7aedf4adb 100644 --- a/changelog.d/760.fixed.md +++ b/changelog.d/760.fixed.md @@ -1,3 +1 @@ -Allow explicit local US datasets with `allow_unmanaged=True` to record unverified runtime provenance without certifying the unused default data bundle. Keep certification on bundled data, cached year files and managed simulation entrypoints. - -Add `native_input_period` for explicit local TIME_PERIOD_ARRAYS files so callers can bind the input clock before the first country constructor while preserving each stored period. Require current US data certification before exporting bundle provenance. Reject non-H5 native paths and report empty native HDF5 roots with a clear value error. +Allow explicit local US datasets with `allow_unmanaged=True` to record unverified runtime provenance without certifying the unused default data bundle. Keep certification on bundled data, cached year files, managed simulation entrypoints and bundle provenance exports. diff --git a/docs/microsim.md b/docs/microsim.md index 273126663..0b96c7d59 100644 --- a/docs/microsim.md +++ b/docs/microsim.md @@ -423,13 +423,15 @@ sim = managed_microsimulation() # `sim` is a policyengine_us.Microsimulation — use its API directly ``` -Pass `allow_unmanaged=True` with a custom `dataset=` to opt out of the release -bundle. Explicit local paths and Hugging Face URIs remain supported in this -mode. GCS dataset URIs are not supported. +Pass `allow_unmanaged=True` with an explicit local file to bypass bundled-data +certification in `managed_microsimulation()`. Explicit Hugging Face URIs also +require `allow_unmanaged=True`, and the wrapper checks US bundled-data +certification before fetching them. GCS dataset URIs are unsupported. An explicit local US file records its SHA-256 and the installed wrapper, country, Core and SPM versions in `sim.policyengine_bundle`. Its `compatibility_basis` records `unverified_explicit_local_unmanaged`, and `certified_by` records `None`. +The `managed_by` field names the wrapper that constructed the simulation. A bare `import policyengine` defers both country namespaces until they are accessed. Accessing the UK namespace still certifies data during initialisation. The US wrapper certifies at first managed use, including bundled and named data, @@ -442,7 +444,7 @@ set the Core Dataset descriptor's annual clock and both default input and calculation periods before the first country constructor. The wrapper preserves stored period keys, including monthly inputs and earlier lookbacks. This option requires `allow_unmanaged=True`, an existing nonempty file with the `.h5` suffix -and a four-digit annual period. It rejects scoping, `dataset_end_year` and +and a four-digit year string. It rejects scoping, `dataset_end_year` and conflicting default input or calculation periods. The caller still selects the tax-benefit system and structural start date. diff --git a/src/policyengine/tax_benefit_models/us/model.py b/src/policyengine/tax_benefit_models/us/model.py index 7a9bf3d29..6e8ddf29f 100644 --- a/src/policyengine/tax_benefit_models/us/model.py +++ b/src/policyengine/tax_benefit_models/us/model.py @@ -603,6 +603,7 @@ def _unmanaged_local_runtime_provenance(source): data_selection="explicit_local_unmanaged", compatibility_basis="unverified_explicit_local_unmanaged", certified_by=None, + country_id="us", model_package="policyengine-us", model_version=versions["policyengine-us"], policyengine_version=versions["policyengine"], @@ -670,10 +671,10 @@ def managed_microsimulation( calculations. This retains earlier supplied income for lookbacks. The unscoped constructor continues to own projection and reform timing. - ``native_input_period="2017"`` binds both input and calculation defaults - before the first country constructor for an explicit local ``.h5`` - TIME_PERIOD_ARRAYS file. It preserves each array's period and does not - project or rescope the file. + Pass a four-digit year string such as ``native_input_period="2017"`` to + bind both defaults before the first country constructor for an explicit + local ``.h5`` TIME_PERIOD_ARRAYS file. The option preserves each array's + period. Projection and scoping options are incompatible with this argument. The caller still selects the tax-benefit system and structural start date. """ @@ -739,8 +740,9 @@ def managed_microsimulation( and dataset is not None and source.bundle_dataset is None and "://" not in source.source_uri - and Path(source.path).is_file() ) + if explicit_local and not Path(source.path).is_file(): + raise ValueError(f"Explicit local US dataset must be a file: {source.path!r}") local_provenance = ( _unmanaged_local_runtime_provenance(source) if explicit_local else None ) diff --git a/tests/test_dataset_source.py b/tests/test_dataset_source.py index 67ae9d0c2..c29d0aeff 100644 --- a/tests/test_dataset_source.py +++ b/tests/test_dataset_source.py @@ -42,9 +42,15 @@ def get(self, url, **kwargs): def _download(uri, tmp_path, session): + def get_after_certifying(*args, **kwargs): + certify.assert_called_once_with() + return session.get(*args, **kwargs) + with ( - patch.object(dataset_source, "_require_us_data_certification", autospec=True), - patch.object(dataset_source.requests, "get", side_effect=session.get), + patch.object( + dataset_source, "_require_us_data_certification", autospec=True + ) as certify, + patch.object(dataset_source.requests, "get", side_effect=get_after_certifying), ): return materialize_dataset( "us", diff --git a/tests/test_us_unmanaged_runtime.py b/tests/test_us_unmanaged_runtime.py index ede8336e3..f8331de6c 100644 --- a/tests/test_us_unmanaged_runtime.py +++ b/tests/test_us_unmanaged_runtime.py @@ -13,6 +13,7 @@ from importlib import metadata from types import SimpleNamespace +import h5py import pytest import policyengine.provenance.dataset_materialization as materialization @@ -267,6 +268,7 @@ def test_local_factory_records_actual_runtime_without_certificate( assert sim is expected assert receipt["compatibility_basis"] == "unverified_explicit_local_unmanaged" assert receipt["certified_by"] is None + assert receipt["country_id"] == "us" assert receipt["runtime_packages"] == { name: metadata.version(name) for name in ( @@ -283,6 +285,12 @@ def test_local_factory_records_actual_runtime_without_certificate( assert not any(key.startswith("certified_data") for key in receipt) +def test_local_factory_refuses_directory_before_construction(monkeypatch, tmp_path): + local_factory_fixture(monkeypatch, tmp_path) + with pytest.raises(ValueError, match="Explicit local US dataset must be a file"): + us_model.managed_microsimulation(dataset=str(tmp_path), allow_unmanaged=True) + + def test_local_factory_refuses_source_changes_during_construction( monkeypatch, tmp_path ): @@ -390,6 +398,37 @@ def constructor(**kwargs): assert list(arrays["monthly_fixture"]) == ["2017-01"] +def test_native_clock_preserves_periods_in_real_us_constructor(monkeypatch, tmp_path): + from policyengine_core.periods import period + + path = tmp_path / "native-input.h5" + with h5py.File(path, "w") as file: + file.create_dataset("person_id/2017", data=[1]) + for entity in us_model.US_GROUP_ENTITIES: + file.create_dataset(f"{entity}_id/2017", data=[1]) + file.create_dataset(f"person_{entity}_id/2017", data=[1]) + file.create_dataset("age/2015", data=[20]) + file.create_dataset("monthly_age/2017-01", data=[22]) + + monkeypatch.setattr( + us_model.PolicyEngineUSLatest, + "require_data_certification", + refuse_certification, + ) + sim = us_model.managed_microsimulation( + dataset=str(path), allow_unmanaged=True, native_input_period="2017" + ) + + assert sim.dataset.time_period == "2017" + assert sim.default_input_period == "2017" + assert sim.default_calculation_period == "2017" + assert sim.get_holder("age").get_known_periods() == [period("2015")] + assert sim.get_holder("monthly_age").get_known_periods() == [period("2017-01")] + assert sim.get_holder("age").get_array(period("2015")).tolist() == [20] + assert sim.get_holder("monthly_age").get_array(period("2017-01")).tolist() == [22] + assert sim.policyengine_bundle["certified_by"] is None + + @pytest.mark.parametrize( "data_format, arrays, message", [ From 8ec93677df77cbb8b484a8b54eb6d7b63b9a024d Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 22:57:49 -0500 Subject: [PATCH 12/20] Check PR fragments against their target and require all code jobs Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- .github/workflows/certify-uk-release.yaml | 15 ++- .github/workflows/pr_agent_notes.yaml | 6 +- .github/workflows/pr_code_changes.yaml | 17 +++- .github/workflows/push.yaml | 4 +- changelog.d/761.changed.md | 6 +- .../runbooks/canonical-spm-development.md | 4 +- docs/engineering/runbooks/uk-qualification.md | 21 +++-- tests/test_pr_code_checks.py | 92 +++++++++++++++++++ tests/test_spm_bundle_bootstrap.py | 6 +- tests/test_uk_qualification_workflow.py | 22 +++++ 10 files changed, 157 insertions(+), 36 deletions(-) diff --git a/.github/workflows/certify-uk-release.yaml b/.github/workflows/certify-uk-release.yaml index 09794dabc..2d126b53c 100644 --- a/.github/workflows/certify-uk-release.yaml +++ b/.github/workflows/certify-uk-release.yaml @@ -1,5 +1,5 @@ -# Run UK qualification manually from 30 November 2026. This workflow reads -# only the retired uk-data line. A UK pair check will replace it. +# UK candidate qualification starts via workflow_dispatch and resolves legacy +# uk-data pairs. Scheduled recovery and requalification are disabled. # # A candidate pair (newest model wheel, the core it needs, newest data # release) is resolved and deduplicated against the ledger, certified into a @@ -11,8 +11,7 @@ # main, closes superseded ones and those of pairs from another data line # (which are never promoted), and (cos d1344) fast-forwards main to its # qualified commit once every check on it has passed, which succeeds only -# while main is still the commit it was built on; otherwise the catch-up -# requalifies it on current main. +# while main is still the commit it was built on. # # A manual run with accept_pair_id records a reviewer's acceptance of a # needs-review receipt. @@ -294,10 +293,8 @@ jobs: # The local gates took 80-89 minutes while every wrapper.household # contract row errored at once. Since #651 those rows run the household # calculator, which takes the gates past two hours, so a 120-minute limit - # cancelled every attempt and re-staged it. 330 stays under the 360-minute - # ceiling for GitHub-hosted jobs. Note that stage_attempt's four-hour lease - # still lets a catch-up re-stage a live attempt whose gates pass about four - # hours (#662), so in practice runs should stay under that. + # cancelled every attempt. 330 stays under the 360-minute ceiling for + # GitHub-hosted jobs. timeout-minutes: 330 concurrency: group: uk-candidate-${{ needs.resolve.outputs.pair_id }} @@ -414,6 +411,8 @@ jobs: fi gh pr edit "$number" --body-file "$RUNNER_TEMP/pr-body.md" + # Intentionally dormant while workflow_dispatch is the only trigger. + # Its two self-dispatches cannot run without a schedule. catch-up: if: github.event_name == 'schedule' runs-on: ubuntu-latest diff --git a/.github/workflows/pr_agent_notes.yaml b/.github/workflows/pr_agent_notes.yaml index 12a91a792..45b14c160 100644 --- a/.github/workflows/pr_agent_notes.yaml +++ b/.github/workflows/pr_agent_notes.yaml @@ -5,9 +5,9 @@ # on 23 October 2026. .github/check-agent-notes.sh lists the paths it # rejects. # -# This workflow checks every pull request's head commit as fetched, so the -# base cannot change the result. Main has none of these paths, so a pull -# request based on main fails exactly when it adds one. +# On each subscribed pull-request event, the guard checks the fetched PR head +# tree using the default branch's guard when available. Main has none of these +# paths, so a pull request based on main fails exactly when it adds one. # "edited" covers a retarget: a stacked pull request whose old base had # no guard first gets one when it is retargeted to main. Every edit runs the # full check, so a title edit cannot replace a failure with a skipped run. diff --git a/.github/workflows/pr_code_changes.yaml b/.github/workflows/pr_code_changes.yaml index cfb1714e4..706e45493 100644 --- a/.github/workflows/pr_code_changes.yaml +++ b/.github/workflows/pr_code_changes.yaml @@ -1,5 +1,6 @@ -# Report PR code checks on every pull request. Run the code jobs when the -# changes include files outside the documentation or when dispatched manually. +# Report PR code checks on opened, synchronised, reopened and edited pull +# requests and on manual dispatch. Skip code jobs when a pull request's +# changed paths match the documentation exclusions. # # Runners. These jobs, the docs build, and Lint and Test on pushes to main # run on ubuntu-latest unless a repository variable names another runner @@ -77,11 +78,15 @@ jobs: steps: - uses: actions/checkout@v6 with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} fetch-depth: 0 + persist-credentials: false - name: Install towncrier run: pip install towncrier - name: Check for changelog fragment - run: .github/check-changelog.sh + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: .github/check-changelog.sh "${BASE_SHA:-origin/main}" Lint: needs: Changes if: needs.Changes.outputs.code == 'true' @@ -265,12 +270,14 @@ jobs: VERIFY_BUNDLE: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }} run: | jq -e --arg verify_bundle "$VERIFY_BUNDLE" ' - .Changes as $changes | + (keys == ["BundleVerification", "Changes", "Lint", "Mypy", + "Python-Compat", "Test", "check-changelog"]) and + (.Changes as $changes | $changes.result == "success" and ($changes.outputs.code == "true" or $changes.outputs.code == "false") and all(del(.Changes) | to_entries[]; .value.result == (if $changes.outputs.code == "false" or (.key == "BundleVerification" and $verify_bundle == "false") - then "skipped" else "success" end)) + then "skipped" else "success" end))) ' <<< "$RESULTS" diff --git a/.github/workflows/push.yaml b/.github/workflows/push.yaml index 812f2f163..9a50e0a39 100644 --- a/.github/workflows/push.yaml +++ b/.github/workflows/push.yaml @@ -97,7 +97,7 @@ jobs: steps: - uses: actions/checkout@v6 - name: Setup Pages - uses: actions/configure-pages@v3 + uses: actions/configure-pages@v5 - uses: actions/setup-node@v4 with: node-version: 18.x @@ -177,7 +177,7 @@ jobs: runs-on: ubuntu-latest if: github.event.head_commit.message == 'Update package version' # PyPI accepts uploads from this workflow through trusted publishing. - # The pypi environment allows main and release/uk-autumn-budget-2026. + # The pypi GitHub environment controls deployment authorisation for trusted publishing. environment: pypi env: GH_TOKEN: ${{ github.token }} diff --git a/changelog.d/761.changed.md b/changelog.d/761.changed.md index bf375e82b..a0b8f1244 100644 --- a/changelog.d/761.changed.md +++ b/changelog.d/761.changed.md @@ -1,3 +1,3 @@ -Report PR code checks on every pull request and skip the code jobs for documentation-only changes. -Run the legacy UK qualification workflow only on manual dispatch. -Document both branches that can publish to PyPI and install and smoke-test the built wheel before upload. +Report PR code checks on opened, synchronised, reopened and edited pull requests and on manual dispatch. Skip code jobs when a pull request’s changed paths match the documentation exclusions. Check changelog fragments against the pull request’s target. + +Run UK candidate qualification on manual dispatch only. Install and smoke-test the built wheel before uploading distributions to PyPI. diff --git a/docs/engineering/runbooks/canonical-spm-development.md b/docs/engineering/runbooks/canonical-spm-development.md index 89ed8b395..e2bd45114 100644 --- a/docs/engineering/runbooks/canonical-spm-development.md +++ b/docs/engineering/runbooks/canonical-spm-development.md @@ -101,8 +101,8 @@ Run such a script from the wrapper worktree with the isolated interpreter and then call `pe.us.managed_microsimulation(dataset=LOCAL_H5, allow_unmanaged=True, spm={...})`. That local-data call records `compatibility_basis="unverified_explicit_local_unmanaged"` and -`certified_by=None`; it does not attach the development certificate to the local -file. Only that worker is authorized for the heavy population process. +`certified_by=None`. The test plugin supplies a separate unverified fixture +receipt. Only that worker is authorised for the heavy population process. Bundle-only tests avoid the country bootstrap entirely: diff --git a/docs/engineering/runbooks/uk-qualification.md b/docs/engineering/runbooks/uk-qualification.md index 062c8c3ea..a1cad6e2e 100644 --- a/docs/engineering/runbooks/uk-qualification.md +++ b/docs/engineering/runbooks/uk-qualification.md @@ -1,8 +1,7 @@ # UK candidate qualification: what the ledger shows, and reproducing a gate -From 30 November 2026, start the `certify-uk-release` workflow manually. -It reads only the retired uk-data line, so it no longer runs on a schedule -or on release dispatches. A UK pair check will replace it. +UK candidate qualification starts via `workflow_dispatch` and resolves legacy +uk-data pairs. Scheduled recovery and requalification are disabled. The workflow qualifies candidate policyengine-uk and uk-data pairs before promotion (`scripts/check_uk_candidate.py`, `policyengine.provenance.uk_candidate`). @@ -69,10 +68,12 @@ some from fewer than 10 records, so never commit, paste or publish it. Automatic promotion moves main to a qualified candidate only once the newest run of each workflow and event on the candidate branch, from this repository, has passed, including a `pr_code_changes.yaml` run dispatched on the branch -itself. Runs of pull requests from other branches or forks at the same -commit do not count. The `refresh-pr-checks` step re-runs a failed, timed-out or -cancelled run until it has had four attempts, within GitHub's 30 days of its -first attempt. +itself. The candidate-tree code-check dispatch remains reachable. Replay and +acceptance still refresh candidate PR checks. The schedule-only recovery job +and its two self-dispatches are unreachable. Runs of pull requests from other +branches or forks at the same commit do not count. The `refresh-pr-checks` +step re-runs a failed, timed-out or cancelled run until it has had four +attempts, within GitHub's 30 days of its first attempt. When the candidate waits on a run that refresh will not re-run, the promote job fails with `::error:: waits on runs refresh will not re-run`, @@ -136,8 +137,8 @@ drops main's area routing (`--drop-regional-release`), because the routing belongs to the line the pair would replace, and leaves the test constants that pin main's certificate as they are, so the candidate's own tests fail. Its pull request says it is never promoted, and promotion closes it once its receipt is -published, at the commit that receipt qualified. The catch-up does not recover -such a run: re-run it by hand with `force`. A run whose attempt dies before it -publishes a receipt leaves its pull request open; close that one by hand. Changing the data line +published, at the commit that receipt qualified. Re-run the workflow by hand +with `force` to recover an attempt. If an attempt dies before publishing a +receipt, close its open pull request by hand. Changing the data line is a reviewed certification pull request (see `docs/engineering/skills/data-certification.md`), not a promotion. diff --git a/tests/test_pr_code_checks.py b/tests/test_pr_code_checks.py index a3e20c3d5..0a7fab1fe 100644 --- a/tests/test_pr_code_checks.py +++ b/tests/test_pr_code_checks.py @@ -123,3 +123,95 @@ def test_required_job_reports_only_expected_results( ) assert result.returncode in (0, 1), result.stderr assert (result.returncode == 0) is passes, result.stderr + + +def test_retargeted_changelog_requires_a_fragment_added_by_the_pr(tmp_path): + workflow = yaml.safe_load(WORKFLOW.read_text()) + steps = workflow["jobs"]["check-changelog"]["steps"] + check = steps[-1] + repository = WORKFLOW.parents[2] + + def git(*args): + return subprocess.check_output(["git", *args], cwd=tmp_path, text=True).strip() + + git("init", "-qb", "main") + git("config", "user.name", "Test") + git("config", "user.email", "test@example.org") + (tmp_path / ".github").mkdir() + script = tmp_path / ".github/check-changelog.sh" + script.write_bytes((repository / ".github/check-changelog.sh").read_bytes()) + script.chmod(0o755) + (tmp_path / "pyproject.toml").write_bytes( + (repository / "pyproject.toml").read_bytes() + ) + git("add", ".") + git("commit", "-qm", "Initial checkout") + git("branch", "release") + (tmp_path / "README.md").write_text("Main change") + git("add", ".") + git("commit", "-qm", "Advance main") + git("update-ref", "refs/remotes/origin/main", "HEAD") + + git("switch", "-q", "release") + fragments = tmp_path / "changelog.d" + fragments.mkdir() + (fragments / "100.fixed.md").write_text("Existing release fragment") + git("add", ".") + git("commit", "-qm", "Add release fragment") + git("branch", "feature") + (tmp_path / "release.py").write_text("pass") + git("add", ".") + git("commit", "-qm", "Advance release") + release = git("rev-parse", "HEAD") + + git("switch", "-q", "feature") + (tmp_path / "code.py").write_text("pass") + git("add", ".") + git("commit", "-qm", "Add feature without a fragment") + assert git("diff", "--name-only", f"{release}...HEAD") == "code.py" + + def run_check(base): + return subprocess.run( + ["bash", "-ec", check["run"]], + cwd=tmp_path, + env={**os.environ, "BASE_SHA": base}, + capture_output=True, + text=True, + check=False, + ) + + refused = run_check(release) + assert refused.returncode == 1, refused.stdout + refused.stderr + assert "No new newsfragments found" in refused.stdout + assert run_check("").returncode == 0 + + (fragments / "101.fixed.md").write_text("Feature fragment") + git("add", ".") + git("commit", "-qm", "Add feature fragment") + assert run_check(release).returncode == 0 + assert check["env"]["BASE_SHA"] == "${{ github.event.pull_request.base.sha }}" + assert ( + steps[0]["with"]["ref"] + == "${{ github.event.pull_request.head.sha || github.sha }}" + ) + + +@pytest.mark.parametrize("status", [None, "failure", "cancelled", "skipped"]) +def test_required_job_rejects_missing_or_unsuccessful_needs(status): + job = yaml.safe_load(WORKFLOW.read_text())["jobs"]["PR-Checks"] + success = {name: {"result": "success"} for name in job["needs"]} + success["Changes"]["outputs"] = {"code": "true"} + for name in success: + results = dict(success) + if status is None: + del results[name] + else: + results[name] = {**results[name], "result": status} + result = subprocess.run( + ["bash", "-ec", job["steps"][-1]["run"]], + env={**os.environ, "RESULTS": json.dumps(results), "VERIFY_BUNDLE": "true"}, + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 1, (name, status, result.stdout, result.stderr) diff --git a/tests/test_spm_bundle_bootstrap.py b/tests/test_spm_bundle_bootstrap.py index 640a9e589..4b5b767a3 100644 --- a/tests/test_spm_bundle_bootstrap.py +++ b/tests/test_spm_bundle_bootstrap.py @@ -129,9 +129,7 @@ def test_publish_smoke_tests_the_wheel_before_upload(): source = (REPO_ROOT / ".github/workflows/push.yaml").read_text() publish = yaml.safe_load(source)["jobs"]["Publish"] assert publish["environment"] == "pypi" - assert ( - "The pypi environment allows main and release/uk-autumn-budget-2026." in source - ) + assert "The pypi GitHub environment controls deployment authorisation" in source steps = publish["steps"] names = [step["name"] for step in steps] @@ -139,6 +137,8 @@ def test_publish_smoke_tests_the_wheel_before_upload(): assert names.index("Build package") < smoke assert smoke < names.index("Publish a Python distribution to PyPI") + assert "if" not in steps[smoke] + assert not steps[smoke].get("continue-on-error", False) command = steps[smoke]["run"] assert "python -m venv" in command assert 'venv/bin/python" -m pip install dist/*.whl' in command diff --git a/tests/test_uk_qualification_workflow.py b/tests/test_uk_qualification_workflow.py index 2ba1fc96b..f3ad4568a 100644 --- a/tests/test_uk_qualification_workflow.py +++ b/tests/test_uk_qualification_workflow.py @@ -791,3 +791,25 @@ def fake_run(argv, **kwargs): else "#1 (the candidate's own, after a base change)" ) in output assert [call[3] for call in calls if call[:3] == ["gh", "run", "rerun"]] == ["32"] + + +def test_manual_qualification_documents_dormant_schedule_recovery(): + root = Path(__file__).resolve().parents[1] + source = (root / ".github/workflows/certify-uk-release.yaml").read_text() + workflow = yaml.safe_load(source) + assert set(workflow.get("on", workflow.get(True))) == {"workflow_dispatch"} + assert workflow["jobs"]["catch-up"]["if"] == "github.event_name == 'schedule'" + assert "Intentionally dormant while workflow_dispatch is the only trigger" in source + assert ( + sum( + '"gh", "workflow", "run", "certify-uk-release.yaml"' in step.get("run", "") + for step in workflow["jobs"]["catch-up"]["steps"] + ) + == 2 + ) + assert any( + "gh workflow run pr_code_changes.yaml" in step.get("run", "") + for step in workflow["jobs"]["prepare"]["steps"] + ) + runbook = (root / "docs/engineering/runbooks/uk-qualification.md").read_text() + assert "Scheduled recovery and requalification are disabled." in runbook From 0c061e6a03c86c295cce04d39b6f7e4371a57c84 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 22:58:23 -0500 Subject: [PATCH 13/20] Bind US caches and provenance to the runtime and inputs Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- changelog.d/760.fixed.md | 4 +- docs/microsim.md | 21 +- src/policyengine/core/run_record.py | 7 +- src/policyengine/core/simulation.py | 3 + .../core/tax_benefit_model_version.py | 6 + src/policyengine/provenance/manifest.py | 4 +- src/policyengine/provenance/trace.py | 7 +- .../common/model_version.py | 76 +++- .../tax_benefit_models/us/datasets.py | 239 ++++++++---- .../tax_benefit_models/us/legacy_inputs.py | 13 +- .../tax_benefit_models/us/model.py | 83 +++- tests/test_us_legacy_inputs_integration.py | 66 ++-- tests/test_us_unmanaged_runtime.py | 355 +++++++++++++++++- tests/test_us_year_file_stamp.py | 40 +- 14 files changed, 786 insertions(+), 138 deletions(-) diff --git a/changelog.d/760.fixed.md b/changelog.d/760.fixed.md index 7aedf4adb..b382e2104 100644 --- a/changelog.d/760.fixed.md +++ b/changelog.d/760.fixed.md @@ -1 +1,3 @@ -Allow explicit local US datasets with `allow_unmanaged=True` to record unverified runtime provenance without certifying the unused default data bundle. Keep certification on bundled data, cached year files, managed simulation entrypoints and bundle provenance exports. +Allow explicit local US datasets with `allow_unmanaged=True` to record the local file’s SHA-256 and checked package-version metadata with unverified provenance. Keep the explicit local year-file helpers and standalone long-term loader independent of the unused bundled data. + +Check current US runtime certification for managed materialisation, simulation runs and output reuse, model bundle receipts, model TRACE exports and run records with an attached US model. Bind year files to their source and runtime and bind cached simulation outputs to their inputs and runtime. Require self-contained HDF5 for explicit local inputs. diff --git a/docs/microsim.md b/docs/microsim.md index 0b96c7d59..c8ec589fe 100644 --- a/docs/microsim.md +++ b/docs/microsim.md @@ -434,17 +434,28 @@ records `unverified_explicit_local_unmanaged`, and `certified_by` records `None` The `managed_by` field names the wrapper that constructed the simulation. A bare `import policyengine` defers both country namespaces until they are accessed. Accessing the UK namespace still certifies data during initialisation. -The US wrapper certifies at first managed use, including bundled and named data, -year-file caches, managed simulation runs, cached outputs, bundle receipts and -TRACE exports. Constructing an explicit local US simulation bypasses that -certification. +US managed materialisation, managed year-file helpers and the US model’s run, +output-load, cache-reuse, bundle-receipt and TRACE entry points check runtime +compatibility on each call. Run-record export checks the attached US runtime +whether it builds the bundle TRO or receives one from the caller. Direct URI +selection applies the bundle’s selection rules. The compatibility check runs +during managed materialisation. + +`create_datasets()` and `ensure_datasets()` also accept an explicit local source +with `allow_unmanaged=True`. The standalone `load_long_term_datasets()` reads +local files and checks their metadata. `load_managed_long_term_datasets()` +checks bundled-data certification. Year files record the source and runtime +that produced them. Saved US simulation outputs record the input tables and +runtime. Reuse requires matching identities, and `ensure_datasets()` or +`Simulation.ensure()` regenerates older files that lack a matching identity. For a local `.h5` TIME_PERIOD_ARRAYS file, pass `native_input_period="2017"` to set the Core Dataset descriptor's annual clock and both default input and calculation periods before the first country constructor. The wrapper preserves stored period keys, including monthly inputs and earlier lookbacks. This option requires `allow_unmanaged=True`, an existing nonempty file with the `.h5` suffix -and a four-digit year string. It rejects scoping, `dataset_end_year` and +and a four-digit year string. Explicit local HDF5 inputs must be self-contained. +The native clock option rejects scoping, `dataset_end_year` and conflicting default input or calculation periods. The caller still selects the tax-benefit system and structural start date. diff --git a/src/policyengine/core/run_record.py b/src/policyengine/core/run_record.py index d45648631..bb302b083 100644 --- a/src/policyengine/core/run_record.py +++ b/src/policyengine/core/run_record.py @@ -252,13 +252,16 @@ def write_simulation_run_record( ``created_at`` defaults to the simulation's creation time; pass an explicit ISO 8601 string to make record bytes reproducible. """ + model = simulation.tax_benefit_model_version if bundle_tro is None: - if simulation.tax_benefit_model_version is None: + if model is None: raise ValueError( "No bundle TRO available: pass bundle_tro= or attach a " "tax_benefit_model_version with a bundled release manifest." ) - bundle_tro = simulation.tax_benefit_model_version.trace_tro + bundle_tro = model.trace_tro + elif getattr(model, "country_code", None) == "us": + model.require_data_certification() # Build payloads (and surface refusals) before touching the filesystem. payloads = build_simulation_run_record_payloads(simulation) diff --git a/src/policyengine/core/simulation.py b/src/policyengine/core/simulation.py index 74a00e018..8ddbfb125 100644 --- a/src/policyengine/core/simulation.py +++ b/src/policyengine/core/simulation.py @@ -196,6 +196,9 @@ def ensure(self): cached_result = _cache.get(cache_key) if cached_result: self.tax_benefit_model_version._validate_cached_output() + if cached_result and self.tax_benefit_model_version._matches_cached_output( + self, cached_result + ): self.output_dataset = cached_result.output_dataset self.spm = cached_result.spm self.spm_receipt = ( diff --git a/src/policyengine/core/tax_benefit_model_version.py b/src/policyengine/core/tax_benefit_model_version.py index 70237d783..9822b6c89 100644 --- a/src/policyengine/core/tax_benefit_model_version.py +++ b/src/policyengine/core/tax_benefit_model_version.py @@ -108,6 +108,12 @@ def load(self, simulation: "Simulation"): def _validate_cached_output(self) -> None: """Check model-specific requirements before reusing a cached output.""" + def _matches_cached_output( + self, simulation: "Simulation", cached: "Simulation" + ) -> bool: + """Check whether a cached output belongs to the request.""" + return True + def add_parameter(self, param: "Parameter") -> None: """Add a parameter and index it for fast lookup.""" self.parameters.append(param) diff --git a/src/policyengine/provenance/manifest.py b/src/policyengine/provenance/manifest.py index 9b3aa3827..56c20f7d2 100644 --- a/src/policyengine/provenance/manifest.py +++ b/src/policyengine/provenance/manifest.py @@ -1360,7 +1360,9 @@ def resolve_managed_dataset_reference( *, allow_unmanaged: bool = False, ) -> str: - """Resolve a dataset reference under policyengine.py bundle enforcement. + """Resolve a dataset URI using the bundle's selection rules. + + Runtime compatibility is checked when managed data is materialised. Managed mode pins dataset selection to the bundled `policyengine.py` release manifest. Callers can: diff --git a/src/policyengine/provenance/trace.py b/src/policyengine/provenance/trace.py index 0e79b34e8..51edfae8b 100644 --- a/src/policyengine/provenance/trace.py +++ b/src/policyengine/provenance/trace.py @@ -514,13 +514,18 @@ def _build_bundle_performance( started_at: Optional[str], ended_at: Optional[str], ) -> dict[str, Any]: + certified_model_version = ( + certification.certified_for_model_version + if certification is not None + else country_manifest.model_package.version + ) performance: dict[str, Any] = { "@id": "trp/1", "@type": "trov:TransparentResearchPerformance", "rdfs:comment": ( f"Certification of build {certified_data_build_id} for " f"{country_manifest.model_package.name} " - f"{country_manifest.model_package.version}." + f"{certified_model_version}." ), "trov:wasConductedBy": {"@id": "trs"}, "trov:accessedArrangement": {"@id": "arrangement/1"}, diff --git a/src/policyengine/tax_benefit_models/common/model_version.py b/src/policyengine/tax_benefit_models/common/model_version.py index 56f997b83..0ee1e2e86 100644 --- a/src/policyengine/tax_benefit_models/common/model_version.py +++ b/src/policyengine/tax_benefit_models/common/model_version.py @@ -440,6 +440,9 @@ def resolve_entity_variables( resolved[entity] = merged return resolved + def _output_cache_identity(self, simulation: Simulation) -> dict: + raise NotImplementedError + def save(self, simulation: Simulation) -> None: """Persist the simulation's output dataset to its bundled filepath.""" if simulation.output_dataset is None: @@ -463,13 +466,6 @@ def save(self, simulation: Simulation) -> None: raise ValueError( "SPM settings changed since this output was calculated; run again before saving" ) - serialized_spm = json.dumps( - { - "config": simulation.spm_config, - "provenance": receipt.model_dump(mode="json"), - }, - sort_keys=True, - ) # ``PolicyEngineUSDataset.save()`` writes this record into the # file, and ``load()`` refuses an output without it. renames = (getattr(simulation.output_dataset, "metadata", None) or {}).get( @@ -481,6 +477,19 @@ def save(self, simulation: Simulation) -> None: "inputs were mapped when it was calculated; run again " "before saving" ) + identity = simulation.output_dataset.metadata.get("output_identity") + if identity != self._output_cache_identity(simulation): + raise ValueError( + "US simulation inputs or runtime changed; run again before saving" + ) + serialized_spm = json.dumps( + { + "config": simulation.spm_config, + "provenance": receipt.model_dump(mode="json"), + "output_identity": identity, + }, + sort_keys=True, + ) if self.country_code == "uk": from policyengine.tax_benefit_models.uk.capital_gains_responses import ( RECORD_KEY, @@ -503,17 +512,25 @@ def save(self, simulation: Simulation) -> None: "Capital gains response settings changed since this output " "was calculated; run again before saving" ) - simulation.output_dataset.save() - if serialized_spm is not None: - # Store UTF-8 JSON in a dataset rather than an attribute: the - # payload size stays unbounded and the receipt is kept out of - # the object header, keeping the result file self-contained. - with h5py.File(simulation.output_dataset.filepath, "a") as stream: - stream.create_dataset( - "policyengine_spm", - data=serialized_spm, - dtype=h5py.string_dtype("utf-8"), + if serialized_spm is None: + simulation.output_dataset.save() + else: + destination = Path(simulation.output_dataset.filepath) + destination.parent.mkdir(parents=True, exist_ok=True) + # Publish the tables and their identity together. + with tempfile.TemporaryDirectory(dir=destination.parent) as directory: + temporary = Path(directory) / destination.name + output = simulation.output_dataset.model_copy( + update={"filepath": str(temporary)} ) + output.save() + with h5py.File(temporary, "a") as stream: + stream.create_dataset( + "policyengine_spm", + data=serialized_spm, + dtype=h5py.string_dtype("utf-8"), + ) + temporary.replace(destination) def load(self, simulation: Simulation) -> None: """Rehydrate the simulation's output dataset from disk. @@ -527,6 +544,7 @@ def load(self, simulation: Simulation) -> None: receipt = None if self.country_code == "us": + before = Path(filepath).stat() from policyengine.core.spm import SPMProvenance from policyengine.tax_benefit_models.us.legacy_inputs import ( RENAMES_RECORD_KEY, @@ -579,6 +597,13 @@ def load(self, simulation: Simulation) -> None: "run it again" ) + if recorded.get("output_identity") != self._output_cache_identity( + simulation + ): + raise StaleOutputError( + "Saved US simulation has a missing or different input or runtime identity" + ) + if self.country_code == "uk": from policyengine.tax_benefit_models.uk.datasets import ( _year_file_records_data_year, @@ -614,7 +639,7 @@ def load(self, simulation: Simulation) -> None: "run it again" ) - simulation.output_dataset = self._dataset_class( + output_dataset = self._dataset_class( id=simulation.id, name=simulation.dataset.name, description=simulation.dataset.description, @@ -622,13 +647,26 @@ def load(self, simulation: Simulation) -> None: year=simulation.dataset.year, is_output_dataset=True, ) + if self.country_code == "us": + after = Path(filepath).stat() + if ( + not os.path.samestat(before, after) + or before.st_mtime_ns != after.st_mtime_ns + ): + raise StaleOutputError("Saved US simulation changed during loading") + + simulation.output_dataset = output_dataset if self.country_code == "us": from policyengine.core.spm import SPMSelection simulation.spm_receipt = receipt simulation.spm = SPMSelection.model_validate(recorded["config"]) simulation.output_dataset.metadata.update( - {"spm_config": recorded["config"], RENAMES_RECORD_KEY: recorded_renames} + { + "spm_config": recorded["config"], + RENAMES_RECORD_KEY: recorded_renames, + "output_identity": recorded["output_identity"], + } ) if isinstance(recorded_legacy_spm, dict): simulation.output_dataset.metadata[LEGACY_SPM_RECORD_KEY] = ( diff --git a/src/policyengine/tax_benefit_models/us/datasets.py b/src/policyengine/tax_benefit_models/us/datasets.py index b935f0e6d..e03d52cbe 100644 --- a/src/policyengine/tax_benefit_models/us/datasets.py +++ b/src/policyengine/tax_benefit_models/us/datasets.py @@ -2,6 +2,8 @@ import importlib.util import json import logging +import os +import tempfile import warnings from importlib import metadata as importlib_metadata from pathlib import Path @@ -14,6 +16,7 @@ from policyengine.core import Dataset, YearData from policyengine.provenance.dataset_materialization import ( + DatasetSource, MaterializedDataset, _require_us_data_certification, materialize_dataset, @@ -403,6 +406,26 @@ def _load_policyengine_core_h5(path: Path, year: int) -> USYearData: ) +def _require_self_contained_hdf5(path: str) -> None: + """Refuse HDF5 links or storage that refer to bytes outside the file.""" + + def check_node(_name, node): + if isinstance(node, h5py.Group): + external = any( + isinstance(node.get(key, getlink=True), h5py.ExternalLink) + for key in node + ) + else: + external = node.is_virtual or bool(node.external) + if external: + raise ValueError("Native local HDF5 must be self-contained") + + if h5py.is_hdf5(path): + with h5py.File(path, "r") as file: + check_node("/", file) + file.visititems(check_node) + + def create_datasets( datasets: Optional[list[str]] = None, years: list[int] = [2024, 2025, 2026, 2027, 2028], @@ -412,8 +435,8 @@ def create_datasets( """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 + and stamped with its source and runtime identity, the register of + renamed stored inputs and the year-file format revision (see ``legacy_inputs.YEAR_FILE_STAMP_H5_DATASET``), which ``ensure_datasets`` and ``load_datasets`` check. @@ -425,24 +448,39 @@ def create_datasets( Returns: Dictionary mapping dataset keys (e.g., "populace_us_2024") to PolicyEngineUSDataset objects """ - _require_us_data_certification() from policyengine_us import Microsimulation + from policyengine.tax_benefit_models.us.model import _us_runtime_versions 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: + # A bundle URI supplied by a region registry selects the same source + # as its logical name. + selection = dataset + if dataset is not None and dataset.startswith("hf://"): + selection = _managed_source_name(dataset) or dataset source = materialize_dataset( "us", - dataset, + selection, allow_unmanaged=allow_unmanaged, data_dir=Path(data_folder), ) dataset_stem = source.name - sim = Microsimulation(dataset=source.path, spm=resolve_spm_selection()) - # The register the mapping below uses, stamped into each year file. + if source.bundle_dataset is None and "://" not in source.source_uri: + if not Path(source.path).is_file(): + raise ValueError( + f"Explicit local US dataset must be a file: {source.path!r}" + ) + _require_self_contained_hdf5(source.path) stamp = year_file_stamp() + if years: + stamp["identity"] = { + "source": _year_file_source(source, selection), + "runtime_packages": _us_runtime_versions(), + } + sim = Microsimulation(dataset=source.path, spm=resolve_spm_selection()) # 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) @@ -453,6 +491,10 @@ def create_datasets( sim, source.bundle_dataset, Path(data_folder) ) + if years and source.bundle_dataset is None: + if _year_file_source(source, selection) != stamp["identity"]["source"]: + raise ValueError("US year-file source changed during construction") + for year in years: # Get all input variables from the simulation # We'll calculate each input variable for the specified year @@ -618,10 +660,14 @@ 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(us_dataset.filepath) + destination.parent.mkdir(parents=True, exist_ok=True) + # Publish the tables and their stamp together. + with tempfile.TemporaryDirectory(dir=destination.parent) as directory: + temporary = Path(directory) / destination.name + us_dataset.model_copy(update={"filepath": str(temporary)}).save() + write_year_file_stamp(temporary, stamp) + temporary.replace(destination) dataset_key = f"{dataset_stem}_{year}" result[dataset_key] = us_dataset @@ -649,29 +695,87 @@ def _legacy_spm_declarations( return 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. - """ +def _managed_source_name(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 + return manifest.default_dataset + if dataset in manifest.datasets: + return dataset + if not dataset.startswith("hf://"): + return None + return next( + ( + name + for name in manifest.datasets + if resolve_dataset_reference("us", name) == dataset + ), + None, + ) + + +def _managed_source_sha256(dataset: Optional[str]) -> Optional[str]: + """Return the digest declared for a bundled name or URI.""" + name = _managed_source_name(dataset) + if name is None: + return None + return get_release_manifest("us").datasets[name].sha256 + + +def _year_file_source(source: DatasetSource, selection: Optional[str]) -> dict: + if source.bundle_dataset is not None: + name = _managed_source_name(selection) + return { + "kind": "bundle", + "uri": resolve_dataset_reference("us", name) if name else source.source_uri, + "sha256": source.bundle_dataset.sha256, + } + path = Path(source.path) + if "://" in source.source_uri: + return { + "kind": "remote", + "uri": source.source_uri, + "sha256": sha256_file(path), + } + return {"kind": "local", "sha256": sha256_file(path)} + + +def _year_file_request( + dataset: str, data_folder: str, *, allow_local: bool +) -> tuple[str, dict]: + from policyengine.tax_benefit_models.us.model import _us_runtime_versions + + managed_name = _managed_source_name(dataset) + if ( + managed_name is not None + or "://" in dataset + or not Path(dataset).expanduser().exists() + ): + _require_us_data_certification() + uri = resolve_dataset_reference("us", dataset) + sha256 = _managed_source_sha256(dataset) + if sha256 is not None: + source = {"kind": "bundle", "uri": uri, "sha256": sha256} + else: + path = Path(data_folder) / Path(uri.rsplit("@", 1)[0]).name + source = { + "kind": "remote", + "uri": uri, + "sha256": sha256_file(path) if path.is_file() else None, + } else: - name = next( - ( - candidate - for candidate in manifest.datasets - if resolve_dataset_reference("us", candidate) == dataset - ), - None, - ) - reference = manifest.datasets.get(name) if name is not None else None - return reference.sha256 if reference is not None else None + if not allow_local: + raise ValueError( + "Pass allow_unmanaged=True to use an explicit local dataset" + ) + path = Path(dataset).expanduser() + if not path.is_file(): + raise ValueError(f"Explicit local US dataset must be a file: {dataset!r}") + uri = str(path) + source = {"kind": "local", "sha256": sha256_file(path)} + return dataset_logical_name(uri), { + "source": source, + "runtime_packages": _us_runtime_versions(), + } def _expected_legacy_spm_profile(dataset: Optional[str]) -> Optional[LegacySPMProfile]: @@ -687,8 +791,9 @@ def load_datasets( ) -> dict[str, PolicyEngineUSDataset]: """Load PolicyEngineUSDataset instances from saved HDF5 files. - A year file is refused unless ``create_datasets`` stamped it with this - release's register of renamed stored inputs and year-file format revision + A year file is refused unless its source and runtime match and + ``create_datasets`` stamped it with the current register of renamed stored + inputs and year-file format revision (see ``legacy_inputs.year_file_stamp_problem``). A file cut before a 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 @@ -703,40 +808,45 @@ def load_datasets( Returns: Dictionary mapping dataset keys (e.g., "populace_us_2024") to PolicyEngineUSDataset objects """ - _require_us_data_certification() 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) + dataset_stem, identity = _year_file_request( + dataset, data_folder, allow_local=True + ) for year in years: - filepath = f"{data_folder}/{dataset_stem}_year_{year}.h5" - if Path(filepath).exists(): - problem = year_file_stamp_problem(filepath) - 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) + filepath = Path(data_folder) / f"{dataset_stem}_year_{year}.h5" + before = filepath.stat() + problem = year_file_stamp_problem(filepath, identity=identity) + 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()." ) - if legacy_problem is not None: - raise ValueError( - f"US year file {filepath} is out of date: " - f"{legacy_problem}. Regenerate it with ensure_datasets() " - "or create_datasets()." - ) us_dataset = PolicyEngineUSDataset( name=f"{dataset_stem}-year-{year}", description=f"US Dataset for year {year} based on {dataset_stem}", - filepath=filepath, + filepath=str(filepath), year=year, ) - us_dataset.load() + after = filepath.stat() + if ( + not os.path.samestat(before, after) + or before.st_mtime_ns != after.st_mtime_ns + ): + raise ValueError(f"US year file {filepath} changed during loading") dataset_key = f"{dataset_stem}_{year}" result[dataset_key] = us_dataset @@ -1197,8 +1307,6 @@ def load_long_term_datasets( artifacts with sidecar metadata validation, including optional checks that the installed ``policyengine-us`` runtime matches the H5 build metadata. """ - _require_us_data_certification() - result = {} root = Path(data_folder).expanduser() for year in years: @@ -1379,9 +1487,10 @@ def ensure_datasets( 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 + revision (see ``legacy_inputs.year_file_stamp_problem``), and its source and + runtime identity still match. Bundled sources use the manifest hash. + Other sources use the hash of the available input file. 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. @@ -1393,7 +1502,6 @@ def ensure_datasets( Returns: Dictionary mapping dataset keys to PolicyEngineUSDataset objects """ - _require_us_data_certification() datasets = datasets or [get_release_manifest("us").default_dataset] # Check that every year file exists and is current. A year file cut @@ -1401,14 +1509,15 @@ def ensure_datasets( # 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) + dataset_stem, identity = _year_file_request( + dataset, data_folder, allow_local=allow_unmanaged + ) for year in years: filepath = Path(f"{data_folder}/{dataset_stem}_year_{year}.h5") if not filepath.exists(): all_current = False continue - problem = year_file_stamp_problem(filepath) + problem = year_file_stamp_problem(filepath, identity=identity) if problem is not None: all_current = False logger.warning( diff --git a/src/policyengine/tax_benefit_models/us/legacy_inputs.py b/src/policyengine/tax_benefit_models/us/legacy_inputs.py index f108ccd54..bc5c24477 100644 --- a/src/policyengine/tax_benefit_models/us/legacy_inputs.py +++ b/src/policyengine/tax_benefit_models/us/legacy_inputs.py @@ -178,14 +178,17 @@ 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, *, identity: Mapping[str, Any] | 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: - 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. + - it stores the renames record, listing only renames in that register; + - its source and runtime match the expected identity, if supplied. 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 @@ -247,7 +250,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) - {"identity"} == {"register", "revision"} and type(revision) is int and _is_str_map(stamp["register"]) ): @@ -268,7 +271,9 @@ 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 identity is not None and stamp.get("identity") != identity: + return "it has a missing or different source or runtime identity" return None missing = { legacy: live for legacy, live in register.items() if stamped.get(legacy) != live diff --git a/src/policyengine/tax_benefit_models/us/model.py b/src/policyengine/tax_benefit_models/us/model.py index 6e8ddf29f..ace84504c 100644 --- a/src/policyengine/tax_benefit_models/us/model.py +++ b/src/policyengine/tax_benefit_models/us/model.py @@ -1,4 +1,6 @@ import datetime +import hashlib +import json from importlib import metadata from pathlib import Path from typing import TYPE_CHECKING, ClassVar, Optional @@ -20,7 +22,12 @@ output_dataset_filepath as _output_dataset_filepath, ) -from .datasets import PolicyEngineUSDataset, USYearData, _validate_entity_ids +from .datasets import ( + PolicyEngineUSDataset, + USYearData, + _require_self_contained_hdf5, + _validate_entity_ids, +) from .legacy_inputs import ( RENAMES_RECORD_KEY, apply_legacy_input_renames, @@ -181,14 +188,50 @@ def _dataset_class(self): @property def release_bundle(self): - # A bundle receipt must never borrow the configured certificate when - # this runtime has not been checked against its bundled data. - self.require_data_certification() - return super().release_bundle + certification = self.require_data_certification() + bundle = super().release_bundle + bundle["model_version"] = certification.certified_for_model_version + return bundle def _validate_cached_output(self) -> None: self.require_data_certification() + def _output_cache_identity(self, simulation: "Simulation") -> dict: + """Bind an output to the runtime and the tables consumed by the model.""" + dataset = simulation.dataset + if dataset.data is None: + dataset.load() + digest = hashlib.sha256() + digest.update( + json.dumps( + [dataset.year, dataset.metadata.get(LEGACY_SPM_RECORD_KEY)], + sort_keys=True, + ).encode() + ) + for entity, table in dataset.data.entity_data.items(): + frame = pd.DataFrame(table) + schema = [ + (str(name), str(dtype)) + for name, dtype in zip(frame.columns, frame.dtypes) + ] + digest.update(json.dumps([entity, len(frame), schema]).encode()) + hashes = pd.util.hash_pandas_object(frame, index=False) + digest.update(hashes.to_numpy(dtype=" bool: + if cached.output_dataset is None: + return False + return cached.output_dataset.metadata.get( + "output_identity" + ) == self._output_cache_identity(simulation) + def load(self, simulation): self._validate_cached_output() return super().load(simulation) @@ -212,6 +255,7 @@ def run(self, simulation: "Simulation") -> "Simulation": # autosave removal in datasets.py). if dataset.data is None: dataset.load() + output_identity = self._output_cache_identity(simulation) # Validate every entity before constructing either the reform or its # baseline, so no set_input can suppress a canonical SPM formula. @@ -387,6 +431,7 @@ class InputMicrosimulation(Microsimulation): ) output_metadata = { + "output_identity": output_identity, "spm_config": dict(microsim.spm_config), RENAMES_RECORD_KEY: dict(sorted(legacy_input_renames.items())), } @@ -586,18 +631,27 @@ def _build_simulation_from_dataset(self, microsim, dataset, system): return apply_legacy_input_renames(microsim, {dataset.year: stored_tables}) -def _unmanaged_local_runtime_provenance(source): - """Bind local data and actual runtime; assert no bundle certification.""" +def _us_runtime_versions() -> dict[str, str]: + """Return package versions after checking them against the loaded runtime.""" + import spm_calculator + from policyengine.provenance.loaded import loaded_versions - from policyengine.utils.hashing import sha256_file names = ("policyengine", "policyengine-us", "policyengine-core", "spm-calculator") versions = {name: metadata.version(name) for name in names} loaded = loaded_versions() - if any( + if spm_calculator.__version__ != versions["spm-calculator"] or any( name in loaded and loaded[name] != version for name, version in versions.items() ): raise ValueError("Installed runtime changed after import") + return versions + + +def _unmanaged_local_runtime_provenance(source): + """Record the local file hash and the versions of the loaded packages.""" + from policyengine.utils.hashing import sha256_file + + versions = _us_runtime_versions() provenance = build_runtime_dataset_provenance(source.source_uri, source.path, None) provenance.update( data_selection="explicit_local_unmanaged", @@ -620,6 +674,7 @@ def _native_local_dataset(source, native_input_period): if Path(source.path).suffix != ".h5": raise ValueError("native_input_period requires a .h5 TIME_PERIOD_ARRAYS file") + _require_self_contained_hdf5(source.path) try: descriptor = CoreDataset.from_file(source.path) except IndexError as error: @@ -705,6 +760,10 @@ def managed_microsimulation( raise ValueError( "native_input_period requires an explicit local unmanaged file" ) + if Path(dataset).suffix != ".h5": + raise ValueError( + "native_input_period requires a .h5 TIME_PERIOD_ARRAYS file" + ) if scoping_strategy is not None or "dataset_end_year" in kwargs: raise ValueError( "native_input_period cannot project or scope its input data" @@ -713,6 +772,10 @@ def managed_microsimulation( if option in kwargs and kwargs[option] != native_input_period: raise ValueError(f"{option} must match native_input_period") kwargs[option] = native_input_period + if Path(dataset).suffix != ".h5": + raise ValueError( + "native_input_period requires a .h5 TIME_PERIOD_ARRAYS file" + ) selection = resolve_spm_selection(spm) source = materialize_dataset( @@ -754,6 +817,8 @@ def managed_microsimulation( ) constructor_dataset = _native_local_dataset(source, native_input_period) local_provenance["native_input_period"] = native_input_period + if explicit_local and native_input_period is None: + _require_self_contained_hdf5(source.path) microsim = Microsimulation(dataset=constructor_dataset, spm=selection, **kwargs) scoping_record = None if scoping_strategy is not None: diff --git a/tests/test_us_legacy_inputs_integration.py b/tests/test_us_legacy_inputs_integration.py index 23a445123..5da4e155d 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 @@ -557,7 +558,7 @@ def _create_year_file(directory): def test_create_datasets_extracts_the_draw_under_the_live_name(tmp_path): - _, dataset = _create_year_file(tmp_path) + source, dataset = _create_year_file(tmp_path) person = pd.DataFrame(dataset.data.person) assert person[LIVE].tolist() == DRAW @@ -566,7 +567,7 @@ def test_create_datasets_extracts_the_draw_under_the_live_name(tmp_path): # The year file keeps the record, so reloading it keeps the chain. assert read_renames_record(dataset.filepath) == RENAME # It is stamped with the register it was cut under, so it is current. - assert read_year_file_stamp(dataset.filepath) == year_file_stamp() + assert read_year_file_stamp(dataset.filepath) == _stamp_for_source(source) assert year_file_stamp_problem(dataset.filepath) is None reloaded = PolicyEngineUSDataset( name=dataset.name, @@ -681,7 +682,7 @@ def test_a_year_file_cut_before_a_register_entry_is_regenerated(tmp_path): assert LIVE not in person.columns assert LEGACY not in person.columns assert read_renames_record(path) == {} - assert read_year_file_stamp(path) == {"register": {}, "revision": 1} + assert read_year_file_stamp(path) == _stamp_for_source(source, register={}) # The draw is lost from it: a run gives the infant WIC. assert _person_outputs(_run(dataset))["wic"].iloc[INFANT] > 0 @@ -699,7 +700,7 @@ def test_a_year_file_cut_before_a_register_entry_is_regenerated(tmp_path): regenerated = _ensure(source, tmp_path / "data") assert regenerated.filepath == path - assert read_year_file_stamp(path) == year_file_stamp() + assert read_year_file_stamp(path) == _stamp_for_source(source) assert pd.DataFrame(regenerated.data.person)[LIVE].tolist() == DRAW loaded = _assert_reused(source, tmp_path / "data") assert _person_outputs(_run(loaded))["wic"].iloc[INFANT] == 0 @@ -735,10 +736,9 @@ def spy(*args, **kwargs): regenerated = _ensure(source, data_folder) assert created == [[YEAR]] - assert read_year_file_stamp(dataset.filepath) == { - "register": {**RENAME, **future}, - "revision": 1, - } + assert read_year_file_stamp(dataset.filepath) == _stamp_for_source( + source, register={**RENAME, **future} + ) # Only the entry the engine needs was applied, and the data is as # before. assert read_renames_record(dataset.filepath) == RENAME @@ -765,11 +765,34 @@ def test_ensure_datasets_regenerates_a_year_file_with_only_the_renames_record( regenerated = _ensure(source, data_folder) - assert read_year_file_stamp(regenerated.filepath) == year_file_stamp() + assert read_year_file_stamp(regenerated.filepath) == _stamp_for_source(source) assert pd.DataFrame(regenerated.data.person)[LIVE].tolist() == DRAW _assert_reused(source, data_folder) +def _stamp_for_source(source, **changes): + from importlib.metadata import version + + from policyengine.utils.hashing import sha256_file + + return { + **year_file_stamp(), + **changes, + "identity": { + "source": {"kind": "local", "sha256": sha256_file(Path(source))}, + "runtime_packages": { + name: version(name) + for name in ( + "policyengine", + "policyengine-us", + "policyengine-core", + "spm-calculator", + ) + }, + }, + } + + def test_create_datasets_stamps_each_year_file_after_saving_it(tmp_path): source = _write_entity_tables(tmp_path / "microcosm_layout.h5") events = [] @@ -778,11 +801,11 @@ def test_create_datasets_stamps_each_year_file_after_saving_it(tmp_path): def recording_save(self): save(self) - events.append(("save", self.filepath)) + events.append(("save", Path(self.filepath).name)) def recording_stamp(path, value): stamp(path, value) - events.append(("stamp", path)) + events.append(("stamp", Path(path).name)) with ( patch.object(PolicyEngineUSDataset, "save", recording_save), @@ -797,16 +820,16 @@ def recording_stamp(path, value): paths = [dataset.filepath for dataset in created.values()] assert events == [ - ("save", paths[0]), - ("stamp", paths[0]), - ("save", paths[1]), - ("stamp", paths[1]), + ("save", Path(paths[0]).name), + ("stamp", Path(paths[0]).name), + ("save", Path(paths[1]).name), + ("stamp", Path(paths[1]).name), ] for path in paths: assert year_file_stamp_problem(path) is None -def test_a_year_file_whose_stamp_was_never_written_is_out_of_date(tmp_path): +def test_a_year_file_whose_stamp_was_never_written_is_not_published(tmp_path): source = _write_entity_tables(tmp_path / "microcosm_layout.h5") def stop(path, value): @@ -821,13 +844,10 @@ def stop(path, value): 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) - assert year_file_stamp_problem(path) is None + assert list((tmp_path / "data").iterdir()) == [] + regenerated = _ensure(source, tmp_path / "data") + assert read_renames_record(regenerated.filepath) == RENAME + assert year_file_stamp_problem(regenerated.filepath) is None # --- Saved outputs and run records keep the record ---------------------- diff --git a/tests/test_us_unmanaged_runtime.py b/tests/test_us_unmanaged_runtime.py index f8331de6c..70b3c7085 100644 --- a/tests/test_us_unmanaged_runtime.py +++ b/tests/test_us_unmanaged_runtime.py @@ -142,14 +142,15 @@ def test_local_source_requires_opt_in_and_avoids_unused_bundle(monkeypatch, tmp_ [ "create_datasets", "load_datasets", - "load_long_term_datasets", "load_managed_long_term_datasets", "ensure_datasets", ], ) def test_year_helpers_certify_before_cached_data(monkeypatch, name): monkeypatch.setattr( - us_datasets, "_require_us_data_certification", refuse_certification + us_model.PolicyEngineUSLatest, + "require_data_certification", + refuse_certification, ) with pytest.raises(ValueError, match="incompatible bundled data"): getattr(us_datasets, name)(years=[2017]) @@ -286,7 +287,12 @@ def test_local_factory_records_actual_runtime_without_certificate( def test_local_factory_refuses_directory_before_construction(monkeypatch, tmp_path): - local_factory_fixture(monkeypatch, tmp_path) + import policyengine_us + + def unexpected_constructor(**kwargs): + pytest.fail("An explicit directory reached the country constructor") + + monkeypatch.setattr(policyengine_us, "Microsimulation", unexpected_constructor) with pytest.raises(ValueError, match="Explicit local US dataset must be a file"): us_model.managed_microsimulation(dataset=str(tmp_path), allow_unmanaged=True) @@ -580,3 +586,346 @@ def io_failure(path): with pytest.raises(OSError) as caught: us_model._native_local_dataset(SimpleNamespace(path="inert-fixture.h5"), "2017") assert caught.value is original + + +@pytest.fixture +def uncertified_us_runtime(monkeypatch): + from policyengine.core import tax_benefit_model_version as core_model + from policyengine.provenance import manifest + + version = metadata.version + + def offline(country): + raise DataReleaseManifestUnavailableError("test offline manifest") + + monkeypatch.setattr(manifest, "get_data_release_manifest", offline) + monkeypatch.setattr(core_model, "get_data_release_manifest", offline) + monkeypatch.setattr( + metadata, + "version", + lambda name: "2.3.0" if name == "policyengine-us" else version(name), + ) + monkeypatch.setattr(loaded, "loaded_versions", lambda: {"policyengine-us": "2.3.0"}) + monkeypatch.setattr( + us_model.PolicyEngineUSLatest, + "_get_runtime_data_build_metadata", + lambda self: {}, + ) + + +def test_static_managed_selection_leaves_certification_to_materialization( + uncertified_us_runtime, tmp_path +): + from policyengine.provenance.manifest import resolve_managed_dataset_reference + + assert "Runtime compatibility is checked when managed data is materialised" in ( + resolve_managed_dataset_reference.__doc__ + ) + assert ( + resolve_managed_dataset_reference("us") + == get_release_manifest("us").default_dataset_uri + ) + with pytest.raises(ValueError, match="Cannot certify the bundled US data"): + materialization.materialize_dataset("us", data_dir=tmp_path) + + +def test_supplied_run_record_tro_requires_current_us_certification( + monkeypatch, tmp_path +): + import json + from pathlib import Path + + from tests.test_us_legacy_inputs_integration import _saved_run + + simulation = _saved_run(tmp_path, "uncertified-run-record") + simulation.dataset.save() + bundled_tro = json.loads( + ( + Path(us_model.__file__).resolve().parents[2] + / "data/bundle/us.trace.tro.jsonld" + ).read_text() + ) + monkeypatch.setattr( + us_model.PolicyEngineUSLatest, + "require_data_certification", + refuse_certification, + ) + output = tmp_path / "must-not-be-created" + with pytest.raises(ValueError, match="incompatible bundled data"): + simulation.write_run_record(output, bundle_tro=bundled_tro) + assert not output.exists() + + +def test_runtime_receipt_and_trace_name_the_certified_us_version( + monkeypatch, uncertified_us_runtime +): + manifest = get_release_manifest("us") + certificate = manifest.certification.model_copy( + update={"certified_for_model_version": "2.3.0"} + ) + monkeypatch.setattr( + common, "certify_data_release_compatibility", lambda *a, **kw: certificate + ) + model = us_model.PolicyEngineUSLatest.model_construct( + release_manifest=manifest, + model_package=manifest.model_package, + data_certification=None, + ) + + performance = model.trace_tro["@graph"][0]["trov:hasPerformance"] + assert performance["pe:certifiedForModelVersion"] == "2.3.0" + assert performance["rdfs:comment"].endswith("for policyengine-us 2.3.0.") + assert model.release_bundle["model_version"] == "2.3.0" + assert manifest.model_package.version != certificate.certified_for_model_version + + +def test_local_factory_refuses_preloaded_spm_when_metadata_differs(tmp_path): + path = tmp_path / "local.h5" + path.touch() + script = textwrap.dedent( + """ + import sys + from importlib import metadata + + import spm_calculator + + def offline(event, args): + if event in {"socket.connect", "socket.getaddrinfo", "socket.gethostbyname"}: + raise OSError("network blocked") + + sys.addaudithook(offline) + version = metadata.version + different_version = spm_calculator.__version__ + ".post1" + metadata.version = lambda name: ( + different_version if name == "spm-calculator" else version(name) + ) + + import policyengine as pe + from unittest.mock import patch + + with patch("policyengine_us.Microsimulation") as constructor: + try: + pe.us.managed_microsimulation(dataset=sys.argv[1], allow_unmanaged=True) + except ValueError as error: + assert "Installed runtime changed after import" in str(error) + else: + raise AssertionError("Local provenance accepted preloaded SPM drift") + constructor.assert_not_called() + """ + ) + result = subprocess.run( + [sys.executable, "-c", script, str(path)], + capture_output=True, + text=True, + timeout=60, + check=False, + ) + assert result.returncode == 0, result.stderr + + +@pytest.mark.parametrize("native_input_period", [None, "2017"]) +def test_local_factory_refuses_external_hdf5_inputs( + monkeypatch, tmp_path, native_input_period +): + external = tmp_path / "external.h5" + with h5py.File(external, "w") as file: + file.create_dataset("vector", data=[20]) + path = tmp_path / "native.h5" + with h5py.File(path, "w") as file: + file.create_dataset("person_id/2017", data=[1]) + for entity in us_model.US_GROUP_ENTITIES: + file.create_dataset(f"{entity}_id/2017", data=[1]) + file.create_dataset(f"person_{entity}_id/2017", data=[1]) + file["age/2017"] = h5py.ExternalLink(str(external), "/vector") + + monkeypatch.setattr( + us_model.PolicyEngineUSLatest, + "require_data_certification", + refuse_certification, + ) + for value in (20, 21): + with h5py.File(external, "r+") as file: + file["vector"][0] = value + with pytest.raises( + ValueError, match="Native local HDF5 must be self-contained" + ): + us_model.managed_microsimulation( + dataset=str(path), + allow_unmanaged=True, + native_input_period=native_input_period, + ) + + +def test_native_factory_refuses_suffix_before_hashing(monkeypatch, tmp_path): + from policyengine.utils import hashing + + path = tmp_path / "local.bin" + path.write_bytes(b"test source plumbing only") + + def hash_read(path): + raise PermissionError("Attempted to hash a non-HDF5 file") + + monkeypatch.setattr(hashing, "sha256_file", hash_read) + with pytest.raises(ValueError, match=r"requires a \.h5 TIME_PERIOD_ARRAYS file"): + us_model.managed_microsimulation( + dataset=str(path), allow_unmanaged=True, native_input_period="2017" + ) + + +@pytest.mark.parametrize( + "operation", ["create_datasets", "ensure_datasets", "long_term"] +) +def test_explicit_local_year_operations_bypass_unused_bundle( + uncertified_us_runtime, tmp_path, operation +): + from tests.test_us_legacy_inputs_integration import ( + YEAR, + _in_memory_dataset, + _write_entity_tables, + ) + + if operation == "long_term": + dataset = _in_memory_dataset(tmp_path) + dataset.save() + (loaded,) = us_datasets.load_long_term_datasets( + years=[YEAR], + data_folder=str(tmp_path), + dataset_template="input.h5", + require_metadata=False, + ).values() + else: + path = _write_entity_tables(tmp_path / "native.h5") + (loaded,) = getattr(us_datasets, operation)( + datasets=[path], + years=[YEAR], + data_folder=str(tmp_path / "years"), + allow_unmanaged=True, + ).values() + if operation == "ensure_datasets": + (loaded,) = us_datasets.ensure_datasets( + datasets=[path], + years=[YEAR], + data_folder=str(tmp_path / "years"), + allow_unmanaged=True, + ).values() + assert loaded.data.person["age"].tolist() == [30, 0, 2] + + +def test_managed_year_replaces_a_same_stem_explicit_local_year(monkeypatch, tmp_path): + from pathlib import Path + + import pandas as pd + + from policyengine.provenance.dataset_materialization import ( + DatasetSource, + MaterializedDataset, + ) + from policyengine.utils.hashing import sha256_file + from tests.test_us_legacy_inputs_integration import YEAR, _write_entity_tables + + manifest = get_release_manifest("us") + name = manifest.default_dataset + local = _write_entity_tables(tmp_path / f"{name}.h5") + managed = Path(_write_entity_tables(tmp_path / "managed.h5")) + with pd.HDFStore(managed, "a") as store: + person = store["person"] + person["age"] += 1 + store.put("person", person, format="table", data_columns=True) + + year_dir = str(tmp_path / "years") + (local_year,) = us_datasets.create_datasets( + datasets=[local], years=[YEAR], data_folder=year_dir, allow_unmanaged=True + ).values() + assert local_year.data.person["age"].tolist() == [30, 0, 2] + + uri = manifest.default_dataset_uri + digest = sha256_file(managed) + source = MaterializedDataset( + data_package_name=manifest.data_package.name, + repo_type=manifest.data_package.repo_type, + revision="synthetic", + source_uri=uri, + sha256=digest, + path=managed, + ) + calls = [] + + def materialize(country, selection, **kwargs): + calls.append(selection) + return DatasetSource(source_uri=uri, path=str(managed), bundle_dataset=source) + + monkeypatch.setattr(us_datasets, "materialize_dataset", materialize) + monkeypatch.setattr(us_datasets, "_managed_source_sha256", lambda selection: digest) + for _ in range(2): + (year,) = us_datasets.ensure_datasets( + years=[YEAR], data_folder=year_dir + ).values() + assert year.filepath == local_year.filepath + assert year.data.person["age"].tolist() == [31, 1, 3] + assert len(calls) == 1 + + +def test_saved_us_output_refuses_a_different_runtime(monkeypatch, tmp_path): + from policyengine.core import Simulation + from policyengine.core.tax_benefit_model_version import StaleOutputError + from tests.test_us_legacy_inputs_integration import _saved_run + + original = _saved_run(tmp_path, "different-runtime") + certificate = get_release_manifest("us").certification.model_copy( + update={"certified_for_model_version": "2.3.0"} + ) + monkeypatch.setattr( + us_model.PolicyEngineUSLatest, + "require_data_certification", + lambda self: certificate, + ) + version = metadata.version + monkeypatch.setattr( + metadata, + "version", + lambda name: "2.3.0" if name == "policyengine-us" else version(name), + ) + monkeypatch.setattr(loaded, "loaded_versions", lambda: {"policyengine-us": "2.3.0"}) + retry = Simulation( + id=original.id, + dataset=original.dataset, + tax_benefit_model_version=us_model.us_latest, + ) + assert original.storage_id == retry.storage_id + with pytest.raises(StaleOutputError, match="input or runtime identity"): + retry.load() + assert retry.output_dataset is None + + +def test_memory_cache_misses_same_id_and_spm_with_different_input(tmp_path): + from policyengine.core import Simulation + from policyengine.core.simulation import _cache + from tests.test_us_legacy_inputs_integration import _frames, _in_memory_dataset + + def new_request(dataset): + return Simulation( + id="same-id-and-spm", + dataset=dataset, + tax_benefit_model_version=us_model.us_latest, + extra_variables={"person": ["age"]}, + ) + + _cache.clear() + try: + initial = new_request(_in_memory_dataset(tmp_path)) + initial.ensure() + equivalent = new_request(_in_memory_dataset(tmp_path)) + equivalent.ensure() + assert equivalent.output_dataset is initial.output_dataset + + frames = _frames() + frames["person"]["age"] += 1 + data = _in_memory_dataset(tmp_path, frames) + data.id = initial.dataset.id + changed = new_request(data) + assert changed.storage_id == initial.storage_id + changed.ensure() + assert changed.output_dataset is not initial.output_dataset + assert changed.output_dataset.data.person["age"].tolist() == [31, 1, 3] + finally: + _cache.clear() diff --git a/tests/test_us_year_file_stamp.py b/tests/test_us_year_file_stamp.py index 38d4acba3..b24b8a87f 100644 --- a/tests/test_us_year_file_stamp.py +++ b/tests/test_us_year_file_stamp.py @@ -72,10 +72,9 @@ LEGACY = "would_claim_wic" LIVE = "takes_up_wic_if_eligible" REVISION = YEAR_FILE_STAMP_REVISION -#: ``hf://`` references are used as they are, and name year files after the -#: file's stem, so no manifest or download is involved. -SOURCE = "hf://fixture/tiny.h5" -STEM = "tiny" +# A bundled source lets the cache compare a pinned hash offline. +SOURCE = "populace_us_2024" +STEM = "populace_us_2024" GROUPS = ("household", "tax_unit", "spm_unit", "family", "marital_unit") #: A small alphabet, so generated registers often share names and disagree @@ -864,6 +863,35 @@ def test_a_well_formed_renames_record_still_reads_back(tmp_path): } +def _stamp_with_source_identity(stamp): + from importlib.metadata import version + + from policyengine.provenance.manifest import ( + get_release_manifest, + resolve_dataset_reference, + ) + + return { + **stamp, + "identity": { + "source": { + "kind": "bundle", + "uri": resolve_dataset_reference("us", SOURCE), + "sha256": get_release_manifest("us").datasets[SOURCE].sha256, + }, + "runtime_packages": { + name: version(name) + for name in ( + "policyengine", + "policyengine-us", + "policyengine-core", + "spm-calculator", + ) + }, + }, + } + + def _make_state(path: Path, state: str) -> None: written, _ = STATES[state] if state == "missing": @@ -872,6 +900,8 @@ def _make_state(path: Path, state: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text("not an H5 file") return + if STATES[state][1]: + written = {**written, "stamp": _stamp_with_source_identity(written["stamp"])} _write_year_file(path, **written) @@ -880,7 +910,7 @@ def _create_current_files(datasets, years, data_folder, allow_unmanaged=False): for year in years: _write_year_file( Path(data_folder) / f"{STEM}_year_{year}.h5", - stamp=year_file_stamp(), + stamp=_stamp_with_source_identity(year_file_stamp()), record={}, ) return {"created": True} From 6c15ab82185769b4a17691df9298528393035913 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 23:02:19 -0500 Subject: [PATCH 14/20] Preserve native option errors and allow in-file virtual storage Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- src/policyengine/tax_benefit_models/us/datasets.py | 7 ++++++- src/policyengine/tax_benefit_models/us/model.py | 4 ---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/policyengine/tax_benefit_models/us/datasets.py b/src/policyengine/tax_benefit_models/us/datasets.py index e03d52cbe..dd128cdac 100644 --- a/src/policyengine/tax_benefit_models/us/datasets.py +++ b/src/policyengine/tax_benefit_models/us/datasets.py @@ -415,8 +415,13 @@ def check_node(_name, node): isinstance(node.get(key, getlink=True), h5py.ExternalLink) for key in node ) + elif isinstance(node, h5py.Dataset): + external = bool(node.external) or ( + node.is_virtual + and any(source.file_name != "." for source in node.virtual_sources()) + ) else: - external = node.is_virtual or bool(node.external) + return if external: raise ValueError("Native local HDF5 must be self-contained") diff --git a/src/policyengine/tax_benefit_models/us/model.py b/src/policyengine/tax_benefit_models/us/model.py index ace84504c..816703914 100644 --- a/src/policyengine/tax_benefit_models/us/model.py +++ b/src/policyengine/tax_benefit_models/us/model.py @@ -760,10 +760,6 @@ def managed_microsimulation( raise ValueError( "native_input_period requires an explicit local unmanaged file" ) - if Path(dataset).suffix != ".h5": - raise ValueError( - "native_input_period requires a .h5 TIME_PERIOD_ARRAYS file" - ) if scoping_strategy is not None or "dataset_end_year" in kwargs: raise ValueError( "native_input_period cannot project or scope its input data" From 968af6150bbb54d971b6428bceb605cd031d049f Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 23:03:53 -0500 Subject: [PATCH 15/20] Exercise preloaded SPM drift with country imports enabled Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- tests/test_us_unmanaged_runtime.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/test_us_unmanaged_runtime.py b/tests/test_us_unmanaged_runtime.py index 70b3c7085..f8cac4cbe 100644 --- a/tests/test_us_unmanaged_runtime.py +++ b/tests/test_us_unmanaged_runtime.py @@ -713,12 +713,15 @@ def offline(event, args): constructor.assert_not_called() """ ) + env = os.environ.copy() + env.pop("POLICYENGINE_SKIP_COUNTRY_IMPORTS", None) result = subprocess.run( [sys.executable, "-c", script, str(path)], capture_output=True, text=True, timeout=60, check=False, + env=env, ) assert result.returncode == 0, result.stderr From cbf8d59c456d895ac3ed43e1d719d2a7e6c1bb66 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 1 Dec 2026 07:14:04 -0500 Subject: [PATCH 16/20] Bind US output reuse to resolved requests and verify local data provenance Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- changelog.d/760.fixed.md | 2 +- .../runbooks/canonical-spm-development.md | 62 ++-- docs/microsim.md | 26 +- src/policyengine/core/run_record.py | 10 +- .../provenance/dataset_materialization.py | 25 +- src/policyengine/provenance/trace.py | 97 +++++- .../common/model_version.py | 13 +- .../tax_benefit_models/us/datasets.py | 12 +- .../tax_benefit_models/us/model.py | 175 ++++++++-- tests/test_us_legacy_inputs_integration.py | 13 + tests/test_us_unmanaged_runtime.py | 328 +++++++++++++++++- 11 files changed, 631 insertions(+), 132 deletions(-) diff --git a/changelog.d/760.fixed.md b/changelog.d/760.fixed.md index b382e2104..754920204 100644 --- a/changelog.d/760.fixed.md +++ b/changelog.d/760.fixed.md @@ -1,3 +1,3 @@ Allow explicit local US datasets with `allow_unmanaged=True` to record the local file’s SHA-256 and checked package-version metadata with unverified provenance. Keep the explicit local year-file helpers and standalone long-term loader independent of the unused bundled data. -Check current US runtime certification for managed materialisation, simulation runs and output reuse, model bundle receipts, model TRACE exports and run records with an attached US model. Bind year files to their source and runtime and bind cached simulation outputs to their inputs and runtime. Require self-contained HDF5 for explicit local inputs. +Check current US runtime certification for managed materialisation, simulation runs and output reuse, model bundle receipts, model TRACE exports and run records with an attached US model. Validate a supplied bundle TRO against the attached model before writing a run record. Bind year files to their source and runtime. Bind cached US outputs to the calculation inputs, resolved legacy SPM profile, reforms, effective scope, requested columns and runtime. Require self-contained HDF5 for explicit local inputs, including standalone long-term loads, and retain in-file virtual storage. Report a missing absolute US dataset path before checking bundled-data certification. diff --git a/docs/engineering/runbooks/canonical-spm-development.md b/docs/engineering/runbooks/canonical-spm-development.md index e2bd45114..1ba53c8d7 100644 --- a/docs/engineering/runbooks/canonical-spm-development.md +++ b/docs/engineering/runbooks/canonical-spm-development.md @@ -1,11 +1,10 @@ # Canonical SPM wrapper development and remaining release gates -The canonical SPM wrapper integration is **pending promotion**. The packaged -5.3.0 manifest still pins US 1.764.6 and its existing certified Build P release. -Only `measurements.spm` has been staged: forecast content SHA-256 -`3d86d5c4c0423480e6b69b75d222ffa4a7a2639e4094df5ba2504af01be17173`, scenario -`ce_trend`, county geography, vintage `2020`. This measurement pin does not -certify the new country package or the enriched data. +This runbook records the historical SPM development procedure. The checked-in +6.20.2 bundle pins US 2.2.2, Core 3.34.10, UK 2.177.7 and spm-calculator 1.1.0. +The US certificate covers `populace-us-2024-spm-20260915`. The `ce_trend` county +forecast for vintage 2020 has SHA-256 +`335e6755dc8e0bd883e09b76c2bd53a5315683773e44d50085c7d6b8832b6291`. The configuration accepts exactly `forecast_content_sha256`, `scenario`, `geography_kind`, `geography_id`, `county_vintage` and `as_of`. The hash and @@ -15,7 +14,7 @@ date. Unknown fields, paths, provider overrides and fallback settings fail validation. Country runtime validation resolves scenario, year and location against the pinned artifact when the calculation needs SPM. -## Reproduce the local development fixture +## Historical local development fixture Use a fresh isolated environment containing the exact qualified local country, calculator and Core wheels. Preserve all earlier qualification environments. Set @@ -33,13 +32,15 @@ UV_CACHE_DIR=/tmp/wrapper-spm-uv-cache \ --output /tmp/wrapper-spm-development-manifest.json ``` -The most recently qualified development country wheel is version 1.824.7, SHA-256 +### Historical wheel inventory + +The development worker recorded country wheel version 1.824.7 with SHA-256 `7644819916a4f8ca2aa37a4a9d992fa834bfa66ab2d441326a9686baa5c1a688`. -The observed local calculator wheel is version 1.0.0, SHA-256 +The worker recorded calculator wheel version 1.0.0 with SHA-256 `c49c41da5fd482e563eaea956e205a3ba6841cadd4dd32bef4c0c3dbce17ffba`. -These are local development artifacts, not published package identities. The calculator wheel uses the canonical source commit -`fd7de4b3b670a10acd72567904ccea800252c9a5`. Core remains 3.30.1 and UK 2.90.2. +`fd7de4b3b670a10acd72567904ccea800252c9a5`. The worker used Core 3.30.1 and UK +2.90.2. The fixture records `development.data_certification: not_certified` and `development.promotion_status: pending`. It removes the inherited US @@ -48,8 +49,8 @@ reference-only. It records the real local wheel names, versions, file URIs and SHA-256 hashes. UK release metadata is retained unchanged. It refuses to overwrite the packaged manifest. -US initialization defers data certification until code requests certification -or uses bundled data. UK initialization continues to require a compatibility +US initialisation defers data certification until code requests certification +or uses bundled data. UK initialisation continues to require a compatibility receipt. An explicitly enabled pytest plugin supplies the `unverified_development_fixture` receipt when those US entrypoints request certification and disables remote data-manifest fetches for that test process. @@ -75,11 +76,10 @@ shadowing from `PYTHONPATH` or previously loaded modules, and repeats these checks after bootstrap. Core wheel bytes are checked by the separate four-wheel native probe. Only focused household and synthetic small-dataset tests belong in this command. The final acceptance -worker owns the heavy population process. Local enriched H5 experiments require -an explicit path with `allow_unmanaged=True` and remain development runs while -certification is pending. +worker owns the heavy population process. Local enriched H5 experiments use an +explicit path with `allow_unmanaged=True` and record unverified local provenance. -An explicitly labeled development script can use the same bootstrap before +An explicitly labelled development script can use the same bootstrap before importing country models. This helper lives under `tests/fixtures` and is not a production environment override: @@ -113,11 +113,11 @@ UV_CACHE_DIR=/tmp/wrapper-spm-uv-cache POLICYENGINE_SKIP_COUNTRY_IMPORTS=1 \ tests/test_bundle.py -q ``` -## Stage and later verify published measurement pins +## Stage and verify published measurement pins The operator command validates all settings before writing. Omitting `--calculator-version` stages only configuration and preserves package pins -and data certification: +and data certification. This example shows the historical staging command: ```bash uv run --python "$SPM_PYTHON" --no-sync python scripts/bundle.py set-spm \ @@ -126,7 +126,7 @@ uv run --python "$SPM_PYTHON" --no-sync python scripts/bundle.py set-spm \ uv run --python "$SPM_PYTHON" --no-sync python scripts/bundle.py check ``` -After the calculator's actual registry release is authorized and published, +After the calculator's actual registry release is authorised and published, repeat `set-spm` with `--calculator-version "$PUBLISHED_CALCULATOR_VERSION"`. The command fetches that exact version's authoritative PyPI metadata, requires one non-yanked universal wheel on `files.pythonhosted.org`, downloads its bytes, @@ -135,13 +135,11 @@ hashed `runtime_dependency` scoped to the US, adds it to US/models/dev extras, and preserves UK requirements. The version must come from the real release; local wheel metadata is not proof of registry publication. -`scripts/bundle.py check --published-spm` checks the measurement pin and -published calculator dependency metadata. **It does not establish country/data -compatibility or whole-release readiness.** It rejects development fixtures and -currently exits 2 with `SPM promotion pending: no published spm-calculator pin`. -Ordinary `check` passes for the staged draft; this is metadata consistency only. +Both `bundle.py check` and `bundle.py check --published-spm` pass on the +checked-in bundle. The published check verifies the measurement pin and +calculator dependency metadata and rejects development fixtures. -## Exact work remaining before a production bundle +## Historical pre-promotion checklist 1. Complete the coordinator's canonical numerical acceptance and source/review gates. Deploy the separately owned protections for old bundle images before @@ -157,7 +155,7 @@ Ordinary `check` passes for the staged draft; this is metadata consistency only. county inputs and weights are preserved. This is source enrichment, not recalibration. The inherited diagnostics remain schema 5, SHA-256 `870449b44e86b13b25bcea1a57f0e7af37f4d4db18be815eea3acdf9fe6eb40e`; - relabeling those diagnostics as schema 6 is invalid. + relabelling those diagnostics as schema 6 is invalid. 3. In the producer checkout, run its real `python -m microcosm.data.source_enrichment --certify` contract with the new candidate, exact parent H5 and actual country/Core/wrapper compatibility wheels. That @@ -186,11 +184,5 @@ Ordinary `check` passes for the staged draft; this is metadata consistency only. No release, publication, deployment, full population run or data certification was performed by this wrapper tooling work. -The bundled TRACE sidecars are regenerated against the current manifest, so -`TestVendoredSidecarBinding` passes: both `us.trace.tro.jsonld` and -`uk.trace.tro.jsonld` bind manifest SHA-256 -`d430b8e561d76e5836a17bf506b06b9cd16560eb77f15718dd46f4e78513de85`, which is -the hash of `src/policyengine/data/bundle/manifest.json` in this tree. That -binding covers the staged measurement bytes only; it is metadata provenance, -not data certification, and the sidecars must be regenerated and reviewed again -at the real bundle promotion step against published artifacts. +Both vendored TRACE sidecars bind the checked-in manifest SHA-256 +`07da3cc8567ce06d61b1dddbcb038e484865231827d6ec4bd0d40046aed96e3b`. diff --git a/docs/microsim.md b/docs/microsim.md index c8ec589fe..72ba32703 100644 --- a/docs/microsim.md +++ b/docs/microsim.md @@ -424,9 +424,9 @@ sim = managed_microsimulation() ``` Pass `allow_unmanaged=True` with an explicit local file to bypass bundled-data -certification in `managed_microsimulation()`. Explicit Hugging Face URIs also -require `allow_unmanaged=True`, and the wrapper checks US bundled-data -certification before fetching them. GCS dataset URIs are unsupported. +certification in `managed_microsimulation()`. Pass `allow_unmanaged=True` for a +Hugging Face URI outside the bundled default. The wrapper checks US bundled-data +certification before fetching either kind of URI. GCS dataset URIs are unsupported. An explicit local US file records its SHA-256 and the installed wrapper, country, Core and SPM versions in `sim.policyengine_bundle`. Its `compatibility_basis` @@ -437,17 +437,21 @@ accessed. Accessing the UK namespace still certifies data during initialisation. US managed materialisation, managed year-file helpers and the US model’s run, output-load, cache-reuse, bundle-receipt and TRACE entry points check runtime compatibility on each call. Run-record export checks the attached US runtime -whether it builds the bundle TRO or receives one from the caller. Direct URI -selection applies the bundle’s selection rules. The compatibility check runs +whether it builds the bundle TRO or receives one from the caller. A supplied +TRO must match the attached model’s country, bundle, data build and certified +runtime. Direct URI selection applies the bundle’s selection rules. The compatibility check runs during managed materialisation. `create_datasets()` and `ensure_datasets()` also accept an explicit local source -with `allow_unmanaged=True`. The standalone `load_long_term_datasets()` reads -local files and checks their metadata. `load_managed_long_term_datasets()` -checks bundled-data certification. Year files record the source and runtime -that produced them. Saved US simulation outputs record the input tables and -runtime. Reuse requires matching identities, and `ensure_datasets()` or -`Simulation.ensure()` regenerates older files that lack a matching identity. +with `allow_unmanaged=True`. A missing absolute local path raises +`FileNotFoundError` before bundled-data certification. The standalone +`load_long_term_datasets()` checks local files for self-contained HDF5 storage +and validates their metadata. `load_managed_long_term_datasets()` checks +bundled-data certification. Year files record the source and runtime that +produced them. Cached US simulation outputs bind the calculation inputs, +resolved legacy SPM profile, policy and dynamic reforms, effective scope, +requested output columns and runtime. `ensure_datasets()` and +`Simulation.ensure()` regenerate files that lack a matching identity. For a local `.h5` TIME_PERIOD_ARRAYS file, pass `native_input_period="2017"` to set the Core Dataset descriptor's annual clock and both default input and diff --git a/src/policyengine/core/run_record.py b/src/policyengine/core/run_record.py index bb302b083..aecd5ff06 100644 --- a/src/policyengine/core/run_record.py +++ b/src/policyengine/core/run_record.py @@ -26,6 +26,7 @@ from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from policyengine.provenance.trace import ( + _validate_supplied_bundle_tro, build_simulation_trace_tro, canonical_json_bytes, extract_bundle_tro_reference, @@ -260,8 +261,13 @@ def write_simulation_run_record( "tax_benefit_model_version with a bundled release manifest." ) bundle_tro = model.trace_tro - elif getattr(model, "country_code", None) == "us": - model.require_data_certification() + elif model is not None: + certification = ( + model.require_data_certification() + if getattr(model, "country_code", None) == "us" + else model.data_certification + ) + _validate_supplied_bundle_tro(bundle_tro, model.release_manifest, certification) # Build payloads (and surface refusals) before touching the filesystem. payloads = build_simulation_run_record_payloads(simulation) diff --git a/src/policyengine/provenance/dataset_materialization.py b/src/policyengine/provenance/dataset_materialization.py index bb2cba757..be630ee5b 100644 --- a/src/policyengine/provenance/dataset_materialization.py +++ b/src/policyengine/provenance/dataset_materialization.py @@ -159,6 +159,18 @@ def _require_us_data_certification(): return us_latest.require_data_certification() +def _us_local_dataset_path(dataset: str) -> Optional[Path]: + """Distinguish local paths from dataset names and remote URIs.""" + if "://" in dataset: + return None + path = Path(dataset).expanduser() + if path.exists(): + return path + if path.is_absolute() or dataset.startswith(("./", "../")): + raise FileNotFoundError(f"Explicit local US dataset not found: {path}") + return None + + def materialize_dataset( country_id: str, dataset: Optional[str] = None, @@ -184,16 +196,9 @@ def materialize_dataset( manifest=manifest, ) - if ( - country_id == "us" - and allow_unmanaged - and isinstance(dataset, str) - and ( - dataset.startswith("hf://") - or ("://" not in dataset and not Path(dataset).expanduser().exists()) - ) - ): - _require_us_data_certification() + if country_id == "us" and _us_local_dataset_path(dataset) is None: + if allow_unmanaged and (dataset.startswith("hf://") or "://" not in dataset): + _require_us_data_certification() source_uri = resolve_managed_dataset_reference( country_id, dataset, diff --git a/src/policyengine/provenance/trace.py b/src/policyengine/provenance/trace.py index 51edfae8b..46c385c98 100644 --- a/src/policyengine/provenance/trace.py +++ b/src/policyengine/provenance/trace.py @@ -286,6 +286,15 @@ def _assemble_tro_node( return node +def _bundle_manifest_sha256(manifest: CountryReleaseManifest) -> str: + return ( + manifest.source_sha256 + or hashlib.sha256( + canonical_json_bytes(manifest.model_dump(mode="json")) + ).hexdigest() + ) + + def build_trace_tro_from_release_bundle( country_manifest: CountryReleaseManifest, data_release_manifest: Optional[DataReleaseManifest], @@ -359,12 +368,7 @@ def build_trace_tro_from_release_bundle( repo_type=country_manifest.data_package.repo_type, ) - bundle_manifest_hash = ( - country_manifest.source_sha256 - or hashlib.sha256( - canonical_json_bytes(country_manifest.model_dump(mode="json")) - ).hexdigest() - ) + bundle_manifest_hash = _bundle_manifest_sha256(country_manifest) data_release_manifest_hash = ( data_release_manifest.source_sha256 or hashlib.sha256( @@ -579,13 +583,7 @@ def serialize_trace_tro(tro: Mapping) -> bytes: return canonical_json_bytes(tro) -def extract_bundle_tro_reference(tro: Mapping) -> dict[str, Any]: - """Extract a compact reference to a bundle TRO for use as a simulation input. - - Locates the ``trov:TransparentResearchObject`` node explicitly rather - than trusting ``@graph[0]`` so future TROs that embed additional - nodes (TRS, TSA) do not break reference extraction. - """ +def _bundle_tro_node(tro: Mapping) -> Mapping: graph = tro.get("@graph") or [] node = next( (n for n in graph if n.get("@type") == "trov:TransparentResearchObject"), @@ -595,6 +593,79 @@ def extract_bundle_tro_reference(tro: Mapping) -> dict[str, Any]: raise ValueError( "TRO graph does not contain a trov:TransparentResearchObject node." ) + return node + + +def _validate_supplied_bundle_tro( + tro: Mapping, + manifest: Optional[CountryReleaseManifest], + certification: Optional[DataCertification], +) -> None: + """Check that a supplied TRO describes the attached model's certification.""" + if ( + manifest is None + or manifest.certified_data_artifact is None + or certification is None + ): + raise ValueError( + "Supplied bundle TRO requires an attached model with a certified bundle" + ) + + try: + node = _bundle_tro_node(tro) + artifacts = node["trov:hasComposition"]["trov:hasArtifact"] + (manifest_artifact,) = ( + artifact + for artifact in artifacts + if artifact["@id"].endswith("/bundle_manifest") + ) + (dataset_artifact,) = ( + artifact for artifact in artifacts if artifact["@id"].endswith("/dataset") + ) + performance = node["trov:hasPerformance"] + extract_bundle_tro_reference(tro) + except (AttributeError, KeyError, TypeError, ValueError) as error: + raise ValueError("Supplied bundle TRO has invalid bundle provenance") from error + + if ( + manifest_artifact.get("schema:name") + != f"policyengine.py bundle manifest for {manifest.country_id}" + or manifest_artifact.get("trov:sha256") != _bundle_manifest_sha256(manifest) + ): + raise ValueError( + "Supplied bundle TRO refers to a different country or bundle manifest" + ) + + dataset = manifest.certified_data_artifact + if ( + dataset_artifact.get("schema:name") != dataset.dataset + or (dataset.sha256 and dataset_artifact.get("trov:sha256") != dataset.sha256) + or performance.get("pe:dataBuildId") != certification.data_build_id + or performance.get("pe:dataBuildFingerprint") + != certification.data_build_fingerprint + ): + raise ValueError( + "Supplied bundle TRO refers to a different certified data build" + ) + + if ( + performance.get("pe:certifiedForModelVersion") + != certification.certified_for_model_version + or performance.get("pe:certifiedForCoreVersion") + != certification.certified_for_core_version + or performance.get("pe:coreBinding") != certification.core_binding + ): + raise ValueError("Supplied bundle TRO refers to a different certified runtime") + + +def extract_bundle_tro_reference(tro: Mapping) -> dict[str, Any]: + """Extract a compact reference to a bundle TRO for use as a simulation input. + + Locates the ``trov:TransparentResearchObject`` node explicitly rather + than trusting ``@graph[0]`` so future TROs that embed additional + nodes (TRS, TSA) do not break reference extraction. + """ + node = _bundle_tro_node(tro) composition = node.get("trov:hasComposition") or {} fingerprint = ( composition.get("trov:hasFingerprint", {}).get("trov:sha256") diff --git a/src/policyengine/tax_benefit_models/common/model_version.py b/src/policyengine/tax_benefit_models/common/model_version.py index 0ee1e2e86..9c1fd3d97 100644 --- a/src/policyengine/tax_benefit_models/common/model_version.py +++ b/src/policyengine/tax_benefit_models/common/model_version.py @@ -440,7 +440,9 @@ def resolve_entity_variables( resolved[entity] = merged return resolved - def _output_cache_identity(self, simulation: Simulation) -> dict: + def _output_cache_identity( + self, simulation: Simulation, recorded: Optional[dict] = None + ) -> dict: raise NotImplementedError def save(self, simulation: Simulation) -> None: @@ -478,9 +480,9 @@ def save(self, simulation: Simulation) -> None: "before saving" ) identity = simulation.output_dataset.metadata.get("output_identity") - if identity != self._output_cache_identity(simulation): + if identity != self._output_cache_identity(simulation, identity): raise ValueError( - "US simulation inputs or runtime changed; run again before saving" + "US simulation request, inputs or runtime changed; run again before saving" ) serialized_spm = json.dumps( { @@ -597,9 +599,8 @@ def load(self, simulation: Simulation) -> None: "run it again" ) - if recorded.get("output_identity") != self._output_cache_identity( - simulation - ): + identity = recorded.get("output_identity") + if identity != self._output_cache_identity(simulation, identity): raise StaleOutputError( "Saved US simulation has a missing or different input or runtime identity" ) diff --git a/src/policyengine/tax_benefit_models/us/datasets.py b/src/policyengine/tax_benefit_models/us/datasets.py index dd128cdac..c1e9b8df9 100644 --- a/src/policyengine/tax_benefit_models/us/datasets.py +++ b/src/policyengine/tax_benefit_models/us/datasets.py @@ -19,6 +19,7 @@ DatasetSource, MaterializedDataset, _require_us_data_certification, + _us_local_dataset_path, materialize_dataset, ) from policyengine.provenance.manifest import ( @@ -406,7 +407,7 @@ def _load_policyengine_core_h5(path: Path, year: int) -> USYearData: ) -def _require_self_contained_hdf5(path: str) -> None: +def _require_self_contained_hdf5(path: str | Path) -> None: """Refuse HDF5 links or storage that refer to bytes outside the file.""" def check_node(_name, node): @@ -750,11 +751,8 @@ def _year_file_request( from policyengine.tax_benefit_models.us.model import _us_runtime_versions managed_name = _managed_source_name(dataset) - if ( - managed_name is not None - or "://" in dataset - or not Path(dataset).expanduser().exists() - ): + path = _us_local_dataset_path(dataset) if managed_name is None else None + if path is None: _require_us_data_certification() uri = resolve_dataset_reference("us", dataset) sha256 = _managed_source_sha256(dataset) @@ -772,7 +770,6 @@ def _year_file_request( raise ValueError( "Pass allow_unmanaged=True to use an explicit local dataset" ) - path = Path(dataset).expanduser() if not path.is_file(): raise ValueError(f"Explicit local US dataset must be a file: {dataset!r}") uri = str(path) @@ -1354,6 +1351,7 @@ def load_long_term_datasets( require_runtime_policyengine_us_match=require_runtime_policyengine_us_match, ) + _require_self_contained_hdf5(path) dataset = _build_long_term_dataset( path=path, year=year, diff --git a/src/policyengine/tax_benefit_models/us/model.py b/src/policyengine/tax_benefit_models/us/model.py index 816703914..0f44cdd61 100644 --- a/src/policyengine/tax_benefit_models/us/model.py +++ b/src/policyengine/tax_benefit_models/us/model.py @@ -23,6 +23,7 @@ ) from .datasets import ( + US_ENTITY_ID_COLUMNS, PolicyEngineUSDataset, USYearData, _require_self_contained_hdf5, @@ -32,17 +33,21 @@ RENAMES_RECORD_KEY, apply_legacy_input_renames, apply_legacy_input_renames_to_microsimulation, + pending_legacy_input_renames, ) from .legacy_spm import ( RECORD_KEY as LEGACY_SPM_RECORD_KEY, ) from .legacy_spm import ( derive_from_stored_tables, + expected_profile_for_dataset, legacy_spm_for_run, legacy_spm_source, prepare_microsimulation, set_declarations, ) +from .legacy_spm.independence import INDEPENDENCE_ROLE +from .legacy_spm.model_adapter import UNIVERSE_VARIABLE from .spm import ( SPMProvenance, SPMSelection, @@ -62,6 +67,14 @@ ] +def _hash_input_table(digest, entity, frame): + schema = [(str(name), str(dtype)) for name, dtype in frame.dtypes.items()] + digest.update(json.dumps([entity, len(frame), schema]).encode()) + if len(frame.columns): + hashes = pd.util.hash_pandas_object(frame, index=False) + digest.update(hashes.to_numpy(dtype=" None: self.require_data_certification() - def _output_cache_identity(self, simulation: "Simulation") -> dict: - """Bind an output to the runtime and the tables consumed by the model.""" + def _scoped_input_tables(self, simulation: "Simulation") -> dict: + from spm_calculator.policyengine_adapter import validate_policyengine_inputs + dataset = simulation.dataset if dataset.data is None: dataset.load() + tables = dataset.data.entity_data + validate_policyengine_inputs(tables) + if simulation.scoping_strategy is None: + return tables + return simulation.scoping_strategy.apply( + entity_data=tables, group_entities=US_GROUP_ENTITIES, year=dataset.year + ) + + def _output_cache_identity( + self, + simulation: "Simulation", + recorded: Optional[dict] = None, + *, + scoped_tables: Optional[dict] = None, + input_variables: Optional[set[str]] = None, + runtime_packages: Optional[dict[str, str]] = None, + ) -> dict: + """Bind an output to the resolved request, consumed inputs and runtime.""" + from policyengine.utils.parametric_reforms import build_reform_dict + + dataset = simulation.dataset + if scoped_tables is None: + scoped_tables = self._scoped_input_tables(simulation) + + # Keep the structural reforms' variable changes with the output so a + # cache lookup can recognise their inputs without building a country sim. + base_variables = self.variables_by_name.keys() + if input_variables is not None: + added = sorted(input_variables - base_variables) + removed = sorted(base_variables - input_variables) + else: + variable_changes = ( + recorded.get("variable_changes", {}) + if isinstance(recorded, dict) + else {} + ) + added = variable_changes.get("added", []) + removed = variable_changes.get("removed", []) + input_variables = (base_variables | set(added)) - set(removed) + + scope = simulation.scoping_strategy + legacy_profile = expected_profile_for_dataset(dataset) + stored_legacy = dataset.metadata.get(LEGACY_SPM_RECORD_KEY) + reforms = [] + for reform in (simulation.policy, simulation.dynamic): + changes = build_reform_dict(reform) or {} + # Core uses period order to break ties with the same start date. + reforms.append( + {name: list(periods.items()) for name, periods in changes.items()} + ) digest = hashlib.sha256() digest.update( json.dumps( - [dataset.year, dataset.metadata.get(LEGACY_SPM_RECORD_KEY)], + [ + dataset.year, + reforms, + scope.model_dump(mode="json") if scope is not None else None, + list(self.resolve_entity_variables(simulation).items()), + dataset.metadata.get(RENAMES_RECORD_KEY), + stored_legacy, + legacy_profile.model_dump(mode="json") if legacy_profile else None, + ], sort_keys=True, ).encode() ) - for entity, table in dataset.data.entity_data.items(): + + # Legacy SPM validates or derives its declarations before scoping. + if legacy_profile is not None: + tables = dataset.data.entity_data + legacy_columns = ( + { + "person": [ + "person_id", + "person_spm_unit_id", + "spm_unit_id", + "person_household_id", + "household_id", + "person_support_channel", + "RELSHIPP", + "is_household_head", + "is_household_spouse", + INDEPENDENCE_ROLE, + ], + "household": ["household_id", "TYPEHUGQ"], + } + if stored_legacy is None + else {"person": [INDEPENDENCE_ROLE], "spm_unit": [UNIVERSE_VARIABLE]} + ) + for entity, columns in legacy_columns.items(): + frame = pd.DataFrame(tables[entity]) + _hash_input_table( + digest, entity, frame.loc[:, frame.columns.isin(columns)] + ) + + pending_renames = pending_legacy_input_renames(dict.fromkeys(input_variables)) + for entity, table in scoped_tables.items(): frame = pd.DataFrame(table) - schema = [ - (str(name), str(dtype)) - for name, dtype in zip(frame.columns, frame.dtypes) - ] - digest.update(json.dumps([entity, len(frame), schema]).encode()) - hashes = pd.util.hash_pandas_object(frame, index=False) - digest.update(hashes.to_numpy(dtype=" bool: if cached.output_dataset is None: return False - return cached.output_dataset.metadata.get( - "output_identity" - ) == self._output_cache_identity(simulation) + identity = cached.output_dataset.metadata.get("output_identity") + return identity == self._output_cache_identity(simulation, identity) def load(self, simulation): self._validate_cached_output() @@ -248,33 +360,16 @@ def run(self, simulation: "Simulation") -> "Simulation": assert isinstance(simulation.dataset, PolicyEngineUSDataset) + runtime_packages = _us_runtime_versions() dataset = simulation.dataset - # Load from disk only when the caller did not already supply data. - # An unconditional reload discards caller-provided in-memory data - # and forced construction to persist datasets to disk (see the - # autosave removal in datasets.py). - if dataset.data is None: - dataset.load() - output_identity = self._output_cache_identity(simulation) - - # Validate every entity before constructing either the reform or its - # baseline, so no set_input can suppress a canonical SPM formula. - from spm_calculator.policyengine_adapter import validate_policyengine_inputs - - validate_policyengine_inputs(dataset.data.entity_data) + scoped_data = self._scoped_input_tables(simulation) # BACKWARD COMPATIBILITY (#597, #598): a legacy certified source # carries no SPM declarations. A year file cut from one stores them; # a run straight over one derives them now (see ``legacy_spm``). legacy_spm = legacy_spm_for_run(dataset) - # Apply regional scoping if specified - if simulation.scoping_strategy: - scoped_data = simulation.scoping_strategy.apply( - entity_data=dataset.data.entity_data, - group_entities=US_GROUP_ENTITIES, - year=dataset.year, - ) + if simulation.scoping_strategy is not None: dataset = PolicyEngineUSDataset( id=dataset.id + "_scoped", name=dataset.name, @@ -350,6 +445,16 @@ class InputMicrosimulation(Microsimulation): # raw legacy source are set on the simulation and its baseline. set_declarations(microsim, legacy_spm.in_memory, [dataset.year]) + input_variables = set(microsim.tax_benefit_system.variables) + if microsim.baseline is not None: + input_variables.update(microsim.baseline.tax_benefit_system.variables) + output_identity = self._output_cache_identity( + simulation, + scoped_tables=scoped_data, + input_variables=input_variables, + runtime_packages=runtime_packages, + ) + data = { "person": pd.DataFrame(), "marital_unit": pd.DataFrame(), diff --git a/tests/test_us_legacy_inputs_integration.py b/tests/test_us_legacy_inputs_integration.py index 5da4e155d..64cb230ec 100644 --- a/tests/test_us_legacy_inputs_integration.py +++ b/tests/test_us_legacy_inputs_integration.py @@ -942,3 +942,16 @@ def test_the_run_record_binds_the_renames_applied(tmp_path): payloads = build_simulation_run_record_payloads(simulation) assert payloads["results"]["legacy_input_renames"] == RENAME + + +def test_us_run_ignores_list_valued_annotation(tmp_path): + frames = _frames() + frames["person"]["ignored_annotation"] = [["adult"], [], ["child", "toddler"]] + + annotated = _run(_in_memory_dataset(tmp_path, frames)) + plain = _run(_in_memory_dataset(tmp_path)) + for entity in plain.output_dataset.data.entity_data: + pd.testing.assert_frame_equal( + pd.DataFrame(annotated.output_dataset.data.entity_data[entity]), + pd.DataFrame(plain.output_dataset.data.entity_data[entity]), + ) diff --git a/tests/test_us_unmanaged_runtime.py b/tests/test_us_unmanaged_runtime.py index f8cac4cbe..0699e5549 100644 --- a/tests/test_us_unmanaged_runtime.py +++ b/tests/test_us_unmanaged_runtime.py @@ -23,9 +23,11 @@ DataReleaseManifestUnavailableError, get_release_manifest, ) +from tests import test_us_legacy_spm_integration as legacy_spm_tests us_model = importlib.import_module("policyengine.tax_benefit_models.us.model") us_datasets = importlib.import_module("policyengine.tax_benefit_models.us.datasets") +legacy_files = legacy_spm_tests.legacy_files def refuse_certification(*args, **kwargs): @@ -656,6 +658,48 @@ def test_supplied_run_record_tro_requires_current_us_certification( assert not output.exists() +@pytest.fixture(scope="module") +def certified_us_run(tmp_path_factory): + from tests.test_us_legacy_inputs_integration import _saved_run + + simulation = _saved_run( + tmp_path_factory.mktemp("certified"), "certified-run-record" + ) + simulation.dataset.save() + return simulation + + +@pytest.mark.parametrize("mismatch", ["country", "bundle", "build", "runtime", None]) +def test_supplied_run_record_tro_matches_certified_us_bundle( + certified_us_run, tmp_path, mismatch +): + import json + from pathlib import Path + + country = "uk" if mismatch == "country" else "us" + bundle_dir = Path(us_model.__file__).resolve().parents[2] / "data/bundle" + bundle_tro = json.loads((bundle_dir / f"{country}.trace.tro.jsonld").read_text()) + node = bundle_tro["@graph"][0] + if mismatch == "bundle": + artifacts = node["trov:hasComposition"]["trov:hasArtifact"] + next(item for item in artifacts if item["@id"].endswith("/bundle_manifest"))[ + "trov:sha256" + ] = "0" * 64 + if mismatch == "build": + node["trov:hasPerformance"]["pe:dataBuildId"] = "another-build" + if mismatch == "runtime": + node["trov:hasPerformance"]["pe:certifiedForModelVersion"] = "2.3.0" + + output = tmp_path / "run-record" + if mismatch is None: + record = certified_us_run.write_run_record(output, bundle_tro=bundle_tro) + assert json.loads(record.paths["bundle_tro"].read_text()) == bundle_tro + else: + with pytest.raises(ValueError, match="Supplied bundle TRO"): + certified_us_run.write_run_record(output, bundle_tro=bundle_tro) + assert not output.exists() + + def test_runtime_receipt_and_trace_name_the_certified_us_version( monkeypatch, uncertified_us_runtime ): @@ -726,21 +770,42 @@ def offline(event, args): assert result.returncode == 0, result.stderr +@pytest.fixture +def native_hdf5_storage(tmp_path): + def write(storage): + path = tmp_path / "native.h5" + external = tmp_path / "external.h5" + with h5py.File(external, "w") as file: + file.create_dataset("vector", data=[20]) + with h5py.File(path, "w") as file: + file.create_dataset("person_id/2017", data=[1]) + file.create_dataset("household_weight/2017", data=[1.0]) + for entity in us_model.US_GROUP_ENTITIES: + file.create_dataset(f"{entity}_id/2017", data=[1]) + file.create_dataset(f"person_{entity}_id/2017", data=[1]) + if storage == "external-link": + file["age/2017"] = h5py.ExternalLink(str(external), "/vector") + else: + if storage == "in-file-virtual": + file.create_dataset("employment_income/2017", data=[20]) + source = h5py.VirtualSource( + ".", "employment_income/2017", shape=(1,) + ) + else: + source = h5py.VirtualSource(str(external), "vector", shape=(1,)) + layout = h5py.VirtualLayout(shape=(1,), dtype="int64") + layout[:] = source + file.create_virtual_dataset("age/2017", layout) + return path, external + + return write + + @pytest.mark.parametrize("native_input_period", [None, "2017"]) def test_local_factory_refuses_external_hdf5_inputs( - monkeypatch, tmp_path, native_input_period + monkeypatch, native_hdf5_storage, native_input_period ): - external = tmp_path / "external.h5" - with h5py.File(external, "w") as file: - file.create_dataset("vector", data=[20]) - path = tmp_path / "native.h5" - with h5py.File(path, "w") as file: - file.create_dataset("person_id/2017", data=[1]) - for entity in us_model.US_GROUP_ENTITIES: - file.create_dataset(f"{entity}_id/2017", data=[1]) - file.create_dataset(f"person_{entity}_id/2017", data=[1]) - file["age/2017"] = h5py.ExternalLink(str(external), "/vector") - + path, external = native_hdf5_storage("external-link") monkeypatch.setattr( us_model.PolicyEngineUSLatest, "require_data_certification", @@ -759,6 +824,49 @@ def test_local_factory_refuses_external_hdf5_inputs( ) +@pytest.mark.parametrize("storage", ["in-file-virtual", "external-virtual"]) +def test_native_factory_checks_virtual_hdf5_storage(native_hdf5_storage, storage): + path, _ = native_hdf5_storage(storage) + expected = ( + nullcontext() + if storage == "in-file-virtual" + else pytest.raises(ValueError, match="must be self-contained") + ) + with expected: + simulation = us_model.managed_microsimulation( + dataset=str(path), allow_unmanaged=True, native_input_period="2017" + ) + assert simulation.calculate("age", "2017").values.tolist() == [20] + + +@pytest.mark.parametrize( + "storage", ["external-link", "external-virtual", "in-file-virtual"] +) +def test_standalone_long_term_loader_checks_hdf5_storage( + monkeypatch, native_hdf5_storage, storage +): + path, _ = native_hdf5_storage(storage) + if storage != "in-file-virtual": + monkeypatch.setattr( + us_datasets.PolicyEngineUSDataset, + "load", + lambda self: pytest.fail("Started hydrating external HDF5 data"), + ) + expected = ( + nullcontext() + if storage == "in-file-virtual" + else pytest.raises(ValueError, match="must be self-contained") + ) + with expected: + (dataset,) = us_datasets.load_long_term_datasets( + years=[2017], + data_folder=str(path.parent), + dataset_template=path.name, + require_metadata=False, + ).values() + assert dataset.data.person["age"].tolist() == [20] + + def test_native_factory_refuses_suffix_before_hashing(monkeypatch, tmp_path): from policyengine.utils import hashing @@ -814,6 +922,30 @@ def test_explicit_local_year_operations_bypass_unused_bundle( assert loaded.data.person["age"].tolist() == [30, 0, 2] +@pytest.mark.parametrize( + "operation", ["create_datasets", "ensure_datasets", "load_datasets"] +) +def test_missing_absolute_local_year_source_skips_certification( + monkeypatch, tmp_path, operation +): + calls = [] + + def certify(): + calls.append("certify") + pytest.fail("Attempted bundled-data certification for a missing local path") + + for module in (materialization, us_datasets): + monkeypatch.setattr(module, "_require_us_data_certification", certify) + + options = {} if operation == "load_datasets" else {"allow_unmanaged": True} + path = tmp_path / "missing.h5" + with pytest.raises(FileNotFoundError, match="missing.h5"): + getattr(us_datasets, operation)( + datasets=[str(path)], years=[2024], data_folder=str(tmp_path), **options + ) + assert calls == [] + + def test_managed_year_replaces_a_same_stem_explicit_local_year(monkeypatch, tmp_path): from pathlib import Path @@ -932,3 +1064,175 @@ def new_request(dataset): assert changed.output_dataset.data.person["age"].tolist() == [31, 1, 3] finally: _cache.clear() + + +@pytest.mark.parametrize("change", ["policy", "dynamic", "scope", "columns"]) +def test_us_output_cache_misses_when_the_request_changes(monkeypatch, tmp_path, change): + import pandas as pd + + from policyengine.core import Simulation + from policyengine.core.scoping_strategy import RowFilterStrategy + from policyengine.core.simulation import _cache + from tests.test_us_legacy_inputs_integration import _frames, _in_memory_dataset + + monkeypatch.setattr(us_model.us_latest, "entity_variables", {"tax_unit": ["eitc"]}) + frames = _frames() + for entity, frame in frames.items(): + second = frame.copy() + for column in second: + if column.endswith("_id"): + second[column] += 10 + frames[entity] = pd.concat([frame, second], ignore_index=True) + frames["person"]["employment_income"] = [8_000, 0, 0, 8_000, 0, 0] + frames["household"]["state_code"] = ["CA", "NY"] + frames["household"]["scope_state"] = ["CA", "NY"] + frames["household"]["county_fips"] = ["06037", "36061"] + reform = {"gov.irs.credits.eitc.phase_in_rate[2].amount": 0.9} + request = { + "policy": {"policy": reform}, + "dynamic": {"dynamic": reform}, + "scope": { + "scoping_strategy": RowFilterStrategy( + variable_name="scope_state", variable_value="CA" + ) + }, + "columns": {"extra_variables": {"tax_unit": ["adjusted_gross_income"]}}, + }[change] + + def simulation(**options): + return Simulation( + id="same-id-and-request", + dataset=_in_memory_dataset(tmp_path, frames), + tax_benefit_model_version=us_model.us_latest, + **options, + ) + + def signature(run): + tables = run.output_dataset.data + return ( + tables.tax_unit["eitc"].tolist(), + tables.household["household_id"].tolist(), + tables.tax_unit.get( + "adjusted_gross_income", pd.Series(dtype=float) + ).tolist(), + ) + + _cache.clear() + try: + initial = simulation() + initial.ensure() + fresh = simulation(**request) + fresh.run() + assert signature(fresh) != signature(initial) + + memory = simulation(**request) + memory.ensure() + _cache.clear() + initial.save() + disk = simulation(**request) + disk.ensure() + assert {"memory": signature(memory), "disk": signature(disk)} == { + "memory": signature(fresh), + "disk": signature(fresh), + } + for result in (memory, disk): + tables = result.output_dataset.data.entity_data + for entity, expected in fresh.output_dataset.data.entity_data.items(): + pd.testing.assert_frame_equal( + pd.DataFrame(tables[entity]), pd.DataFrame(expected) + ) + + with monkeypatch.context() as m: + m.setattr( + us_model.PolicyEngineUSLatest, + "run", + lambda *args: pytest.fail("Recalculated an equivalent request"), + ) + memory_hit = simulation(**request) + memory_hit.ensure() + assert memory_hit.output_dataset is disk.output_dataset + _cache.clear() + disk_hit = simulation(**request) + disk_hit.ensure() + assert signature(disk_hit) == signature(fresh) + + for field in request: + setattr(initial, field, getattr(fresh, field)) + with pytest.raises(ValueError, match="request, inputs or runtime changed"): + initial.save() + unchanged_on_disk = simulation(**request) + unchanged_on_disk.load() + assert signature(unchanged_on_disk) == signature(fresh) + finally: + _cache.clear() + + +def test_us_memory_cache_resolves_each_raw_legacy_file( + tmp_path, legacy_files, monkeypatch +): + import shutil + from pathlib import Path + + import pandas as pd + + from policyengine.core import Simulation + from policyengine.core.simulation import _cache + + registered = Path(legacy_files.source) + with pd.HDFStore(registered, "a") as store: + person = store["person"] + # The single-person units also need an adult on the unregistered run. + person["age"] = person["age"].where(~person["person_id"].isin([3, 6]), 20) + store.put("person", person, format="table", data_columns=True) + unregistered = tmp_path / "unregistered.h5" + shutil.copyfile(registered, unregistered) + with h5py.File(unregistered, "r+") as file: + file.attrs["synthetic_marker"] = "changes bytes without changing tables" + + registered_hash = legacy_spm_tests.runs.sha256_file(registered) + assert legacy_spm_tests.runs.sha256_file(unregistered) != registered_hash + monkeypatch.setattr( + legacy_spm_tests.runs, + "legacy_spm_source", + lambda sha256: legacy_spm_tests.BUILD_O if sha256 == registered_hash else None, + ) + + def request(path): + return Simulation( + id="same-id-and-tables-legacy-source", + dataset=us_datasets.PolicyEngineUSDataset( + name="raw-legacy-source", + description="Synthetic raw legacy source", + filepath=str(path), + year=2024, + ), + tax_benefit_model_version=us_model.us_latest, + ) + + _cache.clear() + try: + original = request(registered) + original.ensure() + same_source = request(registered) + same_source.ensure() + assert same_source.output_dataset is original.output_dataset + + fresh = request(unregistered) + fresh.run() + assert legacy_spm_tests.RECORD_KEY in original.output_dataset.metadata + assert legacy_spm_tests.RECORD_KEY not in fresh.output_dataset.metadata + for entity, table in original.dataset.data.entity_data.items(): + pd.testing.assert_frame_equal( + pd.DataFrame(table), + pd.DataFrame(fresh.dataset.data.entity_data[entity]), + ) + + changed = request(unregistered) + changed.ensure() + assert legacy_spm_tests.RECORD_KEY not in changed.output_dataset.metadata + pd.testing.assert_frame_equal( + legacy_spm_tests._frame(changed, "spm_unit"), + legacy_spm_tests._frame(fresh, "spm_unit"), + ) + finally: + _cache.clear() From 2cb1d96db08172c5ffb190f05dae2fa378007ee8 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 1 Dec 2026 07:29:42 -0500 Subject: [PATCH 17/20] Exclude unused population ID aliases from US output cache identity Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- .../tax_benefit_models/us/model.py | 31 +++++++------------ tests/test_us_legacy_inputs_integration.py | 6 ++-- 2 files changed, 16 insertions(+), 21 deletions(-) diff --git a/src/policyengine/tax_benefit_models/us/model.py b/src/policyengine/tax_benefit_models/us/model.py index 0f44cdd61..4ce9d99c1 100644 --- a/src/policyengine/tax_benefit_models/us/model.py +++ b/src/policyengine/tax_benefit_models/us/model.py @@ -24,6 +24,7 @@ from .datasets import ( US_ENTITY_ID_COLUMNS, + US_PERSON_ENTITY_ID_COLUMNS, PolicyEngineUSDataset, USYearData, _require_self_contained_hdf5, @@ -66,6 +67,10 @@ "marital_unit", ] +_POPULATION_ID_COLUMNS = frozenset(US_ENTITY_ID_COLUMNS.values()) | frozenset( + US_PERSON_ENTITY_ID_COLUMNS.values() +) + def _hash_input_table(digest, entity, frame): schema = [(str(name), str(dtype)) for name, dtype in frame.dtypes.items()] @@ -310,16 +315,18 @@ def _output_cache_identity( ) pending_renames = pending_legacy_input_renames(dict.fromkeys(input_variables)) + model_inputs = input_variables - _POPULATION_ID_COLUMNS for entity, table in scoped_tables.items(): frame = pd.DataFrame(table) - columns = input_variables | { + columns = model_inputs | { US_ENTITY_ID_COLUMNS[entity], f"{entity}_weight", } if entity == "person": - for group in US_GROUP_ENTITIES: - link = US_ENTITY_ID_COLUMNS[group] - columns.add(f"person_{link}" if f"person_{link}" in frame else link) + for group, native in US_PERSON_ENTITY_ID_COLUMNS.items(): + columns.add( + native if native in frame else US_ENTITY_ID_COLUMNS[group] + ) if "would_claim_wic" in pending_renames and ( "would_claim_wic" in frame and "takes_up_wic_if_eligible" not in frame @@ -685,20 +692,6 @@ def _build_simulation_from_dataset(self, microsim, dataset, system): microsim.build_from_populations(builder.populations) - id_columns = { - "person_id", - "household_id", - "person_household_id", - "spm_unit_id", - "person_spm_unit_id", - "family_id", - "person_family_id", - "tax_unit_id", - "person_tax_unit_id", - "marital_unit_id", - "person_marital_unit_id", - } - stored_tables = {} for entity_name, entity_df in [ ("person", dataset.data.person), @@ -727,7 +720,7 @@ def _build_simulation_from_dataset(self, microsim, dataset, system): if live_name in system.variables: microsim.set_input(live_name, dataset.year, df[column].values) for column in df.columns: - if column not in id_columns and column in system.variables: + if column not in _POPULATION_ID_COLUMNS and column in system.variables: microsim.set_input(column, dataset.year, df[column].values) # The loop above skips columns the engine does not define, including diff --git a/tests/test_us_legacy_inputs_integration.py b/tests/test_us_legacy_inputs_integration.py index 64cb230ec..8be12ed9a 100644 --- a/tests/test_us_legacy_inputs_integration.py +++ b/tests/test_us_legacy_inputs_integration.py @@ -944,9 +944,11 @@ def test_the_run_record_binds_the_renames_applied(tmp_path): assert payloads["results"]["legacy_input_renames"] == RENAME -def test_us_run_ignores_list_valued_annotation(tmp_path): +@pytest.mark.parametrize("column", ["ignored_annotation", "household_id"]) +def test_us_run_ignores_list_valued_unread_column(tmp_path, column): frames = _frames() - frames["person"]["ignored_annotation"] = [["adult"], [], ["child", "toddler"]] + # The fixture supplies person_household_id, which takes precedence over household_id. + frames["person"][column] = [["adult"], [], ["child", "toddler"]] annotated = _run(_in_memory_dataset(tmp_path, frames)) plain = _run(_in_memory_dataset(tmp_path)) From 6e87cad6ee70014ab816baeeabe13840abc0d3b2 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 2 Dec 2026 16:02:47 -0500 Subject: [PATCH 18/20] Accept the shipped TRO, pin the model wheel and hash only linked legacy columns Round 3 found that this branch rejected the shipped US TRO, causing all four CI test failures; that the model wheel went unchecked; and that an unused raw legacy alias broke the cache hash. An omitted Core binding and bundle_pin now resolve to the validated manifest pin, while explicit bindings and versions stay strict. A pinned wheel digest now requires one wheel with that name and SHA-256. The cache hash uses the same household and SPM-unit link selector as legacy declaration derivation. The SPM runbook now dates its pins to wrapper release 6.20.2 and is titled as history. Tests cover each case and the two scope gaps round 3 named. Co-Authored-By: Claude Opus 5.5 --- .../runbooks/canonical-spm-development.md | 16 +- src/policyengine/provenance/trace.py | 23 +- .../tax_benefit_models/us/model.py | 20 +- tests/test_us_legacy_inputs_integration.py | 46 +++- tests/test_us_unmanaged_runtime.py | 237 ++++++++++++++++-- 5 files changed, 299 insertions(+), 43 deletions(-) diff --git a/docs/engineering/runbooks/canonical-spm-development.md b/docs/engineering/runbooks/canonical-spm-development.md index 1ba53c8d7..90e3600b4 100644 --- a/docs/engineering/runbooks/canonical-spm-development.md +++ b/docs/engineering/runbooks/canonical-spm-development.md @@ -1,9 +1,9 @@ -# Canonical SPM wrapper development and remaining release gates +# Canonical SPM wrapper development history -This runbook records the historical SPM development procedure. The checked-in -6.20.2 bundle pins US 2.2.2, Core 3.34.10, UK 2.177.7 and spm-calculator 1.1.0. -The US certificate covers `populace-us-2024-spm-20260915`. The `ce_trend` county -forecast for vintage 2020 has SHA-256 +At wrapper release 6.20.2, the bundle pinned US 2.2.2, Core 3.34.10, UK 2.177.7 +and spm-calculator 1.1.0. That release's US certificate covers +`populace-us-2024-spm-20260915`. Its `ce_trend` county forecast for vintage +2020 has SHA-256 `335e6755dc8e0bd883e09b76c2bd53a5315683773e44d50085c7d6b8832b6291`. The configuration accepts exactly `forecast_content_sha256`, `scenario`, @@ -135,8 +135,8 @@ hashed `runtime_dependency` scoped to the US, adds it to US/models/dev extras, and preserves UK requirements. The version must come from the real release; local wheel metadata is not proof of registry publication. -Both `bundle.py check` and `bundle.py check --published-spm` pass on the -checked-in bundle. The published check verifies the measurement pin and +Both `bundle.py check` and `bundle.py check --published-spm` passed for wrapper +release 6.20.2. The published check verifies the measurement pin and calculator dependency metadata and rejects development fixtures. ## Historical pre-promotion checklist @@ -184,5 +184,5 @@ calculator dependency metadata and rejects development fixtures. No release, publication, deployment, full population run or data certification was performed by this wrapper tooling work. -Both vendored TRACE sidecars bind the checked-in manifest SHA-256 +Both vendored TRACE sidecars at wrapper release 6.20.2 bind manifest SHA-256 `07da3cc8567ce06d61b1dddbcb038e484865231827d6ec4bd0d40046aed96e3b`. diff --git a/src/policyengine/provenance/trace.py b/src/policyengine/provenance/trace.py index 46c385c98..c45d4b471 100644 --- a/src/policyengine/provenance/trace.py +++ b/src/policyengine/provenance/trace.py @@ -622,6 +622,11 @@ def _validate_supplied_bundle_tro( (dataset_artifact,) = ( artifact for artifact in artifacts if artifact["@id"].endswith("/dataset") ) + wheel_artifacts = [ + artifact + for artifact in artifacts + if artifact["@id"].endswith("/model_wheel") + ] performance = node["trov:hasPerformance"] extract_bundle_tro_reference(tro) except (AttributeError, KeyError, TypeError, ValueError) as error: @@ -648,15 +653,31 @@ def _validate_supplied_bundle_tro( "Supplied bundle TRO refers to a different certified data build" ) + # An omitted binding and "bundle_pin" both follow the manifest's Core pin. + core_binding = performance.get("pe:coreBinding") + core_bindings_match = core_binding == certification.core_binding or ( + certification.certified_for_core_version is None + and core_binding in (None, "bundle_pin") + and certification.core_binding in (None, "bundle_pin") + ) if ( performance.get("pe:certifiedForModelVersion") != certification.certified_for_model_version or performance.get("pe:certifiedForCoreVersion") != certification.certified_for_core_version - or performance.get("pe:coreBinding") != certification.core_binding + or not core_bindings_match ): raise ValueError("Supplied bundle TRO refers to a different certified runtime") + model_package = manifest.model_package + if model_package.sha256 is not None and ( + len(wheel_artifacts) != 1 + or wheel_artifacts[0].get("schema:name") + != f"{model_package.name}=={model_package.version} wheel" + or wheel_artifacts[0].get("trov:sha256") != model_package.sha256 + ): + raise ValueError("Supplied bundle TRO refers to a different model wheel") + def extract_bundle_tro_reference(tro: Mapping) -> dict[str, Any]: """Extract a compact reference to a bundle TRO for use as a simulation input. diff --git a/src/policyengine/tax_benefit_models/us/model.py b/src/policyengine/tax_benefit_models/us/model.py index 4ce9d99c1..2eda70989 100644 --- a/src/policyengine/tax_benefit_models/us/model.py +++ b/src/policyengine/tax_benefit_models/us/model.py @@ -49,6 +49,7 @@ ) from .legacy_spm.independence import INDEPENDENCE_ROLE from .legacy_spm.model_adapter import UNIVERSE_VARIABLE +from .legacy_spm.universe import person_link from .spm import ( SPMProvenance, SPMSelection, @@ -289,14 +290,13 @@ def _output_cache_identity( # Legacy SPM validates or derives its declarations before scoping. if legacy_profile is not None: tables = dataset.data.entity_data - legacy_columns = ( - { + if stored_legacy is None: + person = tables["person"] + legacy_columns = { "person": [ "person_id", - "person_spm_unit_id", - "spm_unit_id", - "person_household_id", - "household_id", + person_link(person, "spm_unit"), + person_link(person, "household"), "person_support_channel", "RELSHIPP", "is_household_head", @@ -305,9 +305,11 @@ def _output_cache_identity( ], "household": ["household_id", "TYPEHUGQ"], } - if stored_legacy is None - else {"person": [INDEPENDENCE_ROLE], "spm_unit": [UNIVERSE_VARIABLE]} - ) + else: + legacy_columns = { + "person": [INDEPENDENCE_ROLE], + "spm_unit": [UNIVERSE_VARIABLE], + } for entity, columns in legacy_columns.items(): frame = pd.DataFrame(tables[entity]) _hash_input_table( diff --git a/tests/test_us_legacy_inputs_integration.py b/tests/test_us_legacy_inputs_integration.py index 8be12ed9a..891b610f6 100644 --- a/tests/test_us_legacy_inputs_integration.py +++ b/tests/test_us_legacy_inputs_integration.py @@ -945,15 +945,47 @@ def test_the_run_record_binds_the_renames_applied(tmp_path): @pytest.mark.parametrize("column", ["ignored_annotation", "household_id"]) -def test_us_run_ignores_list_valued_unread_column(tmp_path, column): +def test_us_run_ignores_list_valued_unread_column(tmp_path, monkeypatch, column): + from policyengine.core.simulation import _cache + frames = _frames() # The fixture supplies person_household_id, which takes precedence over household_id. frames["person"][column] = [["adult"], [], ["child", "toddler"]] - annotated = _run(_in_memory_dataset(tmp_path, frames)) - plain = _run(_in_memory_dataset(tmp_path)) - for entity in plain.output_dataset.data.entity_data: - pd.testing.assert_frame_equal( - pd.DataFrame(annotated.output_dataset.data.entity_data[entity]), - pd.DataFrame(plain.output_dataset.data.entity_data[entity]), + def request(input_frames=None): + return pe.Simulation( + id="unused-input-column", + dataset=_in_memory_dataset(tmp_path, input_frames), + tax_benefit_model_version=pe.us.model, + extra_variables={ + "person": ["is_wic_eligible", "wic_if_takes_up", LIVE, "wic"], + }, ) + + _cache.clear() + try: + plain = request() + plain.ensure() + annotated = request(frames) + annotated.run() + + monkeypatch.setattr( + PolicyEngineUSLatest, + "run", + lambda *args: pytest.fail("Recalculated after adding an unread column"), + ) + memory = request(frames) + memory.ensure() + assert memory.output_dataset is plain.output_dataset + + _cache.clear() + disk = request(frames) + disk.ensure() + for result in (annotated, disk): + for entity, expected in plain.output_dataset.data.entity_data.items(): + pd.testing.assert_frame_equal( + pd.DataFrame(result.output_dataset.data.entity_data[entity]), + pd.DataFrame(expected), + ) + finally: + _cache.clear() diff --git a/tests/test_us_unmanaged_runtime.py b/tests/test_us_unmanaged_runtime.py index 0699e5549..1be932609 100644 --- a/tests/test_us_unmanaged_runtime.py +++ b/tests/test_us_unmanaged_runtime.py @@ -669,33 +669,127 @@ def certified_us_run(tmp_path_factory): return simulation -@pytest.mark.parametrize("mismatch", ["country", "bundle", "build", "runtime", None]) +@pytest.mark.parametrize( + "publisher_available", [False, True], ids=["offline", "publisher"] +) +@pytest.mark.parametrize( + "mismatch", + [ + "country", + "bundle", + "build", + "runtime", + "core-binding", + "core-version", + "wheel", + "wheel-name", + "wheel-sha", + None, + ], +) def test_supplied_run_record_tro_matches_certified_us_bundle( - certified_us_run, tmp_path, mismatch + certified_us_run, monkeypatch, tmp_path, mismatch, publisher_available ): import json from pathlib import Path + from policyengine.provenance import manifest + from policyengine.provenance.trace import compute_trace_composition_fingerprint + + def load_publisher_manifest(country): + assert country == "us" + if not publisher_available: + raise DataReleaseManifestUnavailableError("test offline manifest") + bundle = get_release_manifest(country) + certificate = bundle.certification + return manifest.DataReleaseManifest.model_validate( + { + "schema_version": 1, + "data_package": bundle.data_package, + "build": { + "build_id": certificate.data_build_id, + "built_with_model_package": { + "name": bundle.model_package.name, + "version": certificate.built_with_model_version, + "data_build_fingerprint": certificate.data_build_fingerprint, + }, + }, + "compatible_model_packages": [ + { + "name": bundle.model_package.name, + "specifier": f"=={certificate.certified_for_model_version}", + } + ], + } + ) + + monkeypatch.setattr(manifest, "get_data_release_manifest", load_publisher_manifest) + monkeypatch.setattr( + certified_us_run.tax_benefit_model_version, "data_certification", None + ) + country = "uk" if mismatch == "country" else "us" bundle_dir = Path(us_model.__file__).resolve().parents[2] / "data/bundle" bundle_tro = json.loads((bundle_dir / f"{country}.trace.tro.jsonld").read_text()) node = bundle_tro["@graph"][0] + composition = node["trov:hasComposition"] + artifacts = composition["trov:hasArtifact"] + performance = node["trov:hasPerformance"] if mismatch == "bundle": - artifacts = node["trov:hasComposition"]["trov:hasArtifact"] next(item for item in artifacts if item["@id"].endswith("/bundle_manifest"))[ "trov:sha256" ] = "0" * 64 if mismatch == "build": - node["trov:hasPerformance"]["pe:dataBuildId"] = "another-build" + performance["pe:dataBuildId"] = "another-build" if mismatch == "runtime": - node["trov:hasPerformance"]["pe:certifiedForModelVersion"] = "2.3.0" + performance["pe:certifiedForModelVersion"] = "2.3.0" + if mismatch == "core-binding": + performance["pe:coreBinding"] = "certified" + if mismatch == "core-version": + performance["pe:certifiedForCoreVersion"] = "3.34.9" + if mismatch in {"wheel", "wheel-name", "wheel-sha"}: + uk_tro = json.loads((bundle_dir / "uk.trace.tro.jsonld").read_text()) + uk_node = uk_tro["@graph"][0] + uk_artifacts = uk_node["trov:hasComposition"]["trov:hasArtifact"] + wheel = next(item for item in artifacts if item["@id"].endswith("/model_wheel")) + uk_wheel = next( + item for item in uk_artifacts if item["@id"].endswith("/model_wheel") + ) + if mismatch in {"wheel", "wheel-name"}: + wheel["schema:name"] = uk_wheel["schema:name"] + if mismatch in {"wheel", "wheel-sha"}: + wheel["trov:sha256"] = uk_wheel["trov:sha256"] + if mismatch == "wheel": + us_locations = node["trov:hasArrangement"][0]["trov:hasArtifactLocation"] + uk_locations = uk_node["trov:hasArrangement"][0]["trov:hasArtifactLocation"] + us_location = next( + item + for item in us_locations + if item["trov:hasArtifact"]["@id"] == wheel["@id"] + ) + uk_location = next( + item + for item in uk_locations + if item["trov:hasArtifact"]["@id"] == uk_wheel["@id"] + ) + us_location["trov:hasLocation"] = uk_location["trov:hasLocation"] + composition["trov:hasFingerprint"]["trov:sha256"] = ( + compute_trace_composition_fingerprint( + item["trov:sha256"] for item in artifacts + ) + ) output = tmp_path / "run-record" if mismatch is None: record = certified_us_run.write_run_record(output, bundle_tro=bundle_tro) assert json.loads(record.paths["bundle_tro"].read_text()) == bundle_tro else: - with pytest.raises(ValueError, match="Supplied bundle TRO"): + message = ( + "different model wheel" + if mismatch in {"wheel", "wheel-name", "wheel-sha"} + else "Supplied bundle TRO" + ) + with pytest.raises(ValueError, match=message): certified_us_run.write_run_record(output, bundle_tro=bundle_tro) assert not output.exists() @@ -1066,16 +1160,12 @@ def new_request(dataset): _cache.clear() -@pytest.mark.parametrize("change", ["policy", "dynamic", "scope", "columns"]) -def test_us_output_cache_misses_when_the_request_changes(monkeypatch, tmp_path, change): +@pytest.fixture +def two_household_us_frames(): import pandas as pd - from policyengine.core import Simulation - from policyengine.core.scoping_strategy import RowFilterStrategy - from policyengine.core.simulation import _cache - from tests.test_us_legacy_inputs_integration import _frames, _in_memory_dataset + from tests.test_us_legacy_inputs_integration import _frames - monkeypatch.setattr(us_model.us_latest, "entity_variables", {"tax_unit": ["eitc"]}) frames = _frames() for entity, frame in frames.items(): second = frame.copy() @@ -1083,10 +1173,26 @@ def test_us_output_cache_misses_when_the_request_changes(monkeypatch, tmp_path, if column.endswith("_id"): second[column] += 10 frames[entity] = pd.concat([frame, second], ignore_index=True) - frames["person"]["employment_income"] = [8_000, 0, 0, 8_000, 0, 0] frames["household"]["state_code"] = ["CA", "NY"] - frames["household"]["scope_state"] = ["CA", "NY"] frames["household"]["county_fips"] = ["06037", "36061"] + return frames + + +@pytest.mark.parametrize("change", ["policy", "dynamic", "scope", "columns"]) +def test_us_output_cache_misses_when_the_request_changes( + monkeypatch, tmp_path, two_household_us_frames, change +): + import pandas as pd + + from policyengine.core import Simulation + from policyengine.core.scoping_strategy import RowFilterStrategy + from policyengine.core.simulation import _cache + from tests.test_us_legacy_inputs_integration import _in_memory_dataset + + monkeypatch.setattr(us_model.us_latest, "entity_variables", {"tax_unit": ["eitc"]}) + frames = two_household_us_frames + frames["person"]["employment_income"] = [8_000, 0, 0, 8_000, 0, 0] + frames["household"]["scope_state"] = ["CA", "NY"] reform = {"gov.irs.credits.eitc.phase_in_rate[2].amount": 0.9} request = { "policy": {"policy": reform}, @@ -1167,6 +1273,67 @@ def signature(run): _cache.clear() +@pytest.mark.parametrize("cache", ["memory", "disk"]) +def test_us_output_cache_misses_when_scope_weights_change( + monkeypatch, tmp_path, two_household_us_frames, cache +): + from policyengine.core import Simulation + from policyengine.core.scoping_strategy import WeightReplacementStrategy + from policyengine.core.simulation import _cache + from tests.test_us_legacy_inputs_integration import _in_memory_dataset + + monkeypatch.setattr(us_model.us_latest, "entity_variables", {"person": ["age"]}) + monkeypatch.setenv("POLICYENGINE_UK_GEOGRAPHY_DATA_DIR", str(tmp_path)) + dataset = _in_memory_dataset(tmp_path, two_household_us_frames) + year_key = str(dataset.year) + weight_file = tmp_path / "weights.h5" + lookup_file = tmp_path / "lookup.csv" + lookup_file.write_text("code\nR001\n", encoding="utf-8") + with h5py.File(weight_file, "w") as file: + file.create_dataset(year_key, data=[[2.0, 3.0]]) + + strategy = WeightReplacementStrategy( + weight_matrix_bucket="test-bucket", + weight_matrix_key=weight_file.name, + lookup_csv_bucket="test-bucket", + lookup_csv_key=lookup_file.name, + region_code="R001", + download_missing_assets=False, + ) + + def request(): + return Simulation( + id="same-id-and-scope-assets", + dataset=dataset, + tax_benefit_model_version=us_model.us_latest, + scoping_strategy=strategy, + ) + + def weights(run): + return run.output_dataset.data.household["household_weight"].tolist() + + _cache.clear() + try: + initial = request() + initial.ensure() + assert weights(initial) == [2.0, 3.0] + + with h5py.File(weight_file, "r+") as file: + file[year_key][0] = [5.0, 7.0] + fresh = request() + fresh.run() + assert weights(fresh) == [5.0, 7.0] + + if cache == "disk": + _cache.clear() + changed = request() + assert changed.storage_id == initial.storage_id + changed.ensure() + assert weights(changed) == weights(fresh) + finally: + _cache.clear() + + def test_us_memory_cache_resolves_each_raw_legacy_file( tmp_path, legacy_files, monkeypatch ): @@ -1209,6 +1376,14 @@ def request(path): tax_benefit_model_version=us_model.us_latest, ) + def request_with_unused_aliases(): + simulation = request(registered) + person = simulation.dataset.data.person + for entity in ("household", "spm_unit"): + links = person[f"person_{entity}_id"] + person[f"{entity}_id"] = [[link] for link in links] + return simulation + _cache.clear() try: original = request(registered) @@ -1217,10 +1392,36 @@ def request(path): same_source.ensure() assert same_source.output_dataset is original.output_dataset + aliased = request_with_unused_aliases() + aliased.run() + with monkeypatch.context() as m: + m.setattr( + us_model.PolicyEngineUSLatest, + "run", + lambda *args: pytest.fail("Recalculated with unused ID aliases"), + ) + memory_hit = request_with_unused_aliases() + memory_hit.ensure() + assert memory_hit.output_dataset is original.output_dataset + + _cache.clear() + disk_hit = request_with_unused_aliases() + disk_hit.ensure() + + record_key = legacy_spm_tests.RECORD_KEY + registered_record = original.output_dataset.metadata[record_key] + for result in (aliased, disk_hit): + assert result.output_dataset.metadata[record_key] == registered_record + for entity, table in original.output_dataset.data.entity_data.items(): + pd.testing.assert_frame_equal( + pd.DataFrame(result.output_dataset.data.entity_data[entity]), + pd.DataFrame(table), + ) + assert legacy_spm_tests.runs.sha256_file(registered) == registered_hash + fresh = request(unregistered) fresh.run() - assert legacy_spm_tests.RECORD_KEY in original.output_dataset.metadata - assert legacy_spm_tests.RECORD_KEY not in fresh.output_dataset.metadata + assert record_key not in fresh.output_dataset.metadata for entity, table in original.dataset.data.entity_data.items(): pd.testing.assert_frame_equal( pd.DataFrame(table), @@ -1229,7 +1430,7 @@ def request(path): changed = request(unregistered) changed.ensure() - assert legacy_spm_tests.RECORD_KEY not in changed.output_dataset.metadata + assert record_key not in changed.output_dataset.metadata pd.testing.assert_frame_equal( legacy_spm_tests._frame(changed, "spm_unit"), legacy_spm_tests._frame(fresh, "spm_unit"), From 6f22b8b32f50a14400f2b1ef6f72df8b3035db00 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 2 Dec 2026 16:42:01 -0500 Subject: [PATCH 19/20] Check a supplied TRO's composition fingerprint against its artifacts The run record cites the supplied bundle TRO's composition fingerprint, but the validator only read it. It now recomputes the fingerprint from the artifact hashes and refuses a TRO whose claimed value differs. The shipped US and UK TROs match their artifacts, and a new mismatch case covers a replaced fingerprint on both certification paths. Co-Authored-By: Claude Opus 5.5 --- src/policyengine/provenance/trace.py | 9 ++++++++- tests/test_us_unmanaged_runtime.py | 3 +++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/policyengine/provenance/trace.py b/src/policyengine/provenance/trace.py index c45d4b471..311a34b8a 100644 --- a/src/policyengine/provenance/trace.py +++ b/src/policyengine/provenance/trace.py @@ -628,7 +628,8 @@ def _validate_supplied_bundle_tro( if artifact["@id"].endswith("/model_wheel") ] performance = node["trov:hasPerformance"] - extract_bundle_tro_reference(tro) + claimed_fingerprint = extract_bundle_tro_reference(tro)["fingerprint"] + artifact_hashes = [artifact["trov:sha256"] for artifact in artifacts] except (AttributeError, KeyError, TypeError, ValueError) as error: raise ValueError("Supplied bundle TRO has invalid bundle provenance") from error @@ -678,6 +679,12 @@ def _validate_supplied_bundle_tro( ): raise ValueError("Supplied bundle TRO refers to a different model wheel") + # The run record cites this fingerprint, so it must match the artifacts. + if compute_trace_composition_fingerprint(artifact_hashes) != claimed_fingerprint: + raise ValueError( + "Supplied bundle TRO has a composition fingerprint its artifacts don't match" + ) + def extract_bundle_tro_reference(tro: Mapping) -> dict[str, Any]: """Extract a compact reference to a bundle TRO for use as a simulation input. diff --git a/tests/test_us_unmanaged_runtime.py b/tests/test_us_unmanaged_runtime.py index 1be932609..183701c1e 100644 --- a/tests/test_us_unmanaged_runtime.py +++ b/tests/test_us_unmanaged_runtime.py @@ -684,6 +684,7 @@ def certified_us_run(tmp_path_factory): "wheel", "wheel-name", "wheel-sha", + "fingerprint", None, ], ) @@ -747,6 +748,8 @@ def load_publisher_manifest(country): performance["pe:coreBinding"] = "certified" if mismatch == "core-version": performance["pe:certifiedForCoreVersion"] = "3.34.9" + if mismatch == "fingerprint": + composition["trov:hasFingerprint"]["trov:sha256"] = "0" * 64 if mismatch in {"wheel", "wheel-name", "wheel-sha"}: uk_tro = json.loads((bundle_dir / "uk.trace.tro.jsonld").read_text()) uk_node = uk_tro["@graph"][0] From 760b1860fec32a06217e65314fa398fa54bf95f8 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 2 Dec 2026 22:29:10 -0500 Subject: [PATCH 20/20] Refuse a supplied TRO whose artifact digests aren't SHA-256 hex A numeric digest raised a raw TypeError while the fingerprint sorted them, and a non-hex string passed once the fingerprint was recomputed. The validator now requires each digest to be 64 lowercase hex digits and refuses others as invalid provenance. Two new cases cover a non-hex string with a matching fingerprint and an integer digest. Co-Authored-By: Claude Opus 5.5 --- src/policyengine/provenance/trace.py | 6 ++++++ tests/test_us_unmanaged_runtime.py | 15 +++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/src/policyengine/provenance/trace.py b/src/policyengine/provenance/trace.py index 311a34b8a..87bba34b1 100644 --- a/src/policyengine/provenance/trace.py +++ b/src/policyengine/provenance/trace.py @@ -21,6 +21,7 @@ import hashlib import json import os +import re from collections.abc import Iterable, Mapping from typing import Any, Optional @@ -630,6 +631,11 @@ def _validate_supplied_bundle_tro( performance = node["trov:hasPerformance"] claimed_fingerprint = extract_bundle_tro_reference(tro)["fingerprint"] artifact_hashes = [artifact["trov:sha256"] for artifact in artifacts] + if not all( + isinstance(digest, str) and re.fullmatch(r"[0-9a-f]{64}", digest) + for digest in artifact_hashes + ): + raise ValueError("artifact digest is not a lowercase SHA-256") except (AttributeError, KeyError, TypeError, ValueError) as error: raise ValueError("Supplied bundle TRO has invalid bundle provenance") from error diff --git a/tests/test_us_unmanaged_runtime.py b/tests/test_us_unmanaged_runtime.py index 183701c1e..69f4baf97 100644 --- a/tests/test_us_unmanaged_runtime.py +++ b/tests/test_us_unmanaged_runtime.py @@ -685,6 +685,8 @@ def certified_us_run(tmp_path_factory): "wheel-name", "wheel-sha", "fingerprint", + "digest-format", + "digest-type", None, ], ) @@ -750,6 +752,19 @@ def load_publisher_manifest(country): performance["pe:certifiedForCoreVersion"] = "3.34.9" if mismatch == "fingerprint": composition["trov:hasFingerprint"]["trov:sha256"] = "0" * 64 + if mismatch in {"digest-format", "digest-type"}: + release_manifest = next( + item for item in artifacts if item["@id"].endswith("/data_release_manifest") + ) + if mismatch == "digest-format": + release_manifest["trov:sha256"] = "Z" * 64 + composition["trov:hasFingerprint"]["trov:sha256"] = ( + compute_trace_composition_fingerprint( + item["trov:sha256"] for item in artifacts + ) + ) + else: + release_manifest["trov:sha256"] = 0 if mismatch in {"wheel", "wheel-name", "wheel-sha"}: uk_tro = json.loads((bundle_dir / "uk.trace.tro.jsonld").read_text()) uk_node = uk_tro["@graph"][0]