From 92cb4fb6d90e7c96166db19861b674ec727e2438 Mon Sep 17 00:00:00 2001 From: Oscar Esteban Date: Sat, 5 Dec 2026 17:25:50 +0100 Subject: [PATCH 1/4] feat(migrate): M301, the legacy-skeleton gate in every plan The superdataset builds the legacy skeleton from the templates and their .renames.tsv, and stops when a name of the previous skeleton would vanish. Every plan now simulates that build (the rule of templateflow/templateflow#219, where several old names may share a target) and blocks with M301 when its result would stop it. The previous names come from the legacy zip when given, and are otherwise inferred from the template and its rows. Plan.names_rows and Plan.names_result describe the template after the first of the two commits (the names), for apply. Co-Authored-By: Claude Opus 5.5 --- tfmanager/migrate/engine.py | 30 +++++++- tfmanager/migrate/findings.py | 1 + tfmanager/migrate/legacy.py | 94 +++++++++++++++++++++++++ tfmanager/tests/conftest.py | 13 ++++ tfmanager/tests/test_archive.py | 13 ---- tfmanager/tests/test_migrate_content.py | 8 +++ tfmanager/tests/test_migrate_legacy.py | 49 +++++++++++++ 7 files changed, 192 insertions(+), 16 deletions(-) create mode 100644 tfmanager/migrate/legacy.py create mode 100644 tfmanager/tests/test_migrate_legacy.py diff --git a/tfmanager/migrate/engine.py b/tfmanager/migrate/engine.py index 90ac673..242410c 100644 --- a/tfmanager/migrate/engine.py +++ b/tfmanager/migrate/engine.py @@ -4,13 +4,16 @@ hand and date give the same plan. Rows follow the policy ``content_change: freeze``: a renamed file keeps a rename row when its bytes stay, and takes an ``n/a`` row when they change (its old name keeps serving its last old bytes). + +A plan is applied in two commits: the names (renames, merges and removals, with their +rows), then the content. :meth:`Plan.names_entries` is the template between the two. """ from __future__ import annotations import hashlib import json -from collections.abc import Mapping +from collections.abc import Collection, Mapping from dataclasses import dataclass, field from ..validate import validate_template @@ -20,6 +23,7 @@ from .findings import Finding from .headers import HeaderIndex from .labels import LabelIndex +from .legacy import check_gate, previous_names from .names import NamePlan, plan_names, rows_of from .renames import merge_fragment from .snapshot import NA, Entry, Snapshot @@ -42,15 +46,28 @@ class Plan: """Fingerprint of the snapshot the plan was made from.""" result: str = '' """Fingerprint of the template after the migration.""" + names_rows: list[tuple[str, str]] = field(default_factory=list) + """Every row of ``.renames.tsv`` after the first commit (the names).""" + names_result: str = '' + """Fingerprint of the template after the first commit.""" + gate: list[Finding] = field(default_factory=list) + """Names of the legacy skeleton the result would drop (M301).""" @property def findings(self) -> list[Finding]: - return sorted(self.names.findings + self.content.findings) + return sorted(self.names.findings + self.content.findings + self.gate) @property def blocked(self) -> bool: return any(f.blocking for f in self.findings) + def names_entries(self, snapshot: Snapshot) -> dict[str, Entry]: + """The visible files after the first commit: the same files under their new names.""" + return { + new: snapshot.entries[old] + for old, new in self.names.new_paths(snapshot.entries).items() + } + def entries(self, snapshot: Snapshot) -> dict[str, Entry]: """The visible files after the migration, as a snapshot holds them.""" old_of = {new: old for old, new in self.names.new_paths(snapshot.entries).items()} @@ -84,10 +101,12 @@ def plan_template( date: str, authored: Mapping[str, bytes] | None = None, labels: LabelIndex | None = None, + legacy: Collection[str] | None = None, ) -> Plan: """Plan the migration of one template to TemplateFlow 2.0. - ``labels`` are the facts about segmentations (by default, those shipped with tfmanager). + ``labels`` are the facts about segmentations (by default, those shipped with tfmanager); + ``legacy`` the template's names in the legacy skeleton (by default, its current names). """ names = plan_names(snapshot, config, headers) content = plan_content( @@ -96,10 +115,15 @@ def plan_template( plan = Plan(template=snapshot.name, names=names, content=content) plan.rows = rows(snapshot, names, content) plan.fragment = merge_fragment(snapshot.rows, plan.rows) + plan.names_rows = merge_fragment(snapshot.rows, rows_of(names)) plan.before = validate_template(snapshot.tree(), 'strict', 'metadata') plan.base = snapshot.fingerprint() + middle = Snapshot(snapshot.name, plan.names_entries(snapshot), tuple(plan.names_rows)) + plan.names_result = middle.fingerprint() result = Snapshot(snapshot.name, plan.entries(snapshot), tuple(plan.fragment)) plan.result = result.fingerprint() + previous = previous_names(snapshot) if legacy is None else set(legacy) + plan.gate = check_gate(content.files, plan.fragment, previous) return plan diff --git a/tfmanager/migrate/findings.py b/tfmanager/migrate/findings.py index 3131a62..45a8f9b 100644 --- a/tfmanager/migrate/findings.py +++ b/tfmanager/migrate/findings.py @@ -31,6 +31,7 @@ 'M210': (False, 'The GIFTI files of a surface atlas disagree on its label table.'), 'M211': (True, 'A license text is needed but neither tfmanager nor the config has it.'), 'M212': (False, 'An atlas has no row in the config: the atlases table leaves it out.'), + 'M301': (True, 'A name released clients know would vanish from the legacy skeleton.'), } diff --git a/tfmanager/migrate/legacy.py b/tfmanager/migrate/legacy.py new file mode 100644 index 0000000..22cf9cb --- /dev/null +++ b/tfmanager/migrate/legacy.py @@ -0,0 +1,94 @@ +"""The legacy-skeleton gate (M301): released clients keep every name they know. + +The superdataset builds the legacy skeleton (``templateflow-skel.zip``, read by clients +25.x and older) from the templates and their ``.renames.tsv`` (``legacy_tree`` in its +``.github/scripts/build-skeletons.py``), and stops when a file of the previous legacy +skeleton would vanish (``check_gate``). A plan's result is checked with the same rule, so +that a plan that would stop the build is caught before it is applied: + +* the legacy view lists the template's files, except those only TemplateFlow 2.0 clients + know (:data:`~tfmanager.migrate.names.V2_ONLY`); +* each row whose old path the previous skeleton listed brings that name back: an ``n/a`` + row with the file's last bytes, a rename row with its target's. Several old names may + share a target (a copy merged into it), and the target is listed only if the previous + skeleton listed it; +* every file of the previous skeleton must be in the view, unless a row purges it. + +The previous skeleton's names come from the legacy zip (``tfmgr migrate plan +--legacy-skeleton``). Without it, :func:`previous_names` infers them from the template: +its files, without the targets of its rename rows (new names, which the legacy skeleton +did not list before), plus the old paths its rows keep. The inference misses a target +that the legacy skeleton did list (a copy merged into a file that kept its name): only +the zip is exact. +""" + +from __future__ import annotations + +import os +import zipfile +from collections.abc import Collection, Iterable + +from ..tree import visible +from .findings import Finding +from .names import V2_ONLY +from .snapshot import NA, Snapshot + +PURGE = 'purge' + + +def previous_names(snapshot: Snapshot) -> set[str]: + """The names the legacy skeleton lists for a template, inferred from its rows.""" + targets = {new for _, new in snapshot.rows if new not in (NA, PURGE)} + files = {p for p in snapshot.entries if not any(r.match(p) for r in V2_ONLY)} + return (files - targets) | {old for old, new in snapshot.rows if new != PURGE} + + +def load_legacy_zip(path: str | os.PathLike) -> dict[str, set[str]]: + """The file names of a legacy skeleton zip, by template (relative to the template).""" + out: dict[str, set[str]] = {} + with zipfile.ZipFile(path) as archive: + for member in archive.namelist(): + name, _, rel = member.partition('/') + if rel and not member.endswith('/') and visible([rel]): + out.setdefault(name, set()).add(rel) + return out + + +def legacy_view( + files: Iterable[str], rows: Iterable[tuple[str, str]], previous: Collection[str] +) -> set[str]: + """The names the legacy skeleton lists after a change (``files``: visible files). + + >>> sorted(legacy_view(['b', 'c'], [('a', 'b'), ('d', 'b'), ('e', 'n/a')], {'a', 'd', 'e'})) + ['a', 'c', 'd', 'e'] + """ + targets = {p for p in files if not any(r.match(p) for r in V2_ONLY)} + view, given = set(targets), set() + for old, new in rows: + if new == PURGE or old not in previous: + continue + if new == NA: + view.add(old) + elif new in targets: + view.add(old) + if new not in previous: + given.add(new) + return view - given + + +def check_gate( + files: Iterable[str], rows: Iterable[tuple[str, str]], previous: Collection[str] +) -> list[Finding]: + """M301 for each name of the previous legacy skeleton that the result would drop.""" + rows = list(rows) + view = legacy_view(files, rows, previous) + purged = {old for old, new in rows if new == PURGE} + return [ + Finding( + 'M301', + path, + f'{path} is in the legacy skeleton, and would vanish from it: the superdataset ' + 'stops building the skeletons.', + ) + for path in sorted(set(previous) - view - purged, key=str.encode) + ] diff --git a/tfmanager/tests/conftest.py b/tfmanager/tests/conftest.py index 2f4dba5..d9dc03a 100644 --- a/tfmanager/tests/conftest.py +++ b/tfmanager/tests/conftest.py @@ -15,6 +15,8 @@ from tfmanager.tree import MappingTree LABEL = 'Test' +#: The legacy skeleton of the Archive (python-client, 2026-12-01), before TemplateFlow 2.0 +SKELETON_SHA = '597b047fe7264923c9ce768216056c22c848e367' #: The v2 skeleton of the Archive (python-client, 2026-12-03), before TemplateFlow 2.0 SKELETON_V2_SHA = '45755e57ac4cd44727de31041760c47af8dc506b' SKELETON_V2_MD5 = 'cfb9f247ea8a56a4693e6662d05a3e24' @@ -133,6 +135,17 @@ def pinned(tmp_path_factory, url: str, name: str, md5: str | None = None) -> Pat return target +@pytest.fixture(scope='session') +def skeleton(tmp_path_factory) -> Path: + """The legacy skeleton zip of the Archive before TemplateFlow 2.0 (old names).""" + return pinned( + tmp_path_factory, + f'https://raw.githubusercontent.com/templateflow/python-client/{SKELETON_SHA}' + '/templateflow/conf/templateflow-skel.zip', + f'templateflow-skel-{SKELETON_SHA[:7]}.zip', + ) + + @pytest.fixture(scope='session') def skeleton_v2(tmp_path_factory) -> Path: """The v2 skeleton zip of the Archive before TemplateFlow 2.0 (manifest and renames).""" diff --git a/tfmanager/tests/test_archive.py b/tfmanager/tests/test_archive.py index 831af05..dde68d2 100644 --- a/tfmanager/tests/test_archive.py +++ b/tfmanager/tests/test_archive.py @@ -3,19 +3,11 @@ from __future__ import annotations from collections import Counter -from pathlib import Path import pytest -from tfmanager.tests.conftest import pinned from tfmanager.validate import check_archive, validate_path -#: A skeleton of the Archive (python-client, 2026-12-01), before TemplateFlow 2.0 -SKELETON_SHA = '597b047fe7264923c9ce768216056c22c848e367' -SKELETON_URL = ( - f'https://raw.githubusercontent.com/templateflow/python-client/{SKELETON_SHA}' - '/templateflow/conf/templateflow-skel.zip' -) #: Issues of the legacy Archive (they reproduce the audit of 2026-12-02) SNAPSHOT = { 'TF102': 2, # tpl-SUIT stat-confidence @@ -31,11 +23,6 @@ } -@pytest.fixture(scope='module') -def skeleton(tmp_path_factory) -> Path: - return pinned(tmp_path_factory, SKELETON_URL, f'templateflow-skel-{SKELETON_SHA[:7]}.zip') - - def test_legacy_snapshot(skeleton): issues, meta = validate_path(skeleton, mode='legacy') assert meta['mode'] == 'legacy' diff --git a/tfmanager/tests/test_migrate_content.py b/tfmanager/tests/test_migrate_content.py index 0059c69..66dbe9c 100644 --- a/tfmanager/tests/test_migrate_content.py +++ b/tfmanager/tests/test_migrate_content.py @@ -16,6 +16,7 @@ from tfmanager.migrate.findings import CODES from tfmanager.migrate.headers import Header, HeaderIndex from tfmanager.migrate.labels import LabelIndex +from tfmanager.migrate.legacy import check_gate, load_legacy_zip from tfmanager.migrate.names import plan_names from tfmanager.migrate.renames import check_fragment, dump_fragment from tfmanager.migrate.res import ResPlan @@ -346,6 +347,13 @@ def archive(skeleton_v2): return snapshots, plans +def test_archive_legacy_gate(archive, skeleton): + """No plan drops a name of the legacy skeleton (M301), with the zip's exact names.""" + legacy = load_legacy_zip(skeleton) + for name, plan in archive[1].items(): + assert check_gate(plan.content.files, plan.fragment, legacy[name]) == [], name + + def test_golden_res(archive): """The res blocks of the migrated Archive (``TFMGR_UPDATE_GOLDEN=1`` writes them).""" table = res_table(archive[1]) diff --git a/tfmanager/tests/test_migrate_legacy.py b/tfmanager/tests/test_migrate_legacy.py new file mode 100644 index 0000000..a358f13 --- /dev/null +++ b/tfmanager/tests/test_migrate_legacy.py @@ -0,0 +1,49 @@ +"""The legacy-skeleton gate (M301), as build-skeletons.py applies it.""" + +from __future__ import annotations + +import zipfile + +from tfmanager.migrate.legacy import check_gate, legacy_view, load_legacy_zip, previous_names +from tfmanager.migrate.snapshot import Entry, Snapshot + + +def test_merged_names(): + """R22: two old names point at one new file, and both stay in the legacy skeleton.""" + previous = {'res-01_desc-brain_probseg', 'res-01_label-brain_probseg', 'T1w'} + rows = [('res-01_desc-brain_probseg', 'new'), ('res-01_label-brain_probseg', 'new')] + assert legacy_view(['new', 'T1w'], rows, previous) == previous + assert check_gate(['new', 'T1w'], rows, previous) == [] + + +def test_targets(): + """A new name joins the legacy skeleton only if it was listed before.""" + rows = [('a', 'A'), ('b', 'B')] + assert legacy_view(['A', 'B'], rows, {'a', 'b'}) == {'a', 'b'} + assert legacy_view(['A', 'B'], rows, {'a', 'b', 'B'}) == {'a', 'b', 'B'} + # Rows of names the previous skeleton did not list bring nothing back + assert legacy_view(['A'], [('x', 'A'), ('y', 'n/a')], set()) == {'A'} + # Names only TemplateFlow 2.0 clients list stay out + assert legacy_view(['docs/a.md', 'tpl-X_atlases.tsv', 'c'], [], set()) == {'c'} + + +def test_gate(): + previous = {'renamed', 'removed', 'purged', 'dropped'} + rows = [('renamed', 'new'), ('removed', 'n/a'), ('purged', 'purge')] + found = check_gate(['new'], rows, previous) + assert [(f.code, f.path, f.blocking) for f in found] == [('M301', 'dropped', True)] + + +def test_previous_names(): + entries = {p: Entry(1, 'md5', b'x') for p in ('new', 'kept', 'docs/a.md')} + rows = (('old', 'new'), ('gone', 'n/a'), ('purged', 'purge')) + assert previous_names(Snapshot('tpl-X', entries, rows)) == {'kept', 'old', 'gone'} + + +def test_load_legacy_zip(tmp_path): + path = tmp_path / 'skel.zip' + with zipfile.ZipFile(path, 'w') as archive: + for member in ('tpl-A/', 'tpl-A/a.json', 'tpl-A/sub/b.tsv', 'tpl-A/.renames.tsv'): + archive.writestr(member, b'') + archive.writestr('tpl-B/c', b'') + assert load_legacy_zip(path) == {'tpl-A': {'a.json', 'sub/b.tsv'}, 'tpl-B': {'c'}} From a2a2c2575ae56cdf01895b22d69f30b500f1fe02 Mon Sep 17 00:00:00 2001 From: Oscar Esteban Date: Sat, 5 Dec 2026 17:25:50 +0100 Subject: [PATCH 2/4] feat(migrate): tfmgr migrate plan, apply and verify plan writes, for each template, plan.json (self-contained: what apply reads), plan.md (the complete plan, for review), pr.md (the pull request body, within GitHub's limit) and renames.tsv; summary.md with --all. apply builds two commits with git plumbing in a temporary index (the names, then the metadata), checks fingerprints, annex keys, the paths changed and the predicted validation, and only then creates and checks out the branch. It refuses stale, dirty, adjusted or unlocked checkouts and existing branches, rolls back on failure, and never pushes. A dry run keeps its objects in a temporary store. verify checks a commit against the plan. A CI job runs the apply tests with git-annex. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/pythonapp.yml | 19 + CHANGES.rst | 22 + setup.cfg | 2 + tfmanager/cli.py | 234 +++++++++++ tfmanager/migrate/apply.py | 388 ++++++++++++++++++ tfmanager/migrate/report.py | 567 ++++++++++++++++++++++++++ tfmanager/migrate/snapshot.py | 44 +- tfmanager/tests/test_migrate_apply.py | 392 ++++++++++++++++++ tfmanager/tree.py | 20 +- 9 files changed, 1679 insertions(+), 9 deletions(-) create mode 100644 tfmanager/migrate/apply.py create mode 100644 tfmanager/migrate/report.py create mode 100644 tfmanager/tests/test_migrate_apply.py diff --git a/.github/workflows/pythonapp.yml b/.github/workflows/pythonapp.yml index 1104753..b82483b 100644 --- a/.github/workflows/pythonapp.yml +++ b/.github/workflows/pythonapp.yml @@ -28,6 +28,25 @@ jobs: - name: Test run: python -m pytest -o addopts="" --doctest-modules tfmanager + annex: + # tfmgr migrate apply on a real git-annex repository (skipped in the test job) + runs-on: ubuntu-26.04 + steps: + - uses: actions/checkout@v7 + - name: Set up Python 3.13 + uses: actions/setup-python@v7 + with: + python-version: '3.13' + - name: Install git-annex + run: | + sudo apt-get update + sudo apt-get install -y git-annex + git annex version + - name: Install with test dependencies + run: python -m pip install ".[test]" + - name: Test with git-annex + run: python -m pytest -o addopts="" -m annex -rs tfmanager + build: runs-on: ubuntu-26.04 diff --git a/CHANGES.rst b/CHANGES.rst index dd2f7ed..ddabaee 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -84,6 +84,28 @@ Unreleased config ``edits`` may create a sidecar (``create: true``): the migration describes the ``desc`` and ``atlas`` values that renames drop, corrects authors, broken links and the ages of the dhcp surface templates (postmenstrual weeks). +* New commands ``tfmgr migrate plan``, ``apply`` and ``verify`` move templates to + TemplateFlow 2.0. ``plan (-t tpl-