diff --git a/README.md b/README.md index b90c6c2564..b899afb91e 100644 --- a/README.md +++ b/README.md @@ -705,17 +705,18 @@ only its tag, so existing builds' references keep working. read: at `main` from `releases///`, or at the tag from `releases//`. -**No release publishes with tags.** `microcosm-publish-release` (and -`tools/publish_release.sh`, a thin wrapper that passes every argument straight -through) refuses every release that publishes into build folders and any -repository that has `releases.json`, so it publishes no UK or US release. -The UK repository's switch moved the June 2023 build, which `latest.json` -named, into its own folder as the only and current build of release -`populace-uk-2023`; `microcosm.data.load("uk", 2023)` reads it there, and no -new builds publish to that release. `populace-uk---k` releases -have no publication path in the UK repository since its switch: the emitter -command takes only the releases above, and the tagged publisher refuses -a repository that has `releases.json`. A US annual-projection build publishes +**No release publishes with tags.** Every release that +`publishes_to_build_folder` names publishes each build into its own folder +with `microcosm-publish-release-build`, and no other release publishes. The +tagged publisher, +`microcosm-publish-release`, which committed, tagged and wrote `latest*.json` +pointer files on the Hub directly, has been removed, with +`tools/publish_release.sh`. The UK repository's switch moved the June 2023 +build, which `latest.json` named, into its own folder as the only and current +build of release `populace-uk-2023`; `microcosm.data.load("uk", 2023)` reads it +there, and no new builds publish to that release. +`populace-uk---k` releases have no publication path: the +emitter command takes only the releases above. A US annual-projection build publishes into `microcosm-us-2024-annual`, carrying its base national build's files ([the annual guide](docs/us-annual-static-aging.md)); its base is a calibrated national build, not yet a source enrichment. An annual projection @@ -950,14 +951,10 @@ The US switch deleted every `latest*.json` file, so `microcosm.data.latest_evidence_release`, which still reads `latest-evidence.json`, finds no pointer in the US repository. -The tagged publisher posts a Slack alert when it moves `latest.json`, and only -when the channel's incoming-webhook URL is set (`SLACK_WEBHOOK_POPULACE_US`, -`SLACK_WEBHOOK_POPULACE_UK`), which `tools/publish_release.sh` loads from -`tools/release.env` and warns about when neither is set. It publishes no UK or -US release since the two repositories' switches, so no publication reads -either variable: the calibration diagnostics dashboard posts every UK and US -release alert from changes to `releases.json`. `tools/release.env` still -holds the UK release key below; create it once on the build machine: +No release command posts a Slack alert: `microcosm-publish-release-build` +sends none, and the calibration diagnostics dashboard posts release alerts +from changes to `releases.json`. `tools/release.env` holds the UK release key +below; create it once on the build machine: ```bash cp tools/release.env.example tools/release.env # then fill in the values diff --git a/changelog.d/remove-tagged-publisher.removed.md b/changelog.d/remove-tagged-publisher.removed.md new file mode 100644 index 0000000000..6b1d19506e --- /dev/null +++ b/changelog.d/remove-tagged-publisher.removed.md @@ -0,0 +1 @@ +Remove the tagged publisher, `microcosm-publish-release` (`microcosm.data.publish_cli` and `tools/publish_release.sh`), which committed a release's files to Hugging Face directly, tagged them and wrote a `latest*.json` pointer file. It refused every repository that records its builds in `releases.json`, which the US, UK and BE release repositories all do, so release builds now publish only into their own folders, through the emitter with `microcosm-publish-release-build`. `publish_release`, `prepare_release` and `PreparedRelease` leave `microcosm.data.release`, `microcosm.data` no longer exports `publish_release`, and `microcosm.data.slack`, whose only caller was `publish_release`, is gone with the Slack webhook settings in `tools/release.env.example`. `publication_refusal`, which `microcosm-publish-release-build` runs, moves to `microcosm.data.release`. No command publishes a release that `publishes_to_build_folder` does not name (#1796). diff --git a/docs/agent-guide.md b/docs/agent-guide.md index 45f8d6735f..360d334d20 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -392,14 +392,12 @@ package stage prints both commands itself. need no calibration on the base before a build, and again with the finished build's `--release-manifest`. The emitter changes no current build while any `latest*.json` pointer file exists; the UK and US -repositories' switches to `releases.json` deleted them. The tagged publisher -(`tools/publish_release.sh` → `microcosm-publish-release`) refuses every one of -these releases and any repository that has `releases.json`, so no UK or US -release publishes with tags. The UK repository's switch moved the June 2023 UK -build into release `populace-uk-2023`, which takes no new builds, and -`populace-uk---k` releases have no publication path there. This -holds for the US from its repository's switch commit; Microcosm's US change -(microcosm#1570) merges straight after it. Tests hand release changes to the +repositories' switches to `releases.json` deleted them. No release publishes +with tags: the tagged publisher (`microcosm-publish-release`) has been +removed, and `microcosm-publish-release-build` takes only the releases that +`publishes_to_build_folder` names. The UK repository's switch moved the June +2023 UK build into release `populace-uk-2023`, which takes no new builds, and +`populace-uk---k` releases have no publication path. Tests hand release changes to the in-memory client (`client.release_requests`), which applies them to `hub_files` with the interface's shared `releases.json` checks. See README "Releasing & alerts". Before launching a US @@ -633,12 +631,14 @@ and writes local annual H5 files without running the base graph or publishing. See [the annual candidate guide](us-annual-static-aging.md). Its completion manifest is build evidence, not release certification. Optional annual release metadata invokes additional artifact, identity, and -acceptance checks alongside the normal release checks. Annual builds pin every file -to one `-annual--` tag, and a build folder -pins no revision, so an annual build has no publication path in the US -repository since its switch to `releases.json`: the tagged publisher refuses -that repository. Qualify source-enrichment bases before adding annual metadata, -in the candidate guide's qualification order. +acceptance checks alongside the normal release checks. An annual build of the +tagged layout pins every file to one +`-annual--` tag, so it has no publication +path: a build folder pins no revision, and the tagged publisher, which took +such builds, has been removed. A new annual build is a build of +`microcosm-us-2024-annual` in its own folder, pins no revision and publishes +with `microcosm-publish-release-build`. Qualify source-enrichment bases before +adding annual metadata, in the candidate guide's qualification order. ## Concept schema and engine mappings diff --git a/docs/release-contract.md b/docs/release-contract.md index e768e5c378..00c76e90a6 100644 --- a/docs/release-contract.md +++ b/docs/release-contract.md @@ -26,12 +26,12 @@ milestone the plan assigns it to, and the [enforcement timeline](#enforcement-timeline) records how far each milestone had got by that date. -The ruling set 2026-11-06 for publishing to start refusing. On 2026-11-12 both -publication commands, `microcosm-publish-release-build` and the tagged -publisher `microcosm-publish-release`, refuse a build that fails today's C1 -(`validate_release_dir`, or its evidence sibling) or that recorded staging it -never delivered (today's C3, `publication_refusal`). Max decides when the -version-1 refusals of C1 to C4 start. +The ruling set 2026-11-06 for publishing to start refusing. The publication +command, `microcosm-publish-release-build`, refuses a build that fails today's +C1 (`validate_release_dir`, or its evidence sibling) or that recorded staging +it never delivered (today's C3, `publication_refusal`). On 2026-11-12 the +tagged publisher `microcosm-publish-release`, since removed, refused them too. +Max decides when the version-1 refusals of C1 to C4 start. This document replaces `docs/us-uk-release-path.md`, a planning snapshot that never reached main. The snapshot's last version (363a9033b, 2026-09-15) lives @@ -126,7 +126,7 @@ repository. | --- | --- | --- | --- | --- | | C1 | Release manifest and certification | The release directory's files, both manifests, and a certification that the certifier composes from gate-battery reports | `validate_release_dir` (`microcosm/data/contract.py`), which `prepare_build_folder_release` runs before every build-folder publication; a build of `microcosm-us-2024-evidence` answers to `validate_evidence_release_dir` instead | `v1/c1/` | | C2 | Loader compatibility | One rule admitting a model and Core version against a release | `microcosm.data.loader` and policyengine.py, separately | none | -| C3 | Staging telemetry and run outcome | How a build records and delivers its end | `publication_refusal` (`microcosm/data/publish_cli.py`), through `_staging_undelivered`, in both publication commands | the staging fixtures | +| C3 | Staging telemetry and run outcome | How a build records and delivers its end | `publication_refusal` (`microcosm/data/release.py`), through `_staging_undelivered`, in `microcosm-publish-release-build` | the staging fixtures | | C4 | Logbook | One durable row per terminal build attempt | nothing at publication | none | | C5 | Publish and registry | The build-folder layout, `releases.json`, release names and the registry | `microcosm-publish-release-build` (`publish_release_build` and `promote_release_build` in `microcosm.build.release_publication`), `prepare_build_folder_release`, `publishes_to_build_folder`, the emitter's release writer, `parse_releases_record` and `microcosm.data.registry` | `v1/c5/` | @@ -140,8 +140,7 @@ command that publishes a build runs it, or its evidence-tier sibling `microcosm-publish-release-build` runs it through `prepare_build_folder_release` for every build it publishes except a build of `microcosm-us-2024-evidence`, which answers to the evidence contract instead. -Before it validates anything, the tagged publisher's `prepare_release` refuses -any release that publishes into build folders. Promotion +No other command publishes a build. Promotion (`microcosm-publish-release-build --promote`, through `promote_release_build`) uploads no file and runs no contract: it reads the release and the build that the local release manifest names. @@ -362,8 +361,8 @@ both: any other name, for publication and promotion alike: its `main` checks `publishes_to_build_folder` before anything else, and `build_folder_identity` refuses the same names inside `publish_release_build` and - `promote_release_build`. So only the tagged publisher accepts a new country's - release. `line_for_release_id` still knows only + `promote_release_build`. So no command publishes a new country's release + until it joins `publishes_to_build_folder`. `line_for_release_id` still knows only `microcosm-uk-2024-25-national` and `microcosm-uk-2024-25-local-k`. Its remaining callers serve pointer files: `latest_line_release`, which the loader's pointer reader calls, and `line_pointer_payload`, which no publisher @@ -729,21 +728,20 @@ unchanged. (`start_bundle_emitter`): `tools/stage_uk_rowwise_candidate.py`, `tools/run_uk_cut.py` and `microcosm-publish-release-build`, which hands a release build to it. -- **The publish gate.** `publish_cli.publication_refusal` holds the checks - every publication shares: non-release smoke output, a reform validation that - skipped its out-of-sample reforms, and undelivered staging - (`_staging_undelivered`). Both publication commands run it before they check - the build's release contract: `microcosm-publish-release-build`, once it has - confirmed that the release publishes into build folders, and - `microcosm-publish-release`, the tagged publisher. `_staging_undelivered` +- **The publication checks.** `publication_refusal` (`microcosm.data.release`) + holds the checks that run before a build's release contract: non-release + smoke output, a reform validation that skipped its out-of-sample reforms, + and undelivered staging (`_staging_undelivered`). + `microcosm-publish-release-build` runs it once it has confirmed that the + release publishes into build folders. `_staging_undelivered` refuses a build whose manifest records staging the build intended but never delivered: an empty block, a version-2 record in `local_only` mode or with a failed read-back, or an enabled run with no successful upload. It passes a disabled record with a non-empty reason as an opt-out. It also passes a manifest with no `staging` key, and a US ACS-local build publishes that way. - `--allow-missing-staging` overrides the gate on both commands. Neither + `--allow-missing-staging` overrides the staging check. Neither `prepare_build_folder_release` nor the function `publish_release_build` runs - the gate, and promotion (`--promote`) runs none. The Route A candidate in the + these checks, and promotion (`--promote`) runs none. The Route A candidate in the 2026-10-15 table carried the version-1 opt-out. #### Version 1 (planned) @@ -808,8 +806,9 @@ unchanged. folder publishes only its two manifests, its checksum ledger and the artifacts the release manifest declares. The publisher accepts the build only if the receipt's read-back passed and its digest matches the shipped - `progress.json`. M3 also moves the delivery gate from the two commands into - `prepare_build_folder_release`, so every publication runs it. + `progress.json`. M3 also moves the staging delivery check from + `microcosm-publish-release-build` into `prepare_build_folder_release`, so + every publication runs it. - The build folder ships the build's staging version-3 terminal document (its `progress.json`) as an artifact that `release_manifest.json` names, and `build_manifest.json` binds it by digest. The build manifest records the @@ -907,7 +906,8 @@ repository that has no `releases.json`. source coverage (`_check_be_release_artifacts`). The function reads the registry on each call. `validate_release_dir` and `validate_evidence_release_dir` refuse every layout of a local-area name - that no entry names, and neither publisher takes one (microcosm#1586). + that no entry names, and `microcosm-publish-release-build` takes none + (microcosm#1586). `microcosm-us-2024-national` holds every national build: calibrated builds, SPM source enrichments, compatibility recertifications and exact-k builds. `microcosm-us-2024-local` holds the ACS local-area @@ -994,24 +994,17 @@ repository that has no `releases.json`. one that still has a `latest*.json` pointer file, and a build folder the record does not list. Each tagged build stays readable at its tag, and each deleted file stays in `main`'s history. -- **The tagged publisher and the pointer files.** `microcosm-publish-release` - (`publish_cli`, which `tools/publish_release.sh` wraps) still publishes a - release that keeps tags. It runs `publication_refusal`, then - `publish_release`. That function runs `prepare_release` (the release contract - and the pointer and tag guards), then `require_parent_publication` for a - recertification, then uploads the release files, creates the immutable tag - and writes `latest.json` or `latest-evidence.json` last. Each pointer is a - schema-1 JSON document at the repository root; `latest.json` holds - `schema_version`, `release_id`, `updated_at`, and `paths` to the contract - files (`latest_pointer_payload`). Only a `national_default` release whose tag - is its own id may move `latest.json`, and never a reported-receipt source - enrichment or a recertification. The tagged publisher refuses by release name - and by repository state: `prepare_release` refuses every release that - `publishes_to_build_folder` names, and `publish_release` refuses every - repository that has `releases.json` (`_refuse_releases_record`; only the - Hub's answer that the file is absent lets it go on). Nothing writes - `latest-.json`: `publish_release` takes no line, although - `line_pointer_payload` remains. Three readers of pointer files remain. The +- **The pointer files.** Nothing writes a pointer file. The tagged publisher, + `microcosm-publish-release`, which uploaded a tagged build's files, created + its immutable tag and wrote `latest.json` or `latest-evidence.json` last, has + been removed, with `tools/publish_release.sh`. Each pointer is a schema-1 + JSON document at the repository root; `latest.json` holds `schema_version`, + `release_id`, `updated_at`, and `paths` to the contract files. The payload + builders remain: the readers (through `_read_pointer`) and + `_current_evidence_build` call `latest_pointer_payload` to name the files a + pointer or an evidence build holds, and only tests call + `line_pointer_payload` and `latest_evidence_pointer_payload`. Three readers + of pointer files remain. The loader follows `latest.json` (`latest_release`) or `latest-.json` (`latest_line_release`) only for an entry whose repository has no `releases.json`. `latest_evidence_release` returns the evidence release's @@ -1101,12 +1094,13 @@ work. and an annual or local-annual build takes `-annual--`. - **Every country and line publishes into build folders.** A new country's release joins `publishes_to_build_folder` and the registry in the pull - request that authorizes its first publication. The gaps on 2026-11-12: - - *A new country's tagged publish.* Nothing refuses it: the tagged - publisher accepts any release outside `publishes_to_build_folder`, except - a UK local-area name that the registry does not name, into a repository - without `releases.json`. M3's refusal of unknown countries closes the gap, - under M3's owners. + request that authorizes its first publication. The gaps on 2026-11-12, with + what has changed since: + - *A new country's tagged publish.* On 2026-11-12 nothing refused it: the + tagged publisher accepted any release outside `publishes_to_build_folder` + into a repository without `releases.json` (from 2026-11-14, microcosm#1586, + except a UK local-area name that the registry does not name). Since #1796 + removed the tagged publisher, no command publishes such a release. - *The NZ and AM declarations.* Each country's `release_contract.json` (under `packages/microcosm-build/src/microcosm/build/`) names `latest.json` in its boundary. Each country's owner changes its file @@ -1132,17 +1126,16 @@ work. and `load` raises because `releases.json` does not list the release. `line_for_release_id` keeps its pattern, because the pointer reader still calls it. - - *The tagged publisher.* `microcosm-publish-release` and - `tools/publish_release.sh` stay installed and sit on the - [retire list](#retire-list-as-of-2026-10-15). Their removal waits on the - refusal of a new country's tagged publish. Loading a tagged build that - never moved into a folder stays. + - *The tagged publisher.* On 2026-11-12 `microcosm-publish-release` and + `tools/publish_release.sh` stayed installed and sat on the + [retire list](#retire-list-as-of-2026-10-15); #1796 removed them. Loading a + tagged build that never moved into a folder stays. - *Pointer readers.* The loader's fallback (`DatasetSpec.pointer_path`, `latest_release`, `latest_line_release`) and the `latest-evidence.json` fallback in `latest_evidence_release` still resolve through `latest*.json`. `microcosm.data` still exports `latest_release`, which reads `latest.json` - without looking for `releases.json`, and `publish_release`, which writes - it. They leave once no registered repository lacks `releases.json`. The + without looking for `releases.json`; until #1796 it also exported + `publish_release`, which wrote it. They leave once no registered repository lacks `releases.json`. The plan names no owner or milestone for them yet. - *The policyengine.py certification tool.* `tools/certify_uk_cut_in_policyengine_py.py` still reads a national @@ -1480,7 +1473,7 @@ release and the tagged publisher joined the table on 2026-11-11. | `format_uk_release_id`, `apply_uk_release_identity` | This milestone deletes them, with `UKReleaseIdentity`, which builds on `format_uk_release_id`: none had a caller outside its own tests and the `uk_runtime` re-export. The tier vocabulary and the line ids stay | On main none has a caller outside its own tests and the `uk_runtime` re-export | | Stale text, microcosm.institute `/calibration`, the evidence tier | A separate task owns them (task_d2b70813) | Not read again. For the evidence tier, see the next row | | The US evidence release, `microcosm-us-2024-evidence` | On this list since 2026-10-15, as the evidence tier | A named exception: version 1 neither admits it to the contract nor retires it. microcosm#1571 made it a standing release in `US_RELEASES`, with the `national` role. `tools/certify_us_national_build.py --evidence-release` places its builds there: a build has no tier, and certification chooses it (microcosm#1585 item 11). `prepare_build_folder_release` checks them with `validate_evidence_release_dir`; they carry schema `1-evidence` and fail C1's certified contract by design. The registry names no entry for it, so `microcosm.data.load` never serves it. No module under `packages/*/src` or `tools/` calls `latest_evidence_release`. Whoever retires the release must first find, from code, the readers of the evidence release and of `latest_evidence_release` | -| The tagged publisher: `microcosm-publish-release` and `tools/publish_release.sh` | Not on the report's list | On the list from 2026-11-11. It refuses every release that `publishes_to_build_folder` names and every repository that has `releases.json`. Its removal waits on the refusal of a new country's tagged publish (C5 version 1, M3). Loading a tagged build that never moved into a folder stays | +| The tagged publisher: `microcosm-publish-release` and `tools/publish_release.sh` | Not on the report's list | On the list from 2026-11-11. Since then removed (#1796), once the US, UK and BE repositories all recorded their builds in `releases.json`: the command, the wrapper, `publish_release`, `prepare_release` and the Slack alert only `publish_release` sent. No command publishes a release that `publishes_to_build_folder` does not name. Loading a tagged build that never moved into a folder stays | | microcosm-benchmarks, the calibration-diagnostics evaluation harness, policyengine-data's calibrate module | Each lives in another repository; proposed as a separate task (task_18c2af98) | Not read again | | cos d816 | Ruled 2026-10-09 (per-country Core pins, microcosm#1143) | The same | | cos d928 | Parked; its 2026-10-10 note records it resolved on main (the plan-2 exclusions renewed to 2026-11-03). Nothing to rule | Still parked. On main the plan-2 exclusions read approved on 2026-10-23 and expire on 2027-01-23 | diff --git a/packages/microcosm-build/src/microcosm/build/release_publication.py b/packages/microcosm-build/src/microcosm/build/release_publication.py index 1e21296f93..a7fc538a81 100644 --- a/packages/microcosm-build/src/microcosm/build/release_publication.py +++ b/packages/microcosm-build/src/microcosm/build/release_publication.py @@ -18,9 +18,9 @@ refuses, before any emitter starts, while any pointer file is there: in a repository without ``releases.json`` it says the switch has not run, since the loader follows those files and the switch reads them, and in one with -it, that the file appeared after the switch and should be removed. The -tagged publisher refuses these releases, and any repository that has -``releases.json``. +it, that the file appeared after the switch and should be removed. No +other command publishes a release: the tagged publisher, which committed, +tagged and wrote pointer files on the Hub directly, is gone. ``microcosm-withdraw-release-build`` (:func:`withdraw_release_build`) names a published build by its repository, release and build and hands its @@ -122,13 +122,13 @@ is_be_release, publishes_to_build_folder, ) -from microcosm.data.publish_cli import publication_refusal from microcosm.data.release import ( TAGGED_RELEASE_ADVICE, BuildFolderRelease, build_folder_identity, not_a_build_folder_release_reason, prepare_build_folder_release, + publication_refusal, ) from microcosm.data.releases_record import RELEASES_RECORD_PATH @@ -636,8 +636,7 @@ def _refuse_recertification_as_current(release_dir: Path | str) -> None: """Refuse to make a compatibility recertification its release's current build. A recertification republishes its parent's data under a wider - compatibility claim. As with the tagged publisher, which never moved - ``latest.json`` to one, it is published without becoming current, and + compatibility claim, so it is published without becoming current, and consumers load it with ``build=``. """ from microcosm.data import compatibility_recertification @@ -674,8 +673,8 @@ def publish_release_build( emitter starts, when the repository still has ``latest*.json`` pointer files; it hands nothing over unless the emitter's write-access check passes. A recertification is handed over only once the Hub shows its - parent published with the manifest it carries, as the tagged publisher - required, and never with ``make_current``. Once the publication has + parent published with the manifest it carries, and never with + ``make_current``. Once the publication has landed, it waits at most ``collector_wait_seconds`` for the collector to accept the build's submissions. """ @@ -982,9 +981,9 @@ def _claim_records(release_dir: Path) -> dict[str, Any]: def _print_claim_records(records: Mapping[str, Any]) -> None: - """Say a build's compatibility records on stderr, as the tagged command - did, on the preflight and on publication, which needs no preflight - first; the preflight's verdict on stdout carries them too.""" + """Say a build's compatibility records on stderr, on the preflight and + on publication, which needs no preflight first; the preflight's verdict + on stdout carries them too.""" if "narrowed_claims" in records: print( "note: this build records a compatibility narrowing from an " diff --git a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py index 5bc00641a1..2e2f2f4b42 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py @@ -179,7 +179,6 @@ "microcosm.data.registry", "microcosm.data.release", "microcosm.data.releases_record", - "microcosm.data.slack", "microcosm.data.source_enrichment", "microcosm.data.stored_inputs", "microcosm.data.us_critical_targets", diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py index a9c654483a..d2e8659c5a 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py @@ -7163,7 +7163,6 @@ def _run_green_register_release( _check_us_stored_input_evidence, stored_input_evidence_manifest_block, ) - from microcosm.data.release import _release_manifest_release_artifacts release_dir = out / "releases" / builder.US_NATIONAL_RELEASE_ID # The build's own directory: a build has no tier, so certification places @@ -7688,7 +7687,9 @@ def record_certified_contract(directory, *, artifact_root=None): evidence_tier=False, ) assert failures == [] - assert set(bound.values()) <= set(_release_manifest_release_artifacts(release_dir)) + assert set(bound.values()) <= set( + _declared_artifacts_in_build_directory(release_dir) + ) assert not list(release_dir.glob("final_household_weight*")) @@ -13910,7 +13911,6 @@ def test_build_manifests_selects_ssi_social_security_holdout_for_publication( _check_local_artifact_hashes, _check_release_manifest, ) - from microcosm.data.release import _release_manifest_release_artifacts builder = _load_builder_module() release_id, release_dir, artifact_root = _gate_evidence_release_dir( @@ -13952,7 +13952,7 @@ def score_holdout(name, consumer, **kwargs): "revision": release_id, "sha256": hashlib.sha256(holdout_path.read_bytes()).hexdigest(), } - assert filename in _release_manifest_release_artifacts(release_dir) + assert filename in _declared_artifacts_in_build_directory(release_dir) failures: list[str] = [] _check_release_manifest(manifest, release_id, failures) _check_local_artifact_hashes(release_dir, manifest, failures) @@ -13972,7 +13972,6 @@ def test_build_manifests_selects_medicare_irmaa_holdout_for_publication( _check_local_artifact_hashes, _check_release_manifest, ) - from microcosm.data.release import _release_manifest_release_artifacts builder = _load_builder_module() release_id, release_dir, artifact_root = _gate_evidence_release_dir( @@ -14015,7 +14014,7 @@ def score_holdout(name, consumer, **kwargs): "revision": release_id, "sha256": hashlib.sha256(holdout_path.read_bytes()).hexdigest(), } - assert filename in _release_manifest_release_artifacts(release_dir) + assert filename in _declared_artifacts_in_build_directory(release_dir) failures: list[str] = [] _check_release_manifest(manifest, release_id, failures) _check_local_artifact_hashes(release_dir, manifest, failures) @@ -14034,6 +14033,29 @@ def _write_scf_education_debt_fits(builder, monkeypatch, release_dir, filenames) ) +def _declared_artifacts_in_build_directory(release_dir: Path) -> set[str]: + """The files a build's release manifest declares that are in the build's + own directory, from which build-folder publication reads them.""" + manifest = json.loads((release_dir / "release_manifest.json").read_text()) + return { + entry["path"] + for entry in manifest["artifacts"].values() + if (release_dir / entry["path"]).is_file() + } + + +def _declared_artifacts_outside_build_directory(release_dir: Path) -> set[str]: + """The files a build's release manifest declares that are not in the + build's own directory, which build-folder publication reads from the + artifact root.""" + manifest = json.loads((release_dir / "release_manifest.json").read_text()) + return { + entry["path"] + for entry in manifest["artifacts"].values() + if not (release_dir / entry["path"]).is_file() + } + + SCF_EDUCATION_DEBT_FIT_ARTIFACT_PATHS = { "us_scf_education_debt_fit": "us_scf_education_debt_fit.json", "us_scf_education_debt_calibrated_fit": "us_scf_education_debt_calibrated_fit.json", @@ -14052,10 +14074,6 @@ def test_build_manifests_lists_scf_education_debt_fits_only_with_the_flag( _check_local_artifact_hashes, _check_release_manifest, ) - from microcosm.data.release import ( - _release_manifest_release_artifacts, - _release_manifest_root_artifacts, - ) builder = _load_builder_module() assert builder.US_SCF_EDUCATION_DEBT_FIT_ARTIFACTS == ( @@ -14077,8 +14095,8 @@ def test_build_manifests_lists_scf_education_debt_fits_only_with_the_flag( for key, entry in manifest["artifacts"].items() if entry["path"] in filenames } - published = set(_release_manifest_release_artifacts(release_dir)) - assert not filenames & set(_release_manifest_root_artifacts(release_dir)) + published = set(_declared_artifacts_in_build_directory(release_dir)) + assert not filenames & set(_declared_artifacts_outside_build_directory(release_dir)) if not flag: assert listed == {} assert not filenames & published @@ -14266,7 +14284,6 @@ def test_build_manifests_selects_population_structure_holdout_for_publication( _check_local_artifact_hashes, _check_release_manifest, ) - from microcosm.data.release import _release_manifest_release_artifacts builder = _load_builder_module() release_id, release_dir, artifact_root = _gate_evidence_release_dir( @@ -14320,7 +14337,7 @@ def test_build_manifests_selects_population_structure_holdout_for_publication( "revision": release_id, "sha256": hashlib.sha256(holdout_path.read_bytes()).hexdigest(), } - assert filename in _release_manifest_release_artifacts(release_dir) + assert filename in _declared_artifacts_in_build_directory(release_dir) failures: list[str] = [] _check_release_manifest(manifest, release_id, failures) _check_local_artifact_hashes(release_dir, manifest, failures) @@ -14364,7 +14381,6 @@ def test_build_manifests_binds_gate_evidence_and_the_qrf_tail_register( _check_us_stored_input_evidence, stored_input_evidence_manifest_block, ) - from microcosm.data.release import _release_manifest_release_artifacts builder = _load_builder_module() receipt = { @@ -14488,7 +14504,7 @@ def test_build_manifests_binds_gate_evidence_and_the_qrf_tail_register( ) assert contract_failures == [] assert set(builder.US_RELEASE_GATE_EVIDENCE_FILES.values()) <= set( - _release_manifest_release_artifacts(release_dir) + _declared_artifacts_in_build_directory(release_dir) ) # ...and its local hash check covers each file: an edited verdict fails. for key, filename in builder.US_RELEASE_GATE_EVIDENCE_FILES.items(): diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_receipt_enrichment_release.py b/packages/microcosm-build/tests/engine_free/us/test_us_receipt_enrichment_release.py index cc1b2d606c..efdc551695 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_receipt_enrichment_release.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_receipt_enrichment_release.py @@ -148,7 +148,6 @@ def test_the_donor_is_a_build_of_its_own_release_never_the_national_default( ) -> None: _build(lineage) certified = _certify(lineage, monkeypatch, []) - monkeypatch.setattr(publisher, "_hf_api", lambda: pytest.fail("use no Hub")) # The release contract replays the H5 comparison and the loader checks, # which take the parent H5 and the tested wheels. options = {"parent_h5": lineage.parent, "compatibility_wheels": _WHEELS} @@ -170,11 +169,6 @@ def test_the_donor_is_a_build_of_its_own_release_never_the_national_default( contract.RECEIPT_DATASET_FILENAME: _artifacts(lineage) / contract.RECEIPT_DATASET_FILENAME } - # The tag publisher, which writes latest.json, refuses it. - with pytest.raises(ValueError, match="microcosm-publish-release-build"): - publisher.prepare_release( - certified, artifact_root=_artifacts(lineage), **options - ) # The same build named as a build of the national release is refused: it # is not that release's lineage, and its file is not that release's # dataset file. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_publication.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_publication.py index 88279a8484..d7bd84b2e4 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_publication.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_publication.py @@ -188,6 +188,35 @@ def prepare(path, **kwargs): assert passed["compatibility_wheels"] == (wheel,) +def test_the_preflight_lists_the_release_contract_warnings( + tmp_path, monkeypatch, capsys +) -> None: + """The preflight's verdict lists the release contract's warnings and still + passes: a warning never refuses a build (microcosm#1301, review of + microcosm#1307).""" + release_dir = tmp_path / "microcosm-us-2024-national" + release_dir.mkdir() + contract_warnings = ("synthetic.json carries a synthetic finding",) + + def prepare(path, **_kwargs): + prepared = _prepared(path) + prepared.contract_warnings = contract_warnings + return prepared + + monkeypatch.setattr( + release_publication, "publication_refusal", lambda *_a, **_k: None + ) + monkeypatch.setattr(release_publication, "prepare_build_folder_release", prepare) + + exit_code = release_publication.main([str(release_dir), "--preflight-only"]) + + assert exit_code == 0 + verdict = json.loads(capsys.readouterr().out) + assert verdict["valid"] is True + assert verdict["published"] is False + assert verdict["contract_warnings"] == list(contract_warnings) + + def test_a_recertification_is_handed_over_only_once_its_parent_is_published( tmp_path, monkeypatch ) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_spm_role_enrichment_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_spm_role_enrichment_builder.py index 93239a6dee..c9ce200729 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_spm_role_enrichment_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_spm_role_enrichment_builder.py @@ -17,7 +17,7 @@ from microcosm.data import source_enrichment as contract from microcosm.data.contract import US_NATIONAL_RELEASE_ID from microcosm.data.h5_enrichment import file_sha256 -from microcosm.data.publish_cli import _staging_undelivered +from microcosm.data.release import _staging_undelivered from tools import build_us_spm_role_enrichment as builder pytest.importorskip("tables") @@ -450,7 +450,6 @@ def check_synthetic_producer(code): monkeypatch.setattr( contract, "_check_producer_source_identity", check_synthetic_producer ) - monkeypatch.setattr(publisher, "_hf_api", lambda: pytest.fail("must not use Hub")) certified = contract.certify_source_enrichment( candidate_release, tmp_path / "certified" / US_NATIONAL_RELEASE_ID, diff --git a/packages/microcosm-data/pyproject.toml b/packages/microcosm-data/pyproject.toml index 7aabadc6b4..5de8a1e9bb 100644 --- a/packages/microcosm-data/pyproject.toml +++ b/packages/microcosm-data/pyproject.toml @@ -19,9 +19,6 @@ dependencies = [ [tool.uv.sources] microcosm-diagnostics = { workspace = true } -[project.scripts] -microcosm-publish-release = "microcosm.data.publish_cli:main" - # Country engines are optional: install the one(s) you load. The extra name is # the country slug, matching the registry key and the loader's error message. [project.optional-dependencies] diff --git a/packages/microcosm-data/src/microcosm/data/__init__.py b/packages/microcosm-data/src/microcosm/data/__init__.py index 50c06c2cfd..f9727ae1c1 100644 --- a/packages/microcosm-data/src/microcosm/data/__init__.py +++ b/packages/microcosm-data/src/microcosm/data/__init__.py @@ -54,7 +54,6 @@ latest_evidence_release, latest_pointer_payload, latest_release, - publish_release, ) __all__ = [ @@ -88,7 +87,6 @@ "latest_evidence_release", "latest_pointer_payload", "latest_release", - "publish_release", ] __version__ = "0.1.0" diff --git a/packages/microcosm-data/src/microcosm/data/compatibility_recertification.py b/packages/microcosm-data/src/microcosm/data/compatibility_recertification.py index ac29455a45..753103e41e 100644 --- a/packages/microcosm-data/src/microcosm/data/compatibility_recertification.py +++ b/packages/microcosm-data/src/microcosm/data/compatibility_recertification.py @@ -918,8 +918,9 @@ def _publishable_parent_path(path: str) -> bool: """Whether the publisher wrote a parent artifact at ``path``. A release file is uploaded to the parent's directory and a root artifact - to its own path; neither publisher writes into another release's - directory, or outside the repository. + to its own path; neither ``microcosm-publish-release-build`` nor the + removed tagged publisher, which published older parents, writes into + another release's directory, or outside the repository. """ return not ( diff --git a/packages/microcosm-data/src/microcosm/data/contract.py b/packages/microcosm-data/src/microcosm/data/contract.py index 6ed61309f2..20fed6bbdb 100644 --- a/packages/microcosm-data/src/microcosm/data/contract.py +++ b/packages/microcosm-data/src/microcosm/data/contract.py @@ -376,9 +376,10 @@ def publishes_to_build_folder(release_id: str) -> bool: def unregistered_uk_local_release(release_id: str) -> bool: """Whether ``release_id`` is a UK local-area name that no registry entry names. - No layout of such a release validates and neither publisher takes it: the - pull request that authorizes a ``k``'s first publication adds its registry - entry, and its builds then publish into build folders. + No layout of such a release validates and + ``microcosm-publish-release-build`` refuses it: the pull request that + authorizes a ``k``'s first publication adds its registry entry, and its + builds then publish into build folders. """ return _is_uk_local_release_name(release_id) and not _uk_registry_entry_names( release_id diff --git a/packages/microcosm-data/src/microcosm/data/publish_cli.py b/packages/microcosm-data/src/microcosm/data/publish_cli.py deleted file mode 100644 index d748e58375..0000000000 --- a/packages/microcosm-data/src/microcosm/data/publish_cli.py +++ /dev/null @@ -1,423 +0,0 @@ -"""CLI for contract-checked Microcosm release publication. - -It publishes releases that keep the tagged layout and ``latest.json``. It -publishes no UK, US or BE release: the UK national, dense and local-area -releases, the US releases (``microcosm.data.contract.US_RELEASES``) and BE's -releases (``microcosm.data.contract.BE_RELEASES``) publish -each build into its own folder through the emitter -(``microcosm-publish-release-build``), and this command refuses them. It also -refuses any repository that records its builds in ``releases.json``, as the -UK and US repositories do after their switches. The UK switch moves the June -2023 build into a build folder of release ``populace-uk-2023`` and leaves -``populace-uk---k`` releases with no publication path. -""" - -from __future__ import annotations - -import argparse -import json -import sys -from pathlib import Path - -from microcosm.data.release import prepare_release, publish_release - - -def _non_release_artifact(release_dir: Path) -> bool: - """Return whether the manifest explicitly identifies non-release output.""" - - path = release_dir / "build_manifest.json" - if not path.exists(): - return False - try: - manifest = json.loads(path.read_text()) - except (OSError, ValueError): - return False - return isinstance(manifest, dict) and ( - manifest.get("non_release") is True - or manifest.get("release_posture") == "non_release_smoke" - ) - - -def _staging_undelivered(release_dir: Path) -> bool: - """True if a build that should have staged has nothing to show for it. - - The gate is scoped by the presence of the ``staging`` key. Builders with - no staging path are untouched, while an explicit ``enabled: false`` is a - legitimate opt-out. A present but empty block, or an enabled run with no - successful upload, records intended staging that never arrived. - - A US national build is certified as a step of its own (microcosm#1585 - item 11): the ``staging`` block is its certification's, and the build's - own rides inside it under ``build``. Both must have arrived or been - declared opted out, so a build whose own uploads never arrived is - refused as it was before the split, however its certification staged. - """ - path = release_dir / "build_manifest.json" - if not path.exists(): - return False - try: - manifest = json.loads(path.read_text()) - except (OSError, ValueError): - return False - if not isinstance(manifest, dict) or "staging" not in manifest: - return False - staging = manifest["staging"] - if not isinstance(staging, dict) or "build" not in staging: - return _staging_block_undelivered(staging) - certification = {key: value for key, value in staging.items() if key != "build"} - return _staging_block_undelivered(certification) or _staging_block_undelivered( - staging["build"] - ) - - -def _staging_block_undelivered(staging: object) -> bool: - """True if one staging block records intended staging that never arrived.""" - - if not isinstance(staging, dict) or not staging: - return True - if "contract_version" in staging: - return _version_2_staging_undelivered(staging) - if staging.get("enabled") is False: - return not bool(staging.get("reason")) - return not staging.get("uploads_succeeded") - - -def _version_2_staging_undelivered(staging: dict[str, object]) -> bool: - """Validate publication-relevant version 2 delivery semantics.""" - - required = { - "contract_version", - "enabled", - "mode", - "run_id", - "configured_repository", - "upload_attempts", - "upload_successes", - "read_back", - "last_error_code", - "opt_out_reason", - } - if set(staging) != required or staging.get("contract_version") != 2: - return True - enabled = staging.get("enabled") - mode = staging.get("mode") - run_id = staging.get("run_id") - repository = staging.get("configured_repository") - attempts = staging.get("upload_attempts") - successes = staging.get("upload_successes") - read_back = staging.get("read_back") - error_code = staging.get("last_error_code") - reason = staging.get("opt_out_reason") - if ( - not isinstance(enabled, bool) - or isinstance(attempts, bool) - or not isinstance(attempts, int) - or attempts < 0 - or isinstance(successes, bool) - or not isinstance(successes, int) - or successes < 0 - or successes > attempts - or read_back not in {"not_requested", "passed", "failed"} - or (error_code is not None and not isinstance(error_code, str)) - ): - return True - if not enabled: - return not ( - mode == "disabled" - and run_id is None - and repository is None - and attempts == 0 - and successes == 0 - and read_back == "not_requested" - and error_code is None - and isinstance(reason, str) - and bool(reason.strip()) - ) - if reason is not None or not isinstance(run_id, str) or not run_id: - return True - if mode == "local_only": - return True - if ( - mode != "local_and_remote" - or not isinstance(repository, str) - or not repository.strip() - ): - return True - if read_back == "passed": - return successes == 0 or error_code is not None - if read_back == "failed": - return True - if error_code not in {None, "UPLOAD_FAILED"}: - return True - return successes == 0 - - -def _reform_validation_skipped(release_dir: Path) -> bool: - """True if the release carries a reform_validation.json that was built with - out-of-sample reforms skipped (``out_of_sample_simulated`` false). - - Such a release publishes blank out-of-sample (OBBBA) rows on the dashboard, - indistinguishable from a real result — so publishing one is refused unless - explicitly allowed. Absent/unreadable file or a true flag → not skipped. - """ - path = release_dir / "reform_validation.json" - if not path.exists(): - return False - try: - payload = json.loads(path.read_text()) - except (OSError, ValueError): - return False - return payload.get("out_of_sample_simulated") is False - - -def publication_refusal( - release_dir: Path, - *, - allow_incomplete_reform_validation: bool = False, - allow_missing_staging: bool = False, -) -> str | None: - """Why a release must not be published, read from its local files, or None. - - The checks every publication path shares: non-release smoke output, a - reform validation built with out-of-sample reforms skipped, and staging - telemetry that never arrived. Each override flag lifts one check. - """ - if _non_release_artifact(release_dir): - return ( - "refusing to publish: build_manifest.json identifies this as " - "non-release smoke output." - ) - if not allow_incomplete_reform_validation and _reform_validation_skipped( - release_dir - ): - return ( - "refusing to publish: reform_validation.json has " - "out_of_sample_simulated=false (built with " - "--skip-out-of-sample-reforms), so the dashboard would show blank " - "out-of-sample reforms. Rebuild without skipping, or pass " - "--allow-incomplete-reform-validation to publish anyway." - ) - if not allow_missing_staging and _staging_undelivered(release_dir): - return ( - "refusing to publish: this release's build_manifest records no " - "delivered staging telemetry for the build (for a build " - "certified separately: for its certification, or for the build " - "itself under staging.build), so the build never appeared on the " - "staging dashboard and there is no pre-publication review of it. " - "Either the staging destination was lost mid-build (uploads " - "pause after repeated failures — check the build machine's " - "Hugging Face write token), or the manifest predates staging " - "provenance. Rebuild with staging reaching its repo, or pass " - "--allow-missing-staging to publish anyway. A build that declared " - "--no-staging publishes without the flag." - ) - return None - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("release_dir", help="Local releases/ directory.") - parser.add_argument( - "--repo-id", - default="policyengine/populace-us", - help="Hugging Face dataset repo id.", - ) - parser.add_argument( - "--artifact-root", - help=( - "Directory holding root artifacts named by release_manifest.json, " - "for example populace_us_2024.h5." - ), - ) - parser.add_argument( - "--parent-h5", - type=Path, - help="Exact certified parent H5 required for source-enrichment publication.", - ) - parser.add_argument( - "--compatibility-wheel", - action="append", - type=Path, - default=[], - help="Exact installed country/Core/wrapper/calculator wheel; repeat for all four packages. Candidate wheels may be tested before publication.", - ) - parser.add_argument( - "--preflight-only", - action="store_true", - help="Run all local publisher guards, including enrichment loader tests, without constructing a Hub client or publishing.", - ) - parser.add_argument( - "--create-tag", - action="store_true", - default=True, - help=( - "Create a Hugging Face tag for the immutable release before any " - "main-branch update." - ), - ) - parser.add_argument( - "--no-create-tag", - action="store_false", - dest="create_tag", - help=( - "Skip creating a Hugging Face tag. Refused when the release " - "manifest pins artifacts to the release id." - ), - ) - parser.add_argument( - "--tag-name", - help="Optional tag name override; defaults to the release id.", - ) - parser.add_argument( - "--extra-file", - action="append", - default=[], - help="Additional release-dir file to include in the immutable release.", - ) - parser.add_argument( - "--updated-at", - help="Optional latest.json timestamp override for reproducible tests.", - ) - parser.add_argument( - "--no-latest", - action="store_true", - help=( - "Publish as a non-default release: upload files and create the " - "immutable tag, but never touch latest.json (the default pointer)." - ), - ) - parser.add_argument( - "--tag-only", - action="store_true", - help=( - "Publish only the immutable tag revision, without any main-branch " - "commit. Requires --no-latest and tag creation; used by exact-k " - "ladder candidates." - ), - ) - parser.add_argument( - "--allow-incomplete-reform-validation", - action="store_true", - help=( - "Publish even if reform_validation.json was built with out-of-sample " - "reforms skipped (out_of_sample_simulated false). Off by default so a " - "release never silently ships blank OBBBA validation." - ), - ) - parser.add_argument( - "--allow-missing-staging", - action="store_true", - help=( - "Publish even if the build recorded no staging telemetry, or " - "recorded staging that never uploaded anything. Off by default so " - "a release that never appeared on the staging dashboard is not " - "shipped unnoticed. A declared --no-staging build publishes " - "without this flag." - ), - ) - parser.add_argument( - "--evidence", - action="store_true", - help=( - "Publish at the EVIDENCE tier (microcosm#506): validate against the " - "evidence release contract (which requires a non-empty " - "known_failures block) and move latest-evidence.json instead of " - "latest.json. Structurally never touches the certified pointer; a " - "certified-shape release is refused under this flag." - ), - ) - args = parser.parse_args(argv) - - if args.tag_only and not args.no_latest: - parser.error("--tag-only requires --no-latest.") - if args.tag_only and not args.create_tag: - parser.error("--tag-only requires tag creation; remove --no-create-tag.") - - refusal = publication_refusal( - Path(args.release_dir), - allow_incomplete_reform_validation=args.allow_incomplete_reform_validation, - allow_missing_staging=args.allow_missing_staging, - ) - if refusal is not None: - print(refusal, file=sys.stderr) - return 1 - - preparation_options = dict( - artifact_root=Path(args.artifact_root) if args.artifact_root else None, - parent_h5=args.parent_h5, - compatibility_wheels=tuple(args.compatibility_wheel), - create_tag=args.create_tag, - tag_name=args.tag_name, - extra_files=tuple(args.extra_file), - update_latest=not args.no_latest, - tag_only=args.tag_only, - evidence=args.evidence, - ) - from microcosm.data.source_enrichment import ( - recorded_claim_measurement, - recorded_narrowed_claims, - ) - - # A re-certification that reverted a declared compatibility range to the - # exact pin warned in the terminal that ran it, days and an operator ago. - # Both paths out of here say so, because publication does not require the - # preflight first: tools/publish_release.sh passes its arguments straight - # through. stdout carries the machine-readable verdict, stderr the record - # for whoever is reading the terminal. - narrowed = recorded_narrowed_claims(Path(args.release_dir)) - if narrowed: - print( - "note: this release records a compatibility narrowing from an " - f"earlier certification: {json.dumps(narrowed)}", - file=sys.stderr, - ) - # A declared compatibility range admits model versions no check measured. - # The bundle records which one was; say it on the same two paths. A - # recertification records the measured version, its baseline and the - # drift summary the declarer read. - from microcosm.data import compatibility_recertification - - measurement = recorded_claim_measurement( - Path(args.release_dir) - ) or compatibility_recertification.recorded_claim_measurement( - Path(args.release_dir) - ) - if measurement: - print( - "note: this release declares a publisher compatibility range that " - "certification measured against only the versions recorded here: " - f"{json.dumps(measurement)}", - file=sys.stderr, - ) - if args.preflight_only: - prepared = prepare_release(Path(args.release_dir), **preparation_options) - preflight = {"valid": True, "published": False} - if narrowed: - preflight["narrowed_claims"] = narrowed - if measurement: - preflight["claim_measurement"] = measurement - # The contract's warnings never refuse, so the verdict carries them - # for whatever parses stdout; each names a file and paths in it, - # never a value. Publication's printed pointer carries them the same - # way. - if prepared.contract_warnings: - preflight["contract_warnings"] = list(prepared.contract_warnings) - print(json.dumps(preflight)) - return 0 - - pointer = publish_release( - Path(args.release_dir), - args.repo_id, - **preparation_options, - updated_at=args.updated_at, - ) - print(json.dumps(pointer, indent=2)) - - # The Slack release alert now fires inside publish_release (coupled to the - # promotion, so every publish path announces the release), warning loudly if - # the webhook is unset. Nothing to do here. - return 0 - - -if __name__ == "__main__": # pragma: no cover - raise SystemExit(main()) diff --git a/packages/microcosm-data/src/microcosm/data/registry.py b/packages/microcosm-data/src/microcosm/data/registry.py index bd043fc601..471c7142b0 100644 --- a/packages/microcosm-data/src/microcosm/data/registry.py +++ b/packages/microcosm-data/src/microcosm/data/registry.py @@ -195,7 +195,8 @@ def register(spec: DatasetSpec) -> DatasetSpec: # builds in releases.json. The pull request that authorizes a k's first # publication adds its registry entry (docs/release-contract.md, C5). # microcosm.data.contract.publishes_to_build_folder admits the release only -# once an entry here names it, and both publishers refuse it before then. +# once an entry here names it, and microcosm-publish-release-build refuses it +# before then. register( DatasetSpec( diff --git a/packages/microcosm-data/src/microcosm/data/release.py b/packages/microcosm-data/src/microcosm/data/release.py index 920b0ed30a..7e8b9e2070 100644 --- a/packages/microcosm-data/src/microcosm/data/release.py +++ b/packages/microcosm-data/src/microcosm/data/release.py @@ -1,60 +1,46 @@ -"""Publish a release and move its approved repository pointer. - -**No UK, US or BE release publishes here.** The UK national and dense -releases, each UK local-area release that the dataset registry names, the US -releases (:data:`~microcosm.data.contract.US_RELEASES`) and BE's releases -(:data:`~microcosm.data.contract.BE_RELEASES`) publish each build into its -own folder, ``releases///``, through the emitter's -``publish_release`` call (``microcosm-publish-release-build``, in -``microcosm-build``), and the repository's ``releases.json`` records which -build is current. :func:`prepare_build_folder_release` checks such a build -and lists its files with their roles; :func:`prepare_release` and -:func:`publish_release` refuse it. :func:`publish_release` also refuses any -repository that records its builds in ``releases.json``, as the UK and US -repositories do after their switches, so the June 2023 UK release and -``populace-uk---k`` releases take no new builds. Everything -below describes the tagged layout, which builds that keep only their tag -still have. - -The Hub repo publishes builds under ``releases//``, but nothing -identified which release is *current*: a consumer had to list the tree and -guess, and because build ids end in a date (``populace-us-2024-9f1260b- -20260611``), two builds published the same day have no defined ordering. -``latest.json`` at the repo root is that missing pointer — a tiny manifest -naming the current release and the path of each of its contract files. - -Two sides of the pointer live here: - -- :func:`publish_release` is the producer: it validates the local release - directory against the :mod:`release contract ` - (a release that fails the contract refuses to publish), uploads its - files, and either stops at an immutable tag (the exact-k candidate lane) or - uploads ``latest.json`` **last** — so a reader never sees the pointer before - the release it points at. -- :func:`latest_release` is the consumer: it downloads ``latest.json`` and - returns the typed pointer, the one-call answer to "which release is - current?" for dashboards and scorers. - -The UK national and local-area releases were made current through pointer -files named ``latest-.json``. Those schema-1 pointers add the fields -``line`` and ``revision``, so each could name an immutable per-build tag -without changing the frozen repository-global ``latest.json``. Nothing -writes them any more; -:func:`latest_line_release` still reads them until they are deleted. - -The EVIDENCE tier (microcosm#506) published through the same producer with -``evidence=True``: identical immutable-tag mechanics, but the pointer that -moves is ``latest-evidence.json`` — structurally never ``latest.json`` — -and :func:`latest_evidence_release` is its consumer. Since the US switch, an -evidence-tier build is a build of +"""Check a release build before it publishes, and read release pointer files. + +A release publishes each build into its own folder, +``releases///``, when +:func:`~microcosm.data.contract.publishes_to_build_folder` names it: the UK +national and dense releases, each UK local-area release that the dataset +registry names, the US releases +(:data:`~microcosm.data.contract.US_RELEASES`) and BE's releases +(:data:`~microcosm.data.contract.BE_RELEASES`). +``microcosm-publish-release-build`` (``microcosm.build.release_publication``, +in ``microcosm-build``) hands each build to the emitter's ``publish_release`` +call, and the repository's ``releases.json`` records which build is current. +Before it does, :func:`publication_refusal` refuses non-release smoke output, +a reform validation that skipped its out-of-sample reforms and staging that +never arrived, and :func:`prepare_build_folder_release` checks the build +against its release contract and lists its files with their roles. Nothing +here writes to the Hub. No command publishes a release that +``publishes_to_build_folder`` does not name: the June 2023 UK release and +``populace-uk---k`` releases take no new builds, and a new +country's releases join it in the pull request that authorizes their first +publication. + +Before each repository switched to ``releases.json``, its builds were +published under ``releases//`` with a tag each, and a +``latest.json`` pointer file at its root named the current release and the +path of each of its contract files. The tagged publisher that wrote those +pointer files is gone; the readers here still follow them. +:func:`latest_release` reads ``latest.json`` and returns the typed pointer, +and :func:`latest_line_release` reads the schema-1 ``latest-.json`` +pointers that made the UK national and local-area releases current. Those +add the fields ``line`` and ``revision``, so each could name an immutable +per-build tag without changing the repository-global ``latest.json``. + +The EVIDENCE tier (microcosm#506) moved ``latest-evidence.json``, never +``latest.json``, and :func:`latest_evidence_release` reads it. Since the US +switch, an evidence-tier build is a build of :data:`~microcosm.data.contract.US_EVIDENCE_RELEASE_ID` instead, whose current build in ``releases.json`` takes the place of ``latest-evidence.json``. The switch deleted every ``latest*.json`` file, and :func:`latest_evidence_release` reads that current build instead. -The Hub client is injected (``api=``) everywhere it is used, so the suite -exercises the real branch, commit, tag, and pointer ordering against a fake — -no network and no mocking of our own internals. +The Hub client is injected (``api=``) everywhere it is used, so the tests +read pointers from a fake Hub, with no network. """ from __future__ import annotations @@ -68,7 +54,6 @@ from dataclasses import dataclass from datetime import UTC, datetime from pathlib import Path -from typing import Any from microcosm.data.contract import ( BE_RELEASES, @@ -84,7 +69,6 @@ _uk_line_cut_tag_re, line_for_release_id, publishes_to_build_folder, - release_dataset_role, required_release_files, unregistered_uk_local_release, validate_evidence_release_dir, @@ -95,7 +79,6 @@ build_folder, parse_releases_record, ) -from microcosm.data.slack import notify_release __all__ = [ "BUILD_FOLDER_PUBLICATION_COMMAND", @@ -110,10 +93,8 @@ "TAGGED_RELEASE_ADVICE", "UNREGISTERED_UK_LOCAL_RELEASE_ADVICE", "LatestPointer", - "PreparedRelease", "build_folder_identity", "prepare_build_folder_release", - "prepare_release", "latest_evidence_pointer_payload", "latest_line_release", "latest_pointer_payload", @@ -121,7 +102,7 @@ "missing_on_hub", "not_a_build_folder_release_reason", "line_pointer_payload", - "publish_release", + "publication_refusal", "latest_release", "latest_evidence_release", ] @@ -134,8 +115,6 @@ LINE_POINTER_PATH_TEMPLATE = "latest-{line}.json" _LINE_RE = re.compile(r"^[a-z]+(-k[1-9][0-9]*)?$") -_RESERVED_POINTER_PATH_RE = re.compile(r"^latest(-[a-z0-9-]+)?\.json$") - #: The evidence-tier pointer (microcosm#506): which evidence release is the #: best *current* one. A separate file at the repo root, so certified #: consumers reading ``latest.json`` (and the pe.py certification path built @@ -300,31 +279,12 @@ def _hf_api(): from huggingface_hub import HfApi except ImportError as exc: # pragma: no cover - declared dependency raise ImportError( - "microcosm-data needs huggingface_hub to publish releases; " + "microcosm-data needs huggingface_hub to read release pointers; " "reinstall microcosm-data with its dependencies." ) from exc return HfApi() -@dataclass(frozen=True) -class PreparedRelease: - """Validated local paths and upload destinations, prepared without Hub activity. - - ``contract_warnings`` are the release contract's warnings, which never - refuse a release; each names a file and paths in it, never a value. - """ - - release_dir: Path - artifact_root: Path | None - release_id: str - tag: str - filenames: list[str] - root_artifacts: dict[str, str] - pointer_path: str - calibration_diagnostics_available: bool - contract_warnings: tuple[str, ...] = () - - #: Where a build-folder release publishes from: the workspace command that #: hands each build to the emitter (``microcosm.build.release_publication``). BUILD_FOLDER_PUBLICATION_COMMAND = "microcosm-publish-release-build" @@ -346,8 +306,8 @@ class PreparedRelease: ) -#: Why neither publisher takes a UK local-area release that the dataset -#: registry does not name. +#: Why ``microcosm-publish-release-build`` refuses a UK local-area release +#: that the dataset registry does not name. UNREGISTERED_UK_LOCAL_RELEASE_ADVICE = ( "The dataset registry (microcosm.data.registry.REGISTRY) names no UK " "local-area release with this k. The pull request that authorizes a k's " @@ -366,21 +326,6 @@ def not_a_build_folder_release_reason(release_id: str) -> str: return f"release {release_id!r} does not publish into build folders. {advice}" -def _refuse_build_folder_release(release_id: str) -> None: - if unregistered_uk_local_release(release_id): - raise ValueError( - f"release {release_id!r} publishes through no publisher yet. " - + UNREGISTERED_UK_LOCAL_RELEASE_ADVICE - ) - if publishes_to_build_folder(release_id): - raise ValueError( - f"release {release_id!r} publishes each build into its own folder " - "through the emitter, which also records it in releases.json; " - f"publish it with `{BUILD_FOLDER_PUBLICATION_COMMAND}`. This " - "publisher commits, tags and writes latest*.json pointer files." - ) - - @dataclass(frozen=True) class BuildFolderFile: """One file of a build folder: its bare name, role, local path and digest.""" @@ -602,510 +547,197 @@ def prepare_build_folder_release( ) -def prepare_release( - release_dir: Path | str, - *, - artifact_root: Path | str | None = None, - parent_h5: Path | str | None = None, - compatibility_wheels: tuple[Path | str, ...] = (), - create_tag: bool = True, - tag_name: str | None = None, - extra_files: tuple[str, ...] = (), - update_latest: bool = True, - tag_only: bool = False, - evidence: bool = False, -) -> PreparedRelease: - """Run every local publisher guard and collect the files to upload. - - Shared by CLI preflight and publication. Arguments have the same meaning - as in :func:`publish_release`; validation only reads the local bundle and - replays any required source-enrichment compatibility checks. No Hub client - is constructed, no Hub activity occurs, and no release alert is sent. - Publication must prepare again so preflight cannot authorize stale inputs. - A release that publishes into build folders is refused first. - """ - release_dir = Path(release_dir) - _refuse_build_folder_release(release_dir.name) - _refuse_misplaced_parent_inputs(release_dir, parent_h5, compatibility_wheels) - contract_warnings: list[str] = [] - if evidence: - validate_evidence_release_dir(release_dir) - elif parent_h5 is not None or compatibility_wheels: - contract_warnings = validate_release_dir( - release_dir, - parent_h5=parent_h5, - artifact_root=artifact_root, - compatibility_wheels=compatibility_wheels, - ) - else: - contract_warnings = validate_release_dir( - release_dir, artifact_root=artifact_root - ) - for contract_warning in contract_warnings: - warnings.warn(f"release contract: {contract_warning}", stacklevel=2) - release_id = release_dir.name - role = release_dataset_role(release_dir) - pointer_path = LATEST_EVIDENCE_POINTER_PATH if evidence else LATEST_POINTER_PATH - if role != NATIONAL_DEFAULT_DATASET_ROLE and update_latest: - # microcosm#398 defense in depth beyond --no-latest: a non-default - # release can never move the global default pointer, even if a - # caller asks. - raise ValueError( - f"release {release_id!r} declares dataset_role {role!r}; " - "non-default releases publish immutably (tag only) and can " - "never update latest.json. Pass update_latest=False " - "(publish CLI: --no-latest)." - ) - if update_latest and not evidence: - from microcosm.data.source_enrichment import is_receipt_enrichment - - if is_receipt_enrichment(release_dir): - # microcosm#978: the reported-receipt child is a published donor for - # the ACS local chain. Country formulas read its receipt inputs - # (policyengine-us 2.2.1's WIC and SNAP categorical eligibility, - # among others), so it never becomes the default as a side effect. - raise ValueError( - f"release {release_id!r} is a reported-receipt source " - "enrichment: a published donor, never the national default " - "pointer. Pass update_latest=False (publish CLI: --no-latest, " - "with --tag-only to leave main untouched)." - ) - from microcosm.data.compatibility_recertification import is_recertification - - if is_recertification(release_dir): - # A recertification republishes its parent's data under a wider - # compatibility claim, so it never moves the default pointer as a - # side effect; consumers reach it by its release id. - raise ValueError( - f"release {release_id!r} is a compatibility recertification of " - "a published release, never the national default pointer. " - "Pass update_latest=False (publish CLI: --no-latest, with " - "--tag-only to leave main untouched)." - ) - if tag_only and update_latest: - raise ValueError( - "tag_only=True requires update_latest=False; a tag-only publication " - "cannot update latest.json." - ) - if tag_only and not create_tag: - raise ValueError( - "tag_only=True requires create_tag=True; deleting the staging branch " - "without a tag would leave no published revision." - ) - artifact_root = Path(artifact_root) if artifact_root is not None else None - release_manifest = json.loads((release_dir / "release_manifest.json").read_text()) - diagnostics_declaration = release_manifest.get("calibration_diagnostics") - calibration_diagnostics_available = not ( - isinstance(diagnostics_declaration, Mapping) - and diagnostics_declaration.get("status") == "failed" - ) - if not calibration_diagnostics_available: - warnings.warn( - "Publishing a dataset whose calibration diagnostics generation failed: " - f"{diagnostics_declaration.get('error_code')}: " - f"{diagnostics_declaration.get('message')}", - stacklevel=2, - ) +def _non_release_artifact(release_dir: Path) -> bool: + """Return whether the manifest explicitly identifies non-release output.""" - if role == NATIONAL_DEFAULT_DATASET_ROLE: - contract_files = tuple( - filename - for filename in required_release_files(release_id) - if calibration_diagnostics_available - or filename != "calibration_diagnostics.json" - ) - else: - # A non-default release's directory IS its bundle: publishing a - # subset would leave a remote release that fails its own role - # contract (the checksum ledger and sidecars are required files). - contract_files = tuple( - sorted(path.name for path in release_dir.iterdir() if path.is_file()) - ) - release_artifacts = _release_manifest_release_artifacts(release_dir) - filenames = _ordered_unique((*contract_files, *release_artifacts, *extra_files)) - for filename in filenames: - # Every release-dir upload lands at releases// — a name - # carrying path components ('../../latest.json') could escape that - # prefix once the Hub canonicalizes the path. Bare file names only. - if filename in {".", ".."} or "/" in filename or "\\" in filename: - raise ValueError( - f"release file name {filename!r} must be a bare file name; " - "path components cannot ride into the release upload." - ) - local = release_dir / filename - if not local.is_file(): - raise FileNotFoundError( - f"extra release file {filename!r} not found in {release_dir}." - ) - root_artifacts = _release_manifest_root_artifacts(release_dir) - # Root artifacts upload at their manifest-declared repo paths — the one - # surface where a manifest author could smuggle a pointer write past the - # tier's pointer selection. Two layers, both on BOTH tiers: the declared - # path must already be in canonical clean relative form (so './latest.json' - # or 'x/../latest.json' cannot dodge a raw-string comparison and be - # canonicalized by the Hub afterwards), and the canonical pointer paths - # are reserved outright — pointers move only via the publisher's own - # pointer operation. - for path_in_repo in root_artifacts: - if ( - "\\" in path_in_repo - or path_in_repo.startswith("/") - or posixpath.normpath(path_in_repo) != path_in_repo - ): - raise ValueError( - f"release_manifest.json root artifact path {path_in_repo!r} " - "is not a clean relative POSIX path; refusing to upload it." - ) - pointer_collisions = sorted( - path - for path in root_artifacts - if _RESERVED_POINTER_PATH_RE.fullmatch(path) is not None - ) - if pointer_collisions: - raise ValueError( - "release_manifest.json declares root artifact(s) at reserved " - f"pointer path(s) {pointer_collisions}; latest*.json pointers are " - "written only by the publisher itself, never as release artifacts." - ) - artifact_revisions, unreadable_revisions = _release_manifest_artifact_revisions( - release_dir - ) - tag = tag_name or release_id - # These guards must fail closed: an empty revision set may only ever mean - # "no artifacts declared" (which the contract refuses anyway), never - # "artifacts whose pins could not be read" — either silence would publish - # artifacts under a tag their manifest never pinned. - if unreadable_revisions: - raise ValueError( - "release_manifest.json artifacts have missing or non-string " - f"revisions: {sorted(unreadable_revisions)}; every artifact must " - "pin a revision string." - ) - if not artifact_revisions: - raise ValueError( - "release_manifest.json declares no artifact revisions; releases " - "publish only revision-pinned artifacts." - ) - if not create_tag: - raise ValueError( - "release_manifest.json pins artifacts to revisions; " - "publish_release must create the matching Hugging Face tag before " - "updating latest.json." - ) - if artifact_revisions != {tag}: - raise ValueError( - "release_manifest.json pins artifacts to revisions; tag_name must " - "match the release id or uniform per-cut artifact revision." - ) - # The repository-global pointer may only name a release whose immutable tag - # IS the release id. - if update_latest and tag != release_id: - raise ValueError( - f"latest.json may not name per-cut tag {tag!r} for release " - f"{release_id!r}; a tag other than the release id publishes " - "inspect-only. Pass update_latest=False (--no-latest)." - ) - if root_artifacts and artifact_root is None: - raise ValueError( - "release_manifest.json declares root artifacts; pass artifact_root " - "so publish_release can upload and verify them before latest.json." - ) - for path_in_repo, expected_sha in root_artifacts.items(): - if artifact_root is None: # pragma: no cover - guarded above - continue - local = artifact_root / path_in_repo - if not local.is_file(): - raise FileNotFoundError( - f"release artifact {path_in_repo!r} not found under {artifact_root}." - ) - observed_sha = _sha256(local) - if observed_sha != expected_sha: - raise ValueError( - f"release artifact {path_in_repo!r} has sha256 {observed_sha} " - f"but release_manifest.json declares {expected_sha}." - ) - - return PreparedRelease( - release_dir=release_dir, - artifact_root=artifact_root, - release_id=release_id, - tag=tag, - filenames=filenames, - root_artifacts=root_artifacts, - pointer_path=pointer_path, - calibration_diagnostics_available=calibration_diagnostics_available, - contract_warnings=tuple(contract_warnings), + path = release_dir / "build_manifest.json" + if not path.exists(): + return False + try: + manifest = json.loads(path.read_text()) + except (OSError, ValueError): + return False + return isinstance(manifest, dict) and ( + manifest.get("non_release") is True + or manifest.get("release_posture") == "non_release_smoke" ) -def publish_release( - release_dir: Path | str, - repo_id: str, - *, - api=None, - artifact_root: Path | str | None = None, - parent_h5: Path | str | None = None, - compatibility_wheels: tuple[Path | str, ...] = (), - create_tag: bool = True, - tag_name: str | None = None, - extra_files: tuple[str, ...] = (), - updated_at: str | None = None, - update_latest: bool = True, - tag_only: bool = False, - notify: bool = True, - evidence: bool = False, -) -> dict: - """Publish a release directory and optionally point ``latest.json`` at it. - - A release that publishes into build folders (the UK national and dense - releases and each registered UK local-area release) is refused before - any check or Hub call, and so is a UK local-area release that the - registry does not name; see the module docstring. - - The order is the guarantee: the release contract is validated first (an - invalid release never reaches the Hub), then an immutable branch commit is - created with every release file and artifact and tagged. A tag-only publish - stops there. Otherwise, only after that certificate exists does one atomic - main-branch commit update the release copies, mutable root conveniences, - and, for standard publication, ``latest.json`` (the final operation). - Backends without the branch and atomic-commit surface are refused before - any remote mutation. +def _staging_undelivered(release_dir: Path) -> bool: + """True if a build that should have staged has nothing to show for it. - Args: - release_dir: Local ``releases/`` directory. - repo_id: Hub dataset repo, e.g. ``"policyengine/populace-us"``. - api: A ``huggingface_hub.HfApi``-shaped object with branch, atomic - commit, tag, and branch-deletion methods; constructed lazily when - omitted. Non-atomic upload-only backends are refused. - artifact_root: Directory holding root dataset artifacts declared in - ``release_manifest.json`` (for example ``populace_us_2024.h5``). - Contract files are always read from ``release_dir`` and uploaded - under ``releases//``; artifact paths are uploaded to their - manifest-declared repo paths. - parent_h5: Exact certified parent H5 for source-enrichment releases. - The publication gate rereads it and the candidate to prove that - every pre-existing logical variable and metadata field is preserved. - compatibility_wheels: Exact installed country, Core, wrapper, and calculator wheels - used to replay source-enrichment native-loader compatibility checks. - External package publication and numerical model acceptance remain - the release operator's gates. - create_tag: Create an immutable Hub tag for the release snapshot before - updating main. The tag defaults to the release id. This is required - when artifact revisions in ``release_manifest.json`` are pinned to - the release id. - tag_name: Optional tag name override when ``create_tag=True``. - extra_files: Additional filenames in ``release_dir`` to upload - beyond the contract files (e.g. a diagnostics artifact). - updated_at: Pointer timestamp; defaults to now (UTC). - update_latest: Update the production ``latest.json`` pointer after the - immutable release tag is created. ``False`` preserves the legacy - non-default publication behavior: release copies and root artifacts - are still committed to main, but the pointer is not. - tag_only: Publish only the immutable tagged revision, with no main-branch - commit. Requires ``update_latest=False`` and ``create_tag=True``. - This is the exact-k candidate lane; it is separate from legacy - ``update_latest=False`` publication so existing non-default releases - retain their main-branch copies. - notify: Post a best-effort Slack release alert once ``latest.json`` is - live (no-op unless the country ``SLACK_WEBHOOK_MICROCOSM_*`` env var - is set; never fatal). Coupling the alert to the promotion here means - every publish path announces the release, not just the CLI. Only - fires when ``update_latest`` is set — a non-default publish moves no - pointer, so there is no "new latest release" to announce. Set - ``False`` to suppress it (tests, dry-runs, re-publishes). - evidence: Publish at the EVIDENCE tier (microcosm#506). The release - is validated against - :func:`~microcosm.data.contract.validate_evidence_release_dir` - instead of the certified contract, and the pointer that moves is - ``latest-evidence.json`` — this path is structurally incapable of - writing ``latest.json``, so an evidence artifact can never become - the certified default or feed pe.py certification. Tag and upload - mechanics are otherwise identical. ``update_latest`` then governs - the evidence pointer. - - A release published earlier without the pointer (``update_latest=False`` - under the same tag) is pointed to by a later call: the publisher - recognises the existing tag that already describes this release, creates - no second immutable revision, and writes only the main commit carrying - the pointer. The same recognition makes a retry after a failure between - tag creation and the pointer commit safe. - - Returns: - The release's pointer payload (``latest.json`` shape, plus ``tier`` at - the evidence tier). - It is uploaded only when ``update_latest=True``. When the release - contract warned, the returned payload also lists the warnings under - ``contract_warnings``; the uploaded pointer never carries them, and - the message of the tag this call creates records only how many there - were (microcosm#1301). + The check is scoped by the presence of the ``staging`` key. Builders with + no staging path are untouched, while an explicit ``enabled: false`` is a + legitimate opt-out. A present but empty block, or an enabled run with no + successful upload, records intended staging that never arrived. - Raises: - ReleaseContractError: If the release directory violates its tier's - contract. Nothing is uploaded in that case. - FileNotFoundError: If an ``extra_files`` entry does not exist. + A US national build is certified as a step of its own (microcosm#1585 + item 11): the ``staging`` block is its certification's, and the build's + own rides inside it under ``build``. Both must have arrived or been + declared opted out, so a build whose own uploads never arrived is + refused as it was before the split, however its certification staged. """ - prepared = prepare_release( - release_dir, - artifact_root=artifact_root, - parent_h5=parent_h5, - compatibility_wheels=compatibility_wheels, - create_tag=create_tag, - tag_name=tag_name, - extra_files=extra_files, - update_latest=update_latest, - tag_only=tag_only, - evidence=evidence, + path = release_dir / "build_manifest.json" + if not path.exists(): + return False + try: + manifest = json.loads(path.read_text()) + except (OSError, ValueError): + return False + if not isinstance(manifest, dict) or "staging" not in manifest: + return False + staging = manifest["staging"] + if not isinstance(staging, dict) or "build" not in staging: + return _staging_block_undelivered(staging) + certification = {key: value for key, value in staging.items() if key != "build"} + return _staging_block_undelivered(certification) or _staging_block_undelivered( + staging["build"] ) - release_id = prepared.release_id - if api is None: - api = _hf_api() - from microcosm.data.compatibility_recertification import ( - is_recertification, - require_parent_publication, - ) - if is_recertification(prepared.release_dir): - # The offline gates proved the child against the parent manifest it - # carries; only the Hub can say that manifest is the published one. - # Checked before any branch, commit or upload. - require_parent_publication( - api, - prepared.release_dir, - repo_id=repo_id, - artifact_root=prepared.artifact_root, - ) - if evidence: - payload = latest_evidence_pointer_payload( - release_id, - updated_at=updated_at, - calibration_diagnostics_available=( - prepared.calibration_diagnostics_available - ), - ) - pointer_label = "evidence release" - else: - payload = latest_pointer_payload( - release_id, - updated_at=updated_at, - calibration_diagnostics_available=( - prepared.calibration_diagnostics_available - ), - ) - pointer_label = "release" - if create_tag and not callable(getattr(api, "create_tag", None)): - raise TypeError( - "publish_release requires a Hub backend with create_tag support; " - "release manifests pin artifacts to immutable release tags." - ) - if not _supports_atomic_publication(api): - raise TypeError( - "publish_release requires a Hub backend with create_branch, " - "create_commit, create_tag, and delete_branch support so release " - "publication is immutable-first and atomic." +def _staging_block_undelivered(staging: object) -> bool: + """True if one staging block records intended staging that never arrived.""" + + if not isinstance(staging, dict) or not staging: + return True + if "contract_version" in staging: + return _version_2_staging_undelivered(staging) + if staging.get("enabled") is False: + return not bool(staging.get("reason")) + return not staging.get("uploads_succeeded") + + +def _version_2_staging_undelivered(staging: dict[str, object]) -> bool: + """Validate publication-relevant version 2 delivery semantics.""" + + required = { + "contract_version", + "enabled", + "mode", + "run_id", + "configured_repository", + "upload_attempts", + "upload_successes", + "read_back", + "last_error_code", + "opt_out_reason", + } + if set(staging) != required or staging.get("contract_version") != 2: + return True + enabled = staging.get("enabled") + mode = staging.get("mode") + run_id = staging.get("run_id") + repository = staging.get("configured_repository") + attempts = staging.get("upload_attempts") + successes = staging.get("upload_successes") + read_back = staging.get("read_back") + error_code = staging.get("last_error_code") + reason = staging.get("opt_out_reason") + if ( + not isinstance(enabled, bool) + or isinstance(attempts, bool) + or not isinstance(attempts, int) + or attempts < 0 + or isinstance(successes, bool) + or not isinstance(successes, int) + or successes < 0 + or successes > attempts + or read_back not in {"not_requested", "passed", "failed"} + or (error_code is not None and not isinstance(error_code, str)) + ): + return True + if not enabled: + return not ( + mode == "disabled" + and run_id is None + and repository is None + and attempts == 0 + and successes == 0 + and read_back == "not_requested" + and error_code is None + and isinstance(reason, str) + and bool(reason.strip()) ) - # The tag records that the release was published past the contract's - # warnings, and how many, but not the warnings themselves, which name - # paths in the shipped files (microcosm#1301). - warned = len(prepared.contract_warnings) - tag_message = ( - f"Release {release_id}, published past {warned} release contract " - "warning(s) (microcosm#1301). The publisher printed them; none is " - "recorded here." - if warned - else None - ) - _publish_atomic( - api, - release_dir=prepared.release_dir, - artifact_root=prepared.artifact_root, - repo_id=repo_id, - release_id=release_id, - tag=prepared.tag, - filenames=prepared.filenames, - root_artifacts=prepared.root_artifacts, - payload=payload, - create_tag=create_tag, - update_latest=update_latest, - tag_only=tag_only, - pointer_path=prepared.pointer_path, - pointer_label=pointer_label, - tag_message=tag_message, - ) - # The pointer is live: announce it. Best-effort and coupled to the promotion - # so every publish path alerts; warn (don't fail) if the webhook is unset. - # Skip when no pointer moved — a non-default publish is not a new release. - if notify and update_latest: - notify_kwargs: dict = {"warn_if_unset": True} - if evidence: - # The alert must never read as a certified release announcement. - notify_kwargs["tier"] = RELEASE_TIER_EVIDENCE - notify_release(repo_id, release_id, payload.get("updated_at"), **notify_kwargs) - if prepared.contract_warnings: - return {**payload, "contract_warnings": list(prepared.contract_warnings)} - return payload - - -def _supports_atomic_publication(api: object) -> bool: - return all( - callable(getattr(api, method, None)) - for method in ("create_branch", "create_commit", "create_tag", "delete_branch") - ) + if reason is not None or not isinstance(run_id, str) or not run_id: + return True + if mode == "local_only": + return True + if ( + mode != "local_and_remote" + or not isinstance(repository, str) + or not repository.strip() + ): + return True + if read_back == "passed": + return successes == 0 or error_code is not None + if read_back == "failed": + return True + if error_code not in {None, "UPLOAD_FAILED"}: + return True + return successes == 0 + + +def _reform_validation_skipped(release_dir: Path) -> bool: + """True if the release carries a reform_validation.json that was built with + out-of-sample reforms skipped (``out_of_sample_simulated`` false). + + Such a release publishes blank out-of-sample (OBBBA) rows on the dashboard, + indistinguishable from a real result — so publishing one is refused unless + explicitly allowed. Absent/unreadable file or a true flag → not skipped. + """ + path = release_dir / "reform_validation.json" + if not path.exists(): + return False + try: + payload = json.loads(path.read_text()) + except (OSError, ValueError): + return False + return payload.get("out_of_sample_simulated") is False -def _commit_operations( - *, +def publication_refusal( release_dir: Path, - artifact_root: Path | None, - release_id: str, - filenames: list[str], - root_artifacts: Mapping[str, str], - pointer: bytes | None = None, - pointer_path: str = LATEST_POINTER_PATH, -) -> list: - try: - from huggingface_hub import CommitOperationAdd - except ImportError as exc: # pragma: no cover - declared dependency - raise ImportError( - "microcosm-data needs huggingface_hub to publish releases; " - "reinstall microcosm-data with its dependencies." - ) from exc - - operations = [ - CommitOperationAdd( - path_in_repo=f"releases/{release_id}/{filename}", - path_or_fileobj=str(release_dir / filename), + *, + allow_incomplete_reform_validation: bool = False, + allow_missing_staging: bool = False, +) -> str | None: + """Why a release must not be published, read from its local files, or None. + + The checks ``microcosm-publish-release-build`` runs before a build's + release contract: non-release smoke output, a reform validation built + with out-of-sample reforms skipped, and staging telemetry that never + arrived. Each override flag lifts one check. + """ + if _non_release_artifact(release_dir): + return ( + "refusing to publish: build_manifest.json identifies this as " + "non-release smoke output." ) - for filename in filenames - ] - if artifact_root is not None: - operations.extend( - CommitOperationAdd( - path_in_repo=path_in_repo, - path_or_fileobj=str(artifact_root / path_in_repo), - ) - for path_in_repo in root_artifacts + if not allow_incomplete_reform_validation and _reform_validation_skipped( + release_dir + ): + return ( + "refusing to publish: reform_validation.json has " + "out_of_sample_simulated=false (built with " + "--skip-out-of-sample-reforms), so the dashboard would show blank " + "out-of-sample reforms. Rebuild without skipping, or pass " + "--allow-incomplete-reform-validation to publish anyway." ) - if pointer is not None: - operations.append( - CommitOperationAdd( - path_in_repo=pointer_path, - path_or_fileobj=pointer, - ) + if not allow_missing_staging and _staging_undelivered(release_dir): + return ( + "refusing to publish: this release's build_manifest records no " + "delivered staging telemetry for the build (for a build " + "certified separately: for its certification, or for the build " + "itself under staging.build), so the build never appeared on the " + "staging dashboard and there is no pre-publication review of it. " + "Either the staging destination was lost mid-build (uploads " + "pause after repeated failures — check the build machine's " + "Hugging Face write token), or the manifest predates staging " + "provenance. Rebuild with staging reaching its repo, or pass " + "--allow-missing-staging to publish anyway. A build that declared " + "--no-staging publishes without the flag." ) - return operations - - -def _repo_revision(api: object, *, repo_id: str) -> str | None: - repo_info = getattr(api, "repo_info", None) - if not callable(repo_info): - return None - info = repo_info(repo_id=repo_id, repo_type="dataset", revision="main") - if isinstance(info, Mapping): - value = info.get("sha") - else: - value = getattr(info, "sha", None) - return str(value) if value else None + return None def missing_on_hub(error: BaseException) -> bool: @@ -1127,145 +759,6 @@ def missing_on_hub(error: BaseException) -> bool: ) -def _refuse_releases_record(api: object, *, repo_id: str, revision: str | None) -> None: - """Refuse a repository that records its builds in ``releases.json``. - - Such a repository publishes each build into its own folder through the - emitter, and ``releases.json`` is the only record of which build is - current; a tag or ``latest*.json`` pointer file written beside it would - disagree with the record. Only the Hub's answer that the file is absent - (:func:`missing_on_hub`) lets the publication go on; any other failure - to read it, a server error included, propagates before anything is - written. - """ - try: - api.hf_hub_download( - repo_id=repo_id, - filename=RELEASES_RECORD_PATH, - repo_type="dataset", - revision=revision, - ) - except Exception as exc: - if missing_on_hub(exc): - return - raise - raise ValueError( - f"{repo_id} records its builds in {RELEASES_RECORD_PATH}, so this " - "publisher, which tags each build and writes latest*.json pointer " - "files, refuses it. Only releases that publish into build folders " - f"publish there, through `{BUILD_FOLDER_PUBLICATION_COMMAND}`; any " - "other release takes no new builds there." - ) - - -def _publish_atomic( - api: object, - *, - release_dir: Path, - artifact_root: Path | None, - repo_id: str, - release_id: str, - tag: str, - filenames: list[str], - root_artifacts: Mapping[str, str], - payload: dict, - create_tag: bool, - update_latest: bool = True, - tag_only: bool = False, - pointer_path: str, - pointer_label: str, - tag_message: str | None = None, -) -> None: - staging_branch = f"release-staging/{release_id}" - main_revision = _repo_revision(api, repo_id=repo_id) - # The main commit below is made on main_revision, so a releases.json - # added after this check makes it fail rather than land beside it. - _refuse_releases_record(api, repo_id=repo_id, revision=main_revision) - existing_revision = ( - _tag_revision(api, repo_id=repo_id, tag=tag) if create_tag else None - ) - if existing_revision is not None: - # The immutable revision already exists under this tag (an inspect - # publication of the same cut, or a run that failed after tagging). - # It must describe exactly this release; then there is nothing - # immutable left to write, and publication continues with the main - # commit alone. A tag that describes another release refuses. - _require_tag_describes_release( - api, - repo_id=repo_id, - release_id=release_id, - tag=tag, - release_dir=release_dir, - ) - immutable_revision = existing_revision - else: - api.create_branch( - repo_id=repo_id, - branch=staging_branch, - repo_type="dataset", - revision=main_revision, - ) - immutable_commit = api.create_commit( - repo_id=repo_id, - repo_type="dataset", - revision=staging_branch, - commit_message=f"Publish immutable release {release_id}", - operations=_commit_operations( - release_dir=release_dir, - artifact_root=artifact_root, - release_id=release_id, - filenames=filenames, - root_artifacts=root_artifacts, - ), - ) - immutable_revision = _commit_revision(immutable_commit) - if immutable_revision is None: - raise RuntimeError( - "Hub create_commit returned no revision for immutable release " - f"{release_id!r}; refusing to update main or {pointer_path}." - ) - if create_tag: - _create_release_tag( - api, - repo_id=repo_id, - tag=tag, - revision=immutable_revision, - message=tag_message, - ) - api.delete_branch( - repo_id=repo_id, - branch=staging_branch, - repo_type="dataset", - ) - if tag_only: - # The release-id tag points directly at immutable_revision, so deleting - # the temporary branch does not make the candidate unreachable. Exact-k - # candidates deliberately stop here: neither canonical root artifacts - # nor release-directory copies are written to main. - return - if update_latest: - message = f"Update latest {pointer_label} to {release_id}" - pointer = json.dumps(payload, indent=1).encode() - else: - message = f"Publish non-default {pointer_label} {release_id}" - pointer = None - api.create_commit( - repo_id=repo_id, - repo_type="dataset", - commit_message=message, - parent_commit=main_revision, - operations=_commit_operations( - release_dir=release_dir, - artifact_root=artifact_root, - release_id=release_id, - filenames=filenames, - root_artifacts=root_artifacts, - pointer=pointer, - pointer_path=pointer_path, - ), - ) - - def _sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: @@ -1274,158 +767,6 @@ def _sha256(path: Path) -> str: return digest.hexdigest() -def _release_manifest_root_artifacts(release_dir: Path) -> dict[str, str]: - manifest = json.loads((release_dir / "release_manifest.json").read_text()) - artifacts = manifest.get("artifacts", {}) - if not isinstance(artifacts, dict): # pragma: no cover - validated already - return {} - contract_files = set(required_release_files(release_dir.name)) - root_artifacts: dict[str, str] = {} - for artifact in artifacts.values(): - if not isinstance(artifact, dict): # pragma: no cover - validated already - continue - path = artifact.get("path") - sha = artifact.get("sha256") - if not isinstance(path, str) or not path: - continue - if path in contract_files: - continue - if path.startswith("releases/"): - continue - if (release_dir / path).is_file(): - continue - if isinstance(sha, str): - root_artifacts[path] = sha - return root_artifacts - - -def _release_manifest_release_artifacts(release_dir: Path) -> tuple[str, ...]: - """Non-contract release-dir artifacts declared by the release manifest.""" - manifest = json.loads((release_dir / "release_manifest.json").read_text()) - artifacts = manifest.get("artifacts", {}) - if not isinstance(artifacts, dict): # pragma: no cover - validated already - return () - contract_files = set(required_release_files(release_dir.name)) - filenames: list[str] = [] - for artifact in artifacts.values(): - if not isinstance(artifact, dict): # pragma: no cover - validated already - continue - path = artifact.get("path") - if not isinstance(path, str) or not path: - continue - filename = path - release_prefix = f"releases/{release_dir.name}/" - if filename.startswith(release_prefix): - filename = filename.removeprefix(release_prefix) - if filename in contract_files: - continue - if "/" in filename: - continue - if (release_dir / filename).is_file(): - filenames.append(filename) - return tuple(filenames) - - -def _release_manifest_artifact_paths(release_dir: Path) -> dict[str, str]: - """Root artifact paths from the validated release manifest. - - Contract files have their public home under ``releases//`` and - are uploaded by filename elsewhere in :func:`publish_release`; this helper - returns only root dataset artifacts such as H5/NPZ payloads. - """ - manifest = json.loads((release_dir / "release_manifest.json").read_text()) - artifacts = manifest.get("artifacts", {}) - if not isinstance(artifacts, dict): # pragma: no cover - validated already - return {} - contract_files = set(required_release_files(release_dir.name)) - paths: dict[str, str] = {} - for key, artifact in artifacts.items(): - if not isinstance(artifact, dict): # pragma: no cover - validated already - continue - path = artifact.get("path") - if not isinstance(path, str) or not path: - continue - if path in contract_files: - continue - if path.startswith("releases/"): - continue - paths[str(key)] = path - return paths - - -def _ordered_unique(names: tuple[str, ...]) -> list[str]: - seen: set[str] = set() - ordered: list[str] = [] - for name in names: - if name in seen: - continue - seen.add(name) - ordered.append(name) - return ordered - - -def _release_manifest_artifact_revisions( - release_dir: Path, -) -> tuple[set[str], list[str]]: - """Every artifact's pinned revision, and the artifacts whose pin is unreadable. - - A missing, empty, or non-string revision lands in the unreadable list - instead of silently shrinking the revision set: an empty set must mean "no - artifacts declared", never "artifacts whose pins could not be read". - """ - manifest = json.loads((release_dir / "release_manifest.json").read_text()) - artifacts = manifest.get("artifacts", {}) - if not isinstance(artifacts, dict): - return set(), ["artifacts"] - revisions: set[str] = set() - unreadable: list[str] = [] - for key, artifact in artifacts.items(): - if not isinstance(artifact, dict): - unreadable.append(str(key)) - continue - revision = artifact.get("revision") - if isinstance(revision, str) and revision: - revisions.add(revision) - else: - unreadable.append(str(key)) - return revisions, unreadable - - -def _commit_revision(commit_info: Any) -> str | None: - """Best-effort revision from ``huggingface_hub`` upload return objects.""" - if commit_info is None: - return None - for attr in ("oid", "commit_hash", "commit_id"): - value = getattr(commit_info, attr, None) - if value: - return str(value) - if isinstance(commit_info, dict): - for key in ("oid", "commit_hash", "commit_id"): - value = commit_info.get(key) - if value: - return str(value) - return None - - -def _tag_revision(api: object, *, repo_id: str, tag: str) -> str | None: - """The revision an existing tag points at, or None when the tag is absent.""" - repo_info = getattr(api, "repo_info", None) - if not callable(repo_info): - return None - try: - info = repo_info(repo_id=repo_id, repo_type="dataset", revision=tag) - except Exception as exc: - # Only "no such revision" means the tag is absent. Anything else (a - # transient network failure, an auth error) must propagate: treating - # it as absent would re-enter the create path and die on create_tag - # with the staging branch left behind. - if _is_absent_revision_error(exc): - return None - raise - value = info.get("sha") if isinstance(info, Mapping) else getattr(info, "sha", None) - return str(value) if value else None - - _ABSENT_REVISION_ERRORS = frozenset({"RevisionNotFoundError", "KeyError"}) _ABSENT_ENTRY_ERRORS = frozenset({"EntryNotFoundError", "FileNotFoundError"}) @@ -1447,75 +788,6 @@ def _is_absent_entry_error(exc: BaseException) -> bool: return bool(names & _ABSENT_ENTRY_ERRORS) and "LocalEntryNotFoundError" not in names -def _require_tag_describes_release( - api: object, - *, - repo_id: str, - release_id: str, - tag: str, - release_dir: Path, -) -> None: - """Refuse an existing tag unless its release manifest is byte-identical. - - The manifest pins every artifact's digest and revision, so equal bytes - mean the tagged revision is this release; anything else (another cut, - a manifest that never landed) must not be promoted under this tag. - """ - manifest_path = f"releases/{release_id}/release_manifest.json" - try: - remote = Path( - api.hf_hub_download( - repo_id=repo_id, - filename=manifest_path, - repo_type="dataset", - revision=tag, - ) - ).read_bytes() - except Exception as exc: - # Only an absent manifest means the tag describes another release; a - # transient failure must propagate rather than send the operator to a - # fresh cut tag and orphan a good one. - if not _is_absent_entry_error(exc): - raise - raise ValueError( - f"tag {tag!r} already exists in {repo_id} but carries no " - f"{manifest_path} ({exc}); it does not describe this release, so " - "it cannot be reused. Publish under a fresh cut tag." - ) from exc - local = (release_dir / "release_manifest.json").read_bytes() - if remote != local: - raise ValueError( - f"tag {tag!r} already exists in {repo_id} and describes another " - f"release (its {manifest_path} differs from the local one); " - "refusing to promote it. Publish under a fresh cut tag." - ) - - -def _create_release_tag( - api: object, - *, - repo_id: str, - tag: str, - revision: str | None, - message: str | None = None, -): - kwargs = { - "repo_id": repo_id, - "tag": tag, - "repo_type": "dataset", - } - if revision is not None: - kwargs["revision"] = revision - if message is not None: - kwargs["tag_message"] = message - create_tag = getattr(api, "create_tag", None) - if create_tag is None: - raise TypeError( - "publish_release requires a Hub backend with create_tag support." - ) - return create_tag(**kwargs) - - def _read_pointer(repo_id: str, api, *, pointer_path: str) -> dict: """Download and structurally validate a release pointer file.""" if api is None: diff --git a/packages/microcosm-data/src/microcosm/data/slack.py b/packages/microcosm-data/src/microcosm/data/slack.py deleted file mode 100644 index 59aabb9d57..0000000000 --- a/packages/microcosm-data/src/microcosm/data/slack.py +++ /dev/null @@ -1,129 +0,0 @@ -"""Best-effort Slack notification when a Microcosm release is published. - -Sent inline from :func:`microcosm.data.release.publish_release` right after -``latest.json`` is uploaded — coupled to the promotion itself, so the alert -fires for *every* publish path (the CLI, a build script, a manual promote), not -just one entry point. The webhook URL comes from a per-country env var, so this -is a no-op unless it is configured, and a failed post is logged rather than -raised — a Slack hiccup must never fail a release. Pass ``warn_if_unset=True`` -(as ``publish_release`` does) to make a missing webhook loud instead of silent, -so a misconfiguration shows up in the publish log rather than vanishing. -""" - -from __future__ import annotations - -import json -import os -import urllib.request -from collections.abc import Callable -from typing import Any - -CHANNEL_ENV: dict[str, str] = { - "us": "SLACK_WEBHOOK_POPULACE_US", - "uk": "SLACK_WEBHOOK_POPULACE_UK", -} - -DASHBOARD_URL = "https://calibration-diagnostics.vercel.app/microcosm" - - -def country_for_repo(repo_id: str) -> str: - return "uk" if "uk" in repo_id.lower() else "us" - - -def _default_post(url: str, payload: dict[str, Any]) -> None: - request = urllib.request.Request( - url, - data=json.dumps(payload).encode("utf-8"), - headers={"Content-Type": "application/json"}, - method="POST", - ) - with urllib.request.urlopen(request, timeout=15) as response: - response.read() - - -def notify_release( - repo_id: str, - release_id: str, - updated_at: str | None = None, - *, - webhook: str | None = None, - post: Callable[[str, dict[str, Any]], None] | None = None, - warn_if_unset: bool = False, - tier: str = "certified", - line: str | None = None, - revision: str | None = None, -) -> bool: - """Announce a published release to the country's Slack channel. - - Returns True if a message was sent. Returns False (no-op) when the webhook - env var is unset. Never raises — a failed post is logged, not fatal. When - ``warn_if_unset`` is set, an unset webhook logs a warning instead of - returning silently, so a release that publishes without an alert is visible - in the log rather than a mystery. ``tier="evidence"`` labels the alert as - an evidence-tier publish (microcosm#506) so it can never read as a new - certified release. ``line`` and ``revision`` label an approved line - promotion; the existing certified and evidence messages are unchanged. - """ - country = country_for_repo(repo_id) - url = webhook or os.environ.get(CHANNEL_ENV[country]) - if not url: - if warn_if_unset: - print( - f"::warning:: {CHANNEL_ENV[country]} is not set — release " - f"{release_id} was published without a Slack alert." - ) - return False - - label = "🇬🇧 UK" if country == "uk" else "🇺🇸 US" - is_evidence = tier == "evidence" - context = " · ".join( - part - for part in ( - repo_id, - ( - "evidence tier — known failures recorded in the release manifest" - if is_evidence - else "" - ), - f"published {updated_at}" if updated_at else "", - f"<{DASHBOARD_URL}|calibration diagnostics>", - ) - if part - ) - if line is not None: - promoted_revision = revision or release_id - text = ( - f"Microcosm {country.upper()} line promoted: {line} -> {promoted_revision}" - ) - header = ( - f":rocket: *Microcosm {label} line promoted*\n" - f"`{line}` → `{promoted_revision}`" - ) - elif is_evidence: - text = f"New Microcosm {country.upper()} EVIDENCE release: {release_id}" - header = f":warning: *New Microcosm {label} EVIDENCE release*\n`{release_id}`" - else: - text = f"New Microcosm {country.upper()} release: {release_id}" - header = f":rocket: *New Microcosm {label} release*\n`{release_id}`" - payload = { - "text": text, - "blocks": [ - { - "type": "section", - "text": { - "type": "mrkdwn", - "text": header, - }, - }, - { - "type": "context", - "elements": [{"type": "mrkdwn", "text": context}], - }, - ], - } - try: - (post or _default_post)(url, payload) - return True - except Exception as exc: - print(f"::warning:: Microcosm Slack notification failed: {exc}") - return False diff --git a/packages/microcosm-data/src/microcosm/data/source_enrichment.py b/packages/microcosm-data/src/microcosm/data/source_enrichment.py index b7f48d4409..18234904b4 100644 --- a/packages/microcosm-data/src/microcosm/data/source_enrichment.py +++ b/packages/microcosm-data/src/microcosm/data/source_enrichment.py @@ -577,21 +577,6 @@ def _check_receipt_producers( failures.append(f"qualification producer source identity failed: {exc}") -def is_receipt_enrichment(release_dir: Path | str) -> bool: - """Whether ``release_dir`` declares the reported-receipt operation. - - A reporting probe for the publisher's latest-pointer guard; it validates - nothing, and an unreadable report reads as ``False``. - """ - try: - report = json.loads((Path(release_dir) / SOURCE_ENRICHMENT_FILE).read_text()) - except (OSError, ValueError): - return False - return isinstance(report, Mapping) and report.get("operation") == ( - RECEIPT_OPERATION - ) - - def validate_source_enrichment_candidate( release_dir: Path | str, *, diff --git a/packages/microcosm-data/tests/engine_free/shared/test_be_build_folder_releases.py b/packages/microcosm-data/tests/engine_free/shared/test_be_build_folder_releases.py index 24687344db..4be9ae967b 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_be_build_folder_releases.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_be_build_folder_releases.py @@ -302,12 +302,6 @@ def test_a_be_build_is_prepared_with_the_role_its_dataset_role_gives( assert set(BE_REQUIRED_FILES) <= {item.name for item in prepared.files} -@pytest.mark.parametrize("release_id", BE_RELEASE_IDS) -def test_the_tagged_publisher_refuses_a_be_release(tmp_path, release_id) -> None: - with pytest.raises(ValueError, match="publishes each build into its own folder"): - release_module.prepare_release(tmp_path / release_id) - - def test_a_be_build_named_by_its_old_folder_is_pointed_at_the_be_releases() -> None: """The publisher's refusal of a directory that is not a build-folder release names the releases BE's builds now publish into.""" diff --git a/packages/microcosm-data/tests/engine_free/shared/test_compatibility_recertification.py b/packages/microcosm-data/tests/engine_free/shared/test_compatibility_recertification.py index a5d7a29ea7..727ad6c216 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_compatibility_recertification.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_compatibility_recertification.py @@ -1241,37 +1241,6 @@ def test_the_publication_contract_takes_wheels_but_not_a_parent_h5( ) -def test_a_recertification_never_moves_latest( - paths_hub, parent, candidate, tmp_path, monkeypatch -): - """The tagged publisher, which writes latest.json, refuses the child: it - is a build of a release that publishes into build folders.""" - - parent_dir, parent_root = parent - output, artifact_root = certify(candidate, tmp_path, monkeypatch) - seed_published_parent(paths_hub, parent_dir, parent_root) - monkeypatch.setattr(recert, "run_recertification_loader_replay", fake_replay()) - monkeypatch.setattr(recert, "_check_producer", lambda code, failures, label: None) - wheel = tmp_path / "policyengine_us-2.60.4-py3-none-any.whl" - wheel.write_bytes(b"") - with pytest.raises(ValueError, match="publishes each build into its own folder"): - release_module.prepare_release( - output, artifact_root=artifact_root, compatibility_wheels=(wheel,) - ) - events = list(paths_hub.events) - with pytest.raises(ValueError, match="publishes each build into its own folder"): - release_module.publish_release( - output, - "policyengine/populace-us", - api=paths_hub, - artifact_root=artifact_root, - compatibility_wheels=(wheel,), - notify=False, - ) - assert paths_hub.events == events - assert "latest.json" not in dict(paths_hub.uploads) - - def test_validation_prints_the_recertification_measurement( candidate, tmp_path, monkeypatch, capsys ): diff --git a/packages/microcosm-data/tests/engine_free/shared/test_local_area_contract.py b/packages/microcosm-data/tests/engine_free/shared/test_local_area_contract.py index c37bc05710..7aebfab882 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_local_area_contract.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_local_area_contract.py @@ -37,7 +37,6 @@ validate_evidence_release_dir, validate_release_dir, ) -from microcosm.data.release import prepare_release, publish_release from microcosm.data.stored_inputs import register_sha256 from test_support.microcosm_data.build_folders import ( UK_LOCAL_BUILD, @@ -637,14 +636,6 @@ def test_explicit_diagnostics_failure_does_not_block_local_release( ) validate_release_dir(release_dir) - with pytest.warns(UserWarning, match="generation failed"): - prepared = prepare_release( - release_dir, - artifact_root=tmp_path, - update_latest=False, - ) - assert prepared.calibration_diagnostics_available is False - assert "calibration_diagnostics.json" not in prepared.filenames def test_local_area_dispatch_does_not_bypass_uk_tier_identity(tmp_path: Path) -> None: @@ -740,47 +731,6 @@ def test_tampered_diagnostics_artifact_hash_is_rejected(tmp_path: Path) -> None: validate_release_dir(release_dir) -def test_publish_refuses_pointer_update_for_local_area_role( - tmp_path: Path, monkeypatch -) -> None: - from microcosm.data import release as release_module - from microcosm.data.publish_cli import main - - release_dir = _write_local_bundle(tmp_path) - validate_release_dir(release_dir) - monkeypatch.setattr( - release_module, "_hf_api", lambda: pytest.fail("unexpected Hub construction") - ) - - with pytest.raises(ValueError, match="never update latest.json") as publication: - publish_release( - release_dir, - "policyengine/populace-us", - api=object(), - update_latest=True, - ) - - with pytest.raises(type(publication.value)) as preflight: - main([str(release_dir), "--preflight-only"]) - assert str(preflight.value) == str(publication.value) - - -def test_publish_without_pointer_passes_the_role_guard(tmp_path: Path) -> None: - release_dir = _write_local_bundle(tmp_path) - - # A dummy backend fails the atomic-publication capability check — which - # sits AFTER the role guard and the artifact verification, proving - # --no-latest publishes proceed to the Hub surface. - with pytest.raises(TypeError, match="Hub backend|create_tag"): - publish_release( - release_dir, - "policyengine/populace-us", - api=object(), - artifact_root=tmp_path, - update_latest=False, - ) - - def test_empty_checksum_ledger_is_rejected(tmp_path: Path) -> None: release_dir = _write_local_bundle(tmp_path) (release_dir / "sha256sums.txt").write_text("") diff --git a/packages/microcosm-data/tests/engine_free/shared/test_publish_guard.py b/packages/microcosm-data/tests/engine_free/shared/test_publish_guard.py index 852859bd67..927124cadf 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_publish_guard.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_publish_guard.py @@ -3,11 +3,11 @@ import pytest -from microcosm.data.publish_cli import ( +from microcosm.data.release import ( _non_release_artifact, _reform_validation_skipped, _staging_undelivered, - main, + publication_refusal, ) @@ -33,38 +33,30 @@ def test_not_skipped_when_no_reform_validation(tmp_path): assert _reform_validation_skipped(tmp_path) is False -def test_publish_refused_when_out_of_sample_skipped(tmp_path, capsys): +def test_publication_refused_when_out_of_sample_skipped(tmp_path): _write_rv(tmp_path, out_of_sample_simulated=False) - # The guard returns before publish_release is ever called (no HF upload). - rc = main([str(tmp_path), "--repo-id", "policyengine/populace-us"]) - assert rc == 1 - assert "refusing to publish" in capsys.readouterr().err + refusal = publication_refusal(tmp_path) -def _stub_publish(monkeypatch): - import microcosm.data.publish_cli as cli - - monkeypatch.setattr( - cli, "publish_release", lambda *a, **k: {"release_id": "r", "updated_at": None} - ) - return cli + assert refusal is not None + assert refusal.startswith("refusing to publish") + assert "--allow-incomplete-reform-validation" in refusal -def test_allow_incomplete_reform_validation_publishes(tmp_path, capsys, monkeypatch): +def test_allow_incomplete_reform_validation_lifts_the_refusal(tmp_path): _write_rv(tmp_path, out_of_sample_simulated=False) - cli = _stub_publish(monkeypatch) - monkeypatch.delenv("SLACK_WEBHOOK_POPULACE_US", raising=False) - rc = cli.main([str(tmp_path), "--allow-incomplete-reform-validation"]) - assert rc == 0 - assert "refusing to publish" not in capsys.readouterr().err + + assert ( + publication_refusal(tmp_path, allow_incomplete_reform_validation=True) is None + ) def _write_bm(release_dir: Path, manifest: dict) -> None: (release_dir / "build_manifest.json").write_text(json.dumps(manifest)) -def test_publish_refuses_non_release_smoke_even_with_staging_override( - tmp_path, capsys, monkeypatch +def test_publication_refuses_non_release_smoke_even_with_staging_override( + tmp_path, ): _write_bm( tmp_path, @@ -76,12 +68,11 @@ def test_publish_refuses_non_release_smoke_even_with_staging_override( }, ) assert _non_release_artifact(tmp_path) is True - monkeypatch.delenv("SLACK_WEBHOOK_POPULACE_US", raising=False) - rc = main([str(tmp_path), "--allow-missing-staging"]) + refusal = publication_refusal(tmp_path, allow_missing_staging=True) - assert rc == 1 - assert "non-release smoke output" in capsys.readouterr().err + assert refusal is not None + assert "non-release smoke output" in refusal def test_staging_undelivered_reads_the_manifest_not_the_country(tmp_path): @@ -259,8 +250,8 @@ def test_a_separately_certified_build_needs_its_own_staging_too( assert _staging_undelivered(tmp_path) is undelivered -def test_publish_refuses_a_certified_build_whose_own_staging_never_arrived( - tmp_path, capsys, monkeypatch +def test_publication_refuses_a_certified_build_whose_own_staging_never_arrived( + tmp_path, ): _write_bm( tmp_path, @@ -273,14 +264,15 @@ def test_publish_refuses_a_certified_build_whose_own_staging_never_arrived( }, }, ) - cli = _stub_publish(monkeypatch) - monkeypatch.delenv("SLACK_WEBHOOK_POPULACE_US", raising=False) - assert cli.main([str(tmp_path)]) == 1 - assert "for the build itself under staging.build" in capsys.readouterr().err - assert cli.main([str(tmp_path), "--allow-missing-staging"]) == 0 + refusal = publication_refusal(tmp_path) -def test_publish_refused_when_staging_never_delivered(tmp_path, capsys, monkeypatch): + assert refusal is not None + assert "for the build itself under staging.build" in refusal + assert publication_refusal(tmp_path, allow_missing_staging=True) is None + + +def test_publication_refused_when_staging_never_delivered(tmp_path): _write_bm( tmp_path, { @@ -292,53 +284,44 @@ def test_publish_refused_when_staging_never_delivered(tmp_path, capsys, monkeypa }, }, ) - monkeypatch.delenv("SLACK_WEBHOOK_POPULACE_US", raising=False) - rc = main([str(tmp_path)]) - assert rc == 1 - assert "refusing to publish" in capsys.readouterr().err + refusal = publication_refusal(tmp_path) + + assert refusal is not None + assert refusal.startswith("refusing to publish") -def test_publish_refused_when_staging_block_is_null(tmp_path, capsys, monkeypatch): + +def test_publication_refused_when_staging_block_is_null(tmp_path): _write_bm(tmp_path, {"build_id": "x", "staging": None}) - monkeypatch.delenv("SLACK_WEBHOOK_POPULACE_US", raising=False) - rc = main([str(tmp_path)]) - assert rc == 1 - assert "refusing to publish" in capsys.readouterr().err + + refusal = publication_refusal(tmp_path) + + assert refusal is not None + assert refusal.startswith("refusing to publish") -def test_publish_allowed_for_a_declared_no_staging_build(tmp_path, capsys, monkeypatch): +def test_publication_allowed_for_a_declared_no_staging_build(tmp_path): _write_bm( tmp_path, {"build_id": "x", "staging": {"enabled": False, "reason": "--no-staging"}}, ) - cli = _stub_publish(monkeypatch) - monkeypatch.delenv("SLACK_WEBHOOK_POPULACE_US", raising=False) - rc = cli.main([str(tmp_path)]) - assert rc == 0 - assert "refusing to publish" not in capsys.readouterr().err + assert publication_refusal(tmp_path) is None -def test_publish_allowed_when_the_builder_has_no_staging_path( - tmp_path, capsys, monkeypatch -): + +def test_publication_allowed_when_the_builder_has_no_staging_path(tmp_path): _write_bm(tmp_path, {"build_id": "microcosm-us-local-x", "dataset": {}}) - cli = _stub_publish(monkeypatch) - monkeypatch.delenv("SLACK_WEBHOOK_POPULACE_US", raising=False) - rc = cli.main([str(tmp_path), "--no-latest"]) - assert rc == 0 - assert "refusing to publish" not in capsys.readouterr().err + + assert publication_refusal(tmp_path) is None -def test_allow_missing_staging_escape_hatch_publishes(tmp_path, capsys, monkeypatch): +def test_allow_missing_staging_lifts_the_staging_refusal(tmp_path): _write_bm(tmp_path, {"build_id": "x", "staging": None}) - cli = _stub_publish(monkeypatch) - monkeypatch.delenv("SLACK_WEBHOOK_POPULACE_US", raising=False) - rc = cli.main([str(tmp_path), "--allow-missing-staging"]) - assert rc == 0 - assert "refusing to publish" not in capsys.readouterr().err + assert publication_refusal(tmp_path, allow_missing_staging=True) is None -def test_publish_proceeds_when_staging_delivered(tmp_path, capsys, monkeypatch): + +def test_publication_proceeds_when_staging_delivered(tmp_path): _write_bm( tmp_path, { @@ -350,18 +333,15 @@ def test_publish_proceeds_when_staging_delivered(tmp_path, capsys, monkeypatch): }, }, ) - cli = _stub_publish(monkeypatch) - monkeypatch.delenv("SLACK_WEBHOOK_POPULACE_US", raising=False) - rc = cli.main([str(tmp_path)]) - assert rc == 0 - assert "refusing to publish" not in capsys.readouterr().err + + assert publication_refusal(tmp_path) is None @pytest.mark.parametrize( - ("delivery", "expected"), + ("delivery", "refused"), [ - (_version_2_delivery(), 0), - (_version_2_delivery(upload_attempts=0, upload_successes=0), 1), + (_version_2_delivery(), False), + (_version_2_delivery(upload_attempts=0, upload_successes=0), True), ( _version_2_delivery( mode="local_only", @@ -369,7 +349,7 @@ def test_publish_proceeds_when_staging_delivered(tmp_path, capsys, monkeypatch): upload_attempts=0, upload_successes=0, ), - 1, + True, ), ( _version_2_delivery( @@ -381,22 +361,17 @@ def test_publish_proceeds_when_staging_delivered(tmp_path, capsys, monkeypatch): upload_successes=0, opt_out_reason="--no-staging", ), - 0, + False, ), ], ) -def test_version_2_publication_decisions( - tmp_path, capsys, monkeypatch, delivery, expected -): +def test_version_2_publication_decisions(tmp_path, delivery, refused): _write_bm(tmp_path, {"build_id": "x", "staging": delivery}) - cli = _stub_publish(monkeypatch) - monkeypatch.delenv("SLACK_WEBHOOK_POPULACE_US", raising=False) - assert cli.main([str(tmp_path)]) == expected - assert ("refusing to publish" in capsys.readouterr().err) is (expected == 1) + assert (publication_refusal(tmp_path) is not None) is refused -def test_version_2_local_only_can_use_explicit_override(tmp_path, capsys, monkeypatch): +def test_version_2_local_only_can_use_explicit_override(tmp_path): _write_bm( tmp_path, { @@ -409,86 +384,6 @@ def test_version_2_local_only_can_use_explicit_override(tmp_path, capsys, monkey ), }, ) - cli = _stub_publish(monkeypatch) - monkeypatch.delenv("SLACK_WEBHOOK_POPULACE_US", raising=False) - - assert cli.main([str(tmp_path), "--allow-missing-staging"]) == 0 - assert "refusing to publish" not in capsys.readouterr().err - - -def test_tag_only_cli_forwards_no_main_publication_mode(tmp_path, monkeypatch): - import microcosm.data.publish_cli as cli - - captured: dict = {} - - def fake_publish(*args, **kwargs): - captured["args"] = args - captured["kwargs"] = kwargs - return {"release_id": "r", "updated_at": None} - - monkeypatch.setattr(cli, "publish_release", fake_publish) - - rc = cli.main([str(tmp_path), "--no-latest", "--tag-only"]) - - assert rc == 0 - assert captured["kwargs"]["update_latest"] is False - assert captured["kwargs"]["tag_only"] is True - assert captured["kwargs"]["create_tag"] is True - - -@pytest.mark.parametrize( - ("arguments", "message"), - [ - (["--tag-only"], "--tag-only requires --no-latest"), - ( - ["--no-latest", "--tag-only", "--no-create-tag"], - "--tag-only requires tag creation", - ), - ], -) -def test_tag_only_cli_rejects_unsafe_flag_combinations_before_publish( - tmp_path, capsys, monkeypatch, arguments, message -): - import microcosm.data.publish_cli as cli - - called = False - - def unexpected_publish(*args, **kwargs): - nonlocal called - called = True - - monkeypatch.setattr(cli, "publish_release", unexpected_publish) - - with pytest.raises(SystemExit, match="2"): - cli.main([str(tmp_path), *arguments]) - - assert message in capsys.readouterr().err - assert called is False - - -def _capture_publish(monkeypatch) -> list: - import microcosm.data.publish_cli as cli - - calls: list = [] - - def _record(release_dir, repo_id, **kwargs): - calls.append((release_dir, repo_id, kwargs)) - return {"release_id": "r", "updated_at": None} - - monkeypatch.setattr(cli, "publish_release", _record) - return calls - - -def test_publish_cli_evidence_flag_wires_the_evidence_tier(tmp_path, monkeypatch): - calls = _capture_publish(monkeypatch) - rc = main([str(tmp_path), "--evidence"]) - assert rc == 0 - assert len(calls) == 1 - assert calls[0][2]["evidence"] is True - -def test_publish_cli_defaults_to_the_certified_tier(tmp_path, monkeypatch): - calls = _capture_publish(monkeypatch) - rc = main([str(tmp_path)]) - assert rc == 0 - assert calls[0][2]["evidence"] is False + assert publication_refusal(tmp_path) is not None + assert publication_refusal(tmp_path, allow_missing_staging=True) is None diff --git a/packages/microcosm-data/tests/engine_free/shared/test_release.py b/packages/microcosm-data/tests/engine_free/shared/test_release.py index b5555c2068..235373dd5b 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_release.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_release.py @@ -9,80 +9,9 @@ annual_build_folder, national_build, ) -from test_support.microcosm_data.hub_errors import hub_unreachable from test_support.microcosm_data.release import * -def test_annual_cut_passes_real_release_contract( - release_dir, artifact_root, annual_release -): - prepared = release_module.prepare_release( - release_dir, - artifact_root=artifact_root, - tag_name=annual_release, - update_latest=False, - ) - assert prepared.tag == annual_release - assert {"annual_manifest.json", "annual_acceptance.json"}.issubset( - prepared.filenames - ) - assert {"annual_2025.h5", "populace_us_2024.h5"}.issubset(prepared.root_artifacts) - - -def test_annual_cut_uploads_exact_artifacts_without_latest( - hub, release_dir, artifact_root, annual_release -): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - tag_name=annual_release, - update_latest=False, - ) - uploads = dict(hub.uploads) - assert uploads["annual_2025.h5"] == (artifact_root / "annual_2025.h5").read_bytes() - assert ( - uploads["populace_us_2024.h5"] - == (artifact_root / "populace_us_2024.h5").read_bytes() - ) - for name in ( - "annual_manifest.json", - "annual_acceptance.json", - "projection_2025.json", - "release_manifest.json", - ): - assert ( - uploads[f"releases/{release_dir.name}/{name}"] - == (release_dir / name).read_bytes() - ) - assert hub.tags == [{"tag": annual_release, "revision": "commit-1"}] - assert LATEST_POINTER_PATH not in uploads - assert LATEST_EVIDENCE_POINTER_PATH not in uploads - - -@pytest.mark.parametrize( - "option", ["latest", "wrong_tag", "absent_annual", "invalid_base"] -) -def test_annual_cut_preserves_publisher_and_base_guards( - release_dir, artifact_root, annual_release, option -): - path = release_dir / "release_manifest.json" - manifest = json.loads(path.read_text()) - if option == "absent_annual": - del manifest["metadata"] - path.write_text(json.dumps(manifest)) - elif option == "invalid_base": - (release_dir / "calibration_diagnostics.json").write_text("{}") - with pytest.raises((ReleaseContractError, ValueError)): - release_module.prepare_release( - release_dir, - artifact_root=artifact_root, - tag_name=release_dir.name if option == "wrong_tag" else annual_release, - update_latest=option == "latest", - ) - - def test_pointer_payload_names_every_contract_file() -> None: payload = latest_pointer_payload(RELEASE_ID, updated_at="2026-06-11T13:53:15+00:00") assert payload["schema_version"] == LATEST_POINTER_SCHEMA_VERSION @@ -167,187 +96,6 @@ def test_line_pointer_payload_refuses_a_line_id_mismatch() -> None: ) -def _write_uk_build_folder_release( - release_id: str, release_dir: Path, tmp_path: Path -) -> Path: - """One build-folder release of each kind: national, dense or local-area.""" - if release_id == UK_NATIONAL_RELEASE_ID: - return _as_uk_national_build_folder_release(release_dir) - from .test_local_area_contract import _write_local_bundle - - if release_id == UK_LOCAL_RELEASE_ID: - return _write_local_bundle(tmp_path / "local", release_id=release_id) - from test_support.microcosm_data.build_folders import UK_DENSE_BUILD - - dense = _write_local_bundle(tmp_path / "dense", release_id=UK_LOCAL_RELEASE_ID) - dense = dense.rename(dense.with_name(release_id)) - for name in ("build_manifest.json", "release_manifest.json"): - manifest = json.loads((dense / name).read_text()) - manifest.update(release=release_id, build=UK_DENSE_BUILD) - (dense / name).write_text(json.dumps(manifest)) - return dense - - -@pytest.mark.parametrize( - "release_id", - [UK_NATIONAL_RELEASE_ID, "microcosm-uk-2024-25-dense", UK_LOCAL_RELEASE_ID], -) -def test_the_tagged_publisher_refuses_every_build_folder_release( - release_dir: Path, - artifact_root: Path, - tmp_path: Path, - monkeypatch, - release_id: str, -) -> None: - """A UK build publishes into its own folder through the emitter; this - publisher, which commits, tags and writes pointer files, refuses it - before any check or Hub call, on every path. The local-area release is - one the registry names.""" - from test_support.microcosm_data.build_folders import register_uk_local_release - - register_uk_local_release(monkeypatch, UK_LOCAL_RELEASE_ID) - uk_dir = _write_uk_build_folder_release(release_id, release_dir, tmp_path) - uk_hub = FakeHub("policyengine/populace-uk-private") - uk_hub._download_dir = tmp_path / "uk-hub-cache" - message = "publishes each build into its own folder" - - with pytest.raises(ValueError, match=message): - release_module.prepare_release(uk_dir, artifact_root=artifact_root) - with pytest.raises(ValueError, match=message): - publish_release( - uk_dir, - "policyengine/populace-uk-private", - api=uk_hub, - artifact_root=artifact_root, - update_latest=False, - ) - with pytest.raises(ValueError, match=message): - publish_cli.main([str(uk_dir), "--preflight-only", "--no-latest"]) - - assert uk_hub.events == [] - assert uk_hub.uploads == [] - - -def test_the_tagged_publisher_has_no_pointer_promotion_option(capsys) -> None: - """Only UK releases were made current through latest-.json pointer - files, and they no longer publish here.""" - import inspect - - assert "line" not in inspect.signature(publish_release).parameters - assert "line" not in inspect.signature(release_module.prepare_release).parameters - with pytest.raises(SystemExit): - publish_cli.main(["releases/x", "--promote-line", "national"]) - assert "unrecognized arguments: --promote-line" in capsys.readouterr().err - - -#: A releases.json that the switch to build folders writes; its contents do -#: not matter to the tagged publisher, which refuses once it exists. -_RELEASES_RECORD = json.dumps( - {"schema_version": 1, "default": None, "releases": {}} -).encode() - - -@pytest.mark.parametrize( - "options", - [{}, {"update_latest": False}, {"update_latest": False, "tag_only": True}], - ids=["latest", "no-latest", "tag-only"], -) -def test_the_tagged_publisher_refuses_a_repository_with_releases_json( - hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch, options: dict -) -> None: - """Once a repository records its builds in releases.json, the emitter - publishes there; a tag or pointer file written beside it would disagree - with the record, so the publisher refuses before it writes anything.""" - monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) - hub.seed_main_file("releases.json", _RELEASES_RECORD) - - with pytest.raises(ValueError, match="releases.json") as refusal: - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - **options, - ) - - assert "microcosm-publish-release-build" in str(refusal.value) - assert "takes no new builds there" in str(refusal.value) - assert hub.tags == [] - assert hub.uploads == [] - assert [event for event, _ in hub.events] == [] - - -@pytest.mark.parametrize( - "status_code", [None, 503, 403], ids=["no-answer", "server-error", "forbidden"] -) -def test_the_tagged_publisher_refuses_when_it_cannot_read_releases_json( - hub: FakeHub, - release_dir: Path, - artifact_root: Path, - monkeypatch, - status_code: int | None, -) -> None: - """Only the Hub's 404 for releases.json lets a publication go on. - - huggingface_hub raises LocalEntryNotFoundError, which is also an - EntryNotFoundError and a FileNotFoundError, when it could not ask the - Hub: after a 5xx outlasted its retries, or on a 403. A publication that - went on could write a tag and a pointer file beside a releases.json. - """ - monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) - download = hub.hf_hub_download - - def unreachable(*, repo_id, filename, repo_type, revision=None): - if filename == "releases.json": - raise hub_unreachable(repo_id, filename, revision, status_code=status_code) - return download( - repo_id=repo_id, filename=filename, repo_type=repo_type, revision=revision - ) - - monkeypatch.setattr(hub, "hf_hub_download", unreachable) - - with pytest.raises(LocalEntryNotFoundError): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - ) - - assert hub.tags == [] - assert hub.uploads == [] - assert [event for event, _ in hub.events] == [] - - -def test_the_tagged_publisher_refuses_a_uk_build_folder_release( - release_dir: Path, artifact_root: Path, tmp_path: Path, monkeypatch -) -> None: - """A build in the build-folder layout pins no revision, so the tagged - publisher, which publishes a revision per build, refuses it before any - Hub request.""" - national = _as_uk_national_build_folder_release(release_dir) - monkeypatch.setattr( - release_module, "validate_release_dir", lambda _path, **_kwargs: [] - ) - hub = _uk_hub(tmp_path) - events_before = list(hub.events) - - with pytest.raises(ValueError): - release_module.prepare_release(national, artifact_root=artifact_root) - with pytest.raises(ValueError): - publish_release( - national, - "policyengine/populace-uk-private", - api=hub, - artifact_root=artifact_root, - update_latest=False, - ) - - assert hub.events == events_before - assert hub.tags == [] - assert hub.uploads == [] - - def test_prepare_build_folder_release_lists_each_file_with_its_role( release_dir: Path, artifact_root: Path, monkeypatch ) -> None: @@ -421,17 +169,15 @@ def test_build_folder_identity_says_where_a_tagged_release_publishes( assert "take no new builds" in str(refusal.value) -def test_no_publisher_takes_a_uk_local_area_release_the_registry_does_not_name( +def test_no_build_folder_publication_takes_an_unregistered_uk_local_area_release( artifact_root: Path, tmp_path: Path ) -> None: - """Neither publisher takes a complete bundle of a UK local-area release - that the registry does not name. Each refusal points to the registry, and - the tagged publisher makes no Hub call (microcosm#1586).""" + """Build-folder publication takes no complete bundle of a UK local-area + release that the registry does not name, and each refusal points to the + registry (microcosm#1586).""" from .test_local_area_contract import _write_local_bundle unregistered = _write_local_bundle(tmp_path, release_id=UK_LOCAL_RELEASE_ID) - uk_hub = FakeHub("policyengine/populace-uk-private") - uk_hub._download_dir = tmp_path / "uk-hub-cache" refusals = [] with pytest.raises( @@ -446,881 +192,72 @@ def test_no_publisher_takes_a_uk_local_area_release_the_registry_does_not_name( unregistered, artifact_root=artifact_root ) refusals.append(refusal) - tagged = "publishes through no publisher" - with pytest.raises(ValueError, match=tagged) as refusal: - release_module.prepare_release(unregistered, artifact_root=artifact_root) - refusals.append(refusal) - with pytest.raises(ValueError, match=tagged) as refusal: - publish_release( - unregistered, - "policyengine/populace-uk-private", - api=uk_hub, - artifact_root=artifact_root, - update_latest=False, - ) - refusals.append(refusal) - with pytest.raises(ValueError, match=tagged) as refusal: - publish_cli.main([str(unregistered), "--preflight-only", "--no-latest"]) - refusals.append(refusal) for refusal in refusals: assert release_module.UNREGISTERED_UK_LOCAL_RELEASE_ADVICE in str(refusal.value) assert "take no new builds" not in str(refusal.value) - assert uk_hub.events == [] - assert uk_hub.uploads == [] - - -def test_prepare_build_folder_release_refuses_a_tagged_release( - release_dir: Path, artifact_root: Path -) -> None: - with pytest.raises(ValueError, match="does not publish into build folders"): - release_module.prepare_build_folder_release( - release_dir, artifact_root=artifact_root - ) - - -def test_prepare_build_folder_release_refuses_changed_or_missing_files( - release_dir: Path, artifact_root: Path, monkeypatch -) -> None: - national = _as_uk_national_build_folder_release(release_dir) - monkeypatch.setattr( - release_module, "validate_release_dir", lambda _path, **_kwargs: [] - ) - (artifact_root / "populace_us_2024.h5").write_bytes(b"other bytes") - with pytest.raises(ValueError, match="populace_us_2024.h5 has sha256"): - release_module.prepare_build_folder_release( - national, artifact_root=artifact_root - ) - (artifact_root / "populace_us_2024.h5").unlink() - with pytest.raises(FileNotFoundError, match="populace_us_2024.h5"): - release_module.prepare_build_folder_release( - national, artifact_root=artifact_root - ) - - -def test_prepare_build_folder_release_publishes_to_one_repository( - release_dir: Path, artifact_root: Path, monkeypatch -) -> None: - national = _as_uk_national_build_folder_release(release_dir) - monkeypatch.setattr( - release_module, "validate_release_dir", lambda _path, **_kwargs: [] - ) - with pytest.raises(ValueError, match="names policyengine/populace-uk-private"): - release_module.prepare_build_folder_release( - national, artifact_root=artifact_root, repository="policyengine/other" - ) - manifest_path = national / "release_manifest.json" - manifest = json.loads(manifest_path.read_text()) - manifest["artifacts"]["calibration_diagnostics"]["repo_id"] = "policyengine/other" - manifest_path.write_text(json.dumps(manifest)) - with pytest.raises(ValueError, match="more than one repository"): - release_module.prepare_build_folder_release( - national, artifact_root=artifact_root - ) - - -def test_line_promotion_alert_names_the_line_and_revision() -> None: - from microcosm.data.slack import notify_release - - sent: list = [] - assert notify_release( - "policyengine/populace-uk-private", - UK_NATIONAL_RELEASE_ID, - webhook="https://hooks.slack.test/uk", - post=lambda url, payload: sent.append((url, payload)), - line="national", - revision=UK_NATIONAL_CUT_TAG, - ) - headline = sent[0][1]["blocks"][0]["text"]["text"] - assert "line promoted" in headline - assert "national" in headline - assert UK_NATIONAL_CUT_TAG in headline - - -def test_publish_release_announces_after_pointer( - hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch -) -> None: - """The alert fires from publish_release itself — every publish path, not - just the CLI — with the released id and timestamp.""" - calls: list = [] - monkeypatch.setattr( - "microcosm.data.release.notify_release", - lambda repo_id, release_id, updated_at, **kw: calls.append( - (repo_id, release_id, updated_at, kw) - ), - ) - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - updated_at="2026-06-11T13:53:15+00:00", - ) - assert calls == [ - ( - "policyengine/populace-us", - RELEASE_ID, - "2026-06-11T13:53:15+00:00", - {"warn_if_unset": True}, - ) - ] - - -def test_publish_release_notify_false_skips_alert( - hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch -) -> None: - calls: list = [] - monkeypatch.setattr( - "microcosm.data.release.notify_release", lambda *a, **k: calls.append(a) - ) - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - notify=False, - ) - assert calls == [] - - -def test_publish_uploads_pointer_last( - hub: FakeHub, release_dir: Path, artifact_root: Path -) -> None: - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - updated_at="2026-06-11T13:53:15+00:00", - ) - final_event, final_commit = hub.events[-1] - assert final_event == "create_commit" - assert final_commit["revision"] == "main" - assert final_commit["paths"][-1] == LATEST_POINTER_PATH - for filename in required_release_files(RELEASE_ID): - assert f"releases/{RELEASE_ID}/{filename}" in final_commit["paths"][:-1] - - -def test_publish_no_latest_never_touches_pointer( - hub: FakeHub, release_dir: Path, artifact_root: Path -) -> None: - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - updated_at="2026-06-11T13:53:15+00:00", - update_latest=False, - ) - # Immutable branch + tag flow is unchanged; the final main commit exists - # (release copies + root artifacts) but carries NO pointer operation. - assert [event for event, _ in hub.events] == [ - "create_branch", - "create_commit", - "create_tag", - "delete_branch", - "create_commit", - ] - final_event, final_commit = hub.events[-1] - assert final_event == "create_commit" - assert final_commit["revision"] == "main" - assert LATEST_POINTER_PATH not in final_commit["paths"] - assert final_commit["message"] == f"Publish non-default release {RELEASE_ID}" - assert { - "populace_us_2024.h5", - "populace_us_2024_calibration.npz", - }.issubset(final_commit["paths"]) - - -def test_exact_k_tag_only_publish_never_mutates_main( - hub: FakeHub, release_dir: Path, artifact_root: Path -) -> None: - main_before = hub._refs["main"] - - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - updated_at="2026-06-11T13:53:15+00:00", - update_latest=False, - tag_only=True, - ) - - assert [event for event, _ in hub.events] == [ - "create_branch", - "create_commit", - "create_tag", - "delete_branch", - ] - assert hub._refs["main"] == main_before - - canonical_root_paths = { - "populace_us_2024.h5", - "populace_us_2024_calibration.npz", - } - main_commit_paths = { - path - for event, receipt in hub.events - if event == "create_commit" and receipt["revision"] == "main" - for path in receipt["paths"] - } - canonical_root_mutation_present = bool(canonical_root_paths & main_commit_paths) - assert canonical_root_mutation_present is False - assert canonical_root_paths.isdisjoint(main_commit_paths) - - immutable = hub.events[1][1] - assert canonical_root_paths.issubset(immutable["paths"]) - assert { - f"releases/{RELEASE_ID}/{filename}" - for filename in required_release_files(RELEASE_ID) - }.issubset(immutable["paths"]) - assert hub.tags == [{"tag": RELEASE_ID, "revision": immutable["commit"]}] - - tagged_manifest = Path( - hub.hf_hub_download( - repo_id="policyengine/populace-us", - filename=f"releases/{RELEASE_ID}/release_manifest.json", - repo_type="dataset", - revision=RELEASE_ID, - ) - ) - tagged_h5 = Path( - hub.hf_hub_download( - repo_id="policyengine/populace-us", - filename="populace_us_2024.h5", - repo_type="dataset", - revision=RELEASE_ID, - ) - ) - assert ( - tagged_manifest.read_bytes() - == (release_dir / "release_manifest.json").read_bytes() - ) - assert ( - tagged_h5.read_bytes() == (artifact_root / "populace_us_2024.h5").read_bytes() - ) - with pytest.raises(FileNotFoundError, match="populace_us_2024.h5@main"): - hub.hf_hub_download( - repo_id="policyengine/populace-us", - filename="populace_us_2024.h5", - repo_type="dataset", - ) - - -@pytest.mark.parametrize("tag_only", [True, False], ids=["tag-only", "no-latest"]) -def test_us_default_flip_after_a_non_default_publish_reuses_the_release_tag( - hub: FakeHub, release_dir: Path, artifact_root: Path, tag_only: bool, monkeypatch -) -> None: - """microcosm#450: publish immutable now, make it the default later. - - The first call cuts the release-id tag without touching ``latest.json`` - (``--tag-only`` or ``--no-latest``). The flip is the plain default - publish of the same release directory: it recognises the tag that - already describes this release, writes no second immutable revision - and no second tag, and lands only the main commit carrying the pointer. - Before #966 the flip died on ``create_tag`` with a 409. - """ - monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - updated_at="2026-06-11T13:53:15+00:00", - update_latest=False, - tag_only=tag_only, - ) - tags_after_cut = list(hub.tags) - assert [tag["tag"] for tag in tags_after_cut] == [RELEASE_ID] - tagged_revision = hub._refs[RELEASE_ID] - assert LATEST_POINTER_PATH not in hub._commits[hub._refs["main"]] - main_before_flip = hub._refs["main"] - events_after_cut = len(hub.events) - - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - updated_at="2026-06-12T09:00:00+00:00", - ) - - flip_events = hub.events[events_after_cut:] - assert [event for event, _ in flip_events] == ["create_commit"] - flip = flip_events[0][1] - assert flip["revision"] == "main" - assert flip["parent_commit"] == main_before_flip - assert LATEST_POINTER_PATH in flip["paths"] - assert hub.tags == tags_after_cut - assert hub._refs[RELEASE_ID] == tagged_revision - pointer = latest_release("policyengine/populace-us", api=hub) - assert pointer.release_id == RELEASE_ID - - -def test_us_default_flip_refuses_a_release_tag_that_describes_another_cut( - hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch -) -> None: - """microcosm#450: the flip reuses a tag only when it is this release. - - A local release directory whose manifest differs from the tagged one - (a rebuilt cut under the same release id) must refuse before any main - commit, so the default pointer never names bytes nobody published. - """ - monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - updated_at="2026-06-11T13:53:15+00:00", - update_latest=False, - tag_only=True, - ) - main_before_flip = hub._refs["main"] - events_after_cut = len(hub.events) - manifest_path = release_dir / "release_manifest.json" - manifest_path.write_bytes(manifest_path.read_bytes() + b"\n") - - with pytest.raises(ValueError, match="describes another"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - updated_at="2026-06-12T09:00:00+00:00", - ) - - assert hub.events[events_after_cut:] == [] - assert hub._refs["main"] == main_before_flip - - -@pytest.mark.parametrize( - ("publish_options", "message"), - [ - ({"update_latest": True}, "requires update_latest=False"), - ( - {"update_latest": False, "create_tag": False}, - "requires create_tag=True", - ), - ], -) -def test_tag_only_rejects_unsafe_modes_before_remote_mutation( - hub: FakeHub, - release_dir: Path, - artifact_root: Path, - publish_options: dict, - message: str, -) -> None: - with pytest.raises(ValueError, match=message): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - tag_only=True, - **publish_options, - ) - - assert hub.events == [] - assert hub.uploads == [] - - -def test_publish_commits_immutable_release_before_root_and_pointer( - hub: FakeHub, release_dir: Path, artifact_root: Path -) -> None: - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - updated_at="2026-06-11T13:53:15+00:00", - ) - assert [event for event, _ in hub.events] == [ - "create_branch", - "create_commit", - "create_tag", - "delete_branch", - "create_commit", - ] - - staging_branch = f"release-staging/{RELEASE_ID}" - immutable = hub.events[1][1] - assert immutable["revision"] == staging_branch - assert set(immutable["paths"]) == { - "populace_us_2024.h5", - "populace_us_2024_calibration.npz", - *{ - f"releases/{RELEASE_ID}/{filename}" - for filename in required_release_files(RELEASE_ID) - }, - # The gate verdicts are manifest artifacts, so the immutable release - # commit carries them without --extra-file, the stored-input verdict - # the contract requires (microcosm#1034) among them. - *{ - f"releases/{RELEASE_ID}/{filename}" - for filename in (*GATE_EVIDENCE_FILES.values(), "stored_inputs.json") - }, - } - assert LATEST_POINTER_PATH not in immutable["paths"] - - tag = hub.events[2][1] - assert tag == {"tag": RELEASE_ID, "revision": immutable["commit"]} - assert hub.events[3] == ("delete_branch", {"branch": staging_branch}) - - convenience = hub.events[4][1] - assert convenience["revision"] == "main" - assert convenience["parent_commit"] == "commit-0" - assert convenience["paths"][-3:] == [ - "populace_us_2024.h5", - "populace_us_2024_calibration.npz", - LATEST_POINTER_PATH, - ] - assert hub.tags == [{"tag": RELEASE_ID, "revision": immutable["commit"]}] - - -def test_failed_main_commit_leaves_root_and_pointer_unchanged( - hub: FakeHub, release_dir: Path, artifact_root: Path -) -> None: - old_pointer = b'{"release_id": "old-release"}' - old_artifact = b"old certified root artifact" - hub.seed_main_file(LATEST_POINTER_PATH, old_pointer) - hub.seed_main_file("populace_us_2024.h5", old_artifact) - hub.fail_main_commit = True - - with pytest.raises(RuntimeError, match="injected main commit failure"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - ) - - main_commit = hub._commits[hub._refs["main"]] - assert main_commit[LATEST_POINTER_PATH] == old_pointer - assert main_commit["populace_us_2024.h5"] == old_artifact - assert hub.tags == [{"tag": RELEASE_ID, "revision": "commit-1"}] - assert hub.events[-1][0] == "create_commit_failed" - - -def test_non_atomic_backend_is_refused_before_remote_mutation( - hub: FakeHub, release_dir: Path, artifact_root: Path -) -> None: - with pytest.raises(TypeError, match="immutable-first and atomic"): - publish_release( - release_dir, - "policyengine/populace-us", - api=NonAtomicHub(hub), - artifact_root=artifact_root, - ) - - assert hub.events == [] - assert hub.uploads == [] - - -def test_publish_uploads_manifest_release_diagnostics_from_release_dir( - hub: FakeHub, release_dir: Path, artifact_root: Path -) -> None: - (release_dir / "reform_validation.json").write_text('{"schema_version": 1}') - manifest_path = release_dir / "release_manifest.json" - manifest = json.loads(manifest_path.read_text()) - manifest["artifacts"]["reform_validation"] = { - "kind": "diagnostics", - "path": "reform_validation.json", - "repo_id": "policyengine/populace-us", - "revision": RELEASE_ID, - "sha256": _sha256(release_dir / "reform_validation.json"), - } - manifest_path.write_text(json.dumps(manifest)) - - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - updated_at="2026-06-11T13:53:15+00:00", - ) - - uploaded_paths = [path for path, _ in hub.uploads] - release_path = f"releases/{RELEASE_ID}/reform_validation.json" - assert "reform_validation.json" not in uploaded_paths - assert release_path in uploaded_paths - assert uploaded_paths.index(release_path) < uploaded_paths.index( - LATEST_POINTER_PATH - ) - - -def test_publish_uploads_ssi_take_up_diagnostics_without_extra_files( - hub: FakeHub, release_dir: Path, artifact_root: Path -) -> None: - diagnostics_path = release_dir / "us_ssi_take_up.json" - diagnostics_path.write_text('{"schema_version": 1}') - manifest_path = release_dir / "release_manifest.json" - manifest = json.loads(manifest_path.read_text()) - manifest["artifacts"]["us_ssi_take_up"] = { - "kind": "diagnostics", - "path": diagnostics_path.name, - "repo_id": "policyengine/populace-us", - "revision": RELEASE_ID, - "sha256": _sha256(diagnostics_path), - } - manifest_path.write_text(json.dumps(manifest)) - - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - updated_at="2026-06-11T13:53:15+00:00", - ) - - uploaded_paths = [path for path, _ in hub.uploads] - release_path = f"releases/{RELEASE_ID}/{diagnostics_path.name}" - assert diagnostics_path.name not in uploaded_paths - assert release_path in uploaded_paths - assert uploaded_paths.index(release_path) < uploaded_paths.index( - LATEST_POINTER_PATH - ) - - -def test_publish_requires_artifact_root_for_root_artifacts( - hub: FakeHub, release_dir: Path -) -> None: - with pytest.raises(ValueError, match="pass artifact_root"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - ) - assert hub.uploads == [] - - -def test_missing_root_artifact_uploads_nothing( - hub: FakeHub, release_dir: Path, artifact_root: Path -) -> None: - (artifact_root / "populace_us_2024_calibration.npz").unlink() - with pytest.raises(FileNotFoundError, match="populace_us_2024_calibration"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - ) - assert hub.uploads == [] - - -def test_root_artifact_hash_mismatch_uploads_nothing( - hub: FakeHub, release_dir: Path, artifact_root: Path -) -> None: - (artifact_root / "populace_us_2024.h5").write_bytes(b"wrong payload") - with pytest.raises(ValueError, match="release artifact 'populace_us_2024.h5'"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - ) - assert hub.uploads == [] - - -def test_release_tag_is_created_before_pointer( - hub: FakeHub, release_dir: Path, artifact_root: Path -) -> None: - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - create_tag=True, - updated_at="2026-06-11T13:53:15+00:00", - ) - assert hub.tags == [{"tag": RELEASE_ID, "revision": "commit-1"}] - assert [event for event, _ in hub.events][-3:] == [ - "create_tag", - "delete_branch", - "create_commit", - ] - assert hub.uploads[-1][0] == LATEST_POINTER_PATH - - -def test_release_id_artifact_revision_requires_release_tag( - hub: FakeHub, release_dir: Path, artifact_root: Path -) -> None: - with pytest.raises(ValueError, match="pins artifacts to revisions.*must create"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - create_tag=False, - ) - assert hub.uploads == [] - assert hub.tags == [] - - -def test_release_id_artifact_revision_rejects_tag_name_override( - hub: FakeHub, release_dir: Path, artifact_root: Path -) -> None: - with pytest.raises(ValueError, match="tag_name must match.*artifact revision"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - tag_name="different-tag", - ) - assert hub.uploads == [] - assert hub.tags == [] - - -def test_per_cut_artifact_revision_publishes_matching_tag_without_latest( - hub: FakeHub, - release_dir: Path, - artifact_root: Path, - monkeypatch, -) -> None: - cut_tag = RELEASE_ID + "-20260828T101112Z-1a2b3c4d" - manifest_path = release_dir / "release_manifest.json" - manifest = json.loads(manifest_path.read_text()) - for artifact in manifest["artifacts"].values(): - artifact["revision"] = cut_tag - manifest_path.write_text(json.dumps(manifest)) - monkeypatch.setattr( - release_module, "validate_release_dir", lambda _path, **_kwargs: [] - ) - - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - tag_name=cut_tag, - update_latest=False, - ) - - assert hub.tags == [{"tag": cut_tag, "revision": "commit-1"}] - assert all(path != LATEST_POINTER_PATH for path, _payload in hub.uploads) - - -def test_per_cut_artifact_revision_refuses_dangling_default_tag( - hub: FakeHub, - release_dir: Path, - artifact_root: Path, - monkeypatch, -) -> None: - cut_tag = RELEASE_ID + "-20260828T101112Z-1a2b3c4d" - manifest_path = release_dir / "release_manifest.json" - manifest = json.loads(manifest_path.read_text()) - for artifact in manifest["artifacts"].values(): - artifact["revision"] = cut_tag - manifest_path.write_text(json.dumps(manifest)) - monkeypatch.setattr( - release_module, "validate_release_dir", lambda _path, **_kwargs: [] - ) - - with pytest.raises(ValueError, match="uniform per-cut artifact revision"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - ) - assert hub.uploads == [] - assert hub.tags == [] - - -def test_unreadable_artifact_revisions_refuse_instead_of_vanishing( - hub: FakeHub, - release_dir: Path, - artifact_root: Path, - monkeypatch, -) -> None: - # A non-string revision must not shrink the pin set into vacuous guards: - # the empty set may only ever mean "no artifacts declared", never - # "artifacts whose pins could not be read". - manifest_path = release_dir / "release_manifest.json" - manifest = json.loads(manifest_path.read_text()) - for artifact in manifest["artifacts"].values(): - artifact["revision"] = 123 - manifest_path.write_text(json.dumps(manifest)) - monkeypatch.setattr( - release_module, "validate_release_dir", lambda _path, **_kwargs: [] - ) - - with pytest.raises(ValueError, match="missing or non-string revisions"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - ) - assert hub.uploads == [] - assert hub.tags == [] - - -def test_empty_artifact_revisions_refuse_publication( - hub: FakeHub, - release_dir: Path, - artifact_root: Path, - monkeypatch, -) -> None: - manifest_path = release_dir / "release_manifest.json" - manifest = json.loads(manifest_path.read_text()) - manifest["artifacts"] = {} - manifest_path.write_text(json.dumps(manifest)) - monkeypatch.setattr( - release_module, "validate_release_dir", lambda _path, **_kwargs: [] - ) - - with pytest.raises(ValueError, match="declares no artifact revisions"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - ) - assert hub.uploads == [] - assert hub.tags == [] - - -def test_per_cut_tag_refuses_latest_promotion( - hub: FakeHub, - release_dir: Path, - artifact_root: Path, - monkeypatch, -) -> None: - # The pointer may only ever name a release whose tag IS the release id: - # a per-cut inspect tag with the default update_latest must refuse before - # any remote mutation, not promote. - cut_tag = RELEASE_ID + "-20260828T101112Z-1a2b3c4d" - manifest_path = release_dir / "release_manifest.json" - manifest = json.loads(manifest_path.read_text()) - for artifact in manifest["artifacts"].values(): - artifact["revision"] = cut_tag - manifest_path.write_text(json.dumps(manifest)) - monkeypatch.setattr( - release_module, "validate_release_dir", lambda _path, **_kwargs: [] - ) - - with pytest.raises(ValueError, match="inspect-only"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - tag_name=cut_tag, - ) - assert hub.uploads == [] - assert hub.tags == [] - assert hub.events == [] - - -def test_invalid_release_uploads_nothing(hub: FakeHub, release_dir: Path) -> None: - (release_dir / "build_manifest.json").unlink() - with pytest.raises(ReleaseContractError): - publish_release(release_dir, "policyengine/populace-us", api=hub) - assert hub.uploads == [] - - -def test_invalid_calibration_diagnostics_uploads_nothing( - hub: FakeHub, release_dir: Path -) -> None: - (release_dir / "calibration_diagnostics.json").write_text("{}") - with pytest.raises(ReleaseContractError, match="calibration_diagnostics"): - publish_release(release_dir, "policyengine/populace-us", api=hub) - assert hub.uploads == [] - - -def test_failed_diagnostics_publish_dataset_and_omit_diagnostics_path( - hub: FakeHub, - release_dir: Path, - artifact_root: Path, -) -> None: - (release_dir / "calibration_diagnostics.json").unlink() - manifest_path = release_dir / "release_manifest.json" - manifest = json.loads(manifest_path.read_text()) - manifest["artifacts"].pop("calibration_diagnostics") - manifest["calibration_diagnostics"] = { - "status": "failed", - "expected_schema_version": 8, - "error_code": "validation_error", - "message": "Target hierarchy is incomplete.", - } - manifest_path.write_text(json.dumps(manifest)) - - with pytest.warns(UserWarning, match="generation failed"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - ) - - uploaded_paths = [path for path, _ in hub.uploads] - assert f"releases/{RELEASE_ID}/calibration_diagnostics.json" not in uploaded_paths - pointer_bytes = next( - content for path, content in hub.uploads if path == LATEST_POINTER_PATH - ) - pointer = json.loads(pointer_bytes) - assert "calibration_diagnostics" not in pointer["paths"] - assert "populace_us_2024.h5" in uploaded_paths -def test_nonstandard_nan_calibration_diagnostics_uploads_nothing( - hub: FakeHub, release_dir: Path +def test_prepare_build_folder_release_refuses_a_tagged_release( + release_dir: Path, artifact_root: Path ) -> None: - (release_dir / "calibration_diagnostics.json").write_text( - '{"schema_version": 4, "targets": [], "loss_trajectory": [NaN], ' - '"skipped": [], "options": {}}' - ) - with pytest.raises(ReleaseContractError, match="calibration_diagnostics"): - publish_release(release_dir, "policyengine/populace-us", api=hub) - assert hub.uploads == [] + with pytest.raises(ValueError, match="does not publish into build folders"): + release_module.prepare_build_folder_release( + release_dir, artifact_root=artifact_root + ) -def test_extra_files_ride_along_before_the_pointer( - hub: FakeHub, release_dir: Path, artifact_root: Path +def test_prepare_build_folder_release_refuses_changed_or_missing_files( + release_dir: Path, artifact_root: Path, monkeypatch ) -> None: - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - extra_files=("calibration_diagnostics.json",), + national = _as_uk_national_build_folder_release(release_dir) + monkeypatch.setattr( + release_module, "validate_release_dir", lambda _path, **_kwargs: [] ) - uploaded_paths = [path for path, _ in hub.uploads] - extra = f"releases/{RELEASE_ID}/calibration_diagnostics.json" - assert extra in uploaded_paths - assert uploaded_paths.index(extra) < uploaded_paths.index(LATEST_POINTER_PATH) - - -def test_missing_extra_file_fails_loudly(hub: FakeHub, release_dir: Path) -> None: - with pytest.raises(FileNotFoundError, match="support_audit"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - extra_files=("support_audit.json",), + (artifact_root / "populace_us_2024.h5").write_bytes(b"other bytes") + with pytest.raises(ValueError, match="populace_us_2024.h5 has sha256"): + release_module.prepare_build_folder_release( + national, artifact_root=artifact_root + ) + (artifact_root / "populace_us_2024.h5").unlink() + with pytest.raises(FileNotFoundError, match="populace_us_2024.h5"): + release_module.prepare_build_folder_release( + national, artifact_root=artifact_root ) - assert hub.uploads == [] -def test_publish_then_resolve_round_trips( - hub: FakeHub, release_dir: Path, artifact_root: Path +def test_prepare_build_folder_release_publishes_to_one_repository( + release_dir: Path, artifact_root: Path, monkeypatch ) -> None: - published = publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - updated_at="2026-06-11T13:53:15+00:00", + national = _as_uk_national_build_folder_release(release_dir) + monkeypatch.setattr( + release_module, "validate_release_dir", lambda _path, **_kwargs: [] ) + with pytest.raises(ValueError, match="names policyengine/populace-uk-private"): + release_module.prepare_build_folder_release( + national, artifact_root=artifact_root, repository="policyengine/other" + ) + manifest_path = national / "release_manifest.json" + manifest = json.loads(manifest_path.read_text()) + manifest["artifacts"]["calibration_diagnostics"]["repo_id"] = "policyengine/other" + manifest_path.write_text(json.dumps(manifest)) + with pytest.raises(ValueError, match="more than one repository"): + release_module.prepare_build_folder_release( + national, artifact_root=artifact_root + ) + + +def test_latest_release_reads_a_certified_pointer(hub: FakeHub) -> None: + payload = latest_pointer_payload(RELEASE_ID, updated_at="2026-06-11T13:53:15+00:00") + hub.seed_main_file(LATEST_POINTER_PATH, json.dumps(payload).encode()) + pointer = latest_release("policyengine/populace-us", api=hub) + assert pointer.release_id == RELEASE_ID assert pointer.revision == RELEASE_ID assert pointer.line is None assert pointer.updated_at == "2026-06-11T13:53:15+00:00" - assert pointer.paths == published["paths"] + assert pointer.paths == payload["paths"] @pytest.mark.parametrize("field", ["line", "revision"]) @@ -1422,122 +359,14 @@ def test_evidence_pointer_payload_mirrors_the_certified_payload() -> None: assert payload == {**certified_shape, "tier": "evidence"} -def test_publish_evidence_release_never_touches_the_certified_pointer( - hub: FakeHub, evidence_release_dir: Path, artifact_root: Path -) -> None: - payload = publish_release( - evidence_release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - updated_at="2026-07-22T13:53:15+00:00", - evidence=True, - ) - assert payload["tier"] == "evidence" - assert payload["release_id"] == EVIDENCE_RELEASE_ID - # Immutable tag flow unchanged: the tag is the evidence release id. - assert [tag["tag"] for tag in hub.tags] == [EVIDENCE_RELEASE_ID] - # The evidence pointer lands last, in the final main commit. - final_event, final_commit = hub.events[-1] - assert final_event == "create_commit" - assert final_commit["paths"][-1] == LATEST_EVIDENCE_POINTER_PATH - # The certified pointer is never written, anywhere in the flow. - assert all(path != LATEST_POINTER_PATH for path, _ in hub.uploads) - published = json.loads(dict(hub.uploads)[LATEST_EVIDENCE_POINTER_PATH]) - assert published["tier"] == "evidence" - assert published["release_id"] == EVIDENCE_RELEASE_ID - - -def test_publish_evidence_release_refuses_a_certified_release_dir( - hub: FakeHub, release_dir: Path, artifact_root: Path -) -> None: - """--evidence on a certified-shape release: refused, nothing uploaded. - The tier must be declared by the artifact, not chosen at publish time.""" - with pytest.raises(ReleaseContractError): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - evidence=True, - ) - assert hub.uploads == [] - - -def test_certified_publish_refuses_an_evidence_release_dir( - hub: FakeHub, evidence_release_dir: Path, artifact_root: Path -) -> None: - with pytest.raises(ReleaseContractError): - publish_release( - evidence_release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - ) - assert hub.uploads == [] - - -def test_publish_evidence_no_latest_skips_the_evidence_pointer( - hub: FakeHub, evidence_release_dir: Path, artifact_root: Path -) -> None: - publish_release( - evidence_release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - update_latest=False, - evidence=True, - ) - final_event, final_commit = hub.events[-1] - assert final_event == "create_commit" - assert LATEST_EVIDENCE_POINTER_PATH not in final_commit["paths"] - assert all(path != LATEST_POINTER_PATH for path, _ in hub.uploads) - assert ( - final_commit["message"] - == f"Publish non-default evidence release {EVIDENCE_RELEASE_ID}" - ) - - -def test_publish_evidence_release_announces_the_tier( - hub: FakeHub, evidence_release_dir: Path, artifact_root: Path, monkeypatch -) -> None: - calls: list = [] - monkeypatch.setattr( - "microcosm.data.release.notify_release", - lambda repo_id, release_id, updated_at, **kw: calls.append( - (repo_id, release_id, updated_at, kw) - ), - ) - publish_release( - evidence_release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - updated_at="2026-07-22T13:53:15+00:00", - evidence=True, +def test_latest_evidence_release_reads_an_evidence_pointer(hub: FakeHub) -> None: + payload = latest_evidence_pointer_payload( + EVIDENCE_RELEASE_ID, updated_at="2026-07-22T13:53:15+00:00" ) - assert calls == [ - ( - "policyengine/populace-us", - EVIDENCE_RELEASE_ID, - "2026-07-22T13:53:15+00:00", - {"warn_if_unset": True, "tier": "evidence"}, - ) - ] - + hub.seed_main_file(LATEST_EVIDENCE_POINTER_PATH, json.dumps(payload).encode()) -def test_publish_then_latest_evidence_release_round_trips( - hub: FakeHub, evidence_release_dir: Path, artifact_root: Path -) -> None: - publish_release( - evidence_release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - updated_at="2026-07-22T13:53:15+00:00", - evidence=True, - ) pointer = latest_evidence_release("policyengine/populace-us", api=hub) + assert pointer.release_id == EVIDENCE_RELEASE_ID assert pointer.revision == EVIDENCE_RELEASE_ID assert pointer.line is None @@ -1710,22 +539,6 @@ def test_certified_latest_pointer_keeps_its_certified_shape(hub: FakeHub) -> Non assert pointer.tier == "certified" -def test_certified_publish_never_touches_the_evidence_pointer( - hub: FakeHub, release_dir: Path, artifact_root: Path -) -> None: - """The converse of the evidence-pointer isolation: a certified publish - moves latest.json only, never latest-evidence.json.""" - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - updated_at="2026-06-11T13:53:15+00:00", - ) - assert any(path == LATEST_POINTER_PATH for path, _ in hub.uploads) - assert all(path != LATEST_EVIDENCE_POINTER_PATH for path, _ in hub.uploads) - - def test_latest_release_refuses_any_tier_field(hub: FakeHub) -> None: """No certified producer writes a tier field; even 'certified' or null is foreign and refused rather than consumed as the default.""" @@ -1737,251 +550,6 @@ def test_latest_release_refuses_any_tier_field(hub: FakeHub) -> None: latest_release("policyengine/populace-us", api=hub) -def test_publish_refuses_root_artifacts_at_pointer_paths( - hub: FakeHub, release_dir: Path, evidence_release_dir: Path, artifact_root: Path -) -> None: - """A manifest-declared root artifact must not be able to smuggle a - pointer write past the tier's pointer selection — in either direction.""" - _declare_root_artifact( - evidence_release_dir, key="smuggled_pointer", path=LATEST_POINTER_PATH - ) - with pytest.raises(ValueError, match="reserved"): - publish_release( - evidence_release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - update_latest=False, - evidence=True, - ) - assert hub.uploads == [] - - _declare_root_artifact( - release_dir, key="smuggled_pointer", path=LATEST_EVIDENCE_POINTER_PATH - ) - with pytest.raises(ValueError, match="reserved"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - ) - assert hub.uploads == [] - - -@pytest.mark.parametrize( - "pointer_path", - [ - "latest-national.json", - "latest-local-k55000.json", - "latest-future-line-123.json", - ], -) -def test_publish_refuses_root_artifacts_at_every_reserved_line_pointer_path( - hub: FakeHub, - release_dir: Path, - artifact_root: Path, - pointer_path: str, -) -> None: - _declare_root_artifact(release_dir, key="smuggled_line_pointer", path=pointer_path) - - with pytest.raises(ValueError, match="reserved pointer path"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - ) - - assert hub.uploads == [] - - -def test_publish_refuses_unclean_root_artifact_paths( - hub: FakeHub, evidence_release_dir: Path, artifact_root: Path -) -> None: - """'./latest.json' must not dodge the reserved-path comparison and get - canonicalized to the pointer by the Hub afterwards (sol round-2).""" - _declare_root_artifact( - evidence_release_dir, key="smuggled_pointer", path=f"./{LATEST_POINTER_PATH}" - ) - with pytest.raises(ValueError, match="clean relative POSIX path"): - publish_release( - evidence_release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - update_latest=False, - evidence=True, - ) - assert hub.uploads == [] - - -def test_publish_refuses_path_components_in_extra_files( - hub: FakeHub, release_dir: Path, artifact_root: Path -) -> None: - """extra_files land under releases// — a traversal name could escape - that prefix once the service canonicalizes the path.""" - outside = release_dir.parent / "escape.json" - outside.write_text("{}") - with pytest.raises(ValueError, match="bare file name"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - extra_files=("../escape.json",), - ) - assert hub.uploads == [] - - -@pytest.mark.parametrize( - ("condition", "error_type", "message"), - [ - ("extra-file-traversal", ValueError, "bare file name"), - ("missing-extra-file", FileNotFoundError, "extra release file"), - ("tag-mismatch", ValueError, "tag_name must match"), - ("no-create-tag", ValueError, "must create the matching"), - ("missing-artifact-root", ValueError, "pass artifact_root"), - ("missing-root-artifact", FileNotFoundError, "release artifact"), - ("root-artifact-hash-mismatch", ValueError, "has sha256"), - ("reserved-pointer-path", ValueError, "reserved pointer path"), - ("unclean-root-path", ValueError, "clean relative POSIX path"), - ("gate-evidence-hash-mismatch", ReleaseContractError, "declares sha256"), - ("missing-gate-evidence", FileNotFoundError, "qrf_tail_concentration"), - ], -) -def test_cli_preflight_matches_publisher_guards_before_hub_activity( - hub: FakeHub, - release_dir: Path, - artifact_root: Path, - monkeypatch, - condition: str, - error_type: type[Exception], - message: str, -) -> None: - """Real contracts used to pass CLI preflight despite these publisher errors.""" - kwargs = {"artifact_root": artifact_root} - cli_args = [str(release_dir), "--artifact-root", str(artifact_root)] - if condition == "extra-file-traversal": - (release_dir.parent / "escape.json").write_text("{}") - kwargs["extra_files"] = ("../escape.json",) - cli_args.extend(["--extra-file", "../escape.json"]) - elif condition == "missing-extra-file": - kwargs["extra_files"] = ("missing.json",) - cli_args.extend(["--extra-file", "missing.json"]) - elif condition == "tag-mismatch": - kwargs["tag_name"] = "different-tag" - cli_args.extend(["--tag-name", "different-tag"]) - elif condition == "no-create-tag": - kwargs["create_tag"] = False - cli_args.append("--no-create-tag") - elif condition == "missing-artifact-root": - kwargs = {} - cli_args = [str(release_dir)] - elif condition == "missing-root-artifact": - (artifact_root / "populace_us_2024_calibration.npz").unlink() - elif condition == "root-artifact-hash-mismatch": - (artifact_root / "populace_us_2024.h5").write_bytes(b"wrong payload") - elif condition == "reserved-pointer-path": - _declare_root_artifact( - release_dir, key="smuggled_pointer", path=LATEST_EVIDENCE_POINTER_PATH - ) - elif condition == "unclean-root-path": - _declare_root_artifact( - release_dir, key="smuggled_pointer", path=f"./{LATEST_POINTER_PATH}" - ) - elif condition == "gate-evidence-hash-mismatch": - # A verdict edited after the manifest bound it (route A PR-3). - (release_dir / "qrf_tail_concentration.json").write_text("{}") - elif condition == "missing-gate-evidence": - # A bound verdict that is not on disk cannot ship: the publisher - # looks for it as a root artifact and refuses. - (release_dir / "qrf_tail_concentration.json").unlink() - else: - raise AssertionError(f"unhandled condition: {condition}") - - def unexpected_hub_activity(*args, **kwargs): - pytest.fail("invalid local publication must fail before any Hub activity") - - monkeypatch.setattr(release_module, "_hf_api", unexpected_hub_activity) - # FakeHub logs writes; forbid its read methods too, so an empty event log - # proves these failures occurred before any supplied-client activity. - monkeypatch.setattr(hub, "repo_info", unexpected_hub_activity) - monkeypatch.setattr(hub, "hf_hub_download", unexpected_hub_activity) - - with pytest.raises(error_type, match=message) as publication_error: - publish_release(release_dir, "policyengine/populace-us", **kwargs) - with pytest.raises(error_type) as supplied_hub_error: - publish_release(release_dir, "policyengine/populace-us", api=hub, **kwargs) - with pytest.raises(error_type) as cli_publication_error: - publish_cli.main(cli_args) - with pytest.raises(error_type) as preflight_error: - publish_cli.main([*cli_args, "--preflight-only"]) - - for error in (supplied_hub_error, cli_publication_error, preflight_error): - assert type(error.value) is type(publication_error.value) - assert str(error.value) == str(publication_error.value) - assert hub.events == [] - assert hub.uploads == [] - assert hub.tags == [] - - -def test_cli_valid_preflight_performs_no_publication_or_notification( - release_dir: Path, artifact_root: Path, monkeypatch, capsys -) -> None: - def unexpected_side_effect(*args, **kwargs): - pytest.fail("preflight must not construct a Hub client, publish, or notify") - - monkeypatch.setattr(release_module, "_hf_api", unexpected_side_effect) - monkeypatch.setattr(release_module, "notify_release", unexpected_side_effect) - monkeypatch.setattr(publish_cli, "publish_release", unexpected_side_effect) - - assert ( - publish_cli.main( - [ - str(release_dir), - "--artifact-root", - str(artifact_root), - "--preflight-only", - ] - ) - == 0 - ) - assert json.loads(capsys.readouterr().out) == {"valid": True, "published": False} - - -def test_preflight_prepares_the_bound_gate_evidence_for_upload( - release_dir: Path, artifact_root: Path -) -> None: - """Route A remediation PR-3: prepare_release uploads only contract files, - manifest artifacts and extra files, so the gate verdicts ship only because - the manifest binds them. Preflight must list each one as a release-dir - upload, never as a root artifact.""" - prepared = release_module.prepare_release(release_dir, artifact_root=artifact_root) - - assert set(GATE_EVIDENCE_FILES.values()) <= set(prepared.filenames) - assert not set(GATE_EVIDENCE_FILES.values()) & set(prepared.root_artifacts) - - -def test_publication_repeats_the_contract_warnings_and_proceeds( - release_dir: Path, artifact_root: Path, monkeypatch -) -> None: - """A contract warning is repeated, not refused.""" - monkeypatch.setattr( - release_module, - "validate_release_dir", - lambda _path, **_kwargs: ["synthetic.json carries a synthetic finding"], - ) - - with pytest.warns(UserWarning, match="release contract: synthetic.json carries"): - prepared = release_module.prepare_release( - release_dir, artifact_root=artifact_root - ) - - assert prepared.release_id == release_dir.name - assert prepared.contract_warnings == ("synthetic.json carries a synthetic finding",) - - #: Synthetic contract warnings, worded as the dense line's disclosure walk #: worded them until María's ruling of 2026-10-26 dropped it: a file and the #: paths in it, never a value (microcosm#1301). @@ -1994,320 +562,111 @@ def test_publication_repeats_the_contract_warnings_and_proceeds( ] -class _TagMessageHub(FakeHub): - """The fake Hub, keeping each tag's message as the Hub's annotated tags do.""" +def test_line_pointer_path_refuses_the_evidence_line() -> None: + with pytest.raises(ValueError, match="collides with the evidence-tier pointer"): + line_pointer_path("evidence") - def __init__(self) -> None: - super().__init__() - self.tag_messages: dict[str, str | None] = {} - def create_tag(self, *, tag_message=None, **kwargs) -> None: - super().create_tag(**kwargs) - self.tag_messages[kwargs["tag"]] = tag_message +def _microcosm_named_artifacts(artifact_root: Path) -> Path: + """The artifact root with the dataset and weights under the names new US + builds declare.""" + for name in ("populace_us_2024.h5", "populace_us_2024_calibration.npz"): + (artifact_root / name).rename( + artifact_root / name.replace("populace_", "microcosm_") + ) + return artifact_root -def test_preflight_verdict_lists_the_contract_warnings( - release_dir: Path, artifact_root: Path, monkeypatch, capsys +def test_prepare_build_folder_release_lists_a_us_national_build( + release_dir: Path, artifact_root: Path, monkeypatch ) -> None: - """--preflight-only puts the contract's warnings in its JSON verdict, not - only on stderr, and still passes: the walk warns, never refuses (review - of microcosm#1307).""" + national = _as_us_national_build_folder_release(release_dir) + root = _microcosm_named_artifacts(artifact_root) monkeypatch.setattr( - release_module, - "validate_release_dir", - lambda _path, **_kwargs: _CONTRACT_WARNINGS, + release_module, "validate_release_dir", lambda _path, **_kwargs: [] ) - monkeypatch.setattr(release_module, "_hf_api", lambda: pytest.fail("Hub client")) - - with pytest.warns(UserWarning, match="release contract: synthetic.json carries"): - status = publish_cli.main( - [ - str(release_dir), - "--artifact-root", - str(artifact_root), - "--preflight-only", - ] - ) - assert status == 0 - assert json.loads(capsys.readouterr().out) == { - "valid": True, - "published": False, - "contract_warnings": _CONTRACT_WARNINGS, - } + prepared = release_module.prepare_build_folder_release(national, artifact_root=root) + assert prepared.repository == "policyengine/populace-us" + assert (prepared.release, prepared.build) == (US_NATIONAL_RELEASE_ID, RELEASE_ID) + assert prepared.release_role == "national" + roles = {item.name: item.role for item in prepared.files} + assert roles["microcosm_us_2024.h5"] == "dataset" + assert roles["microcosm_us_2024_calibration.npz"] == "calibration_weights" -def test_publication_reports_the_contract_warnings_and_counts_them_on_the_tag( - release_dir: Path, artifact_root: Path, tmp_path: Path, monkeypatch, capsys -) -> None: - """A publication past the contract's warnings lists them in its printed - verdict, and its tag records how many there were but none of them; no - uploaded file carries them (review of microcosm#1307).""" - monkeypatch.setattr( - release_module, - "validate_release_dir", - lambda _path, **_kwargs: _CONTRACT_WARNINGS, - ) - hub = _TagMessageHub() - hub._download_dir = tmp_path / "hub-cache" - monkeypatch.setattr(release_module, "_hf_api", lambda: hub) - - with pytest.warns(UserWarning, match="release contract: other.json cannot"): - status = publish_cli.main( - [ - str(release_dir), - "--artifact-root", - str(artifact_root), - "--no-latest", - "--tag-only", - ] - ) - assert status == 0 - verdict = json.loads(capsys.readouterr().out) - assert verdict["release_id"] == RELEASE_ID - assert verdict["contract_warnings"] == _CONTRACT_WARNINGS - message = hub.tag_messages[RELEASE_ID] - assert message is not None - assert "published past 2 release contract warning(s)" in message - for warning in _CONTRACT_WARNINGS: - assert warning.split(" ")[0] not in message - assert "areas[0]" not in message - assert not any(b"contract_warnings" in content for _, content in hub.uploads) - assert not any(b"areas[0].rows" in content for _, content in hub.uploads) - - -def test_publication_without_warnings_leaves_the_tag_and_verdict_unchanged( - hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch +def test_prepare_build_folder_release_lists_the_bound_gate_evidence( + release_dir: Path, artifact_root: Path, monkeypatch ) -> None: + """Route A remediation PR-3: a build publishes the files its release + manifest declares, so the gate verdicts ship because the manifest binds + them, each from the build's own directory.""" + national = _as_us_national_build_folder_release(release_dir) + root = _microcosm_named_artifacts(artifact_root) monkeypatch.setattr( release_module, "validate_release_dir", lambda _path, **_kwargs: [] ) - tagged = _TagMessageHub() - tagged._download_dir = hub._download_dir - - pointer = publish_release( - release_dir, - "policyengine/populace-us", - api=tagged, - artifact_root=artifact_root, - update_latest=False, - tag_only=True, - ) - - assert "contract_warnings" not in pointer - assert tagged.tag_messages == {RELEASE_ID: None} - - -@pytest.mark.parametrize("evidence", [False, True]) -@pytest.mark.parametrize("release_type", [None, "calibration"]) -@pytest.mark.parametrize("argument", ["parent_h5", "compatibility_wheels", "both"]) -def test_non_enrichment_publisher_refuses_enrichment_only_arguments( - hub, release_dir, artifact_root, monkeypatch, release_type, argument, evidence -): - manifest_path = release_dir / "release_manifest.json" - manifest = json.loads(manifest_path.read_text()) - if release_type is not None: - manifest["release_type"] = release_type - manifest_path.write_text(json.dumps(manifest)) - kwargs = {"artifact_root": artifact_root, "evidence": evidence} - cli_args = [str(release_dir), "--artifact-root", str(artifact_root)] - if evidence: - cli_args.append("--evidence") - if argument in ("parent_h5", "both"): - kwargs["parent_h5"] = artifact_root / "populace_us_2024.h5" - cli_args.extend(["--parent-h5", str(kwargs["parent_h5"])]) - if argument in ("compatibility_wheels", "both"): - kwargs["compatibility_wheels"] = (artifact_root / "unrelated.whl",) - cli_args.extend( - ["--compatibility-wheel", str(kwargs["compatibility_wheels"][0])] - ) - def no_hub(*args, **kwargs): - pytest.fail("non-enrichment arguments must fail before Hub activity") - - monkeypatch.setattr(release_module, "_hf_api", no_hub) - monkeypatch.setattr(hub, "repo_info", no_hub) - monkeypatch.setattr(hub, "hf_hub_download", no_hub) - message = "require a source_enrichment release" - with pytest.raises(ValueError, match=message): - release_module.prepare_release(release_dir, **kwargs) - with pytest.raises(ValueError, match=message): - publish_release(release_dir, "policyengine/populace-us", api=hub, **kwargs) - with pytest.raises(ValueError, match=message): - publish_cli.main(cli_args) - with pytest.raises(ValueError, match=message): - publish_cli.main([*cli_args, "--preflight-only"]) - assert hub.events == [] - assert hub.uploads == [] - - -def test_publish_then_promote_reuses_the_immutable_tag( - hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch -) -> None: - """Publishing without the pointer, then with it: the second call - recognises the existing tag that describes this release, writes no second - immutable revision and only the main commit carrying the pointer.""" - monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) - - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - update_latest=False, - ) - assert LATEST_POINTER_PATH not in hub._commits[hub._refs["main"]] - events_after_inspect = len(hub.events) - - promoted = publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - updated_at="2026-09-23T12:00:00+00:00", - ) + prepared = release_module.prepare_build_folder_release(national, artifact_root=root) - kinds = [event for event, _ in hub.events[events_after_inspect:]] - assert kinds == ["create_commit"], kinds - assert hub.tags == [{"tag": RELEASE_ID, "revision": "commit-1"}] - assert promoted["release_id"] == RELEASE_ID - assert latest_release("policyengine/populace-us", api=hub).release_id == ( - RELEASE_ID - ) + files = {item.name: item for item in prepared.files} + for name in GATE_EVIDENCE_FILES.values(): + assert files[name].path == national / name -def test_retry_after_a_failed_pointer_commit_reuses_the_tag( - hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch +def test_prepare_build_folder_release_repeats_the_contract_warnings_and_proceeds( + release_dir: Path, artifact_root: Path, monkeypatch ) -> None: - """A failure between tag creation and the pointer commit leaves the tag; - the retry stands on it instead of dying on create_tag.""" - monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) - hub.fail_main_commit = True - with pytest.raises(RuntimeError, match="injected main commit failure"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - ) - assert hub.tags == [{"tag": RELEASE_ID, "revision": "commit-1"}] - assert LATEST_POINTER_PATH not in hub._commits[hub._refs["main"]] - - hub.fail_main_commit = False - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, + """A release contract warning is repeated as a warning and listed with the + build, never refused (microcosm#1301).""" + national = _as_us_national_build_folder_release(release_dir) + root = _microcosm_named_artifacts(artifact_root) + monkeypatch.setattr( + release_module, + "validate_release_dir", + lambda _path, **_kwargs: list(_CONTRACT_WARNINGS), ) - assert hub.tags == [{"tag": RELEASE_ID, "revision": "commit-1"}] - assert LATEST_POINTER_PATH in hub._commits[hub._refs["main"]] - - -def test_publication_refuses_a_tag_that_describes_another_release( - hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch -) -> None: - monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) - # A tag already pointing at a revision with no manifest for this release. - hub._refs[RELEASE_ID] = hub._refs["main"] - with pytest.raises(ValueError, match="does not describe this release"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - ) - # A tag whose manifest is another release's. - hub._commits["other"] = {f"releases/{RELEASE_ID}/release_manifest.json": b"{}"} - hub._refs[RELEASE_ID] = "other" - with pytest.raises(ValueError, match="describes another release"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - ) - assert LATEST_POINTER_PATH not in hub._commits[hub._refs["main"]] - - -def test_line_pointer_path_refuses_the_evidence_line() -> None: - with pytest.raises(ValueError, match="collides with the evidence-tier pointer"): - line_pointer_path("evidence") - - -def test_transient_errors_while_checking_an_existing_tag_propagate( - hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch -) -> None: - """Only "absent" answers are swallowed: a transient failure looking up - the tag or its manifest propagates, so a good tag is never orphaned - and the create path is never re-entered with the tag in place.""" - monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) - original_repo_info = hub.repo_info - - def flaky_repo_info(*, repo_id, repo_type, revision=None): - if revision == RELEASE_ID: - raise RuntimeError("injected transient Hub failure") - return original_repo_info( - repo_id=repo_id, repo_type=repo_type, revision=revision - ) - - monkeypatch.setattr(hub, "repo_info", flaky_repo_info) - with pytest.raises(RuntimeError, match="injected transient Hub failure"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - ) - assert hub.tags == [] - assert not [event for event, _ in hub.events if event == "create_branch"] - - monkeypatch.setattr(hub, "repo_info", original_repo_info) - hub._refs[RELEASE_ID] = hub._refs["main"] - - def flaky_download(*, repo_id, filename, repo_type, revision=None): - raise RuntimeError("injected transient download failure") - - monkeypatch.setattr(hub, "hf_hub_download", flaky_download) - with pytest.raises(RuntimeError, match="injected transient download failure"): - publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, + with pytest.warns(UserWarning, match="release contract: synthetic.json carries"): + prepared = release_module.prepare_build_folder_release( + national, artifact_root=root ) - assert LATEST_POINTER_PATH not in hub._commits[hub._refs["main"]] - -def _microcosm_named_artifacts(artifact_root: Path) -> Path: - """The artifact root with the dataset and weights under the names new US - builds declare.""" - for name in ("populace_us_2024.h5", "populace_us_2024_calibration.npz"): - (artifact_root / name).rename( - artifact_root / name.replace("populace_", "microcosm_") - ) - return artifact_root + assert prepared.contract_warnings == tuple(_CONTRACT_WARNINGS) -def test_prepare_build_folder_release_lists_a_us_national_build( +def test_prepare_build_folder_release_publishes_a_build_whose_diagnostics_failed( release_dir: Path, artifact_root: Path, monkeypatch ) -> None: + """A build whose calibration diagnostics generation failed still publishes + its dataset, with a warning, and lists no diagnostics file.""" national = _as_us_national_build_folder_release(release_dir) root = _microcosm_named_artifacts(artifact_root) + (national / "calibration_diagnostics.json").unlink() + manifest_path = national / "release_manifest.json" + manifest = json.loads(manifest_path.read_text()) + manifest["artifacts"].pop("calibration_diagnostics") + manifest["calibration_diagnostics"] = { + "status": "failed", + "expected_schema_version": 8, + "error_code": "validation_error", + "message": "Target hierarchy is incomplete.", + } + manifest_path.write_text(json.dumps(manifest)) monkeypatch.setattr( release_module, "validate_release_dir", lambda _path, **_kwargs: [] ) - prepared = release_module.prepare_build_folder_release(national, artifact_root=root) + with pytest.warns(UserWarning, match="generation failed"): + prepared = release_module.prepare_build_folder_release( + national, artifact_root=root + ) - assert prepared.repository == "policyengine/populace-us" - assert (prepared.release, prepared.build) == (US_NATIONAL_RELEASE_ID, RELEASE_ID) - assert prepared.release_role == "national" - roles = {item.name: item.role for item in prepared.files} - assert roles["microcosm_us_2024.h5"] == "dataset" - assert roles["microcosm_us_2024_calibration.npz"] == "calibration_weights" + names = {item.name for item in prepared.files} + assert prepared.calibration_diagnostics_available is False + assert "calibration_diagnostics.json" not in names + assert "microcosm_us_2024.h5" in names def test_prepare_build_folder_release_lists_an_annual_build( @@ -2340,7 +699,7 @@ def test_prepare_build_folder_release_lists_an_annual_build( } <= set(files) -def test_the_tagged_publisher_s_advice_names_every_us_release() -> None: +def test_the_build_folder_refusal_advice_names_every_us_release() -> None: from microcosm.data.contract import US_RELEASES for release in US_RELEASES: @@ -2369,15 +728,6 @@ def test_prepare_build_folder_release_refuses_a_build_of_another_role( ) -def test_the_tagged_publisher_refuses_the_us_national_release( - release_dir: Path, artifact_root: Path -) -> None: - national = _as_us_national_build_folder_release(release_dir) - - with pytest.raises(ValueError, match="microcosm-publish-release-build"): - release_module.prepare_release(national, artifact_root=artifact_root) - - def test_prepare_build_folder_release_checks_an_evidence_build_with_its_contract( release_dir: Path, artifact_root: Path, monkeypatch ) -> None: diff --git a/packages/microcosm-data/tests/engine_free/shared/test_release_contract_keying.py b/packages/microcosm-data/tests/engine_free/shared/test_release_contract_keying.py index 7b7d974c49..11df411381 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_release_contract_keying.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_release_contract_keying.py @@ -141,8 +141,9 @@ def test_the_registry_names_no_uk_local_area_release(): def test_a_uk_local_area_release_publishes_only_once_the_registry_names_it(drawn): """For any positive ``k``, ``microcosm-uk-2024-25-local-k`` publishes into build folders exactly when a registry entry names it as its release, - the tagged publisher refuses it either way, and its pointer line is the - same whatever the registry holds (microcosm#1586).""" + the refusal of any other directory names the registry when no entry names + it, and its pointer line is the same whatever the registry holds + (microcosm#1586).""" registered, k = drawn release_id = _uk_local_release_id(k) @@ -157,16 +158,12 @@ def test_a_uk_local_area_release_publishes_only_once_the_registry_names_it(drawn assert contract.unregistered_uk_local_release(release_id) is ( k not in registered ) - with pytest.raises(ValueError) as refusal: - release_module._refuse_build_folder_release(release_id) reason = release_module.not_a_build_folder_release_reason(release_id) assert line_for_release_id(release_id) == f"local-k{k}" assert line_for_release_id(release_id) == f"local-k{k}" if k in registered: - assert "publishes each build into its own folder" in str(refusal.value) assert release_module.TAGGED_RELEASE_ADVICE in reason else: - assert release_module.UNREGISTERED_UK_LOCAL_RELEASE_ADVICE in str(refusal.value) assert release_module.UNREGISTERED_UK_LOCAL_RELEASE_ADVICE in reason # Outside the patch the shipped registry names no local-area release. assert not publishes_to_build_folder(release_id) diff --git a/packages/microcosm-data/tests/engine_free/shared/test_slack.py b/packages/microcosm-data/tests/engine_free/shared/test_slack.py deleted file mode 100644 index 121f44a3c6..0000000000 --- a/packages/microcosm-data/tests/engine_free/shared/test_slack.py +++ /dev/null @@ -1,71 +0,0 @@ -from microcosm.data.slack import country_for_repo, notify_release - - -def test_country_inferred_from_repo_id() -> None: - assert country_for_repo("policyengine/populace-us") == "us" - assert country_for_repo("policyengine/populace-uk-private") == "uk" - - -def test_notify_is_noop_without_webhook(monkeypatch) -> None: - monkeypatch.delenv("SLACK_WEBHOOK_POPULACE_US", raising=False) - sent: list = [] - result = notify_release( - "policyengine/populace-us", - "populace-us-2024-abc-20260620T000000Z", - post=lambda url, payload: sent.append((url, payload)), - ) - assert result is False - assert sent == [] - - -def test_notify_posts_to_country_webhook(monkeypatch) -> None: - monkeypatch.setenv("SLACK_WEBHOOK_POPULACE_UK", "https://hooks.slack.test/uk") - sent: list = [] - result = notify_release( - "policyengine/populace-uk-private", - "populace-uk-2023-def-20260620T000000Z", - "2026-06-20T00:00:00+00:00", - post=lambda url, payload: sent.append((url, payload)), - ) - assert result is True - assert len(sent) == 1 - url, payload = sent[0] - assert url == "https://hooks.slack.test/uk" - assert "populace-uk-2023-def" in payload["text"] - assert "UK" in payload["blocks"][0]["text"]["text"] - - -def test_notify_warns_when_unset_and_requested(monkeypatch, capsys) -> None: - monkeypatch.delenv("SLACK_WEBHOOK_POPULACE_US", raising=False) - result = notify_release( - "policyengine/populace-us", - "populace-us-2024-abc-20260620T000000Z", - warn_if_unset=True, - ) - assert result is False - captured = capsys.readouterr() - assert "SLACK_WEBHOOK_POPULACE_US is not set" in captured.out + captured.err - - -def test_notify_silent_when_unset_and_not_requested(monkeypatch, capsys) -> None: - monkeypatch.delenv("SLACK_WEBHOOK_POPULACE_US", raising=False) - result = notify_release( - "policyengine/populace-us", - "populace-us-2024-abc-20260620T000000Z", - ) - assert result is False - captured = capsys.readouterr() - assert "SLACK_WEBHOOK" not in captured.out + captured.err - - -def test_notify_never_raises_on_post_failure() -> None: - def boom(url, payload): - raise RuntimeError("slack down") - - result = notify_release( - "policyengine/populace-us", - "populace-us-2024-abc-20260620T000000Z", - webhook="https://hooks.slack.test/us", - post=boom, - ) - assert result is False diff --git a/packages/microcosm-data/tests/engine_free/shared/test_source_enrichment.py b/packages/microcosm-data/tests/engine_free/shared/test_source_enrichment.py index 6a192225e4..4969142faf 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_source_enrichment.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_source_enrichment.py @@ -20,8 +20,6 @@ validate_release_dir, ) from microcosm.data.h5_enrichment import append_native_spm_role, compare_h5_enrichment -from microcosm.data.publish_cli import main as publish_main -from microcosm.data.release import publish_release from test_support.paths import paths_for _TEST_PATHS = paths_for("microcosm-data") @@ -268,40 +266,6 @@ def test_pending_candidate_is_valid_but_actual_release_gate_refuses(candidate): validate_release_dir(release, parent_h5=parent, artifact_root=root) -def test_publisher_refuses_before_constructing_hub_client(candidate, monkeypatch): - import microcosm.data.release as release_module - - def no_hub(): - pytest.fail("publisher contacted Hub for a pending enrichment") - - monkeypatch.setattr(release_module, "_hf_api", no_hub) - release, parent, root = candidate - with pytest.raises(ReleaseContractError, match="compatibility is pending"): - publish_release( - release, "policyengine/populace-us", parent_h5=parent, artifact_root=root - ) - - -def test_preflight_runs_actual_gate_and_never_publishes(candidate, monkeypatch): - import microcosm.data.publish_cli as cli - - monkeypatch.setattr( - cli, "publish_release", lambda *a, **kw: pytest.fail("preflight published") - ) - release, parent, root = candidate - with pytest.raises(ReleaseContractError, match="compatibility is pending"): - publish_main( - [ - str(release), - "--parent-h5", - str(parent), - "--artifact-root", - str(root), - "--preflight-only", - ] - ) - - def test_requires_actual_parent_and_h5(candidate): release, _, root = candidate with pytest.raises(ReleaseContractError, match="requires parent_h5"): @@ -453,30 +417,20 @@ def actual_test(*args, **kwargs): def test_annual_cut_preserves_source_enrichment_qualification( candidate, tmp_path, monkeypatch ): - from microcosm.data.release import prepare_release from test_support.microcosm_data.annual_projections import add_annual_extension output, calls = _qualify_candidate(candidate, tmp_path, monkeypatch) _, parent, root = candidate - tag = add_annual_extension(output, root) + add_annual_extension(output, root) previous_calls = len(calls) - prepared = prepare_release( + validate_release_dir( output, - artifact_root=root, parent_h5=parent, + artifact_root=root, compatibility_wheels=(tmp_path / "country.whl",), - tag_name=tag, - update_latest=False, ) assert len(calls) == previous_calls + 1 assert calls[-1]["require_wheels"] is True - assert { - "annual_manifest.json", - "annual_acceptance.json", - "projection_2025.json", - enrichment.COMPATIBILITY_FILE, - }.issubset(prepared.filenames) - assert set(prepared.root_artifacts) == {"populace_us_2024.h5", "annual_2025.h5"} @pytest.mark.parametrize( @@ -522,16 +476,9 @@ def test_annual_source_enrichment_retains_original_constraints( ) -def test_certification_writes_new_bundle_and_preflight_replays( +def test_certification_writes_new_bundle_and_the_contract_replays( candidate, tmp_path, monkeypatch ): - import microcosm.data.release as release_module - - monkeypatch.setattr( - release_module, - "_hf_api", - lambda: pytest.fail("successful preflight constructed a Hub client"), - ) release, parent, root = candidate original_report = (release / enrichment.SOURCE_ENRICHMENT_FILE).read_bytes() output, calls = _qualify_candidate(candidate, tmp_path, monkeypatch) @@ -539,22 +486,13 @@ def test_certification_writes_new_bundle_and_preflight_replays( assert (output / enrichment.SOURCE_EVIDENCE_FILE).read_bytes() == ( release / enrichment.SOURCE_EVIDENCE_FILE ).read_bytes() - assert ( - publish_main( - [ - str(output), - "--parent-h5", - str(parent), - "--artifact-root", - str(root), - "--compatibility-wheel", - str(tmp_path / "country.whl"), - "--preflight-only", - ] - ) - == 0 + validate_release_dir( + output, + parent_h5=parent, + artifact_root=root, + compatibility_wheels=(tmp_path / "country.whl",), ) - assert len(calls) == 3 # Test, staged revalidation, then real publisher preflight. + assert len(calls) == 3 # Test, staged revalidation, then the contract's replay. assert all(call["require_wheels"] for call in calls) @@ -608,46 +546,6 @@ def test_certified_enrichment_lists_its_complete_build_folder_with_the_h5_once( assert files["build_manifest.json"].role == "build_manifest" -def test_certified_enrichment_preflight_and_publish_refuse_a_build_folder_identically( - build_folder_candidate, tmp_path, monkeypatch -): - import microcosm.data.release as release_module - - _, parent, root = build_folder_candidate - release, _ = _qualify_candidate(build_folder_candidate, tmp_path, monkeypatch) - monkeypatch.setattr( - release_module, - "_hf_api", - lambda: pytest.fail("a build-folder release constructed a Hub client"), - ) - wheels = (tmp_path / "country.whl",) - with pytest.raises( - ValueError, match="microcosm-publish-release-build" - ) as published: - publish_release( - release, - "policyengine/populace-us", - parent_h5=parent, - artifact_root=root, - compatibility_wheels=wheels, - notify=False, - ) - with pytest.raises(type(published.value)) as preflight: - publish_main( - [ - str(release), - "--parent-h5", - str(parent), - "--artifact-root", - str(root), - "--compatibility-wheel", - str(wheels[0]), - "--preflight-only", - ] - ) - assert str(preflight.value) == str(published.value) - - def test_a_build_folder_candidate_names_its_parent_as_a_build_in_a_folder( build_folder_candidate, ): @@ -857,14 +755,9 @@ def test_certification_records_a_build_folders_built_with_packages_at_its_top_le @pytest.mark.parametrize("duplicate", ["identical", "different", "symlink"]) -@pytest.mark.parametrize( - "entrypoint", ["candidate", "preflight", "publisher", "publisher_existing_client"] -) -def test_release_local_h5_duplicate_is_rejected_before_hub_activity( - candidate, tmp_path, monkeypatch, duplicate, entrypoint +def test_release_local_h5_duplicate_is_rejected( + candidate, tmp_path, monkeypatch, duplicate ): - import microcosm.data.release as release_module - _, parent, root = candidate release, _ = _qualify_candidate(candidate, tmp_path, monkeypatch) # The unduplicated fixture passes the full gate: pending compatibility or @@ -881,46 +774,13 @@ def test_release_local_h5_duplicate_is_rejected_before_hub_activity( row = handle["person/table"][0] row["person_weight"] += 1 handle["person/table"][0] = row - monkeypatch.setattr( - release_module, - "_hf_api", - lambda: pytest.fail("duplicate reached Hub client construction"), - ) - - class NoHubActivity: - def __getattr__(self, name): - pytest.fail(f"duplicate accessed supplied Hub client: {name}") - monkeypatch.setattr( enrichment, "run_native_loader_compatibility", lambda *a, **kw: pytest.fail("duplicate reached compatibility probing"), ) with pytest.raises(ReleaseContractError, match="release-local H5"): - if entrypoint == "candidate": - _validate((release, parent, root)) - elif entrypoint == "preflight": - publish_main( - [ - str(release), - "--parent-h5", - str(parent), - "--artifact-root", - str(root), - "--preflight-only", - ] - ) - else: - publish_release( - release, - "policyengine/populace-us", - parent_h5=parent, - artifact_root=root, - notify=False, - api=NoHubActivity() - if entrypoint == "publisher_existing_client" - else None, - ) + _validate((release, parent, root)) @pytest.mark.parametrize("year", [2023, 2024, 2025]) @@ -1202,16 +1062,9 @@ def test_default_certification_pins_the_tested_version_and_declares_nothing( assert "publisher_claims" not in report["compatibility"] -def test_declared_model_range_is_emitted_verbatim_and_replayed_by_preflight( +def test_declared_model_range_is_emitted_verbatim_and_replayed_by_the_contract( candidate, tmp_path, monkeypatch ): - import microcosm.data.release as release_module - - monkeypatch.setattr( - release_module, - "_hf_api", - lambda: pytest.fail("successful preflight constructed a Hub client"), - ) release, parent, root = candidate output, _ = _qualify_candidate(candidate, tmp_path, monkeypatch, **_declare()) manifest, report = _certified(output) @@ -1225,20 +1078,11 @@ def test_declared_model_range_is_emitted_verbatim_and_replayed_by_preflight( assert manifest["compatible_core_packages"] == [ {"name": "policyengine-core", "specifier": "==3.99.0"} ] - assert ( - publish_main( - [ - str(output), - "--parent-h5", - str(parent), - "--artifact-root", - str(root), - "--compatibility-wheel", - str(tmp_path / "country.whl"), - "--preflight-only", - ] - ) - == 0 + validate_release_dir( + output, + parent_h5=parent, + artifact_root=root, + compatibility_wheels=(tmp_path / "country.whl",), ) @@ -2080,90 +1924,6 @@ def _validate(bundle): } -def test_publish_preflight_surfaces_a_recorded_narrowing( - candidate, tmp_path, monkeypatch, capsys -): - """The publisher's own preflight is where the later operator actually is.""" - import microcosm.data.release as release_module - - monkeypatch.setattr( - release_module, - "_hf_api", - lambda: pytest.fail("successful preflight constructed a Hub client"), - ) - _, parent, root = candidate - narrowed, declared = _narrowed_bundle(candidate, tmp_path, monkeypatch) - - def _preflight(bundle): - assert ( - publish_main( - [ - str(bundle), - "--parent-h5", - str(parent), - "--artifact-root", - str(root), - "--compatibility-wheel", - str(tmp_path / "country.whl"), - "--preflight-only", - ] - ) - == 0 - ) - return json.loads(capsys.readouterr().out) - - assert _preflight(narrowed) == { - "valid": True, - "published": False, - "narrowed_claims": NARROWED_RECORD, - } - assert _preflight(declared) == { - "valid": True, - "published": False, - "claim_measurement": MEASURED_RECORD, - } - - -def test_publication_says_on_stderr_what_the_preflight_says_in_json( - candidate, tmp_path, monkeypatch, capsys -): - """Publication is reachable without ever running the preflight. - - `tools/publish_release.sh` passes its arguments straight through, so the - runbook's "remove --preflight-only" step is a habit rather than a gate. The - JSON verdict belongs to whatever parses stdout; the operator reading the - terminal gets the same record on stderr, on both paths. - """ - from microcosm.data import publish_cli - - _, parent, root = candidate - narrowed, declared = _narrowed_bundle(candidate, tmp_path, monkeypatch) - monkeypatch.setattr( - publish_cli, "publish_release", lambda *args, **kwargs: {"published": True} - ) - tail = [ - "--parent-h5", - str(parent), - "--artifact-root", - str(root), - "--compatibility-wheel", - str(tmp_path / "country.whl"), - ] - assert publish_main([str(narrowed), *tail]) == 0 - published = capsys.readouterr() - assert json.loads(published.out) == {"published": True} - assert "compatibility narrowing" in published.err - assert ">=1.999.0,<2" in published.err - - assert publish_main([str(declared), *tail]) == 0 - declared_err = capsys.readouterr().err - assert "narrowing" not in declared_err - # The declared range is announced with the one version it was measured - # against (microcosm#1034). - assert "measured against only the versions recorded here" in declared_err - assert json.dumps(MEASURED_RECORD, sort_keys=True) in declared_err - - @pytest.mark.parametrize( "claim", [ diff --git a/packages/microcosm-data/tests/engine_free/shared/test_tagged_publisher_removed.py b/packages/microcosm-data/tests/engine_free/shared/test_tagged_publisher_removed.py new file mode 100644 index 0000000000..6329eb1416 --- /dev/null +++ b/packages/microcosm-data/tests/engine_free/shared/test_tagged_publisher_removed.py @@ -0,0 +1,109 @@ +"""No tagged publisher is left: releases publish only into build folders. + +``microcosm-publish-release`` (``microcosm.data.publish_cli``) committed a +release's files to Hugging Face directly, tagged them and wrote a +``latest*.json`` pointer file. Once the US, UK and BE release repositories all +recorded their builds in ``releases.json``, it refused every one of them, and +``microcosm-publish-release-build`` publishes each build through the emitter +instead. These tests check that the tagged publisher is gone and that the +checks both commands shared stay with the build-folder publication. +""" + +from __future__ import annotations + +import importlib.util +import json +import re +import tomllib + +import microcosm.data +from microcosm.data import release as release_module +from microcosm.data import source_enrichment +from test_support.paths import REPOSITORY_ROOT + +#: The tagged publisher's public names, none of which is left. +TAGGED_PUBLISHER_NAMES = ("publish_release", "prepare_release", "PreparedRelease") + +#: How code ran the tagged publisher: its module, by any import, its command +#: (but not ``microcosm-publish-release-build``), its shell wrapper, the +#: functions only it had, or its Slack alert. (The emitter interface's own +#: ``publish_release`` call stays, so that name is not searched for.) +TAGGED_PUBLISHER_REFERENCE = re.compile( + r"\bpublish_cli\b|microcosm-publish-release(?!-build)|publish_release\.sh" + r"|\bprepare_release\b|\bPreparedRelease\b|\bnotify_release\b" + r"|microcosm\.data\.slack" +) +#: The files searched: code, shell scripts, configuration, workflows and the +#: tools' own READMEs. The packages' JSON data is left out for its size. +SEARCHED_SUFFIXES = {".py", ".sh", ".example", ".toml", ".md", ".yml", ".yaml"} + + +def test_no_package_installs_the_tagged_publish_command() -> None: + scripts = { + name: target + for pyproject in sorted((REPOSITORY_ROOT / "packages").glob("*/pyproject.toml")) + for name, target in tomllib.loads(pyproject.read_text())["project"] + .get("scripts", {}) + .items() + } + + assert "microcosm-publish-release" not in scripts + assert not [ + name + for name, target in scripts.items() + if target.startswith("microcosm.data.publish_cli") + ] + + +def test_the_tagged_publisher_and_its_slack_alert_are_gone() -> None: + assert importlib.util.find_spec("microcosm.data.publish_cli") is None + assert importlib.util.find_spec("microcosm.data.slack") is None + + +def test_no_module_exports_the_tagged_publisher() -> None: + for name in TAGGED_PUBLISHER_NAMES: + assert not hasattr(microcosm.data, name), name + assert name not in microcosm.data.__all__, name + assert not hasattr(release_module, name), name + assert name not in release_module.__all__, name + + +def test_the_tagged_publishers_receipt_enrichment_check_is_gone() -> None: + """``is_receipt_enrichment`` served only the tagged publisher's refusal to + move ``latest.json`` to a reported-receipt enrichment; a build folder's + release (``microcosm-us-2024-receipt-donor``) does that work now.""" + assert not hasattr(source_enrichment, "is_receipt_enrichment") + + +def test_the_shared_publication_checks_live_beside_build_folder_preparation( + tmp_path, +) -> None: + publication_refusal = getattr(release_module, "publication_refusal", None) + assert callable(publication_refusal) + assert "publication_refusal" in release_module.__all__ + (tmp_path / "build_manifest.json").write_text(json.dumps({"non_release": True})) + + refusal = publication_refusal(tmp_path, allow_missing_staging=True) + + assert refusal is not None + assert "non-release smoke output" in refusal + + +def test_no_tool_or_package_runs_the_tagged_publisher() -> None: + assert not (REPOSITORY_ROOT / "tools/publish_release.sh").exists() + searched = [ + *sorted((REPOSITORY_ROOT / "tools").rglob("*")), + *sorted((REPOSITORY_ROOT / "packages").glob("*/src/**/*")), + *sorted((REPOSITORY_ROOT / ".github/workflows").glob("*")), + ] + references = [ + f"{source.relative_to(REPOSITORY_ROOT)}:{number}" + for source in searched + if source.is_file() and source.suffix in SEARCHED_SUFFIXES + for number, text in enumerate( + source.read_text(errors="replace").splitlines(), start=1 + ) + if TAGGED_PUBLISHER_REFERENCE.search(text) + ] + + assert references == [] diff --git a/pyproject.toml b/pyproject.toml index cd8b8e13b5..356de3a924 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -52,8 +52,12 @@ ignore = ["E501"] # refusal of BE-era latest*.json pointer files, which 5b removes), a UK # national build's reference build and releases.json (run_uk_cut.py also # fetches its build inputs), the policyengine.py certification, the US -# recertification and the quick-start notebook. +# recertification and the quick-start notebook. release.py's Hub error checks +# (missing_on_hub, never_cached_offline), which the loader's releases.json +# read uses, also import it, as do its readers of latest*.json pointer files, +# which substage 5b removes. "packages/microcosm-data/src/microcosm/data/loader.py" = ["TID251"] +"packages/microcosm-data/src/microcosm/data/release.py" = ["TID251"] "packages/microcosm-build/src/microcosm/build/release_publication.py" = ["TID251"] "packages/microcosm-build/src/microcosm/build/uk_runtime/cut_reference.py" = ["TID251"] "tools/run_uk_cut.py" = ["TID251"] @@ -73,10 +77,8 @@ ignore = ["E501"] "tools/provision_uk_staging_repository.py" = ["TID251"] "tools/fetch_uk_staged_dataset.py" = ["TID251"] "packages/microcosm-build/src/microcosm/build/staging_storage.py" = ["TID251"] -# TID251. BE's publication tools, which substage 5b removes: the build-folder -# switch and the tagged publisher (microcosm-publish-release). +# TID251. The build-folder switch, which substage 5b removes. "packages/microcosm-build/src/microcosm/build/build_folder_switch.py" = ["TID251"] -"packages/microcosm-data/src/microcosm/data/release.py" = ["TID251"] # TID251. Tests and their stand-ins for the Hub (the root conftest.py only). "packages/*/tests/**" = ["TID251"] "test_support/**" = ["TID251"] diff --git a/test_support/microcosm_data/release.py b/test_support/microcosm_data/release.py index 5d0f90e30f..f7ad0fd421 100644 --- a/test_support/microcosm_data/release.py +++ b/test_support/microcosm_data/release.py @@ -1,9 +1,7 @@ -"""Publishing behavior: contract-gated uploads and a last-written pointer. +"""Release fixtures: release directories, build folders and a fake Hub. -The fake Hub client records every upload in order, so the suite asserts the -real guarantees — an invalid release uploads nothing, and ``latest.json`` -lands strictly after the files it points at — rather than implementation -details. +The fake Hub client records every request, so the tests check what the +pointer readers and build-folder publication read and refuse. """ # ruff: noqa: F401 @@ -16,7 +14,7 @@ import pytest -from microcosm.data import ReleaseContractError, publish_cli +from microcosm.data import ReleaseContractError from microcosm.data import release as release_module from microcosm.data.contract import ( EVIDENCE_RELEASE_MANIFEST_SCHEMA_VERSION, @@ -39,7 +37,6 @@ latest_release, line_pointer_path, line_pointer_payload, - publish_release, ) from microcosm.data.stored_inputs import register_sha256 from test_support.microcosm_data.build_folders import ( @@ -50,17 +47,7 @@ ) from test_support.microcosm_data.hub_errors import missing_on_hub - -@pytest.fixture(autouse=True) -def _no_slack_webhook(monkeypatch): - """Keep publish_release's release alert hermetic: never post to a real - webhook if the dev/CI environment happens to have one set.""" - monkeypatch.delenv("SLACK_WEBHOOK_POPULACE_US", raising=False) - monkeypatch.delenv("SLACK_WEBHOOK_POPULACE_UK", raising=False) - - RELEASE_ID = "populace-us-2024-9f1260b-20260611" -JUNE_UK_RELEASE_ID = "populace-uk-2023-dd68c73-4aa4b14-20260619T023711Z" UK_NATIONAL_RELEASE_ID = "microcosm-uk-2024-25-national" UK_NATIONAL_CUT_TAG = f"{UK_NATIONAL_RELEASE_ID}-20260920T120000Z-deadbeef" UK_LOCAL_RELEASE_ID = "microcosm-uk-2024-25-local-k55000" @@ -545,19 +532,6 @@ def hf_hub_download(self, *, repo_id, filename, repo_type, revision=None) -> str return str(local) -class NonAtomicHub: - """Expose only the legacy upload/tag surface of a backing fake Hub.""" - - def __init__(self, backing: FakeHub) -> None: - self.backing = backing - - def upload_file(self, **kwargs): - return self.backing.upload_file(**kwargs) - - def create_tag(self, **kwargs): - return self.backing.create_tag(**kwargs) - - @pytest.fixture def hub(tmp_path: Path) -> FakeHub: fake = FakeHub() @@ -973,25 +947,6 @@ def _as_us_national_build_folder_release(release_dir: Path) -> Path: return to_build_folder_layout(national, build=RELEASE_ID) -@pytest.fixture -def annual_release(release_dir, artifact_root): - from .annual_projections import _h5, add_annual_extension - - dataset = artifact_root / "populace_us_2024.h5" - _h5(dataset, 2024) - sha = _sha256(dataset) - path = release_dir / "build_manifest.json" - build = json.loads(path.read_text()) - build["dataset"]["sha256"] = sha - path.write_text(json.dumps(build)) - path = release_dir / "release_manifest.json" - manifest = json.loads(path.read_text()) - manifest["artifacts"]["populace_us_2024"]["sha256"] = sha - path.write_text(json.dumps(manifest)) - _bind_stored_input_evidence(release_dir) - return add_annual_extension(release_dir, artifact_root) - - # --------------------------------------------------------------------------- # Evidence-tier publishing (microcosm#506) # --------------------------------------------------------------------------- @@ -1055,27 +1010,4 @@ def evidence_release_dir(release_dir: Path) -> Path: return directory -def _declare_root_artifact(release_dir: Path, *, key: str, path: str) -> None: - manifest_path = release_dir / "release_manifest.json" - manifest = json.loads(manifest_path.read_text()) - manifest["artifacts"][key] = { - "kind": "diagnostics", - "path": path, - "repo_id": "policyengine/populace-us", - "revision": release_dir.name, - "sha256": "1" * 64, - } - manifest_path.write_text(json.dumps(manifest)) - - -def _uk_hub(tmp_path: Path) -> FakeHub: - hub = FakeHub("policyengine/populace-uk-private") - hub._download_dir = tmp_path / "uk-hub-cache" - june_pointer = latest_pointer_payload( - JUNE_UK_RELEASE_ID, updated_at="2026-06-19T02:38:00+00:00" - ) - hub.seed_main_file(LATEST_POINTER_PATH, json.dumps(june_pointer, indent=1).encode()) - return hub - - __all__ = [name for name in globals() if not name.startswith("__")] diff --git a/tools/publish_release.sh b/tools/publish_release.sh deleted file mode 100755 index ddfd9db619..0000000000 --- a/tools/publish_release.sh +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env bash -# -# Publish a Microcosm release that keeps tags and latest.json, and fire its -# Slack alert, in one tracked path. It refuses every release that publishes -# into build folders and any repository that records its builds in -# releases.json, which the UK and US repositories both do since their -# switches, so it publishes no UK or US release. -# -# The UK national and dense releases, each UK local-area release that the -# dataset registry names, and the US releases -# (microcosm-us-2024-national, -local, -receipt-donor, -evidence, -annual and -local-annual) publish -# each build into its own folder through the emitter with -# `microcosm-publish-release-build` instead, and the calibration diagnostics -# dashboard posts their Slack alerts from changes to releases.json. -# -# Thin wrapper around `microcosm-publish-release` so that every ship goes -# through the same command and the release alert is guaranteed to be wired. -# The alert itself lives in the publish CLI (microcosm.data.slack.notify_release) -# and is a no-op unless the channel webhook env var is set — this wrapper just -# loads those from an optional gitignored env file and warns if they're missing. -# -# Usage: -# tools/publish_release.sh [--repo-id …] [--artifact-root …] … -# All arguments are passed straight through to `microcosm-publish-release`. -# -# One-time setup on the build machine (see README "Releasing & alerts"): -# cp tools/release.env.example tools/release.env # then fill in the URLs -# or just export SLACK_WEBHOOK_POPULACE_US / _UK in your shell. - -set -euo pipefail - -ENV_FILE="${POPULACE_RELEASE_ENV:-$(dirname "$0")/release.env}" -if [[ -f "$ENV_FILE" ]]; then - set -a - # shellcheck disable=SC1090 - source "$ENV_FILE" - set +a -fi - -if [[ -z "${SLACK_WEBHOOK_POPULACE_US:-}" && -z "${SLACK_WEBHOOK_POPULACE_UK:-}" ]]; then - echo "warning: no SLACK_WEBHOOK_POPULACE_US/_UK set — this release will" >&2 - echo " publish WITHOUT a Slack alert. Set them in your shell or in" >&2 - echo " $ENV_FILE (see README 'Releasing & alerts')." >&2 -fi - -exec microcosm-publish-release "$@" diff --git a/tools/release.env.example b/tools/release.env.example index 50ef637ef0..6c55c29861 100644 --- a/tools/release.env.example +++ b/tools/release.env.example @@ -1,22 +1,13 @@ -# Release configuration for the build machine: the UK release key below, and -# the Slack webhooks that tools/publish_release.sh reads. +# Release configuration for the build machine: the UK release key below. # # Copy this file to tools/release.env (gitignored) on the build machine: # # cp tools/release.env.example tools/release.env # -# Slack webhooks. `tools/publish_release.sh` (and any direct -# `microcosm-publish-release`) posts a release alert to #populace-us or -# #populace-uk when it moves latest.json, if the matching incoming-webhook URL -# is set. Since the UK and US repositories switched to releases.json, that -# publisher refuses both repositories, so no UK or US publication reads either -# variable: leave both blank. Every UK and US release publishes each build into -# its own folder through the emitter (`microcosm-publish-release-build`), which -# sends no alert; the calibration diagnostics dashboard posts every UK and US -# release alert from changes to releases.json. - -export SLACK_WEBHOOK_POPULACE_US= -export SLACK_WEBHOOK_POPULACE_UK= +# No release command reads a Slack webhook: release builds publish only into +# their own folders, through the emitter (`microcosm-publish-release-build`), +# which sends no alert, and the calibration diagnostics dashboard posts release +# alerts from changes to releases.json. # Canonical UK exact-k terminal reports are authenticated with a stable # 32-byte release key encoded as base64. Generate and store this once on the