This is an automated email from the ASF dual-hosted git repository.

potiuk pushed a commit to branch ci-image-keyed-cache
in repository https://gitbox.apache.org/repos/asf/airflow.git

commit 99e4a1186860f870412c9926ae2ae7f072b13964
Author: Jarek Potiuk <[email protected]>
AuthorDate: Sun Nov 15 15:31:10 2026 +0900

    Keep the CI image cache usable right after dependency changes
    
    The registry cache of main is refreshed only by the canary, twice a
    day, under a single moving tag. After a dependency upgrade merges,
    every local breeze build reinstalls all dependencies from scratch for up
    to half a day, and a checkout of any other commit, branch or worktree
    whose dependency inputs differ from the latest canary never hits the
    cache at all.
    
    Tagging the cache with a key of the dependency inputs lets any checkout
    find the cache of its own inputs, and pushing that key from same-repo
    pull requests and right after a dependency change merges means the
    cache is in place before anyone needs it. The keyed tags and the
    untagged versions every push leaves behind need cleaning up, slowly
    enough to stay within the workflow token's API limits.
    
    Generated-by: Claude Opus 5
    Claude-Session: https://claude.ai/code/session_01NyQq9U7i5HhjDgrQ9qd3gq
---
 .github/workflows/ci-amd.yml                       |  45 +++++
 .github/workflows/ci-arm.yml                       |  45 +++++
 .github/workflows/cleanup-keyed-image-cache.yml    |  54 ++++++
 .github/workflows/cleanup-old-image-versions.yml   |  63 +++++++
 .github/workflows/push-image-cache.yml             |   7 +
 .../refresh-image-cache-on-dependency-change.yml   |  48 +++++
 .github/workflows/refresh-image-registry-cache.yml |   8 +
 dev/breeze/doc/ci/01_ci_environment.md             |  32 ++++
 dev/breeze/doc/ci/04_selective_checks.md           |   1 +
 dev/breeze/doc/ci/05_workflows.md                  |   4 +
 dev/breeze/doc/images/output_ci-image_build.svg    |  36 ++--
 dev/breeze/doc/images/output_ci-image_build.txt    |   2 +-
 .../airflow_breeze/commands/ci_image_commands.py   |  11 +-
 .../commands/ci_image_commands_config.py           |   1 +
 .../commands/common_image_options.py               |   7 +
 .../commands/production_image_commands.py          |   2 +-
 dev/breeze/src/airflow_breeze/global_constants.py  |   4 +
 .../src/airflow_breeze/params/build_ci_params.py   |   7 +
 .../airflow_breeze/params/common_build_params.py   |   8 +
 .../airflow_breeze/utils/docker_command_utils.py   |  68 ++++++-
 .../src/airflow_breeze/utils/md5_build_check.py    |  29 +++
 .../src/airflow_breeze/utils/selective_checks.py   |  14 ++
 dev/breeze/tests/test_build_ci_params.py           |  30 +++
 dev/breeze/tests/test_ci_image_commands.py         |  47 ++++-
 dev/breeze/tests/test_docker_command_utils.py      | 128 +++++++++++++
 dev/breeze/tests/test_selective_checks.py          |  27 +++
 scripts/ci/cleanup_keyed_image_cache.py            | 139 ++++++++++++++
 scripts/ci/cleanup_old_image_versions.py           | 201 +++++++++++++++++++++
 scripts/tests/ci/test_cleanup_keyed_image_cache.py | 106 +++++++++++
 .../tests/ci/test_cleanup_old_image_versions.py    | 119 ++++++++++++
 30 files changed, 1271 insertions(+), 22 deletions(-)

diff --git a/.github/workflows/ci-amd.yml b/.github/workflows/ci-amd.yml
index 33ff3aff9ab..2584151dec4 100644
--- a/.github/workflows/ci-amd.yml
+++ b/.github/workflows/ci-amd.yml
@@ -277,7 +277,9 @@ jobs:
       arm-runners: ${{ steps.selective-checks.outputs.arm-runners }}
       basic-checks-only: ${{ steps.selective-checks.outputs.basic-checks-only 
}}
       canary-run: ${{ steps.source-run-info.outputs.canary-run }}
+      all-python-versions: ${{ 
steps.selective-checks.outputs.all-python-versions }}
       ci-image-build: ${{ steps.selective-checks.outputs.ci-image-build }}
+      ci-image-dependencies-changed: ${{ 
steps.selective-checks.outputs.ci-image-dependencies-changed }}
       core-test-types-list-as-strings-in-json: >-
         ${{ 
steps.selective-checks.outputs.core-test-types-list-as-strings-in-json }}
       debug-resources: ${{ steps.selective-checks.outputs.debug-resources }}
@@ -549,6 +551,47 @@ jobs:
       disable-airflow-repo-cache: ${{ 
needs.build-info.outputs.disable-airflow-repo-cache }}
     if: needs.build-info.outputs.ci-image-build == 'true'
 
+  push-keyed-image-cache:
+    # A pull request from a branch of apache/airflow that changes the inputs 
of the CI image's
+    # dependency layers pushes the cache for them under its dependency key, so 
the cache is in the
+    # registry by the time the change merges and `breeze ci-image build` finds 
it for any checkout
+    # with the same inputs. Built without upgrading dependencies, as on main 
after the merge, and
+    # skipped when the key is already pushed. It never moves the shared cache 
or `latest` tags.
+    name: "Push keyed image cache ${{ matrix.platform }}"
+    needs: [build-info]
+    strategy:
+      fail-fast: false
+      matrix:
+        include:
+          - platform: "linux/amd64"
+            runners: '["ubuntu-22.04"]'
+          - platform: "linux/arm64"
+            runners: '["ubuntu-22.04-arm"]'
+    uses: ./.github/workflows/push-image-cache.yml
+    permissions:
+      contents: read
+      # Granted only for pull requests whose head is in apache/airflow; fork 
pull requests never run it.
+      packages: write
+    with:
+      runners: ${{ matrix.runners }}
+      platform: ${{ matrix.platform }}
+      cache-type: "Keyed"
+      include-prod-images: "false"
+      push-latest-images: "false"
+      keyed-cache-only: "true"
+      python-versions: ${{ needs.build-info.outputs.all-python-versions }}
+      branch: ${{ needs.build-info.outputs.default-branch }}
+      constraints-branch: ${{ 
needs.build-info.outputs.default-constraints-branch }}
+      use-uv: ${{ needs.build-info.outputs.use-uv }}
+      include-success-outputs: ${{ 
needs.build-info.outputs.include-success-outputs }}
+      docker-cache: ${{ needs.build-info.outputs.docker-cache }}
+      disable-airflow-repo-cache: ${{ 
needs.build-info.outputs.disable-airflow-repo-cache }}
+    if: >-
+      github.event_name == 'pull_request' &&
+      github.repository == 'apache/airflow' &&
+      github.event.pull_request.head.repo.full_name == 'apache/airflow' &&
+      needs.build-info.outputs.ci-image-dependencies-changed == 'true'
+
   additional-ci-image-checks:
     name: "Additional CI image checks"
     needs: [build-info, build-ci-images]
@@ -1655,6 +1698,7 @@ jobs:
       - migration-round-trip
       - mypy-providers
       - providers
+      - push-keyed-image-cache
       - tests-agent-frameworks
       - tests-airflow-ctl
       - tests-go-sdk
@@ -1724,6 +1768,7 @@ jobs:
       - migration-round-trip
       - mypy-providers
       - providers
+      - push-keyed-image-cache
       - tests-agent-frameworks
       - tests-airflow-ctl
       - tests-go-sdk
diff --git a/.github/workflows/ci-arm.yml b/.github/workflows/ci-arm.yml
index d719834a287..ccb40c5c6e4 100644
--- a/.github/workflows/ci-arm.yml
+++ b/.github/workflows/ci-arm.yml
@@ -153,7 +153,9 @@ jobs:
       arm-runners: ${{ steps.selective-checks.outputs.arm-runners }}
       basic-checks-only: ${{ steps.selective-checks.outputs.basic-checks-only 
}}
       canary-run: ${{ steps.source-run-info.outputs.canary-run }}
+      all-python-versions: ${{ 
steps.selective-checks.outputs.all-python-versions }}
       ci-image-build: ${{ steps.selective-checks.outputs.ci-image-build }}
+      ci-image-dependencies-changed: ${{ 
steps.selective-checks.outputs.ci-image-dependencies-changed }}
       core-test-types-list-as-strings-in-json: >-
         ${{ 
steps.selective-checks.outputs.core-test-types-list-as-strings-in-json }}
       debug-resources: ${{ steps.selective-checks.outputs.debug-resources }}
@@ -425,6 +427,47 @@ jobs:
       disable-airflow-repo-cache: ${{ 
needs.build-info.outputs.disable-airflow-repo-cache }}
     if: needs.build-info.outputs.ci-image-build == 'true'
 
+  push-keyed-image-cache:
+    # A pull request from a branch of apache/airflow that changes the inputs 
of the CI image's
+    # dependency layers pushes the cache for them under its dependency key, so 
the cache is in the
+    # registry by the time the change merges and `breeze ci-image build` finds 
it for any checkout
+    # with the same inputs. Built without upgrading dependencies, as on main 
after the merge, and
+    # skipped when the key is already pushed. It never moves the shared cache 
or `latest` tags.
+    name: "Push keyed image cache ${{ matrix.platform }}"
+    needs: [build-info]
+    strategy:
+      fail-fast: false
+      matrix:
+        include:
+          - platform: "linux/amd64"
+            runners: '["ubuntu-22.04"]'
+          - platform: "linux/arm64"
+            runners: '["ubuntu-22.04-arm"]'
+    uses: ./.github/workflows/push-image-cache.yml
+    permissions:
+      contents: read
+      # Granted only for pull requests whose head is in apache/airflow; fork 
pull requests never run it.
+      packages: write
+    with:
+      runners: ${{ matrix.runners }}
+      platform: ${{ matrix.platform }}
+      cache-type: "Keyed"
+      include-prod-images: "false"
+      push-latest-images: "false"
+      keyed-cache-only: "true"
+      python-versions: ${{ needs.build-info.outputs.all-python-versions }}
+      branch: ${{ needs.build-info.outputs.default-branch }}
+      constraints-branch: ${{ 
needs.build-info.outputs.default-constraints-branch }}
+      use-uv: ${{ needs.build-info.outputs.use-uv }}
+      include-success-outputs: ${{ 
needs.build-info.outputs.include-success-outputs }}
+      docker-cache: ${{ needs.build-info.outputs.docker-cache }}
+      disable-airflow-repo-cache: ${{ 
needs.build-info.outputs.disable-airflow-repo-cache }}
+    if: >-
+      github.event_name == 'pull_request' &&
+      github.repository == 'apache/airflow' &&
+      github.event.pull_request.head.repo.full_name == 'apache/airflow' &&
+      needs.build-info.outputs.ci-image-dependencies-changed == 'true'
+
   additional-ci-image-checks:
     name: "Additional CI image checks"
     needs: [build-info, build-ci-images]
@@ -1530,6 +1573,7 @@ jobs:
       - migration-round-trip
       - mypy-providers
       - providers
+      - push-keyed-image-cache
       - tests-agent-frameworks
       - tests-airflow-ctl
       - tests-go-sdk
@@ -1598,6 +1642,7 @@ jobs:
       - migration-round-trip
       - mypy-providers
       - providers
+      - push-keyed-image-cache
       - tests-agent-frameworks
       - tests-airflow-ctl
       - tests-go-sdk
