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/5] 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/5] 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 16f853187bb60164481d9e6e0acf86bc19601515 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:52:27 +0400 Subject: [PATCH 3/5] Test that no setting names the removed switch tool (#1792) Review round 1: main's root pyproject.toml, merged in from #1743, still exempts the removed module from ruff's TID251 rule, and the scan did not read it. The scan now also reads the root and package pyproject.toml files, the root conftest.py and the CI workflows, and a second test checks that every scanned directory and file exists, so a wrong path cannot make the scan pass without reading anything. The scan fails on pyproject.toml. Co-Authored-By: Claude Opus 5.5 --- .../test_build_folder_switch_removal.py | 63 ++++++++++++++----- 1 file changed, 48 insertions(+), 15 deletions(-) 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 index e09cbbffb7..92c3835bfd 100644 --- 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 @@ -3,8 +3,9 @@ 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. +so Microcosm no longer has it, and nothing tells an operator to run it or +configures anything for it. ``changelog.d/`` and the root journals are history +and may still name it. """ from __future__ import annotations @@ -17,32 +18,49 @@ #: 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. +#: The file suffixes read under the scanned directories: the kinds of file a +#: source, test, tool, document or configuration 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")), +def _scanned_directories(repository: Path) -> list[Path]: + """The package sources and tests, the shared test support, the tools, + the docs and the CI workflows.""" + packages = repository / "packages" + return [ + *sorted(packages.glob("*/src")), + *sorted(packages.glob("*/tests")), repository / "test_support", repository / "tools", repository / "docs", + repository / ".github" / "workflows", ] + + +def _scanned_files(repository: Path) -> list[Path]: + """Every file with a suffix in ``TEXT_SUFFIXES`` under the scanned + directories, plus the READMEs, the ``pyproject.toml`` files (whose lint + settings name modules) and the root ``conftest.py``.""" files = [ candidate - for root in roots - for candidate in root.rglob("*") + for directory in _scanned_directories(repository) + for candidate in directory.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"))) + packages = repository / "packages" + files.extend( + [ + repository / "README.md", + *sorted(packages.glob("*/README.md")), + repository / "pyproject.toml", + *sorted(packages.glob("*/pyproject.toml")), + repository / "conftest.py", + ] + ) return files @@ -50,12 +68,27 @@ 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: +def test_the_scan_reads_directories_and_files_that_exist() -> None: + """A wrong root would make the scan below pass without reading anything.""" + repository = paths_for("microcosm-build").repository + directories = _scanned_directories(repository) + + assert len([directory for directory in directories if directory.name == "src"]) > 1 + assert ( + len([directory for directory in directories if directory.name == "tests"]) > 1 + ) + assert [directory for directory in directories if not directory.is_dir()] == [] + assert [ + candidate for candidate in _scanned_files(repository) if not candidate.is_file() + ] == [] + + +def test_no_source_test_tool_document_or_setting_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) + for candidate in _scanned_files(repository) if candidate.resolve() != this_file and REMOVED_MODULE_NAME in candidate.read_text(encoding="utf-8", errors="replace") From 765819cd410a176c9b2e69feddf801dadd0ee53d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:53:38 +0400 Subject: [PATCH 4/5] Fix review round 1 of the switch tool's removal (#1792) Bug (medium): remove the root pyproject.toml's TID251 exemption for the removed module, which #1743 added on main, and reword its comment so it names only the tagged publisher. Also from the review's quality points: - the refusal test checks that the refusal names neither the `copy` nor the `switch` step; - the loader again has a test that it certifies a moved build's manifest carrying migrated_from, from a tag or an untagged folder; the only such test was in a deleted module; - docs/release-contract.md says the switch tool was a fourth reader of pointer files, and that the fixture generator sets `default` only in the C5 golden records. Co-Authored-By: Claude Opus 5.5 --- docs/release-contract.md | 9 ++--- .../uk/test_uk_release_publication.py | 1 + .../tests/engine_free/shared/test_loader.py | 34 +++++++++++++++++++ pyproject.toml | 5 ++- 4 files changed, 42 insertions(+), 7 deletions(-) diff --git a/docs/release-contract.md b/docs/release-contract.md index 4f79200fe6..4ea575a064 100644 --- a/docs/release-contract.md +++ b/docs/release-contract.md @@ -1016,9 +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 tool read each repository's - pointer files once, to set each release's current build and the record's - `default`. + `latest-evidence.json` otherwise. Before it was removed, the one-time switch + tool was a fourth reader: it 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 @@ -1156,7 +1156,8 @@ work. - *The default.* The loader takes each country's default release from the 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 + this repository sets it in a live record now (the fixture generator sets + it only in the C5 golden records), 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 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 6034e4c5f9..5240e11ccc 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 @@ -955,6 +955,7 @@ def test_the_command_refuses_a_repository_that_has_not_switched_without_advising assert "latest-national.json" in error assert "python -m" not in error assert "microcosm.build." not in error + assert "`copy`" not in error and "`switch`" not in error assert "--write" not in error assert "keep the files in place" in error assert "remove" not in error 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..5eb5fbfa84 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_loader.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_loader.py @@ -664,6 +664,40 @@ def test_download_certified_returns_the_current_builds_record( assert certified.model.built_version == "2.89.2" +@pytest.mark.parametrize( + "migrated_from", + [ + { + "tag": "neutral-release-20000101T000000Z-00000000", + "commit": "0" * 40, + "release_manifest_sha256": "1" * 64, + }, + { + "folder": "releases/neutral-untagged-folder", + "commit": "2" * 40, + "release_manifest_sha256": "3" * 64, + }, + ], + ids=["from-a-tag", "from-an-untagged-folder"], +) +def test_download_certified_reads_a_moved_builds_manifest( + tmp_path: Path, migrated_from: dict +) -> None: + """The builds the one-time switch tool moved into folders carry + ``migrated_from``, naming the tag or the untagged folder they came from, + its commit and the old manifest's SHA-256. The loader certifies them as it + does any build in a folder.""" + manifest = _uk_build_folder_manifest() + manifest["migrated_from"] = migrated_from + hub = _build_folder_hub(tmp_path, manifest=manifest) + + path, certified = loader.download_certified("uk", 2025, hub_download=hub) + + assert path.read_bytes() == UK_TAGGED_ARTIFACT + assert certified.build == UK_NATIONAL_BUILD + assert certified.artifact_sha256 == hashlib.sha256(UK_TAGGED_ARTIFACT).hexdigest() + + def _declare_build_file( hub: FakeHubDownload, tmp_path: Path, diff --git a/pyproject.toml b/pyproject.toml index cd8b8e13b5..9c1b8da3d0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -73,9 +73,8 @@ ignore = ["E501"] "tools/provision_uk_staging_repository.py" = ["TID251"] "tools/fetch_uk_staged_dataset.py" = ["TID251"] "packages/microcosm-build/src/microcosm/build/staging_storage.py" = ["TID251"] -# TID251. BE's publication tools, which substage 5b removes: the build-folder -# switch and the tagged publisher (microcosm-publish-release). -"packages/microcosm-build/src/microcosm/build/build_folder_switch.py" = ["TID251"] +# TID251. BE's remaining publication tool, which substage 5b removes: the +# tagged publisher (microcosm-publish-release). "packages/microcosm-data/src/microcosm/data/release.py" = ["TID251"] # TID251. Tests and their stand-ins for the Hub (the root conftest.py only). "packages/*/tests/**" = ["TID251"] From 1994900b9b8ccfa68d697124f070df516f02ec4d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:17:20 +0400 Subject: [PATCH 5/5] Apply review round 2's quality points (#1792) - The root pyproject.toml's comment on microcosm.data.release's TID251 exemption names everything there that imports huggingface_hub: the tagged publisher, the pointer-file readers and the Hub error checks the loader imports. - The removal test module is now test_switch_tool_removal.py, so a doc or command that names it by path does not contain the name it scans for. - The loader test of a moved build's manifest keeps only the case a loaded repository has: migrated_from naming a tag. - The README and the test module's docstring say the US and UK builds moved from tags and BE's from untagged folders, and that the tool copied the builds it moved. Co-Authored-By: Claude Opus 5.5 --- README.md | 12 ++++--- ...removal.py => test_switch_tool_removal.py} | 5 +-- .../tests/engine_free/shared/test_loader.py | 34 ++++++------------- pyproject.toml | 5 +-- 4 files changed, 23 insertions(+), 33 deletions(-) rename packages/microcosm-build/tests/engine_free/shared/{test_build_folder_switch_removal.py => test_switch_tool_removal.py} (94%) diff --git a/README.md b/README.md index cd15bfc33f..e43d7e6191 100644 --- a/README.md +++ b/README.md @@ -723,11 +723,13 @@ 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.** 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 +**The switch.** The US, UK and BE repositories each moved once to build +folders, with a one-time tool: the US and UK repositories' builds from tags, +BE's from untagged folders on `main`, and all three from `latest*.json` +pointer files. It copied each build it moved 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 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_switch_tool_removal.py similarity index 94% rename from packages/microcosm-build/tests/engine_free/shared/test_build_folder_switch_removal.py rename to packages/microcosm-build/tests/engine_free/shared/test_switch_tool_removal.py index 92c3835bfd..11affd8e95 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_build_folder_switch_removal.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_switch_tool_removal.py @@ -1,7 +1,8 @@ """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 +The tool moved a dataset repository's builds, tagged or in untagged folders, +into build folders listed in ``releases.json``, deleted its pointer files, and +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 or configures anything for it. ``changelog.d/`` and the root journals are history 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 5eb5fbfa84..66936a5cf0 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_loader.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_loader.py @@ -664,31 +664,17 @@ def test_download_certified_returns_the_current_builds_record( assert certified.model.built_version == "2.89.2" -@pytest.mark.parametrize( - "migrated_from", - [ - { - "tag": "neutral-release-20000101T000000Z-00000000", - "commit": "0" * 40, - "release_manifest_sha256": "1" * 64, - }, - { - "folder": "releases/neutral-untagged-folder", - "commit": "2" * 40, - "release_manifest_sha256": "3" * 64, - }, - ], - ids=["from-a-tag", "from-an-untagged-folder"], -) -def test_download_certified_reads_a_moved_builds_manifest( - tmp_path: Path, migrated_from: dict -) -> None: - """The builds the one-time switch tool moved into folders carry - ``migrated_from``, naming the tag or the untagged folder they came from, - its commit and the old manifest's SHA-256. The loader certifies them as it - does any build in a folder.""" +def test_download_certified_reads_a_moved_builds_manifest(tmp_path: Path) -> None: + """The UK and US builds the one-time switch tool moved from their tags + into folders carry ``migrated_from``, naming the tag, its commit and the + old manifest's SHA-256. The loader certifies them as it does any build in + a folder.""" manifest = _uk_build_folder_manifest() - manifest["migrated_from"] = migrated_from + manifest["migrated_from"] = { + "tag": "neutral-release-20000101T000000Z-00000000", + "commit": "0" * 40, + "release_manifest_sha256": "1" * 64, + } hub = _build_folder_hub(tmp_path, manifest=manifest) path, certified = loader.download_certified("uk", 2025, hub_download=hub) diff --git a/pyproject.toml b/pyproject.toml index 9c1b8da3d0..800abe2d43 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -73,8 +73,9 @@ ignore = ["E501"] "tools/provision_uk_staging_repository.py" = ["TID251"] "tools/fetch_uk_staged_dataset.py" = ["TID251"] "packages/microcosm-build/src/microcosm/build/staging_storage.py" = ["TID251"] -# TID251. BE's remaining publication tool, which substage 5b removes: the -# tagged publisher (microcosm-publish-release). +# TID251. microcosm.data.release: the tagged publisher +# (microcosm-publish-release), the pointer-file readers and the Hub error +# checks the loader imports. "packages/microcosm-data/src/microcosm/data/release.py" = ["TID251"] # TID251. Tests and their stand-ins for the Hub (the root conftest.py only). "packages/*/tests/**" = ["TID251"]