diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..2f7a4ae --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,45 @@ +# Dependabot opens pull requests that move what this repository pins: the +# actions in .github/workflows (pinned by commit, with the version in a +# comment, which Dependabot keeps), the direct dependencies' pins in +# uv.lock, and the image's base. These version updates come monthly, one +# pull request per ecosystem. With Dependabot security updates on (a +# repository setting), a pull request also comes as soon as an advisory +# names a version pinned here. +# +# Each waits a week after a release before proposing it: a release that +# was compromised, or broken, is usually pulled within days. +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: monthly + cooldown: + default-days: 7 + groups: + actions: + patterns: ["*"] + + # uv.lock alone. pyproject.toml's lower bounds are floors that CI installs + # and tests (the floors job), so they move by hand, with a reason. + # Version updates cover the direct dependencies, Dependabot's default. + - package-ecosystem: uv + directory: / + schedule: + interval: monthly + versioning-strategy: lockfile-only + cooldown: + default-days: 7 + groups: + python: + patterns: ["*"] + + # The Dockerfile's base image, tag and digest together. Its tag names the + # uv it ships, so this moves the image's uv too; the uv the workflows + # install is setup-uv's `version`, which Dependabot does not read. + - package-ecosystem: docker + directory: / + schedule: + interval: monthly + cooldown: + default-days: 7 diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index ca53a0f..57c86c6 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -5,14 +5,16 @@ # *does* gate merges is tests/test_performance.py, which counts operations # rather than seconds and lives in the ordinary test job. # -# Its own file rather than a job in publish.yml: at the `ci` tier this takes -# the better part of an hour, and hanging that off the release graph would -# either delay the PyPI publish or paint the release run red for a report. +# publish.yml starts it, by a dispatch from the tag, once a release is out: +# PyPI has the version and the release page exists. Up to 0.17.10 every tag +# pushed started it, beside publish.yml, so a tag publish.yml refused still +# had its results committed to main. Its own file rather than a job in +# publish.yml: at the `ci` tier this takes the better part of an hour, and +# hanging that off the release graph would hold the release run open, or +# paint it red, for a report. name: Benchmark on: - push: - tags: ["*"] workflow_dispatch: inputs: tier: @@ -21,7 +23,7 @@ on: options: [smoke, ci, large] default: ci publish: - description: Commit the results to docs/ on main + description: Push the results to a branch, for a pull request into main type: boolean default: false @@ -29,8 +31,9 @@ concurrency: group: benchmark-${{ github.ref }} cancel-in-progress: true -# None by default: the repository's default token can write. The job that -# measures reads; only the job that commits the results can write. +# None by default: a job that names no permissions gets the repository's +# default token. The job that measures reads; only the job that pushes the +# results can write. permissions: {} jobs: @@ -55,7 +58,7 @@ jobs: persist-credentials: false # No cache: what is restored here would run in the job that produces - # the numbers committed to main. + # the numbers published in docs/. - uses: astral-sh/setup-uv@caf0cab7a618c569241d31dcd442f54681755d39 # v3.2.4 with: version: "0.13.1" @@ -99,21 +102,28 @@ jobs: # with nothing to compare it against says very little. The page is # already served by Pages from docs/, so this needs no extra machinery. # + # The results go to a branch, benchmark/, for a pull request into + # main. Up to 0.17.10 this job pushed to main itself, unreviewed, which + # the ruleset planned for main refuses. It cannot open the pull request: + # the repository lets no workflow open or approve one, and one opened by + # this token would start no checks. So it links the pull request to open, + # in the run's summary. Merge it before the next release: that release's + # "vs previous" and history read docs/benchmarks/ on main. + # # This job holds the write token, so it installs nothing: the report is # the standard library and benchmarks/ from main, and results.json is read # as data. It renders its own summary rather than take the one above. publish: - name: Commit the results to docs/ + name: Push the results for a pull request needs: [benchmark] - # A pushed tag, or a dispatch that asks. A dispatch from a tag that does - # not ask must not overwrite that release's results with another tier. - if: needs.benchmark.outputs.measured == 'true' && (github.event_name == 'push' || inputs.publish) + # A dispatch that asks, as publish.yml's does. One that does not ask must + # not overwrite a release's results with another tier. + if: needs.benchmark.outputs.measured == 'true' && inputs.publish runs-on: ubuntu-latest - # 15 for the commit, and the 30 the notes step may wait for the release. - timeout-minutes: 45 + timeout-minutes: 15 continue-on-error: true permissions: - contents: write # push to main, and edit the release notes + contents: write # push the results' branch, and edit the release notes steps: # A tag build is on a detached HEAD; the page belongs on main. The # credentials stay for the push, and nothing here is uploaded. @@ -121,14 +131,15 @@ jobs: with: ref: main fetch-depth: 0 - persist-credentials: true # zizmor: ignore[artipacked] it pushes to main + persist-credentials: true # zizmor: ignore[artipacked] it pushes the results' branch - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: benchmark-results path: ${{ runner.temp }}/results - - name: Publish to docs + - name: Push the results to a branch + id: push env: REF_NAME: ${{ github.ref_name }} run: | @@ -140,20 +151,20 @@ jobs: if git diff --cached --quiet; then echo "nothing to publish"; exit 0 fi - git commit -m "Benchmark results for $REF_NAME [skip ci]" - # Another job may have landed on main in the meantime. - for _ in 1 2 3; do - if git push origin main; then exit 0; fi - git pull --rebase origin main - done - echo "could not push benchmark results"; exit 1 + branch="benchmark/$REF_NAME" + git switch -c "$branch" + # No [skip ci]: the pull request's checks must run before it merges. + git commit -m "Benchmark results for $REF_NAME" + # A re-run replaces what an earlier run pushed. + git push --force origin "HEAD:refs/heads/$branch" + url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/compare/main...$branch?expand=1" + echo "::notice title=Benchmark results::open a pull request from $branch: $url" + echo "The results are on \`$branch\`: [open a pull request into main]($url)." >> "$GITHUB_STEP_SUMMARY" - # Best effort, and last. publish.yml creates the release once PyPI has - # the version, normally before this job gets here, but only by 7 to 13 - # minutes (0.17.4 to 0.17.6): slow tests or a re-run in Publish would - # leave no release yet. So it waits up to 30 minutes for one; a failed - # publish leaves none. The docs page is authoritative either way, and - # re-running this job appends the summary later. + # Best effort, and last. publish.yml starts this run once the release + # exists; a dispatch from a tag with no release skips this. The docs + # page is authoritative either way, and re-running this job replaces + # the summary. - name: Append to the release notes if: github.ref_type == 'tag' continue-on-error: true @@ -161,12 +172,8 @@ jobs: GH_TOKEN: ${{ github.token }} TAG: ${{ github.ref_name }} run: | - for _ in $(seq 30); do - gh release view "$TAG" >/dev/null 2>&1 && break - sleep 60 - done gh release view "$TAG" >/dev/null 2>&1 || { - echo "no release for $TAG after 30 minutes; skipping"; exit 0 + echo "no release for $TAG; skipping"; exit 0 } gh release view "$TAG" --json body -q .body > "$RUNNER_TEMP/body.md" # Idempotent: replace any block this job wrote before. diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 37dd103..a6ded04 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -6,14 +6,22 @@ name: Publish # # a pushed tag PyPI, then the image and the # GitHub release -# workflow_dispatch, target testpypi TestPyPI only, from any ref +# workflow_dispatch, target testpypi TestPyPI only, from main, a +# release/* branch or a tag (the +# testpypi environment's rule) # workflow_dispatch, target pypi PyPI, then the image and the # release; from a tag only, as # check-version refuses a branch # # Nothing publishes unless the suite passed, and nothing reaches PyPI, -# quay.io or the releases page unless the tag matches pyproject.toml and -# docs/changelog.md has a section for it. +# quay.io or the releases page unless the tag is on main, matches +# pyproject.toml and has a section in docs/changelog.md. Once the release +# is out, this starts the benchmark (benchmark.yml). +# +# Those checks catch mistakes. The gate is in the repository's settings, +# since this file runs as the tagged commit has it: a ruleset lets only an +# admin push a tag, and the pypi environment takes only an X.Y.Z tag and +# waits for the maintainer's approval. on: push: tags: ["*"] @@ -26,15 +34,25 @@ on: type: choice options: [testpypi, pypi] -# None by default: the repository's default token can write, and a job that -# names no permissions gets that. Each job below asks for what it uses. +# None by default: a job that names no permissions gets the repository's +# default token. Each job below asks for what it uses. permissions: {} +# One run at a time, never cancelled. Two releases at once raced to move +# quay.io's :latest and GitHub's Latest, and a release stopped part way +# would leave a version on PyPI with no image or release page. GitHub keeps +# one run waiting and cancels it if another arrives, so push one release tag +# at a time. +concurrency: + group: publish + cancel-in-progress: false + jobs: # The tag must match the version in pyproject.toml. Nothing enforced this # before, and 0.3.2 was tagged against a tree declaring 0.3.1. check-version: runs-on: ubuntu-latest + timeout-minutes: 10 # Every tag, and every dispatch to PyPI: one from a branch fails here, # rather than pass having published nothing. if: startsWith(github.ref, 'refs/tags/') || inputs.target == 'pypi' @@ -45,6 +63,8 @@ jobs: steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: + # main's history, for the check that the tag is on it. + fetch-depth: 0 persist-credentials: false - name: Tag must match the declared version id: version @@ -61,6 +81,22 @@ jobs: exit 1 fi echo "version=$declared" >> "$GITHUB_OUTPUT" + # A release is what was reviewed and merged into main. A tag on the + # release branch before it was merged, or on a commit main took only + # as a squash, stops here: main never had that commit. + - name: The tag must be on main + id: on-main + run: | + # The full name: git would take a tag called origin/main first. + main=refs/remotes/origin/main + if ! git rev-parse --verify --quiet "$main" >/dev/null; then + echo "::error::main was not fetched, so the tag cannot be checked against it" + exit 1 + fi + if ! git merge-base --is-ancestor HEAD "$main"; then + echo "::error::$GITHUB_REF_NAME is not on main: merge the release branch, then tag main" + exit 1 + fi # The GitHub release's notes are this section, so check it before # anything is published rather than after: once PyPI has the version # the tag cannot change, and no re-run could mend the notes. The @@ -90,6 +126,7 @@ jobs: build: needs: [test] runs-on: ubuntu-latest + timeout-minutes: 15 permissions: contents: read steps: @@ -112,6 +149,7 @@ jobs: needs: [build] if: github.event_name == 'workflow_dispatch' && inputs.target == 'testpypi' runs-on: ubuntu-latest + timeout-minutes: 15 environment: testpypi permissions: id-token: write # trusted publishing; no API token secret needed @@ -131,6 +169,8 @@ jobs: needs: [build, check-version] if: github.event_name == 'push' || inputs.target == 'pypi' runs-on: ubuntu-latest + # From when the maintainer approves: the wait for that is not timed. + timeout-minutes: 15 environment: pypi permissions: id-token: write @@ -162,12 +202,24 @@ jobs: github-release: needs: [check-version, publish-pypi] runs-on: ubuntu-latest + timeout-minutes: 10 permissions: contents: write # create the release steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: persist-credentials: false + # GitHub shows each newline in a release's notes as a line break, where + # the changelog's page joins wrapped lines into paragraphs, so up to + # 0.17.10 every paragraph showed ragged. The second awk joins each + # wrapped line to the one before it, as CommonMark does for what the + # changelog uses. A blank line, a heading, a rule, a table row that + # starts with `|`, a link definition, fenced code, a quote's lines and + # a line ending in a hard break keep their own lines. A list item + # starts a line where CommonMark starts one: inside a paragraph, an + # empty item or a number other than 1 is a wrapped line (`exited` / + # `0.`), unless it is indented less than the list item it follows. + # tests/test_release_pipeline.py checks every section with markdown-it. - name: Notes from the changelog id: notes env: @@ -175,15 +227,92 @@ jobs: run: | awk -v tag="$TAG" \ '$0 == "## " tag { on = 1; next } on && /^## / { exit } on' \ - docs/changelog.md > notes.md + docs/changelog.md > section.md + awk ' + function flush() { if (held != "") print held; held = "" } + function indent(s) { return match(s, /[^[:space:]]/) ? RSTART - 1 : length(s) } + fenced { print; if ($0 ~ fence) fenced = 0; next } + /^[[:space:]]*(```|~~~)/ { + flush(); print; fenced = 1 + fence = /^[[:space:]]*```/ ? "^[[:space:]]*```+[[:space:]]*$" : "^[[:space:]]*~~~+[[:space:]]*$" + next + } + /^[[:space:]]*$/ { flush(); print; next } + /^[[:space:]]*#+[[:space:]]/ || /^[[:space:]]*#+$/ || /^[[:space:]]*[|>]/ || /^[[:space:]]*\[[^]]+\]:/ { + flush(); print; next + } + /^[[:space:]]*(-+|=+|-[[:space:]]*-[[:space:]]*-[-[:space:]]*|\*[[:space:]]*\*[[:space:]]*\*[*[:space:]]*|_[[:space:]]*_[[:space:]]*_[_[:space:]]*)$/ { + flush(); print; next + } + /^[[:space:]]*([-*+]|[0-9]+[.)])[[:space:]]/ || /^[[:space:]]*([-*+]|[0-9]+[.)])$/ { + if (indent($0) < heldcol || /^[[:space:]]*([-*+]|0*1[.)])[[:space:]]+[^[:space:]]/) flush() + } + { + if (held == "") { + held = $0 + heldcol = match($0, /^[[:space:]]*([-*+]|[0-9]+[.)])[[:space:]]+/) ? RLENGTH : indent($0) + } else { + line = $0 + sub(/[[:space:]]+$/, "", held); sub(/^[[:space:]]+/, "", line) + held = held " " line + } + if (held ~ / $/ || (match(held, /\\+$/) && RLENGTH % 2)) flush() + } + END { flush() } + ' section.md > notes.md grep -q '[^[:space:]]' notes.md + # GitHub makes a new release Latest unless told otherwise, so a + # backport tagged after a later release would have taken it. The same + # test as quay.io's :latest (quay-on-tag.yml), made as late: a re-run + # after a newer release still gets it right. + - name: Is this the newest release? + id: latest + env: + VERSION: ${{ needs.check-version.outputs.version }} + # GitHub runs a bare `run:` without pipefail, which would let a failed + # ls-remote pass for "no newer release". + run: | + set -o pipefail + newest=$(git ls-remote --tags --refs origin \ + | sed 's#.*refs/tags/##' \ + | { grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' || true; } \ + | sort -V | tail -n 1) + echo "newest release: ${newest:-none}; this one: $VERSION" + if [ "$VERSION" = "$newest" ]; then + echo "latest=true" >> "$GITHUB_OUTPUT" + else + echo "latest=false" >> "$GITHUB_OUTPUT" + fi - name: Create the release + id: create env: GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} TAG: ${{ needs.check-version.outputs.version }} + LATEST: ${{ steps.latest.outputs.latest }} run: | if gh release view "$TAG" >/dev/null 2>&1; then echo "release $TAG already exists"; exit 0 fi - gh release create "$TAG" --verify-tag --title "$TAG" --notes-file notes.md + gh release create "$TAG" --verify-tag --title "$TAG" \ + --notes-file notes.md --latest="$LATEST" + + # The benchmark measures the release, so it starts once PyPI has the + # version and the release page exists. Up to 0.17.10 it ran on any tag + # pushed, beside this workflow, and committed its results to main even for + # a tag this workflow refused. A dispatch is the one way this job's token + # can start another workflow. + benchmark: + needs: [check-version, github-release] + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + actions: write # start benchmark.yml + steps: + - name: Start the benchmark + id: start + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + TAG: ${{ needs.check-version.outputs.version }} + run: gh workflow run benchmark.yml --ref "$TAG" -f tier=ci -f publish=true diff --git a/.github/workflows/quay-on-tag.yml b/.github/workflows/quay-on-tag.yml index 329f10e..ca64ef7 100644 --- a/.github/workflows/quay-on-tag.yml +++ b/.github/workflows/quay-on-tag.yml @@ -1,9 +1,9 @@ name: Build & Push Docker image (tag) -# Called by publish.yml once a tag has passed the suite, matched -# pyproject.toml and reached PyPI; nothing triggers it on its own. Up to -# 0.17.4 it ran on every tag by itself, so a tag whose tests failed, or that -# named the wrong version, still pushed an image and moved :latest. +# Called by publish.yml once a tag has passed publish.yml's checks and the +# suite and reached PyPI; nothing triggers it on its own. Up to 0.17.4 it +# ran on every tag by itself, so a tag whose tests failed, or that named the +# wrong version, still pushed an image and moved :latest. on: workflow_call: inputs: @@ -23,6 +23,11 @@ jobs: docker: runs-on: ubuntu-latest timeout-minutes: 45 + # Quay's credentials are secrets of this environment, which the + # repository's settings limit to release tags. publish.yml passes them + # by name: a called workflow gets an environment's secret only that way, + # and the environment's value wins over a repository secret's. + environment: quay permissions: contents: read diff --git a/AGENTS.md b/AGENTS.md index 7830f26..3486d4a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -319,27 +319,45 @@ an item to Released when its tag is out. - whichever of `### Added`, `### Changed` and `### Fixed` apply (0.7.1 has only `Fixed`; an empty section is left out); - entries that start with a bold one-line lead and an issue link. -- Merge the release branch, then push a tag with no `v` prefix. The tag - triggers: - - `publish.yml`, which checks that the tag matches pyproject and has a - changelog section, tests (`tests.yml`, including a build and smoke test - of the Docker image), builds and publishes to PyPI. Then, side by side, - it calls `quay-on-tag.yml` to build the image, check that it runs, and - push that image to `quay.io/cellgeni/adata-cli`, and creates the GitHub - release with the changelog section as its notes (a failed image does - not hold it back). If the tests fail or a check does not pass, nothing - is published. `:latest` moves only to the +- Merge the release branch, then tag the merge with no `v` prefix. The tag + triggers `publish.yml`, which: + - checks that the tag is on `main`, matches pyproject and has a changelog + section, tests (`tests.yml`, including a build and smoke test of the + Docker image), builds and publishes to PyPI once the maintainer + approves. If the tests fail or a check does not pass, nothing is + published; + - then, side by side, calls `quay-on-tag.yml` to build the image, check + that it runs, and push that image to `quay.io/cellgeni/adata-cli`, and + creates the GitHub release with the changelog section as its notes, + each wrapped paragraph joined into one line (a failed image does not + hold the release back). `:latest` and GitHub's Latest move only to the highest `X.Y.Z` tag. Don't create the release by hand: that step was missed from 0.12.0 on, and releases had to be backfilled; - - `benchmark.yml`, which reruns `benchmarks/` and commits the results to - `docs/reference/benchmarks.md` and `docs/benchmarks/.json`, and - appends a summary to the release notes. The job that measures has a - read-only token; the one that commits installs nothing. -- A manual `Publish` dispatch to `testpypi` publishes there alone, from any - ref. One to `pypi` publishes, pushes the image and creates the release, - only when run from a tag; from a branch it fails. + - last, starts `benchmark.yml`, which reruns `benchmarks/`, pushes the + results (`docs/reference/benchmarks.md` and + `docs/benchmarks/.json`) to a branch `benchmark/`, and appends + a summary to the release notes. Open the pull request that its run's + summary links, and merge it before the next release, whose "vs + previous" and history read `docs/benchmarks/` on `main`. The job that + measures has a read-only token; the one that pushes installs nothing. + + One `Publish` run goes at a time, and a run that has started is never + cancelled. GitHub keeps one more run waiting and cancels it when another + arrives, so push one tag at a time. Every job has a timeout. +- The gate is in the repository's settings, since a workflow runs as the + tagged commit has it: a ruleset lets only an admin push a tag, and the + `pypi` and `quay` environments take only `X.Y.Z` tags, `pypi` after the + maintainer's approval. Quay's secrets belong to the `quay` environment. + The tag-on-`main` check catches mistakes. +- A manual `Publish` dispatch to `testpypi` publishes there alone, from + `main`, a `release/*` branch or a tag (the `testpypi` environment's rule). + One to `pypi` publishes, pushes the image and creates the release, only + when run from a tag; from a branch it fails. - Workflows pin third-party actions by commit SHA, with the version in a comment, and pass tags and inputs to scripts through `env:`. `tests/test_release_pipeline.py` and the `workflow lint` job check both. + Dependabot (`.github/dependabot.yml`) proposes new pins monthly, for the + actions, `uv.lock` and the image's base. Vulnerabilities are reported + privately (`SECURITY.md`). - `docs/reference/benchmarks.md` is generated. To change its wording, edit `benchmarks/page_template.md`. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..66d6331 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,42 @@ +# Security policy + +## Reporting a vulnerability + +Report a vulnerability privately, through GitHub's private vulnerability +reporting: open the repository's **Security** tab and choose **Report a +vulnerability**, or go straight to +. Please don't +open a public issue, pull request or discussion about it. + +`adata` reads files that other people wrote: HDF5 and Zarr stores, the +formats `convert` reads, images, tables and pickles. A file that makes +`adata` run code, or create or overwrite files that the command was not +asked to write, is a vulnerability. So is a way to change what a release +contains, on PyPI (`pyadata-cli`) or as the image +`quay.io/cellgeni/adata-cli`. If you are not sure whether something is one, +report it privately anyway: it can always move to a public issue. + +A report helps most when it gives: + +- the version (`adata --version`), and whether it came from PyPI or the image; +- the command, and a file that shows the problem, or a short script that + writes one; +- what happened, and what you expected. + +The report stays private while the fix is made. The fix comes out as a +release, with a GitHub security advisory that credits you unless you ask it +not to. + +## Supported versions + +Fixes go into a new release of the newest minor version. Older releases are +not patched: upgrade with `pip install -U pyadata-cli`, or pull the image's +`:latest`. + +## Pickles + +pycisTopic pickles are trusted input: read one only from a source you would +trust with the data itself. `adata` reads them through an allowlist rather +than running them, and checks what it builds from them +([why and how](https://cellgeni.github.io/adata-cli/reference/formats/cistopic/#pickles-are-trusted-input)). +A pickle that gets past those checks is worth reporting. diff --git a/benchmarks/page_template.md b/benchmarks/page_template.md index 22639b7..dce0c8d 100644 --- a/benchmarks/page_template.md +++ b/benchmarks/page_template.md @@ -10,7 +10,7 @@ redirect_from: adata-cli measured against anndata, and against scanpy wherever scanpy has a real equivalent. The [`Benchmark`](https://github.com/cellgeni/adata-cli/blob/main/.github/workflows/benchmark.yml) workflow rewrites -this page on every tag and keeps each run's raw numbers in `docs/benchmarks/`. +this page after every release and keeps each run's raw numbers in `docs/benchmarks/`. **Peak RSS is the headline, not wall time.** This tool exists so that memory is set by `--chunk` rather than by the size of the input. For data that fits in RAM, loading diff --git a/docs/developers.md b/docs/developers.md index 81f2abd..7953aca 100644 --- a/docs/developers.md +++ b/docs/developers.md @@ -258,9 +258,10 @@ uv run python -m benchmarks.run --tier smoke --case concat-inner --out results.j uv run python -m benchmarks.report results.json ``` -The `Benchmark` workflow runs the `ci` tier on every tag and commits the -results to [Benchmarks](reference/benchmarks.md) and `docs/benchmarks/.json`. -It reports and never gates; the complexity guards gate. +`publish.yml` starts the `Benchmark` workflow once a release is out. It runs +the `ci` tier and pushes the results, [Benchmarks](reference/benchmarks.md) +and `docs/benchmarks/.json`, to a branch `benchmark/` for a pull +request into `main`. It reports and never gates; the complexity guards gate. ## Releases @@ -270,24 +271,42 @@ It reports and never gates; the complexity guards gate. 3. Add a `## X.Y.Z` section at the top of `docs/changelog.md`: a summary paragraph, then whichever of `### Added`, `### Changed` and `### Fixed` apply, each entry led by a bold line and an issue link. -4. Merge, then push a tag with no `v` prefix. The tag runs `publish.yml`, - which checks the tag against `pyproject.toml` and `docs/changelog.md`, - tests (`tests.yml`, including a build and smoke test of the image), - publishes to PyPI. Then, side by side, it calls `quay-on-tag.yml` to - build the image, check that it runs, and push that image, and creates - the GitHub release from the changelog section. If the tests fail or a check does not pass, - nothing is published. `:latest` moves only to the highest `X.Y.Z` tag. - Don't create the release by hand. The tag also runs `benchmark.yml` (the - benchmark page, which it also appends to the release notes), whose - measuring job has a read-only token; the job that commits the results - installs nothing. - -A manual `Publish` dispatch to TestPyPI publishes there alone, from any ref; -one to PyPI publishes, pushes the image and creates the release, only when -run from a tag, and fails from a branch. +4. Merge, then tag the merge with no `v` prefix. The tag runs + `publish.yml`, which checks that the tag is on `main` and agrees with + `pyproject.toml` and `docs/changelog.md`, tests (`tests.yml`, including + a build and smoke test of the image), and publishes to PyPI once you + approve the `pypi` deployment. Then, side by side, it calls + `quay-on-tag.yml` to build the image, check that it runs, and push that + image, and creates the GitHub release from the changelog section, each + wrapped paragraph joined into one line. If the tests fail or a check + does not pass, nothing is published. `:latest` and GitHub's Latest move + only to the highest `X.Y.Z` tag. Don't create the release by hand. +5. Last, `publish.yml` starts `benchmark.yml`, which pushes the benchmark + page to a branch `benchmark/` and appends a summary to the release + notes. Open the pull request its run's summary links, and merge it + before the next release: that release's "vs previous" and history read + `docs/benchmarks/` on `main`. Its measuring job has a read-only token; + the job that pushes the results installs nothing. + +One `Publish` run goes at a time, and a run that has started is never +cancelled. GitHub keeps one more run waiting and cancels it when another +arrives, so push one tag at a time. The gate is in the repository's +settings, since a workflow runs as the tagged commit has it: only an admin +can push a tag, and the `pypi` and `quay` environments take only `X.Y.Z` +tags, `pypi` after your approval. Quay's secrets belong to the `quay` +environment. + +A manual `Publish` dispatch to TestPyPI publishes there alone, from `main`, +a `release/*` branch or a tag (the `testpypi` environment's rule); one to +PyPI publishes, pushes the image and creates the release, only when run +from a tag, and fails from a branch. Workflows pin third-party actions by commit SHA, with the version in a comment, and pass tags and inputs to scripts through `env:`. `tests/test_release_pipeline.py` and the `workflow lint` job check both. +Dependabot proposes new pins monthly, for the actions, `uv.lock` and the +image's base. Vulnerabilities are reported privately, as +[SECURITY.md](https://github.com/cellgeni/adata-cli/blob/main/SECURITY.md) +says. `h5ad` as a command name, `info` and `convert` with `recast`'s flags are deprecated and stay until 1.0.0. diff --git a/docs/reference/benchmarks.md b/docs/reference/benchmarks.md index b25dbcc..78d7894 100644 --- a/docs/reference/benchmarks.md +++ b/docs/reference/benchmarks.md @@ -10,7 +10,7 @@ redirect_from: adata-cli measured against anndata, and against scanpy wherever scanpy has a real equivalent. The [`Benchmark`](https://github.com/cellgeni/adata-cli/blob/main/.github/workflows/benchmark.yml) workflow rewrites -this page on every tag and keeps each run's raw numbers in `docs/benchmarks/`. +this page after every release and keeps each run's raw numbers in `docs/benchmarks/`. **Peak RSS is the headline, not wall time.** This tool exists so that memory is set by `--chunk` rather than by the size of the input. For data that fits in RAM, loading diff --git a/docs/reference/testing.md b/docs/reference/testing.md index 1dcd98e..7fb7167 100644 --- a/docs/reference/testing.md +++ b/docs/reference/testing.md @@ -46,12 +46,15 @@ before testing anything. uv takes its interpreter from `.python-version` suite on 3.12; the workflow now sets `UV_PYTHON` for each leg. The workflows are tested too. Publishing, the image and the benchmark run -only on a tag, so a pull request never runs them. `test_release_pipeline.py` -reads them, works out which jobs publish in each kind of run, and runs their -scripts against stand-ins. The `workflow lint` job runs on every pull -request, though not inside a release, where an advisory published that day -would stop it. The `container image` job runs on every pull request and -inside every release before PyPI has it. +only for a release, so a pull request never runs them. +`test_release_pipeline.py` reads them, works out which jobs publish in each +kind of run, and runs their scripts against real git repositories and +stand-ins for `gh`. The release notes are checked with markdown-it, rendered +as GitHub shows a release and as the site shows the changelog. The +`workflow lint` job runs on every pull request, though not inside a +release, where an advisory published that day would stop it. The +`container image` job runs on every pull request and inside every release +before PyPI has it. ## How the suite is organised @@ -103,7 +106,7 @@ inside every release before PyPI has it. | `test_external_readers.py` | Every converter checked by the reader people use, each in its own uv environment pinned in `reference_stores.ORACLES` (`integration`): 10x HDF5 and MTX and CellBender by scanpy, and our 10x export by PyTables; Parse runs by Parse's own scanpy recipe; looms by anndata with loompy (the pySCENIC tutorial's recipe for SCope looms); anndata's `read_csv`, `read_text` and `read_hdf`; a pandas 1.5 pycisTopic pickle read back there; mudata (a file it writes read as it reads it; ours read by it); Visium by squidpy, Visium HD by scanpy with pandas and pyarrow, its segmented cells by 10x's geopandas recipe, Xenium by 10x's scanpy recipe; scanpy's `rank_genes_groups` through h5ad to Zarr v2 and v3, Zarr to h5ad and a recompressed h5ad | | `test_performance.py` | Complexity guards -- what an operation costs, not how long it takes (see below); its fixtures are in `perf_fixtures.py` | | `test_benchmark_harness.py` | That the benchmark's measurement is trustworthy, and that each run compares with the release before it | -| `test_release_pipeline.py` | The workflows and the Dockerfile: which jobs publish in each kind of run, which hold a write token and what they run, pinned actions and base image, no untrusted value pasted into a script, each Python leg on its own Python | +| `test_release_pipeline.py` | The workflows and the Dockerfile: which jobs publish in each kind of run, and in which environment; a release tag on `main`, one release at a time, a timeout on every job; release notes that read as the changelog does, and Latest only for the newest release; the benchmark started after a release and its results on a branch; which jobs hold a write token and what they run, pinned actions and base image, no untrusted value pasted into a script, each Python leg on its own Python; Dependabot's config and `SECURITY.md` | | `test_docs_are_accurate.py` | The docs against the code: every `adata ...` line in the README, the site and the `--help` examples uses real commands and options; each command has a section in the reference; links resolve; every page has its front matter; every test file is in this table | | `test_subset_oracle.py` | `subset` and `split` against anndata's `adata[obs, var]`, element by element: X, every layer layout, obsm and varm of any rank and as dataframes, obsp, varp, raw; on HDF5, Zarr v2 and Zarr v3 | | `test_block_layout.py` | Outputs keep their source's chunks and shards and are written a whole unit at a time, and still equal anndata's own subsetting, on HDF5, Zarr v2, Zarr v3 and anndata 0.13's sharded layout under zarr 3.1, at blocks small enough to cross every boundary | @@ -470,7 +473,8 @@ dense block is `--chunk` x n_var. The benchmark exists to keep that curve visibl rather than to assert a claim the code does not yet meet. Results are published to [Benchmarks](benchmarks.md) and `docs/benchmarks/.json` -on every tag, and appended to the GitHub release notes if a release exists. +after every release, through a pull request from the branch the benchmark +pushes, and appended to the GitHub release notes. Artifacts expire; the docs page is the durable series. The "vs previous" column compares with the release just before, at the same tier; a run that is not a release compares with the newest one. diff --git a/tests/test_release_pipeline.py b/tests/test_release_pipeline.py index 3cc8182..50a9646 100644 --- a/tests/test_release_pipeline.py +++ b/tests/test_release_pipeline.py @@ -1,12 +1,13 @@ """The workflows test what they say, publish only what passed, and hold no token they do not need. -Three of the four workflows run only on a tag, so a mistake in them shows up -at a release and nowhere earlier. These tests read the workflow files and the -Dockerfile as GitHub and Docker would, and check the properties that matter -at the next tag: which jobs can publish in which run, which hold a write -token, and what each runs. The `workflows` job in tests.yml lints the same -files with actionlint and zizmor. +Three of the four workflows run only for a release, so a mistake in them +shows up at a release and nowhere earlier. These tests read the workflow +files, the Dockerfile and Dependabot's config as GitHub and Docker would, and +check the properties that matter at the next tag: which jobs can publish in +which run, which hold a write token, and what each runs. Their scripts run +here against real git repositories and stand-ins for `gh`. The `workflows` +job in tests.yml lints the same files with actionlint and zizmor. """ from __future__ import annotations @@ -18,8 +19,9 @@ import pytest # Not importorskip: a missing parser must fail these, not skip them. PyYAML -# comes with zarr (through donfig). +# comes with zarr (through donfig), and markdown-it-py with rich. import yaml +from markdown_it import MarkdownIt ROOT = Path(__file__).parents[1] WORKFLOWS = ROOT / ".github" / "workflows" @@ -142,18 +144,81 @@ def test_each_run_publishes_exactly_what_passed(event, ref, target, failing, pub assert results[job] == "failure", f"{job} must run, so the run goes red" +@pytest.mark.parametrize( + "event, target, failing, starts", + [ + ("push", None, (), True), + ("workflow_dispatch", "pypi", (), True), + ("workflow_dispatch", "testpypi", (), False), + ("push", None, ("check-version",), False), + ("push", None, ("test",), False), + ("push", None, ("publish-pypi",), False), + ("push", None, ("github-release",), False), + # PyPI and the release page have the version, so it is measured. + ("push", None, ("image",), True), + ], + ids=[ + "tag", "pypi-dispatch", "testpypi-dispatch", "tag-refused", "tests-fail", + "pypi-upload-fails", "release-fails", "image-fails", + ], +) +def test_the_benchmark_starts_only_once_the_release_is_out( + tmp_path, event, target, failing, starts +): + """F195: up to 0.17.10 every tag pushed started benchmark.yml, beside + publish.yml, and its results were committed to main even for a tag that + publish.yml refused. Now only publish.yml starts it, once PyPI has the + version and the release page exists, by a dispatch from the tag.""" + assert set(_load("benchmark.yml")["on"]) == {"workflow_dispatch"} + inputs = {"target": target} if target else {} + results = _run(_load("publish.yml"), event, TAG, inputs, failing) + assert (results["benchmark"] == "success") == starts + + # What the dispatch asks for, against what benchmark.yml takes: GitHub + # refuses a dispatch naming an input the workflow lacks, or a choice it + # does not offer, and by then PyPI has the release. + calls = tmp_path / "calls" + done = _bash( + _script("publish.yml", "benchmark", "start"), tmp_path, + PATH=_stand_in(tmp_path, "gh", 'printf "%s\\n" "$@" > "$CALLS"\n'), + CALLS=str(calls), TAG="0.17.5", + ) + assert done.returncode == 0, done.stderr + args = calls.read_text().splitlines() + assert args[:2] == ["workflow", "run"] and (WORKFLOWS / args[2]).is_file() + assert args[args.index("--ref") + 1] == "0.17.5" + fields = dict( + args[i + 1].split("=", 1) for i, arg in enumerate(args) if arg == "-f" + ) + declared = _load(args[2])["on"]["workflow_dispatch"]["inputs"] + assert set(fields) <= set(declared) + for name, value in fields.items(): + if declared[name]["type"] == "choice": + assert value in declared[name]["options"], name + if declared[name]["type"] == "boolean": + assert value in {"true", "false"}, name + assert fields == {"tier": "ci", "publish": "true"} + + def _script(workflow, job, step_id): steps = _load(workflow)["jobs"][job]["steps"] return next(step for step in steps if step.get("id") == step_id)["run"] +def _environ(): + """This process's environment, less what points git at a repository: + run from a git hook, GIT_DIR and GIT_INDEX_FILE would aim the tests' git + at the checkout running them.""" + return {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} + + def _bash(script, cwd, **env): """A `run:` script under GitHub's default shell, `bash -e`, with no pipefail.""" return subprocess.run( ["bash", "-e", "-c", script], cwd=cwd, - env={**os.environ, **env}, + env={**_environ(), **env}, capture_output=True, text=True, ) @@ -185,6 +250,86 @@ def test_check_version_passes_only_a_tag_that_names_the_version( assert output.read_text() == f"version={declared}\n" +#: git kept apart from the user's and the system's configuration (a signing +#: key, hooks), with an identity of its own. +GIT = { + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_AUTHOR_NAME": "adata-cli tests", + "GIT_AUTHOR_EMAIL": "tests@example.org", + "GIT_COMMITTER_NAME": "adata-cli tests", + "GIT_COMMITTER_EMAIL": "tests@example.org", +} + + +def _git(cwd, *args): + return subprocess.run( + ["git", *args], cwd=cwd, env={**_environ(), **GIT}, + check=True, capture_output=True, text=True, + ).stdout.strip() + + +def _release_history(repo): + """main is A, B. A release branch makes R off A; M merges it into main, + and S is what a squash merge would have put on main instead.""" + _git(repo, "init", "-q", "-b", "main") + _git(repo, "commit", "-q", "--allow-empty", "-m", "A") + a = _git(repo, "rev-parse", "HEAD") + _git(repo, "commit", "-q", "--allow-empty", "-m", "B") + b = _git(repo, "rev-parse", "HEAD") + _git(repo, "switch", "-q", "-c", "release/0.17.5", a) + (repo / "pyproject.toml").write_text('[project]\nversion = "0.17.5"\n') + _git(repo, "add", "pyproject.toml") + _git(repo, "commit", "-q", "-m", "Release 0.17.5") + r = _git(repo, "rev-parse", "HEAD") + tree = f"{r}^{{tree}}" + m = _git(repo, "commit-tree", tree, "-p", b, "-p", r, "-m", "Merge release/0.17.5") + s = _git(repo, "commit-tree", tree, "-p", b, "-m", "Release 0.17.5 (squashed)") + return {"A": a, "B": b, "R": r, "M": m, "S": s} + + +@pytest.mark.parametrize( + "tagged, main, decoy, ok", + [ + ("B", "B", None, True), + ("A", "B", None, True), + ("R", "M", None, True), + ("R", "B", None, False), + ("R", "S", None, False), + ("B", None, None, False), + # git reads a bare `origin/main` as this tag before the remote's main. + ("R", "B", "R", False), + ], + ids=[ + "main", "earlier-on-main", "merged-release-branch", "unmerged-release-branch", + "squash-merged-release-branch", "main-not-fetched", "tag-named-origin/main", + ], +) +def test_a_release_tag_must_be_on_main(tmp_path, tagged, main, decoy, ok): + """F193: release tags were not restricted to commits on main. The + repository's settings are the gate now; check-version adds the check + that the tagged commit is one main has, as git itself answers it, so a + tag pushed by mistake on an unmerged or squashed branch publishes + nothing.""" + job = _load("publish.yml")["jobs"]["check-version"] + checkout = next(s for s in job["steps"] if s.get("uses", "").startswith("actions/checkout@")) + assert checkout["with"]["fetch-depth"] == 0, "check-version needs main's history" + + commits = _release_history(tmp_path) + _git(tmp_path, "checkout", "-q", "--detach", commits[tagged]) + if main: + _git(tmp_path, "update-ref", "refs/remotes/origin/main", commits[main]) + if decoy: + _git(tmp_path, "tag", "origin/main", commits[decoy]) + done = _bash( + _script("publish.yml", "check-version", "on-main"), tmp_path, + GITHUB_REF_NAME="0.17.5", **GIT, + ) + assert (done.returncode == 0) == ok, done.stdout + done.stderr + if not ok: + assert "::error::" in done.stdout + + @pytest.mark.parametrize( "heading, ok", [ @@ -238,6 +383,94 @@ def test_the_real_changelog_gives_notes_for_its_newest_release(tmp_path): assert notes.strip() and "\n## " not in notes +def _rendered_on_the_site(markdown): + """As the changelog's page shows it: a newline inside a paragraph is a + space.""" + md = MarkdownIt("commonmark").enable("table") + md.add_render_rule("softbreak", lambda *args, **kwargs: " ") + return md.render(markdown) + + +def _rendered_on_github(markdown): + """As GitHub shows a release's notes: every newline inside a paragraph + is a line break.""" + return MarkdownIt("commonmark", {"breaks": True}).enable("table").render(markdown) + + +def _notes(tmp_path, changelog, tag): + """The changelog section, and the notes github-release makes of it.""" + (tmp_path / "docs").mkdir(exist_ok=True) + (tmp_path / "docs" / "changelog.md").write_text(changelog) + done = _bash(_script("publish.yml", "github-release", "notes"), tmp_path, TAG=tag) + assert done.returncode == 0, done.stdout + done.stderr + return (tmp_path / "section.md").read_text(), (tmp_path / "notes.md").read_text() + + +def test_the_release_notes_read_as_the_changelog_does(tmp_path): + """F197: GitHub shows each newline in a release's notes as a line break, + and the notes were the changelog's section as wrapped, so every release + page from 0.17.7 showed its paragraphs ragged. Every section of the real + changelog now gives notes that GitHub shows as the site shows the + section; markdown-it, set as each of them renders, is the oracle.""" + changelog = (ROOT / "docs" / "changelog.md").read_text() + tags = re.findall(r"^## (\S+)$", changelog, re.M) + assert len(tags) > 20 + for tag in tags: + section, notes = _notes(tmp_path, changelog, tag) + assert _rendered_on_github(notes) == _rendered_on_the_site(section), tag + + +#: One case for each way the notes step reads a line: what Markdown joins, +#: and what it keeps on a line of its own. +SECTIONS = { + "paragraph": "A paragraph wrapped\nacross three lines, as the\nchangelog wraps it.\n", + "heading-after-paragraph": "Text that\nwraps.\n### Fixed\n#\nA bare `#` is a heading too.\n", + "list": ( + "- **A lead** ([#1](https://example.org/1)). The text wraps, and the\n" + " command exited\n 0.\n" + " - A nested item that\n wraps too.\n" + "- An item that names\n #139 at the start of a line.\n" + "- Lazy\ncontinuation.\n" + ), + "numbered": "1. A numbered item\n that wraps.\n2. The next one.\n\nIn a paragraph\n2. is no list.\n", + "number-after-item": "- An item\n2. starts a numbered list\n", + "item-paragraph": "- An item\n\n with a second paragraph\n that wraps.\n2. And a list.\n", + "hard-breaks": "Breaks here\\\nand here \nbut a path ends C:\\\\\nand wraps.\n", + "rules": "Text\n\n---\n\n* * *\nafter\na rule.\n\n- - -\n\n_ _ _\n", + "setext": "A title\nthat wraps\n==\n\nAnother\n--\n", + "quote-table-links": ( + "> A quote.\n\n| a | b |\n|---|---|\n| 1 | 2 |\n\n" + "See [a] and\n[b].\n\n[a]: https://example.org/a\n[b]: https://example.org/b\n" + ), + "fences": ( + "```bash\nadata view a.h5ad\n~~~\nadata ls a.h5ad\n```\n\n" + "~~~\nkept\n```\nas is\n~~~\nA paragraph after\na fence.\n" + ), +} + + +@pytest.mark.parametrize("section", SECTIONS.values(), ids=SECTIONS.keys()) +def test_the_release_notes_keep_the_lines_markdown_keeps(tmp_path, section): + """F197: the notes must join only what Markdown joins. A heading, a + rule, a list item, a numbered item that starts a list, a quote, a table + row, a link definition, a fence's lines and a hard break keep their own + lines. A wrapped line that only looks like a list item (`0.`, or a + number other than 1 inside a paragraph) or a heading (`#139`) joins the + line before it. Each case runs on every awk CI runs the suite on.""" + section = "\n" + section + _, notes = _notes(tmp_path, f"# Changelog\n\n## 0.17.5\n{section}\n## 0.17.4\n", "0.17.5") + assert _rendered_on_github(notes) == _rendered_on_the_site(section + "\n") + + +def test_the_oracle_sees_ragged_notes(): + """F197: the section as it was published, wrapped lines and all, does + not render on GitHub as on the site; the check above would catch notes + that kept them.""" + section = SECTIONS["paragraph"] + assert "
" in _rendered_on_github(section) + assert _rendered_on_github(section) != _rendered_on_the_site(section) + + def test_the_image_is_pushed_only_from_publish(): """F143: quay-on-tag.yml ran on every tag by itself until 0.17.4.""" assert set(_load("quay-on-tag.yml")["on"]) == {"workflow_call"} @@ -246,18 +479,50 @@ def test_the_image_is_pushed_only_from_publish(): assert "inherit" not in str(image.get("secrets")), "pass Quay's secrets by name" +def test_every_job_that_publishes_runs_in_an_environment(): + """F193: the publishing environment was not restricted. Every job that + can publish now runs in an environment, which is where the repository's + settings restrict it (release tags only, and for PyPI the maintainer's + approval): PyPI's token comes only to a job in `pypi` or `testpypi`, and + Quay's secrets only to a job in `quay`.""" + jobs = { + (name, job_name): job + for name in _workflows() + for job_name, job in _load(name)["jobs"].items() + } + assert jobs["publish.yml", "publish-pypi"]["environment"] == "pypi" + assert jobs["publish.yml", "publish-testpypi"]["environment"] == "testpypi" + assert jobs["quay-on-tag.yml", "docker"]["environment"] == "quay" + for (name, job_name), job in jobs.items(): + if "uses" in job: + continue # its called workflow's jobs are checked here + if (job.get("permissions") or {}).get("id-token") == "write": + assert job.get("environment") in {"pypi", "testpypi"}, f"{name}: {job_name}" + if "secrets.QUAY_" in str(job): + assert job.get("environment") == "quay", f"{name}: {job_name}" + + +def _stand_in(tmp_path, name, body): + """A `name` on PATH, ahead of the real one, that runs this shell body.""" + bin_dir = tmp_path / "bin" + bin_dir.mkdir(exist_ok=True) + (bin_dir / name).write_text("#!/bin/sh\n" + body) + (bin_dir / name).chmod(0o755) + return f"{bin_dir}{os.pathsep}{os.environ['PATH']}" + + def _stand_in_git(tmp_path, tags, *, fails=False): """A `git` on PATH that answers `ls-remote --tags` with these tags.""" - bin_dir = tmp_path / "bin" - bin_dir.mkdir() listing = "".join(f"{'0' * 40}\trefs/tags/{tag}\n" for tag in tags) body = "exit 128\n" if fails else f"cat <<'EOF'\n{listing}EOF\n" - (bin_dir / "git").write_text("#!/bin/sh\n" + body) - (bin_dir / "git").chmod(0o755) - return f"{bin_dir}{os.pathsep}{os.environ['PATH']}" + return _stand_in(tmp_path, "git", body) -@pytest.mark.parametrize( +#: quay.io's :latest and GitHub's Latest are decided by the same test, each +#: in the job that acts on it. +LATEST_STEPS = [("quay-on-tag.yml", "docker"), ("publish.yml", "github-release")] + +LATEST_CASES = pytest.mark.parametrize( "version, tags, latest", [ ("0.17.5", ["0.9.0", "0.17.4", "0.17.5"], "true"), @@ -268,6 +533,9 @@ def _stand_in_git(tmp_path, tags, *, fails=False): ], ids=["newest", "by-number", "backport", "rc", "hyphenated-pre-release"], ) + + +@LATEST_CASES def test_latest_moves_only_to_the_newest_final_release(tmp_path, version, tags, latest): """F143: up to 0.17.4 :latest moved for any tag without a hyphen, so 1.0.0rc1, or a 0.16.x backport tagged after 0.17.0, would have taken it. @@ -286,13 +554,59 @@ def test_latest_moves_only_to_the_newest_final_release(tmp_path, version, tags, assert output.read_text() == f"latest={latest}\n" -def test_a_failed_tag_lookup_fails_the_image_job(tmp_path): +@LATEST_CASES +def test_a_release_is_marked_latest_only_when_it_is_the_newest( + tmp_path, version, tags, latest +): + """F198: `gh release create` marks a new release Latest unless told + otherwise, so a 0.16.x backport tagged after 0.17.0 would have become + GitHub's Latest release while quay.io's :latest stayed on 0.17. The + release now asks for Latest exactly when :latest would move: the same + test, run against a stand-in for `git ls-remote`, and what the release + step then asks of a stand-in `gh`.""" + assert _script("publish.yml", "github-release", "latest") == _script( + "quay-on-tag.yml", "docker", "latest" + ), "the two decisions must be the same test" + + output = tmp_path / "output" + done = _bash( + _script("publish.yml", "github-release", "latest"), tmp_path, + PATH=_stand_in_git(tmp_path, tags), VERSION=version, + GITHUB_OUTPUT=str(output), + ) + assert done.returncode == 0, done.stderr + assert output.read_text() == f"latest={latest}\n" + + # No release yet, so the step creates one, with what the step above put out. + calls = tmp_path / "calls" + gh = 'echo "$*" >> "$CALLS"\n[ "$1 $2" = "release view" ] && exit 1\nexit 0\n' + done = _bash( + _script("publish.yml", "github-release", "create"), tmp_path, + PATH=_stand_in(tmp_path, "gh", gh), CALLS=str(calls), + TAG=version, LATEST=output.read_text().strip().split("=")[1], + ) + assert done.returncode == 0, done.stderr + create = calls.read_text().splitlines()[-1] + assert create == ( + f"release create {version} --verify-tag --title {version} " + f"--notes-file notes.md --latest={latest}" + ) + step = next( + s for s in _load("publish.yml")["jobs"]["github-release"]["steps"] + if s.get("id") == "create" + ) + assert step["env"]["LATEST"] == "${{ steps.latest.outputs.latest }}" + + +@pytest.mark.parametrize("workflow, job", LATEST_STEPS, ids=["image", "release"]) +def test_a_failed_tag_lookup_fails_the_job(tmp_path, workflow, job): """F143: GitHub runs a `run:` script as `bash -e`, without pipefail, so a failed `git ls-remote` read as "no release is newer" and the job went on - to push with :latest left behind.""" + to push with :latest left behind. The release's step is the same test, + and fails the same way.""" output = tmp_path / "output" done = _bash( - _script("quay-on-tag.yml", "docker", "latest"), tmp_path, + _script(workflow, job, "latest"), tmp_path, PATH=_stand_in_git(tmp_path, [], fails=True), VERSION="0.17.5", GITHUB_OUTPUT=str(output), ) @@ -340,32 +654,107 @@ def test_the_lint_runs_on_pull_requests_and_not_inside_a_release(): @pytest.mark.parametrize( - "event, ref, publish, measured, commits", + "ref, publish, measured, pushes", [ - ("push", TAG, None, "true", True), - ("push", TAG, None, "", False), - ("workflow_dispatch", TAG, False, "true", False), - ("workflow_dispatch", TAG, True, "true", True), - ("workflow_dispatch", "refs/heads/main", True, "true", True), - ("workflow_dispatch", "refs/heads/main", False, "true", False), + # What publish.yml dispatches once a release is out. + (TAG, True, "true", True), + (TAG, True, "", False), + (TAG, False, "true", False), + ("refs/heads/main", True, "true", True), + ("refs/heads/main", False, "true", False), ], ids=[ - "tag", "tag-not-measured", "dispatch-from-tag", "dispatch-from-tag-publish", + "release", "release-not-measured", "dispatch-from-tag", "dispatch-from-branch-publish", "dispatch-from-branch", ], ) -def test_benchmark_results_are_committed_only_when_measured_and_asked_for( - event, ref, publish, measured, commits +def test_benchmark_results_are_pushed_only_when_measured_and_asked_for( + ref, publish, measured, pushes ): """F084, F085: the job that can push runs only after a measurement, and a dispatch from a tag that did not ask to publish no longer overwrites that release's results with another tier.""" - inputs = {"publish": publish} if publish is not None else {} results = _run( - _load("benchmark.yml"), event, ref, inputs, + _load("benchmark.yml"), "workflow_dispatch", ref, {"publish": publish}, outputs={"benchmark": {"measured": measured}}, ) - assert (results["publish"] == "success") == commits + assert (results["publish"] == "success") == pushes + + +#: `python3 -m benchmarks.report RESULTS --out FILE` writes the summary, and +#: `... --docs DIR --publish` the page and the run's raw numbers. +REPORT = """\ +case "$4" in + --out) echo "summary" > "$5" ;; + --docs) + mkdir -p "$5/reference" "$5/benchmarks" + cat "$3" > "$5/reference/benchmarks.md" + cp "$3" "$5/benchmarks/0.17.5.json" ;; +esac +""" + + +def test_benchmark_results_go_to_a_branch_for_a_pull_request(tmp_path): + """F195: up to 0.17.10 the benchmark committed its results to main + itself, unreviewed, with `[skip ci]`; the ruleset planned for main + refuses such a push, and a pull request from a `[skip ci]` commit gets + no checks. The step now pushes a branch off main, which a re-run + replaces, and links the pull request to open. git is the oracle for + what reached the remote.""" + origin = tmp_path / "origin.git" + seed = tmp_path / "seed" + seed.mkdir() + _git(seed, "init", "-q", "-b", "main") + _git(seed, "commit", "-q", "--allow-empty", "-m", "main") + _git(tmp_path, "clone", "-q", "--bare", str(seed), str(origin)) + main = _git(origin, "rev-parse", "refs/heads/main") + + for run, numbers in enumerate(["first run\n", "re-run\n"]): + checkout = tmp_path / f"checkout{run}" + _git(tmp_path, "clone", "-q", "--branch", "main", str(origin), str(checkout)) + results = tmp_path / "runner" / "results" / "results.json" + results.parent.mkdir(parents=True, exist_ok=True) + results.write_text(numbers) + summary = tmp_path / f"summary{run}.md" + done = _bash( + _script("benchmark.yml", "publish", "push"), checkout, + PATH=_stand_in(tmp_path, "python3", REPORT), + REF_NAME="0.17.5", RUNNER_TEMP=str(tmp_path / "runner"), + GITHUB_SERVER_URL="https://github.com", + GITHUB_REPOSITORY="cellgeni/adata-cli", + GITHUB_STEP_SUMMARY=str(summary), **GIT, + ) + assert done.returncode == 0, done.stdout + done.stderr + + assert _git(origin, "rev-parse", "refs/heads/main") == main, "main moved" + branch = "refs/heads/benchmark/0.17.5" + assert _git(origin, "rev-parse", f"{branch}^") == main + assert _git(origin, "show", f"{branch}:docs/benchmarks/0.17.5.json") == numbers.strip() + assert _git(origin, "log", "-1", "--format=%s", branch) == "Benchmark results for 0.17.5" + link = "https://github.com/cellgeni/adata-cli/compare/main...benchmark/0.17.5?expand=1" + assert link in summary.read_text() and link in done.stdout + + +def test_one_release_runs_at_a_time_and_none_is_cancelled(): + """F196: two tags pushed together ran two releases at once, which raced + to move quay.io's :latest and GitHub's Latest. publish.yml now has one + concurrency group for every run, whatever its ref, and never cancels a + run in progress: one stopped after PyPI has the version would leave it + with no image or release page.""" + concurrency = _load("publish.yml")["concurrency"] + assert "${{" not in concurrency["group"], "one group for every tag" + assert concurrency["cancel-in-progress"] is False + + +@pytest.mark.parametrize("name", _workflows()) +def test_every_job_has_a_timeout(name): + """F196: publish.yml's jobs had no timeout, so a hung step could hold a + release run, and the tokens it was given, for GitHub's default of six + hours. A job that calls a workflow takes no timeout of its own; the + called workflow's jobs are checked here too.""" + for job_name, job in _load(name)["jobs"].items(): + if "uses" not in job: + assert 0 < job.get("timeout-minutes", 0) <= 90, f"{name}: {job_name}" LEVELS = {"none": 0, "read": 1, "write": 2} @@ -510,3 +899,43 @@ def test_every_workflow_installs_the_same_uv(): versions.add(str((step.get("with") or {}).get("version"))) assert len(versions) == 1, versions assert re.fullmatch(r"\d+\.\d+\.\d+", versions.pop()) + + +def test_dependabot_watches_everything_this_repository_pins(): + """F194: nothing proposed updates to what the repository pins. The + actions are pinned by commit, so without Dependabot they never moved, + not even for an advisory, and neither did the lock or the image's base. + Each ecosystem is checked against the files Dependabot reads for it.""" + config = yaml.safe_load((ROOT / ".github" / "dependabot.yml").read_text()) + assert config["version"] == 2 + updates = {update["package-ecosystem"]: update for update in config["updates"]} + assert set(updates) == {"github-actions", "uv", "docker"} + assert all(update["directory"] == "/" for update in updates.values()) + for update in updates.values(): + assert update["schedule"]["interval"] in {"daily", "weekly", "monthly"} + assert update["cooldown"]["default-days"] >= 7 + + # github-actions reads .github/workflows, where every action is pinned + # by commit with its version in a comment, which Dependabot keeps. + assert _workflows() + # uv reads uv.lock, and moves only it: pyproject.toml's lower bounds + # are the floors that CI tests, and move by hand. + assert (ROOT / "uv.lock").is_file() + assert updates["uv"]["versioning-strategy"] == "lockfile-only" + # docker reads the Dockerfile, and moves a digest only with the tag that + # names its version. + base = re.findall(r"^FROM\s+(\S+)", (ROOT / "Dockerfile").read_text(), re.M) + assert base and all(re.fullmatch(r"[^@\s]+:[^@\s]+@sha256:[0-9a-f]{64}", b) for b in base) + + +def test_a_vulnerability_has_a_private_way_to_be_reported(): + """F194: there was no SECURITY.md, so whoever found a file that made + adata run its code had no private way to say so, and the obvious public + one. It points to GitHub's private vulnerability reporting for this + repository, the one pyproject.toml names.""" + policy = (ROOT / "SECURITY.md").read_text() + repository = re.search( + r'^Repository = "(.+)"$', (ROOT / "pyproject.toml").read_text(), re.M + )[1] + assert f"{repository}/security/advisories/new" in policy + assert f"{repository}/issues" not in policy