diff --git a/.github/workflows/cleanup-keyed-image-cache.yml 
b/.github/workflows/cleanup-keyed-image-cache.yml
new file mode 100644
index 00000000000..37aeaee99d7
--- /dev/null
+++ b/.github/workflows/cleanup-keyed-image-cache.yml
@@ -0,0 +1,54 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+---
+name: Clean up keyed image cache
+# Deletes the keyed CI image cache tags (`cache-<platform>-<dependency key>`) 
not pushed for 30 days.
+# See scripts/ci/cleanup_keyed_image_cache.py.
+on:  # yamllint disable-line rule:truthy
+  schedule:
+    - cron: '17 4 * * *'
+  workflow_dispatch:
+    inputs:
+      dry-run:
+        description: "Only list what would be deleted"
+        type: boolean
+        default: true
+permissions:
+  contents: read
+concurrency:
+  group: cleanup-keyed-image-cache
+  cancel-in-progress: false
+jobs:
+  cleanup:
+    name: "Clean up keyed image cache"
+    runs-on: ["ubuntu-slim"]
+    permissions:
+      contents: read
+      packages: write
+    if: github.repository == 'apache/airflow'
+    steps:
+      - name: "Checkout ${{ github.ref }} ( ${{ github.sha }} )"
+        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1  # 
v7.0.1
+        with:
+          persist-credentials: false
+      - name: "Delete keyed cache older than 30 days"
+        env:
+          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+          GITHUB_REPOSITORY: ${{ github.repository }}
+          DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && 
inputs.dry-run && '--dry-run' || '' }}
+        run: python3 scripts/ci/cleanup_keyed_image_cache.py --days 30 
${DRY_RUN}
diff --git a/.github/workflows/cleanup-old-image-versions.yml 
b/.github/workflows/cleanup-old-image-versions.yml
new file mode 100644
index 00000000000..74a2de5bcfa
--- /dev/null
+++ b/.github/workflows/cleanup-old-image-versions.yml
@@ -0,0 +1,63 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+---
+name: Clean up old image versions
+# Deletes, a few hundred per run, the untagged CI and PROD image versions 
older than 30 days that
+# no tagged image references. Small, spaced-out runs keep it far below the API 
rate limit of the
+# workflow token. See scripts/ci/cleanup_old_image_versions.py.
+on:  # yamllint disable-line rule:truthy
+  schedule:
+    - cron: '41 */3 * * *'
+  workflow_dispatch:
+    inputs:
+      dry-run:
+        description: "Only list what would be deleted"
+        type: boolean
+        default: true
+      max-deletions:
+        description: "Stop after this many deletions"
+        type: string
+        default: "300"
+permissions:
+  contents: read
+concurrency:
+  group: cleanup-old-image-versions
+  cancel-in-progress: false
+jobs:
+  cleanup:
+    name: "Clean up old image versions"
+    runs-on: ["ubuntu-slim"]
+    timeout-minutes: 30
+    permissions:
+      contents: read
+      packages: write
+    if: github.repository == 'apache/airflow'
+    steps:
+      - name: "Checkout ${{ github.ref }} ( ${{ github.sha }} )"
+        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1  # 
v7.0.1
+        with:
+          persist-credentials: false
+      - name: "Delete old untagged image versions"
+        env:
+          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+          GITHUB_REPOSITORY: ${{ github.repository }}
+          DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && 
inputs.dry-run && '--dry-run' || '' }}
+          MAX_DELETIONS: ${{ inputs.max-deletions || '300' }}
+        run: >
+          python3 scripts/ci/cleanup_old_image_versions.py
+          --days 30 --max-deletions "${MAX_DELETIONS}" --pause 1 ${DRY_RUN}
diff --git a/.github/workflows/push-image-cache.yml 
b/.github/workflows/push-image-cache.yml
index 8fdb06f95ce..8a708d13256 100644
--- a/.github/workflows/push-image-cache.yml
+++ b/.github/workflows/push-image-cache.yml
@@ -36,6 +36,12 @@ on:  # yamllint disable-line rule:truthy
         description: "Whether to also push latest images (true/false)."
         required: true
         type: string
+      keyed-cache-only:
+        description: >-
+          Push only the CI cache tagged with the dependency key of the 
checkout, skipped when the
+          registry already has it, and leave the shared cache tag alone 
(true/false).
+        type: string
+        default: "false"
       debian-version:
         description: "Base Debian distribution to use for the PROD image build 
(trixie/bookworm)"
         type: string
@@ -106,6 +112,7 @@ jobs:
       GITHUB_USERNAME: ${{ github.actor }}
       INCLUDE_SUCCESS_OUTPUTS: "${{ inputs.include-success-outputs }}"
       INSTALL_MYSQL_CLIENT_TYPE: ${{ inputs.install-mysql-client-type }}
+      KEYED_CACHE_ONLY: ${{ inputs.keyed-cache-only }}
       PYTHON_MAJOR_MINOR_VERSION: "${{ matrix.python }}"
       UPGRADE_TO_NEWER_DEPENDENCIES: "false"
       VERBOSE: "true"
diff --git a/.github/workflows/refresh-image-cache-on-dependency-change.yml 
b/.github/workflows/refresh-image-cache-on-dependency-change.yml
new file mode 100644
index 00000000000..eab866a0c2f
--- /dev/null
+++ b/.github/workflows/refresh-image-cache-on-dependency-change.yml
@@ -0,0 +1,48 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+---
+name: Refresh image cache on dependency change
+# `main` is not built on push -- its registry cache is otherwise refreshed 
only by the canary, twice
+# a day. A merged change to the inputs of the CI image's dependency layers (a 
dependency upgrade,
+# most often) would leave every local `breeze ci-image build` installing all 
dependencies from
+# scratch until then. This refreshes the shared and the keyed cache right 
after such a merge.
+# The paths are the `CI_IMAGE_DEPENDENCY_FILES` group of selective checks.
+on:  # yamllint disable-line rule:truthy
+  push:
+    branches:
+      - main
+    paths:
+      - "uv.lock"
+      - "**/pyproject.toml"
+      - "Dockerfile.ci"
+      - ".dockerignore"
+      - "scripts/docker/**"
+      - "dev/breeze/src/airflow_breeze/files/hardened_*_digests.json"
+permissions:
+  contents: read
+jobs:
+  refresh-image-cache:
+    name: "Refresh image cache"
+    uses: ./.github/workflows/refresh-image-registry-cache.yml
+    permissions:
+      contents: read
+      # Only granted for pushes to apache/airflow's `main`, never for forks.
+      packages: write
+    with:
+      platform: "both"
+    if: github.repository == 'apache/airflow'
diff --git a/.github/workflows/refresh-image-registry-cache.yml 
b/.github/workflows/refresh-image-registry-cache.yml
index 2eb1821f474..8b3bf3d8127 100644
--- a/.github/workflows/refresh-image-registry-cache.yml
+++ b/.github/workflows/refresh-image-registry-cache.yml
@@ -30,6 +30,14 @@ name: Refresh image registry cache
 # Every Python version is refreshed in both trigger paths. That is what makes 
the cache useful:
 # a version with no cache entry builds from scratch on every run, whichever 
way it got skipped.
 on:  # yamllint disable-line rule:truthy
+  # `refresh-image-cache-on-dependency-change.yml` calls it on the pushes to 
`main` that change the
+  # inputs of the dependency layers, so a merged dependency upgrade does not 
wait for the next canary.
+  workflow_call:
+    inputs:
+      platform:
+        description: "Platform to refresh the cache for"
+        type: string
+        default: "both"
   workflow_dispatch:
     inputs:
       platform:
diff --git a/dev/breeze/doc/ci/01_ci_environment.md 
b/dev/breeze/doc/ci/01_ci_environment.md
index c785018dbd5..3e789ee975d 100644
--- a/dev/breeze/doc/ci/01_ci_environment.md
+++ b/dev/breeze/doc/ci/01_ci_environment.md
@@ -79,6 +79,37 @@ The latest GitHub registry cache is kept as 
`:cache-linux-amd64` and
 metadata and cache for all segments in the image,
 and cache is kept separately for different platforms.
 
+Next to it, every cache push also writes a keyed tag,
+`:cache-linux-<arch>-<dependency key>`. The key is a hash of the inputs of the
+image's expensive dependency layers: `uv.lock`, every `pyproject.toml`,
+`Dockerfile.ci` and the scripts it runs. `breeze ci-image build` computes the
+key of the checkout it runs in and passes `--cache-from` for the keyed tag
+first and the shared tag second. A checkout whose inputs were ever pushed,
+an older commit or a release-branch worktree included, so gets a full cache
+hit even after the shared tag has moved on. The key only names the cache to
+look up: BuildKit still checks every layer, so a stale or wrong key costs a
+cache miss, never a wrong layer.
+
+Keyed cache is pushed:
+
+* by every cache push (the canary, `refresh-image-registry-cache.yml`) - with 
the shared tag,
+* by `refresh-image-cache-on-dependency-change.yml`, right after a push to 
`main` that changes
+  the dependency inputs, so a merged dependency upgrade does not leave 
everyone building
+  dependencies from scratch until the next canary,
+* by the `push-keyed-image-cache` job of a pull request from a branch of 
`apache/airflow` that
+  changes the dependency inputs (for example the automated CI environment 
upgrade), with
+  `breeze ci-image build --prepare-buildx-cache --keyed-cache-only`. It builds 
without
+  upgrading dependencies, as `main` will after the merge, skips a key already 
in the registry,
+  and never moves the shared cache or `latest` tags. Pull requests from forks 
never push.
+
+`cleanup-keyed-image-cache.yml` deletes keyed tags not pushed for 30 days.
+`cleanup-old-image-versions.yml` slowly deletes, a few hundred per run, the 
untagged
+image versions older than 30 days that every push leaves behind, keeping the
+manifests that tagged images list.
+
+Pushing two caches in one build needs BuildKit 0.11, so `breeze` refuses to 
build
+an image with docker buildx older than 0.10.
+
 The `latest` images of CI and PROD are `amd64` only images for CI,
 because there is no easy way to push multiplatform images without
 merging the manifests, and it is not really needed nor used for cache.
@@ -91,6 +122,7 @@ When you are running the CI jobs in GitHub Actions, 
GITHUB_TOKEN is set automati
 by the actions. This is used only in the `canary` runs that have "write" access
 to the repository.
 
+The same token pushes the keyed cache of pull requests from `apache/airflow` 
branches.
 No `write` access is needed (nor possible) by Pull Requests coming from the 
forks,
 since we are only using "GitHub Artifacts" for cache source in those runs.
 
diff --git a/dev/breeze/doc/ci/04_selective_checks.md 
b/dev/breeze/doc/ci/04_selective_checks.md
index 717282567ae..40932879727 100644
--- a/dev/breeze/doc/ci/04_selective_checks.md
+++ b/dev/breeze/doc/ci/04_selective_checks.md
@@ -754,6 +754,7 @@ GitHub Actions to pass the list of parameters to a command 
to execute
 | all-versions                                            | If set to true, 
then all python, k8s, DB versions are used for tests.                           
        | false                                    |      |
 | basic-checks-only                                       | Whether to run all 
static checks ("false") or only basic set of static checks ("true")             
     | false                                    |      |
 | ci-image-build                                          | Whether CI image 
build is needed                                                                 
       | true                                     |      |
+| ci-image-dependencies-changed                           | Whether dependency 
inputs of the CI image changed (an apache/airflow PR then pushes its keyed 
cache)    | false                                    |      |
 | core-test-types-list-as-strings-in-json                 | Which test types 
should be run for unit tests for core (2 slices; 1 on RunsOn)                   
       | API Always Providers                     | *    |
 | debug-resources                                         | Whether resources 
usage should be printed during parallel job execution ("true"/ "false")         
      | false                                    |      |
 | default-branch                                          | Which branch is 
default for the build ("main" for main branch, "v2-4-test" for 2.4 line etc.)   
        | main                                     |      |
diff --git a/dev/breeze/doc/ci/05_workflows.md 
b/dev/breeze/doc/ci/05_workflows.md
index 7b29cc1d431..c1632918547 100644
--- a/dev/breeze/doc/ci/05_workflows.md
+++ b/dev/breeze/doc/ci/05_workflows.md
@@ -371,6 +371,10 @@ keeps running the full CI on every push.
 
 The CI image cache of `vX-Y-test` and providers branches is still refreshed on 
every push, by
 
