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