From e7255c91d780a39c7634e12f2dfffcf8339bce86 Mon Sep 17 00:00:00 2001 From: Oscar Esteban Date: Thu, 3 Dec 2026 12:43:46 +0100 Subject: [PATCH 1/3] test: compatibility matrix of released clients before and after a renames table Runs templateflow 25.0.4, 25.1.2 and this branch (Python 3.13 and 3.14) against a fixture Archive whose skeletons the real build-skeletons.py builds, before and after a renames table, through a local S3 and skeleton server. Covers pinned clients, update(), homes shared with --migrate, and DataLad homes; negative controls show the matrix notices missing S3 copies and the v2 skeleton served at the legacy URL. The accepted DataLad break of released clients is a strict expected failure. The Compatibility workflow runs on pushes, pull requests and nightly, and replays a proposed table (root rows or a template's .renames.tsv) on demand. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/compat.yml | 88 ++++++ CHANGES.rst | 3 + tests/compat/README.md | 84 ++++++ tests/compat/archive.py | 264 +++++++++++++++++ tests/compat/conftest.py | 19 ++ tests/compat/datalad_archive.py | 116 ++++++++ tests/compat/runtime/scenario.py | 125 ++++++++ tests/compat/runtime/sitecustomize.py | 31 ++ tests/compat/sample-renames.tsv | 8 + tests/compat/server.py | 69 +++++ tests/compat/test_compat.py | 402 ++++++++++++++++++++++++++ 11 files changed, 1209 insertions(+) create mode 100644 .github/workflows/compat.yml create mode 100644 tests/compat/README.md create mode 100644 tests/compat/archive.py create mode 100644 tests/compat/conftest.py create mode 100644 tests/compat/datalad_archive.py create mode 100644 tests/compat/runtime/scenario.py create mode 100644 tests/compat/runtime/sitecustomize.py create mode 100644 tests/compat/sample-renames.tsv create mode 100644 tests/compat/server.py create mode 100644 tests/compat/test_compat.py diff --git a/.github/workflows/compat.yml b/.github/workflows/compat.yml new file mode 100644 index 00000000..0942bbd9 --- /dev/null +++ b/.github/workflows/compat.yml @@ -0,0 +1,88 @@ +name: Compatibility + +# Released clients and this branch against an Archive before and after a renames table +# (tests/compat/README.md). Nightly, it catches changes in the Archive's skeleton +# builder and in the clients' dependencies. Replay a proposed table before merging it +# into a template with "Run workflow". + +on: + push: + branches: [master, 'maint/*'] + pull_request: + schedule: + - cron: '23 3 * * *' + workflow_dispatch: + inputs: + renames-url: + description: >- + HTTPS URL of a renames table to replay: rows of the root renames.tsv, or a + template's .renames.tsv (set the template). Empty runs the sample table. + required: false + default: '' + template: + description: Template of a .renames.tsv fragment (tpl-X); empty for root rows + required: false + default: '' + archive-ref: + description: Ref of templateflow/templateflow whose build-skeletons.py builds the Archive + required: false + default: master + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + compat: + name: Python ${{ matrix.python-version }} + runs-on: ubuntu-26.04 + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + # SPEC 0 (Python 3.15 joins once pybids' dependencies publish wheels) + python-version: ['3.13', '3.14'] + env: + TEMPLATEFLOW_COMPAT_PYTHON: ${{ matrix.python-version }} + TEMPLATEFLOW_ARCHIVE_SCRIPTS: ${{ github.workspace }}/archive/.github/scripts + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 # hatch-vcs versions the client under test + persist-credentials: false + - uses: actions/checkout@v7 + with: + repository: templateflow/templateflow + ref: ${{ inputs.archive-ref || 'master' }} + path: archive + sparse-checkout: .github/scripts + persist-credentials: false + - uses: astral-sh/setup-uv@v10 + - name: Fetch the table to replay + if: inputs.renames-url != '' + env: + URL: ${{ inputs.renames-url }} + TEMPLATE: ${{ inputs.template }} + run: | + curl -fsSL --proto '=https' --max-filesize 1048576 -o "$RUNNER_TEMP/renames.tsv" "$URL" + echo "TEMPLATEFLOW_COMPAT_RENAMES=$RUNNER_TEMP/renames.tsv" >> "$GITHUB_ENV" + if [ -n "$TEMPLATE" ]; then + echo "TEMPLATEFLOW_COMPAT_TEMPLATE=$TEMPLATE" >> "$GITHUB_ENV" + fi + cat "$RUNNER_TEMP/renames.tsv" + - name: Set up the test environment + run: | + uv venv --python "$TEMPLATEFLOW_COMPAT_PYTHON" "$RUNNER_TEMP/compat" + uv pip install --python "$RUNNER_TEMP/compat/bin/python" . pytest + - name: Run the compatibility matrix + run: >- + "$RUNNER_TEMP/compat/bin/python" -m pytest -o addopts="" -rxXs + --junitxml="$RUNNER_TEMP/compat.xml" tests/compat + - uses: actions/upload-artifact@v7 + if: always() + with: + name: compat-python-${{ matrix.python-version }} + path: ${{ runner.temp }}/compat.xml diff --git a/CHANGES.rst b/CHANGES.rst index 3f425322..d879648f 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -28,6 +28,9 @@ TemplateFlow 2.0 file names: the client reads the v2 skeleton and resolves old n * FIX: ``get()`` skipped files when DataLad fetched several at once, and failed for files without a stub in the home. * FIX: Network errors other than connection errors no longer break skeleton updates. +* MAINT: A compatibility matrix (``tests/compat``, workflow *Compatibility*) runs the + released clients and this one against an Archive before and after a renames table, + in S3 and DataLad homes. It replays a proposed table before it is merged. 25.1.2 (March 11, 2026) ======================= diff --git a/tests/compat/README.md b/tests/compat/README.md new file mode 100644 index 00000000..c5998e9f --- /dev/null +++ b/tests/compat/README.md @@ -0,0 +1,84 @@ +# Compatibility matrix + +Released clients and this branch, run against a fixture Archive before and after a +renames table. It checks the promise of TemplateFlow 2.0: renaming files in the Archive +breaks no released client that reads it through S3. + +## How it works + +```text +test_compat.py (pytest, the branch installed) +├── archive.py the fixture Archive: names from the bundled v2 skeleton, made-up +│ content, annexed files as MD5E symlinks; skeletons built by the +│ real build-skeletons.py (templateflow/templateflow), before and +│ after the table +├── datalad_archive.py a one-template git-annex Archive for DataLad homes +├── server.py local S3 (404 answers as S3 sends them) and skeleton URLs +└── client processes one uv environment per client (25.0.4, 25.1.2, branch) + ├── runtime/sitecustomize.py sends requests to server.py; no other network + └── runtime/scenario.py get / update / files, with the API all clients share +``` + +The server serves one state at a time: + +| State | S3 | Skeleton URLs | +|---|---|---| +| `before` | every file, and the old names of the Archive's `renames.tsv` | built before the table | +| `after` | the table applied: new names, old names kept, purged names gone | rebuilt | +| `no-copies` (control) | `after` without the old names of the table | rebuilt | +| `v2-as-legacy` (control) | `after` | the v2 skeleton at the legacy URL | + +## Scenarios + +| Test | Expects | +|---|---| +| `test_pinned` | a client that never updates downloads every old name; purged names fail | +| `test_released_update` | after `update()`, released clients get one file per old name | +| `test_branch_update` | the branch finds old queries (with a `FutureWarning` when entities changed) and removed files | +| `test_shared_home` | a released client's home, used without and with `--migrate`; migration moves downloads, nothing is downloaded again | +| `test_branch_datalad` | in DataLad homes, the branch resolves old names after `datalad update` | +| `test_released_datalad` | released clients in DataLad homes keep renames that preserve entities | +| `test_released_datalad_break` | expected failure (strict): released clients in DataLad homes lose old names that changed entities, and removed files. Accepted for 2.0 and announced with 26.0 | +| `*_control_*` | the matrix notices a missing S3 copy, and the v2 skeleton served at the legacy URL | + +Released clients 25.0 and older save S3's error body as the file when a key is missing, +and never download it again; the tests count that as a miss. + +## Running it + +```bash +git clone --depth 1 --filter=blob:none --sparse https://github.com/templateflow/templateflow +git -C templateflow sparse-checkout set .github/scripts +pip install . pytest +TEMPLATEFLOW_ARCHIVE_SCRIPTS=$PWD/templateflow/.github/scripts \ + python -m pytest -o addopts="" -rxXs tests/compat +``` + +It needs `uv` and `git`; the DataLad environments install `datalad` and the +`git-annex` wheel. Client processes never see the `TEMPLATEFLOW_HOME` of your +environment, and `scenario.py` refuses any home the matrix did not make. + +| Variable | Default | Meaning | +|---|---|---| +| `TEMPLATEFLOW_ARCHIVE_SCRIPTS` | (required) | `.github/scripts` of templateflow/templateflow | +| `TEMPLATEFLOW_COMPAT_RENAMES` | `sample-renames.tsv` | the table to replay | +| `TEMPLATEFLOW_COMPAT_TEMPLATE` | | with a template's `.renames.tsv`, its name (`tpl-X`) | +| `TEMPLATEFLOW_COMPAT_CLIENTS` | `25.0.4 25.1.2 branch` | clients to run | +| `TEMPLATEFLOW_COMPAT_PYTHON` | `3.13` | Python of the client environments | + +## Replaying a table + +Before merging a template PR with a `.renames.tsv`, run the *Compatibility* workflow +with its raw URL and the template's name, or locally: + +```bash +TEMPLATEFLOW_COMPAT_RENAMES=path/to/.renames.tsv TEMPLATEFLOW_COMPAT_TEMPLATE=tpl-X \ +TEMPLATEFLOW_ARCHIVE_SCRIPTS=... python -m pytest -o addopts="" -rxXs tests/compat +``` + +The table's old names must be in the skeleton bundled with this branch. Tests a table +does not exercise (no removed files, say) are skipped. + +The sample table renames `tpl-MNI152Lin` files as the 2.0 rules do: `res-01` to +`res-1` (entities kept), entity order with `res` (kept), `PET` to `pet` and +`desc-head` to `label-head` (entities changed), one removed file (`n/a`) and one purged. diff --git a/tests/compat/archive.py b/tests/compat/archive.py new file mode 100644 index 00000000..078383a1 --- /dev/null +++ b/tests/compat/archive.py @@ -0,0 +1,264 @@ +"""A fixture Archive, before and after a renames table, built by the real skeleton builder. + +The Archive's names come from a v2 skeleton (the one bundled with the client under +test, which the Archive's CI keeps current). Templates become git repositories whose +annexed files are symbolic links named by MD5E keys, as git-annex commits them, so that +``build-skeletons.py`` from templateflow/templateflow reads them as it reads the real +Archive. Annexed content is made up (:func:`content`); the keys, the manifest and the +local S3 agree on it. + +States (what the local S3 and the skeleton URLs serve): + +``before`` + The Archive as it is; S3 holds every file and the old names of ``renames.tsv``. +``after`` + The table applied as the template action does: ``git mv`` in the template, + rows appended to ``renames.tsv``, every old S3 key kept (removed files too), purged + keys deleted, both skeletons rebuilt. +``no-copies`` (negative control) + ``after``, but S3 lost the old names of the table, as a plain ``git annex export`` + leaves it. +``v2-as-legacy`` (negative control) + ``after``, but the legacy skeleton URL serves the v2 skeleton, so released clients + get both names of every renamed file. +""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess +from dataclasses import dataclass, field +from hashlib import md5 +from pathlib import Path +from zipfile import ZipFile + +#: Git identity for fixture commits; added to the environment, never a copy of it +GIT_ENV = { + 'GIT_AUTHOR_NAME': 'compat', + 'GIT_AUTHOR_EMAIL': 'compat@example.org', + 'GIT_COMMITTER_NAME': 'compat', + 'GIT_COMMITTER_EMAIL': 'compat@example.org', + 'GIT_CONFIG_GLOBAL': os.devnull, +} +KEYWORDS = ('n/a', 'purge') +GIT = shutil.which('git') or 'git' + + +def content(path: str) -> bytes: + """The made-up content of an annexed file, by the name it had in ``before``.""" + return f'compat {path}\n'.encode() + + +def checksum(data: bytes) -> str: + return md5(data, usedforsecurity=False).hexdigest() + + +def annex_target(depth: int, data: bytes, ext: str) -> str: + key = f'MD5E-s{len(data)}--{checksum(data)}{ext}' + return '../' * depth + f'.git/annex/objects/Xx/Yy/{key}/{key}' + + +def git(cwd: Path, *args: str) -> str: + return subprocess.run( + [GIT, *args], + cwd=cwd, + env={**os.environ, **GIT_ENV}, + capture_output=True, + text=True, + check=True, + ).stdout.strip() + + +def read_rows(text: str, template: str | None = None) -> list[tuple[str, str]]: + """Rows of a renames table: the root ``renames.tsv``, or with ``template``, a + template's ``.renames.tsv`` (paths relative to the template).""" + lines = text.splitlines() + if not lines or lines[0].split('\t') != ['old_path', 'new_path']: + raise ValueError('a renames table starts with old_pathnew_path') + rows = [tuple(line.split('\t')) for line in lines[1:] if line.strip()] + if any(len(row) != 2 for row in rows): + raise ValueError('every row of a renames table has two columns') + if template is None: + return rows + prefix = f'{template.removesuffix("/")}/' + return [(prefix + o, n if n in KEYWORDS else prefix + n) for o, n in rows] + + +@dataclass +class State: + """What the local server serves: S3 keys, and skeleton files by name.""" + + s3: dict[str, bytes] = field(default_factory=dict) + raw: dict[str, bytes] = field(default_factory=dict) + + +@dataclass +class Fixture: + root: Path + rows: list[tuple[str, str]] + states: dict[str, State] + files: dict[str, dict[str, bytes]] # state -> path -> content + + def content(self, state: str, path: str) -> bytes: + return self.files[state][path] + + +class Archive: + """A superdataset with templates as git repositories.""" + + def __init__(self, root: Path): + self.root = root + root.mkdir(parents=True) + git(root, 'init', '-q', '-b', 'master') + self.files: dict[str, bytes] = {} # path -> content + self.annexed: set[str] = set() + + def add(self, files: dict[str, bytes], annexed: set[str], root_files: dict[str, bytes]): + by_template: dict[str, list[str]] = {} + for path in files: + by_template.setdefault(path.split('/', 1)[0], []).append(path) + for template, paths in sorted(by_template.items()): + repo = self.root / template + repo.mkdir() + git(repo, 'init', '-q', '-b', 'master') + for path in paths: + self._write(path, files[path], path in annexed) + self._commit(template) + for name, data in root_files.items(): + (self.root / name).write_bytes(data) + git(self.root, 'add', name) + git(self.root, 'commit', '-q', '-m', 'before') + + def _write(self, path: str, data: bytes, annexed: bool): + target = self.root / path + target.parent.mkdir(parents=True, exist_ok=True) + if annexed: + rel = path.split('/', 1)[1] + ext = ''.join(Path(rel).suffixes) + target.symlink_to(annex_target(rel.count('/'), data, ext)) + self.annexed.add(path) + else: + target.write_bytes(data) + self.files[path] = data + + def _commit(self, template: str): + repo = self.root / template + git(repo, 'add', '-A') + git(repo, 'commit', '-q', '--allow-empty', '-m', 'update') + sha = git(repo, 'rev-parse', 'HEAD') + git(self.root, 'update-index', '--add', '--cacheinfo', f'160000,{sha},{template}') + + def apply(self, rows: list[tuple[str, str]]): + """Apply a renames table as the template action does.""" + touched = set() + for old, new in rows: + if old not in self.files: + raise ValueError(f'{old}: not in the Archive') + if new not in KEYWORDS and new in self.files: + raise ValueError(f'{new}: already in the Archive') + data, annexed = self.files.pop(old), old in self.annexed + self.annexed.discard(old) + (self.root / old).unlink() + if new not in KEYWORDS: + if new.split('/', 1)[0] != old.split('/', 1)[0]: + raise ValueError(f'{old}: renamed into another template') + self._write(new, data, annexed) + touched.add(old.split('/', 1)[0]) + for template in sorted(touched): + self._commit(template) + table = self.root / 'renames.tsv' + text = table.read_text() if table.exists() else 'old_path\tnew_path\n' + table.write_text(text + ''.join(f'{old}\t{new}\n' for old, new in rows)) + git(self.root, 'add', 'renames.tsv') + git(self.root, 'commit', '-q', '-m', 'after') + + +def skeleton_files(zip_path: Path) -> dict[str, bytes]: + with ZipFile(zip_path) as zf: + return {n: zf.read(n) for n in zf.namelist() if not n.endswith('/')} + + +def build_skeletons(script: Path, root: Path, out: Path, previous: Path, previous_v2=None): + args = ['python3', str(script), str(root), str(out), '--previous', str(previous)] + if previous_v2 is not None: + args += ['--previous-v2', str(previous_v2)] + result = subprocess.run(args, capture_output=True, text=True) + if result.returncode: + raise RuntimeError(f'build-skeletons.py failed:\n{result.stdout}{result.stderr}') + return json.loads(result.stdout.strip().splitlines()[-1]) + + +def raw_files(out: Path) -> dict[str, bytes]: + return { + p.name: p.read_bytes() for p in out.iterdir() if p.name.startswith('templateflow-skel') + } + + +def build( + work: Path, v2_zip: Path, legacy_zip: Path, rows: list[tuple[str, str]], script: Path +) -> Fixture: + """Build the fixture Archive and the states the local server serves.""" + skeleton = skeleton_files(v2_zip) + manifest = { + line.split('\t')[0]: int(line.split('\t')[1]) + for line in skeleton['.templateflow/manifest.tsv'].decode().splitlines()[1:] + } + files, annexed = {}, set() + for path, data in skeleton.items(): + if not path.startswith('tpl-'): + continue + if not data and manifest.get(path, 0) > 0: + files[path], annexed = content(path), annexed | {path} + else: + files[path] = data + root_files = {n: d for n, d in skeleton.items() if '/' not in n and n.endswith('.tsv')} + + archive = Archive(work / 'archive') + archive.add(files, annexed, root_files) + before_out, after_out = work / 'before', work / 'after' + build_skeletons(script, archive.root, before_out, legacy_zip) + before = dict(archive.files) + canaries = read_rows(root_files.get('renames.tsv', b'old_path\tnew_path\n').decode()) + + archive.apply(rows) + build_skeletons( + script, + archive.root, + after_out, + before_out / 'templateflow-skel.zip', + before_out / 'templateflow-skel-v2.zip', + ) + after = dict(archive.files) + + def old_keys(table, current): + """Old S3 keys the template action keeps: renamed and removed files.""" + keys = {} + for old, new in table: + if new == 'purge': + continue + keys[old] = current[new] if new in current else before.get(old, content(old)) + return keys + + s3_before = {**before, **old_keys(canaries, before)} + s3_after = {**after, **old_keys(canaries, after), **old_keys(rows, after)} + for old, new in rows: + if new == 'purge': + s3_after.pop(old, None) + applied_old = {old for old, _ in rows} + raw_after = raw_files(after_out) + states = { + 'before': State(s3_before, raw_files(before_out)), + 'after': State(s3_after, raw_after), + 'no-copies': State({k: v for k, v in s3_after.items() if k not in applied_old}, raw_after), + 'v2-as-legacy': State( + s3_after, + { + **raw_after, + 'templateflow-skel.zip': raw_after['templateflow-skel-v2.zip'], + 'templateflow-skel.md5': raw_after['templateflow-skel-v2.md5'], + }, + ), + } + return Fixture(archive.root, rows, states, {'before': before, 'after': after}) diff --git a/tests/compat/conftest.py b/tests/compat/conftest.py new file mode 100644 index 00000000..bc22688c --- /dev/null +++ b/tests/compat/conftest.py @@ -0,0 +1,19 @@ +"""Keep the matrix away from real TemplateFlow homes. + +The test process imports the client under test (to parse entities), and importing it +creates or reads ``TEMPLATEFLOW_HOME``. A developer's environment usually points that +variable at a real home, so the matrix's tests run with a scratch home. Client +processes get their own homes (``Client.run``). +""" + +import pytest + + +@pytest.fixture(scope='session', autouse=True) +def scratch_home(tmp_path_factory): + with pytest.MonkeyPatch.context() as patch: + home = tmp_path_factory.mktemp('test-process') / 'templateflow' + patch.setenv('TEMPLATEFLOW_HOME', str(home)) + patch.setenv('TEMPLATEFLOW_USE_DATALAD', 'off') + patch.setenv('TEMPLATEFLOW_AUTOUPDATE', 'off') + yield home diff --git a/tests/compat/datalad_archive.py b/tests/compat/datalad_archive.py new file mode 100644 index 00000000..84036e87 --- /dev/null +++ b/tests/compat/datalad_archive.py @@ -0,0 +1,116 @@ +"""A one-template DataLad Archive for DataLad homes, before and after a renames table. + +DataLad homes are clones of the superdataset and its templates: they follow the +Archive's git history, not the skeletons and S3. The fixture is a plain git +superdataset with one template, a git-annex repository holding real content. Client +processes reach it through a git configuration (:meth:`DataladArchive.gitconfig`) that +rewrites the GitHub URLs the clients clone from. git-annex comes from the ``git-annex`` +wheel installed with DataLad in the clients' environments (``bin_dir``), so the fixture and +the clients use the same version. +""" + +from __future__ import annotations + +import os +import subprocess +from collections import Counter +from functools import partial +from pathlib import Path + +from archive import GIT_ENV, KEYWORDS, content + +TEXT = ('template_description.json', 'LICENSE', 'CHANGES') + + +def busiest(rows: list[tuple[str, str]]) -> str: + """The template with the most rows: the one the DataLad fixture holds.""" + return Counter(old.split('/', 1)[0] for old, _ in rows).most_common(1)[0][0] + + +def run(cwd: Path, *args: str, bin_dir: Path) -> str: + env = {**os.environ, **GIT_ENV, 'GIT_CONFIG_NOSYSTEM': '1'} + env['PATH'] = f'{bin_dir}{os.pathsep}{env["PATH"]}' + return subprocess.run( + list(args), + cwd=cwd, + env=env, + capture_output=True, + text=True, + check=True, + ).stdout.strip() + + +class DataladArchive: + def __init__(self, work: Path, rows: list[tuple[str, str]], text: dict[str, bytes], bin_dir): + """The rows of the :func:`busiest` template; ``text`` the Archive's text files; + ``bin_dir`` the folder with ``git-annex``.""" + self.run = partial(run, bin_dir=bin_dir) + self.template = template = busiest(rows) + self.root = work / 'origin' / 'templateflow' + self.rows = [(o, n) for o, n in rows if o.startswith(f'{template}/')] + self.repo = self.root / template + self.repo.mkdir(parents=True) + self.run(self.root, 'git', 'init', '-q', '-b', 'master') + self.run(self.repo, 'git', 'init', '-q', '-b', 'master') + self.run(self.repo, 'git', 'annex', 'init', '-q', 'origin') + (self.repo / '.gitattributes').write_text( + '* annex.backend=MD5E\n*.nii.gz annex.largefiles=anything\n' + ) + for name in TEXT: + if f'{self.template}/{name}' in text: + (self.repo / name).write_bytes(text[f'{self.template}/{name}']) + for old, _ in self.rows: + (self.root / old).write_bytes(content(old)) + self.run(self.repo, 'git', 'annex', 'add', '-q', '.') + self.run( + self.repo, + 'git', + 'add', + '.gitattributes', + *(n for n in TEXT if (self.repo / n).exists()), + ) + self.run(self.repo, 'git', 'commit', '-q', '-m', 'before') + (self.root / '.gitmodules').write_text( + f'[submodule "{self.template}"]\n\tpath = {self.template}\n' + f'\turl = https://github.com/templateflow/{self.template}\n' + ) + (self.root / 'renames.tsv').write_text('old_path\tnew_path\n') + self._record('before') + + def _record(self, message: str): + sha = self.run(self.repo, 'git', 'rev-parse', 'HEAD') + self.run( + self.root, + 'git', + 'update-index', + '--add', + '--cacheinfo', + f'160000,{sha},{self.template}', + ) + self.run(self.root, 'git', 'add', '.gitmodules', 'renames.tsv') + self.run(self.root, 'git', 'commit', '-q', '-m', message) + + def apply(self): + """The renames, as a template PR merged on GitHub and recorded by the superdataset.""" + for old, new in self.rows: + rel = old.split('/', 1)[1] + if new in KEYWORDS: + self.run(self.repo, 'git', 'rm', '-q', rel) + else: + self.run(self.repo, 'git', 'mv', rel, new.split('/', 1)[1]) + self.run(self.repo, 'git', 'commit', '-q', '-m', 'after') + with (self.root / 'renames.tsv').open('a') as table: + table.writelines(f'{old}\t{new}\n' for old, new in self.rows) + self._record('after') + + def gitconfig(self, path: Path) -> Path: + """A global git configuration that sends clients' clones to this Archive.""" + path.write_text( + '[user]\n\tname = compat\n\temail = compat@example.org\n' + '[protocol "file"]\n\tallow = always\n' + f'[url "{self.root}"]\n' + '\tinsteadOf = https://github.com/templateflow/templateflow.git\n' + f'[url "{self.root}/tpl-"]\n' + '\tinsteadOf = https://github.com/templateflow/tpl-\n' + ) + return path diff --git a/tests/compat/runtime/scenario.py b/tests/compat/runtime/scenario.py new file mode 100644 index 00000000..eb874eba --- /dev/null +++ b/tests/compat/runtime/scenario.py @@ -0,0 +1,125 @@ +"""Run TemplateFlow client operations in the client's own environment; print JSON. + +Usage: python scenario.py '' + +One process is one session of a user's program: the client is imported fresh, so a new +home is created from the skeleton bundled with the client. Operations: + +``{"op": "get", "path": P}`` + ``api.get()`` with the query that names ``P``: every entity of ``P``, and ``None`` + for the entities ``P`` lacks (as in ``desc=None``). +``{"op": "update", "local": false, "migrate": false}`` + ``templateflow.conf.update()``; ``migrate`` only for clients that have it. +``{"op": "files"}`` + The files of the home (not hidden), with their sizes. +``{"op": "bundled"}`` + The names in the skeleton bundled with the client. + +Only uses the API that every client in the matrix has (25.0 and later). +""" + +import json +import sys +import warnings +from pathlib import Path + +#: Created by the harness next to every home it makes (tests/compat/test_compat.py) +MARKER = '.templateflow-compat' + + +def entity_query(layout, path): + from bids.layout import parse_file_entities + + import templateflow + + config = Path(templateflow.__file__).parent / 'conf' / 'config.json' + names = {e['name'] for e in json.loads(config.read_text())['entities']} + names &= set(layout.get_entities()) + found = parse_file_entities('/' + path, config='templateflow') + query = {name: None for name in names if name not in ('template', 'description')} + query.update({k: v for k, v in found.items() if k in names | {'template'}}) + return query + + +def op_get(path): + from templateflow import api + + layout = api.TF_LAYOUT + root = Path(layout.root) + query = entity_query(layout, path) + template = query.pop('template') + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + try: + out, error = api.get(template, **query), None + except Exception as exc: # noqa: BLE001 + out, error = None, f'{type(exc).__name__}: {exc}' + paths = [] if out is None else [out] if isinstance(out, Path) else list(out) + return { + 'single': isinstance(out, Path), + 'paths': [Path(p).relative_to(root).as_posix() for p in paths], + 'contents': [ + Path(p).read_bytes()[:200].decode(errors='replace') if Path(p).is_file() else None + for p in paths + ], + 'warnings': [ + f'{w.category.__name__}: {w.message}' + for w in caught + if issubclass(w.category, FutureWarning) + ], + 'error': error, + } + + +def op_update(local=False, migrate=False): + import templateflow.conf as conf + + kwargs = {'local': local, 'overwrite': True, 'silent': True} + if migrate: + kwargs['migrate'] = True + return {'updated': bool(conf.update(**kwargs))} + + +def op_files(): + from templateflow import conf + + root = Path(conf.TF_HOME) + return { + p.relative_to(root).as_posix(): p.stat().st_size + for p in sorted(root.rglob('*')) + if p.is_file() and not any(part.startswith('.') for part in p.relative_to(root).parts) + } + + +def op_bundled(): + from zipfile import ZipFile + + import templateflow + + conf = Path(templateflow.__file__).parent / 'conf' + name = 'templateflow-skel-v2.zip' if (conf / 'templateflow-skel-v2.zip').exists() else '' + with ZipFile(conf / (name or 'templateflow-skel.zip')) as zf: + return sorted(n for n in zf.namelist() if not n.endswith('/')) + + +OPS = {'get': op_get, 'update': op_update, 'files': op_files, 'bundled': op_bundled} + + +def main(ops): + results = [] + for op in ops: + kind = op.pop('op') + results.append(OPS[kind](**op)) + print(json.dumps(results)) + + +if __name__ == '__main__': + import os + + # Only ever against the local server (sitecustomize.py), and in a home of the matrix + if 'sitecustomize' not in sys.modules or not os.getenv('TEMPLATEFLOW_COMPAT_SERVER'): + sys.exit('scenario.py runs only in the compat matrix (no local server set)') + home = Path(os.getenv('TEMPLATEFLOW_HOME', '')) + if not (home.parent / MARKER).is_file(): + sys.exit(f'scenario.py refuses {home}: not a home of the compat matrix') + main(json.loads(sys.argv[1])) diff --git a/tests/compat/runtime/sitecustomize.py b/tests/compat/runtime/sitecustomize.py new file mode 100644 index 00000000..3a007268 --- /dev/null +++ b/tests/compat/runtime/sitecustomize.py @@ -0,0 +1,31 @@ +"""Send a TemplateFlow client's requests to the local compat server. + +Loaded at startup by client processes that have this folder on ``PYTHONPATH`` and +``TEMPLATEFLOW_COMPAT_SERVER`` set. Released clients hard-code their URLs, so the +redirect happens in ``requests``: S3 and the skeleton URLs go to the local server, and +any other request fails, which keeps the matrix off the network. +""" + +import os + +SERVER = os.getenv('TEMPLATEFLOW_COMPAT_SERVER') +ROUTES = { + 'https://templateflow.s3.amazonaws.com/': '/s3/', + 'https://raw.githubusercontent.com/templateflow/python-client/': '/raw/', +} + +if SERVER: + import requests + import requests.sessions + + _request = requests.sessions.Session.request + + def request(self, method, url, *args, **kwargs): + for prefix, route in ROUTES.items(): + if url.startswith(prefix): + return _request(self, method, SERVER + route + url[len(prefix) :], *args, **kwargs) + if not url.startswith(SERVER): + raise requests.ConnectionError(f'compat: no network outside the matrix ({url})') + return _request(self, method, url, *args, **kwargs) + + requests.sessions.Session.request = request diff --git a/tests/compat/sample-renames.tsv b/tests/compat/sample-renames.tsv new file mode 100644 index 00000000..92accffe --- /dev/null +++ b/tests/compat/sample-renames.tsv @@ -0,0 +1,8 @@ +old_path new_path +tpl-MNI152Lin/tpl-MNI152Lin_res-01_T1w.nii.gz tpl-MNI152Lin/tpl-MNI152Lin_res-1_T1w.nii.gz +tpl-MNI152Lin/tpl-MNI152Lin_res-01_desc-brain_mask.nii.gz tpl-MNI152Lin/tpl-MNI152Lin_res-1_desc-brain_mask.nii.gz +tpl-MNI152Lin/tpl-MNI152Lin_desc-SPM12_res-02_T1w.nii.gz tpl-MNI152Lin/tpl-MNI152Lin_res-2_desc-SPM12_T1w.nii.gz +tpl-MNI152Lin/tpl-MNI152Lin_desc-SPM12_res-02_PET.nii.gz tpl-MNI152Lin/tpl-MNI152Lin_res-2_desc-SPM12_pet.nii.gz +tpl-MNI152Lin/tpl-MNI152Lin_res-01_desc-head_mask.nii.gz tpl-MNI152Lin/tpl-MNI152Lin_res-1_label-head_mask.nii.gz +tpl-MNI152Lin/tpl-MNI152Lin_desc-SPM12_res-02_SPECT.nii.gz n/a +tpl-MNI152Lin/tpl-MNI152Lin_desc-SPM12_res-02_epi.nii.gz purge diff --git a/tests/compat/server.py b/tests/compat/server.py new file mode 100644 index 00000000..43819521 --- /dev/null +++ b/tests/compat/server.py @@ -0,0 +1,69 @@ +"""A local stand-in for S3 and for the skeleton URLs on raw.githubusercontent.com. + +``/s3/`` serves an object of the bucket; a missing key answers 404 with the XML +body S3 sends. ``/raw//templateflow/conf/`` serves a skeleton file. +Client processes reach it through ``runtime/sitecustomize.py``. +""" + +from __future__ import annotations + +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import unquote, urlsplit + +from archive import State + +NO_SUCH_KEY = ( + b'\n' + b'NoSuchKeyThe specified key does not exist.' + b'' +) + + +class Server: + def __init__(self): + self.state = State() + self.requests: list[str] = [] + server = self + + class Handler(BaseHTTPRequestHandler): + def do_GET(self): # noqa: N802 + self._answer(body=True) + + def do_HEAD(self): # noqa: N802 + self._answer(body=False) + + def _answer(self, body: bool): + path = unquote(urlsplit(self.path).path) + server.requests.append(path) + data = None + if path.startswith('/s3/'): + data = server.state.s3.get(path[len('/s3/') :]) + elif path.startswith('/raw/'): + data = server.state.raw.get(path.rsplit('/', 1)[-1]) + status = 200 if data is not None else 404 + payload = data if data is not None else NO_SUCH_KEY + self.send_response(status) + self.send_header('Content-Length', str(len(payload))) + self.end_headers() + if body: + self.wfile.write(payload) + + def log_message(self, *args): + pass + + self.httpd = ThreadingHTTPServer(('127.0.0.1', 0), Handler) + self.url = f'http://127.0.0.1:{self.httpd.server_address[1]}' + self.thread = threading.Thread(target=self.httpd.serve_forever, daemon=True) + + def __enter__(self) -> Server: + self.thread.start() + return self + + def __exit__(self, *exc): + self.httpd.shutdown() + self.httpd.server_close() + + def serve(self, state: State) -> None: + self.state = state + self.requests.clear() diff --git a/tests/compat/test_compat.py b/tests/compat/test_compat.py new file mode 100644 index 00000000..0e55ada1 --- /dev/null +++ b/tests/compat/test_compat.py @@ -0,0 +1,402 @@ +"""Released clients and the client under test, before and after a renames table. + +See README.md. Each client runs in its own environment (``uv``), against a local +stand-in for S3 and the skeleton URLs (``server.py``) that serves a fixture Archive +(``archive.py``). +""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess +from pathlib import Path + +import archive +import pytest +from datalad_archive import TEXT, DataladArchive +from server import Server + +HERE = Path(__file__).parent +REPO = HERE.parent.parent +#: Released clients in the SPEC 0 window (two years), and the working tree +CLIENTS = os.getenv('TEMPLATEFLOW_COMPAT_CLIENTS', '25.0.4 25.1.2 branch').split() +RELEASED = [c for c in CLIENTS if c != 'branch'] +PYTHON = os.getenv('TEMPLATEFLOW_COMPAT_PYTHON', '3.13') + + +class Break(Exception): + """A released client lost a file it found before: the expected failure of a test.""" + + +@pytest.fixture(scope='session') +def builder() -> Path: + """``build-skeletons.py`` from a templateflow/templateflow checkout.""" + scripts = os.getenv('TEMPLATEFLOW_ARCHIVE_SCRIPTS') + if not scripts or not (Path(scripts) / 'build-skeletons.py').is_file(): + pytest.skip('set TEMPLATEFLOW_ARCHIVE_SCRIPTS to templateflow/.github/scripts') + return Path(scripts) / 'build-skeletons.py' + + +@pytest.fixture(scope='session') +def fixture(tmp_path_factory, builder) -> archive.Fixture: + """The Archive before and after the sample table, or the table to replay + (``TEMPLATEFLOW_COMPAT_RENAMES``; a template's fragment with + ``TEMPLATEFLOW_COMPAT_TEMPLATE``).""" + table = Path(os.getenv('TEMPLATEFLOW_COMPAT_RENAMES') or HERE / 'sample-renames.tsv') + rows = archive.read_rows(table.read_text(), os.getenv('TEMPLATEFLOW_COMPAT_TEMPLATE')) + conf = REPO / 'templateflow' / 'conf' + return archive.build( + tmp_path_factory.mktemp('archive'), + conf / 'templateflow-skel-v2.zip', + conf / 'templateflow-skel.zip', + rows, + builder, + ) + + +@pytest.fixture(scope='session') +def server(): + with Server() as running: + yield running + + +@pytest.fixture(scope='session') +def environments(tmp_path_factory): + """One environment per client (and DataLad), made on first use.""" + made: dict[tuple[str, bool], Path] = {} + root = tmp_path_factory.mktemp('envs') + uv = shutil.which('uv') + if uv is None: + pytest.skip('the compat matrix makes its environments with uv') + + def make(client: str, datalad: bool = False) -> Path: + if (client, datalad) not in made: + venv = root / (f'{client}-datalad' if datalad else client) + subprocess.run([uv, 'venv', '-q', '--python', PYTHON, str(venv)], check=True) + target = str(REPO) if client == 'branch' else f'templateflow=={client}' + subprocess.run( + [uv, 'pip', 'install', '-q', '--python', str(venv / 'bin' / 'python'), target] + + (['datalad', 'git-annex'] if datalad else []), + check=True, + ) + made[client, datalad] = venv / 'bin' / 'python' + return made[client, datalad] + + return make + + +class Client: + """A client version, its environment, and a home folder. + + With ``gitconfig``, the home is a DataLad home cloned through that configuration. + """ + + def __init__(self, name, python: Path, server: Server, home: Path, gitconfig=None): + self.name, self.python, self.server, self.home = name, python, server, home + self.gitconfig = gitconfig + + def run(self, *ops: dict) -> list: + # Nothing inherited may point a client at a real home or at the network + inherited = { + k: v + for k, v in os.environ.items() + if not k.startswith(('TEMPLATEFLOW_', 'PYTHON')) and k != 'VIRTUAL_ENV' + } + env = { + **inherited, + **archive.GIT_ENV, + 'TEMPLATEFLOW_HOME': str(self.home), + 'TEMPLATEFLOW_USE_DATALAD': 'on' if self.gitconfig else 'off', + 'TEMPLATEFLOW_COMPAT_SERVER': self.server.url, + 'PYTHONPATH': str(HERE / 'runtime'), + } + if self.gitconfig: + env['GIT_CONFIG_GLOBAL'] = str(self.gitconfig) + env['PATH'] = f'{self.python.parent}{os.pathsep}{env["PATH"]}' # git-annex + assert env['TEMPLATEFLOW_HOME'] == str(self.home) + self.home.parent.mkdir(parents=True, exist_ok=True) + (self.home.parent / '.templateflow-compat').touch() + proc = subprocess.run( + [str(self.python), str(HERE / 'runtime' / 'scenario.py'), json.dumps(list(ops))], + env=env, + capture_output=True, + text=True, + cwd=self.home.parent, + ) + if proc.returncode: + raise RuntimeError(f'{self.name}: scenario failed\n{proc.stderr[-3000:]}') + return json.loads(proc.stdout.strip().splitlines()[-1]) + + def get(self, *paths: str) -> dict[str, dict]: + return dict(zip(paths, self.run(*({'op': 'get', 'path': p} for p in paths)), strict=True)) + + def update(self, **kwargs) -> bool: + return self.run({'op': 'update', **kwargs})[0]['updated'] + + def files(self) -> dict[str, int]: + return self.run({'op': 'files'})[0] + + +@pytest.fixture +def client_for(tmp_path, environments, server): + def make(name: str, home: Path | None = None, datalad: DataladArchive | None = None): + python = environments(name, datalad=datalad is not None) + config = datalad.gitconfig(tmp_path / f'gitconfig-{name}') if datalad else None + return Client(name, python, server, home or tmp_path / 'home', config) + + return make + + +def entities_change(old: str, new: str) -> bool: + """Whether a query naming ``old`` misses ``new`` (the rename changed entities).""" + from templateflow.conf.renames import path_entities + + return path_entities(old) != path_entities(new) + + +def renamed(fixture, client=None): + """Rows of renamed files; with ``client``, those whose old name it knows.""" + rows = [(o, n) for o, n in fixture.rows if n not in archive.KEYWORDS] + return _known(rows, client) + + +def removed(fixture, client=None): + return _known([(o, n) for o, n in fixture.rows if n == 'n/a'], client) + + +def purged(fixture, client=None): + return _known([(o, n) for o, n in fixture.rows if n == 'purge'], client) + + +def _known(rows, client): + if client is None: + return rows + bundled = set(client.run({'op': 'bundled'})[0]) + return [(o, n) for o, n in rows if o in bundled] + + +def need(rows, what: str): + """Skip a test the table does not exercise (a replayed table may lack a kind).""" + if not rows: + pytest.skip(f'the renames table has no {what}') + return rows + + +def missed(result: dict) -> bool: + """The client got no file. 25.0 and older save the S3 error body as the file and + return it; that file stays broken, since only empty files are downloaded again.""" + return bool(result['error']) or any(c and 'NoSuchKey' in c for c in result['contents']) + + +def assert_found(result: dict, path: str, expected: bytes): + assert result['error'] is None, result + assert result['single'], result + assert result['paths'] == [path], result + assert result['contents'][0] == expected.decode(), result + + +# Pinned clients: no update, the bundled skeleton ###################################### + + +@pytest.mark.parametrize('name', CLIENTS) +def test_pinned(fixture, server, client_for, name): + """A client that never updates still downloads every file by its old name.""" + server.serve(fixture.states['after']) + client = client_for(name) + rows = need(renamed(fixture, client) + removed(fixture, client), f'names {name} knows') + found = client.get(*(old for old, _ in rows)) + for old, _ in rows: + assert_found(found[old], old, fixture.content('before', old)) + for old, result in client.get(*(o for o, _ in purged(fixture, client))).items(): + assert missed(result), f'{old} is purged, yet {name} downloaded it' + + +@pytest.mark.parametrize('name', CLIENTS) +def test_pinned_control_no_copies(fixture, server, client_for, name): + """Negative control: without the old S3 keys, pinned clients fail.""" + server.serve(fixture.states['no-copies']) + client = client_for(name) + rows = need(renamed(fixture, client), f'renames {name} knows') + found = client.get(*(old for old, _ in rows)) + assert all(missed(found[old]) for old, _ in rows), found + + +# Clients that update ################################################################## + + +@pytest.mark.parametrize('name', RELEASED) +def test_released_update(fixture, server, client_for, name): + """After ``update()``, released clients find one file per old name.""" + server.serve(fixture.states['after']) + client = client_for(name) + rows = need(renamed(fixture, client) + removed(fixture, client), f'names {name} knows') + client.files() # Create the home from the bundled skeleton + client.update() + found = client.get(*(old for old, _ in rows)) + for old, _ in rows: + assert_found(found[old], old, fixture.content('before', old)) + + +@pytest.mark.parametrize('name', RELEASED) +def test_released_update_control_v2_at_legacy_url(fixture, server, client_for, name): + """Negative control: the v2 skeleton at the legacy URL gives released clients two + files for renames that keep the entities (``res-01`` to ``res-1``, reordering).""" + server.serve(fixture.states['v2-as-legacy']) + client = client_for(name) + rows = [(o, n) for o, n in renamed(fixture, client) if not entities_change(o, n)] + need(rows, 'renames that keep the entities') + client.files() + client.update() + found = client.get(*(old for old, _ in rows)) + assert all(not found[old]['single'] for old, _ in rows), found + + +def test_branch_update(fixture, server, client_for): + """The client under test follows the renames, and warns on old queries.""" + server.serve(fixture.states['after']) + client = client_for('branch') + client.files() + assert client.update() + rows = need(renamed(fixture), 'renames') + found = client.get(*(old for old, _ in rows), *(new for _, new in rows)) + for old, new in rows: + assert_found(found[old], new, fixture.content('before', old)) + assert bool(found[old]['warnings']) is entities_change(old, new), found[old] + assert_found(found[new], new, fixture.content('before', old)) + assert not found[new]['warnings'] + for old, _ in removed(fixture): + result = client.get(old)[old] + assert_found(result, old, fixture.content('before', old)) + assert any('removed from the Archive' in w for w in result['warnings']) + + +# Shared homes ######################################################################### + + +@pytest.mark.parametrize('name', RELEASED) +def test_shared_home(fixture, server, client_for, name, tmp_path): + """A home of a released client, used and migrated by the client under test.""" + home = tmp_path / 'home' + released, branch = client_for(name, home), client_for('branch', home) + rows = need(renamed(fixture, released), f'renames {name} knows') + + # Before the table: the released client downloads files by their old names + server.serve(fixture.states['before']) + found = released.get(*(old for old, _ in rows)) + for old, _ in rows: + assert_found(found[old], old, fixture.content('before', old)) + + # The table lands; the released client updates and keeps its files + server.serve(fixture.states['after']) + released.update() + found = released.get(*(old for old, _ in rows)) + for old, _ in rows: + assert_found(found[old], old, fixture.content('before', old)) + + # The client under test, without migrating: current queries find the old files + branch.update() + found = branch.get(*(new for _, new in rows)) + for old, new in rows: + assert_found(found[new], old, fixture.content('before', old)) + assert not found[new]['warnings'] + + # Migrating moves the downloads to the new names: nothing is downloaded again + branch.update(migrate=True) + files = branch.files() + assert not any(old in files for old, _ in rows) + server.requests.clear() + found = branch.get(*(new for _, new in rows)) + for old, new in rows: + assert_found(found[new], new, fixture.content('before', old)) + assert not [r for r in server.requests if r.startswith('/s3/')], server.requests + + # The released client, without updating, finds renamed files whose entities did not + # change (its queries match the new names) + found = released.get(*(old for old, _ in rows)) + for old, new in rows: + if not entities_change(old, new): + assert_found(found[old], new, fixture.content('before', old)) + + +# DataLad homes ######################################################################## +# +# DataLad homes clone the Archive and follow it with ``datalad update --merge``: the +# skeletons and the old S3 keys do not reach them. After an update, the old names are +# gone from the home; 26.0 resolves them through the home's ``renames.tsv``. + + +@pytest.fixture +def datalad_archive(tmp_path, fixture, environments) -> DataladArchive: + text = { + path: data + for path, data in fixture.files['before'].items() + if path.count('/') == 1 and path.split('/', 1)[1] in TEXT + } + bin_dir = environments('branch', datalad=True).parent + return DataladArchive(tmp_path / 'datalad', fixture.rows, text, bin_dir) + + +def datalad_rows(archive_): + renamed_ = [(o, n) for o, n in archive_.rows if n not in archive.KEYWORDS] + return renamed_, [(o, n) for o, n in archive_.rows if n == 'n/a'] + + +def install_and_update(client, datalad_archive) -> None: + """The client downloads the old names, then the Archive applies the table.""" + renamed_, removed_ = datalad_rows(datalad_archive) + found = client.get(*(old for old, _ in renamed_ + removed_)) + for old, _ in renamed_ + removed_: + assert_found(found[old], old, archive.content(old)) + datalad_archive.apply() + client.update() + + +def test_branch_datalad(fixture, server, client_for, datalad_archive): + """In DataLad homes, 26.0 resolves old queries after ``datalad update``.""" + server.serve(fixture.states['after']) + client = client_for('branch', datalad=datalad_archive) + install_and_update(client, datalad_archive) + renamed_, removed_ = datalad_rows(datalad_archive) + found = client.get(*(old for old, _ in renamed_ + removed_)) + for old, new in renamed_: + assert_found(found[old], new, archive.content(old)) + assert bool(found[old]['warnings']) is entities_change(old, new), found[old] + for old, _ in removed_: + assert_found(found[old], old, archive.content(old)) + assert any('removed from the Archive' in w for w in found[old]['warnings']) + + +@pytest.mark.parametrize('name', RELEASED) +def test_released_datalad(fixture, server, client_for, datalad_archive, name): + """Released clients in DataLad homes still find renames that keep the entities.""" + server.serve(fixture.states['after']) + client = client_for(name, datalad=datalad_archive) + install_and_update(client, datalad_archive) + rows = [(o, n) for o, n in datalad_rows(datalad_archive)[0] if not entities_change(o, n)] + need(rows, 'renames that keep the entities') + found = client.get(*(old for old, _ in rows)) + for old, new in rows: + assert_found(found[old], new, archive.content(old)) + + +@pytest.mark.xfail( + strict=True, + raises=Break, + reason='Accepted: in DataLad homes, released clients lose old names that changed ' + 'entities, and removed files, after datalad update (announced with 26.0)', +) +@pytest.mark.parametrize('name', RELEASED) +def test_released_datalad_break(fixture, server, client_for, datalad_archive, name): + """Released clients in DataLad homes lose the other old names after an update.""" + server.serve(fixture.states['after']) + client = client_for(name, datalad=datalad_archive) + install_and_update(client, datalad_archive) + renamed_, removed_ = datalad_rows(datalad_archive) + rows = [(o, n) for o, n in renamed_ if entities_change(o, n)] + removed_ + need(rows, 'renames that change the entities, or removed files') + found = client.get(*(old for old, _ in rows)) + lost = [old for old, _ in rows if not found[old]['single']] + if lost: + raise Break(f'{name} lost {lost}') From 28121eb83ad913981f81f7d495c0a4754ce9323d Mon Sep 17 00:00:00 2001 From: Oscar Esteban Date: Thu, 3 Dec 2026 12:44:53 +0100 Subject: [PATCH 2/3] ci: pin setup-uv to a release tag (it publishes no major tags) Co-Authored-By: Claude Opus 5.5 --- .github/workflows/compat.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/compat.yml b/.github/workflows/compat.yml index 0942bbd9..2f074597 100644 --- a/.github/workflows/compat.yml +++ b/.github/workflows/compat.yml @@ -60,7 +60,7 @@ jobs: path: archive sparse-checkout: .github/scripts persist-credentials: false - - uses: astral-sh/setup-uv@v10 + - uses: astral-sh/setup-uv@v10.4.1 - name: Fetch the table to replay if: inputs.renames-url != '' env: From da241eea06258877a6781d8d71f2aede6c69f365 Mon Sep 17 00:00:00 2001 From: Oscar Esteban Date: Thu, 3 Dec 2026 12:49:30 +0100 Subject: [PATCH 3/3] ci: run the compatibility matrix on Python 3.15 too numpy, pandas, scipy, SQLAlchemy, PyYAML and greenlet publish cp315 wheels; the matrix passes locally on 3.15 (16 passed, 2 xfailed). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/compat.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/compat.yml b/.github/workflows/compat.yml index 2f074597..20e4815e 100644 --- a/.github/workflows/compat.yml +++ b/.github/workflows/compat.yml @@ -43,8 +43,8 @@ jobs: strategy: fail-fast: false matrix: - # SPEC 0 (Python 3.15 joins once pybids' dependencies publish wheels) - python-version: ['3.13', '3.14'] + # SPEC 0 + python-version: ['3.13', '3.14', '3.15'] env: TEMPLATEFLOW_COMPAT_PYTHON: ${{ matrix.python-version }} TEMPLATEFLOW_ARCHIVE_SCRIPTS: ${{ github.workspace }}/archive/.github/scripts