[`refresh-image-registry-cache.yml`](../../../../.github/workflows/refresh-image-registry-cache.yml).
+On `main` it is refreshed by the canary, and also right after a push that 
changes the
+dependency inputs of the CI image, by
+[`refresh-image-cache-on-dependency-change.yml`](../../../../.github/workflows/refresh-image-cache-on-dependency-change.yml)
+(see [GitHub Registry used as 
cache](01_ci_environment.md#github-registry-used-as-cache)).
 
 ### Branch Detection Logic
 
diff --git a/dev/breeze/doc/images/output_ci-image_build.svg 
b/dev/breeze/doc/images/output_ci-image_build.svg
index ee3b29f4493..d28fa5c9421 100644
--- a/dev/breeze/doc/images/output_ci-image_build.svg
+++ b/dev/breeze/doc/images/output_ci-image_build.svg
@@ -1,4 +1,4 @@
-<svg class="rich-terminal" viewBox="0 0 1482 2148.4" 
xmlns="http://www.w3.org/2000/svg";>
+<svg class="rich-terminal" viewBox="0 0 1482 2197.2" 
xmlns="http://www.w3.org/2000/svg";>
     <!-- Generated with Rich https://www.textualize.io -->
     <style>
 
@@ -43,7 +43,7 @@
 
     <defs>
     <clipPath id="breeze-ci-image-build-clip-terminal">
-      <rect x="0" y="0" width="1463.0" height="2097.4" />
+      <rect x="0" y="0" width="1463.0" height="2146.2" />
     </clipPath>
     <clipPath id="breeze-ci-image-build-line-0">
     <rect x="0" y="1.5" width="1464" height="24.65"/>
@@ -300,9 +300,15 @@
 <clipPath id="breeze-ci-image-build-line-84">
     <rect x="0" y="2051.1" width="1464" height="24.65"/>
             </clipPath>
+<clipPath id="breeze-ci-image-build-line-85">
+    <rect x="0" y="2075.5" width="1464" height="24.65"/>
+            </clipPath>
+<clipPath id="breeze-ci-image-build-line-86">
+    <rect x="0" y="2099.9" width="1464" height="24.65"/>
+            </clipPath>
     </defs>
 
-    <rect fill="#292929" stroke="rgba(255,255,255,0.35)" stroke-width="1" 
x="1" y="1" width="1480" height="2146.4" rx="8"/><text 
class="breeze-ci-image-build-title" fill="#c5c8c6" text-anchor="middle" x="740" 
y="27">Command:&#160;ci-image&#160;build</text>
+    <rect fill="#292929" stroke="rgba(255,255,255,0.35)" stroke-width="1" 
x="1" y="1" width="1480" height="2195.2" rx="8"/><text 
class="breeze-ci-image-build-title" fill="#c5c8c6" text-anchor="middle" x="740" 
y="27">Command:&#160;ci-image&#160;build</text>
             <g transform="translate(26,22)">
             <circle cx="0" cy="0" r="7" fill="#ff5f57"/>
             <circle cx="22" cy="0" r="7" fill="#febc2e"/>
@@ -387,17 +393,19 @@
 </text><text class="breeze-ci-image-build-r5" x="0" y="1776.8" 
textLength="12.2" clip-path="url(#breeze-ci-image-build-line-72)">│</text><text 
class="breeze-ci-image-build-r4" x="24.4" y="1776.8" textLength="268.4" 
clip-path="url(#breeze-ci-image-build-line-72)">--push&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;</text><text
 class="breeze-ci-image-build-r1" x="317.2" y="1776.8" textLength="353.8" 
clip-path="url(#breeze-ci-image-build-lin [...]
 </text><text class="breeze-ci-image-build-r5" x="0" y="1801.2" 
textLength="12.2" clip-path="url(#breeze-ci-image-build-line-73)">│</text><text 
class="breeze-ci-image-build-r4" x="24.4" y="1801.2" textLength="268.4" 
clip-path="url(#breeze-ci-image-build-line-73)">--prepare-buildx-cache</text><text
 class="breeze-ci-image-build-r1" x="317.2" y="1801.2" textLength="1122.4" 
clip-path="url(#breeze-ci-image-build-line-73)">Prepares&#160;build&#160;cache&#160;(this&#160;is&#160;done&#160;as&#160
 [...]
 </text><text class="breeze-ci-image-build-r5" x="0" y="1825.6" 
textLength="12.2" clip-path="url(#breeze-ci-image-build-line-74)">│</text><text 
class="breeze-ci-image-build-r1" x="317.2" y="1825.6" textLength="1122.4" 
clip-path="url(#breeze-ci-image-build-line-74)">image).&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#16
 [...]
-</text><text class="breeze-ci-image-build-r5" x="0" y="1850" textLength="1464" 
clip-path="url(#breeze-ci-image-build-line-75)">╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</text><text
 class="breeze-ci-image-build-r1" x="1464" y="1850" textLength="12.2" 
clip-path="url(#breeze-ci-image-build-line-75)">
-</text><text class="breeze-ci-image-build-r5" x="0" y="1874.4" 
textLength="24.4" 
clip-path="url(#breeze-ci-image-build-line-76)">╭─</text><text 
class="breeze-ci-image-build-r5" x="24.4" y="1874.4" textLength="280.6" 
clip-path="url(#breeze-ci-image-build-line-76)">&#160;GitHub&#160;authentication&#160;</text><text
 class="breeze-ci-image-build-r5" x="305" y="1874.4" textLength="1134.6" 
clip-path="url(#breeze-ci-image-build-line-76)">─────────────────────────────────────────────────────────
 [...]
-</text><text class="breeze-ci-image-build-r5" x="0" y="1898.8" 
textLength="12.2" clip-path="url(#breeze-ci-image-build-line-77)">│</text><text 
class="breeze-ci-image-build-r4" x="24.4" y="1898.8" textLength="231.8" 
clip-path="url(#breeze-ci-image-build-line-77)">--github-repository</text><text 
class="breeze-ci-image-build-r6" x="280.6" y="1898.8" textLength="24.4" 
clip-path="url(#breeze-ci-image-build-line-77)">-g</text><text 
class="breeze-ci-image-build-r1" x="329.4" y="1898.8" textLeng [...]
-</text><text class="breeze-ci-image-build-r5" x="0" y="1923.2" 
textLength="12.2" clip-path="url(#breeze-ci-image-build-line-78)">│</text><text 
class="breeze-ci-image-build-r4" x="24.4" y="1923.2" textLength="231.8" 
clip-path="url(#breeze-ci-image-build-line-78)">--github-token&#160;&#160;&#160;&#160;&#160;</text><text
 class="breeze-ci-image-build-r1" x="329.4" y="1923.2" textLength="512.4" 
clip-path="url(#breeze-ci-image-build-line-78)">The&#160;token&#160;used&#160;to&#160;authenticate&
 [...]
-</text><text class="breeze-ci-image-build-r5" x="0" y="1947.6" 
textLength="1464" 
clip-path="url(#breeze-ci-image-build-line-79)">╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</text><text
 class="breeze-ci-image-build-r1" x="1464" y="1947.6" textLength="12.2" 
clip-path="url(#breeze-ci-image-build-line-79)">
-</text><text class="breeze-ci-image-build-r5" x="0" y="1972" textLength="24.4" 
clip-path="url(#breeze-ci-image-build-line-80)">╭─</text><text 
class="breeze-ci-image-build-r5" x="24.4" y="1972" textLength="195.2" 
clip-path="url(#breeze-ci-image-build-line-80)">&#160;Common&#160;options&#160;</text><text
 class="breeze-ci-image-build-r5" x="219.6" y="1972" textLength="1220" 
clip-path="url(#breeze-ci-image-build-line-80)">──────────────────────────────────────────────────────────────────────
 [...]
-</text><text class="breeze-ci-image-build-r5" x="0" y="1996.4" 
textLength="12.2" clip-path="url(#breeze-ci-image-build-line-81)">│</text><text 
class="breeze-ci-image-build-r4" x="24.4" y="1996.4" textLength="109.8" 
clip-path="url(#breeze-ci-image-build-line-81)">--answer&#160;</text><text 
class="breeze-ci-image-build-r6" x="158.6" y="1996.4" textLength="24.4" 
clip-path="url(#breeze-ci-image-build-line-81)">-a</text><text 
class="breeze-ci-image-build-r1" x="207.4" y="1996.4" textLength="3 [...]
-</text><text class="breeze-ci-image-build-r5" x="0" y="2020.8" 
textLength="12.2" clip-path="url(#breeze-ci-image-build-line-82)">│</text><text 
class="breeze-ci-image-build-r4" x="24.4" y="2020.8" textLength="109.8" 
clip-path="url(#breeze-ci-image-build-line-82)">--dry-run</text><text 
class="breeze-ci-image-build-r6" x="158.6" y="2020.8" textLength="24.4" 
clip-path="url(#breeze-ci-image-build-line-82)">-D</text><text 
class="breeze-ci-image-build-r1" x="207.4" y="2020.8" textLength="719.8" [...]
-</text><text class="breeze-ci-image-build-r5" x="0" y="2045.2" 
textLength="12.2" clip-path="url(#breeze-ci-image-build-line-83)">│</text><text 
class="breeze-ci-image-build-r4" x="24.4" y="2045.2" textLength="109.8" 
clip-path="url(#breeze-ci-image-build-line-83)">--verbose</text><text 
class="breeze-ci-image-build-r6" x="158.6" y="2045.2" textLength="24.4" 
clip-path="url(#breeze-ci-image-build-line-83)">-v</text><text 
class="breeze-ci-image-build-r1" x="207.4" y="2045.2" textLength="585.6" [...]
-</text><text class="breeze-ci-image-build-r5" x="0" y="2069.6" 
textLength="12.2" clip-path="url(#breeze-ci-image-build-line-84)">│</text><text 
class="breeze-ci-image-build-r4" x="24.4" y="2069.6" textLength="109.8" 
clip-path="url(#breeze-ci-image-build-line-84)">--help&#160;&#160;&#160;</text><text
 class="breeze-ci-image-build-r6" x="158.6" y="2069.6" textLength="24.4" 
clip-path="url(#breeze-ci-image-build-line-84)">-h</text><text 
class="breeze-ci-image-build-r1" x="207.4" y="2069.6" tex [...]
-</text><text class="breeze-ci-image-build-r5" x="0" y="2094" textLength="1464" 
clip-path="url(#breeze-ci-image-build-line-85)">╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</text><text
 class="breeze-ci-image-build-r1" x="1464" y="2094" textLength="12.2" 
clip-path="url(#breeze-ci-image-build-line-85)">
+</text><text class="breeze-ci-image-build-r5" x="0" y="1850" textLength="12.2" 
clip-path="url(#breeze-ci-image-build-line-75)">│</text><text 
class="breeze-ci-image-build-r4" x="24.4" y="1850" textLength="268.4" 
clip-path="url(#breeze-ci-image-build-line-75)">--keyed-cache-only&#160;&#160;&#160;&#160;</text><text
 class="breeze-ci-image-build-r1" x="317.2" y="1850" textLength="61" 
clip-path="url(#breeze-ci-image-build-line-75)">With&#160;</text><text 
class="breeze-ci-image-build-r4" x="378 [...]
+</text><text class="breeze-ci-image-build-r5" x="0" y="1874.4" 
textLength="12.2" clip-path="url(#breeze-ci-image-build-line-76)">│</text><text 
class="breeze-ci-image-build-r1" x="317.2" y="1874.4" textLength="1122.4" 
clip-path="url(#breeze-ci-image-build-line-76)">skipping&#160;it&#160;when&#160;the&#160;registry&#160;already&#160;has&#160;it,&#160;and&#160;leave&#160;the&#160;shared&#160;cache&#160;tag&#160;alone.&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;</text><text
 class=" [...]
+</text><text class="breeze-ci-image-build-r5" x="0" y="1898.8" 
textLength="1464" 
clip-path="url(#breeze-ci-image-build-line-77)">╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</text><text
 class="breeze-ci-image-build-r1" x="1464" y="1898.8" textLength="12.2" 
clip-path="url(#breeze-ci-image-build-line-77)">
+</text><text class="breeze-ci-image-build-r5" x="0" y="1923.2" 
textLength="24.4" 
clip-path="url(#breeze-ci-image-build-line-78)">╭─</text><text 
class="breeze-ci-image-build-r5" x="24.4" y="1923.2" textLength="280.6" 
clip-path="url(#breeze-ci-image-build-line-78)">&#160;GitHub&#160;authentication&#160;</text><text
 class="breeze-ci-image-build-r5" x="305" y="1923.2" textLength="1134.6" 
clip-path="url(#breeze-ci-image-build-line-78)">─────────────────────────────────────────────────────────
 [...]
+</text><text class="breeze-ci-image-build-r5" x="0" y="1947.6" 
textLength="12.2" clip-path="url(#breeze-ci-image-build-line-79)">│</text><text 
class="breeze-ci-image-build-r4" x="24.4" y="1947.6" textLength="231.8" 
clip-path="url(#breeze-ci-image-build-line-79)">--github-repository</text><text 
class="breeze-ci-image-build-r6" x="280.6" y="1947.6" textLength="24.4" 
clip-path="url(#breeze-ci-image-build-line-79)">-g</text><text 
class="breeze-ci-image-build-r1" x="329.4" y="1947.6" textLeng [...]
+</text><text class="breeze-ci-image-build-r5" x="0" y="1972" textLength="12.2" 
clip-path="url(#breeze-ci-image-build-line-80)">│</text><text 
class="breeze-ci-image-build-r4" x="24.4" y="1972" textLength="231.8" 
clip-path="url(#breeze-ci-image-build-line-80)">--github-token&#160;&#160;&#160;&#160;&#160;</text><text
 class="breeze-ci-image-build-r1" x="329.4" y="1972" textLength="512.4" 
clip-path="url(#breeze-ci-image-build-line-80)">The&#160;token&#160;used&#160;to&#160;authenticate&#160;t
 [...]
+</text><text class="breeze-ci-image-build-r5" x="0" y="1996.4" 
textLength="1464" 
clip-path="url(#breeze-ci-image-build-line-81)">╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</text><text
 class="breeze-ci-image-build-r1" x="1464" y="1996.4" textLength="12.2" 
clip-path="url(#breeze-ci-image-build-line-81)">
+</text><text class="breeze-ci-image-build-r5" x="0" y="2020.8" 
textLength="24.4" 
clip-path="url(#breeze-ci-image-build-line-82)">╭─</text><text 
class="breeze-ci-image-build-r5" x="24.4" y="2020.8" textLength="195.2" 
clip-path="url(#breeze-ci-image-build-line-82)">&#160;Common&#160;options&#160;</text><text
 class="breeze-ci-image-build-r5" x="219.6" y="2020.8" textLength="1220" 
clip-path="url(#breeze-ci-image-build-line-82)">────────────────────────────────────────────────────────────────
 [...]
+</text><text class="breeze-ci-image-build-r5" x="0" y="2045.2" 
textLength="12.2" clip-path="url(#breeze-ci-image-build-line-83)">│</text><text 
class="breeze-ci-image-build-r4" x="24.4" y="2045.2" textLength="109.8" 
clip-path="url(#breeze-ci-image-build-line-83)">--answer&#160;</text><text 
class="breeze-ci-image-build-r6" x="158.6" y="2045.2" textLength="24.4" 
clip-path="url(#breeze-ci-image-build-line-83)">-a</text><text 
class="breeze-ci-image-build-r1" x="207.4" y="2045.2" textLength="3 [...]
+</text><text class="breeze-ci-image-build-r5" x="0" y="2069.6" 
textLength="12.2" clip-path="url(#breeze-ci-image-build-line-84)">│</text><text 
class="breeze-ci-image-build-r4" x="24.4" y="2069.6" textLength="109.8" 
clip-path="url(#breeze-ci-image-build-line-84)">--dry-run</text><text 
class="breeze-ci-image-build-r6" x="158.6" y="2069.6" textLength="24.4" 
clip-path="url(#breeze-ci-image-build-line-84)">-D</text><text 
class="breeze-ci-image-build-r1" x="207.4" y="2069.6" textLength="719.8" [...]
+</text><text class="breeze-ci-image-build-r5" x="0" y="2094" textLength="12.2" 
clip-path="url(#breeze-ci-image-build-line-85)">│</text><text 
class="breeze-ci-image-build-r4" x="24.4" y="2094" textLength="109.8" 
clip-path="url(#breeze-ci-image-build-line-85)">--verbose</text><text 
class="breeze-ci-image-build-r6" x="158.6" y="2094" textLength="24.4" 
clip-path="url(#breeze-ci-image-build-line-85)">-v</text><text 
class="breeze-ci-image-build-r1" x="207.4" y="2094" textLength="585.6" clip-pa 
[...]
+</text><text class="breeze-ci-image-build-r5" x="0" y="2118.4" 
textLength="12.2" clip-path="url(#breeze-ci-image-build-line-86)">│</text><text 
class="breeze-ci-image-build-r4" x="24.4" y="2118.4" textLength="109.8" 
clip-path="url(#breeze-ci-image-build-line-86)">--help&#160;&#160;&#160;</text><text
 class="breeze-ci-image-build-r6" x="158.6" y="2118.4" textLength="24.4" 
clip-path="url(#breeze-ci-image-build-line-86)">-h</text><text 
class="breeze-ci-image-build-r1" x="207.4" y="2118.4" tex [...]
+</text><text class="breeze-ci-image-build-r5" x="0" y="2142.8" 
textLength="1464" 
clip-path="url(#breeze-ci-image-build-line-87)">╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</text><text
 class="breeze-ci-image-build-r1" x="1464" y="2142.8" textLength="12.2" 
clip-path="url(#breeze-ci-image-build-line-87)">
 </text>
     </g>
     </g>
diff --git a/dev/breeze/doc/images/output_ci-image_build.txt 
b/dev/breeze/doc/images/output_ci-image_build.txt
index 660d983fff0..0e846f25d52 100644
--- a/dev/breeze/doc/images/output_ci-image_build.txt
+++ b/dev/breeze/doc/images/output_ci-image_build.txt
@@ -1 +1 @@
-7d27897048667db76904ec4077c384fb
+4e6b3c3213a08ec130d6473da7fe97f7
diff --git a/dev/breeze/src/airflow_breeze/commands/ci_image_commands.py 
b/dev/breeze/src/airflow_breeze/commands/ci_image_commands.py
index 4204b72c370..ccd7549f69e 100644
--- a/dev/breeze/src/airflow_breeze/commands/ci_image_commands.py
+++ b/dev/breeze/src/airflow_breeze/commands/ci_image_commands.py
@@ -47,6 +47,7 @@ from airflow_breeze.commands.common_image_options import (
     option_github_token_for_images,
     option_image_file_dir,
     option_install_mysql_client_type,
+    option_keyed_cache_only,
     option_platform_multiple,
     option_prepare_buildx_cache,
     option_pull,
@@ -93,6 +94,7 @@ from airflow_breeze.utils.confirm import STANDARD_TIMEOUT, 
Answer, user_confirm
 from airflow_breeze.utils.console import Output, console_print, get_console
 from airflow_breeze.utils.docker_command_utils import (
     build_cache,
+    check_buildx_version,
     check_remote_ghcr_io_commands,
     get_docker_build_env,
     make_sure_builder_configured,
@@ -265,6 +267,7 @@ option_ci_image_file_to_load = click.option(
 @option_github_token
 @option_install_mysql_client_type
 @option_include_success_outputs
+@option_keyed_cache_only
 @option_parallelism
 @option_platform_multiple
 @option_prepare_buildx_cache
@@ -304,6 +307,7 @@ def build(
     github_token: str | None,
     include_success_outputs,
     install_mysql_client_type: str,
+    keyed_cache_only: bool,
     parallelism: int,
     platform: str | None,
     prepare_buildx_cache: bool,
@@ -331,7 +335,10 @@ def build(
             console_print(f"[error]Error when building image! {info}")
             sys.exit(return_code)
 
-    perform_environment_checks()
+    if keyed_cache_only and not prepare_buildx_cache:
+        console_print("[error]--keyed-cache-only can only be used with 
--prepare-buildx-cache[/]")
+        sys.exit(1)
+    perform_environment_checks(building_images=True)
     check_remote_ghcr_io_commands()
     fix_group_permissions()
     base_build_params = BuildCiParams(
@@ -356,6 +363,7 @@ def build(
         github_repository=github_repository,
         github_token=github_token,
         install_mysql_client_type=install_mysql_client_type,
+        keyed_cache_only=keyed_cache_only,
         prepare_buildx_cache=prepare_buildx_cache,
         push=push,
         python=python,
@@ -1014,6 +1022,7 @@ def build_ci_image_if_needed(command_params: ShellParams 
| BuildCiParams) -> Non
         ci_image_params=ci_image_params,
         output=None,
     ):
+        check_buildx_version(quiet=True)
         return_code, info = run_build_ci_image(
             ci_image_params=ci_image_params, 
param_description=ci_image_params.python, output=None
         )
diff --git a/dev/breeze/src/airflow_breeze/commands/ci_image_commands_config.py 
b/dev/breeze/src/airflow_breeze/commands/ci_image_commands_config.py
index 464d3e35ac0..ef33164f271 100644
--- a/dev/breeze/src/airflow_breeze/commands/ci_image_commands_config.py
+++ b/dev/breeze/src/airflow_breeze/commands/ci_image_commands_config.py
@@ -93,6 +93,7 @@ CI_IMAGE_TOOLS_PARAMETERS: dict[str, list[dict[str, str | 
list[str]]]] = {
                 "--platform",
                 "--push",
                 "--prepare-buildx-cache",
+                "--keyed-cache-only",
             ],
         },
         {
diff --git a/dev/breeze/src/airflow_breeze/commands/common_image_options.py 
b/dev/breeze/src/airflow_breeze/commands/common_image_options.py
index dfd7e1b0b16..d2294018b98 100644
--- a/dev/breeze/src/airflow_breeze/commands/common_image_options.py
+++ b/dev/breeze/src/airflow_breeze/commands/common_image_options.py
@@ -178,6 +178,13 @@ option_prepare_buildx_cache = click.option(
     is_flag=True,
     envvar="PREPARE_BUILDX_CACHE",
 )
+option_keyed_cache_only = click.option(
+    "--keyed-cache-only",
+    help="With --prepare-buildx-cache, only push the cache tagged with this 
checkout's dependency key, "
+    "skipping it when the registry already has it, and leave the shared cache 
tag alone.",
+    is_flag=True,
+    envvar="KEYED_CACHE_ONLY",
+)
 option_pull = click.option(
     "--pull",
     help="Pull image is missing before attempting to verify it.",
diff --git 
a/dev/breeze/src/airflow_breeze/commands/production_image_commands.py 
b/dev/breeze/src/airflow_breeze/commands/production_image_commands.py
index 534e2efcf58..77433b088d6 100644
--- a/dev/breeze/src/airflow_breeze/commands/production_image_commands.py
+++ b/dev/breeze/src/airflow_breeze/commands/production_image_commands.py
@@ -395,7 +395,7 @@ def build(
             console_print("[warning]Since we are installing from sources - PIP 
is used by default[/]")
             use_uv = False
 
-    perform_environment_checks()
+    perform_environment_checks(building_images=True)
     check_remote_ghcr_io_commands()
     base_build_params = BuildProdParams(
         additional_airflow_extras=additional_airflow_extras,
diff --git a/dev/breeze/src/airflow_breeze/global_constants.py 
b/dev/breeze/src/airflow_breeze/global_constants.py
index 338389dd81f..053f43032ae 100644
--- a/dev/breeze/src/airflow_breeze/global_constants.py
+++ b/dev/breeze/src/airflow_breeze/global_constants.py
@@ -866,6 +866,10 @@ ISSUE_ID = ""
 NUM_RUNS = ""
 
 MIN_DOCKER_VERSION = "25.0.0"
+# The CI image cache push writes the shared and the keyed cache with two 
`--cache-to` in one build,
+# which BuildKit supports since v0.11 (moby/buildkit#3024); buildx 0.10 is the 
release built on it.
+# The daemon's own BuildKit is covered by MIN_DOCKER_VERSION.
+MIN_BUILDX_VERSION = "0.10.0"
 MIN_DOCKER_COMPOSE_VERSION = "2.20.2"
 MIN_GH_VERSION = "2.70.0"
 
diff --git a/dev/breeze/src/airflow_breeze/params/build_ci_params.py 
b/dev/breeze/src/airflow_breeze/params/build_ci_params.py
index 5eb4750d2ea..3641e497bf2 100644
--- a/dev/breeze/src/airflow_breeze/params/build_ci_params.py
+++ b/dev/breeze/src/airflow_breeze/params/build_ci_params.py
@@ -23,6 +23,7 @@ from pathlib import Path
 from airflow_breeze.branch_defaults import DEFAULT_AIRFLOW_CONSTRAINTS_BRANCH
 from airflow_breeze.global_constants import 
ALL_PYTHON_VERSION_TO_PATCHLEVEL_VERSION
 from airflow_breeze.params.common_build_params import CommonBuildParams
+from airflow_breeze.utils.md5_build_check import calculate_ci_image_cache_key
 from airflow_breeze.utils.path_utils import BUILD_CACHE_PATH
 
 
@@ -51,6 +52,12 @@ class BuildCiParams(CommonBuildParams):
     def image_type(self) -> str:
         return "CI"
 
+    def get_keyed_cache(self, single_platform: str) -> str | None:
+        cache_key = calculate_ci_image_cache_key()
+        if not cache_key:
+            return None
+        return f"{self.get_cache(single_platform)}-{cache_key}"
+
     @property
     def md5sum_cache_dir(self) -> Path:
         return Path(BUILD_CACHE_PATH, self.airflow_branch, self.python, "CI")
diff --git a/dev/breeze/src/airflow_breeze/params/common_build_params.py 
b/dev/breeze/src/airflow_breeze/params/common_build_params.py
index d12905c783f..e619f3b0f45 100644
--- a/dev/breeze/src/airflow_breeze/params/common_build_params.py
+++ b/dev/breeze/src/airflow_breeze/params/common_build_params.py
@@ -67,6 +67,7 @@ class CommonBuildParams:
     github_repository: str = APACHE_AIRFLOW_GITHUB_REPOSITORY
     github_token: str = os.environ.get("GITHUB_TOKEN", "")
     install_mysql_client_type: str = ALLOWED_INSTALL_MYSQL_CLIENT_TYPES[0]
+    keyed_cache_only: bool = False
     platform: str = DOCKER_DEFAULT_PLATFORM
     prepare_buildx_cache: bool = False
     python_image: str | None = None
@@ -110,6 +111,9 @@ class CommonBuildParams:
         extra_flags = []
         extra_flags.append(f"--progress={self.build_progress}")
         if self.docker_cache == "registry":
+            keyed_cache = self.get_keyed_cache(self.platform)
+            if keyed_cache:
+                extra_flags.append(f"--cache-from={keyed_cache}")
             extra_flags.append(f"--cache-from={self.get_cache(self.platform)}")
         elif self.docker_cache == "disabled":
             extra_flags.append("--no-cache")
@@ -188,6 +192,10 @@ class CommonBuildParams:
         platform_tag = get_normalized_platform(single_platform).replace("/", 
"-")
         return f"{self.airflow_image_name}:cache-{platform_tag}"
 
+    def get_keyed_cache(self, single_platform: str) -> str | None:
+        """Registry cache ref specific to this checkout's dependency inputs, 
if the image type has one."""
+        return None
+
     def is_multi_platform(self) -> bool:
         return "," in self.platform
 
diff --git a/dev/breeze/src/airflow_breeze/utils/docker_command_utils.py 
b/dev/breeze/src/airflow_breeze/utils/docker_command_utils.py
index cc04933661d..5e8ccc5e762 100644
--- a/dev/breeze/src/airflow_breeze/utils/docker_command_utils.py
+++ b/dev/breeze/src/airflow_breeze/utils/docker_command_utils.py
@@ -64,6 +64,7 @@ from airflow_breeze.global_constants import (
     DOCKER_DEFAULT_PLATFORM,
     KNOWN_DOCKER_COMPOSE_PROJECT_NAMES,
     KNOWN_DOCKER_COMPOSE_PROJECT_PREFIXES,
+    MIN_BUILDX_VERSION,
     MIN_DOCKER_COMPOSE_VERSION,
     MIN_DOCKER_VERSION,
 )
@@ -278,6 +279,36 @@ You can find installation instructions here: 
https://docs.docker.com/engine/inst
                 sys.exit(1)
 
 
+def check_buildx_version(quiet: bool = False):
+    """Exit when docker buildx, which builds the images, is missing or older 
than MIN_BUILDX_VERSION."""
+    result = run_command(
+        ["docker", "buildx", "version"],
+        no_output_dump_on_exception=True,
+        capture_output=True,
+        text=True,
+        check=False,
+        dry_run_override=False,
+    )
+    match = re.search(r"buildx\s+v?(\d+\.\d+\.\d+)", result.stdout) if 
result.returncode == 0 else None
+    if not match:
+        console_print(
+            "[error]Docker buildx is needed to build images, but `docker 
buildx version` did not report "
+            f"a version.[/]\n[warning]Install buildx {MIN_BUILDX_VERSION} or 
newer: "
+            
"https://docs.docker.com/build/concepts/overview/#install-buildx[/]";
+        )
+        sys.exit(1)
+    buildx_version = match.group(1)
+    if not compare_version(buildx_version, MIN_BUILDX_VERSION):
+        console_print(
+            f"[error]Your version of docker buildx is too old: 
{buildx_version}.[/]\n"
+            f"[warning]Please upgrade to at least {MIN_BUILDX_VERSION}: "
+            
"https://docs.docker.com/build/concepts/overview/#install-buildx[/]";
+        )
+        sys.exit(1)
+    if not quiet:
+        console_print(f"[success]Good version of docker buildx: 
{buildx_version}.[/]")
+
+
 def check_container_engine_is_docker(quiet: bool = False) -> bool:
     """Checks if the container engine is Docker or podman."""
     response = run_command(
@@ -430,12 +461,25 @@ def prepare_docker_build_cache_command(
         ["-f", "Dockerfile" if isinstance(image_params, BuildProdParams) else 
"Dockerfile.ci"]
     )
     final_command.extend(["--platform", image_params.platform])
-    final_command.extend(
-        
[f"--cache-to=type=registry,ref={image_params.get_cache(image_params.platform)},mode=max"]
-    )
+    cache_refs = [] if image_params.keyed_cache_only else 
[image_params.get_cache(image_params.platform)]
+    keyed_cache = image_params.get_keyed_cache(image_params.platform)
+    if keyed_cache:
+        cache_refs.append(keyed_cache)
+    final_command.extend(f"--cache-to=type=registry,ref={ref},mode=max" for 
ref in cache_refs)
     return final_command
 
 
+def is_registry_cache_present(cache_ref: str) -> bool:
+    result = run_command(
+        ["docker", "buildx", "imagetools", "inspect", cache_ref],
+        capture_output=True,
+        text=True,
+        check=False,
+        dry_run_override=False,
+    )
+    return result.returncode == 0
+
+
 def prepare_base_build_command(image_params: CommonBuildParams) -> list[str]:
     """
     Prepare build command for docker build. Depending on whether we have 
buildx plugin installed or not,
@@ -520,6 +564,18 @@ def build_cache(image_params: CommonBuildParams, output: 
Output | None) -> RunCo
         # override the platform in the copied params to only be single 
platform per run
         # as a workaround to https://github.com/docker/buildx/issues/1044
         platform_image_params.platform = build_platform
+        if platform_image_params.keyed_cache_only:
+            keyed_cache = platform_image_params.get_keyed_cache(build_platform)
+            if not keyed_cache:
+                get_console(output=output).print(
+                    "[error]No cache key for this checkout - cannot push keyed 
cache only.[/]"
+                )
+                return CompletedProcess(args=[], returncode=1)
+            if is_registry_cache_present(keyed_cache):
+                get_console(output=output).print(
+                    f"[info]Cache {keyed_cache} is already in the registry - 
skipping.[/]"
+                )
+                continue
         cmd = 
prepare_docker_build_cache_command(image_params=platform_image_params)
         build_command_result = run_command(
             cmd,
@@ -629,7 +685,9 @@ def check_executable_entrypoint_permissions(quiet: bool = 
False):
 
 
 @lru_cache
-def perform_environment_checks(quiet: bool = False, *, 
cleanup_stale_worktrees: bool = True):
+def perform_environment_checks(
+    quiet: bool = False, *, cleanup_stale_worktrees: bool = True, 
building_images: bool = False
+):
     check_docker_is_running()
     container_engine_is_docker = check_container_engine_is_docker(quiet)
     if not container_engine_is_docker:
@@ -639,6 +697,8 @@ def perform_environment_checks(quiet: bool = False, *, 
cleanup_stale_worktrees:
     else:
         check_docker_version(quiet)
         check_docker_compose_version(quiet)
+        if building_images:
+            check_buildx_version(quiet)
         check_windows_filesystem_mount(quiet)
         check_executable_entrypoint_permissions(quiet)
     check_uv_version(quiet)
diff --git a/dev/breeze/src/airflow_breeze/utils/md5_build_check.py 
b/dev/breeze/src/airflow_breeze/utils/md5_build_check.py
index 0283aa41f1a..834e7de129f 100644
--- a/dev/breeze/src/airflow_breeze/utils/md5_build_check.py
+++ b/dev/breeze/src/airflow_breeze/utils/md5_build_check.py
@@ -20,8 +20,10 @@ Utilities to check - with MD5 - whether files have been 
modified since the last
 
 from __future__ import annotations
 
+import functools
 import hashlib
 import os
+import subprocess
 from pathlib import Path
 from typing import TYPE_CHECKING
 
@@ -91,6 +93,33 @@ def calculate_ci_sources_hash() -> str:
     return hash_md5.hexdigest()
 
 
[email protected]
+def calculate_ci_image_cache_key() -> str | None:
+    """
+    Return a key identifying the inputs of the CI image's expensive dependency 
layers.
+
+    The key covers the files that trigger a rebuild plus ``uv.lock`` and every 
``pyproject.toml``,
+    which are what the ``dependency-manifests`` stage of ``Dockerfile.ci`` 
copies. It only names the
+    registry cache to look up: BuildKit still validates each layer, so a 
mismatched key costs a cache
+    miss and never reuses a wrong layer. Returns None outside a git checkout.
+    """
+    result = subprocess.run(
+        ["git", "ls-files", "-z", "--", "uv.lock", "pyproject.toml", 
"*/pyproject.toml"],
+        cwd=AIRFLOW_ROOT_PATH,
+        capture_output=True,
+        check=False,
+    )
+    if result.returncode != 0:
+        return None
+    manifests = sorted(path for path in result.stdout.decode().split("\0") if 
path)
+    hash_md5 = hashlib.md5()
+    for file in [*FILES_FOR_REBUILD_CHECK, *manifests]:
+        file_path = AIRFLOW_ROOT_PATH / file
+        if file_path.is_file():
+            hash_md5.update(f"{file}:{generate_md5(file_path)}\n".encode())
+    return hash_md5.hexdigest()[:16]
+
+
 def calculate_md5_checksum_for_files(
     md5sum_cache_dir: Path, update: bool = False, 
skip_provider_dependencies_check: bool = False
 ) -> tuple[list[str], list[str]]:
diff --git a/dev/breeze/src/airflow_breeze/utils/selective_checks.py 
b/dev/breeze/src/airflow_breeze/utils/selective_checks.py
index b0cb135ac97..33faee53d50 100644
--- a/dev/breeze/src/airflow_breeze/utils/selective_checks.py
+++ b/dev/breeze/src/airflow_breeze/utils/selective_checks.py
@@ -138,6 +138,7 @@ class FileGroupForCi(Enum):
     PYTHON_PRODUCTION_FILES = auto()
     JAVASCRIPT_PRODUCTION_FILES = auto()
     ALWAYS_TESTS_FILES = auto()
+    CI_IMAGE_DEPENDENCY_FILES = auto()
     API_FILES = auto()
     GIT_PROVIDER_FILES = auto()
     STANDARD_PROVIDER_FILES = auto()
@@ -571,6 +572,15 @@ CI_FILE_GROUP_MATCHES: HashableDict[FileGroupForCi] = 
HashableDict(
         FileGroupForCi.ALL_PYPROJECT_TOML_FILES: [
             r".*pyproject\.toml$",
         ],
+        # Inputs of the CI image's dependency layers -- the files 
`calculate_ci_image_cache_key` hashes.
+        FileGroupForCi.CI_IMAGE_DEPENDENCY_FILES: [
+            r"^uv\.lock$",
+            r"(^|.*/)pyproject\.toml$",
+            r"^Dockerfile\.ci$",
+            r"^\.dockerignore$",
+            r"^scripts/docker/",
+            r"^dev/breeze/src/airflow_breeze/files/hardened_.*_digests\.json$",
+        ],
         FileGroupForCi.TESTS_UTILS_FILES: [
             r"^devel-common/src/tests_common/.*\.py$",
         ],
@@ -2271,6 +2281,10 @@ class SelectiveChecks:
             return True
         return False
 
+    @cached_property
+    def ci_image_dependencies_changed(self) -> bool:
+        return 
len(self._matching_files(FileGroupForCi.CI_IMAGE_DEPENDENCY_FILES, 
CI_FILE_GROUP_MATCHES)) > 0
+
     @cached_property
     def upgrade_to_newer_dependencies(self) -> bool:
         # The dependency upgrade summary runs in the CI image.
diff --git a/dev/breeze/tests/test_build_ci_params.py 
b/dev/breeze/tests/test_build_ci_params.py
index f652ca2f613..afc721001e7 100644
--- a/dev/breeze/tests/test_build_ci_params.py
+++ b/dev/breeze/tests/test_build_ci_params.py
@@ -17,9 +17,12 @@
 
 from __future__ import annotations
 
+from unittest import mock
+
 import pytest
 
 from airflow_breeze.params.build_ci_params import BuildCiParams
+from airflow_breeze.params.build_prod_params import BuildProdParams
 
 INLINE_CACHE_FLAG = "--build-arg=BUILDKIT_INLINE_CACHE=1"
 
@@ -55,3 +58,30 @@ def 
test_cache_from_image_added_when_registry_cache_is_not_used():
 def test_no_cache_from_image_flag_when_unset():
     flags = BuildCiParams(docker_cache="registry").common_docker_build_flags
     assert not any(flag.startswith("--cache-from=localhost") for flag in flags)
+
+
[email protected](
+    "airflow_breeze.params.build_ci_params.calculate_ci_image_cache_key", 
return_value="0123456789abcdef"
+)
+def test_keyed_registry_cache_is_tried_before_shared_cache(_mock_key):
+    params = BuildCiParams(docker_cache="registry")
+    shared_cache = params.get_cache(params.platform)
+
+    cache_from = [flag for flag in params.common_docker_build_flags if 
flag.startswith("--cache-from=")]
+
+    assert cache_from == [f"--cache-from={shared_cache}-0123456789abcdef", 
f"--cache-from={shared_cache}"]
+
+
[email protected]("airflow_breeze.params.build_ci_params.calculate_ci_image_cache_key",
 return_value=None)
+def test_only_shared_cache_without_cache_key(_mock_key):
+    params = BuildCiParams(docker_cache="registry")
+
+    cache_from = [flag for flag in params.common_docker_build_flags if 
flag.startswith("--cache-from=")]
+
+    assert cache_from == [f"--cache-from={params.get_cache(params.platform)}"]
+
+
+def test_prod_image_has_no_keyed_cache():
+    params = BuildProdParams()
+
+    assert params.get_keyed_cache(params.platform) is None
diff --git a/dev/breeze/tests/test_ci_image_commands.py 
b/dev/breeze/tests/test_ci_image_commands.py
index 029b28e963b..af1ec3500e5 100644
--- a/dev/breeze/tests/test_ci_image_commands.py
+++ b/dev/breeze/tests/test_ci_image_commands.py
@@ -18,6 +18,7 @@
 from __future__ import annotations
 
 import json
+import subprocess
 from unittest import mock
 
 import pytest
@@ -33,7 +34,7 @@ from airflow_breeze.commands.ci_image_commands import (
 )
 from airflow_breeze.global_constants import CI_IMAGE_SOURCES_HASH_LABEL
 from airflow_breeze.params.build_ci_params import BuildCiParams
-from airflow_breeze.utils.md5_build_check import calculate_ci_sources_hash
+from airflow_breeze.utils.md5_build_check import calculate_ci_image_cache_key, 
calculate_ci_sources_hash
 
 CI_IMAGE = BuildCiParams(python="3.11").airflow_image_name
 
@@ -54,6 +55,50 @@ def 
test_calculate_ci_sources_hash_is_stable_across_checkouts(tmp_path, monkeypa
     assert calculate_ci_sources_hash() != hash_of_first_checkout
 
 
+def _make_checkout(root, uv_lock: str) -> None:
+    (root / "providers" / "foo").mkdir(parents=True)
+    (root / "Dockerfile.ci").write_text("FROM base")
+    (root / "pyproject.toml").write_text("[project]")
+    (root / "providers" / "foo" / "pyproject.toml").write_text("[project]")
+    (root / "uv.lock").write_text(uv_lock)
+    subprocess.run(["git", "init", "-q"], cwd=root, check=True)
+    subprocess.run(["git", "add", "-A"], cwd=root, check=True)
+
+
[email protected]
+def compute_cache_key(monkeypatch):
+    
monkeypatch.setattr("airflow_breeze.utils.md5_build_check.FILES_FOR_REBUILD_CHECK",
 ["Dockerfile.ci"])
+
+    def compute(root):
+        calculate_ci_image_cache_key.cache_clear()
+        
monkeypatch.setattr("airflow_breeze.utils.md5_build_check.AIRFLOW_ROOT_PATH", 
root)
+        return calculate_ci_image_cache_key()
+
+    yield compute
+    calculate_ci_image_cache_key.cache_clear()
+
+
+def test_ci_image_cache_key_is_stable_across_checkouts(tmp_path, 
compute_cache_key):
+    for checkout in ("worktree-a", "worktree-b"):
+        _make_checkout(tmp_path / checkout, uv_lock="lock-1")
+
+    assert compute_cache_key(tmp_path / "worktree-a") == 
compute_cache_key(tmp_path / "worktree-b")
+
+
[email protected]("changed_file", ["uv.lock", 
"providers/foo/pyproject.toml", "Dockerfile.ci"])
+def test_ci_image_cache_key_changes_with_dependency_inputs(tmp_path, 
compute_cache_key, changed_file):
+    _make_checkout(tmp_path, uv_lock="lock-1")
+    key_before = compute_cache_key(tmp_path)
+
+    (tmp_path / changed_file).write_text("changed")
+
+    assert compute_cache_key(tmp_path) != key_before
+
+
+def test_ci_image_cache_key_is_none_outside_git_checkout(tmp_path, 
compute_cache_key):
+    assert compute_cache_key(tmp_path) is None
+
+
 @pytest.mark.parametrize(
     ("returncode", "stdout", "expected"),
     [
diff --git a/dev/breeze/tests/test_docker_command_utils.py 
b/dev/breeze/tests/test_docker_command_utils.py
index a6211db4212..8c88edd4ebf 100644
--- a/dev/breeze/tests/test_docker_command_utils.py
+++ b/dev/breeze/tests/test_docker_command_utils.py
@@ -35,6 +35,7 @@ from airflow_breeze.params.build_prod_params import 
BuildProdParams
 from airflow_breeze.utils import docker_command_utils
 from airflow_breeze.utils.docker_command_utils import (
     autodetect_docker_context,
+    build_cache,
     check_docker_compose_version,
     check_docker_is_running,
     check_docker_permission_denied,
@@ -42,6 +43,7 @@ from airflow_breeze.utils.docker_command_utils import (
     enter_shell,
     fix_ownership_using_docker,
     get_images_to_pull,
+    prepare_docker_build_cache_command,
     prepare_docker_build_command,
     pull_images_with_retries,
 )
@@ -1159,3 +1161,129 @@ def 
test_fix_ownership_using_docker_passes_lowercase_rootless_flag(
     fix_ownership_using_docker()
     docker_command = mock_run_command.call_args[0][0]
     assert expected in docker_command
+
+
+KEYED_CACHE_KEY = "0123456789abcdef"
+
+
+def _cache_to_refs(command: list[str]) -> list[str]:
+    return [flag for flag in command if flag.startswith("--cache-to=")]
+
+
[email protected](
+    ("keyed_cache_only", "expect_shared_cache"),
+    [pytest.param(False, True, id="shared-and-keyed"), pytest.param(True, 
False, id="keyed-only")],
+)
[email protected](
+    "airflow_breeze.params.build_ci_params.calculate_ci_image_cache_key", 
return_value=KEYED_CACHE_KEY
+)
[email protected]("airflow_breeze.utils.docker_command_utils.get_and_use_docker_context",
 return_value="default")
+def test_prepare_docker_build_cache_command_pushes_keyed_cache(
+    _mock_context, _mock_key, keyed_cache_only: bool, expect_shared_cache: bool
+):
+    params = BuildCiParams(platform="linux/amd64", 
keyed_cache_only=keyed_cache_only)
+    shared_cache = params.get_cache("linux/amd64")
+
+    expected = 
[f"--cache-to=type=registry,ref={shared_cache}-{KEYED_CACHE_KEY},mode=max"]
+    if expect_shared_cache:
+        expected.insert(0, 
f"--cache-to=type=registry,ref={shared_cache},mode=max")
+    assert _cache_to_refs(prepare_docker_build_cache_command(params)) == 
expected
+
+
[email protected]("airflow_breeze.utils.docker_command_utils.get_and_use_docker_context",
 return_value="default")
+def 
test_prepare_docker_build_cache_command_prod_image_pushes_only_shared_cache(_mock_context):
+    params = BuildProdParams(platform="linux/amd64")
+
+    assert _cache_to_refs(prepare_docker_build_cache_command(params)) == [
+        
f"--cache-to=type=registry,ref={params.get_cache('linux/amd64')},mode=max"
+    ]
+
+
[email protected](
+    ("cache_present", "expect_build"),
+    [pytest.param(True, False, id="already-pushed"), pytest.param(False, True, 
id="missing")],
+)
[email protected](
+    "airflow_breeze.params.build_ci_params.calculate_ci_image_cache_key", 
return_value=KEYED_CACHE_KEY
+)
[email protected]("airflow_breeze.utils.docker_command_utils.get_and_use_docker_context",
 return_value="default")
[email protected]("airflow_breeze.utils.docker_command_utils.run_command")
+def test_build_cache_keyed_only_skips_cache_already_in_registry(
+    mock_run_command, _mock_context, _mock_key, cache_present: bool, 
expect_build: bool
+):
+    mock_run_command.return_value = subprocess.CompletedProcess(args=[], 
returncode=0 if cache_present else 1)
+    params = BuildCiParams(platform="linux/amd64", keyed_cache_only=True)
+
+    build_cache(params, output=None)
+
+    commands = [c.args[0] for c in mock_run_command.call_args_list]
+    assert commands[0] == [
+        "docker",
+        "buildx",
+        "imagetools",
+        "inspect",
+        f"{params.get_cache('linux/amd64')}-{KEYED_CACHE_KEY}",
+    ]
+    assert any(command[:3] == ["docker", "buildx", "build"] for command in 
commands) is expect_build
+
+
[email protected]("airflow_breeze.params.build_ci_params.calculate_ci_image_cache_key",
 return_value=None)
[email protected]("airflow_breeze.utils.docker_command_utils.run_command")
+def test_build_cache_keyed_only_fails_without_cache_key(mock_run_command, 
_mock_key):
+    params = BuildCiParams(platform="linux/amd64", keyed_cache_only=True)
+
+    assert build_cache(params, output=None).returncode == 1
+    mock_run_command.assert_not_called()
+
+
[email protected](
+    ("returncode", "stdout", "passes"),
+    [
+        pytest.param(
+            0, "github.com/docker/buildx v0.29.1 
a32761aeb3debd39be1eca514af3693af0db334b", True, id="new"
+        ),
+        pytest.param(
+            0, "github.com/docker/buildx v0.10.0 
876462897612d36679153c3414f7689626251501", True, id="min"
+        ),
+        pytest.param(0, "github.com/docker/buildx 0.12.1+ds1 0.12.1+ds1-1", 
True, id="distro-build"),
+        pytest.param(
+            0, "github.com/docker/buildx v0.9.1 
ed00243a0ce2a0aee75311b06e32d33b44729689", False, id="too-old"
+        ),
+        pytest.param(0, "buildah version 1.33.7", False, id="no-version"),
+        pytest.param(1, "", False, id="buildx-missing"),
+    ],
+)
[email protected]("airflow_breeze.utils.docker_command_utils.run_command")
+def test_check_buildx_version(mock_run_command, returncode: int, stdout: str, 
passes: bool):
+    mock_run_command.return_value = subprocess.CompletedProcess(args=[], 
returncode=returncode, stdout=stdout)
+
+    if passes:
+        docker_command_utils.check_buildx_version(quiet=True)
+    else:
+        with pytest.raises(SystemExit):
+            docker_command_utils.check_buildx_version(quiet=True)
+
+
[email protected]("building_images", [True, False])
+def 
test_perform_environment_checks_checks_buildx_only_when_building_images(building_images:
 bool):
+    with ExitStack() as stack:
+        for name in (
+            "check_docker_is_running",
+            "check_container_engine_is_docker",
+            "check_docker_version",
+            "check_docker_compose_version",
+            "check_windows_filesystem_mount",
+            "check_executable_entrypoint_permissions",
+            "check_uv_version",
+        ):
+            stack.enter_context(
+                mock.patch.object(docker_command_utils, name, autospec=True, 
return_value=True)
+            )
+        check_buildx = stack.enter_context(
+            mock.patch.object(docker_command_utils, "check_buildx_version", 
autospec=True)
+        )
+        docker_command_utils.perform_environment_checks.__wrapped__(
+            quiet=True, cleanup_stale_worktrees=False, 
building_images=building_images
+        )
+
+    assert check_buildx.called is building_images
diff --git a/dev/breeze/tests/test_selective_checks.py 
b/dev/breeze/tests/test_selective_checks.py
index 90c9abee495..75a61091e42 100644
--- a/dev/breeze/tests/test_selective_checks.py
+++ b/dev/breeze/tests/test_selective_checks.py
@@ -3775,6 +3775,33 @@ def test_upgrade_to_newer_dependencies(
     assert_outputs_are_printed(expected_outputs, str(stderr))
 
 
[email protected](
+    ("files", "expected"),
+    [
+        pytest.param(("uv.lock",), "true", id="uv-lock"),
+        pytest.param(("providers/amazon/pyproject.toml",), "true", 
id="provider-pyproject"),
+        pytest.param(("pyproject.toml",), "true", id="root-pyproject"),
+        pytest.param(("Dockerfile.ci",), "true", id="dockerfile-ci"),
+        pytest.param(("scripts/docker/install_mysql.sh",), "true", 
id="docker-scripts"),
+        pytest.param(
+            
("dev/breeze/src/airflow_breeze/files/hardened_python_image_digests.json",),
+            "true",
+            id="base-image-digests",
+        ),
+        pytest.param(("airflow-core/src/airflow/models/dag.py",), "false", 
id="regular-source"),
+        pytest.param(("README.md",), "false", id="docs-only"),
+    ],
+)
+def test_ci_image_dependencies_changed(files: tuple[str, ...], expected: str):
+    stderr = SelectiveChecks(
+        files=files,
+        commit_ref=NEUTRAL_COMMIT,
+        github_event=GithubEvents.PULL_REQUEST,
+        default_branch="main",
+    )
+    assert_outputs_are_printed({"ci-image-dependencies-changed": expected}, 
str(stderr))
+
+
 @pytest.mark.parametrize(
     ("files", "pr_labels", "github_event", "expected_constraints", 
"expected_pypi"),
     [
diff --git a/scripts/ci/cleanup_keyed_image_cache.py 
b/scripts/ci/cleanup_keyed_image_cache.py
new file mode 100644
index 00000000000..2eaddc6f836
--- /dev/null
+++ b/scripts/ci/cleanup_keyed_image_cache.py
@@ -0,0 +1,139 @@
+#!/usr/bin/env python3
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Delete keyed CI image cache entries that have not been pushed for a while.
+
+``breeze ci-image build --prepare-buildx-cache`` pushes, next to the shared 
``cache-<platform>`` tag,
+a ``cache-<platform>-<dependency key>`` tag for every set of dependency inputs 
it builds. Those pile
+up with every dependency change, so the versions of the CI image packages 
whose only tags are keyed
+cache tags, and which were last updated before the cutoff, are deleted. Shared 
cache tags, ``latest``
+and anything else are never touched.
+
+Usage: cleanup_keyed_image_cache.py [--days N] [--dry-run]
+Environment: GITHUB_REPOSITORY (``owner/repo``), and a token for ``gh`` with 
``packages: write``.
+"""
+
+from __future__ import annotations
+
+import argparse
+import functools
+import json
+import os
+import re
+import subprocess
+import sys
+from collections.abc import Callable, Iterable
+from datetime import UTC, datetime, timedelta
+from urllib.parse import quote
+
+KEYED_CACHE_TAG = re.compile(r"^cache-linux-(amd64|arm64)-[0-9a-f]{16}$")
+
+
+def get_ci_image_package_pattern(repo: str) -> re.Pattern[str]:
+    return re.compile(rf"^{re.escape(repo)}/[^/]+/ci/python[0-9.]+$")
+
+
+def is_expired_keyed_cache(version: dict, cutoff: datetime) -> bool:
+    tags = version.get("metadata", {}).get("container", {}).get("tags", [])
+    if not tags or not all(KEYED_CACHE_TAG.match(tag) for tag in tags):
+        return False
+    return _parse_time(version["updated_at"]) < cutoff
+
+
+def find_expired_versions(versions: Iterable[dict], cutoff: datetime) -> 
list[dict]:
+    return [version for version in versions if is_expired_keyed_cache(version, 
cutoff)]
+
+
+def _parse_time(value: str) -> datetime:
+    return datetime.fromisoformat(value.replace("Z", "+00:00"))
+
+
+def _gh_api_list(path: str) -> list[dict]:
+    output = subprocess.run(
+        ["gh", "api", "--paginate", path, "--jq", ".[]"], check=True, 
capture_output=True, text=True
+    ).stdout
+    return [json.loads(line) for line in output.splitlines() if line.strip()]
+
+
+def _gh_api_page(path: str, page: int) -> list[dict]:
+    output = subprocess.run(
+        ["gh", "api", f"{path}?per_page=100&page={page}"], check=True, 
capture_output=True, text=True
+    ).stdout
+    return json.loads(output)
+
+
+def get_versions_created_since(fetch_page: Callable[[int], list[dict]], since: 
datetime) -> list[dict]:
+    """
+    Return the versions created at or after ``since``.
+
+    The API lists versions newest first, and a CI image package holds tens of 
thousands of them
+    (every cache push adds manifests), so paging stops at the first page that 
reaches past ``since``.
+    """
+    versions: list[dict] = []
+    page = 1
+    while batch := fetch_page(page):
+        versions.extend(version for version in batch if 
_parse_time(version["created_at"]) >= since)
+        if _parse_time(batch[-1]["created_at"]) < since:
+            break
+        page += 1
+    return versions
+
+
+def main() -> int:
+    parser = argparse.ArgumentParser(description=__doc__, 
formatter_class=argparse.RawTextHelpFormatter)
+    parser.add_argument("--days", type=int, default=30, help="Keep keyed cache 
pushed within this many days")
+    parser.add_argument(
+        "--scan-days",
+        type=int,
+        default=7,
+        help="Look this many days past the cutoff; anything older was deleted 
by earlier daily runs",
+    )
+    parser.add_argument("--dry-run", action="store_true", help="Only print 
what would be deleted")
+    args = parser.parse_args()
+
+    owner, repo = os.environ["GITHUB_REPOSITORY"].split("/", 1)
+    cutoff = datetime.now(UTC) - timedelta(days=args.days)
+    scan_since = cutoff - timedelta(days=args.scan_days)
+    package_pattern = get_ci_image_package_pattern(repo)
+    packages = [
+        package["name"]
+        for package in 
_gh_api_list(f"/orgs/{owner}/packages?package_type=container&per_page=100")
+        if package_pattern.match(package["name"])
+    ]
+    deleted = 0
+    for package in sorted(packages):
+        versions_path = f"/orgs/{owner}/packages/container/{quote(package, 
safe='')}/versions"
+        versions = get_versions_created_since(functools.partial(_gh_api_page, 
versions_path), scan_since)
+        for version in find_expired_versions(versions, cutoff):
+            tags = ", ".join(version["metadata"]["container"]["tags"])
+            print(
+                f"{'Would delete' if args.dry_run else 'Deleting'} 
{package}:{tags} ({version['updated_at']})"
+            )
+            if not args.dry_run:
+                subprocess.run(
+                    ["gh", "api", "-X", "DELETE", 
f"{versions_path}/{version['id']}"],
+                    check=True,
+                    capture_output=True,
+                )
+            deleted += 1
+    print(f"{deleted} keyed cache version(s) older than {args.days} days in 
{len(packages)} package(s).")
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main())
diff --git a/scripts/ci/cleanup_old_image_versions.py 
b/scripts/ci/cleanup_old_image_versions.py
new file mode 100644
index 00000000000..f507ba5b373
--- /dev/null
+++ b/scripts/ci/cleanup_old_image_versions.py
@@ -0,0 +1,201 @@
+#!/usr/bin/env python3
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Slowly delete old untagged versions of the CI and PROD image packages.
+
+Every image or cache push leaves the manifest it replaced behind as an 
untagged package version,
+so a package such as ``airflow/main/ci/python3.11`` holds tens of thousands of 
them. This deletes
+the untagged versions created before the cutoff, oldest first, up to a budget 
per run and with a
+pause between deletions, so that a run stays far below the API rate limit of 
the workflow token
+and the next run continues where this one stopped.
+
+A version is only deleted when no tagged manifest of its package references 
it: the platform
+manifests and attestations of a multi-platform image are untagged versions of 
their own and must
+stay while the image tag that lists them exists.
+
+Usage: cleanup_old_image_versions.py [--days N] [--max-deletions N] [--pause 
SECONDS] [--dry-run]
+Environment: GITHUB_REPOSITORY (``owner/repo``), and a token for ``gh`` with 
``packages: write``.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import subprocess
+import sys
+import time
+import urllib.request
+from datetime import UTC, datetime, timedelta
+from urllib.parse import quote
+
+MANIFEST_MEDIA_TYPES = ", ".join(
+    [
+        "application/vnd.oci.image.index.v1+json",
+        "application/vnd.docker.distribution.manifest.list.v2+json",
+        "application/vnd.oci.image.manifest.v1+json",
+        "application/vnd.docker.distribution.manifest.v2+json",
+    ]
+)
+LINK_LAST_PAGE = re.compile(r'[?&]page=(\d+)>; rel="last"')
+PUSH_WINDOW = timedelta(minutes=5)
+COMMIT_TAG = re.compile(r"^[0-9a-f]{7,40}$")
+
+
+def get_image_package_pattern(repo: str) -> re.Pattern[str]:
+    return re.compile(rf"^{re.escape(repo)}/[^/]+/(ci|prod)/python[0-9.]+$")
+
+
+def _parse_time(value: str) -> datetime:
+    return datetime.fromisoformat(value.replace("Z", "+00:00"))
+
+
+def get_referenced_digests(manifest: dict) -> set[str]:
+    return {entry["digest"] for entry in manifest.get("manifests", []) if 
"digest" in entry}
+
+
+def _get_tags(version: dict) -> list[str]:
+    return version.get("metadata", {}).get("container", {}).get("tags") or []
+
+
+def find_deletable_versions(versions: list[dict], keep: set[str], cutoff: 
datetime) -> list[dict]:
+    """
+    Return the untagged versions of one page that are safe to delete.
+
+    The few long-lived tags have their listed manifests in ``keep``. The 
packages also hold
+    thousands of old per-commit tags, too many to read the manifests of, so an 
untagged version
+    pushed within PUSH_WINDOW of a tagged one, or of the page edges where the 
tagged one may sit
+    on the next page, is taken for part of that image and kept: the manifests 
of a
+    multi-platform image are pushed together with it.
+    """
+    if not versions:
+        return []
+    anchors = [_parse_time(v["created_at"]) for v in versions if _get_tags(v)]
+    anchors += [_parse_time(versions[0]["created_at"]), 
_parse_time(versions[-1]["created_at"])]
+    return [
+        version
+        for version in versions
+        if not _get_tags(version)
+        and version["name"] not in keep
+        and (created := _parse_time(version["created_at"])) < cutoff
+        and all(abs(created - anchor) > PUSH_WINDOW for anchor in anchors)
+    ]
+
+
+def _gh_api(args: list[str]) -> str:
+    return subprocess.run(["gh", "api", *args], check=True, 
capture_output=True, text=True).stdout
+
+
+def _get_last_page(versions_path: str) -> int:
+    headers = _gh_api(["--include", "--method", "GET", 
f"{versions_path}?per_page=100&page=1", "--jq", "."])
+    match = LINK_LAST_PAGE.search(headers)
+    return int(match.group(1)) if match else 1
+
+
+def _get_page(versions_path: str, page: int) -> list[dict]:
+    return json.loads(_gh_api([f"{versions_path}?per_page=100&page={page}"]))
+
+
+def _registry_get(url: str, token: str, accept: str = "application/json") -> 
tuple[dict, str | None, str]:
+    request = urllib.request.Request(url, headers={"Authorization": f"Bearer 
{token}", "Accept": accept})
+    with urllib.request.urlopen(request, timeout=60) as response:
+        return (
+            json.load(response),
+            response.headers.get("Docker-Content-Digest"),
+            response.headers.get("Link", ""),
+        )
+
+
+def collect_keep_set(image: str) -> set[str]:
+    """
+    Return the digests of the long-lived (non-commit) tags of ``image`` and of 
the manifests they list.
+
+    Read from the registry (the images are public) rather than from the 
packages API, which can
+    only find the few tagged versions by listing every one of the tens of 
thousands of versions.
+    """
+    with urllib.request.urlopen(
+        f"https://ghcr.io/token?scope=repository:{image}:pull";, timeout=60
+    ) as response:
+        token = json.load(response)["token"]
+    tags: list[str] = []
+    url: str | None = f"https://ghcr.io/v2/{image}/tags/list?n=1000";
+    while url:
+        listing, _, link = _registry_get(url, token)
+        tags.extend(listing.get("tags") or [])
+        next_page = re.search(r"<([^>]+)>;\s*rel=\"next\"", link)
+        url = f"https://ghcr.io{next_page.group(1)}" if next_page else None
+    keep: set[str] = set()
+    for tag in (tag for tag in tags if not COMMIT_TAG.match(tag)):
+        manifest, digest, _ = _registry_get(
+            f"https://ghcr.io/v2/{image}/manifests/{tag}";, token, 
MANIFEST_MEDIA_TYPES
+        )
+        if digest:
+            keep.add(digest)
+        keep |= get_referenced_digests(manifest)
+    return keep
+
+
+def main() -> int:
+    parser = argparse.ArgumentParser(description=__doc__, 
formatter_class=argparse.RawTextHelpFormatter)
+    parser.add_argument("--days", type=int, default=30, help="Keep versions 
created within this many days")
+    parser.add_argument("--max-deletions", type=int, default=300, help="Stop 
after this many deletions")
+    parser.add_argument("--pause", type=float, default=1.0, help="Seconds to 
wait after each deletion")
+    parser.add_argument("--dry-run", action="store_true", help="Only print 
what would be deleted")
+    args = parser.parse_args()
+
+    owner, repo = os.environ["GITHUB_REPOSITORY"].split("/", 1)
+    cutoff = datetime.now(UTC) - timedelta(days=args.days)
+    package_pattern = get_image_package_pattern(repo)
+    package_listing = _gh_api(
+        ["--paginate", 
f"/orgs/{owner}/packages?package_type=container&per_page=100", "--jq", 
".[].name"]
+    )
+    packages = sorted(name for name in package_listing.split() if 
package_pattern.match(name))
+    budget = args.max_deletions
+    for package in packages:
+        if budget <= 0:
+            break
+        versions_path = f"/orgs/{owner}/packages/container/{quote(package, 
safe='')}/versions"
+        page = _get_last_page(versions_path)
+        if not find_deletable_versions(_get_page(versions_path, page), set(), 
cutoff):
+            continue
+        keep = collect_keep_set(f"{owner}/{package}")
+        # Versions are listed newest first, so walking from the last page goes 
oldest first, and
+        # deleting from a page never moves the versions of the pages before it.
+        while page >= 1 and budget > 0:
+            batch = _get_page(versions_path, page)
+            if not batch or _parse_time(batch[-1]["created_at"]) >= cutoff:
+                break
+            for version in find_deletable_versions(batch, keep, 
cutoff)[:budget]:
+                print(
+                    f"{'Would delete' if args.dry_run else 'Deleting'} "
+                    f"{package}@{version['name']} ({version['created_at']})"
+                )
+                if not args.dry_run:
+                    _gh_api(["-X", "DELETE", 
f"{versions_path}/{version['id']}"])
+                    time.sleep(args.pause)
+                budget -= 1
+            page -= 1
+    print(
+        f"{args.max_deletions - budget} old untagged version(s) {'would be ' 
if args.dry_run else ''}deleted."
+    )
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main())
diff --git a/scripts/tests/ci/test_cleanup_keyed_image_cache.py 
b/scripts/tests/ci/test_cleanup_keyed_image_cache.py
new file mode 100644
index 00000000000..d6b5ac3e0ef
--- /dev/null
+++ b/scripts/tests/ci/test_cleanup_keyed_image_cache.py
@@ -0,0 +1,106 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+import importlib.util
+import sys
+from datetime import UTC, datetime
+from pathlib import Path
+
+import pytest
+
+MODULE_PATH = Path(__file__).resolve().parents[3] / "scripts" / "ci" / 
"cleanup_keyed_image_cache.py"
+CUTOFF = datetime(2026, 10, 16, tzinfo=UTC)
+OLD = "2026-09-01T00:00:00Z"
+RECENT = "2026-11-01T00:00:00Z"
+
+
[email protected]
+def cleanup():
+    module_name = "test_cleanup_keyed_image_cache_module"
+    sys.modules.pop(module_name, None)
+    spec = importlib.util.spec_from_file_location(module_name, MODULE_PATH)
+    assert spec is not None
+    assert spec.loader is not None
+    module = importlib.util.module_from_spec(spec)
+    sys.modules[module_name] = module
+    spec.loader.exec_module(module)
+    return module
+
+
+def _version(tags: list[str], updated_at: str) -> dict:
+    return {"id": 1, "updated_at": updated_at, "metadata": {"container": 
{"tags": tags}}}
+
+
[email protected](
+    ("tags", "updated_at", "expired"),
+    [
+        pytest.param(["cache-linux-amd64-0123456789abcdef"], OLD, True, 
id="old-keyed"),
+        pytest.param(["cache-linux-arm64-0123456789abcdef"], OLD, True, 
id="old-keyed-arm"),
+        pytest.param(["cache-linux-amd64-0123456789abcdef"], RECENT, False, 
id="recent-keyed"),
+        pytest.param(["cache-linux-amd64"], OLD, False, id="shared-cache"),
+        pytest.param(["latest"], OLD, False, id="latest"),
+        pytest.param(
+            ["cache-linux-amd64-0123456789abcdef", "cache-linux-amd64"], OLD, 
False, id="keyed-and-shared"
+        ),
+        pytest.param([], OLD, False, id="untagged"),
+        pytest.param(["cache-linux-amd64-not-a-key"], OLD, False, 
id="not-a-key"),
+    ],
+)
+def test_is_expired_keyed_cache(cleanup, tags, updated_at, expired):
+    assert cleanup.is_expired_keyed_cache(_version(tags, updated_at), CUTOFF) 
is expired
+
+
+def 
test_get_versions_created_since_stops_at_the_first_page_past_since(cleanup):
+    def created(day: int) -> dict:
+        return {"created_at": f"2026-10-{day:02d}T00:00:00Z"}
+
+    pages = {1: [created(30), created(20)], 2: [created(16), created(10)], 3: 
[created(5)]}
+    fetched: list[int] = []
+
+    def fetch_page(page: int) -> list[dict]:
+        fetched.append(page)
+        return pages.get(page, [])
+
+    versions = cleanup.get_versions_created_since(fetch_page, datetime(2026, 
10, 15, tzinfo=UTC))
+
+    assert [v["created_at"][:10] for v in versions] == ["2026-10-30", 
"2026-10-20", "2026-10-16"]
+    assert fetched == [1, 2]
+
+
+def test_get_versions_created_since_stops_on_empty_page(cleanup):
+    fetched: list[int] = []
+
+    def fetch_page(page: int) -> list[dict]:
+        fetched.append(page)
+        return [{"created_at": "2026-11-01T00:00:00Z"}] if page == 1 else []
+
+    assert len(cleanup.get_versions_created_since(fetch_page, CUTOFF)) == 1
+    assert fetched == [1, 2]
+
+
[email protected](
+    ("package", "matches"),
+    [
+        pytest.param("airflow/main/ci/python3.11", True, id="main-ci"),
+        pytest.param("airflow/v3-4-test/ci/python3.14", True, 
id="release-branch-ci"),
+        pytest.param("airflow/main/prod/python3.11", False, id="prod"),
+        pytest.param("other/main/ci/python3.11", False, id="other-repo"),
+    ],
+)
+def test_ci_image_package_pattern(cleanup, package, matches):
+    assert 
bool(cleanup.get_ci_image_package_pattern("airflow").match(package)) is matches
diff --git a/scripts/tests/ci/test_cleanup_old_image_versions.py 
b/scripts/tests/ci/test_cleanup_old_image_versions.py
new file mode 100644
index 00000000000..eae80564278
--- /dev/null
+++ b/scripts/tests/ci/test_cleanup_old_image_versions.py
@@ -0,0 +1,119 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+import importlib.util
+import sys
+from datetime import UTC, datetime
+from pathlib import Path
+
+import pytest
+
+MODULE_PATH = Path(__file__).resolve().parents[3] / "scripts" / "ci" / 
"cleanup_old_image_versions.py"
+CUTOFF = datetime(2026, 10, 16, tzinfo=UTC)
+OLD = "2026-09-01T00:00:00Z"
+RECENT = "2026-11-01T00:00:00Z"
+
+
[email protected]
+def cleanup():
+    module_name = "test_cleanup_old_image_versions_module"
+    sys.modules.pop(module_name, None)
+    spec = importlib.util.spec_from_file_location(module_name, MODULE_PATH)
+    assert spec is not None
+    assert spec.loader is not None
+    module = importlib.util.module_from_spec(spec)
+    sys.modules[module_name] = module
+    spec.loader.exec_module(module)
+    return module
+
+
+def _version(digest: str, created_at: str, tags: list[str] | None = None) -> 
dict:
+    return {"name": digest, "created_at": created_at, "metadata": 
{"container": {"tags": tags or []}}}
+
+
+def _page(*middle: dict) -> list[dict]:
+    """A page, newest first, whose edge versions are far from the versions 
under test."""
+    return [
+        _version("sha256:newest-edge", "2026-09-20T00:00:00Z"),
+        *middle,
+        _version("sha256:oldest-edge", "2026-08-01T00:00:00Z"),
+    ]
+
+
[email protected](
+    ("version", "deletable"),
+    [
+        pytest.param(_version("sha256:old", OLD), True, id="old-untagged"),
+        pytest.param(_version("sha256:recent", RECENT), False, 
id="recent-untagged"),
+        pytest.param(_version("sha256:tagged", OLD, ["latest"]), False, 
id="old-tagged"),
+        pytest.param(_version("sha256:kept", OLD), False, 
id="old-referenced-by-a-long-lived-tag"),
+    ],
+)
+def test_find_deletable_versions(cleanup, version, deletable):
+    deletable_names = {
+        v["name"] for v in cleanup.find_deletable_versions(_page(version), 
{"sha256:kept"}, CUTOFF)
+    }
+
+    assert (version["name"] in deletable_names) is deletable
+
+
+def 
test_find_deletable_versions_keeps_untagged_pushed_with_a_tagged_version(cleanup):
+    page = _page(
+        _version("sha256:commit-image", "2026-09-01T00:00:30Z", 
["0123456789abcdef0123456789abcdef01234567"]),
+        _version("sha256:its-platform-manifest", "2026-09-01T00:00:10Z"),
+        _version("sha256:unrelated", "2026-09-01T01:00:00Z"),
+    )
+
+    assert [v["name"] for v in cleanup.find_deletable_versions(page, set(), 
CUTOFF)] == ["sha256:unrelated"]
+
+
+def test_find_deletable_versions_keeps_versions_near_the_page_edges(cleanup):
+    page = [
+        _version("sha256:edge", OLD),
+        _version("sha256:near-edge", "2026-09-01T00:01:00Z"),
+        _version("sha256:middle", "2026-08-20T00:00:00Z"),
+        _version("sha256:last-edge", "2026-08-01T00:00:00Z"),
+    ]
+
+    assert [v["name"] for v in cleanup.find_deletable_versions(page, set(), 
CUTOFF)] == ["sha256:middle"]
+
+
+def test_get_referenced_digests_lists_index_children(cleanup):
+    index = {
+        "mediaType": "application/vnd.oci.image.index.v1+json",
+        "manifests": [{"digest": "sha256:amd64"}, {"digest": 
"sha256:attestation"}],
+    }
+
+    assert cleanup.get_referenced_digests(index) == {"sha256:amd64", 
"sha256:attestation"}
+
+
+def test_get_referenced_digests_of_single_manifest_is_empty(cleanup):
+    assert cleanup.get_referenced_digests({"layers": [{"digest": 
"sha256:layer"}]}) == set()
+
+
[email protected](
+    ("package", "matches"),
+    [
+        pytest.param("airflow/main/ci/python3.11", True, id="ci"),
+        pytest.param("airflow/v2-11-test/prod/python3.10", True, id="prod"),
+        pytest.param("airflow/main/ci/python3.11/extra", False, id="nested"),
+        pytest.param("airflow-site/main/ci/python3.11", False, 
id="other-repo"),
+    ],
+)
+def test_image_package_pattern(cleanup, package, matches):
+    assert bool(cleanup.get_image_package_pattern("airflow").match(package)) 
is matches

Reply via email to