Repository navigation
[CI] rebuild a PR's docker image only when its build inputs change #2675
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 2 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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' | ||
| 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') }} | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] Read the live force-rebuild label instead of the triggering payload
|
||
| 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' | ||
|
|
@@ -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." | ||
| 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()) |
There was a problem hiding this comment.
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 == BASEearly exit. A source-only PR therefore depends on Docker Hub credentials and registry availability even though this job should selectdev; an authentication or registry outage can fail the GPU pipeline before the unchanged-input fast path runs. Please computeCURRENTandBASEfirst, then authenticate only when the workflow needs to inspect the existing PR image tag.