Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 78 additions & 20 deletions .github/workflows/_build-pr-ci-image.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,54 +6,103 @@ on:
built:
description: Whether this call built and pushed a PR-scoped image
value: ${{ jobs.docker-build.outputs.built }}
tag_available:
description: Whether a current PR-scoped image exists, built by this call or an earlier one
value: ${{ jobs.docker-build.outputs.tag_available }}

jobs:
docker-paths:
# A PR keeps one image tag (pr-<number>) for its whole life. Rebuilds are driven by
# the content of the build inputs, not by whether the PR happens to touch them: the
# published tag records its inputs hash in a label, so reruns and unrelated pushes
# reuse the image instead of paying for an identical build.
docker-decide:
if: github.event.action != 'closed'
runs-on: ubuntu-latest
outputs:
changed: ${{ steps.diff.outputs.changed }}
needs_image: ${{ steps.decide.outputs.needs_image }}
rebuild: ${{ steps.decide.outputs.rebuild }}
env:
SAME_REPO: ${{ github.event.pull_request.head.repo.full_name == github.repository }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 2
persist-credentials: false
- id: diff
# Reading the inputs label off the published tag needs registry auth. Forks get no
# secrets and cannot push anyway, so they skip straight to the released image.
- name: Login to Docker Hub
if: env.SAME_REPO == 'true'

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Defer Docker Hub login until an image is actually needed

This login now runs for every same-repository PR before the CURRENT == BASE early exit. A source-only PR therefore depends on Docker Hub credentials and registry availability even though this job should select dev; an authentication or registry outage can fail the GPU pipeline before the unchanged-input fast path runs. Please compute CURRENT and BASE first, then authenticate only when the workflow needs to inspect the existing PR image tag.

uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- id: decide
shell: bash
env:
BASE_SHA: ${{ github.event.pull_request.base.sha || '' }}
PR_NUMBER: ${{ github.event.pull_request.number || '' }}
FORCE_REBUILD: ${{ contains(github.event.pull_request.labels.*.name, 'rebuild-ci-image') }}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Read the live force-rebuild label instead of the triggering payload

github.event.pull_request.labels is frozen to the webhook payload for this workflow run. After a successful labeled run removes rebuild-ci-image, using Re-run all jobs creates another attempt of that same run, so this expression still evaluates true and rebuilds the full multi-arch image again. That breaks both the documented one-shot behavior and the rerun-reuse goal. Please query the current live labels for the PR at decision time. Gating only on github.run_attempt == 1 is not sufficient because a first attempt that failed before consuming the label must still rebuild on retry.

run: |
# Cron and manual runs have no PR diff and never build a PR image.
set -euo pipefail
emit() { echo "needs_image=$1" >> "$GITHUB_OUTPUT"; echo "rebuild=$2" >> "$GITHUB_OUTPUT"; }

# Cron and manual runs have no PR diff and never own a PR image.
if [ -z "$BASE_SHA" ]; then
echo "changed=false" >> "$GITHUB_OUTPUT"
emit false false
exit 0
fi
# Compare the PR merge commit with its current base (HEAD^1) rather than
# the recorded base.sha, which can lag main and pull in unrelated changes.
# Dockerfile.rocm doesn't feed the cu13 multi-arch build this pipeline produces.
if ! CHANGED_PATHS=$(git diff --name-only HEAD^1 HEAD); then
echo "::error::Failed to determine docker-relevant changes."
exit 1

# Compare the PR merge commit with its current base (HEAD^1) rather than the
# recorded base.sha, which can lag main and pull in unrelated changes.
CURRENT=$(python3 docker/image_inputs.py --rev HEAD)
BASE=$(python3 docker/image_inputs.py --rev HEAD^1)
if [ "$CURRENT" = "$BASE" ]; then
echo "Build inputs match the base branch; suites use the released image."
emit false false
exit 0
fi
if grep -qE '^(docker/(Dockerfile|build\.py|install-kube-tools\.sh|verify_transformer_engine\.py)|requirements\.txt)$|^docker/patch/' <<< "$CHANGED_PATHS"; then
echo "changed=true" >> "$GITHUB_OUTPUT"

if [ "$SAME_REPO" != "true" ]; then
echo "::notice::Fork PRs cannot publish an image; suites use the released image."
emit false false
exit 0
fi

if [ "$FORCE_REBUILD" = "true" ]; then
echo "::notice::rebuild-ci-image label present; forcing a rebuild."
emit true true
exit 0
fi

PUBLISHED=$(docker buildx imagetools inspect "radixark/miles:pr-${PR_NUMBER}" \
--format '{{ json .Image }}' 2>/dev/null \
| python3 docker/image_inputs.py --read-label || true)

if [ -z "$PUBLISHED" ]; then
echo "No usable pr-${PR_NUMBER} image; building one."
emit true true
elif [ "$PUBLISHED" = "$CURRENT" ]; then
echo "pr-${PR_NUMBER} already matches the current build inputs; reusing it."
emit true false
else
echo "changed=false" >> "$GITHUB_OUTPUT"
echo "Build inputs changed since pr-${PR_NUMBER} was published; rebuilding."
emit true true
fi

# Docker PRs build the multi-arch image after the caller's CPU gate passes.
# Without a relevant change this stays on a free hosted runner as a no-op;
# Without a rebuild to do this stays on a free hosted runner as a no-op;
# actual builds use docker-build nodes, never the GPU-suite pool.
docker-build:
needs: [docker-paths]
needs: [docker-decide]
if: always() && !cancelled() && github.event.action != 'closed'
runs-on: ${{ fromJSON((needs.docker-paths.outputs.changed == 'true' && github.event.pull_request.head.repo.full_name == github.repository) && '["docker-build"]' || '["ubuntu-latest"]') }}
runs-on: ${{ fromJSON(needs.docker-decide.outputs.rebuild == 'true' && '["docker-build"]' || '["ubuntu-latest"]') }}
timeout-minutes: 180
outputs:
built: ${{ steps.build.outputs.built || 'false' }}
# Reusing an image the previous run published is as good as building one now.
tag_available: ${{ needs.docker-decide.outputs.needs_image == 'true' && (steps.build.outputs.built == 'true' || needs.docker-decide.outputs.rebuild != 'true') }}
env:
# Forks cannot push to the registry, so they keep the released image.
BUILD: ${{ needs.docker-paths.outputs.changed == 'true' && github.event.pull_request.head.repo.full_name == github.repository }}
BUILD: ${{ needs.docker-decide.outputs.rebuild == 'true' }}
steps:
- name: Checkout repository
if: env.BUILD == 'true'
Expand Down Expand Up @@ -90,6 +139,15 @@ jobs:
python3 docker/build.py --variant cu13 --image-tag custom \
--custom-tag pr-${{ github.event.pull_request.number }} --push
echo "built=true" >> "$GITHUB_OUTPUT"
# The label is a one-shot request: leaving it on would rebuild on every later run.
- name: Consume rebuild-ci-image label
if: steps.build.outputs.built == 'true' && contains(github.event.pull_request.labels.*.name, 'rebuild-ci-image')
env:
GH_TOKEN: ${{ github.token }}
run: |
gh api -X DELETE \
"repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/labels/rebuild-ci-image" \
|| echo "::warning::Could not remove the rebuild-ci-image label; remove it by hand or every run will rebuild."
- name: Nothing to build
if: env.BUILD != 'true'
run: echo "No docker-relevant changes; suites use the released image."
run: echo "No rebuild needed; suites use the PR image if it exists, else the released one."
11 changes: 9 additions & 2 deletions .github/workflows/pr-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,11 @@ jobs:
needs.resolve-ci-policy.result == 'success' &&
(needs.stage-a-cpu.result == 'success' ||
needs.resolve-ci-policy.outputs.bypass_fastfail == 'true')
# Scoped to this call: a build consumes the one-shot rebuild-ci-image label by
# removing it. Every other job keeps the workflow-level read-only token.
permissions:
contents: read
pull-requests: write
uses: ./.github/workflows/_build-pr-ci-image.yml
secrets: inherit

Expand All @@ -143,11 +148,13 @@ jobs:
# workflow_call image_tag (a frozen release-CI tag) outranks the
# dispatch input, which only exists on manual runs anyway.
INPUT_CI_IMAGE_TAG: ${{ inputs.image_tag || github.event.inputs.ci_image_tag || '' }}
DOCKER_BUILT: ${{ needs.docker-build.outputs.built }}
# Not `built`: a run that reused an unchanged image published earlier must still
# test against that image rather than silently falling back to the released one.
PR_IMAGE_AVAILABLE: ${{ needs.docker-build.outputs.tag_available }}
PR_NUMBER: ${{ github.event.pull_request.number || '' }}
run: |
CI_IMAGE_TAG="${INPUT_CI_IMAGE_TAG}"
[ -z "$CI_IMAGE_TAG" ] && [ "$DOCKER_BUILT" = "true" ] && CI_IMAGE_TAG="pr-${PR_NUMBER}"
[ -z "$CI_IMAGE_TAG" ] && [ "$PR_IMAGE_AVAILABLE" = "true" ] && CI_IMAGE_TAG="pr-${PR_NUMBER}"
if [ -n "$PR_BODY" ]; then
PR_CI_IMAGE_TAG=$(echo "$PR_BODY" | grep -m1 -oP '^ci-image-tag:\s+\K\S+' || true)
[ -z "$CI_IMAGE_TAG" ] && [ -n "$PR_CI_IMAGE_TAG" ] && CI_IMAGE_TAG="$PR_CI_IMAGE_TAG"
Expand Down
4 changes: 4 additions & 0 deletions docker/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from enum import Enum
from pathlib import Path

import image_inputs
import typer

CACHE_DIR = "/tmp/miles-docker-cache"
Expand Down Expand Up @@ -157,6 +158,9 @@ def build_and_push(
assert "=" in spec, f"--build-arg expects KEY=VALUE, got {spec!r}"
cmd += ["--build-arg", spec]

# CI reads this back off the published tag to skip rebuilds whose inputs are unchanged.
cmd += ["--label", f"{image_inputs.LABEL_KEY}={image_inputs.compute()}"]

for tag in tags:
cmd += ["-t", tag]

Expand Down
117 changes: 117 additions & 0 deletions docker/image_inputs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
#!/usr/bin/env python3
# doc-dev: docs/ci/02-docker-build.md
"""Content hash of everything that feeds a Miles Docker image build.

Single source of truth for "what changes the image". CI compares this hash against
the one recorded on an already-published tag (label ``miles.image-inputs``) to decide
whether a rebuild is needed; ``build.py`` stamps the label at build time.

Stdlib only: CI computes the hash on a plain hosted runner before any dependency
is installed.

Usage:
python docker/image_inputs.py # hash the working tree
python docker/image_inputs.py --rev HEAD^1 # hash a git revision
"""

import argparse
import fnmatch
import hashlib
import json
import subprocess
import sys
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parent.parent

# A build reads exactly these. Anything outside them cannot change the image, so a
# PR touching only such files reuses the released image. Dockerfile.rocm is absent on
# purpose: it feeds pr-test-rocm.yml, not the cu13 multi-arch image built here.
INPUT_GLOBS = (
"docker/Dockerfile",
"docker/build.py",
"docker/install-kube-tools.sh",
"docker/verify_transformer_engine.py",
"docker/patch/*",
"requirements.txt",
)

LABEL_KEY = "miles.image-inputs"


def _matches(path: str) -> bool:
return any(fnmatch.fnmatch(path, glob) for glob in INPUT_GLOBS)


def _git(*args: str) -> bytes:
return subprocess.run(["git", *args], cwd=REPO_ROOT, check=True, stdout=subprocess.PIPE).stdout


def _paths_at(rev: str | None) -> list[str]:
if rev is None:
listing = _git("ls-files").decode()
else:
listing = _git("ls-tree", "-r", "--name-only", rev).decode()
return sorted(p for p in listing.splitlines() if _matches(p))


def _content_at(path: str, rev: str | None) -> bytes:
if rev is None:
return (REPO_ROOT / path).read_bytes()
return _git("show", f"{rev}:{path}")


def compute(rev: str | None = None) -> str:
"""Hash the build inputs in the working tree (``rev=None``) or at a revision."""
digest = hashlib.sha256()
for path in _paths_at(rev):
digest.update(path.encode())
digest.update(b"\0")
digest.update(hashlib.sha256(_content_at(path, rev)).digest())
return digest.hexdigest()


def read_label(manifest: str) -> str:
"""Pull the recorded hash out of ``docker buildx imagetools inspect`` JSON.

The shape differs between single- and multi-platform tags, so search rather than
index; an unpublished tag yields empty input and no hash.
"""

def search(node: object) -> str:
if isinstance(node, dict):
for key, value in node.items():
if key == LABEL_KEY and isinstance(value, str):
return value
if found := search(value):
return found
elif isinstance(node, list):
for item in node:
if found := search(item):
return found
return ""

manifest = manifest.strip()
if not manifest:
return ""
try:
return search(json.loads(manifest))
except json.JSONDecodeError:
return ""


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--rev", default=None, help="Git revision to hash (default: working tree).")
parser.add_argument(
"--read-label",
action="store_true",
help="Read imagetools inspect JSON on stdin and print the hash it recorded.",
)
args = parser.parse_args()
print(read_label(sys.stdin.read()) if args.read_label else compute(args.rev))
return 0


if __name__ == "__main__":
sys.exit(main())
1 change: 1 addition & 0 deletions docs/ci/01-label.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ A label is a GitHub PR label that changes what CI runs or how it fails. Three ki
| Cadence/scope label | `nightly` | select nightly cadence and every enabled tag except `long` and `ft-long`, with fast-fail disabled |
| Scope label | `run-ci-all` | run every enabled tag |
| Behavior label | `bypass-fastfail` | opt out of fast-fail; one run surfaces every failure |
| Behavior label | `rebuild-ci-image` | rebuild this PR's image even though its inputs are unchanged; removed once consumed (see [Docker build](/ci/02-docker-build)) |

Only domain labels are declared in `labels=[...]`; scope and behavior labels are workflow inputs resolved by `tests/ci/ci_policy.py`. The separate `nightly=True` registration field is a cadence gate described below.

Expand Down
13 changes: 9 additions & 4 deletions docs/ci/02-docker-build.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,20 @@ A multi-arch build (`cu13`) needs Buildx's `docker-container` driver and is push

Dockerfile changes are build-tested on the PR itself, before merge — `docker-build.yml` only runs after a push to `main`, so without this breakage lands on `main` first.

`pr-test.yml` calls `_build-pr-ci-image.yml` after `stage-a-cpu` satisfies its success/bypass gate, while both CPU stages run without waiting for it. The reusable workflow owns `docker-paths` and `docker-build`; for changes to `docker/Dockerfile`, `docker/build.py`, `docker/install-kube-tools.sh`, `docker/verify_transformer_engine.py`, `docker/patch/**`, or `requirements.txt`, it inserts a build before the GPU matrix:
`pr-test.yml` calls `_build-pr-ci-image.yml` after `stage-a-cpu` satisfies its success/bypass gate, while both CPU stages run without waiting for it. A PR keeps **one** image tag, `radixark/miles:pr-<num>`, for its whole life, and rebuilds it only when the content that feeds it changes:

| Job | What it does |
| --- | --- |
| `docker-build` | builds `cu13` for `linux/amd64` and `linux/arm64`, then pushes one multi-arch PR-scoped `radixark/miles:pr-<num>` tag (same-repo PRs; fork PRs skip it and test on `dev`) |
| `resolve-ci-image` | waits for the build and resolves the CI image to `pr-<num>`, so **every GPU suite runs inside the freshly built image**; a failed build stops the matrix instead of testing the stale image. The fresh build outranks a `ci-image-tag:` PR-body directive — the directive applies only when no PR image was built (non-docker or fork PRs) |
| `docker-decide` | hashes the build inputs (`docker/image_inputs.py`) and compares. Inputs equal to the base branch → no PR image, suites run on `dev`. Otherwise it reads the `miles.image-inputs` label off the published `pr-<num>` tag: same hash → reuse it, different or absent → rebuild. Fork PRs cannot publish, so they always test on `dev` |
| `docker-build` | builds `cu13` for `linux/amd64` and `linux/arm64` and pushes `pr-<num>`, stamped with the inputs hash. Runs on a `docker-build` node only when a rebuild is due; otherwise it is a hosted-runner no-op |
| `resolve-ci-image` | resolves the CI image to `pr-<num>` whenever that tag is current — whether this run built it or an earlier one did — so **every GPU suite runs inside the PR's image**; a failed build stops the matrix instead of testing a stale image. A PR image outranks a `ci-image-tag:` PR-body directive, which applies only when the PR has no image (non-docker or fork PRs) |
| `delete-pr-tag` (`docker-pr-tag-cleanup.yml`) | removes the `pr-<num>` tag when the PR closes; the tag stays available for re-runs while the PR is open |

Non-docker PRs are untouched: `docker-paths` reports no change, `docker-build` skips, and the matrix runs on `dev` as before.
So a rerun, or a push that touches only source files, reuses the image the PR already has instead of rebuilding an identical one. Non-docker PRs are untouched: no PR image, matrix on `dev`, as before.

`docker/image_inputs.py` is the single source of truth for what counts as an input (`docker/Dockerfile`, `docker/build.py`, `docker/install-kube-tools.sh`, `docker/verify_transformer_engine.py`, `docker/patch/**`, `requirements.txt`). `Dockerfile.rocm` is deliberately excluded — it feeds `pr-test-rocm.yml`, not the `cu13` image built here.

To rebuild when the inputs did not change — a moved base image, a floating dependency, a corrupt push — add the **`rebuild-ci-image`** label. Applying it starts a run that rebuilds and then removes the label, so it acts once rather than forcing a rebuild on every later run.

## Rolling Docker build (`docker-build.yml`)

Expand Down
12 changes: 7 additions & 5 deletions tests/ci/test/test_run_suite.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ def test_cpu_and_gpu_stages_use_dedicated_reusable_workflows(self):
docker_jobs = re.findall(job_id_pattern, docker_workflow.split("\njobs:\n", 1)[1], re.MULTILINE)
assert gpu_jobs == ["run"]
assert cpu_jobs == ["run-cpu"]
assert docker_jobs == ["docker-paths", "docker-build"]
assert docker_jobs == ["docker-decide", "docker-build"]
assert "cpu_runner" not in gpu_workflow
assert "cpu_runner" not in cpu_workflow

Expand All @@ -326,11 +326,13 @@ def test_docker_build_body_lives_in_reusable_workflow(self):
workflow = self._workflow()
reusable = self._reusable_workflow("_build-pr-ci-image.yml")

assert " docker-paths:" not in workflow
assert " docker-decide:" not in workflow
assert "value: ${{ jobs.docker-build.outputs.built }}" in reusable
assert "needs: [docker-paths]" in reusable
assert "if ! CHANGED_PATHS=$(git diff --name-only HEAD^1 HEAD); then" in reusable
assert "::error::Failed to determine docker-relevant changes." in reusable
assert "value: ${{ jobs.docker-build.outputs.tag_available }}" in reusable
assert "needs: [docker-decide]" in reusable
# Rebuilds follow the build inputs, not whether the PR diff touched them.
assert "python3 docker/image_inputs.py --rev HEAD^1" in reusable
assert "python3 docker/image_inputs.py --read-label" in reusable
assert "github.event.pull_request.head.repo.full_name == github.repository" in reusable
assert "python3 docker/build.py --variant cu13 --image-tag custom" in reusable

Expand Down
Loading
Loading