diff --git a/changelog.d/788.added.md b/changelog.d/788.added.md new file mode 100644 index 000000000..44e3a4de0 --- /dev/null +++ b/changelog.d/788.added.md @@ -0,0 +1 @@ +`python scripts/bundle.py check-compatibility` checks one UK or US Microcosm build against one model version, from a checkout. It runs `certify-data`'s metadata checks, downloads the model's PyPI wheel and each microdata H5 file and checks their SHA-256s, refuses a file that stores a column the build's model defines and the new model does not, and runs a deterministic 2,000-household sample of each file through .py under exactly that wheel and core, requiring finite, positive weighted totals for the headline variables. A pass writes a record naming the build by the SHA-256 of its `release_manifest.json` and the model by its wheel's SHA-256. `certify-data --compatibility-record` (and `--regional-compatibility-record`) certifies on it with the new basis `compatibility_checked_exact_pair` and stores the record in `src/policyengine/data/compatibility/.json`; a model accepts such a certificate at load only when that file holds a matching record for the running model, wheel and core. diff --git a/docs/engineering/skills/data-certification.md b/docs/engineering/skills/data-certification.md index 545b1aad4..9bec3d476 100644 --- a/docs/engineering/skills/data-certification.md +++ b/docs/engineering/skills/data-certification.md @@ -266,9 +266,52 @@ Microcosm national release with one of: `src/policyengine/data/schemas/execution_receipt.v1.schema.json`. Either way, certification checks that the regional release serves the pinned -model by its own build or compatibility claims (a `--qualified-pair-id` names -the primary release only), checks its core claims as for the primary release -(below), and HEAD-checks every artifact it carries. +model by its own build, its compatibility claims or a +`--regional-compatibility-record` (a `--qualified-pair-id` names the primary +release only), checks its core claims as for the primary release +(below; a `--regional-compatibility-record` names the core it ran instead), +and HEAD-checks every artifact it carries. + +### Certifying a build for a newer model with a compatibility check + +A build can be certified for a model version it was not built with, and that +no publisher claim covers, by checking it against that version: + +```bash +python scripts/bundle.py check-compatibility --country uk \ + --manifest-uri "hf://dataset/@/releases///release_manifest.json" \ + --model-version \ + --work-dir --output +``` + +Run it from a checkout of this repository, with a Hugging Face token that can +read the build in `HUGGING_FACE_TOKEN` or `HF_TOKEN`. One run checks one +build, UK or US. It refuses a build whose model is the version given (certify +that on `built_with_model_package`), downloads the model's PyPI wheel and each +microdata H5 file and checks their SHA-256s, refuses a file that stores a +column the build's model defines and the given version does not, and runs a +2,000-household sample of each file through .py under exactly that wheel and +core (the bundle's pin, or `--core-version`). Every headline variable must +have a finite, positive weighted total. A pass writes a record to `--output` +that names the build by the SHA-256 of its `release_manifest.json` and the +model by its wheel's SHA-256. + +Certify with the record (`--regional-compatibility-record` for the regional +release): + +```bash +python scripts/bundle.py certify-data --country uk --data-producer populace \ + --manifest-uri "" --model-version \ + --compatibility-record +``` + +The basis is `compatibility_checked_exact_pair`. The certificate names the +core, and certification stores the record in +`src/policyengine/data/compatibility/.json`; commit that file with +the bundle. Certification refuses a record for other manifest bytes, another +build, model, wheel or core, and a record given with `--qualified-pair-id`. At +load, a model accepts the certificate only when that file holds a matching +record for the running model and core. ### The core @@ -285,9 +328,11 @@ country. A certificate says how it covers it: the release's claim; the warning, the certificate and its TRO say so. - **`core_binding: certified` (`--core-version`).** The certificate names the core (`certified_for_core_version`). Certification refuses a core that a - release neither was built with nor claims, and the strict check refuses a + release neither was built with nor claims, unless a qualified exact pair or + a compatibility check's record ran it, and the strict check refuses a pin that differs from the named core, so moving the core needs a - re-certification first. A qualified exact pair always binds its core. + re-certification first. A qualified exact pair and a compatibility check's + record always bind their core. Use the default unless a release must not run on any other core. diff --git a/docs/release-bundles.md b/docs/release-bundles.md index b4f8199ec..2b063fd7f 100644 --- a/docs/release-bundles.md +++ b/docs/release-bundles.md @@ -640,11 +640,26 @@ Things that should usually not affect the fingerprint: (`compatibility_basis: legacy_compatible_model_package` — the publisher's claim, recorded with a warning and made good by the test suite passing on the pinned pair) - -If neither is true, certification fails hard and a new data build or a -published compatibility claim is required. A `data_build_fingerprint` -basis (same fingerprint as the build-time model) is a planned third -basis; it requires fingerprint metadata from the installed model package. +3. a compatibility check of exactly this build, model wheel and core passed + (`compatibility_basis: compatibility_checked_exact_pair`). `python + scripts/bundle.py check-compatibility` runs it from a checkout, for one + UK or US Microcosm build and one model version: `certify-data`'s metadata + checks, the input columns of every microdata H5 file (a column the build's + model defines and the new model does not refuses), and a 2,000-household + sample run through .py under the new model's PyPI wheel. A pass writes a + record naming the build by the SHA-256 of its `release_manifest.json` and + the model by its wheel's SHA-256. `certify-data --compatibility-record` + (or `--regional-compatibility-record` for the regional release) certifies + on it and stores it in `src/policyengine/data/compatibility/.json`; + a model loads the certificate only for that build, wheel and core. The + record replaces a publisher claim, but never applies to the build's own + model or with a qualified pair. + +If none is true, certification fails hard and a new data build, a published +compatibility claim or a passed compatibility check is required. A +`data_build_fingerprint` basis (same fingerprint as the build-time model) +is planned as a further basis; it requires fingerprint metadata from the +installed model package. ## Artifact states diff --git a/scripts/bundle.py b/scripts/bundle.py index b05ffa589..5c2bd5516 100644 --- a/scripts/bundle.py +++ b/scripts/bundle.py @@ -7,6 +7,9 @@ Examples: python scripts/bundle.py update-packages --us 1.730.0 --uk 2.91.0 + python scripts/bundle.py check-compatibility --country uk \ + --manifest-uri hf://... --model-version 2.180.0 \ + --work-dir /tmp/check --output record.json python scripts/bundle.py certify-data --country uk --manifest-uri hf://... python scripts/bundle.py generate python scripts/bundle.py generate --include-tros @@ -66,9 +69,59 @@ def _certify_data(args: argparse.Namespace) -> int: argv.extend(["--core-version", args.core_version]) if args.qualified_pair_id: argv.extend(["--qualified-pair-id", args.qualified_pair_id]) + if args.compatibility_record: + argv.extend(["--compatibility-record", args.compatibility_record]) + if args.regional_compatibility_record: + argv.extend( + ["--regional-compatibility-record", args.regional_compatibility_record] + ) return certify_data_release_main(argv) +def _check_compatibility(args: argparse.Namespace) -> int: + """Check one build against one model version; write the record of a pass.""" + # Building the installed country models at import would check the + # bundle's certificate against the installed model version, which the + # check does not use and the bundle need not cover. + os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1") + from policyengine.provenance import compatibility_check + + if not (REPO_ROOT / "pyproject.toml").is_file(): + raise ValueError( + "check-compatibility runs from a checkout of policyengine.py: the " + "sample run installs this checkout." + ) + token = os.environ.get("HUGGING_FACE_TOKEN") or os.environ.get("HF_TOKEN") + try: + record = compatibility_check.check_build_compatibility( + country=args.country, + manifest_uri=args.manifest_uri, + model_version=args.model_version, + core_version=args.core_version, + token=token, + work_dir=Path(args.work_dir), + policyengine_source=REPO_ROOT, + bundle_path=REPO_ROOT + / "src" + / "policyengine" + / "data" + / "bundle" + / "manifest.json", + ) + except compatibility_check.CompatibilityCheckError as exc: + print(f"The build does not pass: {exc}", file=sys.stderr) + return 1 + output = Path(args.output) + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(record.model_dump_json(indent=2) + "\n") + print( + f"{args.country.upper()} build {record.build} passes with " + f"{record.model_package.name} {record.model_package.version} and " + f"policyengine-core {record.core_version}; record: {output}" + ) + return 0 + + def _update_packages(args: argparse.Namespace) -> int: from prepare_package_bundle_update import main as prepare_package_bundle_update_main @@ -281,8 +334,57 @@ def _parser() -> argparse.ArgumentParser: "--qualified-pair-id", help="Admit the exact pair on automated qualification (needs --core-version).", ) + certify.add_argument( + "--compatibility-record", + help=( + "Record from check-compatibility: certify exactly its model, core " + "and build on the basis compatibility_checked_exact_pair." + ), + ) + certify.add_argument( + "--regional-compatibility-record", + help=( + "Record from check-compatibility for the regional release: route " + "regions to it on that record." + ), + ) certify.set_defaults(func=_certify_data) + compatibility = subparsers.add_parser( + "check-compatibility", + help=( + "Check one Microcosm build against one model version and write the " + "record certify-data --compatibility-record reads." + ), + ) + compatibility.add_argument("--country", required=True, choices=["us", "uk"]) + compatibility.add_argument( + "--manifest-uri", + required=True, + help="hf://dataset/@/", + ) + compatibility.add_argument( + "--model-version", + required=True, + help="The model package version to check, installed from its PyPI wheel.", + ) + compatibility.add_argument( + "--core-version", + help="policyengine-core version to run (default: the bundle's pin).", + ) + compatibility.add_argument( + "--work-dir", + required=True, + help=( + "Folder for the downloaded wheel and H5 files and the sample run; " + "files already there with the expected SHA-256 are reused." + ), + ) + compatibility.add_argument( + "--output", required=True, help="Where to write the record of a pass." + ) + compatibility.set_defaults(func=_check_compatibility) + packages = subparsers.add_parser( "update-packages", help="Update package pins in the bundle manifest.", diff --git a/scripts/certify_data_release.py b/scripts/certify_data_release.py index 341297457..71ba8a045 100644 --- a/scripts/certify_data_release.py +++ b/scripts/certify_data_release.py @@ -39,6 +39,15 @@ REGIONAL_RELEASE_KINDS, certify_data_release, ) +from policyengine.provenance.compatibility_record import ( # noqa: E402 + CompatibilityRecord, +) + + +def _read_record(path: Path | None) -> CompatibilityRecord | None: + if path is None: + return None + return CompatibilityRecord.model_validate_json(path.read_bytes()) def main(argv=None) -> int: @@ -136,6 +145,23 @@ def main(argv=None) -> int: "the regional bytes, its build model and the exact target model." ), ) + parser.add_argument( + "--compatibility-record", + type=Path, + help=( + "Record from bundle.py check-compatibility: certify exactly its " + "model, core and build on the basis compatibility_checked_exact_pair. " + "The core defaults to the record's." + ), + ) + parser.add_argument( + "--regional-compatibility-record", + type=Path, + help=( + "Record from bundle.py check-compatibility for the regional release " + "named by --regional-manifest-uri." + ), + ) parser.add_argument("--no-changelog", action="store_true") parser.add_argument( "--skip-artifact-check", @@ -175,6 +201,8 @@ def main(argv=None) -> int: if args.regional_input_surface_evidence is not None else None ), + compatibility_record=_read_record(args.compatibility_record), + regional_compatibility_record=_read_record(args.regional_compatibility_record), ) print(result.summary()) diff --git a/scripts/generate_trace_tros.py b/scripts/generate_trace_tros.py index 656d1868b..fe3ec79cc 100644 --- a/scripts/generate_trace_tros.py +++ b/scripts/generate_trace_tros.py @@ -26,6 +26,11 @@ core_claim_warning, validate_release_manifest, ) +from policyengine.provenance.compatibility_record import ( + BASIS_COMPATIBILITY_CHECKED, + bundled_compatibility_records, + matching_compatibility_record, +) from policyengine.provenance.manifest import ( CountryReleaseManifest, DataReleaseManifest, @@ -78,6 +83,25 @@ def _validate_reviewed_inputs( != country.model_package.version ): raise ValueError(f"{prefix} requires certification for the pinned model") + compatibility_record = None + if country.certification.compatibility_basis == BASIS_COMPATIBILITY_CHECKED: + # The certificate stands only with the record of the check that ran + # exactly these manifest bytes, model wheel and core. + compatibility_record = matching_compatibility_record( + bundled_compatibility_records(country.country_id), + country=country.country_id, + manifest_sha256=data.source_sha256, + build=country.certification.data_build_id, + model_package=country.model_package.name, + model_version=country.model_package.version, + wheel_sha256=country.model_package.sha256, + core_version=country.certification.certified_for_core_version, + ) + if compatibility_record is None: + raise ValueError( + f"{prefix} requires the stored compatibility record of the " + "certified build, model wheel and core" + ) validate_release_manifest( data, country.model_package.name, @@ -90,6 +114,7 @@ def _validate_reviewed_inputs( if country.certification.compatibility_basis == "qualified_exact_pair" else None ), + compatibility_record=compatibility_record, ) certified = country.certified_data_artifact artifact = data.artifacts.get(certified.dataset) if certified else None @@ -152,6 +177,14 @@ def _validate_runtime_model(bundle: dict, country: CountryReleaseManifest) -> No raise ValueError( f"{prefix}: a qualified exact pair must name its pair and core" ) + if ( + certification is not None + and certification.compatibility_basis == BASIS_COMPATIBILITY_CHECKED + and not certification.certified_for_core_version + ): + raise ValueError( + f"{prefix}: a compatibility check's certificate must name its core" + ) if ( certification is not None and certification.core_binding is not None diff --git a/src/policyengine/provenance/certification.py b/src/policyengine/provenance/certification.py index 72a278903..6c81b2512 100644 --- a/src/policyengine/provenance/certification.py +++ b/src/policyengine/provenance/certification.py @@ -62,6 +62,13 @@ LOCAL_AUTHORITY_ASSET_SPEC, ) from policyengine.provenance.bundle_validation import shadowed_dataset_overlays +from policyengine.provenance.compatibility_record import ( + BASIS_COMPATIBILITY_CHECKED, + CompatibilityRecord, + compatibility_record_problems, + compatibility_records_path, + write_compatibility_records, +) from policyengine.provenance.manifest import ( HF_REQUEST_TIMEOUT_SECONDS, RELEASES_RECORD_NAME, @@ -406,6 +413,7 @@ def validate_release_manifest( *, core_version: Optional[str] = None, qualified_pair_id: Optional[str] = None, + compatibility_record: Optional[CompatibilityRecord] = None, ) -> tuple[str, list[str]]: """Hard checks raise; returns ``(compatibility_basis, warnings)``. @@ -423,6 +431,13 @@ def validate_release_manifest( qualified pair. A core admitted only by the qualification makes the basis ``qualified_exact_pair`` whatever the model's own claim, so the certificate names the pair and its ledger evidence is enforced. + + ``compatibility_record`` (``bundle.py check-compatibility``) admits + exactly the model, core and build the check ran, on the basis + ``compatibility_checked_exact_pair``. It replaces a publisher claim and + covers a core outside the release's core claims, but never applies to + the build's own model, which is certified on its build. It cannot be + combined with a qualified pair. """ warnings: list[str] = [] if "national" not in manifest.default_datasets: @@ -440,6 +455,21 @@ def validate_release_manifest( if not artifact.sha256: warnings.append(f"artifact {name!r} has no sha256") + if compatibility_record is not None: + if qualified_pair_id is not None: + raise CertificationError( + "A compatibility record and a qualified pair are two different " + "bases; pass one of them." + ) + return _compatibility_record_basis( + manifest, + model_package, + model_version, + core_version, + compatibility_record, + warnings, + ) + basis, basis_warning, refusal = _release_model_basis( manifest, model_package, model_version ) @@ -525,18 +555,73 @@ def _release_model_basis( ) +def _compatibility_record_basis( + manifest: DataReleaseManifest, + model_package: str, + model_version: str, + core_version: Optional[str], + record: CompatibilityRecord, + warnings: list[str], +) -> tuple[str, list[str]]: + """Certify exactly the model, core and build a compatibility check ran.""" + + if core_version is None: + raise CertificationError( + "A compatibility record names its core version; pass core_version." + ) + problems = compatibility_record_problems( + record, + build=release_build_id(manifest.build), + model_package=model_package, + model_version=model_version, + core_version=core_version, + ) + if problems: + raise CertificationError( + "The compatibility record is for another build, model or core: " + f"{'; '.join(problems)}." + ) + basis, _, _ = _release_model_basis(manifest, model_package, model_version) + if basis == BASIS_BUILT_WITH: + raise CertificationError( + f"The build was built with {model_package} {model_version}; certify " + "it without a compatibility record." + ) + warnings.append( + f"certifying exactly {model_package}=={model_version} with " + f"policyengine-core=={core_version} on the compatibility check of build " + f"{record.build} at {record.checked_at}; the certificate stands only " + f"with that record stored in data/compatibility/{record.country}.json" + ) + return BASIS_COMPATIBILITY_CHECKED, warnings + + def model_compatibility_basis( manifest: DataReleaseManifest, model_package: str, model_version: str, + compatibility_record: Optional[CompatibilityRecord] = None, + *, + core_version: Optional[str] = None, ) -> tuple[str, list[str]]: """Return the basis on which a release serves a model version by itself. The release must be built with ``model_version`` or claim compatibility with it; automated qualification of a pair does not apply. Certification - uses this for a regional release, which no qualification names. Returns + uses this for a regional release, which no qualification names. A + ``compatibility_record`` of the release admits exactly the checked model + and core (``core_version``, by default the record's). Returns ``(compatibility_basis, warnings)``. """ + if compatibility_record is not None: + return _compatibility_record_basis( + manifest, + model_package, + model_version, + core_version or compatibility_record.core_version, + compatibility_record, + [], + ) basis, warning, refusal = _release_model_basis( manifest, model_package, model_version ) @@ -1490,6 +1575,7 @@ def build_bundle_data_release_payload( regional_release_kind: Optional[RegionalReleaseKind] = None, regional_certification: Optional[dict] = None, regional_manifest_sha256: Optional[str] = None, + regional_compatibility_basis: Optional[str] = None, ) -> dict: """Map the country certification payload into bundle ``data_releases``.""" payload = copy.deepcopy(country_payload) @@ -1513,10 +1599,40 @@ def build_bundle_data_release_payload( payload["regional_release_kind"] = regional_release_kind if regional_certification is not None: payload["regional_certification"] = regional_certification + if regional_compatibility_basis is not None: + payload["regional_compatibility_basis"] = regional_compatibility_basis payload["default_dataset_uri"] = certified_artifact.get("uri") return payload +def _require_record_binds( + record: CompatibilityRecord, label: str, **expected: Optional[str] +) -> None: + """Refuse a compatibility record of another build, model, core or wheel.""" + + problems = compatibility_record_problems(record, **expected) + if problems: + raise CertificationError( + f"The {label}'s compatibility record does not match it: " + f"{'; '.join(problems)}." + ) + + +def _as_compatibility_record( + value: Optional[CompatibilityRecord | dict], label: str +) -> Optional[CompatibilityRecord]: + """Read a record given as a model or as its JSON object.""" + + if value is None or isinstance(value, CompatibilityRecord): + return value + try: + return CompatibilityRecord.model_validate(value) + except ValidationError as exc: + raise CertificationError( + f"The {label} is not a compatibility record: {exc}" + ) from exc + + class DataProducerCertificationStrategy: data_producer: str @@ -1538,6 +1654,8 @@ def certify( bundle_core_version: Optional[str] = None, regional_model_mismatch_reason: Optional[str] = None, regional_input_surface_evidence: Optional[RegionalInputSurfaceEvidence] = None, + compatibility_record: Optional[CompatibilityRecord] = None, + regional_compatibility_record: Optional[CompatibilityRecord] = None, ) -> tuple[dict, str, list[str]]: raise NotImplementedError @@ -1563,6 +1681,8 @@ def certify( bundle_core_version: Optional[str] = None, regional_model_mismatch_reason: Optional[str] = None, regional_input_surface_evidence: Optional[RegionalInputSurfaceEvidence] = None, + compatibility_record: Optional[CompatibilityRecord] = None, + regional_compatibility_record: Optional[CompatibilityRecord] = None, ) -> tuple[dict, str, list[str]]: raise CertificationError( "Legacy data-producer certification updates are not implemented in " @@ -1591,11 +1711,21 @@ def certify( bundle_core_version: Optional[str] = None, regional_model_mismatch_reason: Optional[str] = None, regional_input_surface_evidence: Optional[RegionalInputSurfaceEvidence] = None, + compatibility_record: Optional[CompatibilityRecord] = None, + regional_compatibility_record: Optional[CompatibilityRecord] = None, ) -> tuple[dict, str, list[str]]: manifest, manifest_sha256, uri_parts = fetch_release_manifest( manifest_uri, token=token ) require_tagged_layout(manifest, uri_parts, token) + if compatibility_record is not None: + _require_record_binds( + compatibility_record, + "data release", + country=country, + manifest_sha256=manifest_sha256, + build=release_build_id(manifest.build), + ) primary_manifest = manifest regional_manifest = None regional_manifest_sha256 = None @@ -1604,12 +1734,24 @@ def certify( regional_artifacts: dict[str, DataReleaseArtifact] = {} regional_warnings: list[str] = [] regional_certification: Optional[dict] = None + regional_compatibility_basis: Optional[str] = None mismatch_warning: Optional[str] = None if regional_model_mismatch_reason is not None and regional_manifest_uri is None: raise CertificationError( "--accept-regional-model-mismatch applies to a regional release; " "pass --regional-manifest-uri." ) + if regional_compatibility_record is not None: + if regional_manifest_uri is None: + raise CertificationError( + "A regional compatibility record applies to a regional " + "release; pass --regional-manifest-uri." + ) + if regional_model_mismatch_reason is not None: + raise CertificationError( + "A regional compatibility record and an accepted regional " + "model mismatch are two different bases; pass one of them." + ) if regional_manifest_uri is not None: regional_manifest, regional_manifest_sha256, regional_uri_parts = ( fetch_release_manifest(regional_manifest_uri, token=token) @@ -1617,13 +1759,32 @@ def certify( require_tagged_layout(regional_manifest, regional_uri_parts, token) _regional_build_model_version(regional_manifest, model_package) # The regional release runs on the same model and core, so it must - # cover the pinned versions by its own build or claims. A qualified + # cover the pinned versions by its own build or claims, or by a + # compatibility check of exactly this model and core. A qualified # pair names the primary release only, so it does not extend here. try: - _, regional_warnings = model_compatibility_basis( - regional_manifest, model_package, model_version + if regional_compatibility_record is not None: + _require_record_binds( + regional_compatibility_record, + "regional release", + country=country, + manifest_sha256=regional_manifest_sha256, + build=release_build_id(regional_manifest.build), + ) + regional_compatibility_basis, regional_warnings = ( + model_compatibility_basis( + regional_manifest, + model_package, + model_version, + regional_compatibility_record, + core_version=core_version, + ) ) except CertificationError as exc: + if regional_compatibility_record is not None: + raise CertificationError( + f"Regional release {regional_manifest_uri}: {exc}" + ) from exc if regional_model_mismatch_reason is None: raise CertificationError( f"Regional release {regional_manifest_uri}: {exc}" @@ -1647,7 +1808,8 @@ def certify( "certificate does not record a mismatch that is not there." ) try: - if core_version is not None: + # A compatibility record ran exactly this core. + if core_version is not None and regional_compatibility_record is None: _check_core_compatibility( regional_manifest, core_version, None, regional_warnings ) @@ -1681,6 +1843,7 @@ def certify( model_version, core_version=core_version, qualified_pair_id=qualified_pair_id, + compatibility_record=compatibility_record, ) warnings = warnings + regional_warnings if core_version is None and bundle_core_version is not None: @@ -1718,6 +1881,19 @@ def certify( ) model_wheel = fetch_pypi_wheel_metadata(model_package, model_version) + # A record holds only for the wheel the check installed. + for label, record in ( + ("data release", compatibility_record), + ("regional release", regional_compatibility_record), + ): + if record is not None: + _require_record_binds( + record, + label, + model_package=model_package, + model_version=model_version, + wheel_sha256=(model_wheel or {}).get("sha256"), + ) country_payload = build_country_manifest_payload( country=country, manifest=manifest, @@ -1755,6 +1931,11 @@ def certify( regional_release_kind=recorded_release_kind, regional_certification=regional_certification, regional_manifest_sha256=regional_manifest_sha256, + regional_compatibility_basis=( + regional_compatibility_basis + if regional_compatibility_basis == BASIS_COMPATIBILITY_CHECKED + else None + ), ), manifest_sha256, warnings, @@ -1807,6 +1988,9 @@ def certify_data_release( qualified_pair_id: Optional[str] = None, regional_model_mismatch_reason: Optional[str] = None, regional_input_surface_evidence: Optional[RegionalInputSurfaceEvidence] = None, + compatibility_record: Optional[CompatibilityRecord | dict] = None, + regional_compatibility_record: Optional[CompatibilityRecord | dict] = None, + records_path: Optional[Path] = None, ) -> CertificationResult: """Certify a data release into the bundle manifest. @@ -1831,8 +2015,36 @@ def certify_data_release( never-modelled column, defaulted input and limitation is recorded in ``regional_certification`` alongside the reason and both model versions. The core must still be covered; area receipts remain uncertified. + + ``compatibility_record`` and ``regional_compatibility_record`` + (``bundle.py check-compatibility``) certify the data release or the + regional release on the basis ``compatibility_checked_exact_pair``: each + must name the fetched manifest's SHA-256 and build, the model version, the + SHA-256 of the wheel PyPI lists for it, and the core. ``core_version`` + defaults to the records' core. Certification replaces the country's + records file (``records_path``, by default + ``data/compatibility/.json`` beside the bundle's ``bundle`` + folder) with the records it used, and removes it when it used none. """ certified_country = _certified_country(country) + compatibility_record = _as_compatibility_record( + compatibility_record, "data release's record" + ) + regional_compatibility_record = _as_compatibility_record( + regional_compatibility_record, "regional release's record" + ) + records = [ + record + for record in (compatibility_record, regional_compatibility_record) + if record is not None + ] + record_cores = sorted({record.core_version for record in records}) + if len(record_cores) > 1: + raise CertificationError( + f"The compatibility records name different cores: {record_cores}." + ) + if core_version is None and record_cores: + core_version = record_cores[0] if ( regional_input_surface_evidence is not None and regional_model_mismatch_reason is None @@ -1886,6 +2098,8 @@ def certify_data_release( ).get("version"), regional_model_mismatch_reason=regional_model_mismatch_reason, regional_input_surface_evidence=regional_input_surface_evidence, + compatibility_record=compatibility_record, + regional_compatibility_record=regional_compatibility_record, ) previous_release = (bundle.get("data_releases") or {}).get(country) or {} bundle.setdefault("data_releases", {})[country] = data_release @@ -1924,6 +2138,11 @@ def certify_data_release( if core_version is not None and "policyengine-core" in bundle.get("packages", {}): bundle["packages"]["policyengine-core"]["version"] = core_version bundle_path.write_text(json.dumps(bundle, indent=2, sort_keys=True) + "\n") + write_compatibility_records( + records_path or compatibility_records_path(bundle_path.parent.parent, country), + country, + records, + ) return CertificationResult( country=country, diff --git a/src/policyengine/provenance/compatibility_check.py b/src/policyengine/provenance/compatibility_check.py new file mode 100644 index 000000000..7fdc7511f --- /dev/null +++ b/src/policyengine/provenance/compatibility_check.py @@ -0,0 +1,612 @@ +"""Check one Microcosm data build against one model version. + +``scripts/bundle.py check-compatibility`` runs this for one build, UK or US. +The check passes only when all of these hold: + +1. The build's manifest passes the metadata checks ``certify-data`` makes + before it downloads anything: the tagged-layout check, a recorded build + model and core, and a SHA-256 for every microdata H5 file. +2. Each H5 file, downloaded and verified against the manifest's SHA-256, + stores no column its build model defines and the new model does not. + The build model is read in a throwaway ``uv run`` environment as the + regional input audit reads it (``regional_input_surface``); the new model + in the probe's environment. +3. A 2,000-household sample of each file, drawn as + ``compatibility_probe.sample_household_ids`` describes, loads and runs + through .py under exactly the new model wheel (verified against PyPI's + SHA-256) and core, and every headline variable has a finite, positive + weighted total. + +A pass returns a ``CompatibilityRecord``, which ``certify-data +--compatibility-record`` turns into a certificate on the basis +``compatibility_checked_exact_pair``. +""" + +from __future__ import annotations + +import json +import math +import os +import re +import subprocess +from collections.abc import Callable, Iterable +from datetime import UTC, datetime +from pathlib import Path +from typing import Any, NamedTuple, Optional + +import requests + +from policyengine.provenance.certification import ( + COUNTRY_MODEL_PACKAGES, + CertificationError, + default_bundle_source_path, + fetch_release_manifest, + require_tagged_layout, +) +from policyengine.provenance.compatibility_probe import ( + SAMPLE_HOUSEHOLDS, + SAMPLE_METHOD, + SAMPLE_SALT, +) +from policyengine.provenance.compatibility_record import ( + SHA256_PATTERN, + CompatibilityArtifactCheck, + CompatibilityModelPackage, + CompatibilityRecord, + CompatibilitySample, +) +from policyengine.provenance.manifest import ( + HF_REQUEST_TIMEOUT_SECONDS, + DataReleaseArtifact, + RegionalInputArtifactEvidence, + fetch_pypi_wheel_metadata, + https_dataset_uri, + release_build_id, +) +from policyengine.provenance.regional_input_surface import ( + BUILD_MODEL_INDEX, + BUILD_MODEL_KEPT_UV_SETTINGS, + BUILD_MODEL_PYTHON, + RegionalInputSurfaceError, + _build_model_surface, + _sha256_file, + _stored_columns, + compare_input_surface, + regional_build_cutoff, +) + +#: The variables whose sample totals must be finite and positive. +HEADLINE_VARIABLES: dict[str, tuple[str, ...]] = { + "uk": ( + "household_net_income", + "income_tax", + "universal_credit", + "child_benefit", + "state_pension", + "pension_credit", + "housing_benefit", + ), + "us": ( + "household_net_income", + "income_tax", + "snap", + "ssi", + "social_security", + ), +} +PROBE_MODULE = "policyengine.provenance.compatibility_probe" +#: The checkout this module was imported from, which the probe installs. +REPO_ROOT = Path(__file__).resolve().parents[3] +DOWNLOAD_CHUNK_BYTES = 1024 * 1024 + +Download = Callable[[str, Path, dict[str, str]], None] + + +class CompatibilityCheckError(ValueError): + """The build does not pass the check against the model version.""" + + +class PinnedArtifact(NamedTuple): + """A microdata file of the build with the revision and SHA-256 it is + pinned to.""" + + artifact: DataReleaseArtifact + revision: str + sha256: str + + +def total_problems(totals: dict[str, Any], variables: Iterable[str]) -> list[str]: + """Describe each headline total that is missing, not finite or not positive.""" + problems = [] + for variable in variables: + if variable not in totals: + problems.append(f"{variable}: no total") + continue + value = totals[variable] + if ( + isinstance(value, bool) + or not isinstance(value, (int, float)) + or not math.isfinite(value) + ): + problems.append(f"{variable}: {value!r} is not finite") + elif value <= 0: + problems.append(f"{variable}: {value} is not positive") + return problems + + +def probe_command( + *, + policyengine_source: Path, + wheel_path: Path, + core_version: str, + extra_requirements: Iterable[str], + request_path: Path, +) -> list[str]: + """Run the probe with exactly this .py checkout, model wheel and core. + + As for the build model, ``--isolated --no-project --no-config`` gives a + fresh environment that ignores the caller's project and uv settings, and + PyPI is the only index. The checkout is installed editable, so the probe + imports the checkout's current source; uv caches a wheel it builds from + a plain directory and could reuse it after the source changes. + """ + extras = [ + argument + for requirement in extra_requirements + for argument in ("--with", requirement) + ] + return [ + "uv", + "run", + "--isolated", + "--no-project", + "--no-config", + "--default-index", + BUILD_MODEL_INDEX, + "--python", + BUILD_MODEL_PYTHON, + "--with-editable", + str(policyengine_source), + "--with", + str(wheel_path), + "--with", + f"policyengine-core=={core_version}", + *extras, + "python", + "-I", + "-m", + PROBE_MODULE, + str(request_path), + ] + + +def probe_environment(environ: Optional[dict[str, str]] = None) -> dict[str, str]: + """The probe's environment: no tokens, no .py settings, no uv overrides. + + The probe reads only local files, so Hugging Face tokens are removed. + ``POLICYENGINE_*`` settings are removed so the caller's configuration + cannot steer the run, and ``POLICYENGINE_SKIP_COUNTRY_IMPORTS`` is set + so importing .py builds no model before the certificate lookup is + replaced. + """ + source = os.environ if environ is None else environ + environment = { + key: value + for key, value in source.items() + if key != "VIRTUAL_ENV" + and not key.startswith(("HF_", "HUGGING", "POLICYENGINE_")) + and (not key.startswith("UV_") or key in BUILD_MODEL_KEPT_UV_SETTINGS) + } + environment["POLICYENGINE_SKIP_COUNTRY_IMPORTS"] = "1" + return environment + + +def download_file(url: str, destination: Path, headers: dict[str, str]) -> None: + """Stream ``url`` to ``destination``, replacing it only when complete.""" + destination.parent.mkdir(parents=True, exist_ok=True) + partial = destination.with_name(f"{destination.name}.partial") + try: + with requests.get( + url, headers=headers, stream=True, timeout=HF_REQUEST_TIMEOUT_SECONDS + ) as response: + if response.status_code != 200: + raise CompatibilityCheckError( + f"Could not download {url} ({response.status_code})." + ) + with partial.open("wb") as file: + for chunk in response.iter_content(chunk_size=DOWNLOAD_CHUNK_BYTES): + file.write(chunk) + except requests.RequestException as exc: + raise CompatibilityCheckError(f"Could not download {url}.") from exc + partial.replace(destination) + + +def _download_verified( + download: Download, + url: str, + destination: Path, + headers: dict[str, str], + expected_sha256: str, + label: str, +) -> None: + """Download unless a verified copy is already there; refuse other bytes.""" + if destination.is_file() and _sha256_file(destination) == expected_sha256: + return + download(url, destination, headers) + actual = _sha256_file(destination) + if actual != expected_sha256: + raise CompatibilityCheckError( + f"{label}: the downloaded bytes have SHA-256 {actual}, not " + f"{expected_sha256}." + ) + + +def _microdata_artifacts( + artifacts: dict[str, DataReleaseArtifact], +) -> dict[str, PinnedArtifact]: + """The build's microdata H5 files; each must name a revision and SHA-256.""" + microdata = { + name: artifact + for name, artifact in sorted(artifacts.items()) + if artifact.kind == "microdata" and Path(artifact.path).suffix.lower() == ".h5" + } + if not microdata: + raise CompatibilityCheckError("The build lists no microdata H5 file.") + unpinned = sorted( + name + for name, artifact in microdata.items() + if not artifact.sha256 or not artifact.revision + ) + if unpinned: + raise CompatibilityCheckError( + f"Microdata files {unpinned} have no sha256 or revision in the " + "manifest, so their bytes cannot be verified." + ) + return { + name: PinnedArtifact(artifact, artifact.revision or "", artifact.sha256 or "") + for name, artifact in microdata.items() + } + + +def _run_probe( + run: Callable[..., Any], command: list[str], label: str, result_path: Path +) -> dict[str, Any]: + try: + run( + command, + capture_output=True, + text=True, + check=True, + env=probe_environment(), + ) + except subprocess.CalledProcessError as exc: + detail = " | ".join((exc.stderr or "").strip().splitlines()[-5:]) + raise CompatibilityCheckError( + f"The sample run under {label} failed: {detail or exc}" + ) from exc + except OSError as exc: + raise CompatibilityCheckError( + f"Cannot run uv for the sample run under {label}." + ) from exc + try: + result = json.loads(result_path.read_text()) + except (OSError, ValueError) as exc: + raise CompatibilityCheckError( + f"The sample run under {label} wrote no result." + ) from exc + if not isinstance(result, dict): + raise CompatibilityCheckError(f"The sample run under {label} wrote no result.") + return result + + +def check_build_compatibility( + *, + country: str, + manifest_uri: str, + model_version: str, + work_dir: Path, + core_version: Optional[str] = None, + token: Optional[str] = None, + policyengine_source: Optional[Path] = None, + bundle_path: Optional[Path] = None, + run: Optional[Callable[..., Any]] = None, + download: Optional[Download] = None, + now: Optional[datetime] = None, +) -> CompatibilityRecord: + """Check one build against one model version; return the record of a pass. + + ``core_version`` defaults to the bundle's policyengine-core pin. Files go + under ``work_dir``; a file already there with the manifest's SHA-256 is + not downloaded again. ``run`` (``subprocess.run``) runs uv and + ``download`` (``download_file``) fetches the wheel and H5 files. + Raises ``CompatibilityCheckError`` with the reason when the build does + not pass. + """ + if country not in COUNTRY_MODEL_PACKAGES: + raise CompatibilityCheckError(f"Unknown country {country!r}.") + model_package = COUNTRY_MODEL_PACKAGES[country] # type: ignore[index] + run = run if run is not None else subprocess.run + download = download if download is not None else download_file + work_dir = Path(work_dir) + work_dir.mkdir(parents=True, exist_ok=True) + policyengine_source = Path(policyengine_source or REPO_ROOT) + bundle = json.loads(Path(bundle_path or default_bundle_source_path()).read_text()) + packages = bundle.get("packages") or {} + + # 1. Metadata, before any download. + try: + manifest, manifest_sha256, parts = fetch_release_manifest( + manifest_uri, token=token + ) + require_tagged_layout(manifest, parts, token) + except CertificationError as exc: + raise CompatibilityCheckError(str(exc)) from exc + build = manifest.build + build_model = build.built_with_model_package if build is not None else None + build_core = build.built_with_core_package if build is not None else None + if build is None or build_model is None or build_core is None: + raise CompatibilityCheckError( + "The build's manifest records no build model and core " + "(built_with_model_package and built_with_core_package), so there " + "is nothing to compare the new model with." + ) + if build_model.name != model_package: + raise CompatibilityCheckError( + f"The build was built with {build_model.name}, not {model_package}." + ) + if build_model.version == model_version: + raise CompatibilityCheckError( + f"The build was built with {model_package} {model_version}; it is " + "certified on that basis and needs no compatibility check." + ) + build_id = release_build_id(build) + if not build_id: + raise CompatibilityCheckError("The build's manifest names no build.") + microdata = _microdata_artifacts(manifest.artifacts) + core_version = core_version or (packages.get("policyengine-core") or {}).get( + "version" + ) + if not core_version: + raise CompatibilityCheckError( + "No policyengine-core version: pass --core-version or pin the core " + "in the bundle." + ) + extra_requirements = [] + spm_version = (packages.get("spm-calculator") or {}).get("version") + if country == "us" and spm_version: + extra_requirements.append(f"spm-calculator=={spm_version}") + label = f"{model_package} {model_version} with policyengine-core {core_version}" + + # 2. The exact model wheel, as PyPI lists it. + wheel = fetch_pypi_wheel_metadata(model_package, model_version) + wheel_sha256, wheel_url = wheel.get("sha256"), wheel.get("url") + if not wheel_sha256 or not wheel_url or not wheel_url.endswith(".whl"): + raise CompatibilityCheckError( + f"PyPI lists no wheel for {model_package} {model_version}." + ) + wheel_path = work_dir / "wheels" / wheel_url.rsplit("/", 1)[1] + _download_verified( + download, + wheel_url, + wheel_path, + {}, + wheel_sha256, + f"The {model_package} {model_version} wheel", + ) + + # 3. Each H5 file, verified against the manifest. + headers = {"Authorization": f"Bearer {token}"} if token else {} + files: dict[str, Path] = {} + for name, (artifact, revision, sha256) in microdata.items(): + url = https_dataset_uri( + artifact.repo_id, + artifact.path, + revision, + repo_type=artifact.repo_type or parts["repo_type"], + ) + destination = work_dir / "data" / name / Path(artifact.path).name + _download_verified(download, url, destination, headers, sha256, name) + files[name] = destination + + # 4. The columns each file stores, and the build model's variables. + evidence: dict[str, RegionalInputArtifactEvidence] = {} + years: dict[str, int] = {} + for name, path in files.items(): + artifact, revision, sha256 = microdata[name] + try: + periods = _stored_columns(path, model_package) + except RegionalInputSurfaceError as exc: + raise CompatibilityCheckError(f"{name}: {exc}") from exc + evidence[name] = RegionalInputArtifactEvidence( + repo_id=artifact.repo_id, + repo_type=artifact.repo_type or parts["repo_type"], + path=artifact.path, + revision=revision, + sha256=sha256, + columns=sorted( + {column for columns in periods.values() for column in columns} + ), + columns_by_period=periods, + ) + years[name] = int(min(periods)) + # A build that records no ``built_at`` is read without ``--exclude-newer``, + # so the build model's dependencies resolve to their newest compatible + # releases rather than those available when the build was made. + try: + build_variables, build_inputs = _build_model_surface( + build_model.version, + build_core.version, + run=run, + exclude_newer=regional_build_cutoff(manifest) if build.built_at else None, + model_package=model_package, + ) + except RegionalInputSurfaceError as exc: + raise CompatibilityCheckError(str(exc)) from exc + + # 5. The sample run under the new model. + request_path = work_dir / "probe_request.json" + result_path = work_dir / "probe_result.json" + result_path.unlink(missing_ok=True) + headline = list(HEADLINE_VARIABLES[country]) + request_path.write_text( + json.dumps( + { + "country": country, + "model_package": model_package, + "model_version": model_version, + "core_version": core_version, + "headline_variables": headline, + "sample_size": SAMPLE_HOUSEHOLDS, + "artifacts": { + name: {"path": str(path), "year": years[name]} + for name, path in files.items() + }, + "data_folder": str(work_dir / "datasets"), + "result_path": str(result_path), + }, + indent=2, + ) + ) + result = _run_probe( + run, + probe_command( + policyengine_source=policyengine_source, + wheel_path=wheel_path, + core_version=core_version, + extra_requirements=extra_requirements, + request_path=request_path, + ), + label, + result_path, + ) + resolved = (result.get("model_version"), result.get("core_version")) + if resolved != (model_version, core_version): + raise CompatibilityCheckError( + f"The sample run used {model_package} {resolved[0]} with " + f"policyengine-core {resolved[1]}, not {label}." + ) + + # 6. Columns the new model would not read. + variables = result.get("variables") + inputs = result.get("inputs") + aliases = result.get("input_aliases") or {} + if ( + not isinstance(variables, list) + or not isinstance(inputs, list) + or not isinstance(aliases, dict) + ): + raise CompatibilityCheckError( + f"The sample run under {label} reported no variable lists." + ) + try: + comparison = compare_input_surface( + evidence, + variables, + inputs, + aliases, + build_model_variables=build_variables, + build_model_inputs=build_inputs, + model_package=model_package, + ) + except RegionalInputSurfaceError as exc: + raise CompatibilityCheckError(str(exc)) from exc + if comparison["dropped_columns"]: + raise CompatibilityCheckError( + f"The build stores columns {model_package} {build_model.version} " + f"defines and {model_version} does not, so {model_version} would " + f"not read them: {comparison['dropped_columns']}." + ) + + # 7. The sample and its totals. + policyengine_version = result.get("policyengine_version") + if not isinstance(policyengine_version, str) or not policyengine_version: + raise CompatibilityCheckError( + f"The sample run under {label} reported no policyengine_version." + ) + reported = result.get("artifacts") + if not isinstance(reported, dict) or set(reported) != set(files): + raise CompatibilityCheckError( + f"The sample run under {label} reported files " + f"{sorted(reported or {})}, not {sorted(files)}." + ) + problems: list[str] = [] + checks: dict[str, CompatibilityArtifactCheck] = {} + for name, path in files.items(): + entry = reported[name] + if not isinstance(entry, dict): + problems.append(f"{name}: the run reported {entry!r}, not a mapping") + continue + households = entry.get("households") + sample_households = entry.get("sample_households") + expected_sample = ( + min(SAMPLE_HOUSEHOLDS, households) + if isinstance(households, int) and households > 0 + else None + ) + if ( + not isinstance(households, int) + or expected_sample is None + or sample_households != expected_sample + ): + problems.append( + f"{name}: the sample holds {sample_households} of {households} " + f"households, not {expected_sample}" + ) + continue + totals = entry.get("totals") + if not isinstance(totals, dict): + totals = {} + sample_digest = entry.get("sample_household_ids_sha256") + if not isinstance(sample_digest, str) or not re.fullmatch( + SHA256_PATTERN, sample_digest + ): + problems.append( + f"{name}: sample_household_ids_sha256 is {sample_digest!r}, " + "not a SHA-256" + ) + continue + artifact_problems = total_problems(totals, headline) + if artifact_problems: + problems.extend(f"{name}: {problem}" for problem in artifact_problems) + continue + artifact, revision, sha256 = microdata[name] + checks[name] = CompatibilityArtifactCheck( + path=artifact.path, + revision=revision, + sha256=sha256, + year=years[name], + households=households, + sample_households=expected_sample, + sample_household_ids_sha256=sample_digest, + totals={variable: float(totals[variable]) for variable in headline}, + ) + if problems: + raise CompatibilityCheckError( + f"The sample run under {label} did not pass: {'; '.join(problems)}." + ) + + return CompatibilityRecord( + country=country, # type: ignore[arg-type] + manifest_uri=manifest_uri, + manifest_sha256=manifest_sha256, + release=manifest.release, + build=build_id, + built_with_model_version=build_model.version, + built_with_core_version=build_core.version, + model_package=CompatibilityModelPackage( + name=model_package, + version=model_version, + wheel_sha256=wheel_sha256, + wheel_url=wheel_url, + ), + core_version=core_version, + policyengine_version=policyengine_version, + sample=CompatibilitySample( + method=SAMPLE_METHOD, salt=SAMPLE_SALT, size=SAMPLE_HOUSEHOLDS + ), + headline_variables=headline, + artifacts=checks, + never_modelled_columns=comparison["never_modelled_columns"], + defaulted_inputs=comparison["defaulted_inputs"], + checked_at=(now or datetime.now(UTC)).strftime("%Y-%m-%dT%H:%M:%SZ"), + ) diff --git a/src/policyengine/provenance/compatibility_probe.py b/src/policyengine/provenance/compatibility_probe.py new file mode 100644 index 000000000..5b93380f5 --- /dev/null +++ b/src/policyengine/provenance/compatibility_probe.py @@ -0,0 +1,248 @@ +"""Run a compatibility check's sample in a throwaway environment. + +``compatibility_check`` starts this module with ``uv run`` in an environment +holding exactly the model wheel, the core and this checkout of .py. It +reads one request JSON (``python -m policyengine.provenance.compatibility_probe +request.json``) and writes the result to the request's ``result_path``: + +- the installed model's variables, inputs and input aliases, read as the + regional input audit reads them; +- for each H5 file, its household count, the sampled households' digest and + the weighted totals of the headline variables over the sample. + +The sample is loaded and simulated through .py, as a user's run would be. +The model-version constructor asks for the bundle's data certificate, which +names another model while the check runs; inside this process only that +lookup is replaced (``replace_certificate_lookup``). + +Importing this module loads no country model, so the parent process uses its +sampling functions too. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import numbers +import sys +from collections.abc import Callable, Iterable +from importlib import metadata +from pathlib import Path +from typing import Any, Final, Optional, Union + +SAMPLE_HOUSEHOLDS = 2000 +SAMPLE_METHOD: Final = "sha256_rank_v1" +SAMPLE_SALT = "policyengine-compatibility-sample-v1" +#: The basis of the placeholder certificate the probe's model is built with. +CHECK_IN_PROGRESS_BASIS = "compatibility_check_in_progress" + + +class CompatibilityProbeError(ValueError): + """The probe cannot report a complete result for its request.""" + + +def installed_version(package: str) -> str: + return metadata.version(package) + + +def canonical_household_id(value: Any) -> str: + """Write a household ID as the decimal integer it holds.""" + if isinstance(value, bool): + raise ValueError(f"Household ID {value!r} is not a whole number.") + if isinstance(value, numbers.Integral): + return str(int(value)) + if isinstance(value, numbers.Real): + as_float = float(value) + if math.isfinite(as_float) and as_float.is_integer(): + return str(int(as_float)) + raise ValueError(f"Household ID {value!r} is not a whole number.") + + +def _sample_rank(canonical_id: str) -> str: + return hashlib.sha256(f"{SAMPLE_SALT}:{canonical_id}".encode()).hexdigest() + + +def sample_household_ids( + household_ids: Iterable[Any], size: int = SAMPLE_HOUSEHOLDS +) -> list[int]: + """Draw the check's sample: the ``size`` households ranked lowest. + + Each ID is written as a decimal integer and ranked by the SHA-256 hex + digest of ``"policyengine-compatibility-sample-v1:"``. The draw + depends only on the IDs, not their order, and keeps every household when + there are ``size`` or fewer. Returns the IDs as sorted integers. + """ + canonical = [canonical_household_id(value) for value in household_ids] + if len(set(canonical)) != len(canonical): + raise ValueError("Household IDs repeat; the sample needs unique IDs.") + ranked = sorted( + canonical, key=lambda canonical_id: (_sample_rank(canonical_id), canonical_id) + ) + return sorted(int(canonical_id) for canonical_id in ranked[:size]) + + +def household_ids_sha256(household_ids: Iterable[Any]) -> str: + """SHA-256 of the IDs as sorted decimal integers, one per line.""" + ordered = sorted(int(canonical_household_id(value)) for value in household_ids) + return hashlib.sha256( + "\n".join(str(value) for value in ordered).encode() + ).hexdigest() + + +def replace_certificate_lookup() -> None: + """Build this process's model versions without the bundle certificate. + + ``MicrosimulationModelVersion.__init__`` asks + ``certify_data_release_compatibility`` whether the bundle's data is + certified for the installed model. While a check runs it is not; the + check itself is what may certify it. Only that lookup is replaced, and + only in this process. + """ + from policyengine.provenance.manifest import DataCertification + from policyengine.tax_benefit_models.common import model_version + + def lookup( + country_id: str, + runtime_model_version: str, + runtime_data_build_fingerprint: Optional[str] = None, + runtime_core_version: Optional[str] = None, + ) -> DataCertification: + return DataCertification( + compatibility_basis=CHECK_IN_PROGRESS_BASIS, + certified_for_model_version=runtime_model_version, + ) + + model_version.certify_data_release_compatibility = lookup + + +def weighted_totals( + output_dataset: Any, variable_entities: dict[str, str] +) -> dict[str, float]: + """Sum each variable over its entity's rows, weighted by ``_weight``.""" + import pandas as pd + + totals = {} + for variable, entity in variable_entities.items(): + frame = pd.DataFrame(getattr(output_dataset.data, entity)) + values = frame[variable].astype(float) + weights = frame[f"{entity}_weight"].astype(float) + totals[variable] = float((values * weights).sum()) + return totals + + +def _load_country(country: str) -> tuple[Callable[..., Any], Any]: + import importlib + + replace_certificate_lookup() + module = importlib.import_module(f"policyengine.tax_benefit_models.{country}") + return module.create_datasets, module.model + + +def _model_surface(model_version: str, model_package: str): + from policyengine.provenance.regional_input_surface import _model_surface + + return _model_surface(model_version, model_package=model_package) + + +def _simulate( + dataset: Any, + model: Any, + household_ids: list[int], + variables_by_entity: dict[str, list[str]], +) -> Any: + from policyengine.core import Simulation + from policyengine.core.scoping_strategy import RowFilterStrategy + + filter_values: list[Union[str, int, float]] = list(household_ids) + simulation = Simulation( + dataset=dataset, + tax_benefit_model_version=model, + scoping_strategy=RowFilterStrategy( + variable_name="household_id", variable_value=filter_values + ), + extra_variables=variables_by_entity, + ) + simulation.run() + return simulation.output_dataset + + +def run_probe( + request: dict[str, Any], + *, + load_country: Optional[Callable[[str], tuple[Callable[..., Any], Any]]] = None, + model_surface: Optional[Callable[[str, str], tuple[list, list, dict]]] = None, + simulate: Optional[Callable[..., Any]] = None, +) -> dict[str, Any]: + """Load and simulate each file's sample under the installed model.""" + load_country = load_country or _load_country + model_surface = model_surface or _model_surface + simulate = simulate or _simulate + model_package = request["model_package"] + for package, requested in ( + (model_package, request["model_version"]), + ("policyengine-core", request["core_version"]), + ): + installed = installed_version(package) + if installed != requested: + raise CompatibilityProbeError( + f"The probe environment holds {package} {installed}, not {requested}." + ) + variables, inputs, aliases = model_surface(request["model_version"], model_package) + create_datasets, model = load_country(request["country"]) + headline = list(request["headline_variables"]) + variable_entities = { + variable: model.get_variable(variable).entity for variable in headline + } + variables_by_entity: dict[str, list[str]] = {} + for variable, entity in variable_entities.items(): + variables_by_entity.setdefault(entity, []).append(variable) + artifacts = {} + for name, artifact in request["artifacts"].items(): + created = create_datasets( + datasets=[artifact["path"]], + years=[int(artifact["year"])], + data_folder=str(Path(request["data_folder"]) / name), + allow_unmanaged=True, + ) + if len(created) != 1: + raise CompatibilityProbeError( + f"{name}: .py created {len(created)} datasets, not one." + ) + (dataset,) = created.values() + household_ids = dataset.data.household["household_id"].tolist() + sample = sample_household_ids(household_ids, request["sample_size"]) + output = simulate(dataset, model, sample, variables_by_entity) + artifacts[name] = { + "households": len(household_ids), + "sample_households": len(sample), + "sample_household_ids_sha256": household_ids_sha256(sample), + "totals": weighted_totals(output, variable_entities), + } + return { + "model_version": installed_version(model_package), + "core_version": installed_version("policyengine-core"), + "policyengine_version": installed_version("policyengine"), + "variables": variables, + "inputs": inputs, + "input_aliases": aliases, + "artifacts": artifacts, + } + + +def main(argv: Optional[list[str]] = None) -> int: + arguments = sys.argv[1:] if argv is None else argv + if len(arguments) != 1: + print( + "usage: python -m policyengine.provenance.compatibility_probe REQUEST", + file=sys.stderr, + ) + return 2 + request = json.loads(Path(arguments[0]).read_text()) + result = run_probe(request) + Path(request["result_path"]).write_text(json.dumps(result)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/policyengine/provenance/compatibility_record.py b/src/policyengine/provenance/compatibility_record.py new file mode 100644 index 000000000..7bfa72994 --- /dev/null +++ b/src/policyengine/provenance/compatibility_record.py @@ -0,0 +1,215 @@ +"""Records of a compatibility check of one data build against one model version. + +``scripts/bundle.py check-compatibility`` writes a record when one build +passes: its H5 files store no column its build model defined that the new +model does not, and a 2,000-household sample runs under the new model with +positive totals for the headline variables. ``certify-data`` certifies that +exact build, model wheel and core on the basis +``compatibility_checked_exact_pair`` and stores the record in +``data/compatibility/.json``; a model loads such a certificate only +when that file holds a matching record. + +A record names the build by the SHA-256 of its raw ``release_manifest.json`` +and the model by the SHA-256 of its PyPI wheel. This module imports nothing +from the rest of ``policyengine.provenance``, so certification and the +runtime check can both import it. +""" + +from __future__ import annotations + +import json +from collections.abc import Iterable +from importlib.resources import files +from pathlib import Path +from typing import Callable, Final, Literal, Optional + +from pydantic import BaseModel, Field + +BASIS_COMPATIBILITY_CHECKED: Final = "compatibility_checked_exact_pair" +COMPATIBILITY_RECORDS_SCHEMA_VERSION: Final = 1 +SHA256_PATTERN = r"^[0-9a-f]{64}$" + + +class CompatibilityModelPackage(BaseModel): + """The exact model wheel the check installed.""" + + model_config = {"extra": "forbid"} + + name: str = Field(min_length=1) + version: str = Field(min_length=1) + wheel_sha256: str = Field(pattern=SHA256_PATTERN) + wheel_url: str = Field(min_length=1) + + +class CompatibilitySample(BaseModel): + """How the check drew its households. + + ``sha256_rank_v1``: each household ID is written as a decimal integer, + ranked by the SHA-256 hex digest of ``f"{salt}:{id}"``, and the ``size`` + lowest-ranked households are kept (all of them when a file has fewer). + """ + + model_config = {"extra": "forbid"} + + method: Literal["sha256_rank_v1"] + salt: str = Field(min_length=1) + size: int = Field(gt=0) + + +class CompatibilityArtifactCheck(BaseModel): + """One H5 file of the build, as the check read and ran it.""" + + model_config = {"extra": "forbid"} + + path: str = Field(min_length=1) + revision: str = Field(min_length=1) + sha256: str = Field(pattern=SHA256_PATTERN) + year: int + households: int = Field(gt=0) + sample_households: int = Field(gt=0) + sample_household_ids_sha256: str = Field(pattern=SHA256_PATTERN) + """SHA-256 of the sampled household IDs, sorted, one decimal per line.""" + totals: dict[str, float] = Field(min_length=1) + """Weighted totals of the headline variables over the sample, using the + file's own weights (not scaled up to the whole file).""" + + +class CompatibilityRecord(BaseModel): + """A passed check of one build against one model wheel and core.""" + + model_config = {"extra": "forbid"} + + schema_version: Literal[1] = 1 + compatibility_basis: Literal["compatibility_checked_exact_pair"] = ( + BASIS_COMPATIBILITY_CHECKED + ) + country: Literal["uk", "us"] + manifest_uri: str = Field(min_length=1) + manifest_sha256: str = Field(pattern=SHA256_PATTERN) + """SHA-256 of the raw ``release_manifest.json`` bytes.""" + release: Optional[str] = None + build: str = Field(min_length=1) + built_with_model_version: str = Field(min_length=1) + built_with_core_version: str = Field(min_length=1) + model_package: CompatibilityModelPackage + core_version: str = Field(min_length=1) + policyengine_version: str = Field(min_length=1) + """The .py version that ran the sample.""" + sample: CompatibilitySample + headline_variables: list[str] = Field(min_length=1) + artifacts: dict[str, CompatibilityArtifactCheck] = Field(min_length=1) + never_modelled_columns: list[str] + """Stored columns neither model defines; no model reads them.""" + defaulted_inputs: list[str] + """Inputs of the new model the files do not store and the build model + did not have; runs on the build use their defaults.""" + checked_at: str = Field(min_length=1) + + +class CompatibilityRecords(BaseModel): + """The records one country's certificates rest on.""" + + model_config = {"extra": "forbid"} + + schema_version: Literal[1] = COMPATIBILITY_RECORDS_SCHEMA_VERSION + country: Literal["uk", "us"] + records: list[CompatibilityRecord] = Field(default_factory=list) + + +#: The value of each field a record can be matched on. +RECORD_BINDINGS: dict[str, Callable[[CompatibilityRecord], str]] = { + "country": lambda record: record.country, + "manifest_sha256": lambda record: record.manifest_sha256, + "build": lambda record: record.build, + "model_package": lambda record: record.model_package.name, + "model_version": lambda record: record.model_package.version, + "wheel_sha256": lambda record: record.model_package.wheel_sha256, + "core_version": lambda record: record.core_version, +} + + +def compatibility_records_path(data_dir: Path, country: str) -> Path: + """Return the records file for ``country`` under a package data folder.""" + return Path(data_dir) / "compatibility" / f"{country}.json" + + +def read_compatibility_records(path: Path, country: str) -> list[CompatibilityRecord]: + """Read a country's records file; a missing file holds no records.""" + path = Path(path) + if not path.exists(): + return [] + stored = CompatibilityRecords.model_validate_json(path.read_bytes()) + if stored.country != country: + raise ValueError(f"{path} holds {stored.country} records, not {country}.") + for record in stored.records: + if record.country != country: + raise ValueError( + f"{path} holds a {record.country} record among {country} records." + ) + return list(stored.records) + + +def write_compatibility_records( + path: Path, country: str, records: Iterable[CompatibilityRecord] +) -> None: + """Replace a country's records file; with no records, remove it.""" + path = Path(path) + records = list(records) + if not records: + path.unlink(missing_ok=True) + return + stored = CompatibilityRecords.model_validate( + {"country": country, "records": records} + ) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + json.dumps(stored.model_dump(mode="json"), indent=2, sort_keys=True) + "\n" + ) + + +def bundled_compatibility_records(country: str) -> list[CompatibilityRecord]: + """Read the records installed with this package for ``country``.""" + resource = files("policyengine").joinpath( + "data", "compatibility", f"{country}.json" + ) + if not resource.is_file(): + return [] + stored = CompatibilityRecords.model_validate_json(resource.read_bytes()) + if stored.country != country or any( + record.country != country for record in stored.records + ): + raise ValueError( + f"The installed compatibility records for {country} name another country." + ) + return list(stored.records) + + +def compatibility_record_problems( + record: CompatibilityRecord, **expected: Optional[str] +) -> list[str]: + """Describe each named field on which ``record`` differs from ``expected``. + + Fields are those of ``RECORD_BINDINGS``. An expected value of ``None`` + is a problem too: there is nothing to compare the record with. + """ + problems = [] + for field, value in expected.items(): + try: + recorded = RECORD_BINDINGS[field](record) + except KeyError as exc: + raise TypeError(f"Records are not matched on {field!r}.") from exc + if value is None: + problems.append(f"{field}: nothing to compare the record's {recorded} with") + elif recorded != value: + problems.append(f"{field}: the record names {recorded}, not {value}") + return problems + + +def matching_compatibility_record( + records: Iterable[CompatibilityRecord], **expected: Optional[str] +) -> Optional[CompatibilityRecord]: + """Return the first record that matches every expected field, if any.""" + for record in records: + if not compatibility_record_problems(record, **expected): + return record + return None diff --git a/src/policyengine/provenance/manifest.py b/src/policyengine/provenance/manifest.py index 9b3aa3827..b26263f0e 100644 --- a/src/policyengine/provenance/manifest.py +++ b/src/policyengine/provenance/manifest.py @@ -22,6 +22,12 @@ shadowed_dataset_overlays, shadowing_overlays_message, ) +from policyengine.provenance.compatibility_record import ( + BASIS_COMPATIBILITY_CHECKED, + bundled_compatibility_records, + compatibility_record_problems, + matching_compatibility_record, +) HF_REQUEST_TIMEOUT_SECONDS = 30 PYPI_REQUEST_TIMEOUT_SECONDS = 30 @@ -338,8 +344,19 @@ class DataCertification(BaseModel): { "legacy_compatible_model_package", "qualified_exact_pair", + BASIS_COMPATIBILITY_CHECKED, "legacy_compatible_model_package_local_manifest", "qualified_exact_pair_local_manifest", + f"{BASIS_COMPATIBILITY_CHECKED}_local_manifest", + } +) +#: Bases that hold for one model, one core and one data build only. +EXACT_PAIR_COMPATIBILITY = frozenset( + { + "qualified_exact_pair", + "qualified_exact_pair_local_manifest", + BASIS_COMPATIBILITY_CHECKED, + f"{BASIS_COMPATIBILITY_CHECKED}_local_manifest", } ) @@ -455,6 +472,10 @@ class CountryReleaseManifest(BaseModel): model mismatch rather than its own build or claims.""" regional_source_manifest_sha256: Optional[str] = None """SHA-256 of the original regional release manifest bytes.""" + regional_compatibility_basis: Optional[str] = None + """``compatibility_checked_exact_pair`` when the regional release serves + the certified model and core on a compatibility check's record, which + ``data/compatibility/.json`` must hold; otherwise absent.""" certified_data_artifact: Optional[CertifiedDataArtifact] = None certification: Optional[DataCertification] = None source_sha256: Optional[str] = Field(default=None, exclude=True) @@ -1106,30 +1127,94 @@ def _specifier_matches(version: str, specifier: str) -> bool: return False +def _installed_core_version(runtime_core_version: Optional[str]) -> Optional[str]: + """The running core: the one given, else the installed one, else ``None``.""" + + if runtime_core_version is not None: + return runtime_core_version + from importlib import metadata + + try: + return metadata.version("policyengine-core") + except metadata.PackageNotFoundError: + return None + + def _runtime_core_is_certified( certification: DataCertification, runtime_core_version: Optional[str] ) -> bool: """Whether the running core is the one an exact-pair certificate tested. - Other bases make no claim about the core at run time. An exact pair was - tested with one core, so it holds only for that core. + Other bases make no claim about the core at run time. An exact pair (a + qualified pair, or a compatibility check's record) was tested with one + core, so it holds only for that core. """ - if certification.compatibility_basis not in { - "qualified_exact_pair", - "qualified_exact_pair_local_manifest", - }: + if certification.compatibility_basis not in EXACT_PAIR_COMPATIBILITY: return True + runtime_core_version = _installed_core_version(runtime_core_version) if runtime_core_version is None: - from importlib import metadata - - try: - runtime_core_version = metadata.version("policyengine-core") - except metadata.PackageNotFoundError: - return False + return False return certification.certified_for_core_version == runtime_core_version +def _compatibility_record_gaps( + country_id: str, + country_manifest: CountryReleaseManifest, + **expected: Optional[str], +) -> list[str]: + """Why no installed compatibility record covers ``expected``; empty if one does. + + Every record must also be for this country, the bundle's model package + and the SHA-256 of the wheel the bundle pins. + """ + records = bundled_compatibility_records(country_id) + expected = { + "country": country_id, + "model_package": country_manifest.model_package.name, + "wheel_sha256": country_manifest.model_package.sha256, + **expected, + } + if matching_compatibility_record(records, **expected) is not None: + return [] + if not records: + return ["the installed package holds no compatibility record"] + return [ + f"the record of build {record.build} differs (" + f"{', '.join(compatibility_record_problems(record, **expected))})" + for record in records + ] + + +def _require_regional_compatibility_record( + country_id: str, + country_manifest: CountryReleaseManifest, + runtime_model_version: str, + runtime_core_version: Optional[str], +) -> None: + """Refuse a regional release on a record that does not cover this run. + + The record was checked with one model and one core, so it must name the + running model and the running core, as the national certificate's + record must. + """ + if country_manifest.regional_compatibility_basis != BASIS_COMPATIBILITY_CHECKED: + return + gaps = _compatibility_record_gaps( + country_id, + country_manifest, + manifest_sha256=country_manifest.regional_source_manifest_sha256, + model_version=runtime_model_version, + core_version=_installed_core_version(runtime_core_version), + ) + if gaps: + raise ValueError( + f"The bundle serves country '{country_id}''s regional release on a " + "compatibility check, and no installed record covers it with this " + f"model and core: {'; '.join(gaps)}." + ) + + def certify_data_release_compatibility( country_id: str, runtime_model_version: str, @@ -1137,6 +1222,9 @@ def certify_data_release_compatibility( runtime_core_version: Optional[str] = None, ) -> DataCertification: country_manifest = get_release_manifest(country_id) + _require_regional_compatibility_record( + country_id, country_manifest, runtime_model_version, runtime_core_version + ) try: data_release_manifest = get_data_release_manifest(country_id) except DataReleaseManifestUnavailableError as exc: @@ -1154,12 +1242,25 @@ def certify_data_release_compatibility( "Runtime data build fingerprint does not match the bundled " "data certification." ) + # Without the manifest, a compatibility check's certificate holds + # only with its record for the certified build, model and core. if ( bundled_certification.certified_for_model_version == runtime_model_version and _runtime_core_is_certified( bundled_certification, runtime_core_version ) + and ( + bundled_certification.compatibility_basis + != BASIS_COMPATIBILITY_CHECKED + or not _compatibility_record_gaps( + country_id, + country_manifest, + build=bundled_certification.data_build_id, + model_version=runtime_model_version, + core_version=bundled_certification.certified_for_core_version, + ) + ) ): return bundled_certification return DataCertification( @@ -1237,6 +1338,43 @@ def _certify_available_data_release( f"build {remote_build_id} in country '{country_id}'; the exact " f"pair requires {bundled_certification.data_build_id}." ) + # A compatibility check ran one build, model wheel and core; nothing else + # the remote manifest says can stand in for its record. + if ( + bundled_certification is not None + and bundled_certification.compatibility_basis == BASIS_COMPATIBILITY_CHECKED + ): + gaps = [] + if bundled_certification.certified_for_model_version != runtime_model_version: + gaps.append( + f"the check ran {bundled_certification.certified_for_model_version}" + ) + if not _runtime_core_is_certified(bundled_certification, runtime_core_version): + gaps.append( + "the check ran policyengine-core " + f"{bundled_certification.certified_for_core_version}" + ) + if bundled_certification.data_build_id != remote_build_id: + gaps.append( + f"the check ran build {bundled_certification.data_build_id}, " + f"not {remote_build_id}" + ) + if not gaps: + gaps = _compatibility_record_gaps( + country_id, + country_manifest, + manifest_sha256=data_release_manifest.source_sha256, + build=remote_build_id, + model_version=runtime_model_version, + core_version=bundled_certification.certified_for_core_version, + ) + if gaps: + raise ValueError( + "Data release manifest is not certified for the runtime model " + f"version {runtime_model_version} in country '{country_id}' on " + f"its compatibility check: {'; '.join(gaps)}." + ) + return bundled_certification built_with_model = ( data_release_manifest.build.built_with_model_package if data_release_manifest.build is not None diff --git a/tests/test_compatibility_certification.py b/tests/test_compatibility_certification.py new file mode 100644 index 000000000..dba85c71f --- /dev/null +++ b/tests/test_compatibility_certification.py @@ -0,0 +1,964 @@ +"""Tests for certifying a data build on a compatibility check record. + +A record from ``bundle.py check-compatibility`` binds one build (by its +manifest's SHA-256), one model wheel (by PyPI's SHA-256) and one core. +``certify-data`` certifies that exact combination on the basis +``compatibility_checked_exact_pair`` and stores the record beside the bundle; +loading a model accepts the certificate only for that build, model and core. +""" + +import importlib.util +import json +import os +import sys +from pathlib import Path +from types import ModuleType +from unittest.mock import MagicMock, patch + +import pytest + +from policyengine.provenance.certification import ( + CertificationError, + certify_data_release, + model_compatibility_basis, + parse_manifest_uri, + validate_release_manifest, +) +from policyengine.provenance.compatibility_record import ( + BASIS_COMPATIBILITY_CHECKED, + CompatibilityRecord, + bundled_compatibility_records, + compatibility_records_path, + matching_compatibility_record, + read_compatibility_records, + write_compatibility_records, +) +from policyengine.provenance.manifest import ( + CLAIM_BASED_COMPATIBILITY, + DataCertification, + DataReleaseManifest, + DataReleaseManifestUnavailableError, + _runtime_core_is_certified, + certify_data_release_compatibility, + get_data_release_manifest, + get_release_manifest, +) + +UK_TAG = "microcosm-uk-2024-25-national-20261122T100732Z-b891aa69" +UK_MANIFEST_URI = ( + "hf://dataset/policyengine/populace-uk-private" + f"@{UK_TAG}/releases/{UK_TAG}/release_manifest.json" +) +UK_DENSE_TAG = "microcosm-uk-2024-25-dense-20261123T075147Z-7081d968" +UK_DENSE_URI = ( + "hf://dataset/policyengine/populace-uk-private" + f"@{UK_DENSE_TAG}/releases/{UK_DENSE_TAG}/release_manifest.json" +) +BUILD_MODEL = "2.179.2" +TARGET_MODEL = "2.180.0" +CORE = "3.34.10" +OTHER_CORE = "3.35.0" +MANIFEST_SHA256 = "e" * 64 +DENSE_MANIFEST_SHA256 = "f" * 64 +WHEEL_SHA256 = "d" * 64 +WHEEL_URL = ( + "https://files.pythonhosted.org/packages/aa/bb/" + f"policyengine_uk-{TARGET_MODEL}-py3-none-any.whl" +) + + +def _manifest_payload( + *, + tag: str = UK_TAG, + built_with: str = BUILD_MODEL, + model_claims: tuple[str, ...] = (f"=={BUILD_MODEL}",), + core_claims: tuple[str, ...] = (f"=={CORE}",), +) -> dict: + return { + "schema_version": 1, + "data_package": {"name": "microcosm-data", "version": "0.1.0"}, + "compatible_model_packages": [ + {"name": "policyengine-uk", "specifier": claim} for claim in model_claims + ], + "compatible_core_packages": [ + {"name": "policyengine-core", "specifier": claim} for claim in core_claims + ], + "default_datasets": {"national": "microcosm_uk_2024_25"}, + "build": { + "build_id": tag, + "built_at": "2026-11-22T17:14:41+00:00", + "built_with_model_package": { + "name": "policyengine-uk", + "version": built_with, + }, + "built_with_core_package": {"name": "policyengine-core", "version": CORE}, + }, + "artifacts": { + "microcosm_uk_2024_25": { + "kind": "microdata", + "path": "microcosm_uk_2024_25.h5", + "repo_id": "policyengine/populace-uk-private", + "revision": tag, + "sha256": "a" * 64, + }, + "calibration_diagnostics": { + "kind": "diagnostics", + "path": "calibration_diagnostics.json", + "repo_id": "policyengine/populace-uk-private", + "revision": tag, + "sha256": "c" * 64, + }, + }, + } + + +def _manifest(**kwargs) -> DataReleaseManifest: + return DataReleaseManifest.model_validate(_manifest_payload(**kwargs)) + + +def _dense_manifest(built_with: str = BUILD_MODEL) -> DataReleaseManifest: + return DataReleaseManifest.model_validate( + { + "schema_version": 1, + "data_package": {"name": "microcosm-data", "version": "0.1.0"}, + "dataset_role": "non_default_local_area", + "is_default": False, + "default_datasets": {}, + "compatible_model_packages": [ + {"name": "policyengine-uk", "specifier": f"=={built_with}"} + ], + "compatible_core_packages": [ + {"name": "policyengine-core", "specifier": f"=={CORE}"} + ], + "build": { + "build_id": UK_DENSE_TAG, + "built_at": "2026-11-23T07:51:47+00:00", + "built_with_model_package": { + "name": "policyengine-uk", + "version": built_with, + }, + "built_with_core_package": { + "name": "policyengine-core", + "version": CORE, + }, + }, + "artifacts": { + "microcosm_uk_2024_25_dense": { + "kind": "microdata", + "path": "microcosm_uk_2024_25_dense.h5", + "repo_id": "policyengine/populace-uk-private", + "revision": UK_DENSE_TAG, + "sha256": "b" * 64, + } + }, + } + ) + + +def _record(**overrides) -> CompatibilityRecord: + model_package = { + "name": "policyengine-uk", + "version": TARGET_MODEL, + "wheel_sha256": WHEEL_SHA256, + "wheel_url": WHEEL_URL, + **overrides.pop("model_package", {}), + } + payload = { + "country": "uk", + "manifest_uri": UK_MANIFEST_URI, + "manifest_sha256": MANIFEST_SHA256, + "release": None, + "build": UK_TAG, + "built_with_model_version": BUILD_MODEL, + "built_with_core_version": CORE, + "model_package": model_package, + "core_version": CORE, + "policyengine_version": "6.20.5", + "sample": { + "method": "sha256_rank_v1", + "salt": "policyengine-compatibility-sample-v1", + "size": 2000, + }, + "headline_variables": ["household_net_income", "income_tax"], + "artifacts": { + "microcosm_uk_2024_25": { + "path": "microcosm_uk_2024_25.h5", + "revision": UK_TAG, + "sha256": "a" * 64, + "year": 2024, + "households": 20_000, + "sample_households": 2000, + "sample_household_ids_sha256": "9" * 64, + "totals": {"household_net_income": 1.0e9, "income_tax": 1.0e8}, + } + }, + "never_modelled_columns": [], + "defaulted_inputs": [], + "checked_at": "2026-12-03T00:00:00Z", + **overrides, + } + return CompatibilityRecord.model_validate(payload) + + +def _dense_record(**overrides) -> CompatibilityRecord: + return _record( + manifest_uri=UK_DENSE_URI, + manifest_sha256=DENSE_MANIFEST_SHA256, + build=UK_DENSE_TAG, + artifacts={ + "microcosm_uk_2024_25_dense": { + "path": "microcosm_uk_2024_25_dense.h5", + "revision": UK_DENSE_TAG, + "sha256": "b" * 64, + "year": 2024, + "households": 400_000, + "sample_households": 2000, + "sample_household_ids_sha256": "8" * 64, + "totals": {"household_net_income": 1.0e9, "income_tax": 1.0e8}, + } + }, + **overrides, + ) + + +class TestValidateWithRecord: + def test__given_record_for_a_newer_model__then_certifies_the_exact_pair(self): + basis, warnings = validate_release_manifest( + _manifest(), + "policyengine-uk", + TARGET_MODEL, + core_version=CORE, + compatibility_record=_record(), + ) + + assert basis == BASIS_COMPATIBILITY_CHECKED + assert any("compatibility check" in warning for warning in warnings) + + def test__given_publisher_claim_and_record__then_record_basis_replaces_it(self): + basis, _ = validate_release_manifest( + _manifest(model_claims=(">=2.179,<3",)), + "policyengine-uk", + TARGET_MODEL, + core_version=CORE, + compatibility_record=_record(), + ) + + assert basis == BASIS_COMPATIBILITY_CHECKED + + def test__given_core_outside_claims__then_record_covers_it(self): + basis, _ = validate_release_manifest( + _manifest(core_claims=("==3.33.0",)), + "policyengine-uk", + TARGET_MODEL, + core_version=CORE, + compatibility_record=_record(), + ) + + assert basis == BASIS_COMPATIBILITY_CHECKED + + def test__given_record_and_qualified_pair__then_refuses(self): + with pytest.raises(CertificationError, match="qualified"): + validate_release_manifest( + _manifest(), + "policyengine-uk", + TARGET_MODEL, + core_version=CORE, + qualified_pair_id="pair-1", + compatibility_record=_record(), + ) + + def test__given_other_core__then_refuses(self): + with pytest.raises(CertificationError, match=OTHER_CORE): + validate_release_manifest( + _manifest(), + "policyengine-uk", + TARGET_MODEL, + core_version=OTHER_CORE, + compatibility_record=_record(), + ) + + def test__given_no_core__then_refuses(self): + with pytest.raises(CertificationError, match="core_version"): + validate_release_manifest( + _manifest(), + "policyengine-uk", + TARGET_MODEL, + compatibility_record=_record(), + ) + + def test__given_record_for_another_model__then_refuses(self): + with pytest.raises(CertificationError, match="2.181.0"): + validate_release_manifest( + _manifest(), + "policyengine-uk", + "2.181.0", + core_version=CORE, + compatibility_record=_record(), + ) + + def test__given_record_for_the_builds_own_model__then_refuses(self): + with pytest.raises(CertificationError, match="built with"): + validate_release_manifest( + _manifest(built_with=TARGET_MODEL), + "policyengine-uk", + TARGET_MODEL, + core_version=CORE, + compatibility_record=_record(), + ) + + def test__given_regional_record__then_regional_basis_is_the_exact_pair(self): + basis, warnings = model_compatibility_basis( + _dense_manifest(), + "policyengine-uk", + TARGET_MODEL, + compatibility_record=_dense_record(), + ) + + assert basis == BASIS_COMPATIBILITY_CHECKED + assert warnings + + +def _bundle(tmp_path: Path) -> Path: + bundle_path = tmp_path / "data" / "bundle" / "manifest.json" + bundle_path.parent.mkdir(parents=True) + bundle_path.write_text( + json.dumps( + { + "schema_version": 2, + "bundle_version": "9.9.9", + "policyengine_version": "9.9.9", + "packages": { + "policyengine": {"name": "policyengine", "version": "9.9.9"}, + "policyengine-core": { + "name": "policyengine-core", + "version": "3.30.0", + }, + "policyengine-uk": { + "name": "policyengine-uk", + "version": BUILD_MODEL, + }, + }, + "extras": {}, + "countries": {"uk": {"model_package": "policyengine-uk"}}, + "data_releases": {}, + } + ) + + "\n" + ) + return bundle_path + + +def _certify(bundle_path: Path, *, manifests=None, wheel_sha256=WHEEL_SHA256, **kwargs): + manifests = manifests or { + UK_MANIFEST_URI: (_manifest(), MANIFEST_SHA256), + UK_DENSE_URI: (_dense_manifest(), DENSE_MANIFEST_SHA256), + } + + def fetch(uri, token=None): + manifest, sha256 = manifests[uri] + return manifest.model_copy(deep=True), sha256, parse_manifest_uri(uri) + + with ( + patch("policyengine.provenance.certification.fetch_release_manifest", fetch), + patch( + "policyengine.provenance.certification.require_tagged_layout", + return_value=None, + ), + patch("policyengine.provenance.certification.head_artifact", return_value=True), + patch( + "policyengine.provenance.certification.head_release_file", + return_value=True, + ), + patch( + "policyengine.provenance.certification.head_artifact_reference", + return_value=True, + ), + patch( + "policyengine.provenance.certification.fetch_pypi_wheel_metadata", + return_value={"sha256": wheel_sha256, "url": WHEEL_URL}, + ), + patch( + "policyengine.provenance.certification.policyengine_version", + return_value="9.9.9", + ), + ): + return certify_data_release( + country="uk", + data_producer="populace", + manifest_uri=UK_MANIFEST_URI, + model_version=TARGET_MODEL, + bundle_path=bundle_path, + **kwargs, + ) + + +class TestCertifyWithRecord: + def test__given_record__then_certifies_exact_pair_and_stores_record(self, tmp_path): + bundle_path = _bundle(tmp_path) + record = _record() + + _certify(bundle_path, compatibility_record=record) + + bundle = json.loads(bundle_path.read_text()) + certification = bundle["data_releases"]["uk"]["certification"] + assert certification["compatibility_basis"] == BASIS_COMPATIBILITY_CHECKED + assert certification["certified_for_model_version"] == TARGET_MODEL + assert certification["certified_for_core_version"] == CORE + assert certification["core_binding"] == "certified" + assert certification["data_build_id"] == UK_TAG + assert bundle["packages"]["policyengine-core"]["version"] == CORE + assert bundle["packages"]["policyengine-uk"]["version"] == TARGET_MODEL + records_path = tmp_path / "data" / "compatibility" / "uk.json" + assert records_path == compatibility_records_path(tmp_path / "data", "uk") + assert read_compatibility_records(records_path, "uk") == [record] + + def test__given_record_for_other_manifest_bytes__then_refuses(self, tmp_path): + with pytest.raises(CertificationError, match="manifest_sha256"): + _certify( + _bundle(tmp_path), + compatibility_record=_record(manifest_sha256="1" * 64), + ) + + def test__given_record_for_other_wheel__then_refuses(self, tmp_path): + with pytest.raises(CertificationError, match="wheel_sha256"): + _certify( + _bundle(tmp_path), + compatibility_record=_record(), + wheel_sha256="2" * 64, + ) + + def test__given_record_for_other_build__then_refuses(self, tmp_path): + with pytest.raises(CertificationError, match="build"): + _certify( + _bundle(tmp_path), + compatibility_record=_record(build="another-build"), + ) + + def test__given_record_as_json__then_reads_it(self, tmp_path): + bundle_path = _bundle(tmp_path) + + _certify(bundle_path, compatibility_record=_record().model_dump(mode="json")) + + bundle = json.loads(bundle_path.read_text()) + assert ( + bundle["data_releases"]["uk"]["certification"]["compatibility_basis"] + == BASIS_COMPATIBILITY_CHECKED + ) + + def test__given_certification_without_record__then_removes_stored_records( + self, tmp_path + ): + bundle_path = _bundle(tmp_path) + records_path = compatibility_records_path(tmp_path / "data", "uk") + write_compatibility_records(records_path, "uk", [_record()]) + + _certify( + bundle_path, + manifests={ + UK_MANIFEST_URI: (_manifest(built_with=TARGET_MODEL), MANIFEST_SHA256) + }, + ) + + assert not records_path.exists() + + def test__given_regional_record__then_routes_regions_on_the_exact_pair( + self, tmp_path + ): + bundle_path = _bundle(tmp_path) + manifests = { + UK_MANIFEST_URI: (_manifest(built_with=TARGET_MODEL), MANIFEST_SHA256), + UK_DENSE_URI: (_dense_manifest(), DENSE_MANIFEST_SHA256), + } + dense_record = _dense_record() + + _certify( + bundle_path, + manifests=manifests, + regional_manifest_uri=UK_DENSE_URI, + regional_compatibility_record=dense_record, + ) + + release = json.loads(bundle_path.read_text())["data_releases"]["uk"] + assert release["certification"]["compatibility_basis"] == ( + "built_with_model_package" + ) + assert release["certification"]["certified_for_core_version"] == CORE + assert release["regional_compatibility_basis"] == BASIS_COMPATIBILITY_CHECKED + assert "regional_certification" not in release + assert read_compatibility_records( + compatibility_records_path(tmp_path / "data", "uk"), "uk" + ) == [dense_record] + + def test__given_regional_record_and_accepted_mismatch__then_refuses(self, tmp_path): + with pytest.raises(CertificationError, match="mismatch"): + _certify( + _bundle(tmp_path), + manifests={ + UK_MANIFEST_URI: ( + _manifest(built_with=TARGET_MODEL), + MANIFEST_SHA256, + ), + UK_DENSE_URI: (_dense_manifest(), DENSE_MANIFEST_SHA256), + }, + regional_manifest_uri=UK_DENSE_URI, + regional_compatibility_record=_dense_record(), + regional_model_mismatch_reason="reviewed", + ) + + def test__given_regional_record_without_regional_release__then_refuses( + self, tmp_path + ): + with pytest.raises(CertificationError, match="regional"): + _certify( + _bundle(tmp_path), + regional_compatibility_record=_dense_record(), + ) + + def test__given_regional_record_for_other_bytes__then_refuses(self, tmp_path): + with pytest.raises(CertificationError, match="manifest_sha256"): + _certify( + _bundle(tmp_path), + manifests={ + UK_MANIFEST_URI: ( + _manifest(built_with=TARGET_MODEL), + MANIFEST_SHA256, + ), + UK_DENSE_URI: (_dense_manifest(), "3" * 64), + }, + regional_manifest_uri=UK_DENSE_URI, + regional_compatibility_record=_dense_record(), + ) + + +def _certificate(**overrides) -> DataCertification: + return DataCertification( + **{ + "compatibility_basis": BASIS_COMPATIBILITY_CHECKED, + "certified_for_model_version": TARGET_MODEL, + "certified_for_core_version": CORE, + "core_binding": "certified", + "data_build_id": UK_TAG, + "built_with_model_version": BUILD_MODEL, + **overrides, + } + ) + + +class TestRuntimeAcceptance: + def setup_method(self): + get_data_release_manifest.cache_clear() + + def _remote(self, source_sha256=MANIFEST_SHA256, **kwargs) -> DataReleaseManifest: + remote = _manifest(**kwargs) + remote.source_sha256 = source_sha256 + return remote + + def _load( + self, + certificate, + *, + remote=None, + records=(), + runtime_model=TARGET_MODEL, + core=CORE, + wheel_sha256=WHEEL_SHA256, + regional_basis=None, + regional_sha256=None, + ): + country_manifest = MagicMock(certification=certificate) + country_manifest.model_package.name = "policyengine-uk" + country_manifest.model_package.sha256 = wheel_sha256 + country_manifest.regional_compatibility_basis = regional_basis + country_manifest.regional_source_manifest_sha256 = regional_sha256 + if remote is None: + data_patch = patch( + "policyengine.provenance.manifest.get_data_release_manifest", + side_effect=DataReleaseManifestUnavailableError("private"), + ) + else: + data_patch = patch( + "policyengine.provenance.manifest.get_data_release_manifest", + return_value=remote, + ) + with ( + patch( + "policyengine.provenance.manifest.get_release_manifest", + return_value=country_manifest, + ), + data_patch, + patch( + "policyengine.provenance.manifest.bundled_compatibility_records", + return_value=list(records), + ), + ): + return certify_data_release_compatibility( + "uk", + runtime_model_version=runtime_model, + runtime_core_version=core, + ) + + def test__given_matching_record__then_accepts_the_certificate(self): + certificate = self._load( + _certificate(), remote=self._remote(), records=[_record()] + ) + + assert certificate.compatibility_basis == BASIS_COMPATIBILITY_CHECKED + + def test__given_no_record__then_refuses(self): + with pytest.raises(ValueError, match="not certified"): + self._load(_certificate(), remote=self._remote(), records=[]) + + def test__given_other_model__then_refuses(self): + with pytest.raises(ValueError, match="not certified"): + self._load( + _certificate(), + remote=self._remote(), + records=[_record()], + runtime_model="2.180.1", + ) + + def test__given_other_core__then_refuses(self): + with pytest.raises(ValueError, match="not certified"): + self._load( + _certificate(), + remote=self._remote(), + records=[_record()], + core=OTHER_CORE, + ) + + def test__given_other_manifest_bytes__then_refuses(self): + with pytest.raises(ValueError, match="not certified"): + self._load( + _certificate(), + remote=self._remote(source_sha256="4" * 64), + records=[_record()], + ) + + def test__given_other_wheel__then_refuses(self): + with pytest.raises(ValueError, match="not certified"): + self._load( + _certificate(), + remote=self._remote(), + records=[_record()], + wheel_sha256="5" * 64, + ) + + def test__given_publisher_claim__then_does_not_replace_a_missing_record(self): + with pytest.raises(ValueError, match="not certified"): + self._load( + _certificate(), + remote=self._remote(model_claims=(">=2.179,<3",)), + records=[], + ) + + def test__given_manifest_unavailable_and_matching_record__then_accepts(self): + certificate = self._load(_certificate(), records=[_record()]) + + assert certificate.compatibility_basis == BASIS_COMPATIBILITY_CHECKED + + def test__given_manifest_unavailable_and_no_record__then_unverified(self): + certificate = self._load(_certificate(), records=[]) + + assert certificate.compatibility_basis == ( + "unverified_data_release_manifest_unavailable" + ) + + def test__given_regional_record__then_accepts(self): + certificate = self._load( + _certificate( + compatibility_basis="built_with_model_package", + built_with_model_version=TARGET_MODEL, + ), + remote=self._remote(built_with=TARGET_MODEL), + records=[_dense_record()], + regional_basis=BASIS_COMPATIBILITY_CHECKED, + regional_sha256=DENSE_MANIFEST_SHA256, + ) + + assert certificate.compatibility_basis == "exact_build_model_version" + + def test__given_regional_basis_without_record__then_refuses(self): + with pytest.raises(ValueError, match="regional"): + self._load( + _certificate( + compatibility_basis="built_with_model_package", + built_with_model_version=TARGET_MODEL, + ), + remote=self._remote(built_with=TARGET_MODEL), + records=[], + regional_basis=BASIS_COMPATIBILITY_CHECKED, + regional_sha256=DENSE_MANIFEST_SHA256, + ) + + @pytest.mark.parametrize("online", [True, False]) + def test__given_regional_record_under_another_installed_core__then_refuses( + self, online + ): + """The national build's own basis makes no claim about the core, but + the regional release's record holds only for the core it ran.""" + + with pytest.raises(ValueError, match="regional"): + self._load( + _certificate( + compatibility_basis="built_with_model_package", + built_with_model_version=TARGET_MODEL, + ), + remote=self._remote(built_with=TARGET_MODEL) if online else None, + records=[_dense_record()], + core=OTHER_CORE, + regional_basis=BASIS_COMPATIBILITY_CHECKED, + regional_sha256=DENSE_MANIFEST_SHA256, + ) + + def test__exact_pair_names_its_core(self): + assert BASIS_COMPATIBILITY_CHECKED in CLAIM_BASED_COMPATIBILITY + assert f"{BASIS_COMPATIBILITY_CHECKED}_local_manifest" in ( + CLAIM_BASED_COMPATIBILITY + ) + assert _runtime_core_is_certified(_certificate(), CORE) + assert not _runtime_core_is_certified(_certificate(), OTHER_CORE) + + +def test_committed_certificates_on_the_record_basis_have_records(): + """Every committed certificate resting on a check names a stored record.""" + + for country in ("uk", "us"): + records = bundled_compatibility_records(country) + release = get_release_manifest(country) + certificate = release.certification + if ( + certificate is not None + and certificate.compatibility_basis == BASIS_COMPATIBILITY_CHECKED + ): + assert ( + matching_compatibility_record( + records, + country=country, + build=certificate.data_build_id, + model_package=release.model_package.name, + model_version=certificate.certified_for_model_version, + wheel_sha256=release.model_package.sha256, + core_version=certificate.certified_for_core_version, + ) + is not None + ), f"{country}: no stored compatibility record for the certificate" + if release.regional_compatibility_basis == BASIS_COMPATIBILITY_CHECKED: + assert certificate is not None + assert ( + matching_compatibility_record( + records, + country=country, + manifest_sha256=release.regional_source_manifest_sha256, + model_package=release.model_package.name, + model_version=certificate.certified_for_model_version, + wheel_sha256=release.model_package.sha256, + core_version=certificate.certified_for_core_version, + ) + is not None + ), f"{country}: no stored compatibility record for the regional release" + + +def _load_script(monkeypatch, name: str): + scripts_dir = Path(__file__).resolve().parents[1] / "scripts" + monkeypatch.syspath_prepend(str(scripts_dir)) + spec = importlib.util.spec_from_file_location( + f"{name}_under_test", scripts_dir / f"{name}.py" + ) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +class TestScripts: + def test__given_check_compatibility__then_runs_the_check_and_writes_record( + self, monkeypatch, tmp_path + ): + bundle_script = _load_script(monkeypatch, "bundle") + calls = [] + + def check(**kwargs): + calls.append(kwargs) + return _record() + + monkeypatch.setattr( + "policyengine.provenance.compatibility_check.check_build_compatibility", + check, + ) + output = tmp_path / "record.json" + + assert ( + bundle_script.main( + [ + "check-compatibility", + "--country", + "uk", + "--manifest-uri", + UK_MANIFEST_URI, + "--model-version", + TARGET_MODEL, + "--core-version", + CORE, + "--work-dir", + str(tmp_path / "work"), + "--output", + str(output), + ] + ) + == 0 + ) + + (call,) = calls + assert call["country"] == "uk" + assert call["manifest_uri"] == UK_MANIFEST_URI + assert call["model_version"] == TARGET_MODEL + assert call["core_version"] == CORE + assert call["work_dir"] == tmp_path / "work" + assert CompatibilityRecord.model_validate_json(output.read_text()) == ( + _record() + ) + + def test__given_check_compatibility__then_skips_country_model_imports( + self, monkeypatch, tmp_path + ): + """Importing .py must not build the installed country models: their + bundle certificate need not cover the installed model version.""" + + # setenv first, so teardown removes the value the script sets. + monkeypatch.setenv("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "unset by the test") + monkeypatch.delenv("POLICYENGINE_SKIP_COUNTRY_IMPORTS") + bundle_script = _load_script(monkeypatch, "bundle") + skip_values = [] + + def check(**kwargs): + skip_values.append(os.environ.get("POLICYENGINE_SKIP_COUNTRY_IMPORTS")) + return _record() + + monkeypatch.setattr( + "policyengine.provenance.compatibility_check.check_build_compatibility", + check, + ) + + bundle_script.main( + [ + "check-compatibility", + "--country", + "uk", + "--manifest-uri", + UK_MANIFEST_URI, + "--model-version", + TARGET_MODEL, + "--work-dir", + str(tmp_path / "work"), + "--output", + str(tmp_path / "record.json"), + ] + ) + + assert skip_values == ["1"] + + def test__given_certify_data_records__then_forwards_them(self, monkeypatch): + bundle_script = _load_script(monkeypatch, "bundle") + captured: dict[str, list[str]] = {} + fake = ModuleType("certify_data_release") + + def fake_main(argv): + captured["argv"] = argv + return 0 + + fake.main = fake_main + monkeypatch.setitem(sys.modules, "certify_data_release", fake) + + assert ( + bundle_script.main( + [ + "certify-data", + "--country", + "uk", + "--manifest-uri", + UK_MANIFEST_URI, + "--compatibility-record", + "national.json", + "--regional-manifest-uri", + UK_DENSE_URI, + "--regional-compatibility-record", + "dense.json", + ] + ) + == 0 + ) + + argv = captured["argv"] + assert argv[argv.index("--compatibility-record") + 1] == "national.json" + assert argv[argv.index("--regional-compatibility-record") + 1] == "dense.json" + + def test__given_record_files__then_certifier_reads_them( + self, monkeypatch, tmp_path + ): + certify_script = _load_script(monkeypatch, "certify_data_release") + national = tmp_path / "national.json" + national.write_text(_record().model_dump_json()) + dense = tmp_path / "dense.json" + dense.write_text(_dense_record().model_dump_json()) + calls = [] + + def certify(**kwargs): + calls.append(kwargs) + raise SystemExit(0) + + monkeypatch.setattr(certify_script, "certify_data_release", certify) + + with pytest.raises(SystemExit): + certify_script.main( + [ + "--country", + "uk", + "--manifest-uri", + UK_MANIFEST_URI, + "--compatibility-record", + str(national), + "--regional-manifest-uri", + UK_DENSE_URI, + "--regional-compatibility-record", + str(dense), + ] + ) + + (call,) = calls + assert call["compatibility_record"] == _record() + assert call["regional_compatibility_record"] == _dense_record() + + def test__given_strict_tro_on_record_basis__then_revalidates_with_the_record( + self, monkeypatch + ): + generator = _load_script(monkeypatch, "generate_trace_tros") + captured = {} + + class Stop(Exception): + pass + + def validate(*args, **kwargs): + captured.update(kwargs) + raise Stop + + monkeypatch.setattr(generator, "validate_release_manifest", validate) + monkeypatch.setattr( + generator, "bundled_compatibility_records", lambda country: [_record()] + ) + country = MagicMock() + country.country_id = "uk" + country.data_package.release_manifest_revision = UK_TAG + country.model_package.name = "policyengine-uk" + country.model_package.version = TARGET_MODEL + country.model_package.sha256 = WHEEL_SHA256 + country.model_package.wheel_url = WHEEL_URL + country.certification = _certificate() + data = _manifest() + data.source_sha256 = MANIFEST_SHA256 + + with pytest.raises(Stop): + generator._validate_reviewed_inputs(country, data, Path("unused.jsonld")) + + assert captured["core_version"] == CORE + assert captured["qualified_pair_id"] is None + assert captured["compatibility_record"] == _record() diff --git a/tests/test_compatibility_check.py b/tests/test_compatibility_check.py new file mode 100644 index 000000000..1036e13e4 --- /dev/null +++ b/tests/test_compatibility_check.py @@ -0,0 +1,982 @@ +"""Tests for the compatibility check of one data build against one model version. + +The check downloads the build's H5 files and the model wheel, reads the +stored columns, reads the build model's variables in a throwaway +environment, and runs a 2,000-household sample under the new model in +another. Every download and subprocess is replaced here, so no test +reaches Hugging Face, PyPI or uv. +""" + +import hashlib +import json +import math +import subprocess +from pathlib import Path +from types import SimpleNamespace + +import pandas as pd +import pytest + +from policyengine.provenance import compatibility_check, compatibility_probe +from policyengine.provenance.certification import parse_manifest_uri +from policyengine.provenance.compatibility_check import ( + HEADLINE_VARIABLES, + CompatibilityCheckError, + check_build_compatibility, + probe_command, + probe_environment, + total_problems, +) +from policyengine.provenance.compatibility_probe import ( + CHECK_IN_PROGRESS_BASIS, + SAMPLE_HOUSEHOLDS, + SAMPLE_METHOD, + SAMPLE_SALT, + household_ids_sha256, + replace_certificate_lookup, + run_probe, + sample_household_ids, + weighted_totals, +) +from policyengine.provenance.compatibility_record import ( + BASIS_COMPATIBILITY_CHECKED, + CompatibilityRecord, + compatibility_record_problems, + compatibility_records_path, + matching_compatibility_record, + read_compatibility_records, + write_compatibility_records, +) +from policyengine.provenance.manifest import DataReleaseManifest + +UK_TAG = "uk-frs-calibration-attempt-20261122T100732Z-b891aa69" +UK_MANIFEST_URI = ( + "hf://dataset/policyengine/populace-uk-private" + f"@{UK_TAG}/releases/{UK_TAG}/release_manifest.json" +) +UK_DATASET = "microcosm_uk_2024_25" +BUILD_MODEL_VERSION = "2.179.2" +TARGET_MODEL_VERSION = "2.180.0" +CORE_VERSION = "3.34.10" +WHEEL_BYTES = b"policyengine-uk wheel" +WHEEL_URL = ( + "https://files.pythonhosted.org/packages/aa/bb/" + f"policyengine_uk-{TARGET_MODEL_VERSION}-py3-none-any.whl" +) +MANIFEST_SHA256 = "e" * 64 +UK_TOTALS = { + "household_net_income": 1_200_000.0, + "income_tax": 150_000.0, + "universal_credit": 20_000.0, + "child_benefit": 5_000.0, + "state_pension": 40_000.0, + "pension_credit": 3_000.0, + "housing_benefit": 4_000.0, +} +#: Stored in the file and defined by the build model only. +DROPPED_COLUMN = "retired_input" +#: Stored in the file and defined by neither model. +NEVER_MODELLED_COLUMN = "microcosm_area_code" +#: An input of the target model only, which the file does not store. +NEW_INPUT = "new_target_input" + + +def _sha256(content: bytes) -> str: + return hashlib.sha256(content).hexdigest() + + +def _uk_h5(path: Path, *, extra_household_columns: tuple[str, ...] = ()) -> Path: + with pd.HDFStore(path, mode="w") as store: + store.put("time_period", pd.Series([2024]), format="table") + store.put( + "person", + pd.DataFrame( + { + "person_id": [1.0, 2.0, 3.0], + "person_benunit_id": [1.0, 2.0, 3.0], + "person_household_id": [1.0, 2.0, 3.0], + "age": [30.0, 70.0, 45.0], + "employment_income": [20_000.0, 0.0, 35_000.0], + } + ), + format="table", + ) + store.put("benunit", pd.DataFrame({"benunit_id": [1.0, 2.0, 3.0]})) + household = { + "household_id": [1.0, 2.0, 3.0], + "household_weight": [100.0, 120.0, 80.0], + } + for column in extra_household_columns: + household[column] = [1.0, 2.0, 3.0] + store.put("household", pd.DataFrame(household), format="table") + return path + + +STORED_COLUMNS = [ + "age", + "benunit_id", + "employment_income", + "household_id", + "household_weight", + "person_benunit_id", + "person_household_id", + "person_id", +] +TARGET_VARIABLES = sorted( + [*STORED_COLUMNS, NEW_INPUT, *UK_TOTALS] + ["benunit_weight", "person_weight"] +) +TARGET_INPUTS = sorted([*STORED_COLUMNS, NEW_INPUT]) +BUILD_VARIABLES = sorted([*TARGET_VARIABLES, DROPPED_COLUMN]) +BUILD_INPUTS = sorted([*STORED_COLUMNS, DROPPED_COLUMN]) + + +def _uk_manifest(h5_sha256: str, **build_overrides) -> DataReleaseManifest: + build = { + "build_id": UK_TAG, + "built_at": "2026-11-22T17:14:41.779575+00:00", + "built_with_model_package": { + "name": "policyengine-uk", + "version": BUILD_MODEL_VERSION, + }, + "built_with_core_package": { + "name": "policyengine-core", + "version": CORE_VERSION, + }, + **build_overrides, + } + return DataReleaseManifest.model_validate( + { + "schema_version": 1, + "data_package": {"name": "microcosm-data", "version": "0.1.0"}, + "compatible_model_packages": [ + {"name": "policyengine-uk", "specifier": f"=={BUILD_MODEL_VERSION}"} + ], + "compatible_core_packages": [ + {"name": "policyengine-core", "specifier": f"=={CORE_VERSION}"} + ], + "default_datasets": {"national": UK_DATASET}, + "build": build, + "artifacts": { + UK_DATASET: { + "kind": "microdata", + "path": f"{UK_DATASET}.h5", + "repo_id": "policyengine/populace-uk-private", + "repo_type": "dataset", + "revision": UK_TAG, + "sha256": h5_sha256, + }, + "calibration_diagnostics": { + "kind": "diagnostics", + "path": "calibration_diagnostics.json", + "repo_id": "policyengine/populace-uk-private", + "repo_type": "dataset", + "revision": UK_TAG, + "sha256": "c" * 64, + }, + }, + } + ) + + +def _bundle(tmp_path: Path) -> Path: + bundle_path = tmp_path / "bundle.json" + bundle_path.write_text( + json.dumps( + { + "packages": { + "policyengine-core": { + "name": "policyengine-core", + "version": CORE_VERSION, + }, + "spm-calculator": {"name": "spm-calculator", "version": "1.1.0"}, + } + } + ) + ) + return bundle_path + + +class FakeUv: + """Answers the build-model read and the probe as uv would.""" + + def __init__(self, *, target_variables=None, probe_result=None): + self.commands: list[list[str]] = [] + self.environments: list[dict] = [] + self.requests: list[dict] = [] + self.target_variables = target_variables or TARGET_VARIABLES + self.probe_result = probe_result + + def __call__(self, command, **kwargs): + self.commands.append(command) + self.environments.append(kwargs.get("env") or {}) + if "-c" in command: + surface = { + "model_version": BUILD_MODEL_VERSION, + "core_version": CORE_VERSION, + "variables": BUILD_VARIABLES, + "inputs": BUILD_INPUTS, + } + return subprocess.CompletedProcess(command, 0, json.dumps(surface), "") + request = json.loads(Path(command[-1]).read_text()) + self.requests.append(request) + result = self.probe_result or { + "model_version": TARGET_MODEL_VERSION, + "core_version": CORE_VERSION, + "policyengine_version": "6.20.5", + "variables": self.target_variables, + "inputs": [name for name in TARGET_INPUTS if name in self.target_variables], + "input_aliases": {}, + "artifacts": { + name: { + "households": 3, + "sample_households": 3, + "sample_household_ids_sha256": household_ids_sha256([1, 2, 3]), + "totals": dict(UK_TOTALS), + } + for name in request["artifacts"] + }, + } + Path(request["result_path"]).write_text(json.dumps(result)) + return subprocess.CompletedProcess(command, 0, "", "") + + +class FakeDownloads: + def __init__(self, files: dict[str, bytes]): + self.files = files + self.requests: list[tuple[str, dict]] = [] + + def __call__(self, url: str, destination: Path, headers: dict) -> None: + self.requests.append((url, headers)) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(self.files[url]) + + +def _h5_url() -> str: + return ( + "https://huggingface.co/datasets/policyengine/populace-uk-private/" + f"resolve/{UK_TAG}/{UK_DATASET}.h5" + ) + + +def _check( + tmp_path: Path, + monkeypatch, + *, + uv: FakeUv | None = None, + h5_bytes: bytes | None = None, + manifest_h5_sha256: str | None = None, + wheel_sha256: str | None = None, + model_version: str = TARGET_MODEL_VERSION, + manifest: DataReleaseManifest | None = None, + core_version: str | None = None, +): + source = _uk_h5(tmp_path / "source.h5", extra_household_columns=(DROPPED_COLUMN,)) + # The never-modelled column is stored too. + with pd.HDFStore(source, mode="a") as store: + household = store.select("household") + household[NEVER_MODELLED_COLUMN] = [7.0, 8.0, 9.0] + store.put("household", household, format="table") + stored = source.read_bytes() + served = stored if h5_bytes is None else h5_bytes + manifest = manifest or _uk_manifest(manifest_h5_sha256 or _sha256(stored)) + monkeypatch.setattr( + compatibility_check, + "fetch_release_manifest", + lambda uri, token=None: (manifest, MANIFEST_SHA256, parse_manifest_uri(uri)), + ) + monkeypatch.setattr( + compatibility_check, "require_tagged_layout", lambda *args, **kwargs: None + ) + monkeypatch.setattr( + compatibility_check, + "fetch_pypi_wheel_metadata", + lambda name, version: { + "sha256": wheel_sha256 or _sha256(WHEEL_BYTES), + "url": WHEEL_URL, + }, + ) + uv = uv or FakeUv() + downloads = FakeDownloads({_h5_url(): served, WHEEL_URL: WHEEL_BYTES}) + record = check_build_compatibility( + country="uk", + manifest_uri=UK_MANIFEST_URI, + model_version=model_version, + core_version=core_version, + work_dir=tmp_path / "work", + policyengine_source=tmp_path / "checkout", + bundle_path=_bundle(tmp_path), + run=uv, + download=downloads, + ) + return record, uv, downloads + + +class TestSampleHouseholdIds: + def test__given_more_households_than_the_sample__then_keeps_lowest_ranked( + self, + ): + household_ids = list(range(1, 5001)) + + sample = sample_household_ids(household_ids) + + ranked = sorted( + household_ids, + key=lambda household_id: hashlib.sha256( + f"{SAMPLE_SALT}:{household_id}".encode() + ).hexdigest(), + ) + assert SAMPLE_HOUSEHOLDS == 2000 + assert len(sample) == SAMPLE_HOUSEHOLDS + assert sample == sorted(ranked[:SAMPLE_HOUSEHOLDS]) + + def test__given_ids_in_another_order__then_draws_the_same_sample(self): + household_ids = list(range(1, 5001)) + + assert sample_household_ids(household_ids) == sample_household_ids( + list(reversed(household_ids)) + ) + + def test__given_whole_number_floats__then_reads_them_as_integers(self): + assert sample_household_ids([3.0, 1.0, 2.0]) == [1, 2, 3] + + def test__given_fewer_households_than_the_sample__then_keeps_all(self): + assert sample_household_ids([5, 9, 7], size=10) == [5, 7, 9] + + def test__given_repeated_ids__then_refuses(self): + with pytest.raises(ValueError, match="repeat"): + sample_household_ids([1, 2.0, 2]) + + def test__given_fractional_id__then_refuses(self): + with pytest.raises(ValueError, match="whole number"): + sample_household_ids([1, 1.5]) + + def test__given_ids__then_digest_covers_sorted_decimal_ids(self): + assert household_ids_sha256([3, 1.0, 2]) == _sha256(b"1\n2\n3") + + +class TestTotalProblems: + def test__given_positive_totals__then_none(self): + assert total_problems(UK_TOTALS, HEADLINE_VARIABLES["uk"]) == [] + + @pytest.mark.parametrize( + ("value", "reason"), + [(0.0, "not positive"), (-1.0, "not positive"), (math.nan, "not finite")], + ) + def test__given_bad_total__then_names_it(self, value, reason): + totals = {**UK_TOTALS, "pension_credit": value} + + problems = total_problems(totals, HEADLINE_VARIABLES["uk"]) + + assert len(problems) == 1 + assert "pension_credit" in problems[0] + assert reason in problems[0] + + def test__given_missing_total__then_names_it(self): + totals = { + name: value for name, value in UK_TOTALS.items() if name != "income_tax" + } + + problems = total_problems(totals, HEADLINE_VARIABLES["uk"]) + + assert problems == ["income_tax: no total"] + + def test__headline_variables_follow_the_agreed_lists(self): + assert HEADLINE_VARIABLES["uk"] == ( + "household_net_income", + "income_tax", + "universal_credit", + "child_benefit", + "state_pension", + "pension_credit", + "housing_benefit", + ) + assert HEADLINE_VARIABLES["us"] == ( + "household_net_income", + "income_tax", + "snap", + "ssi", + "social_security", + ) + + +class TestProbeCommand: + def test__given_pins__then_installs_exactly_them_from_pypi_in_isolation( + self, tmp_path + ): + command = probe_command( + policyengine_source=tmp_path / "checkout", + wheel_path=tmp_path / "policyengine_uk-2.180.0-py3-none-any.whl", + core_version=CORE_VERSION, + extra_requirements=["spm-calculator==1.1.0"], + request_path=tmp_path / "request.json", + ) + + assert command[:6] == [ + "uv", + "run", + "--isolated", + "--no-project", + "--no-config", + "--default-index", + ] + assert command[6] == "https://pypi.org/simple" + # The checkout is installed editable, so the run imports its current + # source rather than a wheel uv built from it earlier and cached. + editable = [ + command[index + 1] + for index, argument in enumerate(command) + if argument == "--with-editable" + ] + assert editable == [str(tmp_path / "checkout")] + requirements = [ + command[index + 1] + for index, argument in enumerate(command) + if argument == "--with" + ] + assert requirements == [ + str(tmp_path / "policyengine_uk-2.180.0-py3-none-any.whl"), + f"policyengine-core=={CORE_VERSION}", + "spm-calculator==1.1.0", + ] + assert command[-5:] == [ + "python", + "-I", + "-m", + "policyengine.provenance.compatibility_probe", + str(tmp_path / "request.json"), + ] + + def test__given_caller_environment__then_drops_tokens_and_uv_settings(self): + environment = probe_environment( + { + "PATH": "/bin", + "VIRTUAL_ENV": "/somewhere/.venv", + "UV_INDEX_URL": "https://mirror.invalid/simple", + "UV_CACHE_DIR": "/cache", + "HUGGING_FACE_TOKEN": "secret", + "HF_TOKEN": "secret", + "HUGGINGFACE_HUB_TOKEN": "secret", + "POLICYENGINE_UK_DATA_MANIFEST_FILE": "/manifest.json", + } + ) + + assert environment == { + "PATH": "/bin", + "UV_CACHE_DIR": "/cache", + "POLICYENGINE_SKIP_COUNTRY_IMPORTS": "1", + } + + +class TestCheckBuildCompatibility: + def test__given_compatible_build__then_writes_record(self, tmp_path, monkeypatch): + record, uv, downloads = _check( + tmp_path, + monkeypatch, + uv=FakeUv(target_variables=[*TARGET_VARIABLES, DROPPED_COLUMN]), + ) + + assert isinstance(record, CompatibilityRecord) + assert record.compatibility_basis == BASIS_COMPATIBILITY_CHECKED + assert record.country == "uk" + assert record.manifest_uri == UK_MANIFEST_URI + assert record.manifest_sha256 == MANIFEST_SHA256 + assert record.build == UK_TAG + assert record.built_with_model_version == BUILD_MODEL_VERSION + assert record.built_with_core_version == CORE_VERSION + assert record.model_package.name == "policyengine-uk" + assert record.model_package.version == TARGET_MODEL_VERSION + assert record.model_package.wheel_sha256 == _sha256(WHEEL_BYTES) + assert record.model_package.wheel_url == WHEEL_URL + assert record.core_version == CORE_VERSION + assert record.policyengine_version == "6.20.5" + assert record.sample.method == SAMPLE_METHOD + assert record.sample.salt == SAMPLE_SALT + assert record.sample.size == SAMPLE_HOUSEHOLDS + assert record.headline_variables == list(HEADLINE_VARIABLES["uk"]) + assert list(record.artifacts) == [UK_DATASET] + artifact = record.artifacts[UK_DATASET] + assert artifact.path == f"{UK_DATASET}.h5" + assert artifact.revision == UK_TAG + assert artifact.year == 2024 + assert artifact.households == 3 + assert artifact.sample_households == 3 + assert artifact.totals == UK_TOTALS + assert record.never_modelled_columns == [NEVER_MODELLED_COLUMN] + assert record.defaulted_inputs == [NEW_INPUT] + # Only the microdata H5 and the wheel are downloaded. + assert [url for url, _ in downloads.requests] == [WHEEL_URL, _h5_url()] + + def test__given_check__then_probe_runs_the_verified_wheel_and_core( + self, tmp_path, monkeypatch + ): + _, uv, _ = _check( + tmp_path, + monkeypatch, + uv=FakeUv(target_variables=[*TARGET_VARIABLES, DROPPED_COLUMN]), + ) + + build_read, probe = uv.commands + assert f"policyengine-uk=={BUILD_MODEL_VERSION}" in build_read + assert "--exclude-newer" in build_read + wheel_argument = probe[probe.index(str(tmp_path / "checkout")) + 2] + assert Path(wheel_argument).name == WHEEL_URL.rsplit("/", 1)[1] + assert Path(wheel_argument).read_bytes() == WHEEL_BYTES + assert f"policyengine-core=={CORE_VERSION}" in probe + assert not any("spm-calculator" in argument for argument in probe) + assert uv.environments[1]["POLICYENGINE_SKIP_COUNTRY_IMPORTS"] == "1" + (request,) = uv.requests + assert request["country"] == "uk" + assert request["model_version"] == TARGET_MODEL_VERSION + assert request["core_version"] == CORE_VERSION + assert request["sample_size"] == SAMPLE_HOUSEHOLDS + assert request["headline_variables"] == list(HEADLINE_VARIABLES["uk"]) + assert request["artifacts"][UK_DATASET]["year"] == 2024 + assert Path(request["artifacts"][UK_DATASET]["path"]).is_file() + + def test__given_column_the_new_model_dropped__then_refuses( + self, tmp_path, monkeypatch + ): + with pytest.raises(CompatibilityCheckError, match=DROPPED_COLUMN): + _check(tmp_path, monkeypatch) + + def test__given_h5_bytes_differ_from_manifest__then_refuses( + self, tmp_path, monkeypatch + ): + with pytest.raises(CompatibilityCheckError, match="SHA-256"): + _check(tmp_path, monkeypatch, manifest_h5_sha256="0" * 64) + + def test__given_wheel_bytes_differ_from_pypi__then_refuses( + self, tmp_path, monkeypatch + ): + with pytest.raises(CompatibilityCheckError, match="wheel"): + _check(tmp_path, monkeypatch, wheel_sha256="0" * 64) + + def test__given_the_builds_own_model__then_refuses(self, tmp_path, monkeypatch): + with pytest.raises(CompatibilityCheckError, match="built with"): + _check(tmp_path, monkeypatch, model_version=BUILD_MODEL_VERSION) + + def test__given_build_records_no_core__then_refuses(self, tmp_path, monkeypatch): + manifest = _uk_manifest("0" * 64, built_with_core_package=None) + + with pytest.raises(CompatibilityCheckError, match="core"): + _check(tmp_path, monkeypatch, manifest=manifest) + + def test__given_microdata_without_sha256__then_refuses(self, tmp_path, monkeypatch): + manifest = _uk_manifest("0" * 64) + manifest.artifacts[UK_DATASET].sha256 = None + + with pytest.raises(CompatibilityCheckError, match="sha256"): + _check(tmp_path, monkeypatch, manifest=manifest) + + def test__given_zero_total__then_refuses(self, tmp_path, monkeypatch): + result = { + "model_version": TARGET_MODEL_VERSION, + "core_version": CORE_VERSION, + "policyengine_version": "6.20.5", + "variables": [*TARGET_VARIABLES, DROPPED_COLUMN], + "inputs": TARGET_INPUTS, + "input_aliases": {}, + "artifacts": { + UK_DATASET: { + "households": 3, + "sample_households": 3, + "sample_household_ids_sha256": household_ids_sha256([1, 2, 3]), + "totals": {**UK_TOTALS, "housing_benefit": 0.0}, + } + }, + } + + with pytest.raises(CompatibilityCheckError, match="housing_benefit"): + _check(tmp_path, monkeypatch, uv=FakeUv(probe_result=result)) + + def test__given_probe_ran_another_model__then_refuses(self, tmp_path, monkeypatch): + result = { + "model_version": "2.180.1", + "core_version": CORE_VERSION, + "policyengine_version": "6.20.5", + "variables": [*TARGET_VARIABLES, DROPPED_COLUMN], + "inputs": TARGET_INPUTS, + "input_aliases": {}, + "artifacts": {}, + } + + with pytest.raises(CompatibilityCheckError, match="2.180.1"): + _check(tmp_path, monkeypatch, uv=FakeUv(probe_result=result)) + + def test__given_sample_smaller_than_expected__then_refuses( + self, tmp_path, monkeypatch + ): + result = { + "model_version": TARGET_MODEL_VERSION, + "core_version": CORE_VERSION, + "policyengine_version": "6.20.5", + "variables": [*TARGET_VARIABLES, DROPPED_COLUMN], + "inputs": TARGET_INPUTS, + "input_aliases": {}, + "artifacts": { + UK_DATASET: { + "households": 3, + "sample_households": 2, + "sample_household_ids_sha256": household_ids_sha256([1, 2]), + "totals": dict(UK_TOTALS), + } + }, + } + + with pytest.raises(CompatibilityCheckError, match="sample"): + _check(tmp_path, monkeypatch, uv=FakeUv(probe_result=result)) + + @pytest.mark.parametrize( + ("change", "reason"), + [ + ("no_policyengine_version", "policyengine_version"), + ("entry_not_a_mapping", UK_DATASET), + ("no_sample_digest", "sample_household_ids_sha256"), + ], + ) + def test__given_malformed_probe_result__then_refuses_with_a_reason( + self, tmp_path, monkeypatch, change, reason + ): + result = { + "model_version": TARGET_MODEL_VERSION, + "core_version": CORE_VERSION, + "policyengine_version": "6.20.5", + "variables": [*TARGET_VARIABLES, DROPPED_COLUMN], + "inputs": TARGET_INPUTS, + "input_aliases": {}, + "artifacts": { + UK_DATASET: { + "households": 3, + "sample_households": 3, + "sample_household_ids_sha256": household_ids_sha256([1, 2, 3]), + "totals": dict(UK_TOTALS), + } + }, + } + if change == "no_policyengine_version": + del result["policyengine_version"] + elif change == "entry_not_a_mapping": + result["artifacts"][UK_DATASET] = "not a mapping" + else: + del result["artifacts"][UK_DATASET]["sample_household_ids_sha256"] + + with pytest.raises(CompatibilityCheckError, match=reason): + _check(tmp_path, monkeypatch, uv=FakeUv(probe_result=result)) + + def test__given_core_version__then_runs_that_core(self, tmp_path, monkeypatch): + uv = FakeUv( + target_variables=[*TARGET_VARIABLES, DROPPED_COLUMN], + probe_result=None, + ) + uv.probe_result = { + "model_version": TARGET_MODEL_VERSION, + "core_version": "3.35.0", + "policyengine_version": "6.20.5", + "variables": [*TARGET_VARIABLES, DROPPED_COLUMN], + "inputs": TARGET_INPUTS, + "input_aliases": {}, + "artifacts": { + UK_DATASET: { + "households": 3, + "sample_households": 3, + "sample_household_ids_sha256": household_ids_sha256([1, 2, 3]), + "totals": dict(UK_TOTALS), + } + }, + } + + record, uv, _ = _check(tmp_path, monkeypatch, uv=uv, core_version="3.35.0") + + assert record.core_version == "3.35.0" + assert "policyengine-core==3.35.0" in uv.commands[1] + + +class TestCompatibilityRecords: + def _record(self, **overrides) -> CompatibilityRecord: + payload = { + "country": "uk", + "manifest_uri": UK_MANIFEST_URI, + "manifest_sha256": MANIFEST_SHA256, + "release": None, + "build": UK_TAG, + "built_with_model_version": BUILD_MODEL_VERSION, + "built_with_core_version": CORE_VERSION, + "model_package": { + "name": "policyengine-uk", + "version": TARGET_MODEL_VERSION, + "wheel_sha256": _sha256(WHEEL_BYTES), + "wheel_url": WHEEL_URL, + }, + "core_version": CORE_VERSION, + "policyengine_version": "6.20.5", + "sample": { + "method": SAMPLE_METHOD, + "salt": SAMPLE_SALT, + "size": SAMPLE_HOUSEHOLDS, + }, + "headline_variables": list(HEADLINE_VARIABLES["uk"]), + "artifacts": { + UK_DATASET: { + "path": f"{UK_DATASET}.h5", + "revision": UK_TAG, + "sha256": "a" * 64, + "year": 2024, + "households": 3, + "sample_households": 3, + "sample_household_ids_sha256": "b" * 64, + "totals": UK_TOTALS, + } + }, + "never_modelled_columns": [], + "defaulted_inputs": [], + "checked_at": "2026-12-03T00:00:00Z", + **overrides, + } + return CompatibilityRecord.model_validate(payload) + + def _binding(self, **overrides) -> dict: + return { + "country": "uk", + "manifest_sha256": MANIFEST_SHA256, + "build": UK_TAG, + "model_package": "policyengine-uk", + "model_version": TARGET_MODEL_VERSION, + "wheel_sha256": _sha256(WHEEL_BYTES), + "core_version": CORE_VERSION, + **overrides, + } + + def test__given_unknown_field__then_refuses(self): + with pytest.raises(ValueError): + self._record(note="unexpected") + + def test__given_matching_binding__then_no_problems(self): + assert compatibility_record_problems(self._record(), **self._binding()) == [] + + @pytest.mark.parametrize( + ("field", "value"), + [ + ("manifest_sha256", "f" * 64), + ("build", "another-build"), + ("model_version", "2.181.0"), + ("wheel_sha256", "f" * 64), + ("core_version", "3.35.0"), + ], + ) + def test__given_other_binding__then_names_the_field(self, field, value): + problems = compatibility_record_problems( + self._record(), **self._binding(**{field: value}) + ) + + assert len(problems) == 1 + assert problems[0].startswith(f"{field}:") + + def test__given_unknown_expected_value__then_it_is_a_problem(self): + problems = compatibility_record_problems( + self._record(), **self._binding(wheel_sha256=None) + ) + + assert len(problems) == 1 + assert problems[0].startswith("wheel_sha256:") + + def test__given_records__then_finds_the_matching_one(self): + other = self._record(build="another-build") + record = self._record() + + assert ( + matching_compatibility_record([other, record], **self._binding()) is record + ) + assert matching_compatibility_record([other], **self._binding()) is None + + def test__given_records__then_round_trips_through_the_country_file(self, tmp_path): + path = compatibility_records_path(tmp_path, "uk") + record = self._record() + + write_compatibility_records(path, "uk", [record]) + + assert path == tmp_path / "compatibility" / "uk.json" + assert read_compatibility_records(path, "uk") == [record] + assert json.loads(path.read_text())["country"] == "uk" + + def test__given_no_records__then_removes_the_country_file(self, tmp_path): + path = compatibility_records_path(tmp_path, "uk") + write_compatibility_records(path, "uk", [self._record()]) + + write_compatibility_records(path, "uk", []) + + assert not path.exists() + assert read_compatibility_records(path, "uk") == [] + + def test__given_file_for_another_country__then_refuses(self, tmp_path): + path = compatibility_records_path(tmp_path, "uk") + write_compatibility_records(path, "uk", [self._record()]) + + with pytest.raises(ValueError, match="us"): + read_compatibility_records(path, "us") + + +class TestProbe: + def test__given_lookup_replaced__then_model_constructor_gets_a_placeholder( + self, monkeypatch + ): + from policyengine.tax_benefit_models.common import model_version + + # Restored when the test ends. + monkeypatch.setattr( + model_version, + "certify_data_release_compatibility", + model_version.certify_data_release_compatibility, + ) + + replace_certificate_lookup() + certificate = model_version.certify_data_release_compatibility( + "uk", runtime_model_version="2.180.0", runtime_data_build_fingerprint=None + ) + + assert certificate.compatibility_basis == CHECK_IN_PROGRESS_BASIS + assert certificate.certified_for_model_version == "2.180.0" + + def test__given_output__then_weights_each_variable_by_its_entity(self): + output = SimpleNamespace( + data=SimpleNamespace( + household=pd.DataFrame( + { + "household_net_income": [10.0, 20.0], + "household_weight": [2.0, 3.0], + } + ), + person=pd.DataFrame( + {"income_tax": [1.0, 4.0, 5.0], "person_weight": [1.0, 1.0, 2.0]} + ), + ) + ) + + totals = weighted_totals( + output, {"household_net_income": "household", "income_tax": "person"} + ) + + assert totals == {"household_net_income": 80.0, "income_tax": 15.0} + + def test__given_request__then_samples_simulates_and_reports( + self, tmp_path, monkeypatch + ): + household_ids = [float(household_id) for household_id in range(1, 2501)] + dataset = SimpleNamespace( + data=SimpleNamespace( + household=pd.DataFrame({"household_id": household_ids}) + ) + ) + created = [] + simulated = [] + + def create_datasets(datasets, years, data_folder, allow_unmanaged): + created.append((datasets, years, data_folder, allow_unmanaged)) + return {"source_2024": dataset} + + model = SimpleNamespace( + get_variable=lambda name: SimpleNamespace( + entity="person" if name == "income_tax" else "household" + ) + ) + + def simulate(dataset_argument, model_argument, sample, variables_by_entity): + simulated.append((dataset_argument, sample, variables_by_entity)) + return SimpleNamespace( + data=SimpleNamespace( + household=pd.DataFrame( + { + "household_net_income": [1.0] * len(sample), + "household_weight": [2.0] * len(sample), + } + ), + person=pd.DataFrame({"income_tax": [3.0], "person_weight": [1.0]}), + ) + ) + + monkeypatch.setattr( + compatibility_probe, + "installed_version", + lambda package: { + "policyengine-uk": TARGET_MODEL_VERSION, + "policyengine-core": CORE_VERSION, + "policyengine": "6.20.5", + }[package], + ) + result = run_probe( + { + "country": "uk", + "model_package": "policyengine-uk", + "model_version": TARGET_MODEL_VERSION, + "core_version": CORE_VERSION, + "headline_variables": ["household_net_income", "income_tax"], + "sample_size": SAMPLE_HOUSEHOLDS, + "artifacts": { + UK_DATASET: {"path": str(tmp_path / "source.h5"), "year": 2024} + }, + "data_folder": str(tmp_path / "datasets"), + "result_path": str(tmp_path / "result.json"), + }, + load_country=lambda country: (create_datasets, model), + model_surface=lambda version, package: (["a", "b"], ["a"], {}), + simulate=simulate, + ) + + sample = sample_household_ids(household_ids) + assert created == [ + ( + [str(tmp_path / "source.h5")], + [2024], + str(tmp_path / "datasets" / UK_DATASET), + True, + ) + ] + (simulated_call,) = simulated + assert simulated_call[1] == sample + assert simulated_call[2] == { + "household": ["household_net_income"], + "person": ["income_tax"], + } + assert result["model_version"] == TARGET_MODEL_VERSION + assert result["core_version"] == CORE_VERSION + assert result["policyengine_version"] == "6.20.5" + assert result["variables"] == ["a", "b"] + assert result["inputs"] == ["a"] + assert result["input_aliases"] == {} + assert result["artifacts"][UK_DATASET] == { + "households": 2500, + "sample_households": SAMPLE_HOUSEHOLDS, + "sample_household_ids_sha256": household_ids_sha256(sample), + "totals": { + "household_net_income": 2.0 * SAMPLE_HOUSEHOLDS, + "income_tax": 3.0, + }, + } + + def test__given_another_core_installed__then_refuses(self, tmp_path, monkeypatch): + monkeypatch.setattr( + compatibility_probe, + "installed_version", + lambda package: { + "policyengine-uk": TARGET_MODEL_VERSION, + "policyengine-core": "3.35.0", + "policyengine": "6.20.5", + }[package], + ) + + with pytest.raises(compatibility_probe.CompatibilityProbeError, match="3.35.0"): + run_probe( + { + "country": "uk", + "model_package": "policyengine-uk", + "model_version": TARGET_MODEL_VERSION, + "core_version": CORE_VERSION, + "headline_variables": [], + "sample_size": SAMPLE_HOUSEHOLDS, + "artifacts": {}, + "data_folder": str(tmp_path), + "result_path": str(tmp_path / "result.json"), + }, + load_country=lambda country: (None, None), + model_surface=lambda version, package: ([], [], {}), + simulate=lambda *args: None, + )