From 4dbe19f2de720d1d4745bde8ca9128ed6940394b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:19:57 +0400 Subject: [PATCH 1/9] Test that the build-folder switch tool is gone (#1792) Three failing tests for removing microcosm.build.build_folder_switch: the module cannot be found; no package source or test, shared test support, tool, doc or README names it; and the refusal for a repository with pointer files and no releases.json names no tool or step to run. Co-Authored-By: Claude Opus 5.5 --- .../test_build_folder_switch_removal.py | 64 +++++++++++++++++++ .../uk/test_uk_release_publication.py | 13 ++-- 2 files changed, 72 insertions(+), 5 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/shared/test_build_folder_switch_removal.py diff --git a/packages/microcosm-build/tests/engine_free/shared/test_build_folder_switch_removal.py b/packages/microcosm-build/tests/engine_free/shared/test_build_folder_switch_removal.py new file mode 100644 index 0000000000..e09cbbffb7 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_build_folder_switch_removal.py @@ -0,0 +1,64 @@ +"""The one-time build-folder switch tool is gone. + +The tool moved each dataset repository from tags and pointer files to build +folders and ``releases.json``, then deleted the old layout's files. The US, UK +and BE release repositories have all moved and had their old layout deleted, +so Microcosm no longer has it, and nothing tells an operator to run it. +``changelog.d/`` and the root journals are history and may still name it. +""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +from test_support.paths import paths_for + +#: The removed module's name, as an import, a ``python -m`` command or a path +#: would spell it. +REMOVED_MODULE_NAME = "build_folder_switch" +#: The kinds of file a source, test, tool or document is written in. +TEXT_SUFFIXES = frozenset( + {".py", ".md", ".sh", ".toml", ".json", ".yml", ".yaml", ".txt", ".ipynb"} +) + + +def _current_files(repository: Path) -> list[Path]: + """Every text file of the package sources and tests, the shared test + support, the tools, the docs and the READMEs.""" + roots = [ + *sorted((repository / "packages").glob("*/src")), + *sorted((repository / "packages").glob("*/tests")), + repository / "test_support", + repository / "tools", + repository / "docs", + ] + files = [ + candidate + for root in roots + for candidate in root.rglob("*") + if candidate.is_file() + and candidate.suffix in TEXT_SUFFIXES + and "__pycache__" not in candidate.parts + ] + files.append(repository / "README.md") + files.extend(sorted((repository / "packages").glob("*/README.md"))) + return files + + +def test_the_build_folder_switch_module_is_removed() -> None: + assert importlib.util.find_spec("microcosm.build.build_folder_switch") is None + + +def test_no_source_test_tool_or_document_names_the_switch_tool() -> None: + repository = paths_for("microcosm-build").repository + this_file = Path(__file__).resolve() + naming_files = sorted( + str(candidate.relative_to(repository)) + for candidate in _current_files(repository) + if candidate.resolve() != this_file + and REMOVED_MODULE_NAME + in candidate.read_text(encoding="utf-8", errors="replace") + ) + + assert naming_files == [] diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py index d4fd3219cc..6034e4c5f9 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py @@ -934,10 +934,10 @@ def test_the_command_refuses_a_repository_that_has_not_switched_without_advising hub_listing: HubListing, promote: bool, ) -> None: - """Before its switch a repository has no releases.json, the loader - follows its pointer files and the switch reads them to choose each - release's current build, so the refusal says the repository has not - switched and does not advise removing them.""" + """Before its switch a repository has no releases.json and the loader + follows its pointer files, so the refusal says the repository has not + switched and does not advise removing them. Microcosm no longer has the + one-time switch tool, so the refusal names no tool and no step to run.""" started, repository = _start_emitters(monkeypatch) hub_listing.files.extend(["README.md", "latest.json", "latest-national.json"]) argv = ( @@ -953,7 +953,10 @@ def test_the_command_refuses_a_repository_that_has_not_switched_without_advising assert output is None assert "has not switched to releases.json" in error assert "latest-national.json" in error - assert "microcosm.build.build_folder_switch" in error + assert "python -m" not in error + assert "microcosm.build." not in error + assert "--write" not in error + assert "keep the files in place" in error assert "remove" not in error assert repository == {} From c71f0093d47b12c165ca3aa95439b82caaa41064 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:23:33 +0400 Subject: [PATCH 2/9] Remove the build-folder switch tool (#1792) The US, UK and BE release repositories have all moved to build folders and releases.json and had their old layout deleted, so the one-time tool has nothing left to move. Remove microcosm.build.build_folder_switch (copy, switch and delete-old-layout), its three test modules and their in-memory Hub helper. The refusal for a repository with pointer files and no releases.json no longer names the tool or its steps. The fixture generator's docstring, the README, docs/release-contract.md and three microcosm-data mentions of delete-old-layout describe the move in the past tense. What moved builds' manifests carry (migrated_from, unpublished_artifacts) stays documented and accepted. Co-Authored-By: Claude Opus 5.5 --- README.md | 113 +- ...1792-remove-build-folder-switch.removed.md | 1 + docs/release-contract.md | 51 +- .../microcosm/build/build_folder_switch.py | 2050 ----------------- .../microcosm/build/release_publication.py | 16 +- .../test_untagged_build_folder_switch.py | 609 ----- .../uk/test_build_folder_switch.py | 1185 ---------- .../us/test_us_build_folder_switch.py | 445 ---- packages/microcosm-data/README.md | 2 +- .../src/microcosm/data/registry.py | 2 +- .../test_examples_read_build_folders.py | 6 +- .../microcosm_build/build_folder_switch.py | 859 ------- tools/generate_release_contract_fixtures.py | 8 +- 13 files changed, 62 insertions(+), 5285 deletions(-) create mode 100644 changelog.d/1792-remove-build-folder-switch.removed.md delete mode 100644 packages/microcosm-build/src/microcosm/build/build_folder_switch.py delete mode 100644 packages/microcosm-build/tests/engine_free/shared/test_untagged_build_folder_switch.py delete mode 100644 packages/microcosm-build/tests/engine_free/uk/test_build_folder_switch.py delete mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_build_folder_switch.py delete mode 100644 test_support/microcosm_build/build_folder_switch.py diff --git a/README.md b/README.md index b90c6c2564..cd15bfc33f 100644 --- a/README.md +++ b/README.md @@ -723,101 +723,24 @@ of an ACS local-area build publishes into `microcosm-us-2024-local-annual`, carrying its base local build's files ([the local projection guide](docs/us-local-annual-projection.md)). -**The switch.** `microcosm.build.build_folder_switch` moves a repository over, -once, in two steps, and a third step later deletes what the old layout left -on `main`. Each step only reads the repository and prints, as JSON, what it -would do, unless given `--write`: - -```bash -# 1. Copy each tagged build, and each untagged folder --include-untagged -# names, into its folder, one commit per build; run it again later to -# copy builds published since. Hugging Face copies the large (LFS) files -# on its own servers. -uv run python -m microcosm.build.build_folder_switch copy \ - [--include =] [--exclude ] \ - [--include-untagged =] [--write] -# 2. In one commit, write releases.json and delete every latest*.json file. -uv run python -m microcosm.build.build_folder_switch switch \ - [--include =] [--exclude ] \ - [--include-untagged =] [--retire-pointer ] [--current =] \ - [--default ] [--finished-branch ] [--write] -# 3. Later, in one commit, delete the old layout's files from main. -uv run python -m microcosm.build.build_folder_switch delete-old-layout \ - [--write] -``` - -Run the switch step only while nobody publishes to the repository, and give -it the same `--include`, `--exclude` and `--include-untagged` options as the -copy step. - -The copy step moves every tag of a release that publishes into build folders -whose manifest names that tag, and each release-per-build tag that -`--include` names (the June 2023 UK release, or a US release), and refuses a -build any of whose files does not match its manifest, or whose release, build -or role the emitter interface refuses; it reports both without `--write`. It -also copies the files a build's checksum ledger records but its manifest -doesn't declare (each US ACS local-area build has six), checked against the -ledger, and a manifest that declares its own `build_manifest.json` (the US -SPM builds') declares the rewritten one. - -A build with no tag, as BE's builds are stored, is an untagged folder -`releases//` on `main` holding its files directly, and moves only -when `--include-untagged =` names it; its build is then -``. The copy step copies every file the folder holds from the commit -that last changed it, and rewrites the two manifests as for a tagged build. -The release manifest's `artifacts` then lists exactly the files the folder -holds besides the manifests, and keeps the map it had, which may declare -files of the builder's output directory that the folder doesn't hold, -unchanged as `unpublished_artifacts`. Its `migrated_from` names the old -folder, that commit and the old manifest's SHA-256, and the build's -`published_at` is that commit's date. The copy step refuses a folder that is -also a tag, a release named like a folder `--include-untagged` moves, a -folder holding a checksum ledger, a subfolder or nothing but its manifests, -two files whose names give one artifact name, a folder from which a file was -deleted after the commit that last changed the files it holds, and a -manifest with no `build` object, whose `build.build_id` is not the folder's -name or that names a tag (`build.cut_tag`). A `latest.json` with no `revision` names such a folder by its -`release_id`, and its build becomes current. - -The switch refuses unless every such build's folder holds exactly its copied -files, every pointer file's build moves or `--retire-pointer` deletes that -pointer file, no other build folder is on `main`, the repository's tags did -not change while it read them, no `release-staging/` branch shows a tagged -publication in progress, and the emitter interface's checks pass. A -`release-staging/` branch that a finished publication left behind is -accepted when `--finished-branch` names it, its build is tagged and the commit -it names is on `main`; the branch stays where it is. The publisher makes no -branch for a build that is already tagged, but one older than 2026-09-23 -(`7053b9173`) did when retrying such a build, which looks the same while it -runs (the US leftover branch is one), so name a branch only while nobody -publishes. Each build keeps the date of its -tagged commit as `published_at` (an untagged build, the date of the commit -that last changed its old folder), and each pointer file's build becomes its -release's current build. - -After the switch, `main` still holds the tagged layout's files: those each -tagged build overwrote directly in `releases//`, each -release-per-build tag's `releases//` folder (every US build, the June -2023 UK build and builds the switch did not move), each untagged folder -`releases//` (BE's builds), and the dataset files -(`.h5`, `.hdf5`, `.npz`) at the repository's root. The `delete-old-layout` -step deletes all of them in one commit, so build folders and `releases.json` -are the only layout. It keeps `releases.json`, every build folder it lists, -the other root files (`.gitattributes`, `README.md`) and every directory -outside `releases/`, such as the UK repository's `staged/`. It refuses a -repository without `releases.json` or with a `latest*.json` file, and a build -folder `releases.json` does not list, which it never deletes. It runs the -emitter interface's repository check on what remains, and takes none of the -other steps' options. Every tagged build stays readable at its tag, which is -where Microcosm's tag references read it, and every deleted file stays in -`main`'s history at the head the report names; the report lists any deleted -release-per-build or untagged folder that no tag names (`untagged_folders`). Anything -that reads those paths from `main` stops finding them, so run it only once -nothing does (the example notebook reads the US dataset through -`releases.json`). -The commit removes the files from `main` only: their large (LFS) objects stay -in the repository's history. A second run finds nothing to delete. The -module's docstring describes all three steps in full. +**The switch.** The US, UK and BE repositories each moved once from tags +and `latest*.json` pointer files to build folders, with a one-time tool. It +copied each build into its folder, then in one commit wrote `releases.json` +and deleted every pointer file, and later deleted the old layout's files +from `main`: the files each tagged build overwrote directly in +`releases//`, each release-per-build or untagged folder +`releases//`, and the dataset files (`.h5`, `.hdf5`, `.npz`) at the +repository's root. The tool was removed once BE had moved; its last version +is in Git history at `d3b7f4b4a`. Build folders and `releases.json` are now +the only layout on each repository's `main`. Every tagged build stays +readable at its tag, which is where Microcosm's tag references read it, and +every deleted file stays in `main`'s history, with its large (LFS) objects. +A moved build's release manifest names where it came from in +`migrated_from`: its tag, or BE's old untagged folder, with the commit it +was copied from and the SHA-256 of the manifest it was rewritten from. A +moved BE build's folder holds no dataset; its manifest lists the files the +folder holds and keeps its old `artifacts` map as `unpublished_artifacts` +([the release contract](docs/release-contract.md), C1). `microcosm-publish-release-build` publishes only the two manifests, the artifacts the release manifest declares and the checksum ledger. The US diff --git a/changelog.d/1792-remove-build-folder-switch.removed.md b/changelog.d/1792-remove-build-folder-switch.removed.md new file mode 100644 index 0000000000..c864354840 --- /dev/null +++ b/changelog.d/1792-remove-build-folder-switch.removed.md @@ -0,0 +1 @@ +Remove the one-time build-folder switch tool, `microcosm.build.build_folder_switch`, with its `copy`, `switch` and `delete-old-layout` steps and its tests (#1792). The US, UK and BE release repositories have all moved to build folders and `releases.json` and had their old layout deleted, so nothing is left for it to move. `microcosm-publish-release-build`'s refusal for a repository that has pointer files and no `releases.json` no longer tells the operator to run it. The tool's last version is in Git history at `d3b7f4b4a`. diff --git a/docs/release-contract.md b/docs/release-contract.md index d62d3f98ef..6dd093f7f8 100644 --- a/docs/release-contract.md +++ b/docs/release-contract.md @@ -285,11 +285,12 @@ national line's tagged `build_id` held the release's name and `attempt_id` and its top level. Each artifact carries its role. No artifact pins a revision, because `releases.json` and the folder locate a build's files. Both layouts carry `schema_version` 1, and `publishes_to_build_folder` tells them apart. A -build that the switch tool (`microcosm.build.build_folder_switch`) moved from -its tag also carries `migrated_from`, which names the tag, its commit and the -SHA-256 of the manifest the tool rewrote. A build it moved from an untagged -folder on `main` (`--include-untagged`, for BE's builds) carries instead the -old folder, the commit that last changed it and that SHA-256. Its `artifacts` +build that the one-time switch tool moved from its tag also carries +`migrated_from`, which names the tag, its commit and the SHA-256 of the +manifest the tool rewrote. The tool was removed once the US, UK and BE +repositories had moved; its last version is in Git history at `d3b7f4b4a`. A +build it moved from an untagged folder on `main` (BE's builds) carries +instead the old folder, the commit that last changed it and that SHA-256. Its `artifacts` lists the files its folder holds, each with its `path`, `repo_id`, `role` and `sha256` but no `kind`, and `unpublished_artifacts` keeps, unchanged, the map the old manifest had, which declares files of the builder's output directory @@ -308,7 +309,7 @@ tagged-shape manifests in a directory named after the release and then call both manifests in place. The US annual assembler copies its base build's two manifests, changes `release` and `build` in both, drops `migrated_from`, and in the release manifest adds the annual metadata and an artifact for each file the -projection adds. The switch tool rewrites the manifests of the builds it moves. +projection adds. The switch tool rewrote the manifests of the builds it moved. The **certification** is UK-only. The validator requires `release_certification.json` of `microcosm-uk-2024-25-national`. Whatever its @@ -980,20 +981,19 @@ repository that has no `releases.json`. listed release or `null`) and `releases`; for each release its `role`, its `current` build or `null`, and each build's `published_at` and `withdrawn`; a current build that the record lists and has not withdrawn; at most 4 MiB. - The record carries no country, vintage or line. The one-time `switch` step - of `microcosm.build.build_folder_switch` writes a repository's first record - itself and deletes the repository's `latest*.json` files in the same - commit; after that only the emitter's release writer changes the record. - The switch's `copy` step moves each tagged build into a folder and rewrites - its manifests, as C1 describes. Its `delete-old-layout` step then deletes, - in one commit, the files the tagged layout leaves on `main`: every file + The record carries no country, vintage or line. The one-time switch tool's + `switch` step wrote the first record of each of the US, UK and BE + repositories itself and deleted the repository's `latest*.json` files in + the same commit; after that only the emitter's release writer changes the + record. Before it, the tool's `copy` step moved each build into a folder and + rewrote its manifests, as C1 describes. Its `delete-old-layout` step then + deleted, in one commit, the files the old layout left on `main`: every file under `releases/` outside a build folder, and every dataset file (`.h5`, - `.hdf5`, `.npz`) at the repository's root. It keeps `releases.json`, every + `.hdf5`, `.npz`) at the repository's root. It kept `releases.json`, every build folder the record lists, the other root files and every directory - outside `releases/`, and it refuses a repository without `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. + outside `releases/`. Each tagged build stays readable at its tag, and each + deleted file stays in `main`'s history. The tool was removed once BE had + moved. - **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 @@ -1016,8 +1016,9 @@ repository that has no `releases.json`. (`latest_line_release`) only for an entry whose repository has no `releases.json`. `latest_evidence_release` returns the evidence release's current build from `releases.json` where the file exists, and reads - `latest-evidence.json` otherwise. The switch reads the pointer files once, to - set each release's current build and the record's `default`. + `latest-evidence.json` otherwise. The switch tool read each repository's + pointer files once, to set each release's current build and the record's + `default`. - **The registry.** `microcosm.data.registry.REGISTRY` maps `(country, year, variant)` to a `DatasetSpec`. Each names the Hub repository, the dataset file, the engine class, the `release` the loader reads through @@ -1153,9 +1154,11 @@ work. pins builds by tag; version 1 pins each by release and build in its folder. - *The default.* The loader takes each country's default release from the - registry. `releases.json` also names a `default`: in this repository only - the switch tool sets it, and no loader reads it. The gap: no check at - publication confirms that the record's `default` agrees with the registry. + registry. `releases.json` also names a `default`: the one-time switch + tool set it once in each of the US, UK and BE repositories, nothing in + this repository sets it now, and no loader reads it. The gap: no check at + publication confirms that the record's `default` agrees with the registry, + and nothing here sets it for a new repository, such as AM's or NZ's. - *The evidence release.* Its builds answer to `validate_evidence_release_dir` and fail C1 by design. The [retire list](#retire-list-as-of-2026-10-15) names it as an exception: @@ -1324,7 +1327,7 @@ with the interface's own functions, in the order a repository lives it. `add_build(make_current=False)` lists the build, as a publication does. `make_current` makes it current, as a promotion does. `dataclasses.replace(default=...)` then names the national release as the -record's `default`, as the switch tool's `_switch_record` does; interface +record's `default`, as the one-time switch tool did; interface 0.14.0 has no function that sets `default`. `ReleasesRecord.serialize` writes the bytes. Each release takes the role `national`: the UK's from `RELEASE_ROLES` and the national line's dataset role, the US's from diff --git a/packages/microcosm-build/src/microcosm/build/build_folder_switch.py b/packages/microcosm-build/src/microcosm/build/build_folder_switch.py deleted file mode 100644 index d83afe439a..0000000000 --- a/packages/microcosm-build/src/microcosm/build/build_folder_switch.py +++ /dev/null @@ -1,2050 +0,0 @@ -"""Switch a dataset repository from tags and pointer files to build folders. - -A one-time tool, run once for each dataset repository (tracker 2c, plan item -P3). Before the switch, a repository's builds are tagged commits: a build's -files are in its tagged commit's ``releases//`` folder and at the -repository's root, and ``latest.json`` or a ``latest-.json`` pointer -file names the current build. After it, each build is in its own folder, -``releases///``, and the repository's ``releases.json`` is the -only record of each release's builds and which one is current. From then on -the emitter's release writer is the only thing that changes it. - -The switch is two steps, each a separate run of this tool, and a third -step deletes what the old layout left on ``main`` once both have run: - -``copy`` - One commit for each build that moves adds its folder: - - - its release and build manifests, rewritten in the build-folder layout: - ``release`` and ``build`` as strings, the build details (``built_at`` - and the built-with packages) at the top level, a ``role`` on each - artifact and no ``revision``, plus ``migrated_from``, which names the - tag, its commit and the SHA-256 of the manifest it was rewritten from. - A release manifest that declares its own ``build_manifest.json``, as - the US SPM builds' do, declares the rewritten one by its new SHA-256; - - its checksum ledger, when the build has one, with the two manifests' - lines changed to the rewritten manifests' digests; - - every other file the build's release manifest declares, copied from the - tagged commit with ``CommitOperationCopy``: the Hub copies an LFS file, - which every large file is, on its own servers, and ``huggingface_hub`` - downloads a small regular file and sends it in the commit, so nothing - large is downloaded. Each must match the SHA-256 the manifest records; - - every file in the build's tagged folder that its checksum ledger - records but its release manifest does not declare, as each US ACS - local-area build has, copied the same way. Each must match the SHA-256 - the ledger records, and stays undeclared. - - An untagged build (``--include-untagged``, below) is an untagged folder - ``releases//`` on ``main``. Its commit gets the same two - manifests, rewritten the same way, and a copy of every other file the - folder holds, made with ``CommitOperationCopy`` from the commit that - last changed the folder. Its release manifest's ``artifacts`` lists - exactly those files, each with its ``path``, ``repo_id``, ``role`` and - SHA-256, and the map the folder's manifest had, which may declare files - the folder doesn't hold, is kept unchanged as ``unpublished_artifacts``. - Its ``migrated_from`` names the old folder, the commit that last - changed it and the SHA-256 of the manifest it was rewritten from, and - the build's ``published_at`` is that commit's date. - - A folder that already holds a copy of the same build is skipped, - so the step can run again for builds published since. It writes no - ``releases.json``, so the repository keeps publishing and promoting - through its pointer files. - -``switch`` - One commit writes ``releases.json`` and deletes every ``latest*.json`` - pointer file. It refuses unless each moving build's folder holds a copy - of it: exactly its files, a release manifest naming the release, the - build and the manifest it was rewritten from (with its tag, or its old - folder and the commit that last changed it), every declared file with - the SHA-256 the rewritten manifest records (the bytes it had at the tag - or in the old folder, or a declared build manifest's new bytes), and - every undeclared file its checksum ledger records with the SHA-256 it - had at the tag. An untagged build's old folder must be unchanged since - the copy step read it. It - also refuses a build folder - on ``main`` that the record would not list, a change to the - repository's tags between its first read and its commit (a tagged - publication that does not commit to ``main`` would otherwise be lost), - and, at its first read or just before its commit, any - ``release-staging/`` branch, which the tagged publisher keeps from - before it uploads a build until after it tags it. ``--finished-branch - BRANCH`` accepts one that a finished publication left behind, while its - build is tagged and the commit it names is on ``main``: a first - publication still running either has no tag yet, or has its branch on - the tagged commit, which the publisher never puts on ``main`` (its commit - to ``main`` is a new one, made after it deletes the branch). The branch - stays, and must neither move nor disappear before the commit. The - publisher makes no branch for a build that is already tagged, so the one - running publication that also meets both conditions is a publisher older - than ``7053b9173`` (2026-09-23) retrying an already tagged build: it made - its branch from ``main`` and stopped when tagging failed, which is how - the US repository's leftover branch arose. So name a branch only while - nobody publishes. - The record lists every moved build, with the date of its tagged commit, - or of the commit that last changed an untagged build's old folder, as - ``published_at``. The build - each pointer file names becomes its release's current build, and - ``default`` is the release of ``latest-national.json``'s build, or else - of ``latest.json``'s. The - emitter's release writer would refuse this commit, because ``current`` - may not change while a pointer file exists, so this tool makes it itself, - after running the interface's checks on the record, on the repository's - build folders and on the commit, with the pointer files counted as - deleted. - -**Which builds move.** - -Each tag is resolved to the commit it names: the Hub lists an annotated tag -with the ID of its tag object instead. - -- Every tag ``--<8 hex digits>`` of a release that - publishes into build folders - (:func:`microcosm.data.contract.publishes_to_build_folder`) whose release - manifest's ``build.cut_tag`` is the tag. Its build is the manifest's - ``build.attempt_id``. ``--exclude TAG`` leaves one out. -- Each tag that ``--include TAG=RELEASE`` names: a release whose every build - had its own release name and folder ``releases//`` (the June 2023 UK - release, and every US release). Its build is ``TAG``, in ``RELEASE``. -- Each untagged folder that ``--include-untagged FOLDER=RELEASE`` names: a - folder ``releases//`` on ``main`` that no tag names, holding its - build's files directly, as BE's builds are stored. Its build is - ``FOLDER``, in ``RELEASE``. The tool refuses a ``FOLDER`` that is also a - tag, a ``RELEASE`` that is the name of a folder ``--include-untagged`` - moves, a folder holding a checksum ledger, a subfolder or no file besides - its manifests, two of its files whose names give one artifact name, a - folder from which a file was deleted after the commit that last changed - the files it holds, and a release manifest with no ``build`` object, - whose ``build.build_id`` is not ``FOLDER`` or that names a tag - (``build.cut_tag``). - -A pointer file with no ``revision`` names a release-per-build tag, or an -untagged folder, by its ``release_id``: BE's ``latest.json`` names a folder -this way. ``--current RELEASE=BUILD`` makes a moved build current where no -pointer file names one, and ``--default RELEASE`` chooses the default. The -switch refuses a pointer file whose build does not move, unless -``--retire-pointer PATH`` says that the switch should delete it with nothing -in its place. - -``delete-old-layout`` - One commit deletes the old layout's files from ``main``: every file under - ``releases/`` that is not inside a build folder (the files each tagged - build overwrote directly in ``releases//``, each - release-per-build tag's ``releases//`` folder, and each moved - untagged folder ``releases//``), and the dataset - files at the repository's root (``.h5``, ``.hdf5`` and ``.npz``). It - keeps ``releases.json``, every build folder it lists, the other root - files and every directory outside ``releases/`` (``staged/``, say). It - refuses a repository without ``releases.json`` or with a pointer file, - and a build folder ``releases.json`` does not list, which it never - deletes, and it runs the interface's repository check on what remains - (and its commit check, which a deletion outside build folders always - passes). Every deleted file stays in ``main``'s history at the head the - report names, and each tagged build at its tag; the report lists, as - ``untagged_folders``, any deleted folder ``releases//`` that no tag - names (a release-per-build folder, or a moved untagged folder), whose - files then stay only in ``main``'s history. - Run it once nothing reads those files from ``main`` any more. - -Run the ``switch`` step only while nobody publishes to the repository. The -tagged publisher checks for ``releases.json`` only when it starts, so a -publication that starts just before the switch commit, and makes its staging -branch after the switch's last read, would still be in neither the record nor -a folder. A build tagged while ``copy`` runs is safe: the switch refuses until -``copy`` runs again. - -Every step reads the Hub and prints, as JSON, what it would do. They change -nothing without ``--write``. They read and write with ``HF_TOKEN``, then -``HUGGINGFACE_TOKEN``, then the login ``hf auth login`` saved, and refuse to -run with ``HF_HUB_OFFLINE`` or ``TRANSFORMERS_OFFLINE`` set. Each commit names -the head it was checked against as its ``parent_commit``, so if another -commit lands first, the Hub refuses this one; run the step again. - -Run it as ``uv run python -m microcosm.build.build_folder_switch copy - ...``, then the same with ``switch``, and later -``delete-old-layout ``, which takes none of the other options. -""" - -from __future__ import annotations - -import argparse -import hashlib -import json -import os -import re -import sys -from collections.abc import Callable, Collection, Mapping, Sequence -from dataclasses import dataclass, field, replace -from datetime import UTC -from pathlib import Path -from typing import Any - -from microcosm_emitter_interface.releases import ( - RELEASE_MANIFEST_NAME, - RELEASES_RECORD_PATH, - ReleaseRecordError, - ReleasesRecord, - add_build, - build_folder, - check_change, - check_commit, - check_repository, - is_pointer_file, - make_current, -) - -from microcosm.build.staging_dataset import hub_offline -from microcosm.data.contract import ( - CHECKSUMS_FILE, - NATIONAL_DEFAULT_DATASET_ROLE, - RELEASE_ROLES, - RETIRED_BUILD_FIELDS, - publishes_to_build_folder, - release_artifact_role, -) - -__all__ = [ - "BuildMove", - "Selection", - "SwitchRefusedError", - "build_folder_build_manifest", - "build_folder_release_manifest", - "copy_builds", - "delete_old_layout", - "main", - "switch_repository", - "untagged_build_folder_release_manifest", -] - -_DATASET = "dataset" -#: The branch the tagged publisher (``microcosm.data.release``) makes for each -#: publication: from before it uploads the build until just after it tags it, -#: before its commit to ``main``. Since ``7053b9173`` (2026-09-23) it makes -#: none for a build that is already tagged. -_STAGING_BRANCH_PREFIX = "release-staging/" -_BUILD_MANIFEST_NAME = "build_manifest.json" -#: A tag of a release that publishes into build folders: the release, then -#: the calibration attempt's time and digest. -_DATED_TAG = re.compile(r"(?P.+)-(?P[0-9]{8}T[0-9]{6}Z-[0-9a-f]{8})") -#: The pointer files whose build's release becomes ``default``, in order. -_DEFAULT_POINTER_FILES = ("latest-national.json", "latest.json") -#: The root files a tagged build wrote its data to: the dataset and its -#: calibration weights. -_ROOT_DATASET_SUFFIXES = (".h5", ".hdf5", ".npz") -_DELETE_STEP = "delete-old-layout" -#: One line of a checksum ledger, as ``sha256sum`` writes it. -_LEDGER_LINE = re.compile(r"(?P[0-9a-f]{64}) [ *](?P[^/]+)") -#: The field a rewritten release manifest records its origin in. -MIGRATED_FROM_FIELD = "migrated_from" -#: The field an untagged build's rewritten release manifest keeps its old -#: ``artifacts`` map in: the files its builder declared, which the folder -#: may not hold. -UNPUBLISHED_ARTIFACTS_FIELD = "unpublished_artifacts" -#: How the copy step reports each build, by the state of its folder. -_COPY_STATUS = { - "missing": "to_copy", - "copied": "already_copied", - "occupied": "occupied", -} - - -class SwitchRefusedError(ValueError): - """A step cannot go ahead; nothing was written.""" - - -@dataclass(frozen=True) -class Selection: - """Which builds move, and what the switch makes current and default. - - ``include`` maps a release-per-build tag to the release it moves into; - ``exclude`` leaves automatically selected tags out; - ``include_untagged`` maps the name of an untagged folder under - ``releases/`` on ``main`` to the release it moves into; ``current`` maps a - release to a moved build to make current where no pointer file names - one; ``retired_pointers`` are pointer files the switch deletes with - nothing in their place; ``finished_branches`` are staging branches that - finished publications left behind, which the switch accepts while each - one's build is tagged and its head is on ``main``. - """ - - include: Mapping[str, str] - exclude: frozenset[str] - current: Mapping[str, str] - default: str | None - retired_pointers: frozenset[str] - finished_branches: frozenset[str] = frozenset() - include_untagged: Mapping[str, str] = field(default_factory=dict) - - -@dataclass(frozen=True) -class CopiedFile: - """A file copied into a build folder from the build's tagged commit, or - from the commit that last changed an untagged build's folder. - - ``declared`` is false for a file that the build's checksum ledger records - but its release manifest does not declare, as each US ACS local-area - build has; it is copied, and stays undeclared. - """ - - name: str - source: str - sha256: str - declared: bool = True - - -@dataclass(frozen=True) -class BuildMove: - """One tagged or untagged build, and what its folder holds once it is - copied. - - ``written`` maps each file written with new bytes (the two manifests, and - the checksum ledger) to those bytes; ``copied`` lists every other file; - ``declared`` maps each file the rewritten release manifest declares to - its SHA-256 there; ``left_behind`` names files in the tagged commit's - release folder that neither the build's manifests nor its checksum - ledger name (files an earlier build left there). - ``tagged_release`` is the release's name at the tag: ``release`` for a - dated tag, and the tag itself for a release-per-build tag; for an - untagged build, its old folder's name. ``tag`` is ``None`` for an - untagged build, and ``commit`` is then the commit that last changed its - old folder. - """ - - release: str - build: str - release_role: str - tagged_release: str - tag: str | None - commit: str - published_at: str - written: Mapping[str, bytes] - copied: tuple[CopiedFile, ...] - declared: Mapping[str, str] - left_behind: tuple[str, ...] - - @property - def folder(self) -> str: - """The build's folder, ``releases//``.""" - return build_folder(self.release, self.build) - - @property - def source_folder(self) -> str: - """The folder the build's files are copied from.""" - return f"releases/{self.tagged_release}" - - @property - def origin(self) -> str: - """The build's name in reports: its tag, or its old folder.""" - return self.tag if self.tag is not None else f"{self.source_folder}/" - - @property - def migrated_from(self) -> dict[str, str]: - """What the rewritten release manifest records as its origin.""" - manifest = json.loads(self.written[RELEASE_MANIFEST_NAME]) - return dict(manifest[MIGRATED_FROM_FIELD]) - - def paths(self) -> list[str]: - """Every path the build's folder holds once it is copied.""" - names = [*self.written, *(item.name for item in self.copied)] - return [f"{self.folder}/{name}" for name in sorted(names)] - - def summary(self) -> dict[str, Any]: - """The build as the tool prints it.""" - return { - "release": self.release, - "build": self.build, - "release_role": self.release_role, - "tag": self.tag, - "source_folder": self.source_folder, - "commit": self.commit, - "published_at": self.published_at, - "folder": self.folder, - "written": sorted(self.written), - "copied": [ - {"name": item.name, "from": item.source, "sha256": item.sha256} - for item in self.copied - ], - "undeclared": [item.name for item in self.copied if not item.declared], - "left_behind": list(self.left_behind), - } - - -@dataclass(frozen=True) -class _Candidate: - """A tag to move: where its build is, and how its build is named.""" - - tag: str - commit: str - release: str - source_folder: str - #: ``None`` for a dated tag, whose build is its manifest's attempt ID. - build: str | None - - -@dataclass(frozen=True) -class _UntaggedFolder: - """An untagged folder ``releases//`` on ``main`` to move as build - ``name`` of ``release``: the files it holds, and the commit that last - changed one of them, at which it holds exactly those files.""" - - name: str - release: str - commit: str - files: tuple[str, ...] - - @property - def folder(self) -> str: - return f"releases/{self.name}" - - -class _Hub: - """The ``HfApi`` calls the tool makes, on one dataset repository.""" - - def __init__(self, api: Any, repository: str) -> None: - self.api = api - self.repository = repository - - def head(self) -> str: - return self.resolve("main") - - def resolve(self, revision: str) -> str: - """The commit a revision (a branch, a tag or a commit) names.""" - info = self.api.repo_info( - self.repository, repo_type=_DATASET, revision=revision - ) - return str(info.sha) - - def files(self, revision: str) -> list[str]: - return list( - self.api.list_repo_files( - self.repository, repo_type=_DATASET, revision=revision - ) - ) - - def read(self, path: str, revision: str) -> bytes: - local = self.api.hf_hub_download( - self.repository, path, repo_type=_DATASET, revision=revision - ) - return Path(local).read_bytes() - - def refs(self) -> tuple[dict[str, str], dict[str, str]]: - """Each tag with the ID the Hub lists for it, and each of the tagged - publisher's staging branches with the commit it names, from one - request. - - The Hub lists an annotated tag with the ID of its tag object, not of - its commit (:meth:`resolve` gives the commit); a tag that moves gets - another ID either way. A staging branch means a tagged publication - has started and not yet deleted it (it does so just after tagging its - build), or one stopped before deleting it. - """ - refs = self.api.list_repo_refs(self.repository, repo_type=_DATASET) - listed = {tag.name: str(tag.target_commit) for tag in refs.tags} - staging = { - branch.name: str(branch.target_commit) - for branch in refs.branches - if branch.name.startswith(_STAGING_BRANCH_PREFIX) - } - return listed, staging - - def on_main(self, commit: str) -> bool: - """Whether ``commit`` is in ``main``'s history.""" - history = self.api.list_repo_commits( - self.repository, repo_type=_DATASET, revision="main" - ) - return any(item.commit_id == commit for item in history) - - def commit_date(self, commit: str) -> str: - """The commit's date, in UTC to the second, as ``published_at``.""" - history = self.api.list_repo_commits( - self.repository, repo_type=_DATASET, revision=commit - ) - entry = next( - (item for item in history if item.commit_id == commit), - None, - ) - if entry is None: - raise SwitchRefusedError( - f"the Hub lists no commit {commit} in {self.repository}" - ) - return entry.created_at.astimezone(UTC).replace(microsecond=0).isoformat() - - def last_change(self, paths: Sequence[str], revision: str) -> str: - """The newest commit, in ``revision``'s history, that changed any - of ``paths``: in a history without merges, every one of them has - the bytes there that it has at ``revision``. It doesn't see a file - deleted since; the caller compares the files there.""" - infos = self.api.get_paths_info( - self.repository, - list(paths), - repo_type=_DATASET, - revision=revision, - expand=True, - ) - changed = {} - for info in infos: - last_commit = getattr(info, "last_commit", None) - if last_commit is None: - raise SwitchRefusedError( - f"the Hub names no last commit for {info.path} at {revision}" - ) - changed[info.path] = str(last_commit.oid) - if set(changed) != set(paths): - missing = sorted(set(paths) - set(changed)) - raise SwitchRefusedError(f"{missing} are not in commit {revision}") - history = self.api.list_repo_commits( - self.repository, repo_type=_DATASET, revision=revision - ) - commits = set(changed.values()) - newest = next( - (item.commit_id for item in history if item.commit_id in commits), None - ) - if newest is None: - raise SwitchRefusedError( - f"the commits that last changed {sorted(paths)} are not in the " - f"history of {revision}" - ) - return str(newest) - - def sha256s(self, paths: Sequence[str], revision: str) -> dict[str, str]: - """Each file's SHA-256 at ``revision``: an LFS file's from the Hub's - file information, any other file's by reading it.""" - infos = self.api.get_paths_info( - self.repository, list(paths), repo_type=_DATASET, revision=revision - ) - by_path = {info.path: info for info in infos} - digests: dict[str, str] = {} - for path in paths: - info = by_path.get(path) - if info is None: - raise SwitchRefusedError(f"{path} is not in commit {revision}") - lfs = getattr(info, "lfs", None) - digests[path] = ( - str(lfs.sha256) - if lfs is not None - else hashlib.sha256(self.read(path, revision)).hexdigest() - ) - return digests - - def commit(self, operations: list[Any], *, message: str, parent: str) -> str: - info = self.api.create_commit( - self.repository, - operations, - commit_message=message, - repo_type=_DATASET, - parent_commit=parent, - ) - return str(info.oid) - - -def _serialized(document: Mapping[str, Any]) -> bytes: - return (json.dumps(document, indent=1) + "\n").encode() - - -def _merged_field( - name: str, build_value: Any, release_value: Any, clashes: list[str] -) -> Any: - """The value of a field both the build object and the top level have. - - Equal values stay; two objects whose shared fields are equal become one - object with the fields of both. Each field on which they differ is - added to ``clashes``, by its dotted name. - """ - if build_value == release_value: - return release_value - if isinstance(build_value, Mapping) and isinstance(release_value, Mapping): - differing = sorted( - f"{name}.{key}" - for key in set(build_value) & set(release_value) - if build_value[key] != release_value[key] - ) - clashes.extend(differing) - return {**build_value, **release_value} - clashes.append(name) - return release_value - - -def build_folder_release_manifest( - manifest: Mapping[str, Any], - *, - release: str, - build: str, - artifact_names: Mapping[str, str], - migrated_from: Mapping[str, str], - rewritten_sha256: Mapping[str, str] | None = None, -) -> dict[str, Any]: - """A tagged release manifest rewritten in the build-folder layout. - - ``release`` and ``build`` become strings; the old ``build`` object's - other fields, ``built_at`` and the built-with packages among them, move - to the top level; each artifact loses its ``revision``, gains its - ``role`` and records ``artifact_names``'s bare file name as its - ``path``; and ``migrated_from`` records the origin. An artifact in - ``rewritten_sha256`` (a build manifest the release manifest declares, - which the switch rewrites too) records its new SHA-256. - - A field both the ``build`` object and the top level have must be equal, - or be two objects that do not disagree on any field: the June 2023 - release has a ``metadata`` object in both, describing its one build, - and they become one object. - """ - schema, details, rest = _build_details_at_top_level(manifest, taken=()) - rewritten = rewritten_sha256 or {} - artifacts = { - key: { - **{name: value for name, value in entry.items() if name != "revision"}, - "path": artifact_names[key], - "role": release_artifact_role(key, entry.get("kind")), - **({"sha256": rewritten[key]} if key in rewritten else {}), - } - for key, entry in manifest["artifacts"].items() - } - return { - **schema, - "release": release, - "build": build, - **details, - **rest, - "artifacts": artifacts, - MIGRATED_FROM_FIELD: dict(migrated_from), - } - - -def untagged_build_folder_release_manifest( - manifest: Mapping[str, Any], - *, - release: str, - build: str, - repository: str, - held: Mapping[str, str], - migrated_from: Mapping[str, str], -) -> dict[str, Any]: - """An untagged build's release manifest rewritten in the build-folder layout. - - The ``build`` object is rewritten as :func:`build_folder_release_manifest` - rewrites it. ``artifacts`` then lists exactly ``held``: each file the - build's folder holds besides its two manifests, by its bare name, with - its SHA-256, keyed by its name without its extension. The manifest's own - ``artifacts`` map, which may declare files of the builder's output - directory that the folder doesn't hold, is kept unchanged as - ``unpublished_artifacts``. - """ - schema, details, rest = _build_details_at_top_level( - manifest, taken=(UNPUBLISHED_ARTIFACTS_FIELD,) - ) - unpublished = ( - {UNPUBLISHED_ARTIFACTS_FIELD: rest.pop("artifacts")} - if "artifacts" in rest - else {} - ) - artifacts: dict[str, dict[str, str]] = {} - for name, digest in sorted(held.items()): - key = name.split(".", 1)[0] - if not key or key in artifacts: - raise SwitchRefusedError( - f"its folder's files {[*held]} do not each have an artifact name " - f"of their own: {name} would be artifact {key!r}" - ) - artifacts[key] = { - "path": name, - "repo_id": repository, - "role": release_artifact_role(key, None), - "sha256": digest, - } - return { - **schema, - "release": release, - "build": build, - **details, - **rest, - "artifacts": artifacts, - **unpublished, - MIGRATED_FROM_FIELD: dict(migrated_from), - } - - -def _build_details_at_top_level( - manifest: Mapping[str, Any], *, taken: Sequence[str] -) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]: - """A tagged-shape release manifest split for the build-folder layout. - - The result is its ``schema_version`` (as a one-field object, or empty), - the ``build`` object's fields that are not retired and not already at - the top level, and the other top-level fields, where a field the - ``build`` object also has holds the two values merged by - :func:`_merged_field`. Refuses a manifest without a ``build`` object, or - that already has ``release``, ``migrated_from`` or a field in ``taken``. - """ - old_build = manifest.get("build") - if not isinstance(old_build, Mapping): - raise SwitchRefusedError("its release manifest has no build object") - rest = {key: value for key, value in manifest.items() if key != "build"} - already = sorted({"release", MIGRATED_FROM_FIELD, *taken} & set(rest)) - if already: - raise SwitchRefusedError(f"its release manifest already has {already}") - details = { - key: value - for key, value in old_build.items() - if key not in RETIRED_BUILD_FIELDS - } - clashes: list[str] = [] - for key in sorted(set(details) & set(rest)): - rest[key] = _merged_field(key, details[key], rest[key], clashes) - if clashes: - raise SwitchRefusedError( - f"its build object and its top level differ on {clashes}" - ) - details = {key: value for key, value in details.items() if key not in rest} - schema = ( - {"schema_version": rest.pop("schema_version")} - if "schema_version" in rest - else {} - ) - return schema, details, rest - - -def build_folder_build_manifest( - manifest: Mapping[str, Any], *, release: str, build: str -) -> dict[str, Any]: - """A tagged build manifest with ``release`` and ``build`` as its identity.""" - taken = sorted({"release", "build"} & set(manifest)) - if taken: - raise SwitchRefusedError(f"its build manifest already has {taken}") - return { - "release": release, - "build": build, - **{ - key: value - for key, value in manifest.items() - if key not in RETIRED_BUILD_FIELDS - }, - } - - -def _ledger_entries(ledger: bytes) -> dict[str, str]: - """Each file a checksum ledger records, with its digest, in its order.""" - entries: dict[str, str] = {} - for line in ledger.decode().splitlines(): - if not line.strip(): - continue - match = _LEDGER_LINE.fullmatch(line) - if match is None: - raise SwitchRefusedError(f"its {CHECKSUMS_FILE} has a line it cannot read") - if entries.setdefault(match["name"], match["digest"]) != match["digest"]: - raise SwitchRefusedError( - f"its {CHECKSUMS_FILE} records {match['name']} twice" - ) - return entries - - -def _rewritten_ledger( - ledger: bytes, *, expected: Mapping[str, str], replaced: Mapping[str, str] -) -> bytes: - """The checksum ledger with the rewritten manifests' digests. - - Every line must name a file of the build with the digest that file had - at the tagged commit (``expected``); the lines of the files in - ``replaced`` get their new digests. - """ - lines = [] - for name, digest in _ledger_entries(ledger).items(): - if expected.get(name) != digest: - raise SwitchRefusedError( - f"its {CHECKSUMS_FILE} records {name} with a digest that is not " - "the tagged commit's" - ) - lines.append(f"{replaced.get(name, digest)} {name}") - return ("\n".join(lines) + "\n").encode() - - -def _artifact_names( - artifacts: Mapping[str, Any], *, folder: str, repository: str, tag: str -) -> dict[str, str]: - """Each artifact's bare file name; refuse one this tool cannot move.""" - names: dict[str, str] = {} - for key, entry in artifacts.items(): - if not isinstance(entry, Mapping): - raise SwitchRefusedError(f"its artifact {key} is not an object") - path, digest = entry.get("path"), entry.get("sha256") - if not isinstance(path, str) or not isinstance(digest, str): - raise SwitchRefusedError(f"its artifact {key} has no path or sha256") - if entry.get("repo_id") != repository: - raise SwitchRefusedError(f"its artifact {key} is in another repository") - if entry.get("revision") != tag: - raise SwitchRefusedError( - f"its artifact {key} is pinned to {entry.get('revision')!r}, not " - f"the tag {tag}" - ) - name = path.removeprefix(f"{folder}/") - if not name or "/" in name or name in {".", ".."}: - raise SwitchRefusedError(f"its artifact {key} has the path {path!r}") - names[str(key)] = name - if len(set(names.values())) != len(names): - raise SwitchRefusedError("two of its artifacts have the same file name") - # A release manifest may declare its own build manifest, as the US SPM - # builds' do: the switch rewrites that file and declares the new bytes. - taken = {RELEASE_MANIFEST_NAME, CHECKSUMS_FILE} - if taken & set(names.values()): - raise SwitchRefusedError(f"an artifact is named like one of {sorted(taken)}") - return names - - -def _undeclared_ledger_files( - hub: _Hub, - *, - recorded: Mapping[str, str], - declared_names: set[str], - folder: str, - commit: str, - files_at_tag: set[str], -) -> list[CopiedFile]: - """The files a build's checksum ledger records that its release manifest - doesn't declare, each checked against the ledger at the tagged commit. - - They are the build's too, as each US ACS local-area build has them: the - copy step copies them from the tagged folder, and they stay undeclared. - """ - own = {RELEASE_MANIFEST_NAME, _BUILD_MANIFEST_NAME, CHECKSUMS_FILE} - extra = sorted(set(recorded) - own - declared_names) - absent = [name for name in extra if f"{folder}/{name}" not in files_at_tag] - if absent: - raise SwitchRefusedError( - f"its {CHECKSUMS_FILE} records {absent}, which its tagged commit's " - f"{folder}/ does not hold" - ) - if not extra: - return [] - digests = hub.sha256s([f"{folder}/{name}" for name in extra], commit) - for name in extra: - if digests[f"{folder}/{name}"] != recorded[name]: - raise SwitchRefusedError( - f"its {CHECKSUMS_FILE} records {name} with a digest that is not " - "the tagged commit's" - ) - return [ - CopiedFile( - name=name, source=f"{folder}/{name}", sha256=recorded[name], declared=False - ) - for name in extra - ] - - -def _describe(hub: _Hub, candidate: _Candidate) -> BuildMove: - """Read one tagged build and work out its folder; refuse if it cannot move.""" - tag, commit, folder = candidate.tag, candidate.commit, candidate.source_folder - files_at_tag = set(hub.files(commit)) - manifest_path = f"{folder}/{RELEASE_MANIFEST_NAME}" - if manifest_path not in files_at_tag: - raise SwitchRefusedError(f"its tagged commit has no {manifest_path}") - manifest_bytes = hub.read(manifest_path, commit) - manifest = json.loads(manifest_bytes) - old_build = manifest.get("build") if isinstance(manifest, Mapping) else None - if not isinstance(old_build, Mapping): - raise SwitchRefusedError("its release manifest has no build object") - if candidate.build is None: - if old_build.get("build_id") != candidate.release: - raise SwitchRefusedError( - f"its manifest's build_id is not {candidate.release}" - ) - if old_build.get("cut_tag") != tag: - raise SwitchRefusedError("its manifest's cut_tag is not the tag") - build = old_build.get("attempt_id") - if not isinstance(build, str) or not build: - raise SwitchRefusedError("its manifest names no attempt_id") - else: - if old_build.get("build_id") != tag: - raise SwitchRefusedError("its manifest's build_id is not the tag") - build = candidate.build - dataset_role = manifest.get("dataset_role", NATIONAL_DEFAULT_DATASET_ROLE) - release_role = RELEASE_ROLES.get(dataset_role) - if release_role is None: - raise SwitchRefusedError(f"its dataset_role {dataset_role!r} has no role") - artifacts = manifest.get("artifacts") - if not isinstance(artifacts, Mapping) or not artifacts: - raise SwitchRefusedError("its release manifest declares no artifacts") - names = _artifact_names( - artifacts, folder=folder, repository=hub.repository, tag=tag - ) - sources = {} - for key, name in names.items(): - in_folder = f"{folder}/{name}" - if in_folder in files_at_tag: - sources[key] = in_folder - # A declared build manifest is this build's own, in its folder. - elif name in files_at_tag and name != _BUILD_MANIFEST_NAME: - sources[key] = name - else: - raise SwitchRefusedError(f"its tagged commit has no {name}") - digests = hub.sha256s(sorted(set(sources.values())), commit) - for key, source in sources.items(): - if digests[source] != artifacts[key]["sha256"]: - raise SwitchRefusedError( - f"{source} at its tagged commit does not match the SHA-256 its " - "manifest records" - ) - original_sha256 = hashlib.sha256(manifest_bytes).hexdigest() - written: dict[str, bytes] = {} - expected = { - RELEASE_MANIFEST_NAME: original_sha256, - **{names[key]: artifacts[key]["sha256"] for key in names}, - } - replaced: dict[str, str] = {} - build_manifest_path = f"{folder}/{_BUILD_MANIFEST_NAME}" - if build_manifest_path in files_at_tag: - original = hub.read(build_manifest_path, commit) - rewritten = _serialized( - build_folder_build_manifest( - json.loads(original), release=candidate.release, build=build - ) - ) - written[_BUILD_MANIFEST_NAME] = rewritten - expected[_BUILD_MANIFEST_NAME] = hashlib.sha256(original).hexdigest() - replaced[_BUILD_MANIFEST_NAME] = hashlib.sha256(rewritten).hexdigest() - # The keys of a declared build manifest; the rewritten release manifest - # declares the rewritten bytes. - rewritten_keys = [ - key for key, name in names.items() if name == _BUILD_MANIFEST_NAME - ] - release_manifest = _serialized( - build_folder_release_manifest( - manifest, - release=candidate.release, - build=build, - artifact_names=names, - migrated_from={ - "tag": tag, - "commit": commit, - "release_manifest_sha256": original_sha256, - }, - rewritten_sha256={ - key: replaced[_BUILD_MANIFEST_NAME] for key in rewritten_keys - }, - ) - ) - written[RELEASE_MANIFEST_NAME] = release_manifest - replaced[RELEASE_MANIFEST_NAME] = hashlib.sha256(release_manifest).hexdigest() - undeclared: list[CopiedFile] = [] - ledger_path = f"{folder}/{CHECKSUMS_FILE}" - if ledger_path in files_at_tag: - ledger = hub.read(ledger_path, commit) - undeclared = _undeclared_ledger_files( - hub, - recorded=_ledger_entries(ledger), - declared_names=set(names.values()), - folder=folder, - commit=commit, - files_at_tag=files_at_tag, - ) - expected.update({item.name: item.sha256 for item in undeclared}) - written[CHECKSUMS_FILE] = _rewritten_ledger( - ledger, expected=expected, replaced=replaced - ) - copied = tuple( - sorted( - [ - *( - CopiedFile( - name=names[key], - source=sources[key], - sha256=artifacts[key]["sha256"], - ) - for key in names - if key not in rewritten_keys - ), - *undeclared, - ], - key=lambda item: item.name, - ) - ) - declared = { - names[key]: ( - replaced[_BUILD_MANIFEST_NAME] - if key in rewritten_keys - else artifacts[key]["sha256"] - ) - for key in names - } - kept = {*written, *(item.name for item in copied)} - left_behind = tuple( - sorted( - path.removeprefix(f"{folder}/") - for path in files_at_tag - if path.rsplit("/", 1)[0] == folder - and path.removeprefix(f"{folder}/") not in kept - ) - ) - return BuildMove( - release=candidate.release, - build=build, - release_role=release_role, - tagged_release=folder.removeprefix("releases/"), - tag=tag, - commit=commit, - published_at=hub.commit_date(commit), - written=written, - copied=copied, - declared=declared, - left_behind=left_behind, - ) - - -def _untagged_folder( - hub: _Hub, - name: str, - release: str, - *, - head: str, - head_files: Sequence[str], - tags: Mapping[str, str], - moving: Collection[str], -) -> _UntaggedFolder: - """The untagged folder ``releases//`` to move into ``release``; - refuse one this tool cannot move. - - ``moving`` names every untagged folder the run moves: a release with one - of their names would put its build folder inside that old folder. - """ - if not name or "/" in name or name in {".", ".."}: - raise SwitchRefusedError("it is not a folder directly under releases/") - if name in tags: - raise SwitchRefusedError( - f"{name} is a tag of {hub.repository}; move it with --include " - f"{name}=" - ) - if release in moving: - raise SwitchRefusedError( - f"its release {release} is the name of a folder that " - f"--include-untagged moves, so its build folder would be inside " - f"releases/{release}/" - ) - folder = f"releases/{name}" - paths = sorted(path for path in head_files if path.startswith(f"{folder}/")) - if not paths: - raise SwitchRefusedError(f"it is not a folder on main at {head}") - files = tuple(path.removeprefix(f"{folder}/") for path in paths) - nested = [file for file in files if "/" in file] - if nested: - raise SwitchRefusedError( - f"it holds files in subfolders, which this tool does not move: {nested}" - ) - commit = hub.last_change(paths, head) - # The files it holds are unchanged since that commit; a file deleted - # since then means the folder held more there, and no commit records - # when it took the form that moves. - then = {path for path in hub.files(commit) if path.startswith(f"{folder}/")} - if then != set(paths): - deleted = sorted(path.removeprefix(f"{folder}/") for path in then - set(paths)) - raise SwitchRefusedError( - f"{deleted} were deleted from it after {commit}, the commit that " - "last changed the files it holds, so it has no commit to record as " - "its origin" - ) - return _UntaggedFolder(name=name, release=release, commit=commit, files=files) - - -def _describe_untagged(hub: _Hub, untagged: _UntaggedFolder) -> BuildMove: - """Read one untagged folder and work out its build folder; refuse if it - cannot move. Every file is read at the commit that last changed it.""" - folder, commit, build, names = ( - untagged.folder, - untagged.commit, - untagged.name, - untagged.files, - ) - if RELEASE_MANIFEST_NAME not in names: - raise SwitchRefusedError(f"it holds no {RELEASE_MANIFEST_NAME}") - if CHECKSUMS_FILE in names: - raise SwitchRefusedError( - f"it holds a {CHECKSUMS_FILE}, which this tool does not move from an " - "untagged folder" - ) - manifest_bytes = hub.read(f"{folder}/{RELEASE_MANIFEST_NAME}", commit) - manifest = json.loads(manifest_bytes) - old_build = manifest.get("build") if isinstance(manifest, Mapping) else None - if not isinstance(old_build, Mapping): - raise SwitchRefusedError("its release manifest has no build object") - if old_build.get("build_id") != build: - raise SwitchRefusedError(f"its manifest's build_id is not {build}") - if "cut_tag" in old_build: - raise SwitchRefusedError( - f"its manifest names the tag {old_build['cut_tag']!r} as its " - "cut_tag; move that build from its tag" - ) - dataset_role = manifest.get("dataset_role", NATIONAL_DEFAULT_DATASET_ROLE) - release_role = RELEASE_ROLES.get(dataset_role) - if release_role is None: - raise SwitchRefusedError(f"its dataset_role {dataset_role!r} has no role") - held_names = sorted( - name - for name in names - if name not in {RELEASE_MANIFEST_NAME, _BUILD_MANIFEST_NAME} - ) - if not held_names: - raise SwitchRefusedError("it holds no file besides its manifests") - digests = hub.sha256s([f"{folder}/{name}" for name in held_names], commit) - held = {name: digests[f"{folder}/{name}"] for name in held_names} - written: dict[str, bytes] = {} - if _BUILD_MANIFEST_NAME in names: - original = hub.read(f"{folder}/{_BUILD_MANIFEST_NAME}", commit) - written[_BUILD_MANIFEST_NAME] = _serialized( - build_folder_build_manifest( - json.loads(original), release=untagged.release, build=build - ) - ) - written[RELEASE_MANIFEST_NAME] = _serialized( - untagged_build_folder_release_manifest( - manifest, - release=untagged.release, - build=build, - repository=hub.repository, - held=held, - migrated_from={ - "folder": folder, - "commit": commit, - "release_manifest_sha256": hashlib.sha256(manifest_bytes).hexdigest(), - }, - ) - ) - return BuildMove( - release=untagged.release, - build=build, - release_role=release_role, - tagged_release=untagged.name, - tag=None, - commit=commit, - published_at=hub.commit_date(commit), - written=written, - copied=tuple( - CopiedFile(name=name, source=f"{folder}/{name}", sha256=digest) - for name, digest in held.items() - ), - declared=held, - left_behind=(), - ) - - -@dataclass -class _Survey: - """The builds that move, and every tag that does not, with the reason.""" - - #: Every tag the survey read, and the commit it names. - tags: dict[str, str] - #: Every tag the survey read, with the ID the Hub listed for it. - listed_tags: dict[str, str] - #: The tagged publisher's staging branches the survey's listing showed, - #: each with the commit it names. - staging_branches: dict[str, str] - moves: list[BuildMove] - skipped: list[dict[str, str]] - not_moved: list[str] - problems: list[str] - - -def _survey( - hub: _Hub, selection: Selection, *, head: str, head_files: Sequence[str] -) -> _Survey: - """Find the builds that move and read each one: tagged builds at their - tags, and untagged folders on ``main`` at ``head``.""" - listed_tags, staging_branches = hub.refs() - tags = {tag: hub.resolve(tag) for tag in listed_tags} - survey = _Survey( - tags=tags, - listed_tags=listed_tags, - staging_branches=staging_branches, - moves=[], - skipped=[], - not_moved=[], - problems=[], - ) - unknown = sorted({*selection.include, *selection.exclude} - set(tags)) - survey.problems.extend(f"{tag} is not a tag of {hub.repository}" for tag in unknown) - for tag, commit in sorted(tags.items()): - if tag in selection.exclude: - survey.skipped.append({"tag": tag, "reason": "--exclude"}) - continue - if tag in selection.include: - candidate = _Candidate( - tag=tag, - commit=commit, - release=selection.include[tag], - source_folder=f"releases/{tag}", - build=tag, - ) - else: - match = _DATED_TAG.fullmatch(tag) - if match is None or not publishes_to_build_folder(match["release"]): - survey.not_moved.append(tag) - continue - candidate = _Candidate( - tag=tag, - commit=commit, - release=match["release"], - source_folder=f"releases/{match['release']}", - build=None, - ) - try: - survey.moves.append(_describe(hub, candidate)) - except (ValueError, KeyError) as error: - survey.problems.append(f"{tag} cannot move: {error}") - for name, release in sorted(selection.include_untagged.items()): - try: - untagged = _untagged_folder( - hub, - name, - release, - head=head, - head_files=head_files, - tags=tags, - moving=selection.include_untagged.keys(), - ) - survey.moves.append(_describe_untagged(hub, untagged)) - except (ValueError, KeyError) as error: - survey.problems.append(f"releases/{name}/ cannot move: {error}") - seen: dict[tuple[str, str], str] = {} - for move in survey.moves: - earlier = seen.setdefault((move.release, move.build), move.origin) - if earlier != move.origin: - survey.problems.append( - f"{earlier} and {move.origin} are both build {move.build} of " - f"{move.release}" - ) - survey.moves.sort(key=lambda move: (move.release, move.published_at, move.build)) - return survey - - -def _folder_state( - hub: _Hub, move: BuildMove, *, head: str, head_files: Sequence[str] -) -> tuple[str, str | None]: - """The build's folder at ``head``, and why it is not a copy of the build. - - ``missing`` when the folder holds nothing; ``copied`` when it holds - exactly the build's files, its release manifest names the release, the - build and the manifest it was rewritten from (``migrated_from``: the tag - and its commit, or an untagged build's old folder and the commit that - last changed it, so a change to that folder since the copy makes it - ``occupied``), every file the manifest declares has the SHA-256 the - manifest records, and every undeclared file the checksum ledger records - has the SHA-256 it had at the tag; ``occupied`` otherwise, with the - reason. The rewritten - manifests' bytes are not compared, and the checksum ledger at ``head`` is - not read, nor the build manifest unless the release manifest declares - it, so a folder copied by an earlier version of this tool still counts - as copied. - """ - folder = move.folder - present = {path for path in head_files if path.startswith(folder + "/")} - if not present: - return "missing", None - expected = set(move.paths()) - if present - expected: - extra = sorted(path.removeprefix(f"{folder}/") for path in present - expected) - return "occupied", f"{folder}/ also holds {extra}" - if expected - present: - absent = sorted(path.removeprefix(f"{folder}/") for path in expected - present) - return "occupied", f"{folder}/ lacks {absent}" - manifest_path = f"{folder}/{RELEASE_MANIFEST_NAME}" - try: - manifest = json.loads(hub.read(manifest_path, head)) - except ValueError: - manifest = None - if ( - not isinstance(manifest, Mapping) - or manifest.get("release") != move.release - or manifest.get("build") != move.build - or manifest.get(MIGRATED_FROM_FIELD) != move.migrated_from - ): - return "occupied", ( - f"{manifest_path} does not name release {move.release}, build " - f"{move.build} and {MIGRATED_FROM_FIELD} {move.migrated_from}" - ) - artifacts = manifest.get("artifacts") - declared = ( - { - entry.get("path"): entry.get("sha256") - for entry in artifacts.values() - if isinstance(entry, Mapping) - } - if isinstance(artifacts, Mapping) - else {} - ) - if declared != dict(move.declared): - return "occupied", ( - f"{manifest_path} does not declare the files and SHA-256 values of " - f"the manifest at {move.origin}" - ) - recorded = { - **move.declared, - **{item.name: item.sha256 for item in move.copied if not item.declared}, - } - digests = hub.sha256s([f"{folder}/{name}" for name in sorted(recorded)], head) - for name, digest in sorted(recorded.items()): - if digests[f"{folder}/{name}"] != digest: - source = ( - "its manifest" if name in move.declared else f"its {CHECKSUMS_FILE}" - ) - return "occupied", ( - f"{folder}/{name} does not match the SHA-256 {source} records" - ) - return "copied", None - - -def _build_folder_of(path: str) -> str | None: - """The build folder ``releases//`` a path is inside, if - any, as the emitter interface's ``check_commit`` finds it.""" - parts = path.split("/") - if len(parts) >= 4 and parts[0] == "releases": - return "/".join(parts[:3]) - return None - - -def _refuse_switched(head_files: Sequence[str], repository: str) -> None: - if RELEASES_RECORD_PATH in head_files: - raise SwitchRefusedError( - f"{repository} already has {RELEASES_RECORD_PATH}: it has switched, " - "and the emitter's release writer publishes its builds" - ) - - -def _copy_operations(move: BuildMove) -> list[Any]: - from huggingface_hub import CommitOperationAdd, CommitOperationCopy - - return [ - *( - CommitOperationAdd( - path_in_repo=f"{move.folder}/{name}", path_or_fileobj=content - ) - for name, content in sorted(move.written.items()) - ), - *( - CommitOperationCopy( - src_path_in_repo=item.source, - path_in_repo=f"{move.folder}/{item.name}", - src_revision=move.commit, - ) - for item in move.copied - ), - ] - - -def _copy_violations(move: BuildMove, head_files: Sequence[str]) -> list[str]: - """The interface's rules for one copy commit and the folder it adds.""" - record = add_build( - ReleasesRecord.empty(), - release=move.release, - build=move.build, - release_role=move.release_role, - published_at=move.published_at, - make_current=False, - ) - by_path = { - f"{move.folder}/{name}": content for name, content in move.written.items() - } - violations = [ - *check_commit( - before_files=head_files, - added_paths=move.paths(), - deleted_paths=[], - before=None, - after=ReleasesRecord.empty(), - ), - *check_repository(record, move.paths(), by_path.__getitem__), - ] - return [f"{violation.code}: {violation.message}" for violation in violations] - - -def copy_builds( - api: Any, repository: str, selection: Selection, *, write: bool -) -> dict[str, Any]: - """The ``copy`` step: add each moving build's folder, one commit per build. - - Without ``write`` it only reads, and reports every problem, the emitter - interface's checks on the record the moving builds make and on each copy - commit included. With it, it refuses before any commit when the report - has a problem. - """ - hub = _Hub(api, repository) - head = hub.head() - head_files = hub.files(head) - _refuse_switched(head_files, repository) - survey = _survey(hub, selection, head=head, head_files=head_files) - builds = [] - to_copy = [] - for move in survey.moves: - state, reason = _folder_state(hub, move, head=head, head_files=head_files) - if state == "occupied": - survey.problems.append( - f"{move.folder}/ already holds files that are not a copy of " - f"{move.origin}: {reason}" - ) - elif state == "missing": - to_copy.append(move) - builds.append({**move.summary(), "status": _COPY_STATUS[state]}) - # Every moving build, copied or not, goes into one record at the switch, - # so a name or role the interface refuses is a problem now, before any - # folder is written. - record_problems: list[str] = [] - _switch_record(survey.moves, {}, None, record_problems) - survey.problems.extend(record_problems) - if not record_problems: - planned_files = list(head_files) - for move in to_copy: - survey.problems.extend( - f"{move.origin} cannot be copied: {violation}" - for violation in _copy_violations(move, planned_files) - ) - planned_files.extend(move.paths()) - report: dict[str, Any] = { - "step": "copy", - "repository": repository, - "head": head, - "builds": builds, - "skipped": survey.skipped, - "not_moved": survey.not_moved, - "problems": survey.problems, - "written": False, - "commits": [], - } - if not write: - return report - if survey.problems: - raise SwitchRefusedError("nothing was copied: " + "; ".join(survey.problems)) - for move in to_copy: - try: - head = hub.commit( - _copy_operations(move), - message=( - f"Copy build {move.build} of {move.release} into its folder " - + ( - f"from tag {move.tag} ({move.commit})" - if move.tag is not None - else f"from {move.source_folder}/ at {move.commit}" - ) - ), - parent=head, - ) - # Whatever the Hub raised, the builds before this one are copied and - # this one is not; running the step again copies the rest. - except Exception as error: - copied = [entry["origin"] for entry in report["commits"]] - raise SwitchRefusedError( - f"copying {move.origin} failed ({type(error).__name__}: {error}); " - f"copied before it in this run: {copied or 'none'}; run the step " - "again to copy the rest" - ) from error - report["commits"].append( - { - "tag": move.tag, - "origin": move.origin, - "source_folder": move.source_folder, - "folder": move.folder, - "commit": head, - } - ) - report["written"] = True - return report - - -def _pointer_tag(content: bytes) -> tuple[str | None, str | None, bool]: - """The tag a pointer file names, the release it says that is, and - whether it names a revision.""" - try: - payload = json.loads(content) - except ValueError: - return None, None, False - if not isinstance(payload, Mapping): - return None, None, False - release_id, revision = payload.get("release_id"), payload.get("revision") - release_id = release_id if isinstance(release_id, str) else None - if isinstance(revision, str) and revision: - return revision, release_id, True - # A pointer with no revision names a release-per-build release, whose - # tag is its release name, or an untagged folder, by its name. - return release_id, None, False - - -def _pointer_currents( - hub: _Hub, - head: str, - pointer_files: Sequence[str], - moves: Sequence[BuildMove], - selection: Selection, - problems: list[str], -) -> tuple[dict[str, str], dict[str, Any], str | None]: - """Each release's current build from the pointer files, and the default. - - A pointer with no revision names either a release-per-build tag or an - untagged folder by its ``release_id``; a tag and a moving untagged folder - never share a name, since the survey refuses such a folder. - """ - by_tag = {move.tag: move for move in moves if move.tag is not None} - by_folder = {move.tagged_release: move for move in moves if move.tag is None} - currents: dict[str, str] = {} - report: dict[str, Any] = {} - default = None - for path in pointer_files: - if path in selection.retired_pointers: - report[path] = {"retired": True} - continue - tag, named_release, names_revision = _pointer_tag(hub.read(path, head)) - move = by_tag.get(tag) if tag is not None else None - if move is None and tag is not None and not names_revision: - move = by_folder.get(tag) - if move is None: - how = f"with --include {tag}=" - if not names_revision: - how += ( - f" if it is a tag, or with --include-untagged {tag}= " - f"if it is an untagged folder releases/{tag}/ on main" - ) - problems.append( - f"{path} names {tag!r}, which this switch does not move; move it " - f"{how}, or pass --retire-pointer {path} " - "to delete the pointer file with nothing in its place" - ) - continue - if named_release is not None and named_release != move.tagged_release: - problems.append( - f"{path} names release {named_release}, not {move.tagged_release}" - ) - continue - earlier = currents.setdefault(move.release, move.build) - if earlier != move.build: - problems.append( - f"the pointer files name two current builds of {move.release}: " - f"{earlier} and {move.build}" - ) - report[path] = { - "tag": move.tag, - "source_folder": move.source_folder, - "release": move.release, - "current": move.build, - } - for path in _DEFAULT_POINTER_FILES: - if isinstance(report.get(path), Mapping) and "release" in report[path]: - default = report[path]["release"] - break - for release, build in selection.current.items(): - earlier = currents.setdefault(release, build) - if earlier != build: - problems.append( - f"--current {release}={build} conflicts with the pointer files' " - f"current build {earlier}" - ) - return currents, report, default - - -def _switch_record( - moves: Sequence[BuildMove], - currents: Mapping[str, str], - default: str | None, - problems: list[str], -) -> ReleasesRecord: - """The ``releases.json`` the switch writes, through the interface's changes.""" - record = ReleasesRecord.empty() - for move in moves: - try: - record = add_build( - record, - release=move.release, - build=move.build, - release_role=move.release_role, - published_at=move.published_at, - make_current=False, - ) - except (ReleaseRecordError, ValueError) as error: - problems.append(f"{move.origin}: {error}") - for release, build in sorted(currents.items()): - try: - record = make_current(record, release=release, build=build) - except ReleaseRecordError as error: - problems.append(f"current build {build} of {release}: {error}") - if default is not None and default not in record.releases: - problems.append(f"the default {default} is not a release that moves") - return record - return replace(record, default=default) - - -def _publication_in_progress(branch: str) -> str: - return ( - f"branch {branch} exists, so a tagged publication is in progress: its " - "build would be in neither releases.json nor a build folder; run the " - "step again once it has finished, or, if that publication failed, " - "delete the branch first; if it finished and only its branch was left, " - f"name the branch with --finished-branch {branch}" - ) - - -def _staging_branches( - hub: _Hub, survey: _Survey, selection: Selection, problems: list[str] -) -> dict[str, str]: - """The staging branches the switch accepts, each with the commit it names. - - A branch is accepted only when ``--finished-branch`` names it, a tag of - its build exists, and the commit it names is on ``main``. The tagged - publisher makes the branch from ``main``, commits the build to it, tags - that commit, deletes the branch, and then, unless the publication is - tag-only, commits the build to ``main`` in a new commit; so while a first - publication runs, either its build has no tag or its branch names the - tagged commit, which is not on ``main``. Only a publisher older than - ``7053b9173`` retrying an already tagged build made a branch from - ``main`` for it, which meets both; the module docstring says to name a - branch only while nobody publishes. Every other staging branch is a - problem. - """ - accepted: dict[str, str] = {} - problems.extend( - f"--finished-branch {branch} is not a {_STAGING_BRANCH_PREFIX} branch of " - f"{hub.repository}" - for branch in sorted(selection.finished_branches - set(survey.staging_branches)) - ) - for branch, commit in sorted(survey.staging_branches.items()): - if branch not in selection.finished_branches: - problems.append(_publication_in_progress(branch)) - continue - build = branch.removeprefix(_STAGING_BRANCH_PREFIX) - if build not in survey.tags: - problems.append( - f"--finished-branch {branch}: {build} has no tag, so its " - "publication did not finish" - ) - elif not hub.on_main(commit): - problems.append( - f"--finished-branch {branch}: the commit it names, {commit}, is not " - "on main, so its publication may still be running" - ) - else: - accepted[branch] = commit - return accepted - - -def switch_repository( - api: Any, repository: str, selection: Selection, *, write: bool -) -> dict[str, Any]: - """The ``switch`` step: write ``releases.json`` and delete the pointer files. - - Without ``write`` it only reads. With it, it refuses before the commit - unless every moving build has been copied, every pointer file is - accounted for and the interface's checks pass. - """ - hub = _Hub(api, repository) - head = hub.head() - head_files = hub.files(head) - _refuse_switched(head_files, repository) - survey = _survey(hub, selection, head=head, head_files=head_files) - problems = survey.problems - finished_branches = _staging_branches(hub, survey, selection, problems) - for move in survey.moves: - state, reason = _folder_state(hub, move, head=head, head_files=head_files) - if state == "missing": - problems.append( - f"{move.folder}/ is not a copy of {move.origin}; run the copy step " - "first" - ) - elif state == "occupied": - problems.append(f"{move.folder}/ is not a copy of {move.origin}: {reason}") - pointer_files = sorted(path for path in head_files if is_pointer_file(path)) - unknown_retired = sorted(selection.retired_pointers - set(pointer_files)) - problems.extend( - f"{path} is not a pointer file of {repository}" for path in unknown_retired - ) - currents, pointers, pointer_default = _pointer_currents( - hub, head, pointer_files, survey.moves, selection, problems - ) - default = selection.default if selection.default is not None else pointer_default - record = _switch_record(survey.moves, currents, default, problems) - listed = { - build_folder(release, build) - for release, entry in record.releases.items() - for build in entry.builds - } - unlisted = sorted({_build_folder_of(path) for path in head_files} - listed - {None}) - problems.extend( - f"{folder}/ is a build folder that this switch would not list: move its " - "build with this switch, as the copy step did, or delete the folder first" - for folder in unlisted - ) - if not problems: - remaining = [path for path in head_files if path not in pointer_files] - violations = [ - *check_change(None, record), - *check_repository(record, head_files, lambda path: hub.read(path, head)), - # The commit deletes every pointer file, so the rule that current - # may not change while one exists is checked on what remains. - *check_commit( - before_files=remaining, - added_paths=[RELEASES_RECORD_PATH], - deleted_paths=pointer_files, - before=None, - after=record, - ), - ] - problems.extend(f"{item.code}: {item.message}" for item in violations) - message = ( - f"Switch to {RELEASES_RECORD_PATH}: list " - f"{sum(len(entry.builds) for entry in record.releases.values())} builds of " - f"{len(record.releases)} releases and delete {', '.join(pointer_files) or 'no pointer files'}" - ) - report: dict[str, Any] = { - "step": "switch", - "repository": repository, - "head": head, - "builds": [move.summary() for move in survey.moves], - "skipped": survey.skipped, - "not_moved": survey.not_moved, - "pointer_files": pointers, - "finished_branches": sorted(finished_branches), - "delete": pointer_files, - "releases_json": record.to_document(), - "commit_message": message, - "problems": problems, - "written": False, - "commit": None, - } - if not write: - return report - if problems: - raise SwitchRefusedError("nothing was written: " + "; ".join(problems)) - # A tagged publication creates its tag before any commit to main, and a - # tag-only one never commits to main, so parent_commit would not notice a - # build tagged after the survey; list the tags again just before the - # commit, in one request, and compare the IDs the Hub lists. A - # publication that has checked for releases.json but not yet tagged its - # build has a staging branch, so refuse that too. The staging branches - # must be exactly the finished ones the survey accepted, each naming the - # same commit: a retry of a build can make its branch only once the - # leftover one is gone, so one that moved or disappeared is refused too. - listed_tags, staging_branches = hub.refs() - changed = [] - for branch in sorted({*staging_branches, *finished_branches}): - accepted, now = finished_branches.get(branch), staging_branches.get(branch) - if accepted == now: - continue - if accepted is None: - changed.append( - f"branch {branch} appeared while the switch read the repository, so " - "a tagged publication has started: its build would be in neither " - "releases.json nor a build folder; run the step again once it has " - "finished" - ) - elif now is None: - changed.append( - f"branch {branch}, which --finished-branch named, was deleted while " - "the switch read the repository, so a publication of its build may " - f"be starting; run the step again without --finished-branch {branch} " - "once nobody is publishing" - ) - else: - changed.append( - f"branch {branch}, which --finished-branch named, moved from " - f"{accepted} to {now} while the switch read the repository, so a " - "publication is using it; run the step again once it has finished" - ) - if changed: - raise SwitchRefusedError("nothing was written: " + "; ".join(changed)) - if listed_tags != survey.listed_tags: - raise SwitchRefusedError( - "nothing was written: the repository's tags changed while the switch " - "read it, so a build may be missing from the record; run the step " - "again once nobody is publishing" - ) - from huggingface_hub import CommitOperationAdd, CommitOperationDelete - - content = record.serialize() - ReleasesRecord.parse(content) - try: - report["commit"] = hub.commit( - [ - CommitOperationAdd( - path_in_repo=RELEASES_RECORD_PATH, path_or_fileobj=content - ), - *(CommitOperationDelete(path_in_repo=path) for path in pointer_files), - ], - message=message, - parent=head, - ) - # One commit writes the record and deletes the pointer files, so it - # either landed whole or not at all; a second run refuses if it landed. - except Exception as error: - raise SwitchRefusedError( - f"the switch commit failed ({type(error).__name__}: {error}); run " - "the step again, which refuses if the commit did land" - ) from error - report["written"] = True - return report - - -def _old_layout_file(path: str) -> bool: - """Whether a file on ``main`` belongs to the tagged layout. - - That is every file under ``releases/`` outside a build folder (a path - the interface does not place in ``releases///``) and - every dataset file at the repository's root. - """ - if path.startswith("releases/"): - return _build_folder_of(path) is None - return "/" not in path and path.lower().endswith(_ROOT_DATASET_SUFFIXES) - - -def delete_old_layout(api: Any, repository: str, *, write: bool) -> dict[str, Any]: - """The ``delete-old-layout`` step: delete the tagged layout's files from ``main``. - - Without ``write`` it only reads. With it, it refuses before the commit - if it found a problem: a pointer file, a build folder ``releases.json`` - does not list, or a failed interface check on what remains. A second - run after the commit finds nothing to delete and writes nothing. - """ - hub = _Hub(api, repository) - head = hub.head() - head_files = hub.files(head) - if RELEASES_RECORD_PATH not in head_files: - raise SwitchRefusedError( - f"{repository} has not switched: it has no {RELEASES_RECORD_PATH}, " - "so the loader still follows its pointer files; run the copy and " - "switch steps first" - ) - try: - record = ReleasesRecord.parse(hub.read(RELEASES_RECORD_PATH, head)) - except ReleaseRecordError as error: - raise SwitchRefusedError( - f"{RELEASES_RECORD_PATH} in {repository} is not a valid record: {error}" - ) from error - problems = [ - f"{path} is a pointer file; nothing writes one after the switch, so " - "find the commit that added it and remove it first" - for path in sorted(path for path in head_files if is_pointer_file(path)) - ] - listed = { - build_folder(release, build) - for release, entry in record.releases.items() - for build in entry.builds - } - unlisted = sorted({_build_folder_of(path) for path in head_files} - listed - {None}) - problems.extend( - f"{folder}/ is a build folder that {RELEASES_RECORD_PATH} does not list; " - "this step deletes no build folder, so list its build or remove the " - "folder first" - for folder in unlisted - ) - delete = sorted(path for path in head_files if _old_layout_file(path)) - # A release-per-build folder is named by its build's tag; a folder named - # by a release whose builds publish into folders held copies of builds - # that each have their own tag. - listed_tags, _ = hub.refs() - untagged = sorted( - { - f"releases/{parts[1]}" - for parts in (path.split("/") for path in delete) - if len(parts) == 3 - and not publishes_to_build_folder(parts[1]) - and parts[1] not in listed_tags - } - ) - remaining = [path for path in head_files if not _old_layout_file(path)] - if not problems: - violations = [ - *check_repository(record, remaining, lambda path: hub.read(path, head)), - *check_commit( - before_files=head_files, - added_paths=[], - deleted_paths=delete, - before=record, - after=record, - ), - ] - problems.extend(f"{item.code}: {item.message}" for item in violations) - report: dict[str, Any] = { - "step": _DELETE_STEP, - "repository": repository, - "head": head, - "delete": delete, - "kept_root_files": sorted(path for path in remaining if "/" not in path), - "kept_directories": sorted( - {path.split("/", 1)[0] for path in remaining if "/" in path} - {"releases"} - ), - "untagged_folders": untagged, - "problems": problems, - "written": False, - "commit": None, - } - if not write or not delete: - return report - if problems: - raise SwitchRefusedError("nothing was written: " + "; ".join(problems)) - from huggingface_hub import CommitOperationDelete - - try: - report["commit"] = hub.commit( - [CommitOperationDelete(path_in_repo=path) for path in delete], - message=( - f"Delete the old layout's {len(delete)} files: the release-folder " - "contents outside build folders and the root dataset files" - ), - parent=head, - ) - # One commit deletes every file, so it landed whole or not at all; a - # second run finds nothing to delete if it landed. - except Exception as error: - raise SwitchRefusedError( - f"the deletion commit failed ({type(error).__name__}: {error}); run " - "the step again, which finds nothing to delete if it did land" - ) from error - report["written"] = True - return report - - -def _pairs(values: Sequence[str], option: str) -> dict[str, str]: - pairs: dict[str, str] = {} - for value in values: - key, separator, other = value.partition("=") - if not separator or not key or not other: - raise SwitchRefusedError(f"{option} takes NAME=VALUE, not {value!r}") - if pairs.setdefault(key, other) != other: - raise SwitchRefusedError(f"{option} names {key} twice") - return pairs - - -def _parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser( - prog="python -m microcosm.build.build_folder_switch", - description=( - "Switch a dataset repository from tags and latest*.json pointer files " - "to build folders and releases.json: first copy every build into its " - "folder, then switch, and once nothing reads them from main, delete " - "the old layout's files. Each step prints what it would do and " - "changes nothing without --write." - ), - ) - parser.add_argument("step", choices=("copy", "switch", _DELETE_STEP)) - parser.add_argument("repository", help="The Hugging Face dataset repository.") - parser.add_argument( - "--include", - action="append", - default=[], - metavar="TAG=RELEASE", - help="Move the release-per-build tag TAG as build TAG of RELEASE.", - ) - parser.add_argument( - "--exclude", - action="append", - default=[], - metavar="TAG", - help="Leave out a tag that would move automatically.", - ) - parser.add_argument( - "--include-untagged", - action="append", - default=[], - metavar="FOLDER=RELEASE", - help=( - "Move the untagged folder releases/FOLDER/ on main as build FOLDER " - "of RELEASE." - ), - ) - parser.add_argument( - "--current", - action="append", - default=[], - metavar="RELEASE=BUILD", - help="Make BUILD the current build of RELEASE, which no pointer file names.", - ) - parser.add_argument("--default", help="The release releases.json loads by default.") - parser.add_argument( - "--retire-pointer", - action="append", - default=[], - metavar="PATH", - help="Delete this pointer file with nothing in its place.", - ) - parser.add_argument( - "--finished-branch", - action="append", - default=[], - metavar="BRANCH", - help=( - "Accept this release-staging/ branch, which a finished publication " - "left behind: the switch checks that its build is tagged and that " - "the commit it names is on main, and leaves it in place." - ), - ) - parser.add_argument( - "--write", - action="store_true", - help="Make the commits; without it the step only reads and reports.", - ) - return parser - - -def _default_api() -> Any: - import huggingface_hub - - token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN") or None - return huggingface_hub.HfApi(token=token) - - -def main(argv: Sequence[str] | None = None, *, api: Any = None) -> int: - """Run one step; 0 when it found nothing wrong (and, with ``--write``, wrote).""" - args = _parser().parse_args(argv) - if api is None and hub_offline(): - print( - f"refusing to {args.step}: HF_HUB_OFFLINE or TRANSFORMERS_OFFLINE is " - "set, and " - "this tool reads the Hub", - file=sys.stderr, - ) - return 1 - if args.step == _DELETE_STEP: - given = [ - option - for option, value in ( - ("--include", args.include), - ("--exclude", args.exclude), - ("--include-untagged", args.include_untagged), - ("--current", args.current), - ("--default", args.default), - ("--retire-pointer", args.retire_pointer), - ("--finished-branch", args.finished_branch), - ) - if value - ] - if given: - print( - f"refusing to {_DELETE_STEP}: it takes none of {', '.join(given)}, " - "which only the copy and switch steps read", - file=sys.stderr, - ) - return 1 - try: - selection = Selection( - include=_pairs(args.include, "--include"), - exclude=frozenset(args.exclude), - current=_pairs(args.current, "--current"), - default=args.default, - retired_pointers=frozenset(args.retire_pointer), - finished_branches=frozenset(args.finished_branch), - include_untagged=_pairs(args.include_untagged, "--include-untagged"), - ) - client = api if api is not None else _default_api() - if args.step == _DELETE_STEP: - report = delete_old_layout(client, args.repository, write=args.write) - else: - step: Callable[..., dict[str, Any]] = ( - copy_builds if args.step == "copy" else switch_repository - ) - report = step(client, args.repository, selection, write=args.write) - except SwitchRefusedError as error: - print(f"refusing to {args.step}: {error}", file=sys.stderr) - return 1 - print(json.dumps(report, indent=2)) - if report["problems"]: - print( - f"{len(report['problems'])} problem(s); --write would refuse.", - file=sys.stderr, - ) - return 1 - if not args.write: - print("Nothing was written; run again with --write.", file=sys.stderr) - return 0 - - -if __name__ == "__main__": # pragma: no cover - raise SystemExit(main()) diff --git a/packages/microcosm-build/src/microcosm/build/release_publication.py b/packages/microcosm-build/src/microcosm/build/release_publication.py index 1e21296f93..d25d0ed8b9 100644 --- a/packages/microcosm-build/src/microcosm/build/release_publication.py +++ b/packages/microcosm-build/src/microcosm/build/release_publication.py @@ -17,8 +17,8 @@ while one exists. So the command lists the repository's files first and 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 +the loader follows those files, 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``. @@ -570,9 +570,9 @@ def _refuse_pointer_files(repository: str) -> None: The interface's ``is_pointer_file`` rule says which files those are, and the emitter applies it too. A repository's switch to ``releases.json`` deletes them, and nothing writes them after it. Without ``releases.json`` - the repository has not switched: the loader follows its pointer files - and the switch reads them, so the refusal says to run the switch and - keeps them. With it, a pointer file appeared after the switch, and the + the repository has not switched: the loader follows its pointer files, + so the refusal says so and keeps them. With it, a pointer file appeared + after the switch, and the refusal says to remove it. A repository whose files cannot be listed is refused too. """ @@ -590,10 +590,8 @@ def _refuse_pointer_files(repository: str) -> None: raise ValueError( f"{repository} has not switched to releases.json: it has no " f"releases.json and has the pointer file(s) {', '.join(pointer_files)}, " - "which the loader follows and the switch reads. Its builds publish " - "here only after the switch, which the `copy` and then `switch` " - "steps of `python -m microcosm.build.build_folder_switch` make with " - "--write; keep the files in place and run the command again once " + "which the loader follows. Its builds publish here only after the " + "switch; keep the files in place and run the command again once " "the switch has run" ) if pointer_files: diff --git a/packages/microcosm-build/tests/engine_free/shared/test_untagged_build_folder_switch.py b/packages/microcosm-build/tests/engine_free/shared/test_untagged_build_folder_switch.py deleted file mode 100644 index 9714d36b67..0000000000 --- a/packages/microcosm-build/tests/engine_free/shared/test_untagged_build_folder_switch.py +++ /dev/null @@ -1,609 +0,0 @@ -"""The build-folder switch on a repository whose builds have no tags. - -BE's private release repository keeps each build in an untagged folder, -``releases//`` on ``main``, holding only its two manifests and its -calibration diagnostics; its release manifests declare files of the -builder's own output directory that the folder doesn't hold, and its -``latest.json`` names a folder with no revision. ``--include-untagged -FOLDER=RELEASE`` moves such a folder as build ``FOLDER`` of ``RELEASE``. -These tests run the tool against the in-memory repository in -``test_support.microcosm_build.build_folder_switch``, whose names are neutral -fixture names; none reaches the Hub. -""" - -from __future__ import annotations - -import json -from collections.abc import Callable -from datetime import UTC, datetime - -import pytest -from microcosm_emitter_interface.releases import ReleasesRecord, check_repository - -from microcosm.build import build_folder_switch -from test_support.microcosm_build.build_folder_switch import ( - NEWER_UNTAGGED_FOLDER, - NEWER_UNTAGGED_RELEASE, - OLDER_UNTAGGED_FOLDER, - OLDER_UNTAGGED_RELEASE, - UNTAGGED_BUILT_AT, - UNTAGGED_LAST_CHANGED_AT, - UNTAGGED_REPOSITORY, - FakeDatasetRepository, - dumped, - sha256, - untagged_repository, -) - -INCLUDES = ( - "--include-untagged", - f"{OLDER_UNTAGGED_FOLDER}={OLDER_UNTAGGED_RELEASE}", - "--include-untagged", - f"{NEWER_UNTAGGED_FOLDER}={NEWER_UNTAGGED_RELEASE}", -) -#: ``latest.json`` names the newer build, so the older one's release is told -#: which build is current. -SWITCH_OPTIONS = ( - *INCLUDES, - "--current", - f"{OLDER_UNTAGGED_RELEASE}={OLDER_UNTAGGED_FOLDER}", -) -OLDER_SOURCE = f"releases/{OLDER_UNTAGGED_FOLDER}" -NEWER_SOURCE = f"releases/{NEWER_UNTAGGED_FOLDER}" -OLDER_FOLDER = f"releases/{OLDER_UNTAGGED_RELEASE}/{OLDER_UNTAGGED_FOLDER}" -NEWER_FOLDER = f"releases/{NEWER_UNTAGGED_RELEASE}/{NEWER_UNTAGGED_FOLDER}" -#: When a test changes the repository after the copy step. -LATER = datetime(2026, 11, 26, 12, 0, tzinfo=UTC) -MANIFEST_NAMES = {"release_manifest.json", "build_manifest.json"} - - -@pytest.fixture(autouse=True) -def no_hub_access(monkeypatch): - """Every test runs offline and against the in-memory repository only.""" - monkeypatch.setenv("HF_HUB_OFFLINE", "1") - - def no_hub_client(): - pytest.fail("the tool built a Hub client") - - monkeypatch.setattr(build_folder_switch, "_default_api", no_hub_client) - - -@pytest.fixture -def hub(tmp_path) -> FakeDatasetRepository: - return untagged_repository(tmp_path / "hub-cache") - - -def run( - hub: FakeDatasetRepository, capsys, step: str, *options: str -) -> tuple[int, dict, str]: - """Run one step on the in-memory repository: exit code, report and stderr. - - An option the parser refuses ends the run with its exit code, as on the - command line. - """ - try: - exit_code = build_folder_switch.main( - [step, UNTAGGED_REPOSITORY, *options], api=hub - ) - except SystemExit as refusal: - exit_code = int(refusal.code or 0) - captured = capsys.readouterr() - report = json.loads(captured.out) if captured.out.strip() else {} - return exit_code, report, captured.err - - -def commit_made_at(hub: FakeDatasetRepository, moment: datetime) -> str: - """The commit the fixture made at ``moment``.""" - return next(commit for commit, date in hub.dates.items() if date == moment) - - -def last_change(hub: FakeDatasetRepository, folder: str) -> str: - """The commit that last changed an untagged folder on ``main``.""" - return commit_made_at(hub, UNTAGGED_LAST_CHANGED_AT[folder]) - - -def published_at(folder: str) -> str: - return UNTAGGED_LAST_CHANGED_AT[folder].isoformat() - - -def main_document(hub: FakeDatasetRepository, path: str) -> dict: - """A JSON file on ``main``, or an empty object when it is not there.""" - return json.loads(hub.files_at().get(path, b"{}")) - - -def builds_by_source(report: dict) -> dict[str, dict]: - return {build.get("source_folder"): build for build in report.get("builds", [])} - - -def test_copy_without_write_lists_each_untagged_folder_and_changes_nothing(hub, capsys): - head = hub.main - - exit_code, report, error_output = run(hub, capsys, "copy", *INCLUDES) - - assert exit_code == 0, error_output - assert [ - ( - build["release"], - build["build"], - build.get("tag"), - build.get("source_folder"), - build["commit"], - build["published_at"], - build["status"], - ) - for build in report.get("builds", []) - ] == [ - ( - NEWER_UNTAGGED_RELEASE, - NEWER_UNTAGGED_FOLDER, - None, - NEWER_SOURCE, - last_change(hub, NEWER_UNTAGGED_FOLDER), - published_at(NEWER_UNTAGGED_FOLDER), - "to_copy", - ), - ( - OLDER_UNTAGGED_RELEASE, - OLDER_UNTAGGED_FOLDER, - None, - OLDER_SOURCE, - last_change(hub, OLDER_UNTAGGED_FOLDER), - published_at(OLDER_UNTAGGED_FOLDER), - "to_copy", - ), - ] - older = builds_by_source(report).get(OLDER_SOURCE, {}) - diagnostics = hub.files_at()[f"{OLDER_SOURCE}/calibration_diagnostics.json"] - # Only the folder's own file is copied; the declared files it lacks are not. - assert older.get("copied") == [ - { - "name": "calibration_diagnostics.json", - "from": f"{OLDER_SOURCE}/calibration_diagnostics.json", - "sha256": sha256(diagnostics), - } - ] - assert report.get("not_moved") == [] - assert hub.made == [] - assert hub.main == head - - -def test_copy_writes_each_untagged_build_copying_the_files_its_folder_holds( - hub, capsys -): - before = dict(hub.files_at()) - - exit_code, report, error_output = run(hub, capsys, "copy", "--write", *INCLUDES) - - assert exit_code == 0, error_output - assert [ - (commit.get("source_folder"), commit.get("folder")) - for commit in report.get("commits", []) - ] == [(NEWER_SOURCE, NEWER_FOLDER), (OLDER_SOURCE, OLDER_FOLDER)] - older = next( - (commit for commit in hub.made if OLDER_UNTAGGED_FOLDER in commit["message"]), - {"operations": []}, - ) - # The manifests are written new; the diagnostics are copied from the - # commit that last changed the folder, byte for byte. - assert sorted(older["operations"], key=lambda operation: operation[1]) == [ - ("add", f"{OLDER_FOLDER}/build_manifest.json", None, None), - ( - "copy", - f"{OLDER_FOLDER}/calibration_diagnostics.json", - f"{OLDER_SOURCE}/calibration_diagnostics.json", - last_change(hub, OLDER_UNTAGGED_FOLDER), - ), - ("add", f"{OLDER_FOLDER}/release_manifest.json", None, None), - ] - files = hub.files_at() - for source, folder in ((OLDER_SOURCE, OLDER_FOLDER), (NEWER_SOURCE, NEWER_FOLDER)): - assert ( - files.get(f"{folder}/calibration_diagnostics.json") - == (before[f"{source}/calibration_diagnostics.json"]) - ) - # The old folders and latest.json stay until the switch and the deletion. - assert {path: files.get(path) for path in before} == before - - -def test_copied_untagged_manifests_name_the_release_the_build_and_the_origin( - hub, capsys -): - original_bytes = hub.files_at()[f"{OLDER_SOURCE}/release_manifest.json"] - original = json.loads(original_bytes) - original_build_manifest = main_document(hub, f"{OLDER_SOURCE}/build_manifest.json") - - exit_code, _, error_output = run(hub, capsys, "copy", "--write", *INCLUDES) - - assert exit_code == 0, error_output - manifest = main_document(hub, f"{OLDER_FOLDER}/release_manifest.json") - assert (manifest.get("release"), manifest.get("build")) == ( - OLDER_UNTAGGED_RELEASE, - OLDER_UNTAGGED_FOLDER, - ) - assert manifest.get(build_folder_switch.MIGRATED_FROM_FIELD) == { - "folder": OLDER_SOURCE, - "commit": last_change(hub, OLDER_UNTAGGED_FOLDER), - "release_manifest_sha256": sha256(original_bytes), - } - # The old build object's details are at the top level, without build_id. - assert "build_id" not in manifest - assert manifest.get("built_at") == UNTAGGED_BUILT_AT[OLDER_UNTAGGED_FOLDER] - assert manifest.get("chronicle") == original["build"]["chronicle"] - for field in ("description", "data_package", "default_datasets"): - assert manifest.get(field) == original[field] - assert manifest.get("external_validations") == original["external_validations"] - build_manifest = main_document(hub, f"{OLDER_FOLDER}/build_manifest.json") - assert build_manifest == { - "release": OLDER_UNTAGGED_RELEASE, - "build": OLDER_UNTAGGED_FOLDER, - **{ - key: value - for key, value in original_build_manifest.items() - if key != "build_id" - }, - } - - -def test_an_untagged_build_s_artifacts_are_the_files_its_folder_holds(hub, capsys): - """The rewritten manifest lists exactly the files the folder holds, besides - its two manifests, as the collector's daily check of build folders asks; - the builder's own declarations are kept apart, unchanged.""" - originals = { - folder: json.loads(hub.files_at()[f"releases/{folder}/release_manifest.json"]) - for folder in (OLDER_UNTAGGED_FOLDER, NEWER_UNTAGGED_FOLDER) - } - - exit_code, _, error_output = run(hub, capsys, "copy", "--write", *INCLUDES) - - assert exit_code == 0, error_output - files = hub.files_at() - for folder_name, folder in ( - (OLDER_UNTAGGED_FOLDER, OLDER_FOLDER), - (NEWER_UNTAGGED_FOLDER, NEWER_FOLDER), - ): - manifest = main_document(hub, f"{folder}/release_manifest.json") - diagnostics = files.get(f"{folder}/calibration_diagnostics.json", b"") - assert manifest.get("artifacts") == { - "calibration_diagnostics": { - "path": "calibration_diagnostics.json", - "repo_id": UNTAGGED_REPOSITORY, - "role": "calibration_diagnostics", - "sha256": sha256(diagnostics), - } - } - held = { - path.removeprefix(f"{folder}/"): sha256(content) - for path, content in files.items() - if path.startswith(f"{folder}/") - and path.removeprefix(f"{folder}/") not in MANIFEST_NAMES - } - listed = { - entry.get("path"): entry.get("sha256") - for entry in manifest.get("artifacts", {}).values() - } - assert listed == held - assert ( - manifest.get("unpublished_artifacts") - == (originals[folder_name]["artifacts"]) - ) - - -def test_a_copied_untagged_build_counts_as_copied(hub, capsys): - run(hub, capsys, "copy", "--write", *INCLUDES) - - exit_code, report, error_output = run(hub, capsys, "copy", *INCLUDES) - - assert exit_code == 0, error_output - assert { - source: build.get("status") - for source, build in builds_by_source(report).items() - } == {OLDER_SOURCE: "already_copied", NEWER_SOURCE: "already_copied"} - - -def test_switch_makes_latest_json_s_untagged_build_current_and_its_release_default( - hub, capsys -): - run(hub, capsys, "copy", "--write", *INCLUDES) - - exit_code, report, error_output = run( - hub, capsys, "switch", "--write", *SWITCH_OPTIONS - ) - - assert exit_code == 0, error_output - assert report.get("pointer_files", {}).get("latest.json", {}).get("current") == ( - NEWER_UNTAGGED_FOLDER - ) - assert main_document(hub, "releases.json") == { - "schema_version": 1, - "default": NEWER_UNTAGGED_RELEASE, - "releases": { - NEWER_UNTAGGED_RELEASE: { - "role": "national", - "current": NEWER_UNTAGGED_FOLDER, - "builds": { - NEWER_UNTAGGED_FOLDER: { - "published_at": published_at(NEWER_UNTAGGED_FOLDER), - "withdrawn": False, - } - }, - }, - OLDER_UNTAGGED_RELEASE: { - "role": "national", - "current": OLDER_UNTAGGED_FOLDER, - "builds": { - OLDER_UNTAGGED_FOLDER: { - "published_at": published_at(OLDER_UNTAGGED_FOLDER), - "withdrawn": False, - } - }, - }, - }, - } - files = hub.files_at() - assert "latest.json" not in files - record = ReleasesRecord.parse(files["releases.json"]) - assert check_repository(record, list(files), files.__getitem__) == [] - - -def test_two_untagged_builds_can_move_into_one_release(hub, capsys): - """If both builds go into one release, ``latest.json``'s build is current.""" - includes = ( - "--include-untagged", - f"{OLDER_UNTAGGED_FOLDER}={NEWER_UNTAGGED_RELEASE}", - "--include-untagged", - f"{NEWER_UNTAGGED_FOLDER}={NEWER_UNTAGGED_RELEASE}", - ) - copy_code, _, copy_error = run(hub, capsys, "copy", "--write", *includes) - assert copy_code == 0, copy_error - - exit_code, _, error_output = run(hub, capsys, "switch", "--write", *includes) - - assert exit_code == 0, error_output - record = main_document(hub, "releases.json") - assert record.get("default") == NEWER_UNTAGGED_RELEASE - release = record.get("releases", {}).get(NEWER_UNTAGGED_RELEASE, {}) - assert release.get("current") == NEWER_UNTAGGED_FOLDER - assert sorted(release.get("builds", {})) == sorted( - [OLDER_UNTAGGED_FOLDER, NEWER_UNTAGGED_FOLDER] - ) - - -def test_switch_refuses_an_untagged_folder_changed_since_its_copy(hub, capsys): - run(hub, capsys, "copy", "--write", *INCLUDES) - hub.seed( - {f"{NEWER_SOURCE}/calibration_diagnostics.json": b'{"changed": true}'}, - date=LATER, - ) - - exit_code, report, error_output = run( - hub, capsys, "switch", "--write", *SWITCH_OPTIONS - ) - - assert exit_code == 1 - assert "releases.json" not in hub.files_at() - assert any( - NEWER_FOLDER in problem and NEWER_SOURCE in problem - for problem in report.get("problems", [error_output]) - ), error_output - - -def test_switch_refuses_a_pointer_naming_an_untagged_folder_that_does_not_move( - hub, capsys -): - older_only = ( - "--include-untagged", - f"{OLDER_UNTAGGED_FOLDER}={OLDER_UNTAGGED_RELEASE}", - ) - run(hub, capsys, "copy", "--write", *older_only) - - exit_code, report, _ = run(hub, capsys, "switch", *older_only) - - assert exit_code == 1 - assert any( - "latest.json" in problem - and f"--include-untagged {NEWER_UNTAGGED_FOLDER}=" in problem - for problem in report.get("problems", []) - ) - - -def _add_main_files(hub: FakeDatasetRepository, files: dict[str, bytes]) -> None: - hub.seed(files, date=LATER) - - -def _change_newer_manifest(hub: FakeDatasetRepository, change: Callable) -> None: - path = f"{NEWER_SOURCE}/release_manifest.json" - manifest = json.loads(hub.files_at()[path]) - change(manifest) - _add_main_files(hub, {path: dumped(manifest)}) - - -def _tag_newer_folder(hub: FakeDatasetRepository) -> None: - hub.tags[NEWER_UNTAGGED_FOLDER] = hub.main - - -@pytest.mark.parametrize( - ("change", "named"), - [ - pytest.param(_tag_newer_folder, "--include", id="a tag of the same name"), - pytest.param( - lambda hub: _change_newer_manifest( - hub, lambda manifest: manifest["build"].update(build_id="another") - ), - "build_id", - id="a manifest naming another build", - ), - pytest.param( - lambda hub: _change_newer_manifest( - hub, - lambda manifest: manifest["build"].update( - cut_tag=f"{NEWER_UNTAGGED_FOLDER}-tag" - ), - ), - "cut_tag", - id="a manifest naming a tag", - ), - pytest.param( - lambda hub: _change_newer_manifest( - hub, lambda manifest: manifest.update(unpublished_artifacts={}) - ), - "unpublished_artifacts", - id="a manifest that already has unpublished_artifacts", - ), - pytest.param( - lambda hub: _add_main_files(hub, {f"{NEWER_SOURCE}/sha256sums.txt": b""}), - "sha256sums.txt", - id="a checksum ledger", - ), - pytest.param( - lambda hub: _add_main_files( - hub, {f"{NEWER_SOURCE}/nested/extra.json": b"{}"} - ), - "nested/extra.json", - id="a file in a subfolder", - ), - pytest.param( - lambda hub: _add_main_files( - hub, - { - f"{NEWER_SOURCE}/calibration_diagnostics.csv": b"", - }, - ), - "calibration_diagnostics", - id="two files with one artifact name", - ), - ], -) -def test_copy_refuses_an_untagged_folder_it_cannot_move(hub, capsys, change, named): - change(hub) - - exit_code, report, error_output = run(hub, capsys, "copy", "--write", *INCLUDES) - - assert exit_code == 1 - problems = [ - problem - for problem in report.get("problems", [error_output]) - if NEWER_UNTAGGED_FOLDER in problem - ] - assert problems, error_output - assert any(named in problem for problem in problems), problems - assert hub.made == [] - - -def test_copy_refuses_an_untagged_folder_that_is_not_on_main(hub, capsys): - exit_code, report, error_output = run( - hub, capsys, "copy", "--include-untagged", "not-a-folder=example-release" - ) - - assert exit_code == 1 - assert any( - "releases/not-a-folder/" in problem for problem in report.get("problems", []) - ), error_output - - -def test_include_untagged_takes_folder_equals_release(hub, capsys): - exit_code, _, error_output = run( - hub, capsys, "copy", "--include-untagged", NEWER_UNTAGGED_FOLDER - ) - - assert exit_code == 1 - assert "--include-untagged takes NAME=VALUE" in error_output - - -def test_delete_old_layout_takes_no_include_untagged_option(hub, capsys): - exit_code, _, error_output = run(hub, capsys, "delete-old-layout", *INCLUDES[:2]) - - assert exit_code == 1 - assert "--include-untagged" in error_output - - -def test_delete_old_layout_removes_the_untagged_folders_and_reports_them(hub, capsys): - run(hub, capsys, "copy", "--write", *INCLUDES) - switch_code, _, switch_error = run( - hub, capsys, "switch", "--write", *SWITCH_OPTIONS - ) - assert switch_code == 0, switch_error - before = dict(hub.files_at()) - - exit_code, report, error_output = run(hub, capsys, "delete-old-layout", "--write") - - assert exit_code == 0, error_output - assert set(hub.files_at()) == {".gitattributes", "README.md", "releases.json"} | { - path - for path in before - if path.startswith((f"{OLDER_FOLDER}/", f"{NEWER_FOLDER}/")) - } - # No tag keeps them; they stay in main's history at the head it read. - assert report.get("untagged_folders") == [NEWER_SOURCE, OLDER_SOURCE] - - -def test_a_release_name_the_interface_refuses_names_the_untagged_folder(hub, capsys): - exit_code, report, error_output = run( - hub, - capsys, - "copy", - "--include-untagged", - f"{NEWER_UNTAGGED_FOLDER}=not a release name", - ) - - assert exit_code == 1 - problems = report.get("problems", []) - assert any(problem.startswith(f"{NEWER_SOURCE}/") for problem in problems), ( - error_output - ) - assert not any(problem.startswith("None") for problem in problems), problems - - -def test_copy_refuses_an_untagged_folder_whose_files_were_deleted_since(hub, capsys): - """The commit that last changed the folder's remaining files still held a - file deleted later, so it is not a commit at which the folder held what it - holds now.""" - hub.seed( - { - f"{NEWER_SOURCE}/calibration_diagnostics.json": b'{"rewritten": true}', - f"{NEWER_SOURCE}/notes.json": b"{}", - }, - date=LATER, - ) - hub.seed({}, date=LATER.replace(hour=13)) - del hub.commits[hub.main][f"{NEWER_SOURCE}/notes.json"] - - exit_code, report, error_output = run(hub, capsys, "copy", *INCLUDES) - - assert exit_code == 1 - assert any( - problem.startswith(f"{NEWER_SOURCE}/") and "notes.json" in problem - for problem in report.get("problems", []) - ), error_output - - -@pytest.mark.parametrize( - "includes", - [ - pytest.param( - ("--include-untagged", f"{NEWER_UNTAGGED_FOLDER}={NEWER_UNTAGGED_FOLDER}"), - id="its own folder's name", - ), - pytest.param( - ( - "--include-untagged", - f"{NEWER_UNTAGGED_FOLDER}={OLDER_UNTAGGED_FOLDER}", - "--include-untagged", - f"{OLDER_UNTAGGED_FOLDER}={OLDER_UNTAGGED_RELEASE}", - ), - id="another moving folder's name", - ), - ], -) -def test_copy_refuses_a_release_named_like_a_moving_untagged_folder( - hub, capsys, includes -): - """Its build folder would be inside that old folder, which could then - never move.""" - exit_code, report, error_output = run(hub, capsys, "copy", "--write", *includes) - - assert exit_code == 1 - assert any( - f"{NEWER_SOURCE}/" in problem and "--include-untagged" in problem - for problem in report.get("problems", [error_output]) - ), error_output - assert hub.made == [] diff --git a/packages/microcosm-build/tests/engine_free/uk/test_build_folder_switch.py b/packages/microcosm-build/tests/engine_free/uk/test_build_folder_switch.py deleted file mode 100644 index a428f27183..0000000000 --- a/packages/microcosm-build/tests/engine_free/uk/test_build_folder_switch.py +++ /dev/null @@ -1,1185 +0,0 @@ -"""The one-time switch from tags and pointer files to build folders (P3). - -The tool copies each tagged build into ``releases///`` and -then, in one commit, writes ``releases.json`` and deletes the ``latest*.json`` -pointer files. These tests run it against the in-memory repository in -``test_support.microcosm_build.build_folder_switch``, laid out as the UK -private repository is before its switch; none reaches the Hub. -""" - -from __future__ import annotations - -import json -from datetime import UTC, datetime - -import pytest -from microcosm_emitter_interface.releases import ReleasesRecord, check_repository - -from microcosm.build import build_folder_switch -from microcosm.data import loader -from microcosm.data.registry import REGISTRY -from microcosm.data.releases_record import parse_releases_record -from test_support.microcosm_build.build_folder_switch import ( - DENSE, - DENSE_BUILD, - DENSE_TAG, - JUNE_2023_BUILD_METADATA, - JUNE_2023_RELEASE_METADATA, - JUNE_2023_TAG, - NATIONAL, - NEWER_NATIONAL_BUILD, - NEWER_NATIONAL_TAG, - OLDER_NATIONAL_BUILD, - OLDER_NATIONAL_TAG, - UK_REPOSITORY, - FakeDatasetRepository, - dumped, - sha256, - uk_repository, -) -from test_support.microcosm_data.build_folders import register_uk_local_release - -#: The stable release the June 2023 build moves into, when it moves. -JUNE_2023_RELEASE = "populace-uk-2023" -INCLUDE_JUNE_2023 = ("--include", f"{JUNE_2023_TAG}={JUNE_2023_RELEASE}") -NEWER_NATIONAL_FOLDER = f"releases/{NATIONAL}/{NEWER_NATIONAL_BUILD}" -DENSE_FOLDER = f"releases/{DENSE}/{DENSE_BUILD}" -JUNE_2023_FOLDER = f"releases/{JUNE_2023_RELEASE}/{JUNE_2023_TAG}" -JUNE_2023_MANIFEST = f"releases/{JUNE_2023_TAG}/release_manifest.json" -#: When a test changes the repository after the copy step. -LATER = datetime(2026, 11, 6, 12, 0, tzinfo=UTC) -#: The branch the tagged publisher (``microcosm.data.release``) keeps while it -#: publishes a dense build: from before its upload until after it tags it. -DENSE_STAGING_BRANCH = f"release-staging/{DENSE}" - - -@pytest.fixture(autouse=True) -def no_hub_access(monkeypatch): - """Every test runs offline and against the in-memory repository only.""" - monkeypatch.setenv("HF_HUB_OFFLINE", "1") - - def no_hub_client(): - pytest.fail("the tool built a Hub client") - - monkeypatch.setattr(build_folder_switch, "_default_api", no_hub_client) - - -@pytest.fixture -def hub(tmp_path) -> FakeDatasetRepository: - return uk_repository(tmp_path / "hub-cache") - - -def run( - hub: FakeDatasetRepository, capsys, step: str, *options: str -) -> tuple[int, dict, str]: - """Run one step on the in-memory repository: exit code, report and stderr.""" - exit_code = build_folder_switch.main([step, UK_REPOSITORY, *options], api=hub) - captured = capsys.readouterr() - report = json.loads(captured.out) if captured.out.strip() else {} - return exit_code, report, captured.err - - -def copied_file(hub: FakeDatasetRepository, path: str) -> bytes: - """A file on ``main``, or no bytes when it is not there.""" - return hub.files_at().get(path, b"") - - -def test_copy_without_write_lists_each_tagged_build_and_changes_nothing(hub, capsys): - head = hub.main - - exit_code, report, error_output = run(hub, capsys, "copy") - - assert exit_code == 0 - assert [ - (build["release"], build["build"], build["tag"], build["status"]) - for build in report.get("builds", []) - ] == [ - (DENSE, DENSE_BUILD, DENSE_TAG, "to_copy"), - (NATIONAL, OLDER_NATIONAL_BUILD, OLDER_NATIONAL_TAG, "to_copy"), - (NATIONAL, NEWER_NATIONAL_BUILD, NEWER_NATIONAL_TAG, "to_copy"), - ] - # The June 2023 release names one release per build, so it moves only - # when --include says into which release. - assert report.get("not_moved") == [JUNE_2023_TAG] - newer = next( - ( - build - for build in report.get("builds", []) - if build["build"] == NEWER_NATIONAL_BUILD - ), - {}, - ) - # An earlier build's file that this build's manifest does not name stays. - assert newer.get("left_behind") == ["score_vs_enhanced_frs.json"] - assert hub.made == [] - assert hub.main == head - assert "Nothing was written" in error_output - - -def test_copy_writes_each_build_into_its_folder_copying_its_tagged_files(hub, capsys): - exit_code, report, _ = run(hub, capsys, "copy", "--write") - - assert exit_code == 0 - assert [commit["tag"] for commit in report.get("commits", [])] == [ - DENSE_TAG, - OLDER_NATIONAL_TAG, - NEWER_NATIONAL_TAG, - ] - assert len(hub.made) == 3 - tagged_commit = hub.tags[NEWER_NATIONAL_TAG] - newer = next( - (commit for commit in hub.made if NEWER_NATIONAL_BUILD in commit["message"]), - {"operations": []}, - ) - # The manifests are written new; every other file is copied on the Hub's - # servers from the build's tagged commit, so nothing large is uploaded. - assert sorted(newer["operations"], key=lambda operation: operation[1]) == [ - ("add", f"{NEWER_NATIONAL_FOLDER}/build_manifest.json", None, None), - ( - "copy", - f"{NEWER_NATIONAL_FOLDER}/calibration_diagnostics.json", - f"releases/{NATIONAL}/calibration_diagnostics.json", - tagged_commit, - ), - ( - "copy", - f"{NEWER_NATIONAL_FOLDER}/microcosm_uk_2024_25.h5", - "microcosm_uk_2024_25.h5", - tagged_commit, - ), - ( - "copy", - f"{NEWER_NATIONAL_FOLDER}/microcosm_uk_2024_25_calibration.npz", - "microcosm_uk_2024_25_calibration.npz", - tagged_commit, - ), - ( - "copy", - f"{NEWER_NATIONAL_FOLDER}/release_certification.json", - f"releases/{NATIONAL}/release_certification.json", - tagged_commit, - ), - ("add", f"{NEWER_NATIONAL_FOLDER}/release_manifest.json", None, None), - ] - assert ( - copied_file(hub, f"{NEWER_NATIONAL_FOLDER}/microcosm_uk_2024_25.h5") - == b"newer national dataset" - ) - # Until the switch, the repository still publishes through its pointers. - files = hub.files_at() - assert "releases.json" not in files - assert {"latest.json", "latest-national.json"} <= set(files) - - -def test_copied_manifests_name_the_release_and_the_build(hub, capsys): - run(hub, capsys, "copy", "--write") - tagged_bytes = hub.files_at(NEWER_NATIONAL_TAG)[ - f"releases/{NATIONAL}/release_manifest.json" - ] - tagged = json.loads(tagged_bytes) - - manifest = json.loads( - copied_file(hub, f"{NEWER_NATIONAL_FOLDER}/release_manifest.json") or b"{}" - ) - build_manifest = json.loads( - copied_file(hub, f"{NEWER_NATIONAL_FOLDER}/build_manifest.json") or b"{}" - ) - - assert (manifest.get("release"), manifest.get("build")) == ( - NATIONAL, - NEWER_NATIONAL_BUILD, - ) - for detail in ("built_at", "built_with_core_package", "built_with_model_package"): - assert manifest.get(detail) == tagged["build"][detail] - artifacts = manifest.get("artifacts", {}) - assert {key: entry.get("role") for key, entry in artifacts.items()} == { - "microcosm_uk_2024_25": "dataset", - "microcosm_uk_2024_25_calibration": "calibration_weights", - "calibration_diagnostics": "calibration_diagnostics", - "release_certification": "release_certification", - } - assert not any("revision" in entry for entry in artifacts.values()) - assert {key: entry.get("sha256") for key, entry in artifacts.items()} == { - key: entry["sha256"] for key, entry in tagged["artifacts"].items() - } - assert manifest.get("migrated_from") == { - "tag": NEWER_NATIONAL_TAG, - "commit": hub.tags[NEWER_NATIONAL_TAG], - "release_manifest_sha256": sha256(tagged_bytes), - } - assert (build_manifest.get("release"), build_manifest.get("build")) == ( - NATIONAL, - NEWER_NATIONAL_BUILD, - ) - assert not {"build_id", "attempt_id", "cut_tag"} & set(build_manifest) - - -def test_the_loader_certifies_a_copied_build_from_its_folder(hub, capsys): - run(hub, capsys, "copy", "--write") - manifest = json.loads( - copied_file(hub, f"{NEWER_NATIONAL_FOLDER}/release_manifest.json") or b"{}" - ) - assert manifest.get("build") == NEWER_NATIONAL_BUILD - - certified = loader._certified_release_from_manifest( - REGISTRY[("uk", 2025, "compact")], - NATIONAL, - manifest, - expected_revision=None, - build=NEWER_NATIONAL_BUILD, - release_role="national", - ) - - assert certified.artifact_path == f"{NEWER_NATIONAL_FOLDER}/microcosm_uk_2024_25.h5" - assert certified.artifact_sha256 == sha256(b"newer national dataset") - - -def test_copy_rewrites_the_checksum_ledger_for_the_rewritten_manifests(hub, capsys): - run(hub, capsys, "copy", "--write") - - ledger = { - name: digest - for digest, name in ( - line.split(" ", 1) - for line in copied_file(hub, f"{DENSE_FOLDER}/sha256sums.txt") - .decode() - .splitlines() - ) - } - - assert ledger == { - name: sha256(copied_file(hub, f"{DENSE_FOLDER}/{name}")) - for name in ( - "build_manifest.json", - "calibration_diagnostics.json", - "gate_summary.json", - "microcosm_uk_2024_25_dense.h5", - "release_manifest.json", - ) - } - - -def test_copy_refuses_a_build_whose_file_does_not_match_its_manifest(hub, capsys): - hub.commits[hub.tags[DENSE_TAG]]["microcosm_uk_2024_25_dense.h5"] = b"changed" - - exit_code, _, error_output = run(hub, capsys, "copy", "--write") - - assert exit_code == 1 - assert hub.made == [] - assert "does not match the SHA-256 its manifest records" in error_output - - -def test_copy_again_skips_the_builds_already_in_their_folders(hub, capsys): - run(hub, capsys, "copy", "--write") - assert len(hub.made) == 3 - - exit_code, report, _ = run(hub, capsys, "copy", "--write") - - assert exit_code == 0 - assert len(hub.made) == 3 - assert [build["status"] for build in report.get("builds", [])] == [ - "already_copied" - ] * 3 - - -def test_a_failed_copy_commit_names_the_builds_copied_before_it( - hub, capsys, monkeypatch -): - create_commit = hub.create_commit - attempts = [] - - def second_commit_conflicts(*args, **kwargs): - attempts.append(kwargs["parent_commit"]) - if len(attempts) == 2: - raise RuntimeError("412: another commit landed first") - return create_commit(*args, **kwargs) - - monkeypatch.setattr(hub, "create_commit", second_commit_conflicts) - - exit_code, _, error_output = run(hub, capsys, "copy", "--write") - - assert exit_code == 1 - assert len(hub.made) == 1 - assert f"copied before it in this run: ['{DENSE_TAG}']" in error_output - - -def test_a_tag_whose_manifest_names_another_tag_moves_only_when_excluded(hub, capsys): - stray_tag = f"{NATIONAL}-20261106T000000Z-0badcafe" - hub.tags[stray_tag] = hub.tags[NEWER_NATIONAL_TAG] - - exit_code, report, _ = run(hub, capsys, "copy") - excluded_exit_code, excluded, _ = run(hub, capsys, "copy", "--exclude", stray_tag) - - assert exit_code == 1 - assert [problem for problem in report.get("problems", []) if stray_tag in problem] - assert excluded_exit_code == 0 - assert {"tag": stray_tag, "reason": "--exclude"} in excluded.get("skipped", []) - - -def test_switch_without_write_prints_the_record_and_changes_nothing(hub, capsys): - run(hub, capsys, "copy", "--write") - made = list(hub.made) - - exit_code, report, error_output = run( - hub, capsys, "switch", "--retire-pointer", "latest.json" - ) - - assert exit_code == 0 - assert report.get("delete") == ["latest-national.json", "latest.json"] - record = report.get("releases_json", {}) - assert record.get("default") == NATIONAL - assert record.get("releases", {}).get(NATIONAL, {}).get("current") == ( - OLDER_NATIONAL_BUILD - ) - assert hub.made == made - assert "Nothing was written" in error_output - - -def test_switch_writes_releases_json_and_deletes_the_pointer_files_in_one_commit( - hub, capsys -): - run(hub, capsys, "copy", "--write", *INCLUDE_JUNE_2023) - head = hub.main - - exit_code, _, _ = run(hub, capsys, "switch", "--write", *INCLUDE_JUNE_2023) - - assert exit_code == 0 - switch_commit = hub.made[-1] if len(hub.made) == 5 else {"operations": []} - assert switch_commit.get("parent") == head - assert sorted(operation[:2] for operation in switch_commit["operations"]) == [ - ("add", "releases.json"), - ("delete", "latest-national.json"), - ("delete", "latest.json"), - ] - # Each build keeps the date of its tagged commit, and each pointer file's - # build is its release's current build: latest-national.json names the - # older national build, though a newer one was published since. - assert json.loads(copied_file(hub, "releases.json") or b"{}") == { - "schema_version": 1, - "default": NATIONAL, - "releases": { - DENSE: { - "role": "local_area", - "current": None, - "builds": { - DENSE_BUILD: { - "published_at": "2026-11-04T13:06:25+00:00", - "withdrawn": False, - } - }, - }, - NATIONAL: { - "role": "national", - "current": OLDER_NATIONAL_BUILD, - "builds": { - OLDER_NATIONAL_BUILD: { - "published_at": "2026-10-19T10:21:04+00:00", - "withdrawn": False, - }, - NEWER_NATIONAL_BUILD: { - "published_at": "2026-11-05T23:30:42+00:00", - "withdrawn": False, - }, - }, - }, - JUNE_2023_RELEASE: { - "role": "national", - "current": JUNE_2023_TAG, - "builds": { - JUNE_2023_TAG: { - "published_at": "2026-06-19T02:38:38+00:00", - "withdrawn": False, - } - }, - }, - }, - } - assert not [ - path for path in hub.files_at() if path.rsplit("/", 1)[-1].startswith("latest") - ] - - -def test_the_switched_repository_passes_the_interface_checks_and_the_reader( - hub, capsys -): - run(hub, capsys, "copy", "--write", *INCLUDE_JUNE_2023) - run(hub, capsys, "switch", "--write", *INCLUDE_JUNE_2023) - content = copied_file(hub, "releases.json") - assert content, "the switch wrote no releases.json" - - record = ReleasesRecord.parse(content) - files = hub.files_at() - - assert check_repository(record, list(files), files.__getitem__) == [] - assert parse_releases_record(content).releases[NATIONAL].current == ( - OLDER_NATIONAL_BUILD - ) - - -def test_switch_refuses_a_pointer_file_whose_build_does_not_move(hub, capsys): - run(hub, capsys, "copy", "--write") - - exit_code, _, error_output = run(hub, capsys, "switch", "--write") - - assert exit_code == 1 - assert f"latest.json names '{JUNE_2023_TAG}'" in error_output - assert "--retire-pointer latest.json" in error_output - assert "releases.json" not in hub.files_at() - - -def test_switch_can_retire_a_pointer_file_and_make_a_named_build_current(hub, capsys): - run(hub, capsys, "copy", "--write") - - exit_code, _, _ = run( - hub, - capsys, - "switch", - "--write", - "--retire-pointer", - "latest.json", - "--current", - f"{DENSE}={DENSE_BUILD}", - ) - - assert exit_code == 0 - record = json.loads(copied_file(hub, "releases.json") or b"{}") - assert sorted(record.get("releases", {})) == [DENSE, NATIONAL] - assert record.get("releases", {}).get(DENSE, {}).get("current") == DENSE_BUILD - assert record.get("default") == NATIONAL - assert "latest.json" not in hub.files_at() - - -def test_switch_refuses_until_every_build_is_in_its_folder(hub, capsys): - exit_code, _, error_output = run( - hub, capsys, "switch", "--write", "--retire-pointer", "latest.json" - ) - - assert exit_code == 1 - assert hub.made == [] - assert "run the copy step first" in error_output - - -@pytest.mark.parametrize("step", ["copy", "switch"]) -def test_each_step_refuses_a_repository_that_has_releases_json(hub, capsys, step): - hub.seed({"releases.json": b"{}"}, date=datetime(2026, 11, 6, tzinfo=UTC)) - - exit_code, _, error_output = run( - hub, capsys, step, "--write", "--retire-pointer", "latest.json" - ) - - assert exit_code == 1 - assert hub.made == [] - assert "already has releases.json" in error_output - - -@pytest.mark.parametrize("variable", ["HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE"]) -def test_the_tool_refuses_to_run_offline(capsys, monkeypatch, variable): - # The autouse fixture fails the test if the tool builds a Hub client. - monkeypatch.delenv("HF_HUB_OFFLINE", raising=False) - monkeypatch.setenv(variable, "1") - - exit_code = build_folder_switch.main(["copy", UK_REPOSITORY, "--write"]) - - assert exit_code == 1 - assert variable in capsys.readouterr().err - - -def test_copy_keeps_both_metadata_objects_of_the_june_2023_build(hub, capsys): - exit_code, _, error_output = run(hub, capsys, "copy", "--write", *INCLUDE_JUNE_2023) - - assert exit_code == 0, error_output - manifest = json.loads( - copied_file(hub, f"{JUNE_2023_FOLDER}/release_manifest.json") or b"{}" - ) - # The build object's metadata and the release's describe the same build, - # so they become one object; neither loses a field. - assert manifest.get("metadata") == { - **JUNE_2023_BUILD_METADATA, - **JUNE_2023_RELEASE_METADATA, - } - assert (manifest.get("release"), manifest.get("build")) == ( - JUNE_2023_RELEASE, - JUNE_2023_TAG, - ) - - -def test_copy_refuses_build_metadata_that_disagrees_with_the_release(hub, capsys): - tagged = hub.commits[hub.tags[JUNE_2023_TAG]] - manifest = json.loads(tagged[JUNE_2023_MANIFEST]) - manifest["build"]["metadata"]["region_datasets"] = {"another": "value"} - tagged[JUNE_2023_MANIFEST] = dumped(manifest) - - exit_code, _, error_output = run(hub, capsys, "copy", "--write", *INCLUDE_JUNE_2023) - - assert exit_code == 1 - assert hub.made == [] - assert "differ on ['metadata.region_datasets']" in error_output - - -def test_switch_refuses_a_copied_build_whose_file_changed_since(hub, capsys): - run(hub, capsys, "copy", "--write") - changed = f"{NEWER_NATIONAL_FOLDER}/microcosm_uk_2024_25.h5" - hub.seed({changed: b"another dataset"}, date=LATER) - made = list(hub.made) - - exit_code, _, error_output = run( - hub, capsys, "switch", "--write", "--retire-pointer", "latest.json" - ) - - assert exit_code == 1 - assert hub.made == made - assert f"{changed} does not match the SHA-256" in error_output - assert "releases.json" not in hub.files_at() - - -def test_switch_refuses_a_copied_build_folder_holding_another_file(hub, capsys): - run(hub, capsys, "copy", "--write") - hub.seed({f"{DENSE_FOLDER}/notes.txt": b"added by hand"}, date=LATER) - made = list(hub.made) - - exit_code, _, error_output = run( - hub, capsys, "switch", "--write", "--retire-pointer", "latest.json" - ) - - assert exit_code == 1 - assert hub.made == made - assert f"{DENSE_FOLDER}/ also holds ['notes.txt']" in error_output - - -def test_switch_takes_a_pointer_naming_an_included_build_by_its_tag(hub, capsys): - # A release-per-build pointer that names the build's tag as its revision - # names the release by its old name, the tag. - hub.seed( - { - "latest.json": dumped( - { - "schema_version": 1, - "release_id": JUNE_2023_TAG, - "revision": JUNE_2023_TAG, - } - ) - }, - date=LATER, - ) - run(hub, capsys, "copy", "--write", *INCLUDE_JUNE_2023) - - exit_code, _, error_output = run( - hub, capsys, "switch", "--write", *INCLUDE_JUNE_2023 - ) - - assert exit_code == 0, error_output - record = json.loads(copied_file(hub, "releases.json") or b"{}") - assert record.get("releases", {}).get(JUNE_2023_RELEASE, {}).get("current") == ( - JUNE_2023_TAG - ) - - -def test_an_annotated_tag_moves_from_the_commit_it_names(hub, capsys): - commit = hub.tags[DENSE_TAG] - assert hub.tag_objects[DENSE_TAG] != commit - - exit_code, report, error_output = run(hub, capsys, "copy", "--write") - - assert exit_code == 0, error_output - dense = next( - (build for build in report.get("builds", []) if build["tag"] == DENSE_TAG), {} - ) - assert (dense.get("commit"), dense.get("published_at")) == ( - commit, - "2026-11-04T13:06:25+00:00", - ) - copy_commit = next( - (made for made in hub.made if DENSE_BUILD in made["message"]), - {"operations": []}, - ) - assert { - operation[3] - for operation in copy_commit["operations"] - if operation[0] == "copy" - } == {commit} - manifest = json.loads( - copied_file(hub, f"{DENSE_FOLDER}/release_manifest.json") or b"{}" - ) - assert manifest.get("migrated_from", {}).get("commit") == commit - - -def test_copy_reports_a_release_name_the_interface_refuses_without_writing(hub, capsys): - exit_code, report, _ = run( - hub, capsys, "copy", "--include", f"{JUNE_2023_TAG}=microcosm uk 2023" - ) - - assert exit_code == 1 - assert any(JUNE_2023_TAG in problem for problem in report.get("problems", [])) - assert hub.made == [] - - -def test_copy_refuses_a_release_role_conflict_before_any_commit(hub, capsys): - # The June 2023 build is a national build; the dense release's builds are - # local-area builds, so one release cannot hold both. - exit_code, _, error_output = run( - hub, capsys, "copy", "--write", "--include", f"{JUNE_2023_TAG}={DENSE}" - ) - - assert exit_code == 1 - assert "has role" in error_output - assert hub.made == [] - - -def test_switch_refuses_a_build_folder_that_it_does_not_list(hub, capsys): - run(hub, capsys, "copy", "--write", *INCLUDE_JUNE_2023) - - # The June 2023 build was copied, but this switch neither moves it nor - # keeps the pointer file that names it. - exit_code, _, error_output = run( - hub, capsys, "switch", "--write", "--retire-pointer", "latest.json" - ) - - assert exit_code == 1 - assert f"{JUNE_2023_FOLDER}/" in error_output - assert "releases.json" not in hub.files_at() - - -def test_switch_refuses_when_a_tag_appears_while_it_reads(hub, capsys, monkeypatch): - run(hub, capsys, "copy", "--write", *INCLUDE_JUNE_2023) - list_repo_refs = hub.list_repo_refs - listings = [] - - def a_tag_lands_after_the_first_listing(*args, **kwargs): - refs = list_repo_refs(*args, **kwargs) - listings.append(refs) - if len(listings) == 1: - # A tag-only publication lands while the switch reads the builds: - # it tags a commit that is not on main, so main does not move. - hub.seed( - {}, date=LATER, tag=f"{DENSE}-20261106T120000Z-0badf00d", on_main=False - ) - return refs - - monkeypatch.setattr(hub, "list_repo_refs", a_tag_lands_after_the_first_listing) - - exit_code, _, error_output = run( - hub, capsys, "switch", "--write", *INCLUDE_JUNE_2023 - ) - - assert exit_code == 1 - assert "tags changed" in error_output - assert "releases.json" not in hub.files_at() - - -def test_switch_refuses_a_current_build_that_conflicts_with_a_pointer_file(hub, capsys): - run(hub, capsys, "copy", "--write", *INCLUDE_JUNE_2023) - - exit_code, report, _ = run( - hub, - capsys, - "switch", - *INCLUDE_JUNE_2023, - "--current", - f"{NATIONAL}={NEWER_NATIONAL_BUILD}", - ) - - assert exit_code == 1 - assert any( - "conflicts with the pointer files' current build" in problem - for problem in report.get("problems", []) - ) - - -def test_switch_can_choose_the_default_release(hub, capsys): - run(hub, capsys, "copy", "--write", *INCLUDE_JUNE_2023) - - exit_code, _, _ = run( - hub, - capsys, - "switch", - "--write", - *INCLUDE_JUNE_2023, - "--current", - f"{DENSE}={DENSE_BUILD}", - "--default", - DENSE, - ) - - assert exit_code == 0 - record = json.loads(copied_file(hub, "releases.json") or b"{}") - assert record.get("default") == DENSE - - -def test_switch_refuses_while_a_tagged_publication_is_in_progress(hub, capsys): - run(hub, capsys, "copy", "--write", *INCLUDE_JUNE_2023) - # A dense publication has made its staging branch and not yet its tag; - # a switch now would leave its build in neither the record nor a folder. - hub.branches[DENSE_STAGING_BRANCH] = hub.main - - exit_code, report, _ = run(hub, capsys, "switch", *INCLUDE_JUNE_2023) - - assert exit_code == 1 - assert any( - DENSE_STAGING_BRANCH in problem for problem in report.get("problems", []) - ) - - exit_code, _, error_output = run( - hub, capsys, "switch", "--write", *INCLUDE_JUNE_2023 - ) - - assert exit_code == 1 - assert DENSE_STAGING_BRANCH in error_output - assert "releases.json" not in hub.files_at() - - -def test_switch_refuses_when_a_tagged_publication_starts_while_it_reads( - hub, capsys, monkeypatch -): - run(hub, capsys, "copy", "--write", *INCLUDE_JUNE_2023) - list_repo_refs = hub.list_repo_refs - listings = [] - - def a_publication_starts_after_the_first_listing(*args, **kwargs): - refs = list_repo_refs(*args, **kwargs) - listings.append(refs) - if len(listings) == 1: - # The publisher checked for releases.json before the switch - # commit and makes its staging branch while the switch reads. - hub.branches[DENSE_STAGING_BRANCH] = hub.main - return refs - - monkeypatch.setattr( - hub, "list_repo_refs", a_publication_starts_after_the_first_listing - ) - - exit_code, _, error_output = run( - hub, capsys, "switch", "--write", *INCLUDE_JUNE_2023 - ) - - assert exit_code == 1 - assert DENSE_STAGING_BRANCH in error_output - assert "releases.json" not in hub.files_at() - - -@pytest.mark.parametrize("change", ["deleted", "moved", "annotated tag moved"]) -def test_switch_refuses_when_a_tag_is_deleted_or_moved_while_it_reads( - hub, capsys, monkeypatch, change -): - run(hub, capsys, "copy", "--write", *INCLUDE_JUNE_2023) - list_repo_refs = hub.list_repo_refs - listings = [] - - def a_tag_changes_before_the_second_listing(*args, **kwargs): - if len(listings) == 1: - if change == "deleted": - del hub.tags[OLDER_NATIONAL_TAG] - else: - # The dense tag is annotated; the older national one is not. - tag = ( - DENSE_TAG if change == "annotated tag moved" else OLDER_NATIONAL_TAG - ) - hub.move_tag(tag, hub.seed({}, date=LATER, on_main=False)) - refs = list_repo_refs(*args, **kwargs) - listings.append(refs) - return refs - - monkeypatch.setattr(hub, "list_repo_refs", a_tag_changes_before_the_second_listing) - - exit_code, _, error_output = run( - hub, capsys, "switch", "--write", *INCLUDE_JUNE_2023 - ) - - assert exit_code == 1 - assert "tags changed" in error_output - assert "releases.json" not in hub.files_at() - - -def test_switch_refuses_a_folder_copied_earlier_and_left_out_with_exclude(hub, capsys): - run(hub, capsys, "copy", "--write", *INCLUDE_JUNE_2023) - - exit_code, _, error_output = run( - hub, capsys, "switch", "--write", *INCLUDE_JUNE_2023, "--exclude", DENSE_TAG - ) - - assert exit_code == 1 - assert f"{DENSE_FOLDER}/ is a build folder that this switch would not list" in ( - error_output - ) - assert "releases.json" not in hub.files_at() - - -def test_copy_reports_a_release_role_conflict_without_writing(hub, capsys): - exit_code, report, _ = run( - hub, capsys, "copy", "--include", f"{JUNE_2023_TAG}={DENSE}" - ) - - assert exit_code == 1 - assert any("has role" in problem for problem in report.get("problems", [])) - assert hub.made == [] - - -@pytest.mark.parametrize( - "path", - [ - "releases/a-release/a-build/release_manifest.json", - "releases/a-release/a-build/nested/file.json", - "releases/a-release/release_manifest.json", - "releases/a-release", - "elsewhere/a-release/a-build/file.json", - "latest.json", - "releases.json", - ], -) -def test_the_tool_finds_build_folders_by_the_interfaces_rule(path): - """The switch refuses build folders it would not list by the same rule - that the interface's ``check_commit`` uses, which is private to it.""" - from microcosm_emitter_interface import releases as interface_releases - - assert build_folder_switch._build_folder_of( - path - ) == interface_releases._build_folder_of(path) - - -def test_the_switch_reads_tags_and_branches_again_in_one_request( - hub, capsys, monkeypatch -): - """Just before its commit the switch compares one listing of the tags and - branches with its first read's, and asks the Hub nothing else, so a tag - made or deleted after that listing cannot fall between its requests.""" - run(hub, capsys, "copy", "--write", *INCLUDE_JUNE_2023) - requests: list[str] = [] - list_repo_refs, repo_info = hub.list_repo_refs, hub.repo_info - - def listing(*args, **kwargs): - requests.append("list_repo_refs") - return list_repo_refs(*args, **kwargs) - - def resolution(*args, **kwargs): - requests.append("repo_info") - return repo_info(*args, **kwargs) - - monkeypatch.setattr(hub, "list_repo_refs", listing) - monkeypatch.setattr(hub, "repo_info", resolution) - - exit_code, _, error_output = run( - hub, capsys, "switch", "--write", *INCLUDE_JUNE_2023 - ) - - assert exit_code == 0, error_output - second_listing = [ - index for index, request in enumerate(requests) if request == "list_repo_refs" - ][1] - assert requests[second_listing + 1 :] == [] - - -def test_switch_ignores_branches_that_are_not_the_tagged_publishers(hub, capsys): - run(hub, capsys, "copy", "--write", *INCLUDE_JUNE_2023) - hub.branches["draft-notes"] = hub.main - hub.branches["release-staging-notes"] = hub.main - - exit_code, _, error_output = run( - hub, capsys, "switch", "--write", *INCLUDE_JUNE_2023 - ) - - assert exit_code == 0, error_output - assert "releases.json" in hub.files_at() - - -# The third step, after the switch: delete the old layout's files ---------- - -DELETE_STEP = "delete-old-layout" -#: The build folders the UK switch writes, which the step keeps. -UK_BUILD_FOLDERS = ( - f"releases/{NATIONAL}/{OLDER_NATIONAL_BUILD}", - NEWER_NATIONAL_FOLDER, - DENSE_FOLDER, - JUNE_2023_FOLDER, -) - - -def run_step( - hub: FakeDatasetRepository, capsys, step: str, *options: str -) -> tuple[int, dict, str]: - """``run``, also when the tool refuses its arguments (exit code 2).""" - try: - return run(hub, capsys, step, *options) - except SystemExit as refusal: - return int(refusal.code or 0), {}, capsys.readouterr().err - - -def switched(hub: FakeDatasetRepository, capsys) -> None: - """Copy and switch the in-memory UK repository, as its switch did.""" - run(hub, capsys, "copy", "--write", *INCLUDE_JUNE_2023) - exit_code, _, error_output = run( - hub, capsys, "switch", "--write", *INCLUDE_JUNE_2023 - ) - assert exit_code == 0, error_output - - -def old_layout_files(files) -> set[str]: - """Every file on ``main`` except ``releases.json``, ``.gitattributes`` and - the build folders' files: what the old layout left behind.""" - return { - path - for path in files - if path not in {"releases.json", ".gitattributes"} - and not any(path.startswith(f"{folder}/") for folder in UK_BUILD_FOLDERS) - } - - -def test_delete_old_layout_without_write_lists_the_old_files_and_changes_nothing( - hub, capsys -): - switched(hub, capsys) - head, commits = hub.main, len(hub.made) - - exit_code, report, error_output = run_step(hub, capsys, DELETE_STEP) - - assert exit_code == 0, error_output - expected = old_layout_files(hub.files_at()) - # The root dataset files and every file directly in a release folder, - # including the June 2023 build's own release folder. (The dense build - # was only ever under its tag, so its release folder is not on main.) - assert { - "microcosm_uk_2024_25.h5", - "microcosm_uk_2024_25_calibration.npz", - "populace_uk_2023.h5", - f"releases/{NATIONAL}/release_manifest.json", - JUNE_2023_MANIFEST, - } <= expected - assert report.get("delete") == sorted(expected) - assert report.get("problems") == [] - assert report.get("written") is False - assert (hub.main, len(hub.made)) == (head, commits) - assert "Nothing was written" in error_output - - -def test_delete_old_layout_leaves_only_build_folders_and_releases_json(hub, capsys): - switched(hub, capsys) - head = hub.main - before = dict(hub.files_at()) - - exit_code, report, error_output = run_step(hub, capsys, DELETE_STEP, "--write") - - assert exit_code == 0, error_output - assert report.get("written") is True - commit = hub.made[-1] - assert report.get("commit") == commit["commit"] == hub.main - assert commit["parent"] == head - deleted = sorted(operation[1] for operation in commit["operations"]) - assert {operation[0] for operation in commit["operations"]} == {"delete"} - assert deleted == sorted(old_layout_files(before)) - files = hub.files_at() - assert old_layout_files(files) == set() - assert {"releases.json", ".gitattributes"} <= set(files) - # Every build folder is untouched, and the record still checks out. - assert { - path: content - for path, content in before.items() - if any(path.startswith(f"{folder}/") for folder in UK_BUILD_FOLDERS) - } == { - path: content for path, content in files.items() if path.startswith("releases/") - } - record = ReleasesRecord.parse(files["releases.json"]) - assert check_repository(record, list(files), files.__getitem__) == [] - # The old builds stay at their tags. - assert "microcosm_uk_2024_25.h5" in hub.files_at(OLDER_NATIONAL_TAG) - assert JUNE_2023_MANIFEST in hub.files_at(JUNE_2023_TAG) - - -def test_delete_old_layout_keeps_files_outside_the_release_layout(hub, capsys): - switched(hub, capsys) - outside = { - "README.md": b"# populace-uk-private\n", - "notes.json": b"{}", - "staged/uk-attempt/microcosm_uk_2024_25.h5": b"staged rows", - "runs/uk-attempt/progress.json": b"{}", - } - hub.seed(outside, date=LATER) - - exit_code, report, error_output = run_step(hub, capsys, DELETE_STEP, "--write") - - assert exit_code == 0, error_output - files = hub.files_at() - for path, content in outside.items(): - assert files.get(path) == content, path - assert report.get("kept_root_files") == [ - ".gitattributes", - "README.md", - "notes.json", - "releases.json", - ] - assert report.get("kept_directories") == ["runs", "staged"] - - -def test_delete_old_layout_refuses_a_repository_that_has_not_switched(hub, capsys): - run(hub, capsys, "copy", "--write", *INCLUDE_JUNE_2023) - head, commits = hub.main, len(hub.made) - - exit_code, _, error_output = run_step(hub, capsys, DELETE_STEP, "--write") - - assert exit_code == 1 - assert "has not switched" in error_output - assert (hub.main, len(hub.made)) == (head, commits) - - -def test_delete_old_layout_refuses_while_a_pointer_file_is_there(hub, capsys): - switched(hub, capsys) - hub.seed({"latest.json": b"{}"}, date=LATER) - head, commits = hub.main, len(hub.made) - - exit_code, report, error_output = run_step(hub, capsys, DELETE_STEP, "--write") - - assert exit_code == 1, error_output - assert "latest.json is a pointer file" in error_output - assert (hub.main, len(hub.made)) == (head, commits) - # Without --write the report lists the problem too. - exit_code, report, _ = run_step(hub, capsys, DELETE_STEP) - assert exit_code == 1 - assert any("latest.json" in problem for problem in report.get("problems", [])) - - -def test_delete_old_layout_refuses_a_build_folder_the_record_does_not_list(hub, capsys): - """A folder that holds a release manifest is a build's folder; the step - deletes no build, so one the record does not list stops it.""" - switched(hub, capsys) - unlisted = ( - f"releases/{NATIONAL}/uk-frs-calibration-attempt-20261111T000000Z-0badcafe" - ) - hub.seed({f"{unlisted}/release_manifest.json": b"{}"}, date=LATER) - head, commits = hub.main, len(hub.made) - - exit_code, report, error_output = run_step(hub, capsys, DELETE_STEP, "--write") - - assert exit_code == 1, error_output - assert f"{unlisted}/ is a build folder" in error_output - assert (hub.main, len(hub.made)) == (head, commits) - exit_code, report, _ = run_step(hub, capsys, DELETE_STEP) - assert exit_code == 1 - assert any(unlisted in problem for problem in report.get("problems", [])) - # Its files are not in the deletion list. - assert not any(path.startswith(f"{unlisted}/") for path in report["delete"]) - - -def test_delete_old_layout_again_finds_nothing_to_delete(hub, capsys): - switched(hub, capsys) - first, _, error_output = run_step(hub, capsys, DELETE_STEP, "--write") - assert first == 0, error_output - head, commits = hub.main, len(hub.made) - - exit_code, report, error_output = run_step(hub, capsys, DELETE_STEP, "--write") - - assert exit_code == 0, error_output - assert report.get("delete") == [] - assert report.get("written") is False - assert (hub.main, len(hub.made)) == (head, commits) - - -def test_delete_old_layout_takes_none_of_the_switch_options(hub, capsys): - switched(hub, capsys) - head = hub.main - - exit_code, _, error_output = run_step( - hub, capsys, DELETE_STEP, "--write", *INCLUDE_JUNE_2023 - ) - - assert exit_code == 1 - assert "--include" in error_output - assert hub.main == head - - -def test_delete_old_layout_reports_a_deleted_folder_no_tag_names(hub, capsys): - """A release-per-build folder whose name is no tag stays readable only by - the commit the report names, so the report lists it.""" - switched(hub, capsys) - untagged = "releases/populace-uk-2023-0000000-20260101" - hub.seed({f"{untagged}/release_manifest.json": b"{}"}, date=LATER) - - exit_code, report, error_output = run_step(hub, capsys, DELETE_STEP) - - assert exit_code == 0, error_output - assert f"{untagged}/release_manifest.json" in report["delete"] - # The June 2023 build's own folder is named by its tag, and the national - # release's folder held copies of tagged builds. - assert report.get("untagged_folders") == [untagged] - - -def test_delete_old_layout_reports_a_local_area_folder_the_registry_does_not_name( - hub, capsys, monkeypatch -): - """A folder named by a UK local-area release held copies of tagged builds - only if the registry names the release. Until it does, no build of that - name has published, so the report lists a folder no tag names.""" - switched(hub, capsys) - release = "microcosm-uk-2024-25-local-k55000" - folder = f"releases/{release}" - hub.seed({f"{folder}/release_manifest.json": b"{}"}, date=LATER) - - exit_code, report, error_output = run_step(hub, capsys, DELETE_STEP) - - assert exit_code == 0, error_output - assert f"{folder}/release_manifest.json" in report["delete"] - assert folder in report["untagged_folders"] - - register_uk_local_release(monkeypatch, release) - exit_code, report, error_output = run_step(hub, capsys, DELETE_STEP) - - assert exit_code == 0, error_output - assert f"{folder}/release_manifest.json" in report["delete"] - assert folder not in report["untagged_folders"] - - -def test_delete_old_layout_refuses_an_invalid_releases_json(hub, capsys): - switched(hub, capsys) - hub.seed({"releases.json": b"{"}, date=LATER) - head = hub.main - - exit_code, _, error_output = run_step(hub, capsys, DELETE_STEP, "--write") - - assert exit_code == 1 - assert "is not a valid record" in error_output - assert hub.main == head - - -def test_delete_old_layout_refuses_a_commit_on_a_moved_head(hub, capsys, monkeypatch): - """The commit names the head the step read; another commit landing first - makes the Hub refuse it, and nothing is deleted.""" - switched(hub, capsys) - real_create_commit = hub.create_commit - - def another_commit_first(*args, **options): - hub.seed({"README.md": b"# a commit that landed first\n"}, date=LATER) - return real_create_commit(*args, **options) - - monkeypatch.setattr(hub, "create_commit", another_commit_first) - - exit_code, _, error_output = run_step(hub, capsys, DELETE_STEP, "--write") - - assert exit_code == 1 - assert "the deletion commit failed" in error_output - assert "microcosm_uk_2024_25.h5" in hub.files_at() - - -def test_delete_old_layout_matches_root_dataset_suffixes_in_any_case(hub, capsys): - switched(hub, capsys) - hub.seed( - { - "OLD_DATASET.H5": b"rows", - "older.hdf5": b"rows", - "releases/stray.json": b"{}", - "notes.txt": b"kept", - }, - date=LATER, - ) - - exit_code, report, error_output = run_step(hub, capsys, DELETE_STEP) - - assert exit_code == 0, error_output - assert {"OLD_DATASET.H5", "older.hdf5", "releases/stray.json"} <= set( - report["delete"] - ) - assert "notes.txt" in report["kept_root_files"] - - -def test_the_offline_refusal_names_the_step(hub, capsys, monkeypatch): - """Offline, every step refuses before it builds a Hub client.""" - exit_code = build_folder_switch.main([DELETE_STEP, UK_REPOSITORY]) - - error_output = capsys.readouterr().err - assert exit_code == 1 - assert f"refusing to {DELETE_STEP}" in error_output diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_build_folder_switch.py b/packages/microcosm-build/tests/engine_free/us/test_us_build_folder_switch.py deleted file mode 100644 index e4f64169b8..0000000000 --- a/packages/microcosm-build/tests/engine_free/us/test_us_build_folder_switch.py +++ /dev/null @@ -1,445 +0,0 @@ -"""The build-folder switch on the US repository's tagged layout. - -Every US build is its own release in ``releases//``, so each build moves -with ``--include TAG=RELEASE``. The US builds have two shapes the UK builds -did not: an ACS local-area build keeps files that its checksum ledger records -but its release manifest doesn't declare, and an SPM build declares its own -``build_manifest.json`` as an artifact. A July publication also left its -staging branch behind after it finished. These tests run the tool against the -in-memory repository in ``test_support.microcosm_build.build_folder_switch``; -none reaches the Hub. -""" - -from __future__ import annotations - -import json -from datetime import UTC, datetime - -import pytest - -from microcosm.build import build_folder_switch -from test_support.microcosm_build.build_folder_switch import ( - ACS_TAG, - ACS_UNDECLARED_FILES, - FINISHED_STAGING_BRANCH, - FINISHED_TAG, - SPM_TAG, - US_LOCAL, - US_NATIONAL, - US_REPOSITORY, - FakeDatasetRepository, - sha256, - us_repository, -) - -INCLUDES = ( - "--include", - f"{SPM_TAG}={US_NATIONAL}", - "--include", - f"{ACS_TAG}={US_LOCAL}", -) -#: No pointer file names a current ACS build, so the switch is told which. -SWITCH_OPTIONS = (*INCLUDES, "--current", f"{US_LOCAL}={ACS_TAG}") -FINISHED = ("--finished-branch", FINISHED_STAGING_BRANCH) -#: When a test changes the repository after the copy step. -LATER = datetime(2026, 11, 10, 12, 0, tzinfo=UTC) -SPM_FOLDER = f"releases/{US_NATIONAL}/{SPM_TAG}" -ACS_FOLDER = f"releases/{US_LOCAL}/{ACS_TAG}" - - -@pytest.fixture(autouse=True) -def no_hub_access(monkeypatch): - """Every test runs offline and against the in-memory repository only.""" - monkeypatch.setenv("HF_HUB_OFFLINE", "1") - - def no_hub_client(): - pytest.fail("the tool built a Hub client") - - monkeypatch.setattr(build_folder_switch, "_default_api", no_hub_client) - - -@pytest.fixture -def hub(tmp_path) -> FakeDatasetRepository: - return us_repository(tmp_path / "hub-cache") - - -def run( - hub: FakeDatasetRepository, capsys, step: str, *options: str -) -> tuple[int, dict, str]: - """Run one step on the in-memory repository: exit code, report and stderr.""" - exit_code = build_folder_switch.main([step, US_REPOSITORY, *options], api=hub) - captured = capsys.readouterr() - report = json.loads(captured.out) if captured.out.strip() else {} - return exit_code, report, captured.err - - -def ledger_digests(ledger: bytes) -> dict[str, str]: - """Each file a checksum ledger records, with its SHA-256.""" - digests = {} - for entry in ledger.decode().splitlines(): - if entry.strip(): - digest, name = entry.split() - digests[name] = digest - return digests - - -def build_status(report: dict, tag: str) -> str | None: - return next( - (build["status"] for build in report.get("builds", []) if build["tag"] == tag), - None, - ) - - -def test_copy_moves_the_files_an_acs_build_s_checksum_ledger_records(hub, capsys): - exit_code, report, error_output = run(hub, capsys, "copy", "--write", *INCLUDES) - - assert exit_code == 0, error_output - files = hub.files_at() - for name, content in ACS_UNDECLARED_FILES.items(): - assert files.get(f"{ACS_FOLDER}/{name}") == content - recorded = ledger_digests(files.get(f"{ACS_FOLDER}/sha256sums.txt", b"")) - for name, content in ACS_UNDECLARED_FILES.items(): - assert recorded.get(name) == sha256(content) - assert recorded.get("release_manifest.json") == sha256( - files.get(f"{ACS_FOLDER}/release_manifest.json", b"") - ) - # They stay undeclared: the rewritten manifest declares what the tagged - # one declared, and nothing of the build's folder is left behind. - manifest = json.loads(files.get(f"{ACS_FOLDER}/release_manifest.json", b"{}")) - assert {entry["path"] for entry in manifest.get("artifacts", {}).values()} == { - "populace_us_2024_acs_local.h5", - "calibration_diagnostics.json", - } - acs = next( - (build for build in report.get("builds", []) if build["tag"] == ACS_TAG), {} - ) - assert acs.get("left_behind") == [] - - -def test_a_copied_acs_build_counts_as_copied(hub, capsys): - run(hub, capsys, "copy", "--write", *INCLUDES) - - exit_code, report, error_output = run(hub, capsys, "copy", *INCLUDES) - - assert exit_code == 0, error_output - assert build_status(report, ACS_TAG) == "already_copied" - - -def test_copy_refuses_an_undeclared_file_that_does_not_match_its_ledger(hub, capsys): - # The ledger records each file in name order; this is the last of them. - tagged_files = hub.commits[hub.tags[ACS_TAG]] - tagged_files[f"releases/{ACS_TAG}/run_identity.json"] = b"changed after" - - exit_code, report, _ = run(hub, capsys, "copy", *INCLUDES) - - assert exit_code == 1 - problems = [problem for problem in report.get("problems", []) if ACS_TAG in problem] - assert len(problems) == 1 - assert "run_identity.json" in problems[0] - - -def test_copy_moves_an_spm_build_whose_manifest_declares_its_build_manifest( - hub, capsys -): - exit_code, _, error_output = run(hub, capsys, "copy", "--write", *INCLUDES) - - assert exit_code == 0, error_output - files = hub.files_at() - build_manifest = files.get(f"{SPM_FOLDER}/build_manifest.json", b"") - assert json.loads(build_manifest or b"{}").get("build") == SPM_TAG - manifest = json.loads(files.get(f"{SPM_FOLDER}/release_manifest.json", b"{}")) - declared = manifest.get("artifacts", {}).get("build_manifest", {}) - # The manifest declares the rewritten build manifest, by its new SHA-256. - assert (declared.get("path"), declared.get("sha256")) == ( - "build_manifest.json", - sha256(build_manifest), - ) - parent = f"releases/{SPM_TAG}/parent_build_manifest.json" - assert ( - files.get(f"{SPM_FOLDER}/parent_build_manifest.json") - == hub.files_at(SPM_TAG)[parent] - ) - - -def test_a_copied_spm_build_counts_as_copied(hub, capsys): - run(hub, capsys, "copy", "--write", *INCLUDES) - - exit_code, report, error_output = run(hub, capsys, "copy", *INCLUDES) - - assert exit_code == 0, error_output - assert build_status(report, SPM_TAG) == "already_copied" - - -def test_switch_accepts_a_named_finished_staging_branch(hub, capsys): - run(hub, capsys, "copy", "--write", *INCLUDES) - - exit_code, report, error_output = run( - hub, capsys, "switch", "--write", *SWITCH_OPTIONS, *FINISHED - ) - - assert exit_code == 0, error_output - assert report.get("finished_branches") == [FINISHED_STAGING_BRANCH] - record = json.loads(hub.files_at().get("releases.json", b"{}")) - assert record.get("default") == US_NATIONAL - assert { - release: entry.get("current") - for release, entry in record.get("releases", {}).items() - } == {US_NATIONAL: SPM_TAG, US_LOCAL: ACS_TAG} - assert "latest.json" not in hub.files_at() - # The leftover build stays reachable by its tag, and its branch stays. - assert FINISHED_TAG in report.get("not_moved", []) - assert FINISHED_STAGING_BRANCH in hub.branches - - -def test_switch_still_refuses_a_staging_branch_it_was_not_told_about(hub, capsys): - run(hub, capsys, "copy", "--write", *INCLUDES) - - exit_code, report, _ = run(hub, capsys, "switch", *SWITCH_OPTIONS) - - assert exit_code == 1 - assert any( - FINISHED_STAGING_BRANCH in problem and "--finished-branch" in problem - for problem in report.get("problems", []) - ) - - -def test_switch_refuses_a_named_branch_whose_build_has_no_tag(hub, capsys): - run(hub, capsys, "copy", "--write", *INCLUDES) - del hub.tags[FINISHED_TAG] - - exit_code, report, _ = run(hub, capsys, "switch", *SWITCH_OPTIONS, *FINISHED) - - assert exit_code == 1 - assert any( - FINISHED_STAGING_BRANCH in problem and "no tag" in problem - for problem in report.get("problems", []) - ) - - -def test_switch_refuses_a_named_branch_whose_head_is_not_on_main(hub, capsys): - run(hub, capsys, "copy", "--write", *INCLUDES) - # As a running publication's branch is between its tag and the branch's - # deletion: it names the tagged commit, which is not on main. - hub.branches[FINISHED_STAGING_BRANCH] = hub.tags[FINISHED_TAG] - - exit_code, report, error_output = run( - hub, capsys, "switch", "--write", *SWITCH_OPTIONS, *FINISHED - ) - - assert exit_code == 1 - assert "not on main" in error_output - assert "releases.json" not in hub.files_at() - - -def test_switch_refuses_a_named_branch_that_does_not_exist(hub, capsys): - run(hub, capsys, "copy", "--write", *INCLUDES) - del hub.branches[FINISHED_STAGING_BRANCH] - - exit_code, report, _ = run(hub, capsys, "switch", *SWITCH_OPTIONS, *FINISHED) - - assert exit_code == 1 - assert any( - FINISHED_STAGING_BRANCH in problem - and "not a release-staging/ branch" in problem - for problem in report.get("problems", []) - ) - - -def watch_listings(hub, monkeypatch, after_first_listing): - """Run ``after_first_listing`` once, right after the switch's first - listing of the repository's tags and branches.""" - list_repo_refs = hub.list_repo_refs - listings = [] - - def listing(*args, **kwargs): - refs = list_repo_refs(*args, **kwargs) - listings.append(refs) - if len(listings) == 1: - after_first_listing() - return refs - - monkeypatch.setattr(hub, "list_repo_refs", listing) - - -def test_switch_refuses_when_a_named_finished_branch_moves_while_it_reads( - hub, capsys, monkeypatch -): - run(hub, capsys, "copy", "--write", *INCLUDES) - - def a_publication_uses_the_branch(): - hub.branches[FINISHED_STAGING_BRANCH] = hub.tags[FINISHED_TAG] - - watch_listings(hub, monkeypatch, a_publication_uses_the_branch) - - exit_code, _, error_output = run( - hub, capsys, "switch", "--write", *SWITCH_OPTIONS, *FINISHED - ) - - assert exit_code == 1 - assert FINISHED_STAGING_BRANCH in error_output - # The operator already named it, so the refusal says it moved instead of - # asking for --finished-branch again. - assert "moved" in error_output - assert "name the branch with --finished-branch" not in error_output - assert "releases.json" not in hub.files_at() - - -def test_switch_refuses_when_a_named_finished_branch_disappears_while_it_reads( - hub, capsys, monkeypatch -): - run(hub, capsys, "copy", "--write", *INCLUDES) - # A retry of the build can make its branch only once the leftover one is - # gone, so a branch that disappears is a reason to read again. - watch_listings(hub, monkeypatch, lambda: hub.branches.pop(FINISHED_STAGING_BRANCH)) - - exit_code, _, error_output = run( - hub, capsys, "switch", "--write", *SWITCH_OPTIONS, *FINISHED - ) - - assert exit_code == 1 - assert FINISHED_STAGING_BRANCH in error_output - assert "was deleted" in error_output - # A run again must leave the option out, or the branch is refused as one - # that doesn't exist. - assert f"without --finished-branch {FINISHED_STAGING_BRANCH}" in error_output - assert "releases.json" not in hub.files_at() - - -def test_switch_refuses_a_new_staging_branch_beside_an_accepted_one( - hub, capsys, monkeypatch -): - run(hub, capsys, "copy", "--write", *INCLUDES) - other = "release-staging/populace-us-2024-spm-20261110" - - def a_publication_starts(): - hub.branches[other] = hub.main - - watch_listings(hub, monkeypatch, a_publication_starts) - - exit_code, _, error_output = run( - hub, capsys, "switch", "--write", *SWITCH_OPTIONS, *FINISHED - ) - - assert exit_code == 1 - assert f"branch {other} appeared" in error_output - # It appeared during the switch, so it is no finished publication's. - assert f"--finished-branch {other}" not in error_output - assert "releases.json" not in hub.files_at() - - -def test_copy_refuses_a_ledger_entry_for_a_file_the_tagged_folder_lacks(hub, capsys): - del hub.commits[hub.tags[ACS_TAG]][f"releases/{ACS_TAG}/run_identity.json"] - - exit_code, report, _ = run(hub, capsys, "copy", *INCLUDES) - - assert exit_code == 1 - assert any( - ACS_TAG in problem - and "run_identity.json" in problem - and "does not hold" in problem - for problem in report.get("problems", []) - ) - - -def test_copy_refuses_a_ledger_that_records_a_file_twice(hub, capsys): - tagged_files = hub.commits[hub.tags[ACS_TAG]] - ledger_path = f"releases/{ACS_TAG}/sha256sums.txt" - tagged_files[ledger_path] += ( - f"{sha256(b'other bytes')} consumer_export.json\n".encode() - ) - - exit_code, report, _ = run(hub, capsys, "copy", *INCLUDES) - - assert exit_code == 1 - assert any( - ACS_TAG in problem and "consumer_export.json twice" in problem - for problem in report.get("problems", []) - ) - - -def test_copy_refuses_a_declared_build_manifest_that_does_not_match(hub, capsys): - tagged_files = hub.commits[hub.tags[SPM_TAG]] - tagged_files[f"releases/{SPM_TAG}/build_manifest.json"] = b'{"changed": true}' - - exit_code, report, _ = run(hub, capsys, "copy", *INCLUDES) - - assert exit_code == 1 - assert any( - SPM_TAG in problem and "build_manifest.json" in problem - for problem in report.get("problems", []) - ) - - -def test_the_copy_plan_lists_each_build_s_undeclared_files(hub, capsys): - exit_code, report, error_output = run(hub, capsys, "copy", *INCLUDES) - - assert exit_code == 0, error_output - assert { - build["tag"]: build.get("undeclared") for build in report.get("builds", []) - } == {SPM_TAG: [], ACS_TAG: sorted(ACS_UNDECLARED_FILES)} - - -def test_an_undeclared_file_changed_after_the_copy_makes_its_folder_occupied( - hub, capsys -): - run(hub, capsys, "copy", "--write", *INCLUDES) - hub.seed({f"{ACS_FOLDER}/run_identity.json": b"changed on main"}, date=LATER) - - exit_code, report, _ = run(hub, capsys, "copy", *INCLUDES) - - assert exit_code == 1 - assert build_status(report, ACS_TAG) == "occupied" - assert any( - "run_identity.json" in problem and "sha256sums.txt records" in problem - for problem in report.get("problems", []) - ) - - -def test_a_declared_build_manifest_changed_after_the_copy_makes_its_folder_occupied( - hub, capsys -): - run(hub, capsys, "copy", "--write", *INCLUDES) - hub.seed({f"{SPM_FOLDER}/build_manifest.json": b'{"changed": true}'}, date=LATER) - - exit_code, report, _ = run(hub, capsys, "copy", *INCLUDES) - - assert exit_code == 1 - assert build_status(report, SPM_TAG) == "occupied" - assert any( - "build_manifest.json" in problem and "its manifest records" in problem - for problem in report.get("problems", []) - ) - - -def test_delete_old_layout_removes_every_tag_s_release_folder_and_root_file( - hub, capsys -): - """Every US build had its own release folder, ``releases//``; after - the switch those folders, the leftover build's included, and the root - dataset files are the old layout, and build folders stay.""" - run(hub, capsys, "copy", "--write", *INCLUDES) - switch_code, _, switch_error = run( - hub, capsys, "switch", "--write", *SWITCH_OPTIONS, *FINISHED - ) - assert switch_code == 0, switch_error - before = dict(hub.files_at()) - try: - exit_code, report, error_output = run( - hub, capsys, "delete-old-layout", "--write" - ) - except SystemExit as refusal: - exit_code, report, error_output = int(refusal.code or 0), {}, "" - - assert exit_code == 0, error_output - files = hub.files_at() - kept_folders = (SPM_FOLDER, ACS_FOLDER) - assert set(files) == {"releases.json", ".gitattributes"} | { - path - for path in before - if any(path.startswith(f"{folder}/") for folder in kept_folders) - } - assert any(path.startswith(f"releases/{SPM_TAG}/") for path in report["delete"]) - assert any( - path.startswith(f"releases/{FINISHED_TAG}/") for path in report["delete"] - ) - assert "populace_us_2024.h5" in report["delete"] diff --git a/packages/microcosm-data/README.md b/packages/microcosm-data/README.md index 0fec5e803c..40a59c8b14 100644 --- a/packages/microcosm-data/README.md +++ b/packages/microcosm-data/README.md @@ -51,7 +51,7 @@ checks. The loader refuses it for an entry whose repository records its builds in `releases.json`, which every registered entry's repository does since the UK and US switches. Builds published into folders write no root file, so the US repository's root `populace_us_2024.h5` stopped changing at its switch, -and the switch tool's `delete-old-layout` step deletes it. +and the switch tool's `delete-old-layout` step later deleted it. ## Why a shard, not a repo per country diff --git a/packages/microcosm-data/src/microcosm/data/registry.py b/packages/microcosm-data/src/microcosm/data/registry.py index bd043fc601..50c152c3ea 100644 --- a/packages/microcosm-data/src/microcosm/data/registry.py +++ b/packages/microcosm-data/src/microcosm/data/registry.py @@ -40,7 +40,7 @@ class DatasetSpec: ``"populace_us_2024.h5"``: the name a tagged build's manifest declares, and the file the repository's root held in the tagged layout, which the switch tool's ``delete-old-layout`` step - deletes. + deleted. build_folder_filename: The dataset file name new builds of ``release`` declare, when it differs from ``filename``: the US national release's builds declare ``microcosm_us_2024.h5``, diff --git a/packages/microcosm-data/tests/engine_free/shared/test_examples_read_build_folders.py b/packages/microcosm-data/tests/engine_free/shared/test_examples_read_build_folders.py index 8b0dbe1d15..78070015ac 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_examples_read_build_folders.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_examples_read_build_folders.py @@ -1,8 +1,8 @@ """The example notebooks read published datasets the way the loader does. -The switch tool's ``delete-old-layout`` step deletes the dataset files at a -dataset repository's root, so an example that downloads one from ``main`` -stops working once it has run. Every ``hf_hub_download`` call in an example +The switch tool's ``delete-old-layout`` step deleted the dataset files at +each dataset repository's root, so an example that downloads one from +``main`` no longer works. Every ``hf_hub_download`` call in an example names ``releases.json`` or a file inside ``releases/``. """ diff --git a/test_support/microcosm_build/build_folder_switch.py b/test_support/microcosm_build/build_folder_switch.py deleted file mode 100644 index df8731bcbb..0000000000 --- a/test_support/microcosm_build/build_folder_switch.py +++ /dev/null @@ -1,859 +0,0 @@ -"""An in-memory dataset repository for the build-folder switch tool's tests. - -``FakeDatasetRepository`` answers the ``HfApi`` calls -``microcosm.build.build_folder_switch`` makes, so its tests never reach the -Hub. Every commit keeps the exact bytes of every file; ``*.h5`` and ``*.npz`` -files count as LFS files, whose SHA-256 the file information carries, as the -Hub's does. ``create_commit`` applies the real ``huggingface_hub`` operations -(adding bytes, copying a file from another commit, deleting a file) and -refuses a ``parent_commit`` that is no longer ``main``'s head. An annotated -tag is listed, as the Hub lists one, with the ID of its tag object rather -than its commit; a revision names either. - -``uk_repository`` builds a small repository in the tagged layout the UK -private repository has before its switch: a June 2023 release-per-build -release that ``latest.json`` names, whose release manifest has a -``metadata`` object both at its top level and in its ``build`` object, two -tagged national builds of which ``latest-national.json`` names the older, -and a tag-only dense build with a checksum ledger, whose tag is annotated. - -``us_repository`` builds one in the tagged layout ``policyengine/populace-us`` -has before its switch: every build is a release-per-build release in -``releases//``. ``latest.json`` names an SPM build whose release -manifest declares its own ``build_manifest.json`` as an artifact; a tag-only -ACS local-area build has files its checksum ledger records but its release -manifest doesn't declare; and an older national build has a leftover -``release-staging/`` branch, pointing at a commit on ``main``, from a retry -of its publication that stopped because its tag already existed. - -``untagged_repository`` builds one with no tags at all, laid out as BE's -private release repository is: each build is an untagged folder -``releases//`` on ``main`` holding only its two manifests and its -calibration diagnostics, and ``latest.json`` names a folder by its name, -with no revision. Each release manifest declares files of the builder's own -output directory that the folder doesn't hold, one with builder-local -paths and the other with no paths at all. Its names are neutral fixture -names. -""" - -from __future__ import annotations - -import hashlib -import json -from dataclasses import dataclass, field -from datetime import UTC, datetime -from pathlib import Path -from types import SimpleNamespace -from typing import Any - -from huggingface_hub import ( - CommitOperationAdd, - CommitOperationCopy, - CommitOperationDelete, -) - -UK_REPOSITORY = "policyengine/populace-uk-private" -NATIONAL = "microcosm-uk-2024-25-national" -DENSE = "microcosm-uk-2024-25-dense" -JUNE_2023_TAG = "populace-uk-2023-dd68c73-4aa4b14-20260619T023711Z" -OLDER_NATIONAL_BUILD = "uk-frs-calibration-attempt-20261019T083323Z-6cba5d71" -NEWER_NATIONAL_BUILD = "uk-frs-calibration-attempt-20261105T133052Z-51f60255" -DENSE_BUILD = "uk-local-candidate-f100-s42-20261104T093024Z-83802786" -OLDER_NATIONAL_TAG = f"{NATIONAL}-20261019T083323Z-6cba5d71" -NEWER_NATIONAL_TAG = f"{NATIONAL}-20261105T133052Z-51f60255" -DENSE_TAG = f"{DENSE}-20261104T093024Z-83802786" -US_REPOSITORY = "policyengine/populace-us" -US_NATIONAL = "microcosm-us-2024-national" -US_LOCAL = "microcosm-us-2024-local" -SPM_TAG = "populace-us-2024-spm-20260915" -ACS_TAG = "populace-us-2024-buildo-acs-local-766b7c7-20261017T030317Z" -#: A national build tagged and committed to ``main`` in July. A later retry, -#: by the publisher of that time, made its staging branch from ``main``, found -#: nothing to commit, and stopped when tagging failed, leaving the branch. -FINISHED_TAG = "populace-us-2024-buildm-sparse-rmloss100-98bf731-20260717T075101Z" -FINISHED_STAGING_BRANCH = f"release-staging/{FINISHED_TAG}" -#: The ACS build's files that its checksum ledger records and its release -#: manifest doesn't declare, as each ACS local-area build has them. -ACS_UNDECLARED_FILES = { - "consumer_export.json": b'{"columns": ["household_id"]}', - "run_identity.json": b'{"run": "766b7c7"}', -} -US_PUBLISHED_AT = { - FINISHED_TAG: datetime(2026, 7, 17, 10, 24, 13, tzinfo=UTC), - SPM_TAG: datetime(2026, 9, 15, 7, 6, 23, tzinfo=UTC), - ACS_TAG: datetime(2026, 10, 18, 18, 35, 46, tzinfo=UTC), -} -#: When each tagged commit was made: its build's ``published_at``. -PUBLISHED_AT = { - JUNE_2023_TAG: datetime(2026, 6, 19, 2, 38, 38, tzinfo=UTC), - OLDER_NATIONAL_TAG: datetime(2026, 10, 19, 10, 21, 4, 512000, tzinfo=UTC), - DENSE_TAG: datetime(2026, 11, 4, 13, 6, 25, tzinfo=UTC), - NEWER_NATIONAL_TAG: datetime(2026, 11, 5, 23, 30, 42, tzinfo=UTC), -} -#: The June 2023 release manifest's two ``metadata`` objects, which differ: -#: the release's at its top level, and the build's in its ``build`` object. -JUNE_2023_RELEASE_METADATA: dict[str, Any] = { - "region_datasets": {"populace_uk_2023": "national"} -} -JUNE_2023_BUILD_METADATA: dict[str, Any] = { - "builder": "populace", - "populace_commit": "4aa4b14cdd8bb693df594d822256a843dd8a8645", - "private": "UK Data Service licence: private dataset repo.", -} -_LFS_SUFFIXES = (".h5", ".npz") - - -def sha256(content: bytes) -> str: - """The SHA-256 of ``content``, as manifests record it.""" - return hashlib.sha256(content).hexdigest() - - -def dumped(document: Any) -> bytes: - """A JSON document's bytes as the tagged publisher wrote them.""" - return json.dumps(document, indent=1).encode() - - -@dataclass -class FakeDatasetRepository: - """One dataset repository's commits, tags and ``main`` branch, in memory.""" - - repository: str - download_dir: Path - commits: dict[str, dict[str, bytes]] = field(default_factory=dict) - dates: dict[str, datetime] = field(default_factory=dict) - parents: dict[str, str | None] = field(default_factory=dict) - tags: dict[str, str] = field(default_factory=dict) - #: The tag object of each annotated tag, by tag name. - tag_objects: dict[str, str] = field(default_factory=dict) - #: Every branch other than ``main``, such as the tagged publisher's - #: ``release-staging/``, and the commit it names. - branches: dict[str, str] = field(default_factory=dict) - main: str = "" - #: Every commit the tool made, with its operations, in order. - made: list[dict[str, Any]] = field(default_factory=list) - - def __post_init__(self) -> None: - self.main = self._new_commit( - {}, parent=None, date=datetime(2026, 6, 1, tzinfo=UTC) - ) - - def _new_commit( - self, files: dict[str, bytes], *, parent: str | None, date: datetime - ) -> str: - commit = f"{len(self.commits):040x}" - self.commits[commit] = files - self.parents[commit] = parent - self.dates[commit] = date - return commit - - def seed( - self, - files: dict[str, bytes], - *, - date: datetime, - tag: str | None = None, - on_main: bool = True, - ) -> str: - """Add a commit on top of ``main``: on ``main``, or only under a tag.""" - commit = self._new_commit( - {**self.commits[self.main], **files}, parent=self.main, date=date - ) - if on_main: - self.main = commit - if tag is not None: - self.tags[tag] = commit - return commit - - def annotate(self, tag: str) -> str: - """Make ``tag`` an annotated tag: the Hub lists its tag object's ID, - which, like git's, depends on the commit it names.""" - tag_object = sha256(f"tag object {tag} {self.tags[tag]}".encode())[:40] - self.tag_objects[tag] = tag_object - return tag_object - - def move_tag(self, tag: str, commit: str) -> None: - """Point ``tag`` at another commit, as deleting and creating it again - does; an annotated tag gets a new tag object.""" - self.tags[tag] = commit - if tag in self.tag_objects: - self.annotate(tag) - - def files_at(self, revision: str | None = None) -> dict[str, bytes]: - """Every file at a revision (``main`` by default), by path.""" - return self.commits[self._commit(revision)] - - def _commit(self, revision: str | None) -> str: - if revision in (None, "main"): - return self.main - if revision in self.tags: - return self.tags[revision] - if revision in self.commits: - return revision - for tag, tag_object in self.tag_objects.items(): - if revision == tag_object: - return self.tags[tag] - raise FileNotFoundError(f"no revision {revision}") - - def _check(self, repo_id: str, repo_type: str | None) -> None: - assert repo_id == self.repository - assert repo_type == "dataset" - - # The HfApi calls the switch tool makes --------------------------------- - - def repo_info( - self, repo_id: str, *, repo_type: str | None = None, revision: str | None = None - ) -> Any: - self._check(repo_id, repo_type) - return SimpleNamespace(sha=self._commit(revision)) - - def list_repo_refs(self, repo_id: str, *, repo_type: str | None = None) -> Any: - self._check(repo_id, repo_type) - return SimpleNamespace( - branches=[ - SimpleNamespace(name=name, target_commit=commit) - for name, commit in {"main": self.main, **self.branches}.items() - ], - tags=[ - SimpleNamespace( - name=name, target_commit=self.tag_objects.get(name, commit) - ) - for name, commit in self.tags.items() - ], - ) - - def list_repo_files( - self, repo_id: str, *, repo_type: str | None = None, revision: str | None = None - ) -> list[str]: - self._check(repo_id, repo_type) - return sorted(self.files_at(revision)) - - def hf_hub_download( - self, - repo_id: str, - filename: str, - *, - repo_type: str | None = None, - revision: str | None = None, - ) -> str: - self._check(repo_id, repo_type) - commit = self._commit(revision) - content = self.commits[commit][filename] - local = self.download_dir / commit / filename - local.parent.mkdir(parents=True, exist_ok=True) - local.write_bytes(content) - return str(local) - - def get_paths_info( - self, - repo_id: str, - paths: list[str], - *, - repo_type: str | None = None, - revision: str | None = None, - expand: bool = False, - ) -> list[Any]: - """Each path's information; with ``expand``, also the last commit - that changed it, as the Hub's ``last_commit``.""" - self._check(repo_id, repo_type) - commit = self._commit(revision) - files = self.commits[commit] - return [ - SimpleNamespace( - path=path, - lfs=SimpleNamespace(sha256=sha256(files[path])) - if path.endswith(_LFS_SUFFIXES) - else None, - last_commit=self._last_change(path, commit) if expand else None, - ) - for path in paths - if path in files - ] - - def _last_change(self, path: str, commit: str) -> Any: - """The newest commit up to ``commit`` that added or changed ``path``.""" - content = self.commits[commit][path] - parent = self.parents[commit] - while parent is not None and self.commits[parent].get(path) == content: - commit, parent = parent, self.parents[parent] - return SimpleNamespace(oid=commit, date=self.dates[commit], title="") - - def list_repo_commits( - self, repo_id: str, *, repo_type: str | None = None, revision: str | None = None - ) -> list[Any]: - self._check(repo_id, repo_type) - history = [] - commit: str | None = self._commit(revision) - while commit is not None: - history.append( - SimpleNamespace(commit_id=commit, created_at=self.dates[commit]) - ) - commit = self.parents[commit] - return history - - def create_commit( - self, - repo_id: str, - operations: list[Any], - *, - commit_message: str, - repo_type: str | None = None, - parent_commit: str | None = None, - ) -> Any: - self._check(repo_id, repo_type) - if parent_commit != self.main: - raise RuntimeError( - f"412: parent commit {parent_commit} is not main's head {self.main}" - ) - files = dict(self.commits[self.main]) - recorded = [] - for operation in operations: - if isinstance(operation, CommitOperationAdd): - content = operation.path_or_fileobj - assert isinstance(content, bytes) - files[operation.path_in_repo] = content - recorded.append(("add", operation.path_in_repo, None, None)) - elif isinstance(operation, CommitOperationCopy): - source = self.commits[self._commit(operation.src_revision)] - files[operation.path_in_repo] = source[operation.src_path_in_repo] - recorded.append( - ( - "copy", - operation.path_in_repo, - operation.src_path_in_repo, - operation.src_revision, - ) - ) - elif isinstance(operation, CommitOperationDelete): - del files[operation.path_in_repo] - recorded.append(("delete", operation.path_in_repo, None, None)) - else: # pragma: no cover - the tool makes no other operation - raise TypeError(type(operation).__name__) - commit = self._new_commit( - files, parent=self.main, date=datetime(2026, 11, 7, tzinfo=UTC) - ) - self.main = commit - self.made.append( - { - "commit": commit, - "message": commit_message, - "parent": parent_commit, - "operations": recorded, - } - ) - return SimpleNamespace(oid=commit) - - -def _package(name: str, version: str) -> dict[str, str]: - return {"name": name, "version": version} - - -def _tagged_manifests( - *, - release: str, - tag: str, - attempt_id: str | None, - artifacts: dict[str, tuple[str, str, bytes]], - dataset_role: str | None = None, - release_metadata: dict[str, Any] | None = None, - build_metadata: dict[str, Any] | None = None, - repository: str = UK_REPOSITORY, -) -> tuple[bytes, bytes]: - """A tagged build's release and build manifests. - - ``artifacts`` maps each key to its kind, file name and bytes. A dated - tag's ``build`` names the release as ``build_id`` and carries the - attempt and the tag; a release-per-build tag's names itself. The two - ``metadata`` objects go at the top level and in ``build``, as the June - 2023 release has them. - """ - build: dict[str, Any] = { - "build_id": release if attempt_id is not None else tag, - "built_at": "2026-10-19T08:41:02.123456+00:00", - "built_with_core_package": _package("policyengine-core", "3.33.3"), - "built_with_model_package": _package("policyengine-uk", "2.174.1"), - } - if attempt_id is not None: - build.update(attempt_id=attempt_id, cut_tag=tag) - if build_metadata is not None: - build["metadata"] = build_metadata - manifest: dict[str, Any] = { - "schema_version": 1, - "data_package": _package("microcosm-data", "0.1.0"), - "build": build, - "compatible_core_packages": [ - {"name": "policyengine-core", "specifier": "==3.33.3"} - ], - "compatible_model_packages": [ - {"name": "policyengine-uk", "specifier": "==2.174.1"} - ], - "artifacts": { - key: { - "kind": kind, - "path": name, - "repo_id": repository, - "revision": tag, - "sha256": sha256(content), - } - for key, (kind, name, content) in artifacts.items() - }, - } - if release_metadata is not None: - manifest["metadata"] = release_metadata - if dataset_role is None: - dataset_key = next( - key for key, (kind, _, _) in artifacts.items() if kind == "microdata" - ) - manifest["default_datasets"] = {"national": dataset_key} - else: - manifest["dataset_role"] = dataset_role - manifest["default_datasets"] = {} - build_manifest: dict[str, Any] = { - "build_id": build["build_id"], - "code": {"repository": "PolicyEngine/microcosm"}, - } - if attempt_id is not None: - build_manifest.update(attempt_id=attempt_id, cut_tag=tag) - return dumped(manifest), dumped(build_manifest) - - -def _national_files(tag: str, attempt_id: str, *, dataset: bytes) -> dict[str, bytes]: - """A tagged national build's files: its release folder's and the root's.""" - folder = f"releases/{NATIONAL}" - diagnostics = dumped({"schema_version": 9, "build": attempt_id}) - certification = dumped({"kind": "uk_release_certification", "attempt": attempt_id}) - weights = b"weights for " + attempt_id.encode() - release_manifest, build_manifest = _tagged_manifests( - release=NATIONAL, - tag=tag, - attempt_id=attempt_id, - artifacts={ - "microcosm_uk_2024_25": ("microdata", "microcosm_uk_2024_25.h5", dataset), - "microcosm_uk_2024_25_calibration": ( - "calibration", - "microcosm_uk_2024_25_calibration.npz", - weights, - ), - "calibration_diagnostics": ( - "diagnostics", - "calibration_diagnostics.json", - diagnostics, - ), - "release_certification": ( - "diagnostics", - "release_certification.json", - certification, - ), - }, - ) - return { - f"{folder}/release_manifest.json": release_manifest, - f"{folder}/build_manifest.json": build_manifest, - f"{folder}/calibration_diagnostics.json": diagnostics, - f"{folder}/release_certification.json": certification, - "microcosm_uk_2024_25.h5": dataset, - "microcosm_uk_2024_25_calibration.npz": weights, - } - - -def _dense_files() -> dict[str, bytes]: - """The tag-only dense build's files, with its checksum ledger.""" - folder = f"releases/{DENSE}" - dataset = b"dense dataset" - diagnostics = dumped({"schema_version": 9, "build": DENSE_BUILD}) - summary = dumped({"gates": "passed"}) - release_manifest, build_manifest = _tagged_manifests( - release=DENSE, - tag=DENSE_TAG, - attempt_id=DENSE_BUILD, - dataset_role="non_default_local_area", - artifacts={ - "microcosm_uk_2024_25_dense": ( - "microdata", - "microcosm_uk_2024_25_dense.h5", - dataset, - ), - "calibration_diagnostics": ( - "diagnostics", - "calibration_diagnostics.json", - diagnostics, - ), - "gate_summary": ("diagnostics", "gate_summary.json", summary), - }, - ) - ledger = "".join( - f"{sha256(content)} {name}\n" - for name, content in sorted( - { - "build_manifest.json": build_manifest, - "calibration_diagnostics.json": diagnostics, - "gate_summary.json": summary, - "microcosm_uk_2024_25_dense.h5": dataset, - "release_manifest.json": release_manifest, - }.items() - ) - ).encode() - return { - f"{folder}/release_manifest.json": release_manifest, - f"{folder}/build_manifest.json": build_manifest, - f"{folder}/calibration_diagnostics.json": diagnostics, - f"{folder}/gate_summary.json": summary, - f"{folder}/sha256sums.txt": ledger, - "microcosm_uk_2024_25_dense.h5": dataset, - } - - -def _june_2023_files() -> dict[str, bytes]: - """The June 2023 release-per-build release's files.""" - folder = f"releases/{JUNE_2023_TAG}" - dataset = b"2023 dataset" - diagnostics = dumped({"schema_version": 6}) - release_manifest, build_manifest = _tagged_manifests( - release=JUNE_2023_TAG, - tag=JUNE_2023_TAG, - attempt_id=None, - artifacts={ - "populace_uk_2023": ("microdata", "populace_uk_2023.h5", dataset), - "calibration_diagnostics": ( - "diagnostics", - "calibration_diagnostics.json", - diagnostics, - ), - }, - release_metadata=JUNE_2023_RELEASE_METADATA, - build_metadata=JUNE_2023_BUILD_METADATA, - ) - return { - f"{folder}/release_manifest.json": release_manifest, - f"{folder}/build_manifest.json": build_manifest, - f"{folder}/calibration_diagnostics.json": diagnostics, - "populace_uk_2023.h5": dataset, - } - - -def _pointer(release_id: str, *, revision: str | None = None) -> bytes: - payload: dict[str, Any] = {"schema_version": 1, "release_id": release_id} - if revision is not None: - payload.update(line="national", revision=revision) - return dumped(payload) - - -def uk_repository(download_dir: Path) -> FakeDatasetRepository: - """The UK private repository's tagged layout, before its switch. - - ``main`` holds the newer national build's files and its release folder, - which still has the older build's ``score_vs_enhanced_frs.json``; - ``latest-national.json`` names the older national build, ``latest.json`` - the June 2023 release, and the dense build is only under its tag. - """ - hub = FakeDatasetRepository(UK_REPOSITORY, download_dir) - hub.seed( - {".gitattributes": b"*.h5 filter=lfs\n"}, date=datetime(2026, 6, 1, tzinfo=UTC) - ) - hub.seed( - {**_june_2023_files(), "latest.json": _pointer(JUNE_2023_TAG)}, - date=PUBLISHED_AT[JUNE_2023_TAG], - tag=JUNE_2023_TAG, - ) - older = _national_files( - OLDER_NATIONAL_TAG, OLDER_NATIONAL_BUILD, dataset=b"older national dataset" - ) - older[f"releases/{NATIONAL}/score_vs_enhanced_frs.json"] = b"{}" - hub.seed(older, date=PUBLISHED_AT[OLDER_NATIONAL_TAG], tag=OLDER_NATIONAL_TAG) - hub.seed( - { - "latest-national.json": _pointer(NATIONAL, revision=OLDER_NATIONAL_TAG), - }, - date=datetime(2026, 10, 26, 14, 5, 59, tzinfo=UTC), - ) - hub.seed(_dense_files(), date=PUBLISHED_AT[DENSE_TAG], tag=DENSE_TAG, on_main=False) - # As the Hub lists microcosm-uk-2024-25-dense-20261026T105309Z-c9df4b86. - hub.annotate(DENSE_TAG) - hub.seed( - _national_files( - NEWER_NATIONAL_TAG, NEWER_NATIONAL_BUILD, dataset=b"newer national dataset" - ), - date=PUBLISHED_AT[NEWER_NATIONAL_TAG], - tag=NEWER_NATIONAL_TAG, - ) - return hub - - -def _us_build_files( - tag: str, - *, - dataset_name: str, - dataset: bytes, - dataset_role: str | None = None, - declares_build_manifest: bool = False, - undeclared: dict[str, bytes] | None = None, -) -> dict[str, bytes]: - """A US release-per-build build's files: ``releases//`` and the root. - - With ``declares_build_manifest`` the release manifest lists the build's - own ``build_manifest.json`` as an artifact, as the SPM builds' do. With - ``undeclared`` the folder also holds those files and a checksum ledger - that records every file of the build, as the ACS local-area builds' do. - """ - folder = f"releases/{tag}" - diagnostics = dumped({"schema_version": 9, "build": tag}) - artifacts: dict[str, tuple[str, str, bytes]] = { - dataset_name.removesuffix(".h5"): ("microdata", dataset_name, dataset), - "calibration_diagnostics": ( - "diagnostics", - "calibration_diagnostics.json", - diagnostics, - ), - } - if declares_build_manifest: - parent = dumped({"build_id": "populace-us-2024-buildp-parent"}) - artifacts["parent_build_manifest"] = ( - "evidence", - "parent_build_manifest.json", - parent, - ) - _, build_manifest = _tagged_manifests( - release=tag, - tag=tag, - attempt_id=None, - artifacts=artifacts, - dataset_role=dataset_role, - repository=US_REPOSITORY, - ) - if declares_build_manifest: - artifacts["build_manifest"] = ( - "evidence", - "build_manifest.json", - build_manifest, - ) - release_manifest, _ = _tagged_manifests( - release=tag, - tag=tag, - attempt_id=None, - artifacts=artifacts, - dataset_role=dataset_role, - repository=US_REPOSITORY, - ) - files = { - f"{folder}/release_manifest.json": release_manifest, - f"{folder}/build_manifest.json": build_manifest, - dataset_name: dataset, - } - for _, name, content in artifacts.values(): - if name != dataset_name: - files[f"{folder}/{name}"] = content - if undeclared is not None: - files.update( - {f"{folder}/{name}": content for name, content in undeclared.items()} - ) - recorded = { - path.removeprefix(f"{folder}/"): content - for path, content in files.items() - if path.startswith(f"{folder}/") - } - recorded[dataset_name] = dataset - files[f"{folder}/sha256sums.txt"] = "".join( - f"{sha256(content)} {name}\n" for name, content in sorted(recorded.items()) - ).encode() - return files - - -def us_repository(download_dir: Path) -> FakeDatasetRepository: - """The US repository's tagged layout, before its switch. - - ``main`` holds the leftover national build and the SPM build, which - ``latest.json`` names; the ACS local-area build is only under its tag. - The leftover build's tag is on its own commit, and its staging branch, as - the retry left it, names the commit on ``main`` that repeated its files. - """ - hub = FakeDatasetRepository(US_REPOSITORY, download_dir) - hub.seed( - {".gitattributes": b"*.h5 filter=lfs\n"}, date=datetime(2026, 6, 1, tzinfo=UTC) - ) - finished = _us_build_files( - FINISHED_TAG, dataset_name="populace_us_2024.h5", dataset=b"buildm dataset" - ) - published = US_PUBLISHED_AT[FINISHED_TAG] - hub.seed(finished, date=published, tag=FINISHED_TAG, on_main=False) - hub.branches[FINISHED_STAGING_BRANCH] = hub.seed( - finished, date=published.replace(second=16) - ) - hub.seed( - { - **_us_build_files( - SPM_TAG, - dataset_name="populace_us_2024.h5", - dataset=b"spm dataset", - declares_build_manifest=True, - ), - "latest.json": _pointer(SPM_TAG), - }, - date=US_PUBLISHED_AT[SPM_TAG], - tag=SPM_TAG, - ) - hub.seed( - _us_build_files( - ACS_TAG, - dataset_name="populace_us_2024_acs_local.h5", - dataset=b"acs local-area dataset", - dataset_role="non_default_local_area", - undeclared=ACS_UNDECLARED_FILES, - ), - date=US_PUBLISHED_AT[ACS_TAG], - tag=ACS_TAG, - on_main=False, - ) - return hub - - -UNTAGGED_REPOSITORY = "example-owner/untagged-releases" -#: The two untagged builds' folder names under ``releases/``, which the -#: switch keeps as their build names. -OLDER_UNTAGGED_FOLDER = "example-2026-chronicle-aaaaaaa-20260101T010101Z" -NEWER_UNTAGGED_FOLDER = "example-2025-chronicle-bbbbbbb-20260102T020202Z" -#: The releases the two untagged builds move into. -OLDER_UNTAGGED_RELEASE = "example-2026-national" -NEWER_UNTAGGED_RELEASE = "example-2025-national" -#: When each untagged folder's files last changed on ``main``: the older -#: folder was first published earlier and rewritten in a later commit. -UNTAGGED_FIRST_PUBLISHED_AT = datetime(2026, 1, 3, 3, 0, 0, tzinfo=UTC) -UNTAGGED_LAST_CHANGED_AT = { - OLDER_UNTAGGED_FOLDER: datetime(2026, 1, 3, 4, 0, 0, tzinfo=UTC), - NEWER_UNTAGGED_FOLDER: datetime(2026, 1, 4, 5, 0, 0, tzinfo=UTC), -} -#: When each untagged build was built, as its manifests record it. -UNTAGGED_BUILT_AT = { - OLDER_UNTAGGED_FOLDER: "2026-01-01T01:01:01.000001+00:00", - NEWER_UNTAGGED_FOLDER: "2026-01-02T02:02:02.000002+00:00", -} -_UNTAGGED_DESCRIPTION = "An example synthetic population." - - -def _untagged_build(folder: str, *, year: int, chronicle: str) -> dict[str, Any]: - """An untagged build's ``build`` object, which is also its build manifest.""" - return { - "schema_version": 1, - "description": _UNTAGGED_DESCRIPTION, - "build_id": folder, - "built_at": UNTAGGED_BUILT_AT[folder], - "lineage": f"example_{year}", - "population_year": year, - "chronicle": {"repo": "PolicyEngine/chronicle", "commit": chronicle}, - } - - -def untagged_folder_files( - folder: str, - *, - year: int, - chronicle: str, - diagnostics: bytes, - builder_paths: bool, -) -> dict[str, bytes]: - """An untagged build's folder: its two manifests and its diagnostics. - - Its release manifest declares the builder's own output files, which the - folder doesn't hold: with ``builder_paths`` each under the builder's - ``out/`` directory, as BE's 2025 build has them, otherwise keyed by file - name with no path, as its 2026 build has them. The diagnostics file in - the folder is none of them. - """ - build = _untagged_build(folder, year=year, chronicle=chronicle) - outputs = { - f"example_{year}.h5": b"builder dataset " + folder.encode(), - f"example_{year}_weights.npz": b"builder weights " + folder.encode(), - f"example_{year}_calibration_diagnostics.json": b"builder diagnostics", - } - artifacts = { - (name.rsplit(".", 1)[0] if builder_paths else name): { - **({"path": f"out/example/{name}"} if builder_paths else {}), - "sha256": sha256(content), - "bytes": len(content), - } - for name, content in outputs.items() - } - manifest = { - "schema_version": 1, - "description": _UNTAGGED_DESCRIPTION, - "data_package": _package("example-data", f"0.{year - 2020}.0"), - "default_datasets": {"national": f"example_{year}"}, - "build": build, - "artifacts": artifacts, - "external_validations": {"example": {"status": "reviewed"}}, - } - return { - f"releases/{folder}/release_manifest.json": dumped(manifest), - f"releases/{folder}/build_manifest.json": dumped(build), - f"releases/{folder}/calibration_diagnostics.json": diagnostics, - } - - -def _untagged_pointer(folder: str) -> bytes: - """``latest.json`` as BE's has it: the folder's name, its files' paths - and no revision.""" - return dumped( - { - "schema_version": 1, - "release_id": folder, - "paths": { - name.removesuffix(".json"): f"releases/{folder}/{name}" - for name in ( - "build_manifest.json", - "release_manifest.json", - "calibration_diagnostics.json", - ) - }, - } - ) - - -def untagged_repository(download_dir: Path) -> FakeDatasetRepository: - """A repository with untagged build folders only, as BE's release - repository is before its switch. - - The older folder is published, then rewritten in a later commit, while - ``latest.json`` names it; the newer folder's commit also points - ``latest.json`` at it. There are no tags and no branch but ``main``. - """ - hub = FakeDatasetRepository(UNTAGGED_REPOSITORY, download_dir) - hub.seed( - {".gitattributes": b"*.h5 filter=lfs\n", "README.md": b"# Example\n"}, - date=datetime(2026, 1, 3, 2, 0, 0, tzinfo=UTC), - ) - older = { - "year": 2026, - "chronicle": "a" * 40, - "builder_paths": False, - } - hub.seed( - { - **untagged_folder_files( - OLDER_UNTAGGED_FOLDER, diagnostics=b'{"first": true}', **older - ), - "latest.json": _untagged_pointer(OLDER_UNTAGGED_FOLDER), - }, - date=UNTAGGED_FIRST_PUBLISHED_AT, - ) - hub.seed( - untagged_folder_files( - OLDER_UNTAGGED_FOLDER, diagnostics=b'{"schema_version": 9}', **older - ), - date=UNTAGGED_LAST_CHANGED_AT[OLDER_UNTAGGED_FOLDER], - ) - hub.seed( - {"README.md": b"# Example, reframed\n"}, - date=datetime(2026, 1, 3, 4, 0, 1, tzinfo=UTC), - ) - hub.seed( - { - **untagged_folder_files( - NEWER_UNTAGGED_FOLDER, - year=2025, - chronicle="b" * 40, - diagnostics=b'{"schema_version": 9, "targets": []}', - builder_paths=True, - ), - "latest.json": _untagged_pointer(NEWER_UNTAGGED_FOLDER), - }, - date=UNTAGGED_LAST_CHANGED_AT[NEWER_UNTAGGED_FOLDER], - ) - return hub diff --git a/tools/generate_release_contract_fixtures.py b/tools/generate_release_contract_fixtures.py index da26ae8f5e..8c4a7e8998 100644 --- a/tools/generate_release_contract_fixtures.py +++ b/tools/generate_release_contract_fixtures.py @@ -35,10 +35,10 @@ 1. ``add_build`` with ``make_current=False``, the interface's change for a publication; 2. ``make_current``, the interface's change for a promotion; -3. ``dataclasses.replace(record, default=...)``, the step - ``microcosm.build.build_folder_switch._switch_record`` takes to set - ``default``. The interface has no function that sets it. Both goldens name - the national release as the default. +3. ``dataclasses.replace(record, default=...)``, the step the one-time switch + tool took to set ``default`` when it wrote each repository's first record. + The interface has no function that sets it. Both goldens name the national + release as the default. ``ReleasesRecord.serialize`` then gives the bytes. From dbbc5f4835f2f02b33c1697dcefab48bc883c4fd Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:25:08 +0400 Subject: [PATCH 3/9] Add failing tests for reading and writing no latest.json pointer files Every release repository lists its builds in releases.json, and each repository's switch deleted its latest*.json pointer files. These tests fail before the change, 32 of them on assertions: - DatasetSpec has no pointer_path and must name its release; - microcosm.data and microcosm.data.release export no pointer reader, writer or constant, and keep no private pointer reader; - microcosm.data.contract keeps no rules for latest-.json names and their tags; - load() has no unverified_root option; - the loader refuses a repository without releases.json, online and offline, and requests no pointer file (today it follows latest.json); - AM's and NZ's release contracts name build folders and releases.json, not latest.json or a Hugging Face revision; - the C1 inventory fixture has no line field, and the C5 registry snapshot names no pointer file; - the emitter publishing command refuses pointer files in a repository without releases.json with the same advice to remove them. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_country_spec.py | 18 ++ .../uk/test_uk_release_publication.py | 17 +- .../shared/test_no_pointer_files.py | 219 ++++++++++++++++++ .../shared/test_release_contract_fixtures.py | 15 +- 4 files changed, 256 insertions(+), 13 deletions(-) create mode 100644 packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py diff --git a/packages/microcosm-build/tests/engine_free/shared/test_country_spec.py b/packages/microcosm-build/tests/engine_free/shared/test_country_spec.py index 1e07c17cdb..62d86b14f9 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_country_spec.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_country_spec.py @@ -509,6 +509,24 @@ def test_fingerprint_is_stable_across_loads(self, spec) -> None: assert load_country_spec("am").fingerprint == spec.fingerprint +@pytest.mark.parametrize("country", ["am", "nz"]) +def test_an_unpublished_country_contract_names_build_folders_and_releases_json( + country: str, +) -> None: + """Armenia and New Zealand have no release repository yet. Their builds + will publish into ``releases///`` folders that + ``releases.json`` lists, as BE's do, so their contracts name no pointer + file and no Hugging Face revision as a build's identity.""" + contract = load_country_spec(country).release_contract + assert "latest.json" not in contract.public_artifacts + assert "releases.json" in contract.public_artifacts + assert "releases///" in contract.policy + assert "releases.json" in contract.policy + assert "Hugging Face revision" not in contract.policy + assert "latest.json" not in contract.notes + assert "no pointer file names a build" in contract.notes + + class TestBelgianPackage: @pytest.fixture(scope="class") def spec(self): diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py index d4fd3219cc..a2351e332e 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py @@ -926,7 +926,7 @@ def test_the_command_refuses_a_repository_with_pointer_files_before_an_emitter( @pytest.mark.parametrize("promote", [False, True], ids=["publish", "promote"]) -def test_the_command_refuses_a_repository_that_has_not_switched_without_advising_removal( +def test_the_command_refuses_pointer_files_in_a_repository_without_releases_json( national: Path, artifact_root: Path, # noqa: F811 monkeypatch, @@ -934,10 +934,9 @@ def test_the_command_refuses_a_repository_that_has_not_switched_without_advising hub_listing: HubListing, promote: bool, ) -> None: - """Before its switch a repository has no releases.json, the loader - follows its pointer files and the switch reads them to choose each - release's current build, so the refusal says the repository has not - switched and does not advise removing them.""" + """Nothing reads or writes pointer files, whether or not the repository + has releases.json yet, so the refusal is the same: remove them. It no + longer tells the operator to keep them for a switch.""" started, repository = _start_emitters(monkeypatch) hub_listing.files.extend(["README.md", "latest.json", "latest-national.json"]) argv = ( @@ -951,10 +950,10 @@ def test_the_command_refuses_a_repository_that_has_not_switched_without_advising assert code == 1 assert started == [] assert output is None - assert "has not switched to releases.json" in error - assert "latest-national.json" in error - assert "microcosm.build.build_folder_switch" in error - assert "remove" not in error + assert "latest.json" in error and "latest-national.json" in error + assert "remove the file(s)" in error + assert "has not switched" not in error + assert "loader" not in error assert repository == {} diff --git a/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py b/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py new file mode 100644 index 0000000000..3cb46a8f11 --- /dev/null +++ b/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py @@ -0,0 +1,219 @@ +"""Microcosm neither reads nor writes ``latest*.json`` pointer files. + +Every release repository lists its builds in ``releases.json``, and each +repository's switch to it deleted its pointer files (``latest.json``, +``latest-.json`` and ``latest-evidence.json``). So the registry names no +pointer file, ``microcosm.data`` exports no pointer reader or writer, and the +loader refuses a repository without ``releases.json`` instead of following a +pointer file there. +""" + +from __future__ import annotations + +import dataclasses +import hashlib +import inspect +import json +from pathlib import Path + +import huggingface_hub +import pytest + +import microcosm.data +import microcosm.data.contract as contract +import microcosm.data.release as release +from microcosm.data import DatasetSpec, load +from microcosm.data.loader import resolve_certified +from test_support.microcosm_data.hub_errors import hub_unreachable, missing_on_hub + +US_REPO_ID = "policyengine/populace-us" +#: A build ID of the tagged layout, which a pointer file named by its tag. +TAGGED_BUILD = "populace-us-2024-spm-20260915" +TAGGED_DATASET = b"a dataset at its tag" + +#: Every public name the pointer-file reader and writer had. +POINTER_FILE_NAMES = ( + "LATEST_POINTER_PATH", + "LINE_POINTER_PATH_TEMPLATE", + "LATEST_EVIDENCE_POINTER_PATH", + "LATEST_POINTER_SCHEMA_VERSION", + "RELEASE_TIER_CERTIFIED", + "RELEASE_TIER_EVIDENCE", + "LatestPointer", + "latest_release", + "latest_line_release", + "latest_evidence_release", + "latest_pointer_payload", + "line_pointer_payload", + "latest_evidence_pointer_payload", + "line_pointer_path", +) + + +def test_a_dataset_spec_names_no_pointer_file() -> None: + names = {field.name for field in dataclasses.fields(DatasetSpec)} + + assert "pointer_path" not in names + assert "release" in names + + +def test_a_dataset_spec_must_name_its_release() -> None: + """The loader reads every entry's builds through ``releases.json``, so an + entry without a release has nothing to read.""" + with pytest.raises(TypeError, match="release"): + DatasetSpec( + country="zz", + year=2024, + hf_repo="policyengine/populace-zz", + filename="populace_zz_2024.h5", + engine_module="policyengine_zz.data", + engine_class="ZZSingleYearDataset", + engine_package="policyengine-zz", + ) + + +@pytest.mark.parametrize("name", POINTER_FILE_NAMES) +def test_microcosm_data_exports_no_pointer_file_reader_or_writer(name: str) -> None: + assert not hasattr(microcosm.data, name) + assert name not in microcosm.data.__all__ + assert not hasattr(release, name) + assert name not in release.__all__ + + +@pytest.mark.parametrize( + "name", ["_read_pointer", "_LINE_RE", "_current_evidence_build"] +) +def test_the_release_module_keeps_no_private_pointer_reader(name: str) -> None: + assert not hasattr(release, name) + + +@pytest.mark.parametrize( + "name", + [ + "line_for_release_id", + "dataset_role_for_line", + "_uk_line_cut_tag_re", + "_UK_NATIONAL_REVISION_SUFFIX_RE", + ], +) +def test_the_contract_keeps_no_pointer_file_name_rules(name: str) -> None: + """Only the pointer files' ``latest-.json`` names and their tags + used these.""" + assert not hasattr(contract, name) + assert name not in contract.__all__ + + +def test_load_has_no_unverified_root_option() -> None: + """No repository holds a root dataset file any more.""" + assert "unverified_root" not in inspect.signature(load).parameters + + +class _TaggedLayoutHub: + """A repository in the tagged layout: a pointer file at its root, and the + build's manifest and dataset at the build's tag, but no ``releases.json``. + Records every file requested.""" + + def __init__(self, tmp_path: Path, *, offline: bool = False) -> None: + self.tmp_path = tmp_path + self.offline = offline + self.requested: list[str] = [] + self.files: dict[tuple[str, str | None], bytes] = { + ("latest.json", None): json.dumps( + { + "schema_version": 1, + "release_id": TAGGED_BUILD, + "updated_at": "2026-09-15T00:00:00+00:00", + "paths": { + name.removesuffix(".json"): f"releases/{TAGGED_BUILD}/{name}" + for name in contract.required_release_files(TAGGED_BUILD) + }, + } + ).encode(), + (f"releases/{TAGGED_BUILD}/release_manifest.json", TAGGED_BUILD): ( + json.dumps(_tagged_release_manifest()).encode() + ), + ("populace_us_2024.h5", TAGGED_BUILD): TAGGED_DATASET, + } + + def __call__( + self, + *, + repo_id: str, + filename: str, + repo_type: str, + revision: str | None = None, + ) -> str: + assert (repo_id, repo_type) == (US_REPO_ID, "dataset") + self.requested.append(filename) + if filename == "releases.json" and self.offline: + raise hub_unreachable(repo_id, filename, revision) + content = self.files.get((filename, revision)) + if content is None: + raise missing_on_hub(repo_id, filename, revision) + local = self.tmp_path / (revision or "main") / filename + local.parent.mkdir(parents=True, exist_ok=True) + local.write_bytes(content) + return str(local) + + +def _tagged_release_manifest() -> dict: + return { + "schema_version": 1, + "default_datasets": {"national": "populace_us_2024"}, + "build": { + "build_id": TAGGED_BUILD, + "built_with_core_package": { + "name": "policyengine-core", + "version": "3.26.11", + }, + "built_with_model_package": { + "name": "policyengine-us", + "version": "1.764.6", + }, + }, + "compatible_core_packages": [ + {"name": "policyengine-core", "specifier": "==3.26.11"} + ], + "compatible_model_packages": [ + {"name": "policyengine-us", "specifier": "==1.764.6"} + ], + "artifacts": { + "populace_us_2024": { + "kind": "microdata", + "path": "populace_us_2024.h5", + "repo_id": US_REPO_ID, + "revision": TAGGED_BUILD, + "sha256": hashlib.sha256(TAGGED_DATASET).hexdigest(), + } + }, + } + + +def test_the_loader_refuses_a_repository_without_releases_json( + tmp_path: Path, +) -> None: + """A repository with only a pointer file is refused, naming + ``releases.json``; the pointer file is never requested.""" + hub = _TaggedLayoutHub(tmp_path) + + with pytest.raises(ValueError, match="releases.json") as refusal: + resolve_certified("us", 2024, hub_download=hub) + + assert US_REPO_ID in str(refusal.value) + assert "latest" not in str(refusal.value) + assert hub.requested == ["releases.json"] + + +def test_offline_the_loader_refuses_a_releases_json_never_cached( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Offline, a ``releases.json`` that was never cached is refused too, + saying it is not in the cache; no cached pointer file is read instead.""" + monkeypatch.setattr(huggingface_hub.constants, "HF_HUB_OFFLINE", True) + hub = _TaggedLayoutHub(tmp_path, offline=True) + + with pytest.raises(ValueError, match="releases.json") as refusal: + resolve_certified("us", 2024, hub_download=hub) + + assert "cache" in str(refusal.value) + assert hub.requested == ["releases.json"] diff --git a/packages/microcosm-data/tests/engine_free/shared/test_release_contract_fixtures.py b/packages/microcosm-data/tests/engine_free/shared/test_release_contract_fixtures.py index b880f95b78..295231015a 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_release_contract_fixtures.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_release_contract_fixtures.py @@ -271,10 +271,9 @@ def test_inventory_matches_the_live_contract(): inventory = _json(FIXTURES / "c1" / "inventory.json") certification = inventory["certification"] assert inventory["release_id"] == UK_RELEASE - assert inventory["line"] == contract.line_for_release_id(UK_RELEASE) - assert inventory["dataset_role"] == contract.dataset_role_for_line( - inventory["line"] - ) + # A build's role, not a pointer file's name, says what it is. + assert "line" not in inventory + assert inventory["dataset_role"] == contract.NATIONAL_DEFAULT_DATASET_ROLE assert ( inventory["release_role"] == contract.RELEASE_ROLES[inventory["dataset_role"]] ) @@ -413,3 +412,11 @@ def test_registry_snapshot_matches_the_live_registry(): {"key": list(key), **dataclasses.asdict(REGISTRY[key])} for key in sorted(REGISTRY) ], f"the dataset registry changed; {REGENERATE} (C5)" + + +def test_registry_snapshot_names_no_pointer_file(): + """Every entry is read through its repository's releases.json.""" + snapshot = _json(FIXTURES / "c5" / "registry.json") + for entry in snapshot["entries"]: + assert "pointer_path" not in entry + assert entry["release"] From 0dc0dddda0090912b5b79ac26ce6cea11e57c4c6 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:44:06 +0400 Subject: [PATCH 4/9] Stop reading latest.json pointer files; AM and NZ contracts name releases.json (#1794) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every release repository lists its builds in releases.json, and each repository's switch deleted its latest*.json pointer files. - Loader: reads every entry through releases.json and refuses a repository without it, online and offline (when the cache never held it), naming the file; any other failure to read it propagates. The pointer fallback, the tagged-manifest checks and load(unverified_root=) are gone. CertifiedRelease keeps its fields; artifact_revision is always None. - Registry: DatasetSpec has no pointer_path and must name its release. - microcosm.data.release: latest_release, latest_line_release, latest_evidence_release, LatestPointer, line_pointer_path, line_pointer_payload, LINE_POINTER_PATH_TEMPLATE and RELEASE_TIER_CERTIFIED are gone, and microcosm.data exports no pointer name. The tagged publisher's own pointer writers (LATEST_POINTER_PATH, LATEST_EVIDENCE_POINTER_PATH, LATEST_POINTER_SCHEMA_VERSION, RELEASE_TIER_EVIDENCE, latest_pointer_payload and latest_evidence_pointer_payload) stay until 5b · 10 removes publish_release, their only caller. - microcosm.data.contract: line_for_release_id, dataset_role_for_line and the per-build tag pattern are gone; the fixture generator's C1 inventory has no line field. - release_publication: one refusal for a pointer file in any repository, with or without releases.json: remove it. - AM's and NZ's release contracts name build folders and releases.json, as BE's does; their golden specs pin the new digests. - Tests: the pointer-reader and line-pointer tests go; the loader checks they covered (a missing manifest, engine incompatibility, construction after verification, a Hub failure reading the record) run against build folders; the live loader test reads releases.json. - Docs and changelog: README, microcosm-data's README, the agent guide and docs/release-contract.md. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 +- ...op-reading-latest-pointer-files.removed.md | 1 + docs/agent-guide.md | 9 +- docs/release-contract.md | 77 +- .../microcosm/build/am/release_contract.json | 6 +- .../microcosm/build/nz/release_contract.json | 6 +- .../microcosm/build/release_publication.py | 40 +- .../src/microcosm/build/uk_runtime/staging.py | 2 +- .../us/test_us_fiscal_refresh_builder.py | 4 +- .../tests/golden/am_country_spec.json | 4 +- .../tests/golden/nz_country_spec.json | 4 +- packages/microcosm-data/README.md | 25 +- .../src/microcosm/data/__init__.py | 29 +- .../src/microcosm/data/contract.py | 57 +- .../src/microcosm/data/loader.py | 382 ++----- .../src/microcosm/data/registry.py | 71 +- .../src/microcosm/data/release.py | 389 +------ .../tests/engine_free/shared/test_contract.py | 13 - .../tests/engine_free/shared/test_loader.py | 971 +++--------------- .../tests/engine_free/shared/test_registry.py | 42 +- .../tests/engine_free/shared/test_release.py | 439 -------- .../shared/test_release_contract_keying.py | 27 +- .../fixtures/release_contract/v1/SHA256SUMS | 4 +- .../release_contract/v1/c1/inventory.json | 1 - .../release_contract/v1/c5/registry.json | 4 - test_support/microcosm_data/loader.py | 118 --- test_support/microcosm_data/release.py | 5 - tools/build_us_fiscal_refresh_release.py | 5 +- tools/generate_release_contract_fixtures.py | 6 +- tools/stage_uk_rowwise_candidate.py | 2 +- 30 files changed, 375 insertions(+), 2376 deletions(-) create mode 100644 changelog.d/1794-stop-reading-latest-pointer-files.removed.md diff --git a/README.md b/README.md index cd15bfc33f..c87a0d2194 100644 --- a/README.md +++ b/README.md @@ -204,7 +204,7 @@ version 2 staging run files to `policyengine/populace-uk-staging` under the same switch. The build command also **stages the finished dataset bundle** it built, national, dense or exact-count, under `staged//` in the private `policyengine/populace-uk-private` repository so the team can inspect -it without publishing it (the build's emitter uploads it): `releases/` and `latest.json` are untouched, the +it without publishing it (the build's emitter uploads it): `releases/` and `releases.json` are untouched, the release contract is not consulted, and a `releasable: false` size run stages like any other. Fetch a bundle with `tools/fetch_uk_staged_dataset.py`; re-stage a finished run directory with `tools/stage_uk_rowwise_candidate.py`. @@ -868,10 +868,8 @@ with the evidence contract, which refuses a build in the certified shape; the certified contract refuses the evidence shape, so an evidence build can't be published into the national release. The evidence release is never the repository's default, so `microcosm.data.load("us")` never loads its builds. -Its current build in `releases.json` takes the place of `latest-evidence.json`. -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. +Its current build in `releases.json` took the place of `latest-evidence.json`, +which the US switch deleted with every other `latest*.json` file. 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`, diff --git a/changelog.d/1794-stop-reading-latest-pointer-files.removed.md b/changelog.d/1794-stop-reading-latest-pointer-files.removed.md new file mode 100644 index 0000000000..03697830ba --- /dev/null +++ b/changelog.d/1794-stop-reading-latest-pointer-files.removed.md @@ -0,0 +1 @@ +Stop reading and writing `latest*.json` pointer files (#1794): every release repository lists its builds in `releases.json`, and each repository's switch deleted its pointer files. The loader refuses a repository without `releases.json`, online and offline, instead of following `latest.json` or a UK release's `latest-.json`; `load()` loses its `unverified_root` option, since no repository holds a root dataset file; `DatasetSpec` loses `pointer_path` and must name its `release`. `microcosm.data` and `microcosm.data.release` no longer have `latest_release`, `latest_line_release`, `latest_evidence_release`, `LatestPointer`, the pointer payload builders, `line_pointer_path` or the pointer constants, and `microcosm.data.contract` no longer has `line_for_release_id` or `dataset_role_for_line`. `microcosm-publish-release-build` still refuses a repository that has a pointer file, now with one message for any repository: remove the file. AM's and NZ's release contracts name build folders and `releases.json` instead of `latest.json`. diff --git a/docs/agent-guide.md b/docs/agent-guide.md index 1c69fd253f..d501554d15 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -391,8 +391,9 @@ package stage prints both commands itself. `tools/preflight_us_release_gates.py` runs the US national release checks that 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 +no current build while any `latest*.json` pointer file exists; each +repository's switch to `releases.json` deleted them, and Microcosm neither +reads nor writes 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 @@ -415,8 +416,8 @@ by pin, a signing key registered in `microcosm.data.gate_signing_keys`, and an inspection-only `--publish`. Never publish or promote artifacts as a side effect of another task. A UK rowwise run's **staged** bundle (`staged//` in the private repository, written by the build itself) -is inspection evidence, not a release: it never moves `releases/` or -`latest.json` and is not loadable through the certified loader. The build's +is inspection evidence, not a release: it never changes `releases/` or +`releases.json` and is not loadable through the certified loader. The build's default is to upload that bundle (hundreds of megabytes of licensed microdata) to the private repository; when you run `microcosm-build-uk` (`tools/build_uk_full.py`, or its stub `tools/build_uk_rowwise_candidate.py`) diff --git a/docs/release-contract.md b/docs/release-contract.md index 6dd093f7f8..cfe651a236 100644 --- a/docs/release-contract.md +++ b/docs/release-contract.md @@ -106,8 +106,8 @@ changed what the registry names and how the loader reaches it: - For every entry, the loader (`_resolve_certified_release`) reads the repository's `releases.json` and loads the release's current build, or a listed build that `build=` pins, from `releases///`. It - follows the entry's pointer file (`latest.json` or `latest-national.json`) - only where the repository has no `releases.json`. + refuses a repository without `releases.json` and reads no pointer file + (microcosm#1794). - The registry names no entry for the other four US releases or for any UK local-area release, so `microcosm.data.load` reaches none of them. - The US tools now write builds of standing releases. The fiscal-refresh tool @@ -364,11 +364,7 @@ both: `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 - `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 - calls. + release. The registry also disagrees with the name about the year. The registry files the UK national release under `("uk", 2025, "compact")`, the UK 2025 default @@ -381,7 +377,9 @@ release's name cannot match; microcosm#1144 reported the failure from a live run. On 2026-11-12 the test requires a release that the loader reads through `releases.json` to carry the registry entry's release name exactly, and requires a release that the loader reaches through a line pointer only to start -with `microcosm--`. +with `microcosm--`. Since microcosm#1794 the loader reaches no +release through a pointer file, so the test requires the entry's release name +for every entry. #### Version 1, planned for M3: dispatch on the declared country @@ -436,7 +434,7 @@ C1 version 1 dispatches on what the manifest declares instead of on its name: comparisons in `contract.py` and 13 in `release.py`. `loader.py` holds none, and `compatibility_recertification.py`, `source_enrichment.py`, `annual_projections.py` and `build_folder_manifests.py` hold more. - `line_for_release_id` leaves with the pointer reader instead. A schema-2 US + `line_for_release_id` left with the pointer reader (microcosm#1794). A schema-2 US build then cannot skip the US checks by choosing another name. 3. **Unknown countries fail closed.** The validator refuses them instead of falling back to the base set. The plan registers NZ before the switch to @@ -885,9 +883,9 @@ either. No publication command reads a Logbook row. The UK national, dense and local-area releases and the six US releases publish each build into its own folder, `releases///`. The repository's `releases.json` records each release's builds and names the -current one. For those releases the `latest*.json` pointer files survive as -read-only legacy: nothing writes one for them, and code reads one only for a -repository that has no `releases.json`. +current one. No repository holds a `latest*.json` pointer file: each +repository's switch to `releases.json` deleted them, and Microcosm neither +reads nor writes one (microcosm#1794). - **The releases.** `publishes_to_build_folder` names the releases that publish into build folders: the UK national release @@ -1010,25 +1008,20 @@ repository that has no `releases.json`. `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 - 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 - current build from `releases.json` where the file exists, and reads - `latest-evidence.json` otherwise. The switch tool read each repository's - pointer files once, to set each release's current build and the record's - `default`. + `latest-.json`, and nothing reads any pointer file: microcosm#1794 + removed the loader's fallback to them, `latest_release`, + `latest_line_release`, `latest_evidence_release` and `line_pointer_payload`. + The switch tool read each repository's pointer files once, to set each + release's current build and the record's `default`. - **The registry.** `microcosm.data.registry.REGISTRY` maps `(country, year, variant)` to a `DatasetSpec`. Each names the Hub repository, the dataset - file, the engine class, the `release` the loader reads through - `releases.json`, and the pointer file the loader follows where the - repository has no `releases.json`. The registry holds four entries: + file, the engine class, and the `release` the loader reads through + `releases.json`, which every entry must name. The registry holds four + entries: - `("uk", 2023, "compact")`: the June 2023 build, release `populace-uk-2023`; - `("uk", 2025, "compact")`: release `microcosm-uk-2024-25-national`, the - UK 2025 default load since microcosm#1432 (2026-11-02), with - `latest-national.json` as its pointer file; + UK 2025 default load since microcosm#1432 (2026-11-02); - `("uk", 2025, "dense")`: release `microcosm-uk-2024-25-dense`; - `("us", 2024, "compact")`: release `microcosm-us-2024-national`, whose builds declare `microcosm_us_2024.h5` (`build_folder_filename`) or @@ -1042,11 +1035,12 @@ repository that has no `releases.json`. release or build, declares a role other than the release's role in `releases.json`, pins a revision on any artifact, or declares a dataset whose role differs from `dataset`, whose repository differs from the registry's, or - whose file name the entry does not list. The loader goes to the entry's - pointer file only when the Hub answers that `releases.json` is absent or, - offline, when the cache never held the record. The loader ignores the - record's `default`: the registry chooses the release. - `load(unverified_root=True)` refuses a repository that has `releases.json`. + whose file name the entry does not list. When the Hub answers that + `releases.json` is absent, or offline when the cache never held the + record, the loader refuses the entry, naming the file; any other failure to + read it propagates. The loader ignores the record's `default`: the registry + chooses the release. `load` has no option to read a root dataset file, + which no repository holds. - **The gaps.** The registry has no entry for the US local-area release `microcosm-us-2024-local`, whose builds carry the US state and district file, or for any UK `local-k` release. policyengine.py's bundle, read on @@ -1110,10 +1104,12 @@ work. under M3's owners. - *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 - before that country's first publication. BE's names `releases.json` and - the `releases///` folders instead since microcosm#1741, - and its required files are the ones `BE_REQUIRED_RELEASE_FILES` lists, + `releases.json` in its boundary and the `releases///` + folders in its policy since microcosm#1794, as BE's has since + microcosm#1741. Neither country has a release name in + `publishes_to_build_folder` or a registry entry yet, so neither + publishes; each country's owner adds them before its first publication. + BE's required files are the ones `BE_REQUIRED_RELEASE_FILES` lists, which a build-shard test holds equal. - *BE's registry entry and staging* (microcosm#1741). BE's releases joined `publishes_to_build_folder` without a registry entry: there is no @@ -1131,20 +1127,11 @@ work. first build validates. Until that build publishes, the registry names a release with no published build: `available_variants()` lists the entry, 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. - - *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 - plan names no owner or milestone for them yet. - *The UK cut runner.* `tools/run_uk_cut.py` still builds the tagged publisher's arguments for the UK national release, and `docs/uk-cut-anyone.md` still describes them; `prepare_release` refuses @@ -1482,7 +1469,7 @@ release and the tagged publisher joined the table on 2026-11-11. | `tools/build_uk_rowwise_dataset.py` | Kept. The report's reason, that the graph driver already takes `--candidate-clone-counts`, does not settle it: both drivers accept the flag only for a dry run. `docs/uk-full-build-graph.md` keeps the row-wise driver as a separate driver, and Max had not ruled on UK-3 (dense or local-k) by 2026-10-15 | Both drivers still accept the flag only for a dry run | | `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 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. `latest_evidence_release`, which no module called, left with the pointer readers (microcosm#1794). Whoever retires the release must first find, from code, the readers of the 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 | | 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 | diff --git a/packages/microcosm-build/src/microcosm/build/am/release_contract.json b/packages/microcosm-build/src/microcosm/build/am/release_contract.json index 5161ec7e11..4e48d585b8 100644 --- a/packages/microcosm-build/src/microcosm/build/am/release_contract.json +++ b/packages/microcosm-build/src/microcosm/build/am/release_contract.json @@ -1,7 +1,7 @@ { "version": 1, "country": "am", - "policy": "Armenia releases are public because the v1 donor artifact and target sources are public. Every per-record artifact must retain an explicit US-donor/support-stratum banner and must never be described as Armenian microdata. Releases use data_build_id plus Hugging Face revision, never ordinal versions.", + "policy": "Armenia releases are public because the v1 donor artifact and target sources are public. Every per-record artifact must retain an explicit US-donor/support-stratum banner and must never be described as Armenian microdata. Builds are named by data_build_id, never ordinals, and each publishes into its own folder, releases///, which releases.json lists.", "builder": "populace-am", "hf": { "artifact_repo": "policyengine/populace-am", @@ -30,7 +30,7 @@ "source_coverage.json", "demographics.json", "validation_bands.json", - "latest.json" + "releases.json" ] }, "licence": { @@ -38,5 +38,5 @@ "restricted": false, "notes": "ArmStat makes ILCS household and member microdata available for free/open download. Chronicle must capture the exact licence text before a native-ILCS release; v1 itself republishes no ILCS unit record. The populace-US donor artifact's own public licence and exact certified revision must also be pinned before execution." }, - "notes": "The target dataset year is 2024. source_coverage.json follows the country-neutral populace#265 contract. validation_bands.json reports ArmStat national-accounts comparisons plus harvested CEQ/World Bank oracle bands; the latter are never gates unless promoted through Ledger. latest.json uploads last as the atomic pointer. No release or publication machinery exists in this spec-only package." + "notes": "The target dataset year is 2024. source_coverage.json follows the country-neutral populace#265 contract. validation_bands.json reports ArmStat national-accounts comparisons plus harvested CEQ/World Bank oracle bands; the latter are never gates unless promoted through Ledger. releases.json names each release's current build and the repository's default release; only the emitter's release writer changes it, and no pointer file names a build. No release or publication machinery exists in this spec-only package." } diff --git a/packages/microcosm-build/src/microcosm/build/nz/release_contract.json b/packages/microcosm-build/src/microcosm/build/nz/release_contract.json index db0690a243..251c674f7a 100644 --- a/packages/microcosm-build/src/microcosm/build/nz/release_contract.json +++ b/packages/microcosm-build/src/microcosm/build/nz/release_contract.json @@ -1,7 +1,7 @@ { "version": 1, "country": "nz", - "policy": "New Zealand v0 is a public synthetic transport artifact: its unit records derive only from the public Microcosm US support release and its calibration facts are public New Zealand aggregates. Every record and public presentation must retain the US-donor/support-stratum provenance banner and must never be described as observed New Zealand microdata. Releases use data_build_id plus immutable Hugging Face revision, never ordinal versions.", + "policy": "New Zealand v0 is a public synthetic transport artifact: its unit records derive only from the public Microcosm US support release and its calibration facts are public New Zealand aggregates. Every record and public presentation must retain the US-donor/support-stratum provenance banner and must never be described as observed New Zealand microdata. Builds are named by data_build_id, never ordinals, and each publishes into its own folder, releases///, which releases.json lists.", "builder": "populace-nz", "hf": { "artifact_repo": "policyengine/populace-nz", @@ -42,7 +42,7 @@ "source_coverage.json", "demographics.json", "reform_validation.json", - "latest.json" + "releases.json" ] }, "licence": { @@ -50,5 +50,5 @@ "restricted": false, "notes": "The donor artifact is the immutable public Build P release pinned in source_stages.json. Chronicle owns per-source licence evidence for each NZ aggregate. Any future HES CURF, IDI, or other restricted unit-record contribution requires a separate private-repository and destination-guard review before it enters this contract." }, - "notes": "The target dataset period is tax year 2026-27, represented by 2026 in the current single-year kernel. The generic release assembler must copy release_manifest_country to release_manifest.json.country exactly. The dashboard registry reads policyengine/populace-nz/latest.json; the staging repository is for build telemetry. calibration_diagnostics.json is the published target-fit surface. reform_validation.json stays a required release file, but its v0 contents are not yet specified: the Treasury official-score comparisons it carried in microcosm#821 came from the WFF reform checks, which this package leaves out. The two Hugging Face repositories and generic NZ release assembler do not yet exist, so this contract authorizes no publication by itself." + "notes": "The target dataset period is tax year 2026-27, represented by 2026 in the current single-year kernel. The generic release assembler must copy release_manifest_country to release_manifest.json.country exactly. releases.json names each release's current build and the repository's default release; only the emitter's release writer changes it, and no pointer file names a build. The staging repository is for build telemetry. calibration_diagnostics.json is the published target-fit surface. reform_validation.json stays a required release file, but its v0 contents are not yet specified: the Treasury official-score comparisons it carried in microcosm#821 came from the WFF reform checks, which this package leaves out. The two Hugging Face repositories and generic NZ release assembler do not yet exist, so this contract authorizes no publication by itself." } diff --git a/packages/microcosm-build/src/microcosm/build/release_publication.py b/packages/microcosm-build/src/microcosm/build/release_publication.py index d25d0ed8b9..893413cc3e 100644 --- a/packages/microcosm-build/src/microcosm/build/release_publication.py +++ b/packages/microcosm-build/src/microcosm/build/release_publication.py @@ -12,13 +12,12 @@ rules in ``microcosm_emitter_interface.releases``. Nothing here commits, tags or writes a pointer file. -A repository's switch to ``releases.json`` deletes its ``latest*.json`` -pointer files in the same commit, and the emitter changes no current build -while one exists. So the command lists the repository's files first and -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 in one with it, that the file appeared -after the switch and should be removed. The +Each repository's switch to ``releases.json`` deleted its ``latest*.json`` +pointer files, and Microcosm neither reads nor writes them; the emitter +writes none and changes no current build while one exists. So the command +lists the repository's files first and refuses, before any emitter starts, +while any pointer file is there, whether or not the repository has +``releases.json`` yet, and says to remove it. The tagged publisher refuses these releases, and any repository that has ``releases.json``. @@ -130,7 +129,6 @@ not_a_build_folder_release_reason, prepare_build_folder_release, ) -from microcosm.data.releases_record import RELEASES_RECORD_PATH if TYPE_CHECKING: from microcosm_emitter_interface import EmitterStartupError, RequestFailure @@ -568,13 +566,13 @@ def _refuse_pointer_files(repository: str) -> None: """Refuse a repository that has any ``latest*.json`` pointer file. The interface's ``is_pointer_file`` rule says which files those are, and - the emitter applies it too. A repository's switch to ``releases.json`` - deletes them, and nothing writes them after it. Without ``releases.json`` - the repository has not switched: the loader follows its pointer files, - so the refusal says so and keeps them. With it, a pointer file appeared - after the switch, and the - refusal says to remove it. A repository whose files cannot be listed is - refused too. + the emitter applies it too. Each repository's switch to ``releases.json`` + deleted them, and Microcosm neither reads nor writes them, so a pointer + file in any repository, with ``releases.json`` or without it, appeared + later, and the refusal says to remove it. The emitter refuses only a + change of a release's current build while one exists, so this is the one + refusal of a publication without ``--make-current``. A repository whose + files cannot be listed is refused too. """ try: paths = _repository_files(repository) @@ -586,19 +584,11 @@ def _refuse_pointer_files(repository: str) -> None: "and run the command again" ) from error pointer_files = sorted(path for path in paths if is_pointer_file(path)) - if pointer_files and RELEASES_RECORD_PATH not in paths: - raise ValueError( - f"{repository} has not switched to releases.json: it has no " - f"releases.json and has the pointer file(s) {', '.join(pointer_files)}, " - "which the loader follows. Its builds publish here only after the " - "switch; keep the files in place and run the command again once " - "the switch has run" - ) if pointer_files: raise ValueError( f"{repository} has the pointer file(s) {', '.join(pointer_files)}. " - "Its builds publish here only once its switch to releases.json has " - "deleted them, and nothing writes them after it, so remove the " + "Microcosm neither reads nor writes latest*.json pointer files, and " + "builds publish only into a repository without them, so remove the " "file(s) that appeared, then run the command again" ) diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/staging.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/staging.py index c70bdc2a1b..d631f64517 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/staging.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/staging.py @@ -4,7 +4,7 @@ staging repository under ``runs//``; the finished dataset bundle a build's manifest vouches for goes to the private artifact repository under ``staged//`` (:mod:`microcosm.build.staging_dataset`), where it is -inspectable without being published: ``releases/`` and ``latest.json`` are +inspectable without being published: ``releases/`` and ``releases.json`` are never touched by staging. """ 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 c95b3267a6..188223fc59 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 @@ -15564,9 +15564,7 @@ def test_a_run_without_base_h5_reads_the_national_release_s_current_build( monkeypatch, tmp_path ) -> None: """Without --base-h5 a run starts from the US national release's current - build, SHA-verified by the loader: from releases.json once the repository - has one, from latest.json until then. The root file stops changing at the - switch, since builds in folders write no root files (microcosm#1570).""" + build in releases.json, SHA-verified by the loader (microcosm#1570).""" import microcosm.data builder = _load_builder_module() diff --git a/packages/microcosm-build/tests/golden/am_country_spec.json b/packages/microcosm-build/tests/golden/am_country_spec.json index ec1158f3b0..ba5fa651ca 100644 --- a/packages/microcosm-build/tests/golden/am_country_spec.json +++ b/packages/microcosm-build/tests/golden/am_country_spec.json @@ -1,6 +1,6 @@ { "country": "am", - "fingerprint": "f7a97654c879f5c68c24580f9017b02e2684b8c0ae732c500e63c7e98ae49719", + "fingerprint": "96776706a02c2ecd5fc89f805fa228ad77a5f792866782eaa4d00c4617492c88", "gate_ids": [ "calibration_per_family_fit", "national_and_marz_admin_aggregates", @@ -36,7 +36,7 @@ "country_package.json": "d16ce36bc7ea2fac4aaa43036cfea04b2c0f905a2e1682fe64665954bc1cd4b3", "gates.json": "ccfb0558558f2b0678637a3bebf0778a25e7a3b999981a0a20bc89f3e7b3d320", "geography_spine.json": "12ee8607f1a222b642cbc251d3fe51c209786b24542084a06249aab8c7ab2fa1", - "release_contract.json": "86339163c03eaa4d9abea5712546dc63697ea4223b8870d177f23b89a0098dbb", + "release_contract.json": "b100f504bd7a8f399ec6f83b39ad614676835d591a165a6e6e0a35cf6c16aa4c", "source_stages.json": "b18188b36fdb2f542487ddf271b95b12f77c19943c65dc801c4cc2e6af9e24aa", "spec/bundle.yaml": "694759e55693868e6b57779162a56b7e030fe449537be58c91fd03c101329dbd", "spec/catalogs.yaml": "4b989afb6abbbed16b17c5f3af155adb7b5f0d1320317b225cf0b995edf15e41", diff --git a/packages/microcosm-build/tests/golden/nz_country_spec.json b/packages/microcosm-build/tests/golden/nz_country_spec.json index c3e05fb14e..43128ff638 100644 --- a/packages/microcosm-build/tests/golden/nz_country_spec.json +++ b/packages/microcosm-build/tests/golden/nz_country_spec.json @@ -1,6 +1,6 @@ { "country": "nz", - "fingerprint": "d959b1042eae960bec85665b6e1db3b5e54523a463fc960d276ef5ac9fff4a34", + "fingerprint": "ec42d6b38abd2915b476675d80e02425b27a9c5757618280045e6035a1d8a72c", "gate_ids": [ "calibration_per_family_fit", "demography_per_family_fit", @@ -80,7 +80,7 @@ "reference_inventory.json": "f0078d9dd42dcc3088459c3e4e1278a8da5fe1506ba903f119cfe5be157c13b8", "reference_profiles.json": "dc3d81e6fdeae12b93176872de690e21424695209390b253a3490e65cfd5740c", "reference_selection.json": "fdd01757db3ade78db2c8a3ab5d2a90dd7dfdf43038fb259778cfd340ce5f443", - "release_contract.json": "6cd5e3a4a2bf30e4025e04e964c393b24040937d13db7e6a07b3966a55f3b114", + "release_contract.json": "0c2cf38da9ce619070f12a819556a9954ce92dcae9afde3006ee170d30e37ac4", "rent_bands.json": "1feccbe80fe662bf14a11ab1a3a4047dd8cf62d0f813112aa2aa248799e620ed", "reporting_classifiers.json": "60f0936a9cab3776affda81e2612174dbc2192947630e9cc037b9b11277ca4d2", "scenarios.json": "86e102bb3f301ee78238f020fef0839dbbad54b367b7b1e9ce7824956f2d1135", diff --git a/packages/microcosm-data/README.md b/packages/microcosm-data/README.md index 40a59c8b14..c516e32122 100644 --- a/packages/microcosm-data/README.md +++ b/packages/microcosm-data/README.md @@ -3,9 +3,9 @@ The distribution end of the [microcosm](https://github.com/PolicyEngine/microcosm) stack. The operator shards (`microcosm-frame`, `microcosm-fit`, `microcosm-calibrate`) *build* populations; `microcosm-data` *serves* the ones -microcosm has published — a registry of `(country, year, variant)` pointers to -artifacts on the Hugging Face Hub, and a loader that returns each as its -PolicyEngine engine dataset. +microcosm has published — a registry of `(country, year, variant)` entries, +each naming a release on the Hugging Face Hub, and a loader that returns a +release's build as its PolicyEngine engine dataset. ```bash pip install 'microcosm-data[us]' @@ -36,21 +36,18 @@ switch moved into folders; the loader accepts either name for a listed build `load("uk")` (the 2025 national release) and the 2025 dense variant read the UK repository's record the same way. `load("uk", 2023)` reads release `populace-uk-2023`: the UK repository's switch moved the June 2023 build into -it as its only and current build. An entry whose repository has no -`releases.json` follows its pointer file (`latest.json` or -`latest-.json`) and reads the manifest at the build's tag; no -registered entry's repository is still in that state. `available()` lists +it as its only and current build. Every registry entry names its release, +and the loader refuses a repository without `releases.json`; it reads no +`latest*.json` pointer file, which each repository's switch deleted. A build +published before its repository switched stays readable by its path at its +tag, outside the loader. `available()` lists the default-variant `(country, year)` pairs (the ones a bare ``load(country, year)`` resolves); `available_variants()` lists every registered `(country, year, variant)`, non-default lines included. -The old mutable-root behavior is an unsafe escape hatch, -`load("us", 2024, unverified_root=True)`, which emits a runtime warning because -it bypasses the release pointer, manifest, digest, and engine compatibility -checks. The loader refuses it for an entry whose repository records its builds -in `releases.json`, which every registered entry's repository does since the -UK and US switches. Builds published into folders write no root file, so the -US repository's root `populace_us_2024.h5` stopped changing at its switch, +No repository has a mutable root dataset file to load: builds published +into folders write no root file, so the US repository's root +`populace_us_2024.h5` stopped changing at its switch, and the switch tool's `delete-old-layout` step later deleted it. ## Why a shard, not a repo per country diff --git a/packages/microcosm-data/src/microcosm/data/__init__.py b/packages/microcosm-data/src/microcosm/data/__init__.py index 50c06c2cfd..4c333171ad 100644 --- a/packages/microcosm-data/src/microcosm/data/__init__.py +++ b/packages/microcosm-data/src/microcosm/data/__init__.py @@ -3,8 +3,9 @@ The distribution end of the stack. Where the operator shards (:mod:`microcosm.frame`, :mod:`microcosm.fit`, :mod:`microcosm.calibrate`) *build* populations, this shard *serves* the ones microcosm has published: a registry of -``(country, year, variant)`` pointers to artifacts on the Hugging Face Hub, and -a loader that returns each as the country engine's dataset object. +``(country, year, variant)`` entries, each naming a release on the Hugging Face +Hub, and a loader that returns a release's build as the country engine's +dataset object. >>> from policyengine_us import Microsimulation >>> from microcosm.data import load @@ -43,19 +44,7 @@ resolve, ) from microcosm.data.registry import DEFAULT_VARIANT, REGISTRY, DatasetSpec, register -from microcosm.data.release import ( - LATEST_EVIDENCE_POINTER_PATH, - LATEST_POINTER_PATH, - LATEST_POINTER_SCHEMA_VERSION, - RELEASE_TIER_CERTIFIED, - RELEASE_TIER_EVIDENCE, - LatestPointer, - latest_evidence_pointer_payload, - latest_evidence_release, - latest_pointer_payload, - latest_release, - publish_release, -) +from microcosm.data.release import publish_release __all__ = [ "load", @@ -78,16 +67,6 @@ "required_release_files", "validate_evidence_release_dir", "validate_release_dir", - "LATEST_EVIDENCE_POINTER_PATH", - "LATEST_POINTER_PATH", - "LATEST_POINTER_SCHEMA_VERSION", - "RELEASE_TIER_CERTIFIED", - "RELEASE_TIER_EVIDENCE", - "LatestPointer", - "latest_evidence_pointer_payload", - "latest_evidence_release", - "latest_pointer_payload", - "latest_release", "publish_release", ] diff --git a/packages/microcosm-data/src/microcosm/data/contract.py b/packages/microcosm-data/src/microcosm/data/contract.py index 8d85f060b1..f17a8dc37e 100644 --- a/packages/microcosm-data/src/microcosm/data/contract.py +++ b/packages/microcosm-data/src/microcosm/data/contract.py @@ -120,7 +120,6 @@ "compatibility_claim_declarer_error", "is_be_release", "is_us_release", - "line_for_release_id", "publishes_to_build_folder", "release_artifact_role", "release_dataset_role", @@ -189,7 +188,7 @@ def compatibility_claim_declarer_error(declared_by: object) -> str | None: # Dataset-role classes (microcosm#398). The national default keeps the full # historical contract; a non-default local-area artifact gets its own -# contract and can never move the latest.json pointer. +# contract and never takes the national default's place. NATIONAL_DEFAULT_DATASET_ROLE = "national_default" NON_DEFAULT_LOCAL_AREA_DATASET_ROLE = "non_default_local_area" @@ -1017,40 +1016,6 @@ def _is_hierarchy_diagnostics_version(value: object) -> bool: ) -def line_for_release_id(release_id: str) -> str | None: - """Return the ```` name of the ``latest-.json`` pointer file. - - Each such pointer file named the current build of one UK release before - those releases published into build folders: ``national`` for the national - release and ``local-k`` for a local-area one. Only the pointer reader - still needs it. - """ - if release_id == _UK_NATIONAL_RELEASE_ID: - return "national" - match = _UK_LOCAL_LINE_RELEASE_ID_RE.fullmatch(release_id) - if match is not None: - return f"local-k{match.group('n')}" - return None - - -def dataset_role_for_line(line: str) -> str: - """The one dataset role a publication line may carry. - - The national line carries national-default releases; every local-area - line carries non-default local-area releases. The loader refuses a - manifest that reached a ``latest-.json`` pointer with the wrong - role, so a local-area release can never ride the national pointer (or - the reverse) on the strength of its release id alone. Nothing writes - those pointers any more; the loader still follows them in a repository - that has no ``releases.json``. - """ - if line == "national": - return NATIONAL_DEFAULT_DATASET_ROLE - if re.fullmatch(r"local-k[1-9][0-9]*", line): - return NON_DEFAULT_LOCAL_AREA_DATASET_ROLE - raise ValueError(f"{line!r} is not a publication line.") - - # The dense joint national + local release (microcosm#762 A18, ruling # 2026-09-03): the same constant-id approach, published as a non-default # local-area release, each build into its own folder. Mirrored from @@ -1131,23 +1096,6 @@ def dataset_role_for_line(line: str) -> str: "uk_local_target_fit", "uk_input_mass_parity", ) -# The per-build tag shape UK national and local-area builds were tagged with -# before the switch: the release, then the calibration attempt's time and -# digest. The pointer-file reader and writer in microcosm.data.release check a -# latest-.json revision against it, so a hand-edited or stale pointer -# cannot name a tag outside the release's builds. -_UK_NATIONAL_REVISION_SUFFIX_RE = re.compile(r"[0-9]{8}T[0-9]{6}Z-[0-9a-f]{8}") - - -def _uk_line_cut_tag_re(release_id: str) -> re.Pattern[str] | None: - """Return the immutable cut-tag grammar for a promotable UK line.""" - if line_for_release_id(release_id) is None: - return None - return re.compile( - re.escape(release_id) + "-" + _UK_NATIONAL_REVISION_SUFFIX_RE.pattern - ) - - # The canonical release-dir filenames of the evidence the certification signs # (tools/assemble_uk_release_dir.py copies each byte-for-byte). Validation # binds every local file to its signed digest: a certification whose evidence @@ -7664,8 +7612,7 @@ def release_dataset_role(release_dir: Path | str) -> str: Read from ``release_manifest.json``'s ``dataset_role``. An absent field or unreadable manifest is the national default — the pre-role-class - shape — so every historical release keeps its meaning; the publish path - separately refuses pointer updates for any non-default role. + shape — so every historical release keeps its meaning. """ manifest_path = Path(release_dir) / "release_manifest.json" diff --git a/packages/microcosm-data/src/microcosm/data/loader.py b/packages/microcosm-data/src/microcosm/data/loader.py index a09d074e35..58142fc079 100644 --- a/packages/microcosm-data/src/microcosm/data/loader.py +++ b/packages/microcosm-data/src/microcosm/data/loader.py @@ -1,24 +1,18 @@ """Resolve, verify, download, and load a certified microcosm release. -A registry entry that names a release (the UK 2025 national and dense -entries, whose builds publish into their own folders, and the UK 2023 entry, -whose one build the switch moved into a folder) is read through the -repository's ``releases.json`` once the repository has one: the record names -the release's current build (or ``build=`` pins a listed one), the loader -reads ``releases///release_manifest.json``, downloads the -dataset that manifest names from the same folder, verifies its SHA-256, and -enforces the certified model/Core versions before constructing the engine -dataset. Build folders never change after publishing, so every file is read -at ``main``. - -A repository without ``releases.json`` (every repository until its switch to -build folders) follows the release certificate as before: resolve the -registry-selected pointer (``latest.json``, or a UK release's -``latest-.json``), read that release's manifest at the pointer's -immutable revision, download the manifest-selected dataset at the same -revision and check it the same way. Its mutable root artifacts are available -only through the explicitly unsafe ``load(..., unverified_root=True)`` escape -hatch; a repository with ``releases.json`` has no root file. +Every registry entry names a release, and the loader reads it through the +repository's ``releases.json``: the record names the release's current build +(or ``build=`` pins a listed one), the loader reads +``releases///release_manifest.json``, downloads the dataset +that manifest names from the same folder, verifies its SHA-256, and enforces +the certified model/Core versions before constructing the engine dataset. +Build folders never change after publishing, so every file is read at +``main``. + +A repository without ``releases.json`` is refused. The loader reads no +``latest*.json`` pointer file: each repository's switch to ``releases.json`` +deleted them. A build published before its repository switched stays +readable by its path at its tag, outside the loader. """ from __future__ import annotations @@ -32,7 +26,6 @@ from dataclasses import dataclass from importlib import metadata from pathlib import Path -from types import SimpleNamespace from typing import Any from packaging.specifiers import InvalidSpecifier, SpecifierSet @@ -44,19 +37,9 @@ NON_DEFAULT_LOCAL_AREA_DATASET_ROLE, RELEASE_MANIFEST_SCHEMA_VERSION, RELEASE_ROLES, - dataset_role_for_line, ) from microcosm.data.registry import DEFAULT_VARIANT, REGISTRY, DatasetSpec -from microcosm.data.release import ( - LATEST_POINTER_PATH, - LINE_POINTER_PATH_TEMPLATE, - LatestPointer, - latest_line_release, - latest_release, - line_pointer_path, - missing_on_hub, - never_cached_offline, -) +from microcosm.data.release import missing_on_hub, never_cached_offline from microcosm.data.releases_record import ( RELEASES_RECORD_PATH, build_folder, @@ -77,25 +60,9 @@ ] _SHA256_PATTERN = re.compile(r"[0-9a-fA-F]{64}") -_LINE_POINTER_PATH_PATTERN = re.compile( - re.escape(LINE_POINTER_PATH_TEMPLATE).replace(re.escape("{line}"), r"(?P.+)") -) _HubDownload = Callable[..., str] -def _line_from_pointer_path(pointer_path: str) -> str | None: - """Invert the shared line-pointer template and validate its line.""" - match = _LINE_POINTER_PATH_PATTERN.fullmatch(pointer_path) - if match is None: - return None - line = match.group("line") - try: - rendered_path = line_pointer_path(line) - except ValueError: - return None - return line if rendered_path == pointer_path else None - - @dataclass(frozen=True) class _PackageCertification: name: str @@ -107,9 +74,9 @@ class _PackageCertification: class CertifiedRelease: """A release's certified dataset: where it is and what it was built with. - For a build-folder release, ``build`` is the build that was loaded, - ``artifact_path`` is inside its folder and ``artifact_revision`` is - ``None`` (the folder never changes, so it is read at ``main``). + ``build`` is the build that was loaded, ``artifact_path`` is inside its + folder, and ``artifact_revision`` is ``None``: the folder never changes, + so it is read at ``main``. """ release_id: str @@ -247,7 +214,6 @@ def _package_certification( package_name: str, built_field: str, release_id: str, - build_folder: bool = False, ) -> _PackageCertification: entries = manifest.get(field) if not isinstance(entries, list): @@ -274,13 +240,8 @@ def _package_certification( ) # A build-folder manifest records what the build was built with at its - # top level; a tagged one, in its ``build`` object. - owner = ( - manifest - if build_folder - else _required_mapping(manifest, "build", release_id=release_id) - ) - built_package = _required_mapping(owner, built_field, release_id=release_id) + # top level. + built_package = _required_mapping(manifest, built_field, release_id=release_id) if built_package.get("name") != package_name: raise ValueError( f"Release {release_id!r} build provenance does not name {package_name}." @@ -308,15 +269,13 @@ def _certified_release_from_manifest( release_id: str, manifest: Mapping[str, Any], *, - expected_revision: str | None, - build: str | None = None, - release_role: str | None = None, + build: str, + release_role: str, ) -> _CertifiedRelease: - """Validate and select ``spec`` from one release manifest. + """Validate and select ``spec`` from one build's release manifest. - With ``build``, the manifest is that build's, read from its folder in a - build-folder release whose ``releases.json`` gives it ``release_role``; - otherwise it is a tagged release's, read at ``expected_revision``. + The manifest is that build's, read from its folder in a release whose + ``releases.json`` entry gives it ``release_role``. """ schema_version = manifest.get("schema_version") if schema_version != RELEASE_MANIFEST_SCHEMA_VERSION: @@ -325,23 +284,13 @@ def _certified_release_from_manifest( f"{schema_version!r}; this microcosm-data reads version " f"{RELEASE_MANIFEST_SCHEMA_VERSION}. Upgrade microcosm-data." ) - build_folder_release = build is not None - if build_folder_release: - folder = build_folder(release_id, build) - named = (manifest.get("release"), manifest.get("build")) - if named != (release_id, build): - raise ValueError( - f"{folder}/release_manifest.json names release {named[0]!r} and " - f"build {named[1]!r}, not {release_id!r} and {build!r}." - ) - else: - tagged_build = _required_mapping(manifest, "build", release_id=release_id) - if tagged_build.get("build_id") != release_id: - raise ValueError( - f"{spec.pointer_path} points to release {release_id!r}, but its " - "release manifest declares build_id " - f"{tagged_build.get('build_id')!r}." - ) + folder = build_folder(release_id, build) + named = (manifest.get("release"), manifest.get("build")) + if named != (release_id, build): + raise ValueError( + f"{folder}/release_manifest.json names release {named[0]!r} and " + f"build {named[1]!r}, not {release_id!r} and {build!r}." + ) dataset_role = manifest.get("dataset_role", NATIONAL_DEFAULT_DATASET_ROLE) if dataset_role not in { @@ -351,20 +300,7 @@ def _certified_release_from_manifest( raise ValueError( f"Release {release_id!r} has unknown dataset_role {dataset_role!r}." ) - pointer_line = ( - None if build_folder_release else _line_from_pointer_path(spec.pointer_path) - ) - if pointer_line is not None: - # A line pointer carries one role: the manifest it names must - # declare it, whatever its release id says. - expected_role = dataset_role_for_line(pointer_line) - if dataset_role != expected_role: - raise ValueError( - f"Release {release_id!r} declares dataset_role {dataset_role!r}; " - f"{spec.pointer_path!r} follows line {pointer_line!r}, which " - f"publishes only {expected_role!r} releases." - ) - if build_folder_release and release_role != RELEASE_ROLES[dataset_role]: + if release_role != RELEASE_ROLES[dataset_role]: # releases.json gives a release one role, so a manifest whose role # differs is not this release's, whatever its names say. raise ValueError( @@ -383,14 +319,6 @@ def _certified_release_from_manifest( ) artifact_label = "default" else: - if not build_folder_release and pointer_line is None: - raise ValueError( - f"Release {release_id!r} declares dataset_role " - f"{NON_DEFAULT_LOCAL_AREA_DATASET_ROLE!r}; a local-area release " - "is loaded from its build folder through releases.json, or " - f"through a {LINE_POINTER_PATH_TEMPLATE!r} line pointer, not " - f"{spec.pointer_path!r}." - ) if default_datasets != {}: raise ValueError( f"Release {release_id!r} declares dataset_role " @@ -400,40 +328,18 @@ def _certified_release_from_manifest( artifact_label = "local-area" artifacts = _required_mapping(manifest, "artifacts", release_id=release_id) - if build_folder_release: - # A build folder's files are found through releases.json; nothing is - # tagged, so a manifest that pins a revision is not this layout's. - pinned = sorted( - str(key) - for key, candidate in artifacts.items() - if not isinstance(candidate, Mapping) or "revision" in candidate + # A build folder's files are found through releases.json; nothing is + # tagged, so a manifest that pins a revision is not this layout's. + pinned = sorted( + str(key) + for key, candidate in artifacts.items() + if not isinstance(candidate, Mapping) or "revision" in candidate + ) + if pinned: + raise ValueError( + f"Release {release_id!r} build {build!r} pins a revision on " + f"artifact(s) {pinned}; a build folder's files carry none." ) - if pinned: - raise ValueError( - f"Release {release_id!r} build {build!r} pins a revision on " - f"artifact(s) {pinned}; a build folder's files carry none." - ) - else: - # One revision per pointer, by intent: the loader follows a pointer - # to a single immutable revision and downloads every artifact of the - # release from it, so every artifact must be pinned to exactly that - # revision. This is stricter than the publisher contract's - # annual-revision allowance for mixed-revision releases; a release - # that mixes revisions is publishable for inspection but never - # resolvable as a default here. - mismatched_revisions = { - str(key): candidate.get("revision") - if isinstance(candidate, Mapping) - else None - for key, candidate in artifacts.items() - if not isinstance(candidate, Mapping) - or candidate.get("revision") != expected_revision - } - if mismatched_revisions: - raise ValueError( - f"Release {release_id!r} has artifacts not pinned to expected " - f"revision {expected_revision!r}: {mismatched_revisions}." - ) if dataset_role == NON_DEFAULT_LOCAL_AREA_DATASET_ROLE: microdata_keys = [ key @@ -459,7 +365,7 @@ def _certified_release_from_manifest( f"Release {release_id!r} {artifact_label} artifact {artifact_key!r} has kind " f"{artifact.get('kind')!r}, not 'microdata'." ) - if build_folder_release and artifact.get("role") != DATASET_FILE_ROLE: + if artifact.get("role") != DATASET_FILE_ROLE: raise ValueError( f"Release {release_id!r} {artifact_label} artifact {artifact_key!r} has " f"role {artifact.get('role')!r}, not {DATASET_FILE_ROLE!r}." @@ -474,11 +380,8 @@ def _certified_release_from_manifest( f"{artifact_repo_id!r} " f"does not match registry repo {spec.hf_repo!r}." ) - accepted_paths = ( - spec.dataset_filenames if build_folder_release else (spec.filename,) - ) - if artifact_path not in accepted_paths: - expected = " or ".join(repr(name) for name in accepted_paths) + if artifact_path not in spec.dataset_filenames: + expected = " or ".join(repr(name) for name in spec.dataset_filenames) raise ValueError( f"Release {release_id!r} {artifact_label} artifact path {artifact_path!r} " f"does not match registry filename {expected}." @@ -496,7 +399,6 @@ def _certified_release_from_manifest( package_name=spec.engine_package, built_field="built_with_model_package", release_id=release_id, - build_folder=build_folder_release, ) core = _package_certification( manifest, @@ -504,27 +406,16 @@ def _certified_release_from_manifest( package_name="policyengine-core", built_field="built_with_core_package", release_id=release_id, - build_folder=build_folder_release, ) - if build_folder_release: - return _CertifiedRelease( - release_id=release_id, - artifact_repo_id=artifact_repo_id, - artifact_path=f"{folder}/{artifact_path}", - artifact_revision=None, - artifact_sha256=artifact_sha256.lower(), - model=model, - core=core, - build=build, - ) return _CertifiedRelease( release_id=release_id, artifact_repo_id=artifact_repo_id, - artifact_path=artifact_path, - artifact_revision=artifact.get("revision"), + artifact_path=f"{folder}/{artifact_path}", + artifact_revision=None, artifact_sha256=artifact_sha256.lower(), model=model, core=core, + build=build, ) @@ -536,48 +427,32 @@ def _sha256(path: Path) -> str: return digest.hexdigest() -def _pointer_for( - spec: DatasetSpec, *, hub_download: _HubDownload | None = None -) -> LatestPointer: - """Read the release pointer configured for ``spec``.""" - if hub_download is None: - hub_download = _hub_download() - api = SimpleNamespace(hf_hub_download=hub_download) - if spec.pointer_path == LATEST_POINTER_PATH: - return latest_release(spec.hf_repo, api=api) - line = _line_from_pointer_path(spec.pointer_path) - if line is not None: - return latest_line_release( - spec.hf_repo, - line=line, - api=api, - ) - raise ValueError( - f"Unsupported release pointer path {spec.pointer_path!r} for {spec.key}; " - f"expected {LATEST_POINTER_PATH!r} or the " - f"{LINE_POINTER_PATH_TEMPLATE!r} line-pointer form." - ) - - -def _releases_record_bytes( - spec: DatasetSpec, *, hub_download: _HubDownload -) -> bytes | None: - """The repository's ``releases.json``, or ``None`` when it has none. +def _releases_record_bytes(spec: DatasetSpec, *, hub_download: _HubDownload) -> bytes: + """The repository's ``releases.json``, refused when it has none. - Until its switch to build folders a repository has no ``releases.json``, - and its releases are found through their pointer files. Only the Hub's - answer that the file is absent (:func:`~microcosm.data.release.missing_on_hub`) - means that, or, in offline mode, a file that was never cached. Any other - failure propagates, a server error included: falling back then would load - the pointer file's build in a repository that has switched. + Every release repository lists its builds there, so a repository without + it is not one the loader reads. The Hub's answer that the file is absent + (:func:`~microcosm.data.release.missing_on_hub`), or, in offline mode, a + file that was never cached, is refused with that reason; any other + failure propagates, a server error included. """ try: record_path = hub_download( repo_id=spec.hf_repo, filename=RELEASES_RECORD_PATH, repo_type="dataset" ) except Exception as exc: - if missing_on_hub(exc) or never_cached_offline(exc): - return None + if never_cached_offline(exc): + raise ValueError( + f"{RELEASES_RECORD_PATH} of {spec.hf_repo} is not in the Hugging " + "Face cache, and the Hub cannot be asked in offline mode; read " + f"it once online to load {spec.release!r} offline." + ) from exc + if missing_on_hub(exc): + raise ValueError( + f"{spec.hf_repo} has no {RELEASES_RECORD_PATH}, so it lists no " + f"build of {spec.release!r}; the loader reads builds only " + f"through a repository's {RELEASES_RECORD_PATH}." + ) from exc raise return Path(record_path).read_bytes() @@ -596,7 +471,6 @@ def _resolve_build_folder_release( choice. """ release = spec.release - assert release is not None try: record = parse_releases_record(record_bytes) except ValueError as exc: @@ -641,7 +515,6 @@ def _resolve_build_folder_release( spec, release, manifest, - expected_revision=None, build=build, release_role=entry.role, ) @@ -653,54 +526,15 @@ def _resolve_certified_release( hub_download: _HubDownload | None = None, build: str | None = None, ) -> _CertifiedRelease: - """Resolve and validate the release's selected build and its manifest. - - An entry that names a release reads the repository's ``releases.json`` - when it has one. Otherwise, and for every other entry, the loader follows - the entry's pointer to a pinned manifest, and ``build`` cannot pin a - build. - """ - if spec.release is None and build is not None: - raise ValueError( - f"{spec.key} keeps the tagged layout; build= pins a build only for " - "releases whose builds publish into their own folders." - ) + """Resolve and validate the release's selected build and its manifest, + read through the repository's ``releases.json``.""" if hub_download is None: hub_download = _hub_download() - if spec.release is not None: - record_bytes = _releases_record_bytes(spec, hub_download=hub_download) - if record_bytes is not None: - return _resolve_build_folder_release( - spec, - record_bytes=record_bytes, - build=build, - hub_download=hub_download, - ) - if build is not None: - raise ValueError( - f"{spec.hf_repo} has no releases.json yet, so build= cannot pin a " - f"build of {spec.release!r}; its current build is the one " - f"{spec.pointer_path} names." - ) - pointer = _pointer_for(spec, hub_download=hub_download) - manifest_path = Path( - hub_download( - repo_id=spec.hf_repo, - filename=pointer.paths["release_manifest"], - repo_type="dataset", - revision=pointer.revision, - ) - ) - manifest = _load_manifest( - manifest_path, - repo_id=spec.hf_repo, - release_id=pointer.release_id, - ) - return _certified_release_from_manifest( + return _resolve_build_folder_release( spec, - pointer.release_id, - manifest, - expected_revision=pointer.revision, + record_bytes=_releases_record_bytes(spec, hub_download=hub_download), + build=build, + hub_download=hub_download, ) @@ -731,16 +565,6 @@ def _verified_download( return artifact_path, certified -def _unverified_root_download(spec: DatasetSpec) -> Path: - return Path( - _hub_download()( - repo_id=spec.hf_repo, - filename=spec.filename, - repo_type="dataset", - ) - ) - - def download( country: str, year: int | None = None, @@ -750,17 +574,15 @@ def download( ) -> Path: """Download and SHA-verify a certified release artifact. - Where the repository has ``releases.json``, a release's current build - (or the listed ``build`` it pins) comes from it, and its manifest and - dataset from that build's folder. Otherwise the entry's mutable pointer - selects a release; - both its manifest and dataset artifact are then fetched at the pointer's - immutable revision. Uses the Hugging Face cache, so repeated calls do not + The repository's ``releases.json`` names the release's current build (or + lists the ``build`` it pins), and its manifest and dataset come from that + build's folder. Uses the Hugging Face cache, so repeated calls do not re-download unchanged files. Raises: ImportError: If ``huggingface_hub`` is not installed. - ValueError: If release metadata or the artifact digest is invalid. + ValueError: If the repository has no ``releases.json``, or release + metadata or the artifact digest is invalid. """ spec = resolve(country, year, variant=variant) path, _ = _verified_download(spec, build=build) @@ -822,13 +644,13 @@ def download_build_file( changes after publishing. Raises: - ValueError: If the release keeps the tagged layout (no build folder), - the manifest declares no such artifact, or its digest differs. + ValueError: If ``certified`` names no build, the manifest declares no + such artifact, or its digest differs. """ if certified.build is None: raise ValueError( - f"Release {certified.release_id!r} keeps the tagged layout; only a " - "build published into its own folder declares its files there." + f"The record of release {certified.release_id!r} names no build; " + "only a build in its own folder declares its files there." ) if hub_download is None: hub_download = _hub_download() @@ -925,7 +747,6 @@ def load( year: int | None = None, *, variant: str = DEFAULT_VARIANT, - unverified_root: bool = False, build: str | None = None, ): """Return a certified population as its engine dataset object. @@ -935,43 +756,16 @@ def load( year: Population year; ``None`` loads the latest published year. variant: Dataset variant; ``"compact"`` is the default fast national microsimulation artifact. - unverified_root: Load the mutable root convenience artifact while - bypassing release metadata, SHA-256, and engine certification. - This unsafe compatibility escape hatch emits a loud warning; a - repository that records its builds in ``releases.json`` has no - root file. - build: Load this listed build of a release recorded in the - repository's ``releases.json`` instead of its current one. + build: Load this listed build of the release instead of its current + one. Raises: ImportError: If the country engine is not installed. ValueError: If release verification or engine compatibility fails. """ spec = resolve(country, year, variant=variant) - if unverified_root and build is not None: - raise ValueError("unverified_root cannot be combined with build=.") - if ( - unverified_root - and spec.release is not None - and _releases_record_bytes(spec, hub_download=_hub_download()) is not None - ): - raise ValueError( - f"{spec.hf_repo} records the builds of {spec.release!r} in " - "releases.json, and has no root file to load unverified; load a " - "build without unverified_root." - ) dataset_class = _dataset_class(spec) - if unverified_root: - warnings.warn( - "UNVERIFIED mutable-root loading bypasses latest.json, the release " - "manifest, artifact SHA-256, and model/Core compatibility checks. " - "Do not use this path for production or reproducible analysis.", - RuntimeWarning, - stacklevel=2, - ) - path = _unverified_root_download(spec) - else: - path, certified = _verified_download(spec, build=build) - _enforce_package_compatibility(certified.model, release_id=certified.release_id) - _enforce_package_compatibility(certified.core, release_id=certified.release_id) + path, certified = _verified_download(spec, build=build) + _enforce_package_compatibility(certified.model, release_id=certified.release_id) + _enforce_package_compatibility(certified.core, release_id=certified.release_id) return dataset_class(file_path=str(path)) diff --git a/packages/microcosm-data/src/microcosm/data/registry.py b/packages/microcosm-data/src/microcosm/data/registry.py index 50c152c3ea..0df366eb12 100644 --- a/packages/microcosm-data/src/microcosm/data/registry.py +++ b/packages/microcosm-data/src/microcosm/data/registry.py @@ -24,7 +24,7 @@ @dataclass(frozen=True) class DatasetSpec: - """A pointer to one published microcosm population and how to read it. + """One published microcosm population and how to read it. Attributes: country: ISO-style country slug (lowercase), e.g. ``"us"``. The first @@ -54,17 +54,13 @@ class DatasetSpec: engine_package: The pip package providing the engine, e.g. ``"policyengine-us"`` — named in the install extra and in the ImportError when the engine is absent. - pointer_path: The repository-root release pointer followed by the - certified loader while the repository has no ``releases.json``. - release: The release the loader reads through ``releases.json``, - whose builds are in ``releases///``: one whose - builds publish into their own folders, or ``populace-uk-2023``, - whose one build the switch moved into a folder. Where the - repository has ``releases.json``, the loader reads the release's - current build there and loads ``filename`` from that build's - folder; until the repository switches to it, the loader follows - ``pointer_path``. ``None`` for a release that keeps the tagged - layout. + release: The release the loader reads through the repository's + ``releases.json``, whose builds are in + ``releases///``: one whose builds publish into + their own folders, or ``populace-uk-2023``, whose one build the + switch moved into a folder. The loader reads the release's + current build there (or a listed build that ``build=`` pins) and + loads ``filename`` from that build's folder. """ country: str @@ -74,9 +70,8 @@ class DatasetSpec: engine_module: str engine_class: str engine_package: str + release: str variant: str = DEFAULT_VARIANT - pointer_path: str = "latest.json" - release: str | None = None build_folder_filename: str | None = None @property @@ -127,11 +122,9 @@ def register(spec: DatasetSpec) -> DatasetSpec: register( DatasetSpec( # The June 2023 build, populace-uk-2023-dd68c73-4aa4b14-20260619T023711Z. - # Until its repository switches to releases.json, the loader follows - # latest.json, which names it. The switch moves it into its own folder - # as the only and current build of release populace-uk-2023, under its - # old release ID, and deletes latest.json; the loader then reads it - # there. No new builds publish to this release. + # The UK switch moved it into its own folder as the only and current + # build of release populace-uk-2023, under its old release ID; the + # loader reads it there. No new builds publish to this release. country="uk", year=2023, variant=DEFAULT_VARIANT, @@ -146,15 +139,12 @@ def register(spec: DatasetSpec) -> DatasetSpec: register( DatasetSpec( - # microcosm#823: the UK 2024-25 national line, followed through its - # own pointer, is the default UK load. It stayed off the default - # variant until its first certified cut was promoted (review of #966; - # Max's #823 ruling), and latest-national.json has named - # microcosm-uk-2024-25-national-20261025T091414Z-a6299504 since - # 2026-10-26. resolve("uk") picks the latest default-variant year, so - # it loads this line; the June 2023 artifact stays at ("uk", 2023). - # Once the repository switches to releases.json, the loader reads the - # release's current build there instead. + # microcosm#823: the UK 2024-25 national release is the default UK + # load. It stayed off the default variant until its first certified + # build was made current (review of #966; Max's #823 ruling). + # resolve("uk") picks the latest default-variant year, so it loads + # this release's current build in releases.json; the June 2023 + # artifact stays at ("uk", 2023). country="uk", year=2025, variant=DEFAULT_VARIANT, @@ -163,19 +153,16 @@ def register(spec: DatasetSpec) -> DatasetSpec: engine_module="policyengine_uk.data", engine_class="UKSingleYearDataset", engine_package="policyengine-uk", - pointer_path="latest-national.json", release="microcosm-uk-2024-25-national", ) ) register( DatasetSpec( - # microcosm#762 A18: the dense joint national + local UK build. Before - # the switch its builds were tags only, with no pointer file. It + # microcosm#762 A18: the dense joint national + local UK build. It # carries every constituency and local authority at K=15 clones per - # spine household. Once the repository - # switches to releases.json, a new dense build becomes current when it - # is promoted, or published with --make-current, through + # spine household. A new dense build becomes current when it is + # promoted, or published with --make-current, through # microcosm-publish-release-build, and the loader reads it there. country="uk", year=2025, @@ -189,11 +176,10 @@ def register(spec: DatasetSpec) -> DatasetSpec: ) ) -# microcosm#898 reserves the local-area line as variant "local", with pointer -# latest-local-k.json and artifact microcosm_uk_2024_25_local_k.h5, and -# the release microcosm-uk-2024-25-local-k once its repository records -# builds in releases.json. The pull request that authorizes a k's first -# publication adds its registry entry (docs/release-contract.md, C5). +# microcosm#898 reserves the UK local-area releases as variant "local", with +# artifact microcosm_uk_2024_25_local_k.h5 and release +# microcosm-uk-2024-25-local-k. 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. @@ -207,10 +193,9 @@ def register(spec: DatasetSpec) -> DatasetSpec: engine_module="policyengine_us.data", engine_class="USSingleYearDataset", engine_package="policyengine-us", - # Every US national build goes into this release once the repository - # records its builds in releases.json (microcosm#1570); until then - # the loader follows latest.json. New builds declare the new file - # name; the builds the switch moved keep populace_us_2024.h5. + # Every US national build goes into this release (microcosm#1570). + # New builds declare the new file name; the builds the switch moved + # keep populace_us_2024.h5. release="microcosm-us-2024-national", build_folder_filename="microcosm_us_2024.h5", ) diff --git a/packages/microcosm-data/src/microcosm/data/release.py b/packages/microcosm-data/src/microcosm/data/release.py index 920b0ed30a..243bc3f16b 100644 --- a/packages/microcosm-data/src/microcosm/data/release.py +++ b/packages/microcosm-data/src/microcosm/data/release.py @@ -23,34 +23,24 @@ ``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. +:func:`publish_release` 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. + +Microcosm reads no pointer file. Every release repository lists its builds +in ``releases.json``, and each repository's switch to it deleted its +``latest.json``, the UK releases' ``latest-.json`` files and the US +repository's ``latest-evidence.json``. 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 +moved was ``latest-evidence.json``, never ``latest.json``. 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. +current build in ``releases.json`` took the place of ``latest-evidence.json``. 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 — @@ -75,14 +65,11 @@ BUILD_MANIFEST_FILE_ROLE, CHECKSUMS_FILE, CHECKSUMS_FILE_ROLE, - EVIDENCE_RELEASE_ID_SEGMENT, NATIONAL_DEFAULT_DATASET_ROLE, RELEASE_MANIFEST_FILE_ROLE, RELEASE_ROLES, US_EVIDENCE_RELEASE_ID, US_RELEASES, - _uk_line_cut_tag_re, - line_for_release_id, publishes_to_build_folder, release_dataset_role, required_release_files, @@ -90,11 +77,7 @@ validate_evidence_release_dir, validate_release_dir, ) -from microcosm.data.releases_record import ( - RELEASES_RECORD_PATH, - build_folder, - parse_releases_record, -) +from microcosm.data.releases_record import RELEASES_RECORD_PATH from microcosm.data.slack import notify_release __all__ = [ @@ -104,36 +87,24 @@ "LATEST_EVIDENCE_POINTER_PATH", "LATEST_POINTER_PATH", "LATEST_POINTER_SCHEMA_VERSION", - "LINE_POINTER_PATH_TEMPLATE", - "RELEASE_TIER_CERTIFIED", "RELEASE_TIER_EVIDENCE", "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", - "line_pointer_path", "missing_on_hub", "not_a_build_folder_release_reason", - "line_pointer_payload", "publish_release", - "latest_release", - "latest_evidence_release", ] #: Where the pointer lives in the dataset repo. The root, not a release #: directory: the pointer is repo state, not release state. LATEST_POINTER_PATH = "latest.json" -#: Per-line pointers coexist with the frozen repository-global pointer. -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 @@ -146,47 +117,12 @@ #: consumers guessing (the same discipline the release manifest learned). LATEST_POINTER_SCHEMA_VERSION = 1 -#: Publication tiers (microcosm#506). Certified is the default everywhere; -#: the evidence tier is opted into explicitly and carries its tier in the -#: pointer payload, the release id, and the release manifest. -RELEASE_TIER_CERTIFIED = "certified" +#: The evidence publication tier (microcosm#506), opted into explicitly; it +#: carries its tier in the pointer payload, the release id, and the release +#: manifest. RELEASE_TIER_EVIDENCE = "evidence" -@dataclass(frozen=True) -class LatestPointer: - """A parsed release pointer: which release is current, and where. - - Attributes: - release_id: The current build id (the ``releases/`` directory name). - updated_at: ISO-8601 UTC timestamp of when the pointer was written. - paths: Repo-relative path of each contract file, keyed by its stem - (``"build_manifest"``, ``"release_manifest"``, - ``"calibration_diagnostics"``, plus country-specific contract - files such as US source coverage). - tier: The publication tier the pointer names — - :data:`RELEASE_TIER_CERTIFIED` for ``latest.json`` (whose payload - predates tiers and carries no field), or - :data:`RELEASE_TIER_EVIDENCE` for ``latest-evidence.json``. - revision: Revision to fetch. Repository-global and evidence - pointers default to ``release_id``, an immutable tag; a line - pointer may name another tag; an evidence build in a build folder - is read at ``main``, at which its folder never changes. - line: Publication line for ``latest-.json``; otherwise ``None``. - """ - - release_id: str - updated_at: str - paths: dict[str, str] - tier: str = RELEASE_TIER_CERTIFIED - revision: str | None = None - line: str | None = None - - def __post_init__(self) -> None: - if self.revision is None: - object.__setattr__(self, "revision", self.release_id) - - def latest_pointer_payload( release_id: str, *, @@ -218,61 +154,6 @@ def latest_pointer_payload( } -def line_pointer_path(line: str) -> str: - """Return the reserved root pointer path for a publication line.""" - if _LINE_RE.fullmatch(line) is None: - raise ValueError( - f"invalid release line {line!r}; expected ^[a-z]+(-k[1-9][0-9]*)?$" - ) - if line == "evidence": - # The grammar would render latest-evidence.json, the evidence-tier - # pointer: refused at the grammar, not only downstream. - raise ValueError( - "release line 'evidence' collides with the evidence-tier pointer " - f"{LATEST_EVIDENCE_POINTER_PATH}; it is not a publication line." - ) - return LINE_POINTER_PATH_TEMPLATE.format(line=line) - - -def line_pointer_payload( - release_id: str, - *, - line: str, - revision: str, - updated_at: str | None = None, - calibration_diagnostics_available: bool = True, -) -> dict: - """Build a schema-1 per-line pointer naming an immutable revision.""" - line_pointer_path(line) - expected_line = line_for_release_id(release_id) - if line != expected_line: - raise ValueError( - f"release {release_id!r} belongs to line {expected_line!r}, not {line!r}." - ) - cut_tag_re = _uk_line_cut_tag_re(release_id) - if ( - not isinstance(revision, str) - or not revision - or not ( - revision == release_id - or (cut_tag_re is not None and cut_tag_re.fullmatch(revision) is not None) - ) - ): - raise ValueError( - f"revision {revision!r} is not the release id {release_id!r} or " - "a per-cut tag in that release's line family." - ) - return { - **latest_pointer_payload( - release_id, - updated_at=updated_at, - calibration_diagnostics_available=calibration_diagnostics_available, - ), - "line": line, - "revision": revision, - } - - def latest_evidence_pointer_payload( release_id: str, *, @@ -1516,135 +1397,11 @@ def _create_release_tag( 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: - api = _hf_api() - local = api.hf_hub_download( - repo_id=repo_id, filename=pointer_path, repo_type="dataset" - ) - payload = json.loads(Path(local).read_text()) - schema_version = payload.get("schema_version") - if schema_version != LATEST_POINTER_SCHEMA_VERSION: - raise ValueError( - f"{pointer_path} in {repo_id} has schema_version " - f"{schema_version!r}; this microcosm-data reads version " - f"{LATEST_POINTER_SCHEMA_VERSION}. Upgrade microcosm-data." - ) - release_id = payload.get("release_id") - if not release_id: - raise ValueError(f"{pointer_path} in {repo_id} has no 'release_id'.") - paths = payload.get("paths") - if not isinstance(paths, dict): - raise ValueError(f"{pointer_path} in {repo_id} has no 'paths' object.") - expected_paths = latest_pointer_payload(str(release_id), updated_at="")["paths"] - observed_paths = {str(key): value for key, value in paths.items()} - missing_paths = sorted(set(expected_paths) - set(observed_paths)) - if missing_paths == ["calibration_diagnostics"]: - missing_paths = [] - unexpected_paths = sorted(set(observed_paths) - set(expected_paths)) - malformed_paths = sorted( - key - for key in set(expected_paths) & set(observed_paths) - if observed_paths[key] != expected_paths[key] - ) - if missing_paths or unexpected_paths or malformed_paths: - raise ValueError( - f"{pointer_path} in {repo_id} has incomplete paths: " - f"missing={missing_paths}, unexpected={unexpected_paths}, " - f"malformed={malformed_paths}." - ) - return payload - - -def latest_release(repo_id: str, *, api=None) -> LatestPointer: - """Read ``latest.json`` from a dataset repo: which release is current. - - Args: - repo_id: Hub dataset repo, e.g. ``"policyengine/populace-us"``. - api: A ``huggingface_hub.HfApi``-shaped object (anything with - ``hf_hub_download(repo_id=, filename=, repo_type=)``); - constructed lazily when omitted. - - Raises: - ValueError: If the pointer is malformed, its schema version is newer - than this library understands, or it carries a ``tier``, ``line``, - or ``revision`` field. Those fields belong to other pointer - families and must never be consumed as the certified default. - """ - payload = _read_pointer(repo_id, api, pointer_path=LATEST_POINTER_PATH) - if "tier" in payload: - raise ValueError( - f"{LATEST_POINTER_PATH} in {repo_id} carries a 'tier' field " - f"({payload.get('tier')!r}); the certified pointer never does — " - f"evidence releases live at {LATEST_EVIDENCE_POINTER_PATH}." - ) - for field in ("line", "revision"): - if field in payload: - raise ValueError( - f"{LATEST_POINTER_PATH} in {repo_id} carries a {field!r} field; " - "the repository-global certified pointer never does." - ) - return LatestPointer( - release_id=str(payload["release_id"]), - updated_at=str(payload.get("updated_at", "")), - paths={str(k): str(v) for k, v in payload["paths"].items()}, - tier=RELEASE_TIER_CERTIFIED, - revision=str(payload["release_id"]), - ) - - -def latest_line_release(repo_id: str, *, line: str, api=None) -> LatestPointer: - """Read and validate the schema-1 pointer for ``line``.""" - pointer_path = line_pointer_path(line) - payload = _read_pointer(repo_id, api, pointer_path=pointer_path) - if "tier" in payload: - raise ValueError( - f"{pointer_path} in {repo_id} carries a 'tier' field; line pointers " - "are certified pointers, not evidence pointers." - ) - pointer_line = payload.get("line") - if pointer_line != line: - raise ValueError( - f"{pointer_path} in {repo_id} declares line {pointer_line!r}, " - f"expected {line!r}." - ) - release_id = str(payload["release_id"]) - revision = payload.get("revision") - expected_line = line_for_release_id(release_id) - if line != expected_line: - raise ValueError( - f"{pointer_path} in {repo_id} names release {release_id!r}, which " - f"belongs to line {expected_line!r}, not {line!r}." - ) - cut_tag_re = _uk_line_cut_tag_re(release_id) - if ( - not isinstance(revision, str) - or not revision - or not ( - revision == release_id - or (cut_tag_re is not None and cut_tag_re.fullmatch(revision) is not None) - ) - ): - raise ValueError( - f"{pointer_path} in {repo_id} has revision {revision!r}, which is " - f"outside release {release_id!r}'s line family." - ) - return LatestPointer( - release_id=release_id, - updated_at=str(payload.get("updated_at", "")), - paths={str(k): str(v) for k, v in payload["paths"].items()}, - tier=RELEASE_TIER_CERTIFIED, - revision=revision, - line=line, - ) - - def never_cached_offline(error: BaseException) -> bool: """Whether huggingface_hub is offline and the file was never cached. - Offline, the cache is all a reader has, so a ``releases.json`` that was - never cached reads as absent, as the pointer files then do. + Offline, the cache is all a reader has, so the loader refuses a + ``releases.json`` that was never cached, saying so. """ try: from huggingface_hub import constants @@ -1652,109 +1409,3 @@ def never_cached_offline(error: BaseException) -> bool: except ImportError: # pragma: no cover - declared dependency return False return bool(constants.HF_HUB_OFFLINE) and isinstance(error, LocalEntryNotFoundError) - - -def _releases_record_bytes(api: object, *, repo_id: str) -> bytes | None: - """The repository's ``releases.json``, or ``None`` when the Hub says it - has none, or, offline, when it was never cached - (:func:`never_cached_offline`); any other failure to read it propagates.""" - try: - local = api.hf_hub_download( - repo_id=repo_id, filename=RELEASES_RECORD_PATH, repo_type="dataset" - ) - except Exception as exc: - if missing_on_hub(exc) or never_cached_offline(exc): - return None - raise - return Path(local).read_bytes() - - -def _current_evidence_build(repo_id: str, record_bytes: bytes) -> LatestPointer: - """The evidence release's current build in ``releases.json``, as a pointer.""" - try: - record = parse_releases_record(record_bytes) - except ValueError as exc: - raise ValueError( - f"{RELEASES_RECORD_PATH} in {repo_id} is not a valid release record: {exc}." - ) from exc - release = US_EVIDENCE_RELEASE_ID - entry = record.releases.get(release) - if entry is None: - raise ValueError( - f"{RELEASES_RECORD_PATH} in {repo_id} does not list the evidence " - f"release {release!r}." - ) - build = entry.current - if build is None: - raise ValueError( - f"The evidence release {release!r} in {repo_id} has no current build." - ) - folder = build_folder(release, build) - paths = { - stem: f"{folder}/{posixpath.basename(path)}" - for stem, path in latest_pointer_payload(build, updated_at="")["paths"].items() - } - return LatestPointer( - release_id=build, - updated_at=entry.builds[build].published_at, - paths=paths, - tier=RELEASE_TIER_EVIDENCE, - revision="main", - ) - - -def latest_evidence_release(repo_id: str, *, api=None) -> LatestPointer: - """Read ``latest-evidence.json``: the best *current* evidence release. - - The evidence-tier sibling of :func:`latest_release` (microcosm#506) — how - consumers discover the best available artifact when no certified release - carries it yet. Each evidence publish supersedes the last, so this - pointer always names the current one. - - A repository that records its builds in ``releases.json`` (the US - repository since its switch, microcosm#1570) has no - ``latest-evidence.json``: its evidence tier is - :data:`~microcosm.data.contract.US_EVIDENCE_RELEASE_ID`, and this returns - that release's current build. ``release_id`` is then the build, - ``paths`` are in its folder ``releases///``, - ``revision`` is ``main``, at which a build folder never changes, and - ``updated_at`` is when the build was published. - - Args: - repo_id: Hub dataset repo, e.g. ``"policyengine/populace-us"``. - api: A ``huggingface_hub.HfApi``-shaped object (anything with - ``hf_hub_download(repo_id=, filename=, repo_type=)``); - constructed lazily when omitted. - - Raises: - ValueError: If the pointer is malformed, does not declare the - evidence tier, or names a release id without the - ``-evidence-`` segment; or, with ``releases.json``, if the - evidence release is not listed or has no current build. - """ - if api is None: - api = _hf_api() - record_bytes = _releases_record_bytes(api, repo_id=repo_id) - if record_bytes is not None: - return _current_evidence_build(repo_id, record_bytes) - payload = _read_pointer(repo_id, api, pointer_path=LATEST_EVIDENCE_POINTER_PATH) - tier = payload.get("tier") - if tier != RELEASE_TIER_EVIDENCE: - raise ValueError( - f"{LATEST_EVIDENCE_POINTER_PATH} in {repo_id} declares tier " - f"{tier!r}; the evidence pointer must declare " - f"{RELEASE_TIER_EVIDENCE!r}." - ) - release_id = str(payload["release_id"]) - if EVIDENCE_RELEASE_ID_SEGMENT not in release_id: - raise ValueError( - f"{LATEST_EVIDENCE_POINTER_PATH} in {repo_id} names release " - f"{release_id!r}, which does not carry the " - f"{EVIDENCE_RELEASE_ID_SEGMENT!r} segment." - ) - return LatestPointer( - release_id=release_id, - updated_at=str(payload.get("updated_at", "")), - paths={str(k): str(v) for k, v in payload["paths"].items()}, - tier=RELEASE_TIER_EVIDENCE, - ) diff --git a/packages/microcosm-data/tests/engine_free/shared/test_contract.py b/packages/microcosm-data/tests/engine_free/shared/test_contract.py index b49ab15377..a65986b736 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_contract.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_contract.py @@ -2445,19 +2445,6 @@ def test_real_june_release_validates_with_legacy_schema_and_selector_shapes( ) -@pytest.mark.parametrize( - ("release_id", "line"), - [ - (UK_NATIONAL_RELEASE_ID, "national"), - ("microcosm-uk-2024-25-local-k55000", "local-k55000"), - ("microcosm-uk-2024-25-dense", None), - (UK_RELEASE_ID, None), - ], -) -def test_line_for_release_id(release_id: str, line: str | None) -> None: - assert contract.line_for_release_id(release_id) == line - - def test_uk_national_release_dir_validates(tmp_path: Path) -> None: validate_release_dir(_write_uk_national_release_dir(tmp_path)) diff --git a/packages/microcosm-data/tests/engine_free/shared/test_loader.py b/packages/microcosm-data/tests/engine_free/shared/test_loader.py index 5474cbabaa..2b4046d189 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_loader.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_loader.py @@ -6,7 +6,6 @@ import json import os import re -from dataclasses import replace from importlib import metadata from pathlib import Path from types import SimpleNamespace @@ -26,12 +25,6 @@ NON_DEFAULT_LOCAL_AREA_DATASET_ROLE, ) from microcosm.data.registry import DatasetSpec -from microcosm.data.release import ( - LATEST_POINTER_PATH, - latest_pointer_payload, - line_pointer_path, - line_pointer_payload, -) from test_support.microcosm_data.build_folders import ( UK_LOCAL_BUILD, UK_NATIONAL_BUILD, @@ -39,25 +32,19 @@ ) from test_support.microcosm_data.hub_errors import hub_unreachable, missing_on_hub -#: Release id served by the hub fixture. Any well-formed id works: nothing in -#: this suite may assert which release the live Hub currently points at, -#: because re-certification moves ``latest.json`` without a commit here. +#: A US build served by the hub fixtures. Any well-formed name works: nothing +#: in this suite may assert which build is current on the live Hub, because a +#: promotion changes releases.json without a commit here. RELEASE_ID = "populace-us-2024-buildi-sparse-rmloss100-6e8e929-20260709T034135Z" -TAGGED_ARTIFACT = b"certified release artifact" -MUTABLE_ROOT_ARTIFACT = b"uncertified in-flight root artifact" +US_DATASET_BYTES = b"certified release artifact" UK_REPO_ID = "policyengine/populace-uk-private" UK_2023_RELEASE_ID = "populace-uk-2023-dd68c73-4aa4b14-20260619T023711Z" -#: The UK switch moves the June 2023 build into this release, as its only and +#: The UK switch moved the June 2023 build into this release, as its only and #: current build, named by its old release ID. UK_2023_RELEASE = "populace-uk-2023" UK_NATIONAL_RELEASE_ID = "microcosm-uk-2024-25-national" UK_LOCAL_RELEASE_ID = "microcosm-uk-2024-25-local-k15" -UK_TAGGED_ARTIFACT = b"certified UK line artifact" -#: Until a repository switches to releases.json, UK releases are tagged and -#: made current through latest-.json pointer files. -UK_NATIONAL_CUT_TAG = f"{UK_NATIONAL_RELEASE_ID}-20260920T120000Z-deadbeef" -UK_LOCAL_LINE = "local-k15" -UK_LOCAL_CUT_TAG = f"{UK_LOCAL_RELEASE_ID}-20260920T120000Z-cafebabe" +UK_DATASET_BYTES = b"certified UK line artifact" #: An earlier national build, still listed in releases.json. UK_EARLIER_BUILD = "uk-frs-calibration-attempt-20260901T000000Z-0badcafe" @@ -103,7 +90,7 @@ def test_latest_year_unknown_country_raises() -> None: def _release_manifest( *, - artifact_content: bytes = TAGGED_ARTIFACT, + artifact_content: bytes = US_DATASET_BYTES, release_id: str = RELEASE_ID, ) -> dict: return { @@ -147,7 +134,7 @@ def _uk_release_manifest( artifact_key: str = "microcosm_uk_2024_25", dataset_role: str | None = NATIONAL_DEFAULT_DATASET_ROLE, default_datasets: dict[str, str] | None = None, - artifact_content: bytes = UK_TAGGED_ARTIFACT, + artifact_content: bytes = UK_DATASET_BYTES, ) -> dict: if default_datasets is None: default_datasets = {"national": artifact_key} @@ -260,13 +247,11 @@ def _build_folder_hub( *, manifest: dict, record: dict | bytes | None = None, - artifact_content: bytes = UK_TAGGED_ARTIFACT, + artifact_content: bytes = UK_DATASET_BYTES, repo_id: str = UK_REPO_ID, ) -> FakeHubDownload: """Serve releases.json and one build folder, all read at ``main``.""" hub = FakeHubDownload(tmp_path) - hub.calls.clear() - hub.files.clear() record = _releases_record() if record is None else record hub._add( tmp_path, @@ -293,44 +278,12 @@ def _build_folder_hub( class FakeHubDownload: - """Serve mutable and release-tagged files while recording every request.""" + """Serve the files a test adds while recording every request.""" - def __init__(self, tmp_path: Path, *, manifest: dict | None = None) -> None: - pointer = latest_pointer_payload( - RELEASE_ID, updated_at="2026-07-09T04:00:00+00:00" - ) - manifest = manifest or _release_manifest() + def __init__(self, tmp_path: Path) -> None: self.tmp_path = tmp_path self.calls: list[tuple[str, str, str | None]] = [] self.files: dict[tuple[str, str, str | None], Path] = {} - self._add( - tmp_path, - "policyengine/populace-us", - LATEST_POINTER_PATH, - None, - json.dumps(pointer).encode(), - ) - self._add( - tmp_path, - "policyengine/populace-us", - pointer["paths"]["release_manifest"], - RELEASE_ID, - json.dumps(manifest).encode(), - ) - self._add( - tmp_path, - "policyengine/populace-us", - "populace_us_2024.h5", - RELEASE_ID, - TAGGED_ARTIFACT, - ) - self._add( - tmp_path, - "policyengine/populace-us", - "populace_us_2024.h5", - None, - MUTABLE_ROOT_ARTIFACT, - ) def _add( self, @@ -367,35 +320,6 @@ def __call__( ) from exc -def _hub_with_pointer( - tmp_path: Path, - *, - repo_id: str, - pointer_path: str, - pointer: dict, - manifest: dict, -) -> FakeHubDownload: - hub = FakeHubDownload(tmp_path) - hub.calls.clear() - hub.files.clear() - revision = str(pointer.get("revision", pointer["release_id"])) - hub._add( - tmp_path, - repo_id, - pointer_path, - None, - json.dumps(pointer).encode(), - ) - hub._add( - tmp_path, - repo_id, - pointer["paths"]["release_manifest"], - revision, - json.dumps(manifest).encode(), - ) - return hub - - def _patch_engine( monkeypatch: pytest.MonkeyPatch, *, @@ -425,12 +349,11 @@ def __init__(self, *, file_path: str) -> None: def test_resolve_uk_default_is_the_national_release(): """The national release is the default UK load, read through releases.json; the June 2023 release stays at its year, read through - releases.json too once its repository has one, latest.json until then.""" + releases.json too.""" assert latest_year("uk") == 2025 assert resolve("uk").key == ("uk", 2025, DEFAULT_VARIANT) assert resolve("uk").release == UK_NATIONAL_RELEASE_ID assert resolve("uk", 2023).release == UK_2023_RELEASE - assert resolve("uk", 2023).pointer_path == "latest.json" with pytest.raises(ValueError, match="variant 'national'"): resolve("uk", 2025, variant="national") @@ -565,64 +488,6 @@ def test_releases_json_role_must_match_the_manifest(tmp_path: Path) -> None: loader._resolve_certified_release(resolve("uk", 2025), hub_download=hub) -def test_a_build_pin_needs_a_build_folder_release() -> None: - def unexpected_download(**_kwargs) -> str: - pytest.fail("a refused pin must fail before a Hub request") - - # Every registry entry now names a release; an entry that names none - # keeps the tagged layout. - tagged = replace(resolve("us", 2024), release=None) - with pytest.raises(ValueError, match="pins a build only for releases"): - loader._resolve_certified_release( - tagged, hub_download=unexpected_download, build="x" - ) - - -def test_unverified_root_loading_is_refused_for_a_build_folder_release( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - """Once the repository records its builds in releases.json, it has no - root file to load.""" - hub = _build_folder_hub(tmp_path, manifest=_uk_build_folder_manifest()) - monkeypatch.setattr(huggingface_hub, "hf_hub_download", hub) - monkeypatch.setattr( - loader, - "_dataset_class", - lambda _spec: pytest.fail("refused before the engine is imported"), - ) - with pytest.raises(ValueError, match="no root file"): - load("uk", 2025, unverified_root=True) - assert hub.calls == [(UK_REPO_ID, "releases.json", None)] - - -def test_unverified_root_loading_reads_the_root_file_before_the_switch( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - """Without releases.json the repository still has its root file, and the - escape hatch loads it as before.""" - hub = FakeHubDownload(tmp_path) - hub.calls.clear() - hub.files.clear() - hub._add(tmp_path, UK_REPO_ID, "microcosm_uk_2024_25.h5", None, b"root file") - monkeypatch.setattr(huggingface_hub, "hf_hub_download", hub) - constructed: list[str] = [] - - class FakeDataset: - def __init__(self, *, file_path: str) -> None: - constructed.append(file_path) - - monkeypatch.setattr(loader, "_dataset_class", lambda _spec: FakeDataset) - - with pytest.warns(RuntimeWarning, match="UNVERIFIED"): - load("uk", 2025, unverified_root=True) - - assert [Path(path).read_bytes() for path in constructed] == [b"root file"] - assert hub.calls == [ - (UK_REPO_ID, "releases.json", None), - (UK_REPO_ID, "microcosm_uk_2024_25.h5", None), - ] - - def test_download_verifies_the_build_folder_dataset( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: @@ -632,7 +497,7 @@ def test_download_verifies_the_build_folder_dataset( path = download("uk", 2025) folder = f"releases/{UK_NATIONAL_RELEASE_ID}/{UK_NATIONAL_BUILD}" - assert path.read_bytes() == UK_TAGGED_ARTIFACT + assert path.read_bytes() == UK_DATASET_BYTES assert hub.calls[-1] == (UK_REPO_ID, f"{folder}/microcosm_uk_2024_25.h5", None) hub._add( @@ -656,11 +521,11 @@ def test_download_certified_returns_the_current_builds_record( path, certified = loader.download_certified("uk", 2025, hub_download=hub) folder = f"releases/{UK_NATIONAL_RELEASE_ID}/{UK_NATIONAL_BUILD}" - assert path.read_bytes() == UK_TAGGED_ARTIFACT + assert path.read_bytes() == UK_DATASET_BYTES assert certified.release_id == UK_NATIONAL_RELEASE_ID assert certified.build == UK_NATIONAL_BUILD assert certified.artifact_path == f"{folder}/microcosm_uk_2024_25.h5" - assert certified.artifact_sha256 == hashlib.sha256(UK_TAGGED_ARTIFACT).hexdigest() + assert certified.artifact_sha256 == hashlib.sha256(UK_DATASET_BYTES).hexdigest() assert certified.model.built_version == "2.89.2" @@ -739,61 +604,25 @@ def test_download_build_file_refuses_a_file_whose_digest_differs( loader.download_build_file(certified, "release_certification", hub_download=hub) -def test_download_build_file_needs_a_build_folder_release() -> None: - tagged = loader.CertifiedRelease( +def test_download_build_file_needs_a_build() -> None: + without_build = loader.CertifiedRelease( release_id=UK_NATIONAL_RELEASE_ID, artifact_repo_id=UK_REPO_ID, artifact_path="microcosm_uk_2024_25.h5", - artifact_revision=UK_NATIONAL_CUT_TAG, + artifact_revision=None, artifact_sha256="0" * 64, model=loader._PackageCertification("policyengine-uk", ("==2.89.2",), "2.89.2"), core=loader._PackageCertification("policyengine-core", ("==3.27.1",), "3.27.1"), ) - with pytest.raises(ValueError, match="keeps the tagged layout"): - loader.download_build_file(tagged, "release_certification") - - -def test_uk_2023_follows_latest_json_until_its_repository_has_releases_json( - tmp_path: Path, -) -> None: - spec = resolve("uk", 2023) - manifest = _uk_release_manifest( - release_id=UK_2023_RELEASE_ID, - revision=UK_2023_RELEASE_ID, - filename="populace_uk_2023.h5", - artifact_key="populace_uk_2023", - dataset_role=None, - ) - pointer = latest_pointer_payload( - UK_2023_RELEASE_ID, - updated_at="2026-06-19T03:00:00+00:00", - ) - hub = _hub_with_pointer( - tmp_path, - repo_id=UK_REPO_ID, - pointer_path=LATEST_POINTER_PATH, - pointer=pointer, - manifest=manifest, - ) - - certified = loader._resolve_certified_release(spec, hub_download=hub) - - manifest_path = f"releases/{UK_2023_RELEASE_ID}/release_manifest.json" - assert spec.pointer_path == LATEST_POINTER_PATH - assert certified.release_id == UK_2023_RELEASE_ID - assert certified.artifact_revision == UK_2023_RELEASE_ID - assert hub.calls == [ - (UK_REPO_ID, "releases.json", None), - (UK_REPO_ID, LATEST_POINTER_PATH, None), - (UK_REPO_ID, manifest_path, UK_2023_RELEASE_ID), - ] + with pytest.raises(ValueError, match="names no build"): + loader.download_build_file(without_build, "release_certification") def test_uk_2023_loads_the_june_build_from_its_folder_after_the_switch( tmp_path: Path, ) -> None: - """The UK switch moves the June 2023 build into release populace-uk-2023, - as its current build under its old release ID, and deletes latest.json.""" + """The UK switch moved the June 2023 build into release populace-uk-2023, + as its current build under its old release ID.""" spec = resolve("uk", 2023) assert spec.release == UK_2023_RELEASE manifest = _uk_build_folder_manifest( @@ -826,19 +655,6 @@ def test_uk_2023_loads_the_june_build_from_its_folder_after_the_switch( ] -@pytest.mark.parametrize("pointer_path", ["current.json", "latest-local-k0.json"]) -def test_resolve_refuses_an_unsupported_pointer_path(pointer_path: str) -> None: - # An entry that names no release follows only its pointer; one that names - # a release reads releases.json first, so the US entry drops its release. - spec = replace(resolve("us", 2024), release=None, pointer_path=pointer_path) - - def unexpected_download(**_kwargs) -> str: - pytest.fail("an unsupported pointer path must fail before a Hub request") - - with pytest.raises(ValueError, match="Unsupported release pointer path"): - loader._resolve_certified_release(spec, hub_download=unexpected_download) - - def test_local_area_release_selects_its_only_microdata_artifact( tmp_path: Path, ) -> None: @@ -872,33 +688,6 @@ def test_local_area_release_selects_its_only_microdata_artifact( ] -def test_latest_json_refuses_a_local_area_manifest(tmp_path: Path) -> None: - manifest = _uk_release_manifest( - filename="microcosm_uk_2024_25_local_k15.h5", - artifact_key="microcosm_uk_2024_25_local_k15", - dataset_role=NON_DEFAULT_LOCAL_AREA_DATASET_ROLE, - default_datasets={}, - ) - pointer = latest_pointer_payload( - UK_2023_RELEASE_ID, - updated_at="2026-09-20T12:00:00+00:00", - ) - hub = _hub_with_pointer( - tmp_path, - repo_id=UK_REPO_ID, - pointer_path=LATEST_POINTER_PATH, - pointer=pointer, - manifest=manifest, - ) - spec = replace(_uk_local_spec(), release=None, pointer_path=LATEST_POINTER_PATH) - - with pytest.raises( - ValueError, - match=r"non_default_local_area.*build folder.*latest\.json", - ): - loader._resolve_certified_release(spec, hub_download=hub) - - def _local_area_hub(tmp_path: Path, manifest: dict) -> FakeHubDownload: return _build_folder_hub( tmp_path, @@ -962,137 +751,114 @@ def test_loader_refuses_an_unknown_dataset_role(tmp_path: Path) -> None: loader._resolve_certified_release(resolve("uk", 2025), hub_download=hub) -# Before the switch: a repository without releases.json ----------------------- -# Until its repository switches to releases.json, a UK release's current -# build is the one its latest*.json pointer file names. A registry entry that -# names a release reads releases.json where the repository has one, and -# otherwise follows its pointer file exactly as before. +def _hf_offline() -> bool: + return os.environ.get("HF_HUB_OFFLINE", "").lower() in {"1", "true", "yes"} -def _uk_national_line_manifest() -> dict: - return _uk_release_manifest( - release_id=UK_NATIONAL_RELEASE_ID, revision=UK_NATIONAL_CUT_TAG +def _is_offline_error(exc: Exception) -> bool: + """Recognize transport/offline failures without hiding bad release metadata.""" + offline_names = { + "ConnectError", + "ConnectTimeout", + "ConnectionError", + "LocalEntryNotFoundError", + "OfflineModeIsEnabled", + "ProxyError", + "ReadTimeout", + } + closed_after_retry = isinstance(exc, RuntimeError) and str(exc) == ( + "Cannot send a request, as the client has been closed." + ) + return ( + isinstance(exc, (ConnectionError, TimeoutError)) + or closed_after_retry + or any(cls.__name__ in offline_names for cls in type(exc).__mro__) ) -def _uk_local_line_spec() -> DatasetSpec: - return replace(_uk_local_spec(), pointer_path=line_pointer_path(UK_LOCAL_LINE)) +def test_the_national_release_refuses_a_local_area_manifest(tmp_path: Path): + """releases.json gives each release one role: the national release + cannot load a local-area manifest on the strength of its name.""" + manifest = _uk_build_folder_manifest( + dataset_role="non_default_local_area", default_datasets={} + ) + hub = _build_folder_hub(tmp_path, manifest=manifest) + with pytest.raises(ValueError, match="listed with role 'national'"): + loader._resolve_certified_release(resolve("uk", 2025), hub_download=hub) -def _uk_local_line_manifest() -> dict: - return _uk_release_manifest( - release_id=UK_LOCAL_RELEASE_ID, - revision=UK_LOCAL_CUT_TAG, - filename="microcosm_uk_2024_25_local_k15.h5", - artifact_key="microcosm_uk_2024_25_local_k15", - dataset_role=NON_DEFAULT_LOCAL_AREA_DATASET_ROLE, - default_datasets={}, - ) +US_REPO_ID = "policyengine/populace-us" +US_NATIONAL_RELEASE_ID = "microcosm-us-2024-national" -def _line_pointer_hub( - tmp_path: Path, - *, - line: str, - release_id: str, - revision: str, - manifest: dict, -) -> FakeHubDownload: - pointer = line_pointer_payload( - release_id, - line=line, - revision=revision, - updated_at="2026-09-20T12:00:00+00:00", +def _us_build_folder_manifest(*, path: str = "microcosm_us_2024.h5") -> dict: + """A US national build's release manifest in its own folder, declaring + its dataset as ``path``.""" + manifest = _release_manifest() + key = path.removesuffix(".h5") + entry = manifest["artifacts"].pop("populace_us_2024") + manifest["artifacts"][key] = {**entry, "path": path} + manifest["default_datasets"] = {"national": key} + return build_folder_release_manifest( + manifest, release=US_NATIONAL_RELEASE_ID, build=RELEASE_ID ) - return _hub_with_pointer( + + +def _us_build_folder_hub(tmp_path: Path, manifest: dict) -> FakeHubDownload: + return _build_folder_hub( tmp_path, - repo_id=UK_REPO_ID, - pointer_path=line_pointer_path(line), - pointer=pointer, manifest=manifest, + record=_releases_record( + US_NATIONAL_RELEASE_ID, current=RELEASE_ID, builds={RELEASE_ID: False} + ), + artifact_content=US_DATASET_BYTES, + repo_id=US_REPO_ID, ) -def test_resolve_uk_default_is_the_promoted_national_line(): - """microcosm#823: once the national line's first certified cut was - promoted, the line became the default UK load; the June 2023 line stays - addressable at its year and its own pointer (Max's #823 ruling).""" - assert latest_year("uk") == 2025 - assert resolve("uk").key == ("uk", 2025, DEFAULT_VARIANT) - assert resolve("uk").pointer_path == "latest-national.json" - assert resolve("uk", 2023).pointer_path == "latest.json" - with pytest.raises(ValueError, match="variant 'national'"): - resolve("uk", 2025, variant="national") - - -def test_resolve_uk_national_variant_follows_the_line_pointer( +def test_us_national_load_follows_the_current_build_in_releases_json( tmp_path: Path, ) -> None: - spec = resolve("uk", 2025) - hub = _line_pointer_hub( - tmp_path, - line="national", - release_id=UK_NATIONAL_RELEASE_ID, - revision=UK_NATIONAL_CUT_TAG, - manifest=_uk_national_line_manifest(), - ) + hub = _us_build_folder_hub(tmp_path, _us_build_folder_manifest()) - certified = loader._resolve_certified_release(spec, hub_download=hub) + certified = loader._resolve_certified_release(resolve("us", 2024), hub_download=hub) - manifest_path = f"releases/{UK_NATIONAL_RELEASE_ID}/release_manifest.json" - assert spec.key == ("uk", 2025, DEFAULT_VARIANT) - assert spec.pointer_path == "latest-national.json" - assert certified.release_id == UK_NATIONAL_RELEASE_ID - assert certified.build is None - assert certified.artifact_path == "microcosm_uk_2024_25.h5" - assert certified.artifact_revision == UK_NATIONAL_CUT_TAG + folder = f"releases/{US_NATIONAL_RELEASE_ID}/{RELEASE_ID}" + assert certified.release_id == US_NATIONAL_RELEASE_ID + assert certified.build == RELEASE_ID + assert certified.artifact_path == f"{folder}/microcosm_us_2024.h5" assert hub.calls == [ - (UK_REPO_ID, "releases.json", None), - (UK_REPO_ID, "latest-national.json", None), - (UK_REPO_ID, manifest_path, UK_NATIONAL_CUT_TAG), + (US_REPO_ID, "releases.json", None), + (US_REPO_ID, f"{folder}/release_manifest.json", None), ] -def test_download_follows_the_line_pointer_without_releases_json( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path +def test_a_us_build_moved_by_the_switch_loads_with_its_earlier_dataset_name( + tmp_path: Path, ) -> None: - """load("uk") and download("uk") do not fail for want of releases.json.""" - hub = _line_pointer_hub( - tmp_path, - line="national", - release_id=UK_NATIONAL_RELEASE_ID, - revision=UK_NATIONAL_CUT_TAG, - manifest=_uk_national_line_manifest(), - ) - hub._add( - tmp_path, - UK_REPO_ID, - "microcosm_uk_2024_25.h5", - UK_NATIONAL_CUT_TAG, - UK_TAGGED_ARTIFACT, + hub = _us_build_folder_hub( + tmp_path, _us_build_folder_manifest(path="populace_us_2024.h5") ) - monkeypatch.setattr(huggingface_hub, "hf_hub_download", hub) - path = download("uk") + certified = loader._resolve_certified_release(resolve("us", 2024), hub_download=hub) - assert path.read_bytes() == UK_TAGGED_ARTIFACT - assert hub.calls[-1] == ( - UK_REPO_ID, - "microcosm_uk_2024_25.h5", - UK_NATIONAL_CUT_TAG, + assert certified.artifact_path.endswith(f"/{RELEASE_ID}/populace_us_2024.h5") + + +def test_a_us_build_with_another_dataset_name_is_refused(tmp_path: Path) -> None: + hub = _us_build_folder_hub( + tmp_path, + _us_build_folder_manifest(path="microcosm_us_2024_receipt_qualified.h5"), ) + with pytest.raises(ValueError, match="microcosm_us_2024.h5"): + loader._resolve_certified_release(resolve("us", 2024), hub_download=hub) + -def test_a_build_pin_needs_the_repository_to_have_releases_json( +def test_a_build_pin_is_refused_in_a_repository_without_releases_json( tmp_path: Path, ) -> None: - hub = _line_pointer_hub( - tmp_path, - line="national", - release_id=UK_NATIONAL_RELEASE_ID, - revision=UK_NATIONAL_CUT_TAG, - manifest=_uk_national_line_manifest(), - ) + hub = FakeHubDownload(tmp_path) with pytest.raises(ValueError, match="has no releases.json"): loader._resolve_certified_release( @@ -1101,16 +867,10 @@ def test_a_build_pin_needs_the_repository_to_have_releases_json( assert hub.calls == [(UK_REPO_ID, "releases.json", None)] -def test_only_a_missing_releases_json_follows_the_pointer_file(tmp_path: Path) -> None: +def test_an_unanswered_releases_json_request_propagates(tmp_path: Path) -> None: """An error other than the file's absence, such as an unreachable Hub, - propagates rather than reading the pointer files.""" - hub = _line_pointer_hub( - tmp_path, - line="national", - release_id=UK_NATIONAL_RELEASE_ID, - revision=UK_NATIONAL_CUT_TAG, - manifest=_uk_national_line_manifest(), - ) + propagates; it is not read as a repository without releases.json.""" + hub = _build_folder_hub(tmp_path, manifest=_uk_build_folder_manifest()) def unreachable(**request) -> str: if request["filename"] == "releases.json": @@ -1125,20 +885,15 @@ def unreachable(**request) -> str: @pytest.mark.parametrize( "status_code", [None, 503, 403], ids=["no-answer", "server-error", "forbidden"] ) -def test_a_hub_failure_reading_releases_json_does_not_fall_back( +def test_a_hub_failure_reading_releases_json_propagates( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, status_code: int | None ) -> None: """Online, huggingface_hub raises LocalEntryNotFoundError when it could - not ask the Hub, after a 5xx or on a 403. That is not the file's absence: - falling back would load the pointer's build after the switch.""" + not ask the Hub, after a 5xx or on a 403. That is not the file's absence, + so it propagates instead of being refused as a repository without + releases.json.""" monkeypatch.setattr(huggingface_hub.constants, "HF_HUB_OFFLINE", False) - hub = _line_pointer_hub( - tmp_path, - line="national", - release_id=UK_NATIONAL_RELEASE_ID, - revision=UK_NATIONAL_CUT_TAG, - manifest=_uk_national_line_manifest(), - ) + hub = _build_folder_hub(tmp_path, manifest=_uk_build_folder_manifest()) def unreachable(**request) -> str: if request["filename"] == "releases.json": @@ -1150,281 +905,15 @@ def unreachable(**request) -> str: assert hub.calls == [] -def test_offline_a_releases_json_never_cached_falls_back_to_the_pointer_file( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """In offline mode the cache is all there is: a releases.json never - cached loads the cached pointer file's build, as an offline load did - before.""" - monkeypatch.setattr(huggingface_hub.constants, "HF_HUB_OFFLINE", True) - hub = _line_pointer_hub( - tmp_path, - line="national", - release_id=UK_NATIONAL_RELEASE_ID, - revision=UK_NATIONAL_CUT_TAG, - manifest=_uk_national_line_manifest(), - ) - - def offline(**request) -> str: - if request["filename"] == "releases.json": - raise hub_unreachable(UK_REPO_ID, "releases.json") - return hub(**request) - - certified = loader._resolve_certified_release( - resolve("uk", 2025), hub_download=offline - ) - - assert certified.release_id == UK_NATIONAL_RELEASE_ID - assert certified.artifact_revision == UK_NATIONAL_CUT_TAG - - -def test_line_pointer_refuses_any_artifact_revision_mismatch(tmp_path: Path) -> None: - manifest = _uk_national_line_manifest() - manifest["artifacts"]["calibration_report"] = { - "kind": "diagnostics", - "path": "calibration_diagnostics.json", - "repo_id": UK_REPO_ID, - "revision": UK_NATIONAL_RELEASE_ID, - "sha256": "0" * 64, - } - hub = _line_pointer_hub( - tmp_path, - line="national", - release_id=UK_NATIONAL_RELEASE_ID, - revision=UK_NATIONAL_CUT_TAG, - manifest=manifest, - ) +def test_a_missing_release_manifest_raises(tmp_path: Path) -> None: + hub = _build_folder_hub(tmp_path, manifest=_uk_build_folder_manifest()) + folder = f"releases/{UK_NATIONAL_RELEASE_ID}/{UK_NATIONAL_BUILD}" + del hub.files[(UK_REPO_ID, f"{folder}/release_manifest.json", None)] - with pytest.raises( - ValueError, - match=r"artifacts not pinned to expected revision.*calibration_report", - ): + with pytest.raises(FileNotFoundError, match=r"release_manifest\.json"): loader._resolve_certified_release(resolve("uk", 2025), hub_download=hub) -def test_line_pointer_refuses_a_manifest_with_another_lines_role(tmp_path: Path): - """A line pointer carries one role: the national pointer cannot select a - local-area manifest, nor a local-area pointer a national one.""" - spec = resolve("uk", 2025) - manifest = _uk_national_line_manifest() - manifest["dataset_role"] = "non_default_local_area" - manifest["default_datasets"] = {} - hub = _line_pointer_hub( - tmp_path, - line="national", - release_id=UK_NATIONAL_RELEASE_ID, - revision=UK_NATIONAL_CUT_TAG, - manifest=manifest, - ) - with pytest.raises(ValueError, match="publishes only 'national_default'"): - loader._resolve_certified_release(spec, hub_download=hub) - - -def test_local_area_line_selects_its_only_microdata_artifact(tmp_path: Path) -> None: - manifest = _uk_local_line_manifest() - manifest["artifacts"]["calibration_report"] = { - "kind": "diagnostics", - "path": "calibration_diagnostics.json", - "repo_id": UK_REPO_ID, - "revision": UK_LOCAL_CUT_TAG, - "sha256": "0" * 64, - } - hub = _line_pointer_hub( - tmp_path, - line=UK_LOCAL_LINE, - release_id=UK_LOCAL_RELEASE_ID, - revision=UK_LOCAL_CUT_TAG, - manifest=manifest, - ) - - certified = loader._resolve_certified_release( - _uk_local_line_spec(), - hub_download=hub, - ) - - manifest_path = f"releases/{UK_LOCAL_RELEASE_ID}/release_manifest.json" - assert certified.release_id == UK_LOCAL_RELEASE_ID - assert certified.artifact_path == "microcosm_uk_2024_25_local_k15.h5" - assert certified.artifact_revision == UK_LOCAL_CUT_TAG - assert hub.calls == [ - (UK_REPO_ID, "releases.json", None), - (UK_REPO_ID, "latest-local-k15.json", None), - (UK_REPO_ID, manifest_path, UK_LOCAL_CUT_TAG), - ] - - -def test_local_area_line_refuses_nonempty_default_datasets(tmp_path: Path) -> None: - manifest = _uk_local_line_manifest() - manifest["default_datasets"] = {"national": "microcosm_uk_2024_25_local_k15"} - hub = _line_pointer_hub( - tmp_path, - line=UK_LOCAL_LINE, - release_id=UK_LOCAL_RELEASE_ID, - revision=UK_LOCAL_CUT_TAG, - manifest=manifest, - ) - - with pytest.raises(ValueError, match=r"default_datasets is not empty"): - loader._resolve_certified_release(_uk_local_line_spec(), hub_download=hub) - - -@pytest.mark.parametrize("microdata_count", [0, 2]) -def test_local_area_line_requires_exactly_one_microdata_artifact( - tmp_path: Path, - microdata_count: int, -) -> None: - manifest = _uk_local_line_manifest() - artifact = manifest["artifacts"]["microcosm_uk_2024_25_local_k15"] - if microdata_count == 0: - artifact["kind"] = "diagnostics" - else: - manifest["artifacts"]["second_microdata"] = { - "kind": "microdata", - "path": "second.h5", - "repo_id": UK_REPO_ID, - "revision": UK_LOCAL_CUT_TAG, - "sha256": "1" * 64, - } - hub = _line_pointer_hub( - tmp_path, - line=UK_LOCAL_LINE, - release_id=UK_LOCAL_RELEASE_ID, - revision=UK_LOCAL_CUT_TAG, - manifest=manifest, - ) - - with pytest.raises( - ValueError, - match=rf"{microdata_count} microdata artifacts; expected exactly one", - ): - loader._resolve_certified_release(_uk_local_line_spec(), hub_download=hub) - - -def test_download_uses_pointer_manifest_and_release_revision( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - hub = FakeHubDownload(tmp_path) - monkeypatch.setattr(huggingface_hub, "hf_hub_download", hub) - - artifact = download("us", 2024) - - manifest_path = f"releases/{RELEASE_ID}/release_manifest.json" - assert artifact.read_bytes() == TAGGED_ARTIFACT - # The US entry names its release, so the loader looks for releases.json - # first and follows latest.json while the repository has none. - assert hub.calls == [ - ("policyengine/populace-us", "releases.json", None), - ("policyengine/populace-us", LATEST_POINTER_PATH, None), - ("policyengine/populace-us", manifest_path, RELEASE_ID), - ("policyengine/populace-us", "populace_us_2024.h5", RELEASE_ID), - ] - - -def test_resolve_certified_release_returns_pointer_pinned_metadata( - tmp_path: Path, -) -> None: - """Exact release-metadata equalities are pinned against the hub fixture.""" - hub = FakeHubDownload(tmp_path) - - certified = loader._resolve_certified_release(resolve("us", 2024), hub_download=hub) - - assert certified.release_id == RELEASE_ID - assert certified.artifact_repo_id == "policyengine/populace-us" - assert certified.artifact_path == "populace_us_2024.h5" - assert certified.artifact_revision == RELEASE_ID - assert certified.artifact_sha256 == hashlib.sha256(TAGGED_ARTIFACT).hexdigest() - assert certified.model.name == "policyengine-us" - assert certified.model.built_version == "1.764.6" - assert certified.core.name == "policyengine-core" - assert certified.core.built_version == "3.26.11" - - -def test_recertification_advances_the_pointer_and_resolution_follows( - tmp_path: Path, -) -> None: - """Publishing a successor release moves ``latest.json``; resolution follows. - - The pointer is the loader's only entry point — there is no API for - requesting a superseded release id — so a re-certification changes what - every consumer resolves without any commit in this repository. - """ - hub = FakeHubDownload(tmp_path) - spec = resolve("us", 2024) - assert ( - loader._resolve_certified_release(spec, hub_download=hub).release_id - == RELEASE_ID - ) - - successor_id = "populace-us-2024-buildj-sparse-rmloss100-75d5add-20260710T094201Z" - successor_artifact = b"successor certified release artifact" - pointer = latest_pointer_payload( - successor_id, updated_at="2026-07-10T10:00:00+00:00" - ) - hub._add( - hub.tmp_path, - "policyengine/populace-us", - LATEST_POINTER_PATH, - None, - json.dumps(pointer).encode(), - ) - hub._add( - hub.tmp_path, - "policyengine/populace-us", - pointer["paths"]["release_manifest"], - successor_id, - json.dumps( - _release_manifest( - artifact_content=successor_artifact, release_id=successor_id - ) - ).encode(), - ) - - certified = loader._resolve_certified_release(spec, hub_download=hub) - - assert certified.release_id == successor_id - assert certified.artifact_revision == successor_id - assert certified.artifact_sha256 == hashlib.sha256(successor_artifact).hexdigest() - - -def test_pointer_vs_root_divergence_never_serves_mutable_root( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - hub = FakeHubDownload(tmp_path) - monkeypatch.setattr(huggingface_hub, "hf_hub_download", hub) - - artifact = download("us", 2024) - - assert artifact.read_bytes() == TAGGED_ARTIFACT - assert artifact.read_bytes() != MUTABLE_ROOT_ARTIFACT - assert ( - "policyengine/populace-us", - "populace_us_2024.h5", - None, - ) not in hub.calls - - -def test_sha_mismatch_raises(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - hub = FakeHubDownload(tmp_path) - tagged = hub.files[("policyengine/populace-us", "populace_us_2024.h5", RELEASE_ID)] - tagged.write_bytes(b"tampered tagged artifact") - monkeypatch.setattr(huggingface_hub, "hf_hub_download", hub) - - with pytest.raises(ValueError, match=r"sha256.*release.*expected.*observed"): - download("us", 2024) - - -def test_missing_release_manifest_raises( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - hub = FakeHubDownload(tmp_path) - manifest_path = f"releases/{RELEASE_ID}/release_manifest.json" - del hub.files[("policyengine/populace-us", manifest_path, RELEASE_ID)] - monkeypatch.setattr(huggingface_hub, "hf_hub_download", hub) - - with pytest.raises(FileNotFoundError, match=r"release_manifest\.json.*revision"): - download("us", 2024) - - @pytest.mark.parametrize( ("model_version", "core_version", "package", "installed", "required"), [ @@ -1441,7 +930,7 @@ def test_engine_incompatibility_raises_before_dataset_construction( installed: str, required: str, ) -> None: - hub = FakeHubDownload(tmp_path) + hub = _us_build_folder_hub(tmp_path, _us_build_folder_manifest()) monkeypatch.setattr(huggingface_hub, "hf_hub_download", hub) constructed = _patch_engine( monkeypatch, @@ -1461,76 +950,16 @@ def test_engine_incompatibility_raises_before_dataset_construction( def test_load_constructs_dataset_after_release_verification( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: - hub = FakeHubDownload(tmp_path) + hub = _us_build_folder_hub(tmp_path, _us_build_folder_manifest()) monkeypatch.setattr(huggingface_hub, "hf_hub_download", hub) constructed = _patch_engine(monkeypatch) dataset = load("us", 2024) + folder = f"releases/{US_NATIONAL_RELEASE_ID}/{RELEASE_ID}" assert dataset.file_path == constructed[0] - assert Path(dataset.file_path).read_bytes() == TAGGED_ARTIFACT - assert hub.calls[-1] == ( - "policyengine/populace-us", - "populace_us_2024.h5", - RELEASE_ID, - ) - - -def test_unverified_root_opt_out_warns_loudly( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - hub = FakeHubDownload(tmp_path) - monkeypatch.setattr(huggingface_hub, "hf_hub_download", hub) - constructed = _patch_engine(monkeypatch) - - with pytest.warns( - RuntimeWarning, - match=r"UNVERIFIED.*latest\.json.*SHA-256.*compatibility", - ): - dataset = load("us", 2024, unverified_root=True) - - assert dataset.file_path == constructed[0] - assert Path(dataset.file_path).read_bytes() == MUTABLE_ROOT_ARTIFACT - # Before the switch the repository has no releases.json and still has - # its root file. - assert hub.calls == [ - ("policyengine/populace-us", "releases.json", None), - ("policyengine/populace-us", "populace_us_2024.h5", None), - ] - - -def _hf_offline() -> bool: - return os.environ.get("HF_HUB_OFFLINE", "").lower() in {"1", "true", "yes"} - - -def _is_offline_error(exc: Exception) -> bool: - """Recognize transport/offline failures without hiding bad release metadata.""" - offline_names = { - "ConnectError", - "ConnectTimeout", - "ConnectionError", - "LocalEntryNotFoundError", - "OfflineModeIsEnabled", - "ProxyError", - "ReadTimeout", - } - closed_after_retry = isinstance(exc, RuntimeError) and str(exc) == ( - "Cannot send a request, as the client has been closed." - ) - return ( - isinstance(exc, (ConnectionError, TimeoutError)) - or closed_after_retry - or any(cls.__name__ in offline_names for cls in type(exc).__mro__) - ) - - -def _is_missing_pointer_error(exc: BaseException, pointer_path: str) -> bool: - """The pointer file itself is absent at the repo root: an - ``EntryNotFoundError`` naming that path (the Hub's answer for a file that - does not exist at the revision). Repository, auth and manifest errors are - not this, and must not skip as "not yet promoted".""" - names = {cls.__name__ for cls in type(exc).__mro__} - return "EntryNotFoundError" in names and pointer_path in str(exc) + assert Path(dataset.file_path).read_bytes() == US_DATASET_BYTES + assert hub.calls[-1] == (US_REPO_ID, f"{folder}/microcosm_us_2024.h5", None) @pytest.mark.skipif(_hf_offline(), reason="Hugging Face offline mode is enabled") @@ -1542,26 +971,22 @@ def _is_missing_pointer_error(exc: BaseException, pointer_path: str) -> bool: ("uk", 2025, DEFAULT_VARIANT), ], ) -def test_live_latest_pointer_resolves_to_a_coherent_certified_release( +def test_live_releases_json_resolves_to_a_coherent_certified_release( country: str, year: int, variant: str, ) -> None: - """The real pointer and pinned manifest resolve without downloading large H5s. - - Deliberately release-agnostic: re-certification moves ``latest.json`` to a - new release id without a commit here, so pinning which release is current - (or its digest) would red main on every publish. Exact-metadata coverage - lives in :func:`test_resolve_certified_release_returns_pointer_pinned_metadata`; - this test only proves the currently published chain is coherent. Pinning a - release *identity* belongs to policyengine.py's certification fixtures, - which are updated atomically with each certification PR. + """The real releases.json and the current build's manifest resolve + without downloading large H5s. + + Deliberately build-agnostic: a promotion changes releases.json without a + commit here, so pinning which build is current (or its digest) would turn + main red on every promotion. Exact-metadata coverage lives in the fake-Hub + tests above; this test only proves the published record and manifest are + coherent. Pinning a build's identity belongs to policyengine.py's + certification fixtures, which are updated with each certification PR. """ spec = resolve(country, year, variant=variant) - # The UK 2025 default follows its line's pointer since microcosm#823, until - # its repository switches to releases.json; the pointer, not the variant, - # says how the release is named. - line = loader._line_from_pointer_path(spec.pointer_path) try: certified = loader._resolve_certified_release(spec) except Exception as exc: @@ -1573,145 +998,15 @@ def test_live_latest_pointer_resolves_to_a_coherent_certified_release( pytest.skip( f"repo requires credentials this environment lacks (private): {exc}" ) - if line is not None and _is_missing_pointer_error(exc, spec.pointer_path): - # A line pointer exists only once its first cut is promoted; - # until then the line is registered but not yet live. Anything - # else on a promoted line (a manifest 404, a bad pin) fails. - pytest.skip(f"line pointer {spec.pointer_path} not yet promoted: {exc}") raise assert certified.artifact_repo_id == spec.hf_repo - if certified.build is not None: - # The repository records its builds in releases.json. - assert certified.release_id == spec.release - assert certified.artifact_path == ( - f"releases/{spec.release}/{certified.build}/{spec.filename}" - ) - assert certified.artifact_revision is None - elif line is None: - assert certified.artifact_path == spec.filename - assert certified.release_id.startswith( - # Live certified releases still carry the pre-rename id prefix; new - # builds may adopt the microcosm- prefix at the next versioned - # release. - (f"microcosm-{country}-{spec.year}-", f"populace-{country}-{spec.year}-") - ) - assert certified.artifact_revision == certified.release_id - else: - # A line pointer names the immutable cut tag of its constant id. - assert certified.artifact_path == spec.filename - assert certified.release_id.startswith(f"microcosm-{country}-") - assert certified.artifact_revision.startswith(f"{certified.release_id}-") + assert certified.release_id == spec.release + assert certified.build is not None + assert certified.artifact_path in { + f"releases/{spec.release}/{certified.build}/{name}" + for name in spec.dataset_filenames + } + assert certified.artifact_revision is None assert re.fullmatch(r"[0-9a-f]{64}", certified.artifact_sha256) assert certified.model.name == spec.engine_package - - -def test_the_national_release_refuses_a_local_area_manifest(tmp_path: Path): - """releases.json gives each release one role: the national release - cannot load a local-area manifest on the strength of its name.""" - manifest = _uk_build_folder_manifest( - dataset_role="non_default_local_area", default_datasets={} - ) - hub = _build_folder_hub(tmp_path, manifest=manifest) - with pytest.raises(ValueError, match="listed with role 'national'"): - loader._resolve_certified_release(resolve("uk", 2025), hub_download=hub) - - -def test_latest_pointer_refuses_any_artifact_revision_mismatch(tmp_path: Path): - """One revision per pointer, by intent: the loader is stricter than the - publisher contract's annual-revision allowance (review of #966).""" - spec = resolve("uk", 2023) - manifest = _uk_release_manifest( - release_id=UK_2023_RELEASE_ID, - revision=UK_2023_RELEASE_ID, - filename="populace_uk_2023.h5", - artifact_key="populace_uk_2023", - dataset_role=None, - ) - manifest["artifacts"]["calibration_report"] = { - "kind": "diagnostics", - "path": f"releases/{UK_2023_RELEASE_ID}/calibration_diagnostics.json", - "repo_id": UK_REPO_ID, - "revision": f"{UK_2023_RELEASE_ID}-annual-2027", - "sha256": "0" * 64, - } - pointer = latest_pointer_payload( - UK_2023_RELEASE_ID, updated_at="2026-06-19T03:00:00+00:00" - ) - hub = _hub_with_pointer( - tmp_path, - repo_id=UK_REPO_ID, - pointer_path=LATEST_POINTER_PATH, - pointer=pointer, - manifest=manifest, - ) - with pytest.raises(ValueError, match="not pinned to expected revision"): - loader._resolve_certified_release(spec, hub_download=hub) - - -US_REPO_ID = "policyengine/populace-us" -US_NATIONAL_RELEASE_ID = "microcosm-us-2024-national" - - -def _us_build_folder_manifest(*, path: str = "microcosm_us_2024.h5") -> dict: - """A US national build's release manifest in its own folder, declaring - its dataset as ``path``.""" - manifest = _release_manifest() - key = path.removesuffix(".h5") - entry = manifest["artifacts"].pop("populace_us_2024") - manifest["artifacts"][key] = {**entry, "path": path} - manifest["default_datasets"] = {"national": key} - return build_folder_release_manifest( - manifest, release=US_NATIONAL_RELEASE_ID, build=RELEASE_ID - ) - - -def _us_build_folder_hub(tmp_path: Path, manifest: dict) -> FakeHubDownload: - return _build_folder_hub( - tmp_path, - manifest=manifest, - record=_releases_record( - US_NATIONAL_RELEASE_ID, current=RELEASE_ID, builds={RELEASE_ID: False} - ), - artifact_content=TAGGED_ARTIFACT, - repo_id=US_REPO_ID, - ) - - -def test_us_national_load_follows_the_current_build_in_releases_json( - tmp_path: Path, -) -> None: - hub = _us_build_folder_hub(tmp_path, _us_build_folder_manifest()) - - certified = loader._resolve_certified_release(resolve("us", 2024), hub_download=hub) - - folder = f"releases/{US_NATIONAL_RELEASE_ID}/{RELEASE_ID}" - assert certified.release_id == US_NATIONAL_RELEASE_ID - assert certified.build == RELEASE_ID - assert certified.artifact_path == f"{folder}/microcosm_us_2024.h5" - assert hub.calls == [ - (US_REPO_ID, "releases.json", None), - (US_REPO_ID, f"{folder}/release_manifest.json", None), - ] - - -def test_a_us_build_moved_by_the_switch_loads_with_its_earlier_dataset_name( - tmp_path: Path, -) -> None: - hub = _us_build_folder_hub( - tmp_path, _us_build_folder_manifest(path="populace_us_2024.h5") - ) - - certified = loader._resolve_certified_release(resolve("us", 2024), hub_download=hub) - - assert certified.artifact_path.endswith(f"/{RELEASE_ID}/populace_us_2024.h5") - - -def test_a_us_build_with_another_dataset_name_is_refused(tmp_path: Path) -> None: - hub = _us_build_folder_hub( - tmp_path, - _us_build_folder_manifest(path="microcosm_us_2024_receipt_qualified.h5"), - ) - - with pytest.raises(ValueError, match="microcosm_us_2024.h5"): - loader._resolve_certified_release(resolve("us", 2024), hub_download=hub) diff --git a/packages/microcosm-data/tests/engine_free/shared/test_registry.py b/packages/microcosm-data/tests/engine_free/shared/test_registry.py index 6656d6db0b..15bcc8a50a 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_registry.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_registry.py @@ -14,7 +14,6 @@ available_variants, register, ) -from microcosm.data.release import LATEST_POINTER_PATH def test_us_2024_is_registered_with_a_complete_spec() -> None: @@ -47,12 +46,6 @@ def test_uk_2023_compact_is_registered_with_a_complete_spec() -> None: assert spec.engine_package == "policyengine-uk" -def test_dataset_spec_default_pointer_path_matches_release_default() -> None: - assert ( - DatasetSpec.__dataclass_fields__["pointer_path"].default == LATEST_POINTER_PATH - ) - - def test_available_lists_default_variant_keys_only_sorted(monkeypatch) -> None: dense_only = DatasetSpec( country="zz", @@ -63,6 +56,7 @@ def test_available_lists_default_variant_keys_only_sorted(monkeypatch) -> None: engine_module="policyengine_zz.data", engine_class="ZZSingleYearDataset", engine_package="policyengine-zz", + release="microcosm-zz-2099-dense", ) monkeypatch.setattr( loader_module, @@ -112,6 +106,7 @@ def test_register_allows_distinct_variants_for_same_country_year(monkeypatch) -> engine_module="policyengine_zz.data", engine_class="ZZSingleYearDataset", engine_package="policyengine-zz", + release="microcosm-zz-2099-national", ) local = DatasetSpec( country="zz", @@ -122,6 +117,7 @@ def test_register_allows_distinct_variants_for_same_country_year(monkeypatch) -> engine_module="policyengine_zz.data", engine_class="ZZSingleYearDataset", engine_package="policyengine-zz", + release="microcosm-zz-2099-local", ) assert register(compact) is compact @@ -140,6 +136,7 @@ def test_register_refuses_to_shadow_a_key_with_a_different_spec() -> None: engine_module="policyengine_us.data", engine_class="USSingleYearDataset", engine_package="policyengine-us", + release="microcosm-us-2024-national", ) with pytest.raises(ValueError, match="already registered for"): register(conflicting) @@ -157,40 +154,23 @@ def test_uk_2025_dense_is_registered_off_the_default_variant() -> None: assert ("uk", 2025, DEFAULT_VARIANT) in REGISTRY -def test_uk_2025_national_line_is_the_default_variant_after_promotion(): - """microcosm#823: the line's first certified cut was promoted on - 2026-10-26, so the line moved to the default variant (Max's #823 - ruling) and its own variant key retired; the June 2023 line stays - addressable at its year. Until its repository switches to - releases.json, the loader follows latest-national.json.""" - spec = REGISTRY[("uk", 2025, DEFAULT_VARIANT)] - assert spec.pointer_path == "latest-national.json" - assert spec.filename == "microcosm_uk_2024_25.h5" - assert ("uk", 2025, "national") not in REGISTRY - assert REGISTRY[("uk", 2023, DEFAULT_VARIANT)].filename == "populace_uk_2023.h5" - - def test_uk_2025_national_release_is_the_default_variant(): """The national release is the default UK 2025 load: its current build in - releases.json, not a pointer file; the June 2023 release stays - addressable at its year, as release populace-uk-2023 once the UK switch - has moved its build, and through latest.json until then.""" + releases.json. The June 2023 release stays addressable at its year, as + release populace-uk-2023, whose one build the UK switch moved.""" spec = REGISTRY[("uk", 2025, DEFAULT_VARIANT)] assert spec.release == "microcosm-uk-2024-25-national" assert spec.filename == "microcosm_uk_2024_25.h5" assert ("uk", 2025, "national") not in REGISTRY june = REGISTRY[("uk", 2023, DEFAULT_VARIANT)] assert june.filename == "populace_uk_2023.h5" - assert (june.release, june.pointer_path) == ( - "populace-uk-2023", - LATEST_POINTER_PATH, - ) + assert june.release == "populace-uk-2023" -def test_the_registry_entries_that_name_a_release(): - """Each entry that names a release reads it through releases.json once - its repository has one, and follows its pointer file until then.""" - assert {spec.key: spec.release for spec in REGISTRY.values() if spec.release} == { +def test_each_registry_entry_names_its_release(): + """The loader reads each entry's release through its repository's + releases.json.""" + assert {spec.key: spec.release for spec in REGISTRY.values()} == { ("us", 2024, DEFAULT_VARIANT): "microcosm-us-2024-national", ("uk", 2023, DEFAULT_VARIANT): "populace-uk-2023", ("uk", 2025, DEFAULT_VARIANT): "microcosm-uk-2024-25-national", 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..601bf075a0 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_release.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_release.py @@ -100,73 +100,6 @@ def test_pointer_payload_names_every_contract_file() -> None: ) -@pytest.mark.parametrize( - ("release_id", "line", "revision"), - [ - (UK_NATIONAL_RELEASE_ID, "national", UK_NATIONAL_CUT_TAG), - (UK_LOCAL_RELEASE_ID, "local-k55000", UK_LOCAL_RELEASE_ID), - ], -) -def test_line_pointer_payload_round_trips_for_each_line_path( - hub: FakeHub, release_id: str, line: str, revision: str -) -> None: - payload = line_pointer_payload( - release_id, - line=line, - revision=revision, - updated_at="2026-09-20T12:00:00+00:00", - ) - pointer_path = line_pointer_path(line) - hub.seed_main_file(pointer_path, json.dumps(payload).encode()) - - pointer = latest_line_release("policyengine/populace-us", line=line, api=hub) - - assert pointer.release_id == release_id - assert pointer.revision == revision - assert pointer.line == line - assert pointer.updated_at == "2026-09-20T12:00:00+00:00" - assert payload["schema_version"] == LATEST_POINTER_SCHEMA_VERSION - assert pointer_path == f"latest-{line}.json" - - -@pytest.mark.parametrize( - "line", - ["", "National", "local-k0", "local-k01", "national/other"], -) -def test_line_pointer_path_refuses_invalid_lines(line: str) -> None: - with pytest.raises(ValueError, match="invalid release line"): - line_pointer_path(line) - - -@pytest.mark.parametrize( - "revision", - [ - "", - UK_NATIONAL_RELEASE_ID + "-hotfix", - UK_NATIONAL_RELEASE_ID + "-20260920t120000Z-deadbeef", - UK_NATIONAL_RELEASE_ID + "-20260920T120000Z-DEADBEEF", - ], -) -def test_line_pointer_payload_refuses_revisions_outside_the_cut_family( - revision: str, -) -> None: - with pytest.raises(ValueError, match="per-cut tag"): - line_pointer_payload( - UK_NATIONAL_RELEASE_ID, - line="national", - revision=revision, - ) - - -def test_line_pointer_payload_refuses_a_line_id_mismatch() -> None: - with pytest.raises(ValueError, match="belongs to line 'national'"): - line_pointer_payload( - UK_NATIONAL_RELEASE_ID, - line="local-k55000", - revision=UK_NATIONAL_CUT_TAG, - ) - - def _write_uk_build_folder_release( release_id: str, release_dir: Path, tmp_path: Path ) -> Path: @@ -708,56 +641,6 @@ def test_exact_k_tag_only_publish_never_mutates_main( ) -@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: @@ -1305,114 +1188,6 @@ def test_missing_extra_file_fails_loudly(hub: FakeHub, release_dir: Path) -> Non assert hub.uploads == [] -def test_publish_then_resolve_round_trips( - hub: FakeHub, release_dir: Path, artifact_root: Path -) -> None: - published = publish_release( - release_dir, - "policyengine/populace-us", - api=hub, - artifact_root=artifact_root, - updated_at="2026-06-11T13:53:15+00:00", - ) - 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"] - - -@pytest.mark.parametrize("field", ["line", "revision"]) -def test_latest_release_refuses_line_pointer_fields(hub: FakeHub, field: str) -> None: - payload = latest_pointer_payload(RELEASE_ID) - payload[field] = None - hub.seed_main_file(LATEST_POINTER_PATH, json.dumps(payload).encode()) - - with pytest.raises(ValueError, match=field): - latest_release("policyengine/populace-us", api=hub) - - -@pytest.mark.parametrize( - ("field", "value", "message"), - [ - ("line", "local-k55000", "declares line"), - ("revision", None, "revision"), - ("revision", "", "revision"), - ("revision", UK_NATIONAL_RELEASE_ID + "-hotfix", "revision"), - ("tier", "certified", "tier"), - ], -) -def test_latest_line_release_refuses_foreign_pointer_fields( - hub: FakeHub, field: str, value: object, message: str -) -> None: - payload = line_pointer_payload( - UK_NATIONAL_RELEASE_ID, - line="national", - revision=UK_NATIONAL_CUT_TAG, - ) - payload[field] = value - hub.seed_main_file(line_pointer_path("national"), json.dumps(payload).encode()) - - with pytest.raises(ValueError, match=message): - latest_line_release("policyengine/populace-us", line="national", api=hub) - - -def test_latest_line_release_refuses_a_release_from_another_line( - hub: FakeHub, -) -> None: - payload = latest_pointer_payload(UK_LOCAL_RELEASE_ID) - payload.update(line="national", revision=UK_LOCAL_RELEASE_ID) - hub.seed_main_file(line_pointer_path("national"), json.dumps(payload).encode()) - - with pytest.raises(ValueError, match="belongs to line 'local-k55000'"): - latest_line_release("policyengine/populace-us", line="national", api=hub) - - -def test_future_pointer_schema_is_refused(hub: FakeHub) -> None: - hub.seed_main_file( - LATEST_POINTER_PATH, - json.dumps({"schema_version": LATEST_POINTER_SCHEMA_VERSION + 1}).encode(), - ) - with pytest.raises(ValueError, match="Upgrade microcosm-data"): - latest_release("policyengine/populace-us", api=hub) - - -def test_pointer_without_release_id_is_refused(hub: FakeHub) -> None: - hub.seed_main_file( - LATEST_POINTER_PATH, - json.dumps({"schema_version": LATEST_POINTER_SCHEMA_VERSION}).encode(), - ) - with pytest.raises(ValueError, match="release_id"): - latest_release("policyengine/populace-us", api=hub) - - -def test_pointer_without_contract_paths_is_refused(hub: FakeHub) -> None: - hub.seed_main_file( - LATEST_POINTER_PATH, - json.dumps( - { - "schema_version": LATEST_POINTER_SCHEMA_VERSION, - "release_id": RELEASE_ID, - "paths": {"build_manifest": "releases/x/build_manifest.json"}, - } - ).encode(), - ) - with pytest.raises(ValueError, match="paths"): - latest_release("policyengine/populace-us", api=hub) - - -def test_pointer_with_swapped_contract_path_is_refused(hub: FakeHub) -> None: - payload = latest_pointer_payload(RELEASE_ID) - payload["paths"]["build_manifest"] = ( - f"releases/{RELEASE_ID}/calibration_diagnostics.json" - ) - hub.seed_main_file(LATEST_POINTER_PATH, json.dumps(payload).encode()) - - with pytest.raises(ValueError, match="malformed=\\['build_manifest'\\]"): - latest_release("policyengine/populace-us", api=hub) - - def test_evidence_pointer_payload_mirrors_the_certified_payload() -> None: updated_at = "2026-07-22T13:53:15+00:00" certified_shape = latest_pointer_payload(EVIDENCE_RELEASE_ID, updated_at=updated_at) @@ -1526,116 +1301,10 @@ def test_publish_evidence_release_announces_the_tier( ] -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 - assert pointer.tier == "evidence" - assert pointer.updated_at == "2026-07-22T13:53:15+00:00" - assert ( - pointer.paths["build_manifest"] - == f"releases/{EVIDENCE_RELEASE_ID}/build_manifest.json" - ) - - -def test_latest_release_refuses_an_evidence_tier_pointer(hub: FakeHub) -> None: - """Tier defense on the certified consumer: if an evidence payload ever - lands in latest.json, readers refuse it rather than certify it.""" - payload = latest_evidence_pointer_payload(EVIDENCE_RELEASE_ID) - hub.seed_main_file(LATEST_POINTER_PATH, json.dumps(payload).encode()) - - with pytest.raises(ValueError, match="tier"): - latest_release("policyengine/populace-us", api=hub) - - -def test_latest_evidence_release_requires_the_evidence_tier(hub: FakeHub) -> None: - payload = latest_pointer_payload(EVIDENCE_RELEASE_ID) - hub.seed_main_file(LATEST_EVIDENCE_POINTER_PATH, json.dumps(payload).encode()) - - with pytest.raises(ValueError, match="tier"): - latest_evidence_release("policyengine/populace-us", api=hub) - - -def test_latest_evidence_release_requires_the_id_segment(hub: FakeHub) -> None: - payload = latest_evidence_pointer_payload(RELEASE_ID) - hub.seed_main_file(LATEST_EVIDENCE_POINTER_PATH, json.dumps(payload).encode()) - - with pytest.raises(ValueError, match="-evidence-"): - latest_evidence_release("policyengine/populace-us", api=hub) - - #: An evidence-tier build of the US evidence release (microcosm#1570). US_EVIDENCE_BUILD = "populace-us-2024-0fb05b6-evidence-20261201T000000Z" -def _seed_us_releases_record(hub: FakeHub, *, evidence_current: str | None) -> None: - """The US repository's releases.json after its switch, with the evidence - release's current build ``evidence_current``.""" - from microcosm.data.contract import US_EVIDENCE_RELEASE_ID, US_NATIONAL_RELEASE_ID - - record = { - "schema_version": 1, - "default": US_NATIONAL_RELEASE_ID, - "releases": { - US_NATIONAL_RELEASE_ID: {"role": "national", "current": None, "builds": {}}, - US_EVIDENCE_RELEASE_ID: { - "role": "national", - "current": evidence_current, - "builds": { - US_EVIDENCE_BUILD: { - "published_at": "2026-12-01T00:00:00+00:00", - "withdrawn": False, - } - }, - }, - }, - } - hub.seed_main_file("releases.json", json.dumps(record).encode()) - - -def test_latest_evidence_release_reads_the_evidence_releases_current_build( - hub: FakeHub, -) -> None: - """Once the US repository records its builds in releases.json, the - evidence tier is the evidence release, and its current build takes the - place of latest-evidence.json (microcosm#1570).""" - from microcosm.data.contract import US_EVIDENCE_RELEASE_ID - - _seed_us_releases_record(hub, evidence_current=US_EVIDENCE_BUILD) - - pointer = latest_evidence_release("policyengine/populace-us", api=hub) - - folder = f"releases/{US_EVIDENCE_RELEASE_ID}/{US_EVIDENCE_BUILD}" - assert pointer.release_id == US_EVIDENCE_BUILD - # A build folder never changes, so its files are read at main. - assert pointer.revision == "main" - assert pointer.tier == "evidence" - assert pointer.line is None - assert pointer.updated_at == "2026-12-01T00:00:00+00:00" - assert pointer.paths["release_manifest"] == f"{folder}/release_manifest.json" - assert pointer.paths["build_manifest"] == f"{folder}/build_manifest.json" - - -def test_latest_evidence_release_refuses_an_evidence_release_without_a_current_build( - hub: FakeHub, -) -> None: - _seed_us_releases_record(hub, evidence_current=None) - - with pytest.raises(ValueError, match="no current build"): - latest_evidence_release("policyengine/populace-us", api=hub) - - @pytest.mark.parametrize("status_code", [None, 403, 503]) def test_a_hub_that_could_not_be_asked_is_not_an_absent_file( status_code: int | None, @@ -1653,63 +1322,6 @@ def test_a_hub_that_could_not_be_asked_is_not_an_absent_file( ) -def _evidence_pointer_without_releases_record(hub: FakeHub, monkeypatch) -> None: - """A repository before its switch, with latest-evidence.json, whose - releases.json the Hub cannot be asked for.""" - from test_support.microcosm_data import hub_errors - - payload = latest_evidence_pointer_payload(EVIDENCE_RELEASE_ID) - hub.seed_main_file(LATEST_EVIDENCE_POINTER_PATH, json.dumps(payload).encode()) - download = hub.hf_hub_download - - def no_releases_record(*, repo_id, filename, repo_type, revision=None): - if filename == "releases.json": - raise hub_errors.hub_unreachable(repo_id, filename, revision) - return download( - repo_id=repo_id, filename=filename, repo_type=repo_type, revision=revision - ) - - monkeypatch.setattr(hub, "hf_hub_download", no_releases_record) - - -def test_latest_evidence_release_offline_reads_a_cached_pointer_before_the_switch( - hub: FakeHub, monkeypatch -) -> None: - """Offline, a releases.json that was never cached reads as absent, as in - the loader, so the cached latest-evidence.json still answers (review of - #1571).""" - from huggingface_hub import constants - - _evidence_pointer_without_releases_record(hub, monkeypatch) - monkeypatch.setattr(constants, "HF_HUB_OFFLINE", True) - - pointer = latest_evidence_release("policyengine/populace-us", api=hub) - - assert pointer.release_id == EVIDENCE_RELEASE_ID - - -def test_latest_evidence_release_online_refuses_when_the_hub_cannot_be_asked( - hub: FakeHub, monkeypatch -) -> None: - from huggingface_hub import constants - - _evidence_pointer_without_releases_record(hub, monkeypatch) - monkeypatch.setattr(constants, "HF_HUB_OFFLINE", False) - - with pytest.raises(LocalEntryNotFoundError): - latest_evidence_release("policyengine/populace-us", api=hub) - - -def test_certified_latest_pointer_keeps_its_certified_shape(hub: FakeHub) -> None: - """The certified pointer payload gains no tier field — its bytes are the - pre-#506 shape, so existing consumers see no drift.""" - payload = latest_pointer_payload(RELEASE_ID, updated_at="2026-06-11T00:00:00+00:00") - assert "tier" not in payload - hub.seed_main_file(LATEST_POINTER_PATH, json.dumps(payload).encode()) - pointer = latest_release("policyengine/populace-us", api=hub) - assert pointer.tier == "certified" - - def test_certified_publish_never_touches_the_evidence_pointer( hub: FakeHub, release_dir: Path, artifact_root: Path ) -> None: @@ -1726,17 +1338,6 @@ def test_certified_publish_never_touches_the_evidence_pointer( 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.""" - for tier_value in ("certified", None): - payload = latest_pointer_payload(RELEASE_ID) - payload["tier"] = tier_value - hub.seed_main_file(LATEST_POINTER_PATH, json.dumps(payload).encode()) - with pytest.raises(ValueError, match="tier"): - 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: @@ -2142,41 +1743,6 @@ def no_hub(*args, **kwargs): 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", - ) - - 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 - ) - - def test_retry_after_a_failed_pointer_commit_reuses_the_tag( hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch ) -> None: @@ -2232,11 +1798,6 @@ def test_publication_refuses_a_tag_that_describes_another_release( 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: 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..f8b8c3512f 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 @@ -23,7 +23,6 @@ from microcosm.data.contract import ( REQUIRED_RELEASE_FILES, ReleaseContractError, - line_for_release_id, publishes_to_build_folder, required_release_files, validate_release_dir, @@ -160,8 +159,6 @@ def test_a_uk_local_area_release_publishes_only_once_the_registry_names_it(drawn 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 @@ -189,18 +186,17 @@ def test_a_registered_k_admits_its_own_name_and_no_other(): @pytest.mark.parametrize( "changes", ( - {"release": None}, {"release": contract._UK_DENSE_RELEASE_ID}, {"release": "microcosm-uk-2024-25-local-k70"}, {"country": "us"}, ), - ids=("no-release", "another-release", "a-longer-k", "a-us-entry"), + ids=("another-release", "a-longer-k", "a-us-entry"), ) def test_only_a_uk_entrys_release_admits_a_k(changes): """A ``k`` is registered by a UK entry's ``release`` and by nothing else. An entry whose variant and file name carry ``local-k7`` admits nothing - when its release is missing or names another release, and a US entry - that names the UK release admits nothing either.""" + when its release names another release, and a US entry that names the UK + release admits nothing either.""" release_id = _uk_local_release_id(7) spec = dataclasses.replace(uk_local_release_spec(release_id), **changes) @@ -241,23 +237,6 @@ def test_registering_a_name_outside_the_local_area_grammar_admits_nothing(releas assert not contract.unregistered_uk_local_release(release_id) -@pytest.mark.parametrize( - "release_id", (*UNLISTED_IDS, TAGGED_US_ID, *contract.US_RELEASES) -) -def test_only_uk_names_have_a_pointer_line(release_id): - """``line_for_release_id`` gives the ```` of a ``latest-.json`` - pointer file, which only the pointer reader still needs. No US release and - no unlisted name has one.""" - - assert line_for_release_id(release_id) is None - - -def test_the_uk_national_and_local_lines_are_the_only_lines(): - assert line_for_release_id(contract._UK_NATIONAL_RELEASE_ID) == "national" - assert line_for_release_id("microcosm-uk-2024-25-local-k55000") == "local-k55000" - assert line_for_release_id(contract._UK_DENSE_RELEASE_ID) is None - - def test_the_registry_year_is_not_the_uk_national_releases_vintage(): # The national release is the UK 2025 default load since microcosm#1432 # (Max's #823 ruling). diff --git a/packages/microcosm-data/tests/fixtures/release_contract/v1/SHA256SUMS b/packages/microcosm-data/tests/fixtures/release_contract/v1/SHA256SUMS index 20deb330f4..e9ca521882 100644 --- a/packages/microcosm-data/tests/fixtures/release_contract/v1/SHA256SUMS +++ b/packages/microcosm-data/tests/fixtures/release_contract/v1/SHA256SUMS @@ -1,9 +1,9 @@ -ef662a0787031c95b95e745cabffd41b3a7b92ab11283c2343af0bffad4bd904 c1/inventory.json +8d48e59af06fabb5b5e582c18f29e7586dd26753589084eb32f2c2634461bba4 c1/inventory.json 8e53c9192be76a2e9b691919ce27598695b1403073de791ac0f7b23d09f434e0 c1/microcosm-uk-2024-25-national/build_manifest.json c10d33a17e23a1f18b53fad775077bbe4bd76012f877821af194d709ef69f640 c1/microcosm-uk-2024-25-national/release_manifest.json 1cdfc01a19324729b2cb9e456c17a3684fa50f28f7c21889340ad81a46f103c4 c1/microcosm-us-2024-national/build_manifest.json a0846ca19b3164302d5093c7eecd2e611d727f6149b906dacfa56b83376f4495 c1/microcosm-us-2024-national/release_manifest.json -2f8c927b5e0b53dfc8315b38f67d92dae7c1d7574b1fc55ee48ea8133df2eb50 c5/registry.json +10b69436239ecec30f5318cba8052919aac5b5273d4dc1f0bd1bdf8bcd06f1d6 c5/registry.json 1230f545477e6f095f94c1b61539a60a76f14f10146a2b022ea6f3aa66323dbd c5/uk/releases.json 51061e4109b7c5e45e7ba0bcd0efc366d0ed54fe906c737a63ddc1f821a0ff96 c5/us/releases.json 997af7b89d2119b2fa9fc2ba601aa9e37bac593c4eca36d17ceec55a5c2ae910 writers.json diff --git a/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/inventory.json b/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/inventory.json index 3dc2f8e006..fefb9667c7 100644 --- a/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/inventory.json +++ b/packages/microcosm-data/tests/fixtures/release_contract/v1/c1/inventory.json @@ -36,7 +36,6 @@ "signing_key_env": "MICROCOSM_UK_TERMINAL_GATE_SIGNING_KEY" }, "dataset_role": "national_default", - "line": "national", "publishes_to_build_folder": true, "release_directory_files": [ "build_manifest.json", diff --git a/packages/microcosm-data/tests/fixtures/release_contract/v1/c5/registry.json b/packages/microcosm-data/tests/fixtures/release_contract/v1/c5/registry.json index da6a6283f9..b6b874d989 100644 --- a/packages/microcosm-data/tests/fixtures/release_contract/v1/c5/registry.json +++ b/packages/microcosm-data/tests/fixtures/release_contract/v1/c5/registry.json @@ -14,7 +14,6 @@ 2023, "compact" ], - "pointer_path": "latest.json", "release": "populace-uk-2023", "variant": "compact", "year": 2023 @@ -32,7 +31,6 @@ 2025, "compact" ], - "pointer_path": "latest-national.json", "release": "microcosm-uk-2024-25-national", "variant": "compact", "year": 2025 @@ -50,7 +48,6 @@ 2025, "dense" ], - "pointer_path": "latest.json", "release": "microcosm-uk-2024-25-dense", "variant": "dense", "year": 2025 @@ -68,7 +65,6 @@ 2024, "compact" ], - "pointer_path": "latest.json", "release": "microcosm-us-2024-national", "variant": "compact", "year": 2024 diff --git a/test_support/microcosm_data/loader.py b/test_support/microcosm_data/loader.py index e6b1db85ad..4913bfd425 100644 --- a/test_support/microcosm_data/loader.py +++ b/test_support/microcosm_data/loader.py @@ -18,124 +18,6 @@ import microcosm.data.loader as loader from microcosm.data import DEFAULT_VARIANT, download, latest_year, load, resolve -from microcosm.data.release import LATEST_POINTER_PATH, latest_pointer_payload - -#: Release id served by the hub fixture. Any well-formed id works: nothing in -#: this suite may assert which release the live Hub currently points at, -#: because re-certification moves ``latest.json`` without a commit here. -RELEASE_ID = "populace-us-2024-buildi-sparse-rmloss100-6e8e929-20260709T034135Z" -TAGGED_ARTIFACT = b"certified release artifact" -MUTABLE_ROOT_ARTIFACT = b"uncertified in-flight root artifact" - - -def _release_manifest( - *, - artifact_content: bytes = TAGGED_ARTIFACT, - release_id: str = RELEASE_ID, -) -> dict: - return { - "schema_version": 1, - "data_package": {"name": "microcosm-data", "version": "0.1.0"}, - "default_datasets": {"national": "populace_us_2024"}, - "build": { - "build_id": release_id, - "built_with_core_package": { - "name": "policyengine-core", - "version": "3.26.11", - }, - "built_with_model_package": { - "name": "policyengine-us", - "version": "1.764.6", - }, - }, - "compatible_core_packages": [ - {"name": "policyengine-core", "specifier": "==3.26.11"} - ], - "compatible_model_packages": [ - {"name": "policyengine-us", "specifier": "==1.764.6"} - ], - "artifacts": { - "populace_us_2024": { - "kind": "microdata", - "path": "populace_us_2024.h5", - "repo_id": "policyengine/populace-us", - "revision": release_id, - "sha256": hashlib.sha256(artifact_content).hexdigest(), - } - }, - } - - -class FakeHubDownload: - """Serve mutable and release-tagged files while recording every request.""" - - def __init__(self, tmp_path: Path, *, manifest: dict | None = None) -> None: - pointer = latest_pointer_payload( - RELEASE_ID, updated_at="2026-07-09T04:00:00+00:00" - ) - manifest = manifest or _release_manifest() - self.tmp_path = tmp_path - self.calls: list[tuple[str, str, str | None]] = [] - self.files: dict[tuple[str, str, str | None], Path] = {} - self._add( - tmp_path, - "policyengine/populace-us", - LATEST_POINTER_PATH, - None, - json.dumps(pointer).encode(), - ) - self._add( - tmp_path, - "policyengine/populace-us", - pointer["paths"]["release_manifest"], - RELEASE_ID, - json.dumps(manifest).encode(), - ) - self._add( - tmp_path, - "policyengine/populace-us", - "populace_us_2024.h5", - RELEASE_ID, - TAGGED_ARTIFACT, - ) - self._add( - tmp_path, - "policyengine/populace-us", - "populace_us_2024.h5", - None, - MUTABLE_ROOT_ARTIFACT, - ) - - def _add( - self, - tmp_path: Path, - repo_id: str, - filename: str, - revision: str | None, - content: bytes, - ) -> None: - revision_dir = revision or "main" - local = tmp_path / "hub" / revision_dir / filename - local.parent.mkdir(parents=True, exist_ok=True) - local.write_bytes(content) - self.files[(repo_id, filename, revision)] = local - - def __call__( - self, - *, - repo_id: str, - filename: str, - repo_type: str, - revision: str | None = None, - ) -> str: - assert repo_type == "dataset" - self.calls.append((repo_id, filename, revision)) - try: - return str(self.files[(repo_id, filename, revision)]) - except KeyError as exc: - raise FileNotFoundError( - f"{repo_id}/{filename} at revision {revision!r}" - ) from exc def _patch_engine( diff --git a/test_support/microcosm_data/release.py b/test_support/microcosm_data/release.py index 5d0f90e30f..09bed75b1c 100644 --- a/test_support/microcosm_data/release.py +++ b/test_support/microcosm_data/release.py @@ -33,12 +33,7 @@ LATEST_POINTER_PATH, LATEST_POINTER_SCHEMA_VERSION, latest_evidence_pointer_payload, - latest_evidence_release, - latest_line_release, latest_pointer_payload, - latest_release, - line_pointer_path, - line_pointer_payload, publish_release, ) from microcosm.data.stored_inputs import register_sha256 diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 7d544a5041..731838d8f8 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -3704,9 +3704,8 @@ def _download_base_h5() -> Path: """The base a run without ``--base-h5`` starts from: the US national release's current build, SHA-verified by the loader (microcosm#1570). - It is read from ``releases.json`` once the repository has one and from - ``latest.json`` until then. The repository's root file stops changing at - the switch, since builds published into folders write no root files. + It is read from ``releases.json``. The repository's root file stopped + changing at the US switch, which deleted it with ``latest.json``. """ from microcosm.data import download diff --git a/tools/generate_release_contract_fixtures.py b/tools/generate_release_contract_fixtures.py index 8c4a7e8998..016d99f5d2 100644 --- a/tools/generate_release_contract_fixtures.py +++ b/tools/generate_release_contract_fixtures.py @@ -151,7 +151,6 @@ #: The US national build's name: a build ID with the ``populace-us-`` prefix #: the US builder requires (``_assert_us_release_id``). US_BUILD = "populace-us-2024-0000000-20260101" -UK_LINE = "national" #: Synthetic runtime versions. Each is a resolved PEP 440 version, which is all the #: contract asks of a runtime pin. UK_RUNTIME = { @@ -308,12 +307,11 @@ def _c1_uk_national(root: Path, assembler: ModuleType) -> None: def _c1_inventory(root: Path, assembler: ModuleType) -> None: """Write what the live contract requires of the UK national release.""" - dataset_role = contract.dataset_role_for_line(UK_LINE) + dataset_role = contract.NATIONAL_DEFAULT_DATASET_ROLE inventory = { "schema_name": "microcosm.release-contract.c1-inventory", "schema_version": 1, "release_id": UK_RELEASE, - "line": contract.line_for_release_id(UK_RELEASE), "dataset_role": dataset_role, "release_role": contract.RELEASE_ROLES[dataset_role], "publishes_to_build_folder": contract.publishes_to_build_folder(UK_RELEASE), @@ -461,7 +459,7 @@ def _c5_releases(root: Path) -> None: "uk": _one_current_build( release=UK_RELEASE, build=UK_BUILD, - role=contract.RELEASE_ROLES[contract.dataset_role_for_line(UK_LINE)], + role=contract.RELEASE_ROLES[contract.NATIONAL_DEFAULT_DATASET_ROLE], ), "us": _one_current_build( release=US_RELEASE, diff --git a/tools/stage_uk_rowwise_candidate.py b/tools/stage_uk_rowwise_candidate.py index 29bfa85ec7..5cfd1bcfa3 100644 --- a/tools/stage_uk_rowwise_candidate.py +++ b/tools/stage_uk_rowwise_candidate.py @@ -77,7 +77,7 @@ them before it closes the emitter. A hand-over the command resumes keeps what the build named, and its collector receipt is followed the same way. -Staging is not publication: ``releases/`` and ``latest.json`` are untouched. +Staging is not publication: ``releases/`` and ``releases.json`` are untouched. """ from __future__ import annotations From e7dbcaf10ec8c3cd35852e0844c561e0b9664718 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:21:21 +0400 Subject: [PATCH 5/9] Fix review round 1: tests left on the removed loader arguments (#1794) Review round 1 found three bugs, all in tests or CI behaviour: - High: three tests still passed the removed expected_revision keyword to the loader's manifest check (two in test_release_contract_fixtures, one in test_release_contract_fixture_generation), so each raised TypeError. The keyword is gone. - Medium: test_declared_range_certifies_a_later_patch_for_both_readers handed the loader's package-certification reader a tagged-layout manifest; the loader now reads only build folders, so the test rewrites the manifest with the builders' own build_folder_release_manifest first. - Medium: the six cases of the export test for names the tagged publisher still uses failed on purpose, and the engine-free job stops at its first failure. They are now strict expected failures, so CI reports the rest, and the marks must go when the names do. Also from the review: the live-load helper's offline check follows the loader's refusal to its cause, so an offline US engine run still skips; the ruff configuration comment, the Armenia notes, the UK staging operations guide and two release-contract sentences no longer describe pointer files or the loader reading tagged builds. Co-Authored-By: Claude Opus 5.5 --- docs/armenia-country-package-814/NOTES.md | 5 +- docs/release-contract.md | 7 ++- docs/uk-staging-operations.md | 2 +- ...est_release_contract_fixture_generation.py | 1 - .../tests/engine_free/shared/test_loader.py | 4 ++ .../shared/test_no_pointer_files.py | 56 ++++++++++++++----- .../shared/test_release_contract_fixtures.py | 2 - .../shared/test_source_enrichment.py | 11 +++- pyproject.toml | 2 +- test_support/microcosm_data/loader.py | 4 ++ 10 files changed, 67 insertions(+), 27 deletions(-) diff --git a/docs/armenia-country-package-814/NOTES.md b/docs/armenia-country-package-814/NOTES.md index 7a38856a54..b61d875e68 100644 --- a/docs/armenia-country-package-814/NOTES.md +++ b/docs/armenia-country-package-814/NOTES.md @@ -108,8 +108,9 @@ candidate release. The public release must carry the country-neutral `source_coverage.json` contract tracked by `microcosm#265`, plus calibration diagnostics, validation bands, build/release manifests, and an explicit donor-provenance banner. -`latest.json` is an atomic pointer uploaded last; nothing in this spec-only -package publishes an artifact. +Each build is to publish into its own folder, `releases///`, +which `releases.json` lists, as the release contract says; no pointer file +names a build. Nothing in this spec-only package publishes an artifact. ## Amount and currency boundary diff --git a/docs/release-contract.md b/docs/release-contract.md index c6612cdfb9..1d714a4354 100644 --- a/docs/release-contract.md +++ b/docs/release-contract.md @@ -1130,8 +1130,9 @@ work. - *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. + refusal of a new country's tagged publish. A tagged build that never + moved into a folder stays readable by its path at its tag; the loader + reads no tagged build (microcosm#1794). - *The policyengine.py certification tool.* `tools/certify_uk_cut_in_policyengine_py.py` still reads a national build's manifests at its tag (`--national-tag`), so it cannot certify a @@ -1470,7 +1471,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. `latest_evidence_release`, which no module called, left with the pointer readers (microcosm#1794). Whoever retires the release must first find, from code, the readers of the 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. 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). A tagged build that never moved into a folder stays readable by its path at its tag; the loader reads no tagged build (microcosm#1794) | | 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/docs/uk-staging-operations.md b/docs/uk-staging-operations.md index 1ef396f10f..5df340a185 100644 --- a/docs/uk-staging-operations.md +++ b/docs/uk-staging-operations.md @@ -259,7 +259,7 @@ emitter submits them to the collector (see `staged_manifest` and `checksums`. The emitter writes the bundle in one commit with the build's own credential, and its receipt becomes the bundle's `staged_dataset` record, with the commit as -its revision. `releases/` and `latest.json` are never touched, no tag is +its revision. `releases/` and `releases.json` are never touched, no tag is created, and the release contract is not consulted: a staged bundle is not a release and cannot be loaded as one. diff --git a/packages/microcosm-build/tests/engine_free/shared/test_release_contract_fixture_generation.py b/packages/microcosm-build/tests/engine_free/shared/test_release_contract_fixture_generation.py index 54a8368faf..e36ccb50e9 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_release_contract_fixture_generation.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_release_contract_fixture_generation.py @@ -381,7 +381,6 @@ def test_national_manifests_satisfy_the_release_contract(inputs): UK_NATIONAL_SPEC, release_id, release_manifest, - expected_revision=None, build=entry.current, release_role=entry.role, ) diff --git a/packages/microcosm-data/tests/engine_free/shared/test_loader.py b/packages/microcosm-data/tests/engine_free/shared/test_loader.py index 2b4046d189..e8e96d4ec0 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_loader.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_loader.py @@ -769,10 +769,14 @@ def _is_offline_error(exc: Exception) -> bool: closed_after_retry = isinstance(exc, RuntimeError) and str(exc) == ( "Cannot send a request, as the client has been closed." ) + # Offline, the loader refuses a releases.json never cached with a + # ValueError whose cause is the Hub client's error. + cause = exc.__cause__ return ( isinstance(exc, (ConnectionError, TimeoutError)) or closed_after_retry or any(cls.__name__ in offline_names for cls in type(exc).__mro__) + or (isinstance(cause, Exception) and _is_offline_error(cause)) ) diff --git a/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py b/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py index 3cb46a8f11..6841b02809 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py @@ -31,22 +31,48 @@ TAGGED_BUILD = "populace-us-2024-spm-20260915" TAGGED_DATASET = b"a dataset at its tag" +#: The names the tagged publisher, ``publish_release``, still uses to write +#: pointer files. They leave ``microcosm.data.release`` with it; until then +#: their cases are expected to fail, and strictly, so the marks must go when +#: the names do. ``microcosm.data`` exports none of them already. +_TAGGED_PUBLISHER_NAMES = frozenset( + { + "LATEST_POINTER_PATH", + "LATEST_EVIDENCE_POINTER_PATH", + "LATEST_POINTER_SCHEMA_VERSION", + "RELEASE_TIER_EVIDENCE", + "latest_pointer_payload", + "latest_evidence_pointer_payload", + } +) + #: Every public name the pointer-file reader and writer had. -POINTER_FILE_NAMES = ( - "LATEST_POINTER_PATH", - "LINE_POINTER_PATH_TEMPLATE", - "LATEST_EVIDENCE_POINTER_PATH", - "LATEST_POINTER_SCHEMA_VERSION", - "RELEASE_TIER_CERTIFIED", - "RELEASE_TIER_EVIDENCE", - "LatestPointer", - "latest_release", - "latest_line_release", - "latest_evidence_release", - "latest_pointer_payload", - "line_pointer_payload", - "latest_evidence_pointer_payload", - "line_pointer_path", +POINTER_FILE_NAMES = tuple( + pytest.param( + name, + marks=pytest.mark.xfail( + strict=True, + reason="removed with publish_release, the tagged publisher", + ), + ) + if name in _TAGGED_PUBLISHER_NAMES + else name + for name in ( + "LATEST_POINTER_PATH", + "LINE_POINTER_PATH_TEMPLATE", + "LATEST_EVIDENCE_POINTER_PATH", + "LATEST_POINTER_SCHEMA_VERSION", + "RELEASE_TIER_CERTIFIED", + "RELEASE_TIER_EVIDENCE", + "LatestPointer", + "latest_release", + "latest_line_release", + "latest_evidence_release", + "latest_pointer_payload", + "line_pointer_payload", + "latest_evidence_pointer_payload", + "line_pointer_path", + ) ) diff --git a/packages/microcosm-data/tests/engine_free/shared/test_release_contract_fixtures.py b/packages/microcosm-data/tests/engine_free/shared/test_release_contract_fixtures.py index 295231015a..ae00ac12a1 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_release_contract_fixtures.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_release_contract_fixtures.py @@ -363,7 +363,6 @@ def test_loader_selects_each_golden_build_through_its_releases_record(country): spec, release_id, release_manifest, - expected_revision=None, build=entry.current, release_role=entry.role, ) @@ -399,7 +398,6 @@ def test_loader_refuses_a_golden_build_under_the_other_role(country): spec, release_id, _manifests(country)[1], - expected_revision=None, build=entry.current, release_role=other_role, ) 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..30e0cabbc1 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 @@ -11,7 +11,10 @@ import pytest from microcosm.data import source_enrichment as enrichment -from microcosm.data.build_folder_manifests import rewrite_release_dir +from microcosm.data.build_folder_manifests import ( + build_folder_release_manifest, + rewrite_release_dir, +) from microcosm.data.contract import ( US_NATIONAL_RELEASE_ID, US_RECEIPT_DONOR_RELEASE_ID, @@ -1635,8 +1638,12 @@ def test_declared_range_certifies_a_later_patch_for_both_readers( output, _ = _qualify_candidate(candidate, tmp_path, monkeypatch, **_declare()) manifest, _ = _certified(output) + # The loader reads a build in its own folder, whose release manifest + # carries the built-with packages at its top level. certification = _package_certification( - manifest, + build_folder_release_manifest( + manifest, release=US_NATIONAL_RELEASE_ID, build=output.name + ), field="compatible_model_packages", package_name="policyengine-us", built_field="built_with_model_package", diff --git a/pyproject.toml b/pyproject.toml index cd8b8e13b5..1ab694c676 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -49,7 +49,7 @@ ignore = ["E501"] # TID251, huggingface_hub outside the emitter. Datasets and the release # metadata that selects and verifies them: the loader, the publisher's # listing of the repository (its parent and annual base checks, and its -# refusal of BE-era latest*.json pointer files, which 5b removes), a UK +# refusal of any latest*.json pointer file in the repository), 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. diff --git a/test_support/microcosm_data/loader.py b/test_support/microcosm_data/loader.py index 4913bfd425..a173fd16c0 100644 --- a/test_support/microcosm_data/loader.py +++ b/test_support/microcosm_data/loader.py @@ -72,10 +72,14 @@ def _is_offline_error(exc: Exception) -> bool: closed_after_retry = isinstance(exc, RuntimeError) and str(exc) == ( "Cannot send a request, as the client has been closed." ) + # Offline, the loader refuses a releases.json never cached with a + # ValueError whose cause is the Hub client's error. + cause = exc.__cause__ return ( isinstance(exc, (ConnectionError, TimeoutError)) or closed_after_retry or any(cls.__name__ in offline_names for cls in type(exc).__mro__) + or (isinstance(cause, Exception) and _is_offline_error(cause)) ) From 5752caec7eb9fbcd5e91b5c62001880d32840957 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:03:36 +0400 Subject: [PATCH 6/9] Add a failing test: DatasetSpec takes release by keyword (#1794) Review round 2 noted that making release a required field moved it in front of variant, so a caller passing variant as the eighth positional argument would set release instead. The test fails on its assertion: the eighth positional field is release. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_no_pointer_files.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py b/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py index 6841b02809..7691cb17c5 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py @@ -98,6 +98,19 @@ def test_a_dataset_spec_must_name_its_release() -> None: ) +def test_a_dataset_spec_takes_its_release_by_keyword() -> None: + """``release`` is keyword-only, so the fields after the required ones keep + their positions: ``variant`` is still the eighth positional argument.""" + parameters = inspect.signature(DatasetSpec).parameters + positional = [ + name + for name, parameter in parameters.items() + if parameter.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD + ] + assert positional[7] == "variant" + assert parameters["release"].kind is inspect.Parameter.KEYWORD_ONLY + + @pytest.mark.parametrize("name", POINTER_FILE_NAMES) def test_microcosm_data_exports_no_pointer_file_reader_or_writer(name: str) -> None: assert not hasattr(microcosm.data, name) From 9f9cb4aa890afc6e3385b09095987af966077830 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:04:43 +0400 Subject: [PATCH 7/9] Address review round 2: release by keyword, and wording (#1794) Review round 2 found no bugs. From its code-quality points: - DatasetSpec.release is keyword-only, so variant keeps its position as the eighth positional argument (the test in 5752caec7 fails before). - docs/release-contract.md: C2 says the loader's certification reader reads a build-folder manifest's top level only, and the M1 row no longer says "where the repository has one". - DatasetSpec.hf_url's docstring says it names the root URL, which no repository holds a dataset at, for messages. - The tagged publisher's docstring says every release repository has releases.json, not only the UK and US ones. - The --base-h5 and --h5 help texts of build_us_fiscal_refresh_release and score_us_fiscal_targets name the current build in releases.json instead of "HF latest". - The offline check in both live-load helpers follows each cause once, so a cause cycle ends. - The changelog fragment names the one caller found outside this repository. Co-Authored-By: Claude Opus 5.5 --- ...op-reading-latest-pointer-files.removed.md | 2 +- docs/release-contract.md | 8 +++---- .../src/microcosm/data/registry.py | 13 ++++++++--- .../src/microcosm/data/release.py | 4 ++-- .../tests/engine_free/shared/test_loader.py | 22 ++++++++++++++----- test_support/microcosm_data/loader.py | 22 ++++++++++++++----- tools/build_us_fiscal_refresh_release.py | 5 ++++- tools/score_us_fiscal_targets.py | 5 ++++- 8 files changed, 57 insertions(+), 24 deletions(-) diff --git a/changelog.d/1794-stop-reading-latest-pointer-files.removed.md b/changelog.d/1794-stop-reading-latest-pointer-files.removed.md index 03697830ba..967667816a 100644 --- a/changelog.d/1794-stop-reading-latest-pointer-files.removed.md +++ b/changelog.d/1794-stop-reading-latest-pointer-files.removed.md @@ -1 +1 @@ -Stop reading and writing `latest*.json` pointer files (#1794): every release repository lists its builds in `releases.json`, and each repository's switch deleted its pointer files. The loader refuses a repository without `releases.json`, online and offline, instead of following `latest.json` or a UK release's `latest-.json`; `load()` loses its `unverified_root` option, since no repository holds a root dataset file; `DatasetSpec` loses `pointer_path` and must name its `release`. `microcosm.data` and `microcosm.data.release` no longer have `latest_release`, `latest_line_release`, `latest_evidence_release`, `LatestPointer`, the pointer payload builders, `line_pointer_path` or the pointer constants, and `microcosm.data.contract` no longer has `line_for_release_id` or `dataset_role_for_line`. `microcosm-publish-release-build` still refuses a repository that has a pointer file, now with one message for any repository: remove the file. AM's and NZ's release contracts name build folders and `releases.json` instead of `latest.json`. +Stop reading and writing `latest*.json` pointer files (#1794): every release repository lists its builds in `releases.json`, and each repository's switch deleted its pointer files. The loader refuses a repository without `releases.json`, online and offline, instead of following `latest.json` or a UK release's `latest-.json`; `load()` loses its `unverified_root` option, since no repository holds a root dataset file; `DatasetSpec` loses `pointer_path` and must name its `release`. `microcosm.data` and `microcosm.data.release` no longer have `latest_release`, `latest_line_release`, `latest_evidence_release`, `LatestPointer`, the pointer payload builders, `line_pointer_path` or the pointer constants, and `microcosm.data.contract` no longer has `line_for_release_id` or `dataset_role_for_line`. `microcosm-publish-release-build` still refuses a repository that has a pointer file, now with one message for any repository: remove the file. AM's and NZ's release contracts name build folders and `releases.json` instead of `latest.json`. A caller of a removed reader now fails at import, for example PolicyEngine/bottom-50-tax-analysis's call of `latest_release`, which already failed because no repository has `latest.json`. diff --git a/docs/release-contract.md b/docs/release-contract.md index 1d714a4354..7ad6c5f4ea 100644 --- a/docs/release-contract.md +++ b/docs/release-contract.md @@ -508,11 +508,11 @@ that `microcosm-publish-release-build` accepts. **microcosm.data's loader.** `_package_certification` reads `compatible_model_packages` and `compatible_core_packages` from the release -manifest, in either layout. It keeps each entry that names the package and +manifest of a build in its own folder. It keeps each entry that names the package and refuses a specifier that PEP 440 cannot parse. It then refuses the release unless an entry remains and the built version satisfies one of them. It reads -the built version from a build-folder manifest's top level and from a tagged -manifest's `build` object. At load, `_enforce_package_compatibility` refuses +the built version from the manifest's top level; since microcosm#1794 the +loader reads no tagged manifest. At load, `_enforce_package_compatibility` refuses unless the installed model package and the installed `policyengine-core` each satisfy one of their specifiers. Only `load` runs that check: `download`, `resolve_certified` and `download_certified` read and verify the same manifest @@ -1209,7 +1209,7 @@ version 1 takes that shape. | Milestone | Planned | Contract change | Owner | On main, 2026-11-12 | | --- | --- | --- | --- | --- | | M0 | 2026-10-16 | This document and the golden fixtures; nothing refuses | Max's session | microcosm#1285, which adds this document | -| M1 | 2026-10-23 | A UK national cut on policyengine-uk ≥ 2.122.2 with staging version 3, a Logbook row and a certification; the registry's UK default flips to it | juaristi22 | The registry flip, in microcosm#1432 (merged 2026-11-02). Since microcosm#1505 the entry also names release `microcosm-uk-2024-25-national`, and the loader reads that release's current build from `releases.json` where the repository has one. microcosm#1574 (merged 2026-11-11) moved the national certification to schema 2, which adds `reference` and `since_baseline`, and renamed the score receipt to `score_vs_reference.json`. This document does not check the current build's staging, Logbook row or certification on the Hub | +| M1 | 2026-10-23 | A UK national cut on policyengine-uk ≥ 2.122.2 with staging version 3, a Logbook row and a certification; the registry's UK default flips to it | juaristi22 | The registry flip, in microcosm#1432 (merged 2026-11-02). Since microcosm#1505 the entry also names release `microcosm-uk-2024-25-national`, and the loader reads that release's current build from `releases.json`. microcosm#1574 (merged 2026-11-11) moved the national certification to schema 2, which adds `reference` and `since_baseline`, and renamed the score receipt to `score_vs_reference.json`. This document does not check the current build's staging, Logbook row or certification on the Hub | | M2 | 2026-10-30 | `us/gates.json` and the US adapter (C1); the US writes staging version 3 and a Logbook row and records `producer` (C3, C4); staging version 1 goes; the registry gains an entry for the US local-area release, which carries the state and district file (C5); one compatibility rule in both loaders and, at publication, for every role (C2) | Max's session, PavelMakarchuk, anth-volk | Only `us/gates.json`, which the US tools evaluate in shadow without the adapter (microcosm#1585 item 11); the fiscal-refresh tool composes no certification, still writes staging version 1 through `StagingRunBundleWriter` and records no Logbook row; no release manifest records a `producer`; the registry has no entry for `microcosm-us-2024-local`; `_check_local_area_release_manifest` checks no compatibility list; and microcosm.data's loader keeps today's containment rule. policyengine.py, at 5b6d7901c on 2026-11-11, keeps its three bases and the `legacy_compatible_model_package` label | | M3 | 2026-11-06 | Release manifest schema 2 and declared-country dispatch; the validator refuses unknown countries, which also closes a new country's tagged publish; `microcosm-publish-release-build` refuses non-conforming builds, derived builds included; the staging re-delivery command; policyengine.py's registry check | Max's session, juaristi22, anth-volk | None of it: `RELEASE_MANIFEST_SCHEMA_VERSION` is 1; `required_release_files`, `_expected_model_package` and `publishes_to_build_folder` still key on the release name, and an unknown name still gets the base file set; `microcosm-publish-release-build` runs the nine checks that C5 lists under "Order" and adds none of M3's: no check it runs asks for a `run_outcome`, a Logbook row or a manifest's declared `country`, and `required_release_files` names `release_certification.json` for `microcosm-uk-2024-25-national` alone; C1's other certification rule keys on the gate files a directory carries, not on a declared country. `test_release_contract_keying.py`, which arrives with this document, pins today's keying. This document has not looked for policyengine.py's registry check | diff --git a/packages/microcosm-data/src/microcosm/data/registry.py b/packages/microcosm-data/src/microcosm/data/registry.py index 0df366eb12..cd7a3afde7 100644 --- a/packages/microcosm-data/src/microcosm/data/registry.py +++ b/packages/microcosm-data/src/microcosm/data/registry.py @@ -15,7 +15,7 @@ from __future__ import annotations -from dataclasses import dataclass +from dataclasses import dataclass, field __all__ = ["DEFAULT_VARIANT", "DatasetSpec", "REGISTRY", "register"] @@ -70,8 +70,10 @@ class DatasetSpec: engine_module: str engine_class: str engine_package: str - release: str variant: str = DEFAULT_VARIANT + # Keyword-only, so the fields after the required ones keep their + # positions now that every entry must name its release. + release: str = field(kw_only=True) build_folder_filename: str | None = None @property @@ -88,7 +90,12 @@ def key(self) -> tuple[str, int, str]: @property def hf_url(self) -> str: - """The ``hf://`` URL of the published artifact.""" + """``filename``'s ``hf://`` URL at the repository's root. + + It names the entry in messages such as :func:`register`'s. No + repository holds a dataset file at its root any more; each build's + file is in ``releases///``. + """ return f"hf://{self.hf_repo}/{self.filename}" diff --git a/packages/microcosm-data/src/microcosm/data/release.py b/packages/microcosm-data/src/microcosm/data/release.py index 243bc3f16b..dba3976f95 100644 --- a/packages/microcosm-data/src/microcosm/data/release.py +++ b/packages/microcosm-data/src/microcosm/data/release.py @@ -10,8 +10,8 @@ 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 +repository that records its builds in ``releases.json``, as every release +repository does after its switch, 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. diff --git a/packages/microcosm-data/tests/engine_free/shared/test_loader.py b/packages/microcosm-data/tests/engine_free/shared/test_loader.py index e8e96d4ec0..96c427a3a3 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_loader.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_loader.py @@ -769,15 +769,25 @@ def _is_offline_error(exc: Exception) -> bool: closed_after_retry = isinstance(exc, RuntimeError) and str(exc) == ( "Cannot send a request, as the client has been closed." ) - # Offline, the loader refuses a releases.json never cached with a - # ValueError whose cause is the Hub client's error. - cause = exc.__cause__ - return ( + if ( isinstance(exc, (ConnectionError, TimeoutError)) or closed_after_retry or any(cls.__name__ in offline_names for cls in type(exc).__mro__) - or (isinstance(cause, Exception) and _is_offline_error(cause)) - ) + ): + return True + # Offline, the loader refuses a releases.json never cached with a + # ValueError whose cause is the Hub client's error; follow the causes, + # each once. + seen = {id(exc)} + cause = exc.__cause__ + while isinstance(cause, Exception) and id(cause) not in seen: + seen.add(id(cause)) + if isinstance(cause, (ConnectionError, TimeoutError)) or any( + cls.__name__ in offline_names for cls in type(cause).__mro__ + ): + return True + cause = cause.__cause__ + return False def test_the_national_release_refuses_a_local_area_manifest(tmp_path: Path): diff --git a/test_support/microcosm_data/loader.py b/test_support/microcosm_data/loader.py index a173fd16c0..a961ba05e4 100644 --- a/test_support/microcosm_data/loader.py +++ b/test_support/microcosm_data/loader.py @@ -72,15 +72,25 @@ def _is_offline_error(exc: Exception) -> bool: closed_after_retry = isinstance(exc, RuntimeError) and str(exc) == ( "Cannot send a request, as the client has been closed." ) - # Offline, the loader refuses a releases.json never cached with a - # ValueError whose cause is the Hub client's error. - cause = exc.__cause__ - return ( + if ( isinstance(exc, (ConnectionError, TimeoutError)) or closed_after_retry or any(cls.__name__ in offline_names for cls in type(exc).__mro__) - or (isinstance(cause, Exception) and _is_offline_error(cause)) - ) + ): + return True + # Offline, the loader refuses a releases.json never cached with a + # ValueError whose cause is the Hub client's error; follow the causes, + # each once. + seen = {id(exc)} + cause = exc.__cause__ + while isinstance(cause, Exception) and id(cause) not in seen: + seen.add(id(cause)) + if isinstance(cause, (ConnectionError, TimeoutError)) or any( + cls.__name__ in offline_names for cls in type(cause).__mro__ + ): + return True + cause = cause.__cause__ + return False __all__ = [name for name in globals() if not name.startswith("__")] diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 56b99a071e..51b8c6a2db 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -1235,7 +1235,10 @@ def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: parser.add_argument( "--base-h5", type=Path, - help="Existing Microcosm US H5 to recalibrate. Defaults to HF latest.", + help=( + "Existing Microcosm US H5 to recalibrate. Defaults to the current " + "build of microcosm-us-2024-national in releases.json." + ), ) parser.add_argument( "--pool-manifest", diff --git a/tools/score_us_fiscal_targets.py b/tools/score_us_fiscal_targets.py index 93d7e04f58..28cd30cc3b 100644 --- a/tools/score_us_fiscal_targets.py +++ b/tools/score_us_fiscal_targets.py @@ -30,7 +30,10 @@ def _parse_args() -> argparse.Namespace: parser.add_argument( "--h5", type=Path, - help="Microcosm US H5 to score. Defaults to HF latest.", + help=( + "Microcosm US H5 to score. Defaults to the current build of " + "microcosm-us-2024-national in releases.json." + ), ) parser.add_argument( "--age-targets", From 4d87768902dfb332b8a54690cc4e9890ace1911b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:12:21 +0400 Subject: [PATCH 8/9] Address review round 3: refusal advice, one offline check (#1794) Review round 3 found no bugs. From its code-quality points: - The loader's refusal of a repository without releases.json says what to check (the registry entry's repository) and how a build published before its repository switched is read (by path at its tag), and the Raises sections of resolve_certified, download_certified and load list it. - The live-load helpers' offline check is one check applied to the exception and each cause once, kept in test_support's loader module; the engine-free loader tests import it instead of keeping a copy. - The registry comment and the keyword-only test say only that variant stays the eighth positional argument. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/data/loader.py | 16 ++++++-- .../src/microcosm/data/registry.py | 4 +- .../tests/engine_free/shared/test_loader.py | 41 +------------------ .../shared/test_no_pointer_files.py | 4 +- test_support/microcosm_data/loader.py | 38 ++++++++--------- 5 files changed, 36 insertions(+), 67 deletions(-) diff --git a/packages/microcosm-data/src/microcosm/data/loader.py b/packages/microcosm-data/src/microcosm/data/loader.py index 58142fc079..ec1de1d53f 100644 --- a/packages/microcosm-data/src/microcosm/data/loader.py +++ b/packages/microcosm-data/src/microcosm/data/loader.py @@ -451,7 +451,10 @@ def _releases_record_bytes(spec: DatasetSpec, *, hub_download: _HubDownload) -> raise ValueError( f"{spec.hf_repo} has no {RELEASES_RECORD_PATH}, so it lists no " f"build of {spec.release!r}; the loader reads builds only " - f"through a repository's {RELEASES_RECORD_PATH}." + f"through a repository's {RELEASES_RECORD_PATH}. Check that the " + f"registry entry {spec.key} names the right repository; a build " + "published before its repository switched to build folders is " + "read by its path at its tag." ) from exc raise return Path(record_path).read_bytes() @@ -601,6 +604,11 @@ def resolve_certified( Reads only the release record and the build's manifest, with the same checks; the dataset itself is neither downloaded nor verified. + + Raises: + ImportError: If ``huggingface_hub`` is not installed. + ValueError: If the repository has no ``releases.json``, or release + metadata is invalid. """ spec = resolve(country, year, variant=variant) return _resolve_certified_release(spec, hub_download=hub_download, build=build) @@ -625,7 +633,8 @@ def download_certified( Raises: ImportError: If ``huggingface_hub`` is not installed. - ValueError: If release metadata or the artifact digest is invalid. + ValueError: If the repository has no ``releases.json``, or release + metadata or the artifact digest is invalid. """ spec = resolve(country, year, variant=variant) return _verified_download(spec, build=build, hub_download=hub_download) @@ -761,7 +770,8 @@ def load( Raises: ImportError: If the country engine is not installed. - ValueError: If release verification or engine compatibility fails. + ValueError: If the repository has no ``releases.json``, or release + verification or engine compatibility fails. """ spec = resolve(country, year, variant=variant) dataset_class = _dataset_class(spec) diff --git a/packages/microcosm-data/src/microcosm/data/registry.py b/packages/microcosm-data/src/microcosm/data/registry.py index cd7a3afde7..8a5a20f5da 100644 --- a/packages/microcosm-data/src/microcosm/data/registry.py +++ b/packages/microcosm-data/src/microcosm/data/registry.py @@ -71,8 +71,8 @@ class DatasetSpec: engine_class: str engine_package: str variant: str = DEFAULT_VARIANT - # Keyword-only, so the fields after the required ones keep their - # positions now that every entry must name its release. + # Keyword-only, so ``variant`` stays the eighth positional argument now + # that every entry must name its release. release: str = field(kw_only=True) build_folder_filename: str | None = None diff --git a/packages/microcosm-data/tests/engine_free/shared/test_loader.py b/packages/microcosm-data/tests/engine_free/shared/test_loader.py index 96c427a3a3..5dfee927a1 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_loader.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_loader.py @@ -4,7 +4,6 @@ import hashlib import json -import os import re from importlib import metadata from pathlib import Path @@ -31,6 +30,7 @@ build_folder_release_manifest, ) from test_support.microcosm_data.hub_errors import hub_unreachable, missing_on_hub +from test_support.microcosm_data.loader import _hf_offline, _is_offline_error #: A US build served by the hub fixtures. Any well-formed name works: nothing #: in this suite may assert which build is current on the live Hub, because a @@ -751,45 +751,6 @@ def test_loader_refuses_an_unknown_dataset_role(tmp_path: Path) -> None: loader._resolve_certified_release(resolve("uk", 2025), hub_download=hub) -def _hf_offline() -> bool: - return os.environ.get("HF_HUB_OFFLINE", "").lower() in {"1", "true", "yes"} - - -def _is_offline_error(exc: Exception) -> bool: - """Recognize transport/offline failures without hiding bad release metadata.""" - offline_names = { - "ConnectError", - "ConnectTimeout", - "ConnectionError", - "LocalEntryNotFoundError", - "OfflineModeIsEnabled", - "ProxyError", - "ReadTimeout", - } - closed_after_retry = isinstance(exc, RuntimeError) and str(exc) == ( - "Cannot send a request, as the client has been closed." - ) - if ( - isinstance(exc, (ConnectionError, TimeoutError)) - or closed_after_retry - or any(cls.__name__ in offline_names for cls in type(exc).__mro__) - ): - return True - # Offline, the loader refuses a releases.json never cached with a - # ValueError whose cause is the Hub client's error; follow the causes, - # each once. - seen = {id(exc)} - cause = exc.__cause__ - while isinstance(cause, Exception) and id(cause) not in seen: - seen.add(id(cause)) - if isinstance(cause, (ConnectionError, TimeoutError)) or any( - cls.__name__ in offline_names for cls in type(cause).__mro__ - ): - return True - cause = cause.__cause__ - return False - - def test_the_national_release_refuses_a_local_area_manifest(tmp_path: Path): """releases.json gives each release one role: the national release cannot load a local-area manifest on the strength of its name.""" diff --git a/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py b/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py index 7691cb17c5..26de6bcf71 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py @@ -99,8 +99,8 @@ def test_a_dataset_spec_must_name_its_release() -> None: def test_a_dataset_spec_takes_its_release_by_keyword() -> None: - """``release`` is keyword-only, so the fields after the required ones keep - their positions: ``variant`` is still the eighth positional argument.""" + """``release`` is keyword-only, so ``variant`` is still the eighth + positional argument.""" parameters = inspect.signature(DatasetSpec).parameters positional = [ name diff --git a/test_support/microcosm_data/loader.py b/test_support/microcosm_data/loader.py index a961ba05e4..1c251b0051 100644 --- a/test_support/microcosm_data/loader.py +++ b/test_support/microcosm_data/loader.py @@ -59,7 +59,12 @@ def _hf_offline() -> bool: def _is_offline_error(exc: Exception) -> bool: - """Recognize transport/offline failures without hiding bad release metadata.""" + """Recognize transport/offline failures without hiding bad release metadata. + + The check applies to ``exc`` and to each exception in its ``__cause__`` + chain, each once: offline, the loader refuses a ``releases.json`` never + cached with a ``ValueError`` whose cause is the Hub client's error. + """ offline_names = { "ConnectError", "ConnectTimeout", @@ -69,27 +74,20 @@ def _is_offline_error(exc: Exception) -> bool: "ProxyError", "ReadTimeout", } - closed_after_retry = isinstance(exc, RuntimeError) and str(exc) == ( - "Cannot send a request, as the client has been closed." - ) - if ( - isinstance(exc, (ConnectionError, TimeoutError)) - or closed_after_retry - or any(cls.__name__ in offline_names for cls in type(exc).__mro__) - ): - return True - # Offline, the loader refuses a releases.json never cached with a - # ValueError whose cause is the Hub client's error; follow the causes, - # each once. - seen = {id(exc)} - cause = exc.__cause__ - while isinstance(cause, Exception) and id(cause) not in seen: - seen.add(id(cause)) - if isinstance(cause, (ConnectionError, TimeoutError)) or any( - cls.__name__ in offline_names for cls in type(cause).__mro__ + seen: set[int] = set() + current: BaseException | None = exc + while isinstance(current, Exception) and id(current) not in seen: + seen.add(id(current)) + closed_after_retry = isinstance(current, RuntimeError) and str(current) == ( + "Cannot send a request, as the client has been closed." + ) + if ( + isinstance(current, (ConnectionError, TimeoutError)) + or closed_after_retry + or any(cls.__name__ in offline_names for cls in type(current).__mro__) ): return True - cause = cause.__cause__ + current = current.__cause__ return False From d2a6621e2fb6330a23daa0f9b672cd038ba0e158 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:01:26 +0400 Subject: [PATCH 9/9] Expect the tagged publisher's pointer-writer names to be gone (#1794) The six cases of test_microcosm_data_exports_no_pointer_file_reader_or_writer that waited for publish_release were strict expected failures. The merge of main removed the names, so the cases pass and the marks go. Co-Authored-By: Claude Opus 5.5 --- .../shared/test_no_pointer_files.py | 56 +++++-------------- 1 file changed, 15 insertions(+), 41 deletions(-) diff --git a/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py b/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py index 26de6bcf71..78039254a6 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_no_pointer_files.py @@ -31,48 +31,22 @@ TAGGED_BUILD = "populace-us-2024-spm-20260915" TAGGED_DATASET = b"a dataset at its tag" -#: The names the tagged publisher, ``publish_release``, still uses to write -#: pointer files. They leave ``microcosm.data.release`` with it; until then -#: their cases are expected to fail, and strictly, so the marks must go when -#: the names do. ``microcosm.data`` exports none of them already. -_TAGGED_PUBLISHER_NAMES = frozenset( - { - "LATEST_POINTER_PATH", - "LATEST_EVIDENCE_POINTER_PATH", - "LATEST_POINTER_SCHEMA_VERSION", - "RELEASE_TIER_EVIDENCE", - "latest_pointer_payload", - "latest_evidence_pointer_payload", - } -) - #: Every public name the pointer-file reader and writer had. -POINTER_FILE_NAMES = tuple( - pytest.param( - name, - marks=pytest.mark.xfail( - strict=True, - reason="removed with publish_release, the tagged publisher", - ), - ) - if name in _TAGGED_PUBLISHER_NAMES - else name - for name in ( - "LATEST_POINTER_PATH", - "LINE_POINTER_PATH_TEMPLATE", - "LATEST_EVIDENCE_POINTER_PATH", - "LATEST_POINTER_SCHEMA_VERSION", - "RELEASE_TIER_CERTIFIED", - "RELEASE_TIER_EVIDENCE", - "LatestPointer", - "latest_release", - "latest_line_release", - "latest_evidence_release", - "latest_pointer_payload", - "line_pointer_payload", - "latest_evidence_pointer_payload", - "line_pointer_path", - ) +POINTER_FILE_NAMES = ( + "LATEST_POINTER_PATH", + "LINE_POINTER_PATH_TEMPLATE", + "LATEST_EVIDENCE_POINTER_PATH", + "LATEST_POINTER_SCHEMA_VERSION", + "RELEASE_TIER_CERTIFIED", + "RELEASE_TIER_EVIDENCE", + "LatestPointer", + "latest_release", + "latest_line_release", + "latest_evidence_release", + "latest_pointer_payload", + "line_pointer_payload", + "latest_evidence_pointer_payload", + "line_pointer_path", )