You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "zozo123 (via GitHub)" <gi...@apache.org> on 2026/10/03 19:14:34 UTC

[PR] Restore the CI image from a snapshot of Docker's data directory [airflow]

zozo123 opened a new pull request, #74173:
URL: https://github.com/apache/airflow/pull/74173

   Every job that prepares the CI image restores the stash and runs `docker image load` on it.
   Docker then unpacks and checksums every layer of the image again, which takes about 100–140 s in
   each of the dozens of jobs in a PR run.
   
   This adds a second way to hand the image over. The build job also saves a copy of the daemon's
   image store (`image/` and `overlay2/` under `/var/lib/docker`), holding only the CI image, with a
   small `.meta` file naming the daemon that wrote it. A job that prepares the CI image restores that
   copy into its stopped, empty daemon with one extraction, and falls back to the existing stash and
   `docker image load` whenever the snapshot does not fit:
   
   - there is no snapshot for the key;
   - the job's daemon has a different version, storage driver, architecture or data root;
   - the daemon already holds images that the restore would drop;
   - the restored image does not run (the store is emptied again first).
   
   The image stash itself is unchanged, so release branches and the other workflows that read it keep
   working. Snapshots use a new stash key, `ci-image-snapshot-v1-*`, and are only taken for the
   per-branch image, not for `image-stash-ref` builds.
   
   ### Measured on GitHub `ubuntu-22.04` runners
   
   These runs used the image as it was before #74076 removed ~800 MB from it. On the current image
   the saving per job should be somewhat smaller (estimated 65–95 s); this PR's own CI run shows the
   real numbers, and I will update them here.
   
   Restoring the published `ghcr.io/apache/airflow/main/ci/python3.10:latest`, with Docker on `/mnt`
   as in CI:
   
   | | Round 1 | Round 2 |
   |---|---|---|
   | `docker image load` of the stash (2.47 GB, zstd) | 113.8 s | 112.5 s |
   | Snapshot restore (2.65 GB): extract + daemon start | 32.5 s | 32.9 s |
   
   Creating the snapshot took 25.5 s.
   
   End to end: two rounds on a fork with the changed action and script ([run 1](https://github.com/zozo123/airflow/actions/runs/36990568450), [run 2](https://github.com/zozo123/airflow/actions/runs/36992717345)).
   One consumer took the snapshot. The other, asking for a stash with no snapshot behind it, took the fallback.
   
   | Sub-step of *Prepare breeze & CI image* | Run 1 | Run 2 |
   |---|---|---|
   | `breeze ci-image load` (fallback, today's path) | 142.6 s | 111.5 s |
   | Snapshot restore: extract, daemon start, `docker run` check | 36.6 s | 33.5 s |
   
   Both consumers end with the same image ID. Both then ran
   `airflow-core/tests/unit/utils/test_helpers.py` and `airflow-core/tests/unit/models/test_dagrun.py`
   through Breeze: 275 passed, 1 xfailed, on each path. Download times vary with the runner, and the
   snapshot is 7% larger than the stash.
   
   The cost is in the build job, which keeps writing the image stash and now also writes the snapshot.
   Taking the snapshot took 25.5 s in the benchmark and 99/84 s in the two end-to-end runs, and stashing
   it 23/27 s. So the build job gets about 1–2 minutes longer, and each job that loads the image gets
   75–106 s shorter: a large saving in runner time, while the wall clock of a run changes by under a
   minute either way. The build job takes the snapshot right after the build, while the new layers may
   still be in the page cache, and after the mount-cache export, since the snapshot drops the build
   cache. This PR's own CI shows what that costs on a freshly built image.
   
   It also stores one extra artifact per CI image build: the snapshot (about 2.6 GB, kept 2 days) next to
   the existing stash. If that storage is a concern, the snapshot can sit behind a workflow input.
   
   Other notes:
   
   - The snapshot key follows the job's Python version, so the switch of the default to 3.11 (#74151)
     needs no change here.
   - The extra 1–2 minutes in the build job stay under the CI duration monitor's 3-minute absolute
     floor for per-job alerts (`scripts/ci/analyze_ci_job_durations.py`, `JOB_MIN_ABS_INCREASE_MINUTES`).
   - The draft #73095 edits the same restore step in `prepare_breeze_and_image`; whichever lands
     second needs a small rebase.
   
   ### Checks run
   
   - `scripts/tests/ci/test_docker_data_root_snapshot.py` (7 tests) drives the script with fake
     `docker`, `sudo` and `zstd`, covering every fallback decision and what `create` keeps. Removing
     the daemon check makes the "other daemon" case fail.
   - Rebased on main f070997ba6: the 7 tests pass, and `prek run --stage pre-commit` and
     `--stage manual` pass, including actionlint and shellcheck.
   
   ---
   
   ##### Was generative AI tooling used to co-author this PR?
   
   - [X] Yes — Claude Code (Opus 5.5)
   
   Generated-by: Claude Code (Opus 5.5) following [the guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions)
   
   🤖 Generated with [Claude Code](https://claude.com/claude-code)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Restore the CI image from a snapshot of Docker's data directory [airflow]

Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #74173:
URL: https://github.com/apache/airflow/pull/74173#discussion_r4175214392


##########
.github/workflows/ci-image-build.yml:
##########
@@ -321,6 +321,62 @@
           docker rmi "${CACHE_FROM_IMAGE}"
         shell: bash
         if: always() && env.CACHE_FROM_IMAGE != ''
+      - name: "Export mount cache ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"
+        env:
+          PYTHON_MAJOR_MINOR_VERSION: ${{ env.PYTHON_MAJOR_MINOR_VERSION }}
+        run: >
+          breeze ci-image export-mount-cache
+          --cache-file /tmp/ci-cache-mount-save-v3-${PYTHON_MAJOR_MINOR_VERSION}.tar.gz
+        if: >
+          inputs.upload-mount-cache-artifact == 'true' &&
+          steps.stashed-image.outputs.reusable != 'true'
+      - name: >
+          Stash cache mount ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}
+          ${{ inputs.image-stash-ref != '' && format('for ref {0}', inputs.image-stash-ref) || '' }}
+        uses: apache/infrastructure-actions/stash/save@61dcea11f19e2bbe1263f14d72235e8da17d3ad0  # save/v1.0.0
+        with:
+          key: "ci-cache-mount-save-v3-${{ inputs.platform }}-${{ env.PYTHON_MAJOR_MINOR_VERSION }}\
+            ${{ inputs.image-stash-ref != '' && format('-{0}', inputs.image-stash-ref) || '' }}"
+          path: "/tmp/ci-cache-mount-save-v3-${{ env.PYTHON_MAJOR_MINOR_VERSION }}.tar.gz"
+          if-no-files-found: 'error'
+          # A ref's cache is read by the next publish of that same ref, days rather than hours
+          # later, so it gets the retention the ref's image gets rather than the branch's.
+          retention-days: ${{ inputs.image-stash-ref != '' && '6' || '2' }}
+        if: >
+          inputs.upload-mount-cache-artifact == 'true' &&
+          steps.stashed-image.outputs.reusable != 'true'
+      # Every job that prepares the CI image would otherwise `docker image load` the stash below,
+      # unpacking and checksumming each layer again; a copy of the image store restores with one
+      # extraction. Taken while the freshly built layers are still in the page cache, and after the
+      # mount cache export, as it drops the build cache that the export reads.
+      # Only PR-scoped snapshots: arbitrary checkout refs in privileged dispatch/scheduled
+      # workflows must never publish a snapshot into the default branch's cache scope.
+      - name: "Snapshot CI image ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"
+        id: snapshot-export
+        continue-on-error: true
+        env:
+          PLATFORM: ${{ inputs.platform }}
+        run: >
+          ./scripts/ci/docker_data_root_snapshot.sh create
+          "/mnt/ci-image-snapshot-${PLATFORM//\//_}-${PYTHON_MAJOR_MINOR_VERSION}.tar.zst"
+        shell: bash
+        if: >
+          github.event_name == 'pull_request' &&
+          inputs.upload-image-artifact == 'true' && inputs.image-stash-ref == '' &&
+          steps.stashed-image.outputs.reusable != 'true'
+      - name: "Stash CI image snapshot ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"

Review Comment:
   ## CodeQL / Cache Poisoning via execution of untrusted code
   
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([schedule](2)).
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([workflow_dispatch](3)).
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([schedule](4)).
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([workflow_dispatch](5)).
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([workflow_dispatch](6)).
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([workflow_dispatch](7)).
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([workflow_dispatch](8)).
   
   [Show more details](https://github.com/apache/airflow/security/code-scanning/670)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Accelerate CI image materialization and dependency reuse [airflow]

Posted by "zozo123 (via GitHub)" <gi...@apache.org>.
zozo123 commented on PR #74173:
URL: https://github.com/apache/airflow/pull/74173#issuecomment-5992319807

   @shahar1 — following up on your critical-path objection with a deeper timing analysis of the current `f53486a4` design.
   
   The initial measurement above is encouraging, but it does **not yet establish a pure wall-clock win**. Comparing [treatment attempt 1](https://github.com/apache/airflow/actions/runs/37236836509) with [one successful baseline attempt with the same active job names](https://github.com/apache/airflow/actions/runs/37267385329):
   
   | Question | Observed result |
   |---|---|
   | Are consumers held behind a separate snapshot producer? | The current builder includes snapshot creation/upload. Median consumer scheduling gap after it finishes is 3s in both runs. |
   | Does that mean consumer delay is eliminated? | No. Median consumer start from workflow creation is 652s versus 583s: **69s later**. Builder duration is 55s longer, and initial workflow dispatch is 19s longer. These are overlapping timeline observations, not additive causal estimates. |
   | When are consumers actually ready to test? | Pairing the same 79 jobs and comparing the end of the image-preparation step relative to workflow creation gives a median shift of **16s earlier**. 49 consumers become ready earlier and 30 later; individual shifts range from 175s earlier to 155s later. This is a more direct measure of the tradeoff than the post-builder scheduling gap. |
   | What is the snapshot's measured cost? | Creation 73s + upload 23s = **96s of builder execution**. All 79 consumers successfully unpacked the snapshot and skipped the legacy image-load action. |
   | What saving is local to consumer preparation? | Summing paired prep durations gives **110.6 fewer runner-minutes**. Subtracting the 1.6-minute snapshot creation/upload cost leaves **109.0 minutes** for this limited prep-plus-snapshot accounting. It excludes other builder and job changes. |
   | What happened across the whole workflow? | Total observed runner time fell **69.6 minutes (about 5.3%)**, while workflow wall time fell **87s (about 2.8%)**. The local prep accounting exceeds the total saving by about 39.4 minutes, showing that changes elsewhere offset some of it. |
   | What finished last? | The same provider compatibility test job finished last in both runs. Its completion determines the measured all-job workflow finish; faster prep across many parallel consumers does not automatically translate into the same wall-clock saving. |
   
   The important distinction is **consumer start → image-ready → workflow finish**. Moving creation into the builder removes the separate-producer structure, but retains a 96s snapshot cost on the builder path. In this comparison, faster preparation offsets the later start for the median consumer, with mixed outcomes across jobs. The earlier reported ~236s delay and the current observed 69s are from different comparisons; their difference should not be presented as a controlled measurement of the fix.
   
   Limits: this is **one treatment run versus one exact-matrix baseline**, not 79 independent experiments. Source changes, runner performance, cache state, dispatch and test variance can explain part of the differences. The 3s post-builder gap does not prove that every consumer's entire dependency chain is unchanged. Workflow finish covers all executed jobs in this AMD workflow, not verified branch-required checks or every workflow on the PR. Runner-minutes are execution time, not a billing estimate. The dependency preinstallation stage rebuilt in 28.7s; this run does not demonstrate warm-cache dependency-layer reuse.
   
   A stronger acceptance experiment would interleave baseline and treatment on the same source/test matrix, keep runner labels and cache conditions comparable, and collect at least 3–5 full attempts per variant. Report per-run paired image-ready shifts, all-job wall time, total runner time and snapshot restore outcomes; analyze warm-cache reruns separately. Test dependency reuse separately with a warm-cache source-only change followed by a lockfile change. The present evidence supports the preparation saving and successful restores; the net wall-clock/weekly ROI claim still needs replication.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Accelerate CI image materialization with same-run snapshots [airflow]

Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on code in PR #74173:
URL: https://github.com/apache/airflow/pull/74173#discussion_r4307907858


##########
scripts/ci/docker_data_root_snapshot.sh:
##########
@@ -0,0 +1,161 @@
+#!/usr/bin/env bash
+# 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.
+
+# Moves the CI image between jobs as a copy of the Docker data directory that holds it, so a job
+# restores it with one extraction instead of `docker image load` unpacking and checksumming every
+# layer again.
+#
+#   docker_data_root_snapshot.sh create SNAPSHOT_FILE
+#       Creates the snapshot after the builder publishes its caches.
+#   docker_data_root_snapshot.sh restore SNAPSHOT_FILE
+#       Restores the image. Incompatible snapshots leave the daemon untouched. Failed
+#       materialization cleans partial image state and restarts Docker for the normal stash path.
+set -euo pipefail
+
+DATA_ROOT="/var/lib/docker"
+DAEMON_STOPPED=false
+RESTORE_IN_PROGRESS=false
+RESTORE_FILE=""
+
+function cleanup_daemon() {
+    local result=$?
+    trap - EXIT
+    if [[ -n "${RESTORE_FILE}" ]]; then
+        rm -f "${RESTORE_FILE}" "${RESTORE_FILE}.meta"
+    fi
+    if [[ "${RESTORE_IN_PROGRESS}" == true ]]; then
+        stop_daemon
+        remove_image_store
+        start_daemon
+    elif [[ "${DAEMON_STOPPED}" == true ]]; then
+        start_daemon
+    fi
+    exit "${result}"
+}
+trap cleanup_daemon EXIT
+
+function check_supported_daemon() {
+    local daemon=$1
+    local _ driver root
+    read -r _ driver _ root <<< "${daemon}"
+    if [[ "${driver}" != overlay2 || "${root}" != "${DATA_ROOT}" ]]; then
+        echo "::warning::Unsupported Docker image store; skipping snapshot: ${daemon}"
+        exit 3
+    fi
+}
+
+# A data directory is only readable by the daemon version and storage driver that wrote it.
+function daemon_fingerprint() {
+    docker info --format '{{.ServerVersion}} {{.Driver}} {{.Architecture}} {{.DockerRootDir}}'
+}
+
+function stop_daemon() {
+    DAEMON_STOPPED=true
+    sudo systemctl stop docker.socket docker
+}
+
+function start_daemon() {
+    sudo systemctl start docker
+    DAEMON_STOPPED=false
+}
+
+function remove_image_store() {
+    sudo rm -rf "${DATA_ROOT}/image" "${DATA_ROOT}/overlay2"
+}
+
+function create_snapshot() {
+    local snapshot_file="${1}"
+    local daemon image_id
+    daemon="$(daemon_fingerprint)"
+    check_supported_daemon "${daemon}"
+    image_id="$(docker images --quiet --filter 'label=org.apache.airflow.image=airflow-ci' | sort -u)"
+    if [[ -z "${image_id}" || "${image_id}" == *$'\n'* ]]; then
+        echo "Expected exactly one CI image in the daemon, found: '${image_id}'" >&2
+        exit 1
+    fi
+    docker ps --all --quiet | xargs --no-run-if-empty docker rm --force >/dev/null
+    docker images --quiet | sort -u | {
+        grep --invert-match --fixed-strings --line-regexp "${image_id}" || true
+    } | xargs --no-run-if-empty docker rmi --force >/dev/null
+    docker builder prune --all --force >/dev/null
+    printf '%s %s %s\n' "${daemon}" "${image_id}" "$(git rev-parse HEAD)" \
+        > "${snapshot_file}.meta"
+    stop_daemon
+    sudo tar --directory "${DATA_ROOT}" --xattrs --acls --numeric-owner \
+        --create --file - image overlay2 \
+        | zstd -3 -T0 --quiet --force -o "${snapshot_file}"
+    start_daemon
+}
+
+function restore_snapshot() {
+    local snapshot_file="${1}"
+    RESTORE_FILE="${snapshot_file}"
+    local -a meta
+    local image_id snapshot_fingerprint daemon existing_images existing_containers
+    if [[ ! -f "${snapshot_file}" || ! -f "${snapshot_file}.meta" ]]; then
+        echo "No snapshot at ${snapshot_file}"
+        exit 2
+    fi
+    read -r -a meta < "${snapshot_file}.meta"
+    if [[ ${#meta[@]} != 6 ]]; then
+        echo "Invalid snapshot metadata"
+        exit 3
+    fi
+    if [[ "${meta[5]}" != "$(git rev-parse HEAD)" ]]; then
+        echo "Snapshot belongs to a different checkout revision"
+        exit 3
+    fi
+    image_id="${meta[4]}"
+    snapshot_fingerprint="${meta[*]:0:4}"
+    daemon="$(daemon_fingerprint)"
+    check_supported_daemon "${daemon}"
+    if [[ "${snapshot_fingerprint}" != "${daemon}" ]]; then
+        echo "::warning::Snapshot daemon fingerprint mismatch: '${snapshot_fingerprint}' != '${daemon}'"
+        exit 3
+    fi
+    existing_images="$(docker images --all --quiet)"
+    existing_containers="$(docker ps --all --quiet)"
+    if [[ -n "${existing_images}" || -n "${existing_containers}" ]]; then
+        echo "The daemon already holds images, which restoring the snapshot would drop"
+        exit 3
+    fi
+    stop_daemon
+    RESTORE_IN_PROGRESS=true
+    remove_image_store
+    zstd -d -T0 --quiet --stdout "${snapshot_file}" \
+        | sudo tar --directory "${DATA_ROOT}" --xattrs --acls --numeric-owner --extract --file -

Review Comment:
   **Extended attributes are dropped on restore.** GNU tar with `--xattrs` but no `--xattrs-include` restores only `user.*` attributes. I checked in an `ubuntu:24.04` container: a binary with `cap_net_raw=ep` archived with these flags comes back with no capabilities, and adding `--xattrs-include='*'` on extract brings `security.capability` back. overlay2 keeps its opaque-directory markers in `trusted.overlay.opaque`, which are filtered the same way, so a directory that a layer deleted and recreated shows the lower layers' contents again.
   
   ```suggestion
           | sudo tar --directory "${DATA_ROOT}" --xattrs --xattrs-include='*' --acls --numeric-owner --extract --file -
   ```



##########
scripts/ci/docker_data_root_snapshot.sh:
##########
@@ -0,0 +1,161 @@
+#!/usr/bin/env bash
+# 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.
+
+# Moves the CI image between jobs as a copy of the Docker data directory that holds it, so a job
+# restores it with one extraction instead of `docker image load` unpacking and checksumming every
+# layer again.
+#
+#   docker_data_root_snapshot.sh create SNAPSHOT_FILE
+#       Creates the snapshot after the builder publishes its caches.
+#   docker_data_root_snapshot.sh restore SNAPSHOT_FILE
+#       Restores the image. Incompatible snapshots leave the daemon untouched. Failed
+#       materialization cleans partial image state and restarts Docker for the normal stash path.
+set -euo pipefail
+
+DATA_ROOT="/var/lib/docker"
+DAEMON_STOPPED=false
+RESTORE_IN_PROGRESS=false
+RESTORE_FILE=""
+
+function cleanup_daemon() {
+    local result=$?
+    trap - EXIT
+    if [[ -n "${RESTORE_FILE}" ]]; then
+        rm -f "${RESTORE_FILE}" "${RESTORE_FILE}.meta"
+    fi
+    if [[ "${RESTORE_IN_PROGRESS}" == true ]]; then
+        stop_daemon
+        remove_image_store
+        start_daemon
+    elif [[ "${DAEMON_STOPPED}" == true ]]; then
+        start_daemon
+    fi
+    exit "${result}"
+}
+trap cleanup_daemon EXIT
+
+function check_supported_daemon() {
+    local daemon=$1
+    local _ driver root
+    read -r _ driver _ root <<< "${daemon}"
+    if [[ "${driver}" != overlay2 || "${root}" != "${DATA_ROOT}" ]]; then
+        echo "::warning::Unsupported Docker image store; skipping snapshot: ${daemon}"
+        exit 3
+    fi
+}
+
+# A data directory is only readable by the daemon version and storage driver that wrote it.
+function daemon_fingerprint() {
+    docker info --format '{{.ServerVersion}} {{.Driver}} {{.Architecture}} {{.DockerRootDir}}'
+}
+
+function stop_daemon() {
+    DAEMON_STOPPED=true
+    sudo systemctl stop docker.socket docker
+}
+
+function start_daemon() {
+    sudo systemctl start docker
+    DAEMON_STOPPED=false
+}
+
+function remove_image_store() {
+    sudo rm -rf "${DATA_ROOT}/image" "${DATA_ROOT}/overlay2"
+}
+
+function create_snapshot() {
+    local snapshot_file="${1}"
+    local daemon image_id
+    daemon="$(daemon_fingerprint)"
+    check_supported_daemon "${daemon}"
+    image_id="$(docker images --quiet --filter 'label=org.apache.airflow.image=airflow-ci' | sort -u)"
+    if [[ -z "${image_id}" || "${image_id}" == *$'\n'* ]]; then
+        echo "Expected exactly one CI image in the daemon, found: '${image_id}'" >&2
+        exit 1
+    fi
+    docker ps --all --quiet | xargs --no-run-if-empty docker rm --force >/dev/null
+    docker images --quiet | sort -u | {
+        grep --invert-match --fixed-strings --line-regexp "${image_id}" || true
+    } | xargs --no-run-if-empty docker rmi --force >/dev/null
+    docker builder prune --all --force >/dev/null
+    printf '%s %s %s\n' "${daemon}" "${image_id}" "$(git rev-parse HEAD)" \
+        > "${snapshot_file}.meta"
+    stop_daemon
+    sudo tar --directory "${DATA_ROOT}" --xattrs --acls --numeric-owner \
+        --create --file - image overlay2 \
+        | zstd -3 -T0 --quiet --force -o "${snapshot_file}"
+    start_daemon
+}
+
+function restore_snapshot() {
+    local snapshot_file="${1}"
+    RESTORE_FILE="${snapshot_file}"
+    local -a meta
+    local image_id snapshot_fingerprint daemon existing_images existing_containers
+    if [[ ! -f "${snapshot_file}" || ! -f "${snapshot_file}.meta" ]]; then
+        echo "No snapshot at ${snapshot_file}"
+        exit 2
+    fi
+    read -r -a meta < "${snapshot_file}.meta"
+    if [[ ${#meta[@]} != 6 ]]; then
+        echo "Invalid snapshot metadata"
+        exit 3
+    fi
+    if [[ "${meta[5]}" != "$(git rev-parse HEAD)" ]]; then
+        echo "Snapshot belongs to a different checkout revision"
+        exit 3
+    fi
+    image_id="${meta[4]}"
+    snapshot_fingerprint="${meta[*]:0:4}"
+    daemon="$(daemon_fingerprint)"
+    check_supported_daemon "${daemon}"
+    if [[ "${snapshot_fingerprint}" != "${daemon}" ]]; then
+        echo "::warning::Snapshot daemon fingerprint mismatch: '${snapshot_fingerprint}' != '${daemon}'"
+        exit 3
+    fi
+    existing_images="$(docker images --all --quiet)"
+    existing_containers="$(docker ps --all --quiet)"
+    if [[ -n "${existing_images}" || -n "${existing_containers}" ]]; then
+        echo "The daemon already holds images, which restoring the snapshot would drop"
+        exit 3
+    fi
+    stop_daemon
+    RESTORE_IN_PROGRESS=true
+    remove_image_store
+    zstd -d -T0 --quiet --stdout "${snapshot_file}" \
+        | sudo tar --directory "${DATA_ROOT}" --xattrs --acls --numeric-owner --extract --file -
+    start_daemon
+    if ! docker run --rm --entrypoint /bin/bash "${image_id}" -c true; then

Review Comment:
   `bash -c true` still passes with the attributes above missing, so a damaged restore never falls back to the stash. It would be worth checking more after the restore, for example comparing `docker image inspect` with the meta and checking a file that is known to be removed in a later layer.



##########
.github/actions/prepare_breeze_and_image/action.yml:
##########
@@ -79,6 +79,33 @@ runs:
       run: |
         echo "Checking free space!"
         df -H
+    - name: "Restore CI image snapshot ${{ inputs.platform }}:${{ inputs.python }}"
+      continue-on-error: true
+      uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c  # v8.0.1

Review Comment:
   **The multi-GB snapshot is downloaded before the cheap checks** (empty daemon, daemon fingerprint, driver). When any of them rejects it, the job then downloads the stash as well. Uploading the `.meta` as a separate small artifact and checking it first would avoid that.



##########
.github/actions/prepare_breeze_and_image/action.yml:
##########
@@ -79,6 +79,33 @@ runs:
       run: |
         echo "Checking free space!"
         df -H
+    - name: "Restore CI image snapshot ${{ inputs.platform }}:${{ inputs.python }}"
+      continue-on-error: true
+      uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c  # v8.0.1
+      with:
+        name: >-
+          ci-image-snapshot-v1-${{ inputs.python }}-${{
+          inputs.platform == 'linux/amd64' && 'amd64' || 'arm64' }}
+        path: "/mnt/"
+      id: restore-snapshot
+      if: >
+        github.event_name == 'pull_request' &&
+        inputs.image-type == 'ci' && inputs.image-stash-ref == ''

Review Comment:
   When no snapshot exists (builder skipped, create failed, retention expired), `download-artifact` still runs and adds an error annotation in each of the ~30 jobs using this action, even though they stay green. Gating it on the builder's snapshot step output would avoid the noise.



##########
scripts/ci/docker_data_root_snapshot.sh:
##########
@@ -0,0 +1,161 @@
+#!/usr/bin/env bash
+# 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.
+
+# Moves the CI image between jobs as a copy of the Docker data directory that holds it, so a job
+# restores it with one extraction instead of `docker image load` unpacking and checksumming every
+# layer again.
+#
+#   docker_data_root_snapshot.sh create SNAPSHOT_FILE
+#       Creates the snapshot after the builder publishes its caches.
+#   docker_data_root_snapshot.sh restore SNAPSHOT_FILE
+#       Restores the image. Incompatible snapshots leave the daemon untouched. Failed
+#       materialization cleans partial image state and restarts Docker for the normal stash path.
+set -euo pipefail
+
+DATA_ROOT="/var/lib/docker"
+DAEMON_STOPPED=false
+RESTORE_IN_PROGRESS=false
+RESTORE_FILE=""
+
+function cleanup_daemon() {
+    local result=$?
+    trap - EXIT
+    if [[ -n "${RESTORE_FILE}" ]]; then
+        rm -f "${RESTORE_FILE}" "${RESTORE_FILE}.meta"
+    fi
+    if [[ "${RESTORE_IN_PROGRESS}" == true ]]; then
+        stop_daemon
+        remove_image_store
+        start_daemon
+    elif [[ "${DAEMON_STOPPED}" == true ]]; then
+        start_daemon
+    fi
+    exit "${result}"
+}
+trap cleanup_daemon EXIT
+
+function check_supported_daemon() {
+    local daemon=$1
+    local _ driver root
+    read -r _ driver _ root <<< "${daemon}"
+    if [[ "${driver}" != overlay2 || "${root}" != "${DATA_ROOT}" ]]; then

Review Comment:
   With the containerd image store (Docker 29+), the driver is no longer `overlay2`, so every create and restore exits 3 with only a warning, while the builder still pays for pruning and the upload. A hard signal, or skipping the upload in that case, would make that visible.



##########
.github/workflows/ci-image-build.yml:
##########
@@ -401,3 +401,35 @@ jobs:
           steps.stashed-image.outputs.reusable != 'true'
       - name: "Check disk space after build"
         run: df -H
+
+      # Snapshot only after cache publication: pruning removes the mount-cache image.
+      - name: "Snapshot CI image ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"
+        id: snapshot-export
+        continue-on-error: true
+        timeout-minutes: 5
+        env:
+          # Docker is bind-mounted from /mnt on AMD; write the archive on the root disk.
+          SNAPSHOT_FILE: >-
+            ${{ runner.temp }}/ci-image-snapshot-${{
+            inputs.platform == 'linux/amd64' && 'linux_amd64' || 'linux_arm64'
+            }}-${{ env.PYTHON_MAJOR_MINOR_VERSION }}.tar.zst
+        run: |
+          ./scripts/ci/docker_data_root_snapshot.sh create "${SNAPSHOT_FILE}"
+        shell: bash
+        if: >
+          github.event_name == 'pull_request' &&
+          inputs.upload-image-artifact == 'true' && inputs.image-stash-ref == '' &&
+          (inputs.checkout-ref == '' || inputs.checkout-ref == github.sha)
+      - name: "Upload CI image snapshot ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"

Review Comment:
   Every PR run now uploads a second multi-GB copy of each CI image (per Python × platform) as a run artifact, on top of the stash. That is part of the cost the measurements above should weigh.



##########
.github/actions/prepare_breeze_and_image/action.yml:
##########
@@ -98,3 +126,4 @@ runs:
       run: >
         breeze ${IMAGE_TYPE}-image load --platform "${PLATFORM}" --python "${PYTHON}" --image-file-dir "/mnt"
       shell: bash
+      if: steps.snapshot.outputs.restored != 'true'

Review Comment:
   A successful restore skips `breeze ci-image load`, and with it breeze's environment checks and the image diagnostics in the logs, so problems that load would catch surface later and less clearly.



##########
.github/workflows/ci-image-build.yml:
##########
@@ -401,3 +401,35 @@ jobs:
           steps.stashed-image.outputs.reusable != 'true'
       - name: "Check disk space after build"
         run: df -H
+
+      # Snapshot only after cache publication: pruning removes the mount-cache image.
+      - name: "Snapshot CI image ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"
+        id: snapshot-export
+        continue-on-error: true
+        timeout-minutes: 5
+        env:
+          # Docker is bind-mounted from /mnt on AMD; write the archive on the root disk.
+          SNAPSHOT_FILE: >-
+            ${{ runner.temp }}/ci-image-snapshot-${{
+            inputs.platform == 'linux/amd64' && 'linux_amd64' || 'linux_arm64'
+            }}-${{ env.PYTHON_MAJOR_MINOR_VERSION }}.tar.zst
+        run: |
+          ./scripts/ci/docker_data_root_snapshot.sh create "${SNAPSHOT_FILE}"
+        shell: bash
+        if: >
+          github.event_name == 'pull_request' &&
+          inputs.upload-image-artifact == 'true' && inputs.image-stash-ref == '' &&
+          (inputs.checkout-ref == '' || inputs.checkout-ref == github.sha)
+      - name: "Upload CI image snapshot ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"
+        continue-on-error: true
+        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a  # v7.0.1
+        with:
+          name: >-
+            ci-image-snapshot-v1-${{ env.PYTHON_MAJOR_MINOR_VERSION }}-${{
+            inputs.platform == 'linux/amd64' && 'amd64' || 'arm64' }}
+          path: "${{ runner.temp }}/ci-image-snapshot-*-${{ env.PYTHON_MAJOR_MINOR_VERSION }}.tar.zst*"
+          if-no-files-found: 'error'

Review Comment:
   **Re-runs use a stale snapshot.** Without `overwrite: true`, a re-run of the builder fails here with 409, `continue-on-error` hides it, and consumers keep restoring attempt 1's snapshot because the commit matches.
   
   ```suggestion
             if-no-files-found: 'error'
             overwrite: true
   ```



##########
.github/actions/prepare_breeze_and_image/action.yml:
##########
@@ -79,6 +79,33 @@ runs:
       run: |
         echo "Checking free space!"
         df -H
+    - name: "Restore CI image snapshot ${{ inputs.platform }}:${{ inputs.python }}"
+      continue-on-error: true
+      uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c  # v8.0.1
+      with:
+        name: >-
+          ci-image-snapshot-v1-${{ inputs.python }}-${{
+          inputs.platform == 'linux/amd64' && 'amd64' || 'arm64' }}
+        path: "/mnt/"
+      id: restore-snapshot
+      if: >
+        github.event_name == 'pull_request' &&
+        inputs.image-type == 'ci' && inputs.image-stash-ref == ''
+    # Falls back to the image stash below whenever the snapshot does not fit this runner's daemon.
+    - name: "Unpack CI image snapshot ${{ inputs.platform }}:${{ inputs.python }}"
+      id: snapshot

Review Comment:
   **No timeout on the unpack step**, so a hang in `systemctl stop/start docker` or in the extraction blocks the job until its overall timeout. A half-restored data-root cannot fall back to the stash anyway, so failing fast is the best this step can do (the create step has 5 minutes).
   
   ```suggestion
         id: snapshot
         timeout-minutes: 10
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Accelerate CI image materialization and dependency reuse [airflow]

Posted by "zozo123 (via GitHub)" <gi...@apache.org>.
zozo123 commented on PR #74173:
URL: https://github.com/apache/airflow/pull/74173#issuecomment-5992554113

   @shahar1 — measured the current `f53486a4` design against a successful baseline with the same active job names. **Verdict: this run demonstrates useful CI savings, and supports keeping this optimization.** Both total runner time and workflow wall time improved.
   
   | Metric | Matched baseline | This PR | Improvement |
   |---|---:|---:|---:|
   | Median CI-image preparation per consumer | 210s | 127s | **83s faster (39.5%)** |
   | Total runner execution time | 1,306.0 min | 1,236.4 min | **69.6 runner-minutes saved (5.3%)** |
   | AMD workflow wall time | 51m 14s | 49m 47s | **87s faster (2.8%)** |
   | Median gap from CI builder completion to consumer start | 3s | 3s | No increase |
   
   **All 79 active CI-image consumers successfully restored the snapshot and skipped the legacy image-load action.** Snapshot creation took 73s and upload took 23s; the total workflow numbers above already include that 96s overhead.
   
   The critical-path tradeoff is also favorable for the median consumer in this comparison: consumers started 69s later relative to workflow creation, but their faster image preparation meant the median paired job reached the end of preparation **16s earlier**. Across all 79 paired consumers, preparation used **110.6 fewer runner-minutes**. The total workflow saving is 69.6 minutes after accounting for every executed job, including the builder.
   
   Sources: [current-head run, attempt 1](https://github.com/apache/airflow/actions/runs/37236836509) · [matched baseline run, attempt 1](https://github.com/apache/airflow/actions/runs/37267385329). Measurements use GitHub Actions job/step timestamps and consumer action outcomes. Wall time is workflow creation to the last executed job completing; runner time is the sum of executed job durations.
   
   This is one treatment run and one exact-matrix baseline, so the percentages describe this comparison rather than a guaranteed result for every PR. The dependency-layer cache saving is separate and not included as a demonstrated benefit here. Additional repetitions would establish consistency, but the measured result is already positive: **faster preparation, less runner time, and a faster completed workflow.**
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Restore the CI image from a snapshot of Docker's data directory [airflow]

Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #74173:
URL: https://github.com/apache/airflow/pull/74173#discussion_r4174491243


##########
.github/workflows/ci-image-build.yml:
##########
@@ -321,6 +321,55 @@
           docker rmi "${CACHE_FROM_IMAGE}"
         shell: bash
         if: always() && env.CACHE_FROM_IMAGE != ''
+      - name: "Export mount cache ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"
+        env:
+          PYTHON_MAJOR_MINOR_VERSION: ${{ env.PYTHON_MAJOR_MINOR_VERSION }}
+        run: >
+          breeze ci-image export-mount-cache
+          --cache-file /tmp/ci-cache-mount-save-v3-${PYTHON_MAJOR_MINOR_VERSION}.tar.gz
+        if: >
+          inputs.upload-mount-cache-artifact == 'true' &&
+          steps.stashed-image.outputs.reusable != 'true'
+      - name: >
+          Stash cache mount ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}
+          ${{ inputs.image-stash-ref != '' && format('for ref {0}', inputs.image-stash-ref) || '' }}
+        uses: apache/infrastructure-actions/stash/save@61dcea11f19e2bbe1263f14d72235e8da17d3ad0  # save/v1.0.0
+        with:
+          key: "ci-cache-mount-save-v3-${{ inputs.platform }}-${{ env.PYTHON_MAJOR_MINOR_VERSION }}\
+            ${{ inputs.image-stash-ref != '' && format('-{0}', inputs.image-stash-ref) || '' }}"
+          path: "/tmp/ci-cache-mount-save-v3-${{ env.PYTHON_MAJOR_MINOR_VERSION }}.tar.gz"
+          if-no-files-found: 'error'
+          # A ref's cache is read by the next publish of that same ref, days rather than hours
+          # later, so it gets the retention the ref's image gets rather than the branch's.
+          retention-days: ${{ inputs.image-stash-ref != '' && '6' || '2' }}
+        if: >
+          inputs.upload-mount-cache-artifact == 'true' &&
+          steps.stashed-image.outputs.reusable != 'true'
+      # Every job that prepares the CI image would otherwise `docker image load` the stash below,
+      # unpacking and checksumming each layer again; a copy of the image store restores with one
+      # extraction. Taken while the freshly built layers are still in the page cache, and after the
+      # mount cache export, as it drops the build cache that the export reads.
+      - name: "Snapshot CI image ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"
+        env:
+          PLATFORM: ${{ inputs.platform }}
+        run: >
+          ./scripts/ci/docker_data_root_snapshot.sh create
+          "/mnt/ci-image-snapshot-${PLATFORM//\//_}-${PYTHON_MAJOR_MINOR_VERSION}.tar.zst"
+        shell: bash
+        if: >
+          inputs.upload-image-artifact == 'true' && inputs.image-stash-ref == '' &&
+          steps.stashed-image.outputs.reusable != 'true'
+      - name: "Stash CI image snapshot ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"

Review Comment:
   ## CodeQL / Cache Poisoning via execution of untrusted code
   
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([schedule](2)).
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([workflow_dispatch](3)).
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([schedule](4)).
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([workflow_dispatch](5)).
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([workflow_dispatch](6)).
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([workflow_dispatch](7)).
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([workflow_dispatch](8)).
   
   [Show more details](https://github.com/apache/airflow/security/code-scanning/669)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Restore the CI image from a snapshot of Docker's data directory [airflow]

Posted by "shahar1 (via GitHub)" <gi...@apache.org>.
shahar1 commented on code in PR #74173:
URL: https://github.com/apache/airflow/pull/74173#discussion_r4178551814


##########
.github/workflows/ci-image-build.yml:
##########
@@ -401,3 +401,60 @@ jobs:
           steps.stashed-image.outputs.reusable != 'true'
       - name: "Check disk space after build"
         run: df -H
+
+  # Run checkout code in a separate job with no branch-cache publications. This optional
+  # producer hands the snapshot only to consumers of the same workflow run.
+  snapshot-ci-images:
+    name: "Snapshot CI ${{ inputs.platform }} image ${{ matrix.python-version }}"
+    needs: build-ci-images
+    if: >
+      github.event_name == 'pull_request' &&
+      inputs.upload-image-artifact == 'true' && inputs.image-stash-ref == '' &&
+      (inputs.checkout-ref == '' || inputs.checkout-ref == github.sha)
+    continue-on-error: true
+    timeout-minutes: 20
+    runs-on: ${{ fromJSON(inputs.runners) }}
+    permissions:
+      contents: read
+    strategy:
+      fail-fast: false
+      matrix:
+        python-version: ${{ fromJSON(inputs.python-versions) }}
+    env:
+      PYTHON_MAJOR_MINOR_VERSION: ${{ matrix.python-version }}
+      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+    steps:
+      - name: "Checkout sources"
+        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1  # v7.0.1
+        with:
+          ref: ${{ github.sha }}
+          persist-credentials: false
+      - name: "Prepare authoritative CI image"

Review Comment:
   This step took 178 s of the job's 229 s in run 37206844037: it restores and `docker image load`s the stash that `build-ci-images` exported seconds earlier. Creating the snapshot inside `build-ci-images` (after "Stash cache mount", since `create` runs `docker builder prune --all`) removes this reload entirely; the daemon there still reports `DockerRootDir=/var/lib/docker` because `move_docker_to_mnt.sh` bind-mounts rather than reconfigures.



##########
.github/workflows/ci-image-build.yml:
##########
@@ -401,3 +401,60 @@ jobs:
           steps.stashed-image.outputs.reusable != 'true'
       - name: "Check disk space after build"
         run: df -H
+
+  # Run checkout code in a separate job with no branch-cache publications. This optional
+  # producer hands the snapshot only to consumers of the same workflow run.
+  snapshot-ci-images:

Review Comment:
   Every `ci-amd.yml` job with `needs: build-ci-images` waits for the whole called workflow, and this job is part of it (`continue-on-error` changes the conclusion, not the wait). In this PR's run the first consumer started at 13:59:55, 3 min 56 s after the build job finished at 13:55:59; in a baseline run from the same afternoon the gap was 0 s. The ~87 s saved per consumer is paid with ~236 s added before any consumer starts, so end-to-end PR time gets longer. See the review body for the measured numbers and the suggestion to create the snapshot as the last step of `build-ci-images` instead.



##########
scripts/ci/docker_data_root_snapshot.sh:
##########
@@ -0,0 +1,154 @@
+#!/usr/bin/env bash
+# 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.
+
+# Moves the CI image between jobs as a copy of the Docker data directory that holds it, so a job
+# restores it with one extraction instead of `docker image load` unpacking and checksumming every
+# layer again.
+#
+#   docker_data_root_snapshot.sh create SNAPSHOT_FILE
+#       Keeps only the CI image in the daemon and writes its image store to SNAPSHOT_FILE, plus
+#       SNAPSHOT_FILE.meta naming the daemon that wrote it and the image.
+#   docker_data_root_snapshot.sh restore SNAPSHOT_FILE
+#       Restores the image. Incompatible snapshots leave the daemon untouched. Failed
+#       materialization cleans partial image state and restarts Docker for the normal stash path.
+set -euo pipefail
+
+DATA_ROOT="/var/lib/docker"
+DAEMON_STOPPED=false
+RESTORE_IN_PROGRESS=false
+
+function cleanup_daemon() {
+    local result=$?
+    trap - EXIT
+    if [[ "${RESTORE_IN_PROGRESS}" == true ]]; then
+        stop_daemon
+        remove_image_store
+        start_daemon
+    elif [[ "${DAEMON_STOPPED}" == true ]]; then
+        start_daemon
+    fi
+    exit "${result}"
+}
+trap cleanup_daemon EXIT
+
+function check_supported_daemon() {
+    local daemon=$1
+    local _ driver root
+    read -r _ driver _ root <<< "${daemon}"
+    if [[ "${driver}" != overlay2 || "${root}" != "${DATA_ROOT}" ]]; then

Review Comment:
   Minor: when runner images move to the containerd image store this check rejects every snapshot, the producer keeps spending its minutes, and nothing surfaces it because the create step is `continue-on-error`. An `echo "::warning::..."` here and on the fingerprint-mismatch exit would make the silent no-op visible in the run summary.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Restore the CI image from a snapshot of Docker's data directory [airflow]

Posted by "zozo123 (via GitHub)" <gi...@apache.org>.
zozo123 commented on code in PR #74173:
URL: https://github.com/apache/airflow/pull/74173#discussion_r4178937137


##########
scripts/ci/docker_data_root_snapshot.sh:
##########
@@ -0,0 +1,154 @@
+#!/usr/bin/env bash
+# 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.
+
+# Moves the CI image between jobs as a copy of the Docker data directory that holds it, so a job
+# restores it with one extraction instead of `docker image load` unpacking and checksumming every
+# layer again.
+#
+#   docker_data_root_snapshot.sh create SNAPSHOT_FILE
+#       Keeps only the CI image in the daemon and writes its image store to SNAPSHOT_FILE, plus
+#       SNAPSHOT_FILE.meta naming the daemon that wrote it and the image.
+#   docker_data_root_snapshot.sh restore SNAPSHOT_FILE
+#       Restores the image. Incompatible snapshots leave the daemon untouched. Failed
+#       materialization cleans partial image state and restarts Docker for the normal stash path.
+set -euo pipefail
+
+DATA_ROOT="/var/lib/docker"
+DAEMON_STOPPED=false
+RESTORE_IN_PROGRESS=false
+
+function cleanup_daemon() {
+    local result=$?
+    trap - EXIT
+    if [[ "${RESTORE_IN_PROGRESS}" == true ]]; then
+        stop_daemon
+        remove_image_store
+        start_daemon
+    elif [[ "${DAEMON_STOPPED}" == true ]]; then
+        start_daemon
+    fi
+    exit "${result}"
+}
+trap cleanup_daemon EXIT
+
+function check_supported_daemon() {
+    local daemon=$1
+    local _ driver root
+    read -r _ driver _ root <<< "${daemon}"
+    if [[ "${driver}" != overlay2 || "${root}" != "${DATA_ROOT}" ]]; then

Review Comment:
   Fixed in the latest push. Unsupported Docker storage and daemon-fingerprint mismatches now emit ::warning:: annotations before falling back. The producer also warns and skips snapshot creation on unsupported storage, before pruning or archiving. Regression tests verify the restore warnings.
   
   Python and Actions CodeQL passed; the full CI matrix is still running.
   
   AI-assisted: Codex (GPT-6), reviewed by the PR author.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Accelerate CI image materialization and dependency reuse [airflow]

Posted by "zozo123 (via GitHub)" <gi...@apache.org>.
zozo123 commented on PR #74173:
URL: https://github.com/apache/airflow/pull/74173#issuecomment-5992299811

   Indicative only: one treatment run and 1 exact-matrix baseline runs. Consumer preparation changed by -83.0 seconds, all-job workflow wall time by -1.5 minutes, and observed runner time by -69.6 minutes. These observational differences do not establish causation or a weekly saving.
   
   | Metric | Baseline median (p90) | PR median (p90) | Delta PR − baseline | n baseline / PR |
   |---|---:|---:|---:|---:|
   | Prep seconds | 210.0 (250.2) | 127.0 (174.2) | -83.0 | 79 / 79 |
   | Consumer gap after builder seconds | 3.0 (4.0) | 3.0 (4.0) | +0.0 | 79 / 79 |
   | Consumer start from workflow seconds | 583.0 (584.0) | 652.0 (653.0) | +69.0 | 79 / 79 |
   | Workflow wall minutes (all executed jobs) | 51.2 (51.2) | 49.8 (49.8) | -1.5 | 1 / 1 |
   | Runner minutes (all executed jobs) | 1306.0 (1306.0) | 1236.4 (1236.4) | -69.6 | 1 / 1 |
   | Builder duration seconds | 486.0 (486.0) | 541.0 (541.0) | +55.0 | 1 / 1 |
   | Snapshot create+upload seconds | 0.0 (0.0) | 96.0 (96.0) | +96.0 | 1 / 1 |
   | Initial dispatch seconds | 65.0 (65.0) | 84.0 (84.0) | +19.0 | 1 / 1 |
   
   Read-only timing analysis at f53486a4. Snapshot creation/upload: 73s + 23s; restore outcomes: {'restored': 79}. One treatment attempt is insufficient to claim ROI. Baselines match active job names and exclude CI-related file changes; wall time covers this AMD workflow, not verified required checks. True per-job queue time and dependency-cache benefit remain unmeasured. Please collect 2–4 additional full attempts and additional matched baselines before drawing conclusions.
   
   Source runs: [treatment, attempt 1](https://github.com/apache/airflow/actions/runs/37236836509) and [exact-matrix baseline, attempt 1](https://github.com/apache/airflow/actions/runs/37267385329). The 79 prep/start observations in each group are jobs within a single run, not independent workflow samples. p90 uses linear interpolation. Runner-minutes are observed execution time, not billed cost.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Accelerate CI image materialization with same-run snapshots [airflow]

Posted by "zozo123 (via GitHub)" <gi...@apache.org>.
zozo123 commented on PR #74173:
URL: https://github.com/apache/airflow/pull/74173#issuecomment-6087766006

   @shahar1 ready for another look. Your round-2 points are addressed at `2fe6e1219d`:
   
   - The dependency layer is split out into draft #74466. It drops the `|| echo` and the Bash-semantics tests.
   - The artifact is now `ci-image-snapshot-v1-…`, and a test checks that upload and restore use the same name.
   - New: the snapshot is kept for 1 day instead of 2. Only its own run reads it, and a re-run after it expires restores the 2-day stash instead. That halves the storage the snapshot adds.
   
   @potiuk @jscheffl, shahar1 asked for your call on the CI budget before this merges. These figures are per built CI image (Python/platform) per PR run, from run [37804108397](https://github.com/apache/airflow/actions/runs/37804108397):
   
   - **Cost:** about 115 s of extra serial time in the builder, and one more 2.53 GB artifact (now kept 1 day) next to the existing 2.36 GB stash.
   - **Saving:** each of the 79 consumer jobs unpacks the snapshot in 38 s instead of running `docker image load` for 103–109 s. That is about 85–90 runner-minutes per AMD run. The download is the same size either way, and its time varies from run to run (45–211 s medians), so turnaround is unchanged.
   
   Is that tradeoff acceptable?
   
   CodeQL also reports one `actions/cache-poisoning/poisonable-step` alert on the snapshot step. It is a false positive: the step only runs on `pull_request` and writes no cache. The analysis and a reproduction are [here](https://github.com/apache/airflow/pull/74173#discussion_r4225221915). Someone with Security-tab access would need to dismiss it.
   
   ---
   Drafted-by: Claude Code (Opus 5.5) (no human review before posting)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Accelerate CI image materialization with same-run snapshots [airflow]

Posted by "zozo123 (via GitHub)" <gi...@apache.org>.
zozo123 commented on PR #74173:
URL: https://github.com/apache/airflow/pull/74173#issuecomment-6395669045

   I merged `main` (f1510f138e) to resolve the conflict with #74889. The shared `load_image` action now restores the image stash through the new `stash-restore` action, so self-hosted runners keep the S3 path. Both prepare actions still delegate to `load_image`, and the snapshot stays limited to GitHub-hosted runners.
   
   The CI run for this commit is waiting for a maintainer to approve it: workflows on fork PRs now need approval. @shahar1 @potiuk, could one of you approve it?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Accelerate CI image materialization with same-run snapshots [airflow]

Posted by "zozo123 (via GitHub)" <gi...@apache.org>.
zozo123 commented on PR #74173:
URL: https://github.com/apache/airflow/pull/74173#issuecomment-6254253810

   Thanks for the thorough review. Everything inline is addressed in 7c367ee0e2, 2d3dec6b5c and 08c9943712. Below are the measurements you asked for. They are taken from the composite-step durations (`end-action … duration_ms`) in the job logs of 79 CI-image consumer jobs per run. The PR runs are 37950653129, 37980143706 and 39072732374 (attempt 2). For comparison, the baseline is three full-CI PR runs without the snapshot, from the same day as the latest PR run: 39141869252, 39143583838 and 39150120169.
   
   | per consumer job, median | download | load / unpack | total |
   |---|---|---|---|
   | stash path (3 baseline runs) | 41–64 s | `breeze ci-image load` 103–104 s | 154–175 s |
   | snapshot path (3 PR runs) | 71–155 s | unpack 30–34 s | 109–195 s |
   
   - **Acceptance:** in each of the three runs, all 79 eligible jobs restored the snapshot, with 0 fallbacks. The other 26 jobs with a prepare step use the PROD image and are not eligible.
   - **Builder:** prune and create took 85–105 s and the upload 12–17 s. Both happen in the build job, so they sit on the critical path of every consumer.
   - **Storage:** 2.55 GB per Python × platform (zstd -3), against 2.38 GB for the stash. Retention is 1 day.
   
   **What the numbers show:**
   - Unpacking is consistently about 70 s faster than `docker load`.
   - But the snapshot download was slower than the stash download in all three runs, at 16–36 MB/s, which ate most of that gain. Per job, the result ranged from 59 s faster to 27 s slower than the ~168 s baseline.
   - The builder also adds 1.7–2 min of wall clock before any consumer starts.
   - So on these numbers the net effect is not clearly positive. The runs are also from different days, so download throughput is not a like-for-like comparison.
   
   The runs on 08c9943712 also include the new costs: the metadata download, the check, and the file-tree hash after the restore. I'll post those numbers when they finish. If they don't show a clear net win, the extra artifact storage isn't worth it and I'm happy to close this.
   
   **@shahar1:**
   - Snapshots now run only when `runner.environment == 'github-hosted'`, on both the producer and the consumer side, so #74889 can land in either order.
   - CodeQL alert 670 is the same `poisonable-step` pattern as the alerts already dismissed on `main`, and still needs a maintainer to dismiss it.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Accelerate CI image materialization with same-run snapshots [airflow]

Posted by "zozo123 (via GitHub)" <gi...@apache.org>.
zozo123 commented on code in PR #74173:
URL: https://github.com/apache/airflow/pull/74173#discussion_r4308439313


##########
scripts/ci/docker_data_root_snapshot.sh:
##########
@@ -0,0 +1,161 @@
+#!/usr/bin/env bash
+# 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.
+
+# Moves the CI image between jobs as a copy of the Docker data directory that holds it, so a job
+# restores it with one extraction instead of `docker image load` unpacking and checksumming every
+# layer again.
+#
+#   docker_data_root_snapshot.sh create SNAPSHOT_FILE
+#       Creates the snapshot after the builder publishes its caches.
+#   docker_data_root_snapshot.sh restore SNAPSHOT_FILE
+#       Restores the image. Incompatible snapshots leave the daemon untouched. Failed
+#       materialization cleans partial image state and restarts Docker for the normal stash path.
+set -euo pipefail
+
+DATA_ROOT="/var/lib/docker"
+DAEMON_STOPPED=false
+RESTORE_IN_PROGRESS=false
+RESTORE_FILE=""
+
+function cleanup_daemon() {
+    local result=$?
+    trap - EXIT
+    if [[ -n "${RESTORE_FILE}" ]]; then
+        rm -f "${RESTORE_FILE}" "${RESTORE_FILE}.meta"
+    fi
+    if [[ "${RESTORE_IN_PROGRESS}" == true ]]; then
+        stop_daemon
+        remove_image_store
+        start_daemon
+    elif [[ "${DAEMON_STOPPED}" == true ]]; then
+        start_daemon
+    fi
+    exit "${result}"
+}
+trap cleanup_daemon EXIT
+
+function check_supported_daemon() {
+    local daemon=$1
+    local _ driver root
+    read -r _ driver _ root <<< "${daemon}"
+    if [[ "${driver}" != overlay2 || "${root}" != "${DATA_ROOT}" ]]; then
+        echo "::warning::Unsupported Docker image store; skipping snapshot: ${daemon}"
+        exit 3
+    fi
+}
+
+# A data directory is only readable by the daemon version and storage driver that wrote it.
+function daemon_fingerprint() {
+    docker info --format '{{.ServerVersion}} {{.Driver}} {{.Architecture}} {{.DockerRootDir}}'
+}
+
+function stop_daemon() {
+    DAEMON_STOPPED=true
+    sudo systemctl stop docker.socket docker
+}
+
+function start_daemon() {
+    sudo systemctl start docker
+    DAEMON_STOPPED=false
+}
+
+function remove_image_store() {
+    sudo rm -rf "${DATA_ROOT}/image" "${DATA_ROOT}/overlay2"
+}
+
+function create_snapshot() {
+    local snapshot_file="${1}"
+    local daemon image_id
+    daemon="$(daemon_fingerprint)"
+    check_supported_daemon "${daemon}"
+    image_id="$(docker images --quiet --filter 'label=org.apache.airflow.image=airflow-ci' | sort -u)"
+    if [[ -z "${image_id}" || "${image_id}" == *$'\n'* ]]; then
+        echo "Expected exactly one CI image in the daemon, found: '${image_id}'" >&2
+        exit 1
+    fi
+    docker ps --all --quiet | xargs --no-run-if-empty docker rm --force >/dev/null
+    docker images --quiet | sort -u | {
+        grep --invert-match --fixed-strings --line-regexp "${image_id}" || true
+    } | xargs --no-run-if-empty docker rmi --force >/dev/null
+    docker builder prune --all --force >/dev/null
+    printf '%s %s %s\n' "${daemon}" "${image_id}" "$(git rev-parse HEAD)" \
+        > "${snapshot_file}.meta"
+    stop_daemon
+    sudo tar --directory "${DATA_ROOT}" --xattrs --acls --numeric-owner \
+        --create --file - image overlay2 \
+        | zstd -3 -T0 --quiet --force -o "${snapshot_file}"
+    start_daemon
+}
+
+function restore_snapshot() {
+    local snapshot_file="${1}"
+    RESTORE_FILE="${snapshot_file}"
+    local -a meta
+    local image_id snapshot_fingerprint daemon existing_images existing_containers
+    if [[ ! -f "${snapshot_file}" || ! -f "${snapshot_file}.meta" ]]; then
+        echo "No snapshot at ${snapshot_file}"
+        exit 2
+    fi
+    read -r -a meta < "${snapshot_file}.meta"
+    if [[ ${#meta[@]} != 6 ]]; then
+        echo "Invalid snapshot metadata"
+        exit 3
+    fi
+    if [[ "${meta[5]}" != "$(git rev-parse HEAD)" ]]; then
+        echo "Snapshot belongs to a different checkout revision"
+        exit 3
+    fi
+    image_id="${meta[4]}"
+    snapshot_fingerprint="${meta[*]:0:4}"
+    daemon="$(daemon_fingerprint)"
+    check_supported_daemon "${daemon}"
+    if [[ "${snapshot_fingerprint}" != "${daemon}" ]]; then
+        echo "::warning::Snapshot daemon fingerprint mismatch: '${snapshot_fingerprint}' != '${daemon}'"
+        exit 3
+    fi
+    existing_images="$(docker images --all --quiet)"
+    existing_containers="$(docker ps --all --quiet)"
+    if [[ -n "${existing_images}" || -n "${existing_containers}" ]]; then
+        echo "The daemon already holds images, which restoring the snapshot would drop"
+        exit 3
+    fi
+    stop_daemon
+    RESTORE_IN_PROGRESS=true
+    remove_image_store
+    zstd -d -T0 --quiet --stdout "${snapshot_file}" \
+        | sudo tar --directory "${DATA_ROOT}" --xattrs --acls --numeric-owner --extract --file -

Review Comment:
   Fixed in 7c367ee0e2: create and extract now both use `--xattrs --xattrs-include='*'`. I reproduced the problem with GNU tar 1.34 (ubuntu:22.04). Without the include, `trusted.overlay.opaque` and `security.capability` are lost while `user.*` survives; with it, all three come back. Tests assert the flag on both sides.



##########
scripts/ci/docker_data_root_snapshot.sh:
##########
@@ -0,0 +1,161 @@
+#!/usr/bin/env bash
+# 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.
+
+# Moves the CI image between jobs as a copy of the Docker data directory that holds it, so a job
+# restores it with one extraction instead of `docker image load` unpacking and checksumming every
+# layer again.
+#
+#   docker_data_root_snapshot.sh create SNAPSHOT_FILE
+#       Creates the snapshot after the builder publishes its caches.
+#   docker_data_root_snapshot.sh restore SNAPSHOT_FILE
+#       Restores the image. Incompatible snapshots leave the daemon untouched. Failed
+#       materialization cleans partial image state and restarts Docker for the normal stash path.
+set -euo pipefail
+
+DATA_ROOT="/var/lib/docker"
+DAEMON_STOPPED=false
+RESTORE_IN_PROGRESS=false
+RESTORE_FILE=""
+
+function cleanup_daemon() {
+    local result=$?
+    trap - EXIT
+    if [[ -n "${RESTORE_FILE}" ]]; then
+        rm -f "${RESTORE_FILE}" "${RESTORE_FILE}.meta"
+    fi
+    if [[ "${RESTORE_IN_PROGRESS}" == true ]]; then
+        stop_daemon
+        remove_image_store
+        start_daemon
+    elif [[ "${DAEMON_STOPPED}" == true ]]; then
+        start_daemon
+    fi
+    exit "${result}"
+}
+trap cleanup_daemon EXIT
+
+function check_supported_daemon() {
+    local daemon=$1
+    local _ driver root
+    read -r _ driver _ root <<< "${daemon}"
+    if [[ "${driver}" != overlay2 || "${root}" != "${DATA_ROOT}" ]]; then
+        echo "::warning::Unsupported Docker image store; skipping snapshot: ${daemon}"
+        exit 3
+    fi
+}
+
+# A data directory is only readable by the daemon version and storage driver that wrote it.
+function daemon_fingerprint() {
+    docker info --format '{{.ServerVersion}} {{.Driver}} {{.Architecture}} {{.DockerRootDir}}'
+}
+
+function stop_daemon() {
+    DAEMON_STOPPED=true
+    sudo systemctl stop docker.socket docker
+}
+
+function start_daemon() {
+    sudo systemctl start docker
+    DAEMON_STOPPED=false
+}
+
+function remove_image_store() {
+    sudo rm -rf "${DATA_ROOT}/image" "${DATA_ROOT}/overlay2"
+}
+
+function create_snapshot() {
+    local snapshot_file="${1}"
+    local daemon image_id
+    daemon="$(daemon_fingerprint)"
+    check_supported_daemon "${daemon}"
+    image_id="$(docker images --quiet --filter 'label=org.apache.airflow.image=airflow-ci' | sort -u)"
+    if [[ -z "${image_id}" || "${image_id}" == *$'\n'* ]]; then
+        echo "Expected exactly one CI image in the daemon, found: '${image_id}'" >&2
+        exit 1
+    fi
+    docker ps --all --quiet | xargs --no-run-if-empty docker rm --force >/dev/null
+    docker images --quiet | sort -u | {
+        grep --invert-match --fixed-strings --line-regexp "${image_id}" || true
+    } | xargs --no-run-if-empty docker rmi --force >/dev/null
+    docker builder prune --all --force >/dev/null
+    printf '%s %s %s\n' "${daemon}" "${image_id}" "$(git rev-parse HEAD)" \
+        > "${snapshot_file}.meta"
+    stop_daemon
+    sudo tar --directory "${DATA_ROOT}" --xattrs --acls --numeric-owner \
+        --create --file - image overlay2 \
+        | zstd -3 -T0 --quiet --force -o "${snapshot_file}"
+    start_daemon
+}
+
+function restore_snapshot() {
+    local snapshot_file="${1}"
+    RESTORE_FILE="${snapshot_file}"
+    local -a meta
+    local image_id snapshot_fingerprint daemon existing_images existing_containers
+    if [[ ! -f "${snapshot_file}" || ! -f "${snapshot_file}.meta" ]]; then
+        echo "No snapshot at ${snapshot_file}"
+        exit 2
+    fi
+    read -r -a meta < "${snapshot_file}.meta"
+    if [[ ${#meta[@]} != 6 ]]; then
+        echo "Invalid snapshot metadata"
+        exit 3
+    fi
+    if [[ "${meta[5]}" != "$(git rev-parse HEAD)" ]]; then
+        echo "Snapshot belongs to a different checkout revision"
+        exit 3
+    fi
+    image_id="${meta[4]}"
+    snapshot_fingerprint="${meta[*]:0:4}"
+    daemon="$(daemon_fingerprint)"
+    check_supported_daemon "${daemon}"
+    if [[ "${snapshot_fingerprint}" != "${daemon}" ]]; then
+        echo "::warning::Snapshot daemon fingerprint mismatch: '${snapshot_fingerprint}' != '${daemon}'"
+        exit 3
+    fi
+    existing_images="$(docker images --all --quiet)"
+    existing_containers="$(docker ps --all --quiet)"
+    if [[ -n "${existing_images}" || -n "${existing_containers}" ]]; then
+        echo "The daemon already holds images, which restoring the snapshot would drop"
+        exit 3
+    fi
+    stop_daemon
+    RESTORE_IN_PROGRESS=true
+    remove_image_store
+    zstd -d -T0 --quiet --stdout "${snapshot_file}" \
+        | sudo tar --directory "${DATA_ROOT}" --xattrs --acls --numeric-owner --extract --file -
+    start_daemon
+    if ! docker run --rm --entrypoint /bin/bash "${image_id}" -c true; then

Review Comment:
   Done in 2d3dec6b5c.
   - When the snapshot is created, the meta now also records the image ID from `docker image inspect` and a hash of the image's merged file tree: `find / -xdev -printf '%p %y %m'`, sorted, then sha256.
   - After a restore, both are recomputed and must match. If they don't, the store is wiped and the job falls back to the stash.
   - I checked this end to end on Docker 28.5.2 with overlay2 in DinD. The test image has a later layer that deletes and recreates a directory and deletes a file.
   - Restoring without `--xattrs-include` keeps the same image ID but changes the tree hash. The restore is rejected (exit 4) and leaves an empty daemon behind. With the fix, the restore passes and the deleted paths stay deleted.



##########
.github/workflows/ci-image-build.yml:
##########
@@ -401,3 +401,35 @@ jobs:
           steps.stashed-image.outputs.reusable != 'true'
       - name: "Check disk space after build"
         run: df -H
+
+      # Snapshot only after cache publication: pruning removes the mount-cache image.
+      - name: "Snapshot CI image ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"
+        id: snapshot-export
+        continue-on-error: true
+        timeout-minutes: 5
+        env:
+          # Docker is bind-mounted from /mnt on AMD; write the archive on the root disk.
+          SNAPSHOT_FILE: >-
+            ${{ runner.temp }}/ci-image-snapshot-${{
+            inputs.platform == 'linux/amd64' && 'linux_amd64' || 'linux_arm64'
+            }}-${{ env.PYTHON_MAJOR_MINOR_VERSION }}.tar.zst
+        run: |
+          ./scripts/ci/docker_data_root_snapshot.sh create "${SNAPSHOT_FILE}"
+        shell: bash
+        if: >
+          github.event_name == 'pull_request' &&
+          inputs.upload-image-artifact == 'true' && inputs.image-stash-ref == '' &&
+          (inputs.checkout-ref == '' || inputs.checkout-ref == github.sha)
+      - name: "Upload CI image snapshot ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"
+        continue-on-error: true
+        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a  # v7.0.1
+        with:
+          name: >-
+            ci-image-snapshot-v1-${{ env.PYTHON_MAJOR_MINOR_VERSION }}-${{
+            inputs.platform == 'linux/amd64' && 'amd64' || 'arm64' }}
+          path: "${{ runner.temp }}/ci-image-snapshot-*-${{ env.PYTHON_MAJOR_MINOR_VERSION }}.tar.zst*"
+          if-no-files-found: 'error'

Review Comment:
   Added `overwrite: true`. In addition:
   - The `.meta` is now its own artifact. It is uploaded whenever the export step ran, also with `overwrite: true`.
   - `create` writes `unavailable` into it before it starts.
   
   So a re-run whose export fails also retires attempt 1's snapshot instead of leaving it in place.



##########
.github/workflows/ci-image-build.yml:
##########
@@ -401,3 +401,35 @@ jobs:
           steps.stashed-image.outputs.reusable != 'true'
       - name: "Check disk space after build"
         run: df -H
+
+      # Snapshot only after cache publication: pruning removes the mount-cache image.
+      - name: "Snapshot CI image ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"
+        id: snapshot-export
+        continue-on-error: true
+        timeout-minutes: 5
+        env:
+          # Docker is bind-mounted from /mnt on AMD; write the archive on the root disk.
+          SNAPSHOT_FILE: >-
+            ${{ runner.temp }}/ci-image-snapshot-${{
+            inputs.platform == 'linux/amd64' && 'linux_amd64' || 'linux_arm64'
+            }}-${{ env.PYTHON_MAJOR_MINOR_VERSION }}.tar.zst
+        run: |
+          ./scripts/ci/docker_data_root_snapshot.sh create "${SNAPSHOT_FILE}"
+        shell: bash
+        if: >
+          github.event_name == 'pull_request' &&
+          inputs.upload-image-artifact == 'true' && inputs.image-stash-ref == '' &&
+          (inputs.checkout-ref == '' || inputs.checkout-ref == github.sha)
+      - name: "Upload CI image snapshot ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"

Review Comment:
   Measured in the PR comment: 2.55 GB per Python × platform per PR run, kept for 1 day, on top of the 2.38 GB stash.



##########
.github/actions/prepare_breeze_and_image/action.yml:
##########
@@ -79,6 +79,33 @@ runs:
       run: |
         echo "Checking free space!"
         df -H
+    - name: "Restore CI image snapshot ${{ inputs.platform }}:${{ inputs.python }}"
+      continue-on-error: true
+      uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c  # v8.0.1

Review Comment:
   Done.
   - The `.meta` is a separate artifact.
   - Consumers download it first and run `docker_data_root_snapshot.sh check`, which looks at the revision, the daemon fingerprint, the driver and root, and whether the daemon is empty.
   - They download the snapshot only if the check passes.



##########
.github/actions/prepare_breeze_and_image/action.yml:
##########
@@ -79,6 +79,33 @@ runs:
       run: |
         echo "Checking free space!"
         df -H
+    - name: "Restore CI image snapshot ${{ inputs.platform }}:${{ inputs.python }}"
+      continue-on-error: true
+      uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c  # v8.0.1
+      with:
+        name: >-
+          ci-image-snapshot-v1-${{ inputs.python }}-${{
+          inputs.platform == 'linux/amd64' && 'amd64' || 'arm64' }}
+        path: "/mnt/"
+      id: restore-snapshot
+      if: >
+        github.event_name == 'pull_request' &&
+        inputs.image-type == 'ci' && inputs.image-stash-ref == ''

Review Comment:
   The metadata download now uses `pattern:` instead of `name:`. download-artifact only throws "Artifact not found" for `name`; a pattern that matches nothing downloads 0 artifacts and adds no annotation. The large download only runs after the check passes. This avoids threading a builder output through every consumer workflow.



##########
.github/actions/prepare_breeze_and_image/action.yml:
##########
@@ -79,6 +79,33 @@ runs:
       run: |
         echo "Checking free space!"
         df -H
+    - name: "Restore CI image snapshot ${{ inputs.platform }}:${{ inputs.python }}"
+      continue-on-error: true
+      uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c  # v8.0.1
+      with:
+        name: >-
+          ci-image-snapshot-v1-${{ inputs.python }}-${{
+          inputs.platform == 'linux/amd64' && 'amd64' || 'arm64' }}
+        path: "/mnt/"
+      id: restore-snapshot
+      if: >
+        github.event_name == 'pull_request' &&
+        inputs.image-type == 'ci' && inputs.image-stash-ref == ''
+    # Falls back to the image stash below whenever the snapshot does not fit this runner's daemon.
+    - name: "Unpack CI image snapshot ${{ inputs.platform }}:${{ inputs.python }}"
+      id: snapshot

Review Comment:
   Composite actions don't accept `timeout-minutes`: the runner's action schema allows only `continue-on-error`, `env`, `id`, `if`, `name`, `run`, `shell` and `working-directory` on composite run steps. So the bounds live inside the script:
   - `systemctl stop` and `systemctl start`: 60 s each
   - `zstd` and `tar`: 300 s
   - the check after the restore: 60 s
   
   In the worst case the step gives up after about 10 minutes. Any timeout wipes the partial store and restarts Docker, and then the stash path runs.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Accelerate CI image materialization with same-run snapshots [airflow]

Posted by "github-actions[bot] (via GitHub) via commits" <co...@airflow.apache.org>.
github-actions[bot] commented on PR #74173:
URL: https://github.com/apache/airflow/pull/74173#issuecomment-6549003032

   ### Backport successfully created: v3-4-test
   
   Note: As of [Merging PRs targeted for Airflow 3.X](https://github.com/apache/airflow/blob/main/dev/README_AIRFLOW3_DEV.md#merging-prs-targeted-for-airflow-3x)
   the committer who merges the PR is responsible for backporting the PRs that are bug fixes (generally speaking) to the maintenance branches.
   
   In matter of doubt please ask in [#release-management](https://apache-airflow.slack.com/archives/C03G9H97MM2) Slack channel.
   
   <table>
           <tr>
           <th>Status</th>
           <th>Branch</th>
           <th>Result</th>
       </tr>
       <tr>
           <td>✅</td>
           <td>v3-4-test</td>
           <td><a href="https://github.com/apache/airflow/pull/76183"><img src="https://img.shields.io/badge/PR-76183-blue" alt="PR Link"></a></td>
       </tr>
   </table>


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Accelerate CI image materialization with same-run snapshots [airflow]

Posted by "zozo123 (via GitHub)" <gi...@apache.org>.
zozo123 commented on code in PR #74173:
URL: https://github.com/apache/airflow/pull/74173#discussion_r4225221915


##########
.github/workflows/ci-image-build.yml:
##########
@@ -321,6 +321,62 @@
           docker rmi "${CACHE_FROM_IMAGE}"
         shell: bash
         if: always() && env.CACHE_FROM_IMAGE != ''
+      - name: "Export mount cache ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"
+        env:
+          PYTHON_MAJOR_MINOR_VERSION: ${{ env.PYTHON_MAJOR_MINOR_VERSION }}
+        run: >
+          breeze ci-image export-mount-cache
+          --cache-file /tmp/ci-cache-mount-save-v3-${PYTHON_MAJOR_MINOR_VERSION}.tar.gz
+        if: >
+          inputs.upload-mount-cache-artifact == 'true' &&
+          steps.stashed-image.outputs.reusable != 'true'
+      - name: >
+          Stash cache mount ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}
+          ${{ inputs.image-stash-ref != '' && format('for ref {0}', inputs.image-stash-ref) || '' }}
+        uses: apache/infrastructure-actions/stash/save@61dcea11f19e2bbe1263f14d72235e8da17d3ad0  # save/v1.0.0
+        with:
+          key: "ci-cache-mount-save-v3-${{ inputs.platform }}-${{ env.PYTHON_MAJOR_MINOR_VERSION }}\
+            ${{ inputs.image-stash-ref != '' && format('-{0}', inputs.image-stash-ref) || '' }}"
+          path: "/tmp/ci-cache-mount-save-v3-${{ env.PYTHON_MAJOR_MINOR_VERSION }}.tar.gz"
+          if-no-files-found: 'error'
+          # A ref's cache is read by the next publish of that same ref, days rather than hours
+          # later, so it gets the retention the ref's image gets rather than the branch's.
+          retention-days: ${{ inputs.image-stash-ref != '' && '6' || '2' }}
+        if: >
+          inputs.upload-mount-cache-artifact == 'true' &&
+          steps.stashed-image.outputs.reusable != 'true'
+      # Every job that prepares the CI image would otherwise `docker image load` the stash below,
+      # unpacking and checksumming each layer again; a copy of the image store restores with one
+      # extraction. Taken while the freshly built layers are still in the page cache, and after the
+      # mount cache export, as it drops the build cache that the export reads.
+      # Only PR-scoped snapshots: arbitrary checkout refs in privileged dispatch/scheduled
+      # workflows must never publish a snapshot into the default branch's cache scope.
+      - name: "Snapshot CI image ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"
+        id: snapshot-export
+        continue-on-error: true
+        env:
+          PLATFORM: ${{ inputs.platform }}
+        run: >
+          ./scripts/ci/docker_data_root_snapshot.sh create
+          "/mnt/ci-image-snapshot-${PLATFORM//\//_}-${PYTHON_MAJOR_MINOR_VERSION}.tar.zst"
+        shell: bash
+        if: >
+          github.event_name == 'pull_request' &&
+          inputs.upload-image-artifact == 'true' && inputs.image-stash-ref == '' &&
+          steps.stashed-image.outputs.reusable != 'true'
+      - name: "Stash CI image snapshot ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"

Review Comment:
   The current CodeQL alert on the snapshot step (`ci-image-build.yml:406`) is this same `actions/cache-poisoning/poisonable-step` rule. It is a false positive here, and the fix is a dismissal, not a code change:
   
   - **The step can't run on the triggers the alert names.** It runs only when `github.event_name == 'pull_request'` and `checkout-ref` is empty or `github.sha` (L419–422). The alert comes from `schedule` and `workflow_dispatch`. The rule only checks whether the checkout step at L149 is guarded by an access check it models (actor, author association, label, permission, repository, environment). It never reads the flagged step's own `if:`, so even `if: false` on this step keeps the alert (checked locally).
   - **It writes no cache.** `create` archives the local Docker data root into `runner.temp`, and the next step uploads it as an artifact that only this run downloads (2-day retention). Even a cache written during a `pull_request` run is scoped to `refs/pull/<n>/merge` and [can't be restored by the base branch](https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching).
   - **Main already has this finding on this job.** I ran CodeQL 2.27.2 locally with the same query. Main (`bf2de26c7b`) has 11 results, including the four steps right after this checkout (L154–161: `free_up_disk_space.sh`, `make_mnt_writeable.sh`, `move_docker_to_mnt.sh`, `./.github/actions/breeze`), which run on every event. This head (`3793fc0ad5`) adds exactly one, the snapshot step, and it's the only one of the 12 restricted to `pull_request`.
   - **Why the inline revision had no alert.** `c16d395b5f` drew no annotation because its inline `docker`/`git`/`tar`/`zstd` commands aren't in the rule's model of running checked-out code (`./path` scripts, local actions, build tools like `make` or `npm`). It wasn't meaningfully safer: on `pull_request` the job has already run checked-out scripts (L154–161) before this step. Moving the logic into `docker_data_root_snapshot.sh create`, as asked in review, is what made the alert visible again.
   
   The only code changes that clear it either go back to the inline version or dodge the pattern while running the same file. Running the script from a trusted second checkout still alerts. I don't have Security-tab access, so a maintainer would need to dismiss it as a false positive.
   
   ---
   Drafted-by: Claude Code (Opus 5.5) (no human review before posting)
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Accelerate CI image materialization with same-run snapshots [airflow]

Posted by "zozo123 (via GitHub)" <gi...@apache.org>.
zozo123 commented on code in PR #74173:
URL: https://github.com/apache/airflow/pull/74173#discussion_r4221175135


##########
.github/workflows/ci-image-build.yml:
##########
@@ -401,3 +401,70 @@ jobs:
           steps.stashed-image.outputs.reusable != 'true'
       - name: "Check disk space after build"
         run: df -H
+
+      # Snapshot only after cache publication: pruning removes the mount-cache image.
+      # Keep creation in trusted workflow commands; the configurable checkout is untrusted.

Review Comment:
   Agreed: the builder already runs PR-authored Breeze code, so the inline workflow commands did not provide an extra isolation boundary. Removed that claim and moved creation into a `create` subcommand in `docker_data_root_snapshot.sh`, sharing the fingerprint check, stop/start helpers and EXIT recovery with restore. The workflow now calls the script after cache publication, and the tests invoke both subcommands directly rather than extracting the YAML run block. All 24 snapshot tests pass; the full scripts suite on the rebased branch passed with 1,696 tests and one skip. Pushed in head `3793fc0ad560`.
   
   ---
   Drafted-by: Codex (GPT-6) (no human review before posting)



##########
.github/actions/prepare_breeze_and_image/action.yml:
##########
@@ -79,6 +79,33 @@ runs:
       run: |
         echo "Checking free space!"
         df -H
+    - name: "Restore CI image snapshot ${{ inputs.platform }}:${{ inputs.python }}"
+      continue-on-error: true
+      uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c  # v8.0.1
+      with:
+        name: >-
+          ci-image-snapshot-v2-${{ inputs.python }}-${{
+          inputs.platform == 'linux/amd64' && 'amd64' || 'arm64' }}
+        path: "/mnt/"
+      id: restore-snapshot
+      if: >
+        github.event_name == 'pull_request' &&
+        inputs.image-type == 'ci' && inputs.image-stash-ref == ''
+    # Falls back to the image stash below whenever the snapshot does not fit this runner's daemon.
+    - name: "Unpack CI image snapshot ${{ inputs.platform }}:${{ inputs.python }}"
+      id: snapshot
+      env:
+        PLATFORM: ${{ inputs.platform }}
+        PYTHON: ${{ inputs.python }}
+      run: |
+        if ./scripts/ci/docker_data_root_snapshot.sh restore \
+            "/mnt/ci-image-snapshot-${PLATFORM//\//_}-${PYTHON}.tar.zst"; then
+          echo "restored=true" >> "${GITHUB_OUTPUT}"
+        else
+          echo "Falling back to loading the image stash"

Review Comment:
   Fixed in head `3793fc0ad560`: restore registers the exact archive and `.meta` paths with its EXIT cleanup before checking whether either file exists. Every restore exit now removes both files, including missing/malformed metadata, stale checkout, fingerprint/storage/inventory rejection, extraction failure and failed image startup. This frees `/mnt` before the stash fallback starts. The regression harness asserts archive and metadata removal for every restore invocation, covering success and all tested rejection/recovery paths; 24 tests pass.
   
   ---
   Drafted-by: Codex (GPT-6) (no human review before posting)



##########
.github/workflows/ci-image-build.yml:
##########
@@ -401,3 +401,70 @@ jobs:
           steps.stashed-image.outputs.reusable != 'true'
       - name: "Check disk space after build"
         run: df -H
+
+      # Snapshot only after cache publication: pruning removes the mount-cache image.
+      # Keep creation in trusted workflow commands; the configurable checkout is untrusted.
+      - name: "Snapshot CI image ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"
+        id: snapshot-export
+        continue-on-error: true
+        timeout-minutes: 5
+        env:
+          # Docker is bind-mounted from /mnt on AMD; write the archive on the root disk.
+          SNAPSHOT_FILE: >-
+            ${{ runner.temp }}/ci-image-snapshot-${{
+            inputs.platform == 'linux/amd64' && 'linux_amd64' || 'linux_arm64'
+            }}-${{ env.PYTHON_MAJOR_MINOR_VERSION }}.tar.zst
+        run: |
+          daemon_stopped=false
+          function restart_docker_on_exit() {
+            local result=$?
+            trap - EXIT
+            if [[ "${daemon_stopped}" == true ]]; then
+              sudo systemctl start docker
+            fi
+            exit "${result}"
+          }
+          trap restart_docker_on_exit EXIT
+          daemon="$(docker info --format \
+            '{{.ServerVersion}} {{.Driver}} {{.Architecture}} {{.DockerRootDir}}')"
+          read -r _ driver _ root <<< "${daemon}"
+          if [[ "${driver}" != overlay2 || "${root}" != /var/lib/docker ]]; then
+            echo "::warning::Unsupported Docker image store; skipping snapshot creation: ${daemon}"
+            exit 3
+          fi
+          image_id="$(docker images --quiet --filter 'label=org.apache.airflow.image=airflow-ci' | sort -u)"
+          if [[ -z "${image_id}" || "${image_id}" == *$'\n'* ]]; then
+            echo "Expected exactly one CI image in the daemon, found: '${image_id}'" >&2
+            exit 1
+          fi
+          docker ps --all --quiet | xargs --no-run-if-empty docker rm --force >/dev/null
+          docker images --quiet | sort -u | {
+            grep --invert-match --fixed-strings --line-regexp "${image_id}" || true
+          } | xargs --no-run-if-empty docker rmi --force >/dev/null
+          docker builder prune --all --force >/dev/null
+          printf '%s %s %s\n' "${daemon}" "${image_id}" "$(git rev-parse HEAD)" \
+            > "${SNAPSHOT_FILE}.meta"
+          daemon_stopped=true
+          sudo systemctl stop docker.socket docker
+          sudo tar --directory /var/lib/docker --xattrs --acls --numeric-owner \
+            --create --file - image overlay2 \
+            | zstd -3 -T0 --quiet --force -o "${SNAPSHOT_FILE}"
+          sudo systemctl start docker
+          daemon_stopped=false
+        shell: bash
+        if: >
+          github.event_name == 'pull_request' &&
+          inputs.upload-image-artifact == 'true' && inputs.image-stash-ref == '' &&
+          (inputs.checkout-ref == '' || inputs.checkout-ref == github.sha)
+      - name: "Upload CI image snapshot ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"
+        continue-on-error: true
+        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a  # v7.0.1
+        with:
+          name: >-
+            ci-image-snapshot-v2-${{ env.PYTHON_MAJOR_MINOR_VERSION }}-${{
+            inputs.platform == 'linux/amd64' && 'amd64' || 'arm64' }}
+          path: "${{ runner.temp }}/ci-image-snapshot-*-${{ env.PYTHON_MAJOR_MINOR_VERSION }}.tar.zst*"
+          if-no-files-found: 'error'
+          compression-level: '0'
+          retention-days: '2'

Review Comment:
   Agreed. The PR description now explicitly records 2.52 GB for the snapshot plus 2.35 GB for the fallback stash: approximately 4.87 GB per built CI image / Python-platform combination per run, with two-day retention for both transports. Matrix size and overlapping retained runs multiply that amount; it is not a 4.9 GB cap for the whole workflow. The description treats this as a CI-capacity/artifact-quota tradeoff requiring maintainer acceptance before merging, and claims no whole-workflow speedup. I have not assumed ASF budget approval.
   
   ---
   Drafted-by: Codex (GPT-6) (no human review before posting)



##########
Dockerfile.ci:
##########
@@ -1966,13 +1982,24 @@ RUN bash /scripts/docker/install_packaging_tools.sh
 
 COPY --from=scripts install_airflow_when_building_images.sh /scripts/docker/
 
+COPY --from=dependency-manifests /dependency-manifests/ ${AIRFLOW_SOURCES}/
+ARG UPGRADE_RANDOM_INDICATOR_STRING=""
+# Only preinstall locked third-party dependencies. The full sync after COPY still installs
+# workspace packages from the current checkout and retains its existing resolution fallback.
+RUN --mount=type=cache,id=ci-$TARGETARCH-$DEPENDENCY_CACHE_EPOCH,target=/root/.cache/ \
+    if [[ -z "${UPGRADE_RANDOM_INDICATOR_STRING}" ]]; then \
+        uv sync --all-packages --frozen --group ci-image --no-install-workspace \
+            --no-binary-package lxml --no-binary-package xmlsec \
+            --no-python-downloads --no-managed-python || \
+            echo "Dependency preinstallation failed; deferring to the full source installation"; \

Review Comment:
   Agreed: a failed preinstall must not become a successful cached partial layer. Removed the `|| echo` so installation failure now fails the build. Per your review's split request, the entire dependency-layer change is removed from #74173 and moved to draft #74466, which contains this correction. The Dockerfile string-splitting/Bash-semantics tests were also dropped. That draft records your earlier 28.7-second preinstall measurement and explicitly leaves full-image equivalence and registry cache-hit performance unverified pending separate validation. Regular and manual Dockerfile checks pass.
   
   ---
   Drafted-by: Codex (GPT-6) (no human review before posting)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Restore the CI image from a snapshot of Docker's data directory [airflow]

Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #74173:
URL: https://github.com/apache/airflow/pull/74173#discussion_r4176192808


##########
.github/workflows/ci-image-build.yml:
##########
@@ -401,3 +401,58 @@
           steps.stashed-image.outputs.reusable != 'true'
       - name: "Check disk space after build"
         run: df -H
+
+  # Run checkout code in a separate job with no branch-cache publications. This optional
+  # producer hands the snapshot only to consumers of the same workflow run.
+  snapshot-ci-images:
+    name: "Snapshot CI ${{ inputs.platform }} image ${{ matrix.python-version }}"
+    needs: build-ci-images
+    if: >
+      github.event_name == 'pull_request' &&
+      inputs.upload-image-artifact == 'true' && inputs.image-stash-ref == ''
+    continue-on-error: true
+    timeout-minutes: 20
+    runs-on: ${{ fromJSON(inputs.runners) }}
+    permissions:
+      contents: read
+    strategy:
+      fail-fast: false
+      matrix:
+        python-version: ${{ fromJSON(inputs.python-versions) }}
+    env:
+      PYTHON_MAJOR_MINOR_VERSION: ${{ matrix.python-version }}
+      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+    steps:
+      - name: "Checkout sources"
+        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1  # v7.0.1
+        with:
+          ref: ${{ inputs.checkout-ref }}
+          persist-credentials: false
+      - name: "Prepare authoritative CI image"
+        uses: ./.github/actions/prepare_breeze_and_image
+        with:
+          platform: ${{ inputs.platform }}
+          python: ${{ matrix.python-version }}
+          use-uv: ${{ inputs.use-uv }}
+          make-mnt-writeable-and-cleanup: 'true'
+      - name: "Snapshot CI image ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"

Review Comment:
   ## CodeQL / Cache Poisoning via execution of untrusted code
   
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([schedule](2)).
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([workflow_dispatch](3)).
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([schedule](4)).
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([workflow_dispatch](5)).
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([workflow_dispatch](6)).
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([workflow_dispatch](7)).
   Potential cache poisoning in the context of the default branch due to privilege checkout of untrusted code from [inputs.checkout-ref](1). ([workflow_dispatch](8)).
   
   [Show more details](https://github.com/apache/airflow/security/code-scanning/674)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Accelerate CI image materialization and dependency reuse [airflow]

Posted by "shahar1 (via GitHub)" <gi...@apache.org>.
shahar1 commented on code in PR #74173:
URL: https://github.com/apache/airflow/pull/74173#discussion_r4210244944


##########
.github/workflows/ci-image-build.yml:
##########
@@ -401,3 +401,70 @@ jobs:
           steps.stashed-image.outputs.reusable != 'true'
       - name: "Check disk space after build"
         run: df -H
+
+      # Snapshot only after cache publication: pruning removes the mount-cache image.
+      # Keep creation in trusted workflow commands; the configurable checkout is untrusted.
+      - name: "Snapshot CI image ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"
+        id: snapshot-export
+        continue-on-error: true
+        timeout-minutes: 5
+        env:
+          # Docker is bind-mounted from /mnt on AMD; write the archive on the root disk.
+          SNAPSHOT_FILE: >-
+            ${{ runner.temp }}/ci-image-snapshot-${{
+            inputs.platform == 'linux/amd64' && 'linux_amd64' || 'linux_arm64'
+            }}-${{ env.PYTHON_MAJOR_MINOR_VERSION }}.tar.zst
+        run: |
+          daemon_stopped=false
+          function restart_docker_on_exit() {
+            local result=$?
+            trap - EXIT
+            if [[ "${daemon_stopped}" == true ]]; then
+              sudo systemctl start docker
+            fi
+            exit "${result}"
+          }
+          trap restart_docker_on_exit EXIT
+          daemon="$(docker info --format \
+            '{{.ServerVersion}} {{.Driver}} {{.Architecture}} {{.DockerRootDir}}')"
+          read -r _ driver _ root <<< "${daemon}"
+          if [[ "${driver}" != overlay2 || "${root}" != /var/lib/docker ]]; then
+            echo "::warning::Unsupported Docker image store; skipping snapshot creation: ${daemon}"
+            exit 3
+          fi
+          image_id="$(docker images --quiet --filter 'label=org.apache.airflow.image=airflow-ci' | sort -u)"
+          if [[ -z "${image_id}" || "${image_id}" == *$'\n'* ]]; then
+            echo "Expected exactly one CI image in the daemon, found: '${image_id}'" >&2
+            exit 1
+          fi
+          docker ps --all --quiet | xargs --no-run-if-empty docker rm --force >/dev/null
+          docker images --quiet | sort -u | {
+            grep --invert-match --fixed-strings --line-regexp "${image_id}" || true
+          } | xargs --no-run-if-empty docker rmi --force >/dev/null
+          docker builder prune --all --force >/dev/null
+          printf '%s %s %s\n' "${daemon}" "${image_id}" "$(git rev-parse HEAD)" \
+            > "${SNAPSHOT_FILE}.meta"
+          daemon_stopped=true
+          sudo systemctl stop docker.socket docker
+          sudo tar --directory /var/lib/docker --xattrs --acls --numeric-owner \
+            --create --file - image overlay2 \
+            | zstd -3 -T0 --quiet --force -o "${SNAPSHOT_FILE}"
+          sudo systemctl start docker
+          daemon_stopped=false
+        shell: bash
+        if: >
+          github.event_name == 'pull_request' &&
+          inputs.upload-image-artifact == 'true' && inputs.image-stash-ref == '' &&
+          (inputs.checkout-ref == '' || inputs.checkout-ref == github.sha)
+      - name: "Upload CI image snapshot ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"
+        continue-on-error: true
+        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a  # v7.0.1
+        with:
+          name: >-
+            ci-image-snapshot-v2-${{ env.PYTHON_MAJOR_MINOR_VERSION }}-${{
+            inputs.platform == 'linux/amd64' && 'amd64' || 'arm64' }}
+          path: "${{ runner.temp }}/ci-image-snapshot-*-${{ env.PYTHON_MAJOR_MINOR_VERSION }}.tar.zst*"
+          if-no-files-found: 'error'
+          compression-level: '0'
+          retention-days: '2'

Review Comment:
   Both transports are now uploaded per run — this snapshot (2.52 GB) plus the `ci-image-save-v3-*` stash (2.35 GB) that the fallback still needs — so per-run artifact storage for the CI image roughly doubles to ~4.9 GB at 2-day retention. That is the price of having a fallback and I am not arguing against it, but it is an ASF-quota question rather than a code one, so it should be stated explicitly for whoever watches that budget.



##########
.github/workflows/ci-image-build.yml:
##########
@@ -401,3 +401,70 @@ jobs:
           steps.stashed-image.outputs.reusable != 'true'
       - name: "Check disk space after build"
         run: df -H
+
+      # Snapshot only after cache publication: pruning removes the mount-cache image.
+      # Keep creation in trusted workflow commands; the configurable checkout is untrusted.

Review Comment:
   The isolation this comment claims is not there to be had: the create step only runs when `github.event_name == 'pull_request'`, and in that event this same job checks out `inputs.checkout-ref` (empty, so the PR merge commit) and runs `breeze ci-image build` from it at line 160 — PR-authored code already executes here with the same privileges. The three callers that pass a non-empty `checkout-ref` (`update-constraints-on-push.yml`, `release-constraints.yml`, `publish-docs-to-s3.yml`) are all `workflow_dispatch` and so excluded by the event guard anyway.
   
   What the inlining does cost is a second copy of the fingerprint check, the stop/start pair and the restart trap, which the restore path already has in `docker_data_root_snapshot.sh` — and it forces the test to parse this YAML and `bash -c` the `run:` block to reach the logic. A `create` subcommand in the script, sharing those helpers, would drop ~45 lines here and let the test call it directly.



##########
.github/actions/prepare_breeze_and_image/action.yml:
##########
@@ -79,6 +79,33 @@ runs:
       run: |
         echo "Checking free space!"
         df -H
+    - name: "Restore CI image snapshot ${{ inputs.platform }}:${{ inputs.python }}"
+      continue-on-error: true
+      uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c  # v8.0.1
+      with:
+        name: >-
+          ci-image-snapshot-v2-${{ inputs.python }}-${{
+          inputs.platform == 'linux/amd64' && 'amd64' || 'arm64' }}
+        path: "/mnt/"
+      id: restore-snapshot
+      if: >
+        github.event_name == 'pull_request' &&
+        inputs.image-type == 'ci' && inputs.image-stash-ref == ''
+    # Falls back to the image stash below whenever the snapshot does not fit this runner's daemon.
+    - name: "Unpack CI image snapshot ${{ inputs.platform }}:${{ inputs.python }}"
+      id: snapshot
+      env:
+        PLATFORM: ${{ inputs.platform }}
+        PYTHON: ${{ inputs.python }}
+      run: |
+        if ./scripts/ci/docker_data_root_snapshot.sh restore \
+            "/mnt/ci-image-snapshot-${PLATFORM//\//_}-${PYTHON}.tar.zst"; then
+          echo "restored=true" >> "${GITHUB_OUTPUT}"
+        else
+          echo "Falling back to loading the image stash"

Review Comment:
   On the fallback the 2.52 GB archive stays on `/mnt`: the script only `rm -f`s it on the success path, and every rejection (`exit 2/3/4`) leaves it behind. The stash path then downloads another ~2.35 GB to `/mnt` and `docker image load`s it into the data root, which on AMD is bind-mounted from the same disk. Worth an `rm -f "/mnt/ci-image-snapshot-${PLATFORM//\//_}-${PYTHON}.tar.zst"*` in this branch (or in the script's failure trap) so a rejected snapshot does not eat 2.5 GB of the disk the fallback needs.



##########
Dockerfile.ci:
##########
@@ -1966,13 +1982,24 @@ RUN bash /scripts/docker/install_packaging_tools.sh
 
 COPY --from=scripts install_airflow_when_building_images.sh /scripts/docker/
 
+COPY --from=dependency-manifests /dependency-manifests/ ${AIRFLOW_SOURCES}/
+ARG UPGRADE_RANDOM_INDICATOR_STRING=""
+# Only preinstall locked third-party dependencies. The full sync after COPY still installs
+# workspace packages from the current checkout and retains its existing resolution fallback.
+RUN --mount=type=cache,id=ci-$TARGETARCH-$DEPENDENCY_CACHE_EPOCH,target=/root/.cache/ \
+    if [[ -z "${UPGRADE_RANDOM_INDICATOR_STRING}" ]]; then \
+        uv sync --all-packages --frozen --group ci-image --no-install-workspace \
+            --no-binary-package lxml --no-binary-package xmlsec \
+            --no-python-downloads --no-managed-python || \
+            echo "Dependency preinstallation failed; deferring to the full source installation"; \

Review Comment:
   Swallowing the failure here means a failed preinstall is committed as a successful, cached layer. Because `main` pushes its cache with `mode=max`, one transient failure in a `main` build stores a partial `/usr/local` in the registry cache. Every PR with the same manifests then reuses it until a `pyproject.toml` or `uv.lock` changes. The full sync below repairs the environment, so correctness is fine, but the saving is silently gone, and this `echo` is the only trace in the build log.
   
   This step uses the same `uv.lock` and the same `--frozen` flags as the authoritative sync, so whatever makes it fail (network, an sdist build) would also make that sync fail. I would drop the `|| echo` and let the build fail like any other install step. A `::warning::` would not help here: BuildKit prefixes every output line with `#50 26.59`, so the runner never treats it as an annotation.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Accelerate CI image materialization with same-run snapshots [airflow]

Posted by "zozo123 (via GitHub)" <gi...@apache.org>.
zozo123 commented on code in PR #74173:
URL: https://github.com/apache/airflow/pull/74173#discussion_r4225221915


##########
.github/workflows/ci-image-build.yml:
##########
@@ -321,6 +321,62 @@
           docker rmi "${CACHE_FROM_IMAGE}"
         shell: bash
         if: always() && env.CACHE_FROM_IMAGE != ''
+      - name: "Export mount cache ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"
+        env:
+          PYTHON_MAJOR_MINOR_VERSION: ${{ env.PYTHON_MAJOR_MINOR_VERSION }}
+        run: >
+          breeze ci-image export-mount-cache
+          --cache-file /tmp/ci-cache-mount-save-v3-${PYTHON_MAJOR_MINOR_VERSION}.tar.gz
+        if: >
+          inputs.upload-mount-cache-artifact == 'true' &&
+          steps.stashed-image.outputs.reusable != 'true'
+      - name: >
+          Stash cache mount ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}
+          ${{ inputs.image-stash-ref != '' && format('for ref {0}', inputs.image-stash-ref) || '' }}
+        uses: apache/infrastructure-actions/stash/save@61dcea11f19e2bbe1263f14d72235e8da17d3ad0  # save/v1.0.0
+        with:
+          key: "ci-cache-mount-save-v3-${{ inputs.platform }}-${{ env.PYTHON_MAJOR_MINOR_VERSION }}\
+            ${{ inputs.image-stash-ref != '' && format('-{0}', inputs.image-stash-ref) || '' }}"
+          path: "/tmp/ci-cache-mount-save-v3-${{ env.PYTHON_MAJOR_MINOR_VERSION }}.tar.gz"
+          if-no-files-found: 'error'
+          # A ref's cache is read by the next publish of that same ref, days rather than hours
+          # later, so it gets the retention the ref's image gets rather than the branch's.
+          retention-days: ${{ inputs.image-stash-ref != '' && '6' || '2' }}
+        if: >
+          inputs.upload-mount-cache-artifact == 'true' &&
+          steps.stashed-image.outputs.reusable != 'true'
+      # Every job that prepares the CI image would otherwise `docker image load` the stash below,
+      # unpacking and checksumming each layer again; a copy of the image store restores with one
+      # extraction. Taken while the freshly built layers are still in the page cache, and after the
+      # mount cache export, as it drops the build cache that the export reads.
+      # Only PR-scoped snapshots: arbitrary checkout refs in privileged dispatch/scheduled
+      # workflows must never publish a snapshot into the default branch's cache scope.
+      - name: "Snapshot CI image ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"
+        id: snapshot-export
+        continue-on-error: true
+        env:
+          PLATFORM: ${{ inputs.platform }}
+        run: >
+          ./scripts/ci/docker_data_root_snapshot.sh create
+          "/mnt/ci-image-snapshot-${PLATFORM//\//_}-${PYTHON_MAJOR_MINOR_VERSION}.tar.zst"
+        shell: bash
+        if: >
+          github.event_name == 'pull_request' &&
+          inputs.upload-image-artifact == 'true' && inputs.image-stash-ref == '' &&
+          steps.stashed-image.outputs.reusable != 'true'
+      - name: "Stash CI image snapshot ${{ inputs.platform }}:${{ env.PYTHON_MAJOR_MINOR_VERSION }}"

Review Comment:
   The current CodeQL alert on the snapshot step (`ci-image-build.yml:406`) is this same `actions/cache-poisoning/poisonable-step` rule. It is a false positive here, and the fix is a dismissal, not a code change:
   
   - **The step can't run on the triggers the alert names.** It runs only when `github.event_name == 'pull_request'` and `checkout-ref` is empty or `github.sha` (L419–422). The alert comes from `schedule` and `workflow_dispatch`. The rule only checks whether the checkout step at L149 is guarded by an access check it models (actor, author association, label, permission, repository, environment). It never reads the flagged step's own `if:`, so even `if: false` on this step keeps the alert (checked locally).
   - **It writes no cache.** `create` archives the local Docker data root into `runner.temp`, and the next step uploads it as an artifact that only this run downloads (2-day retention). Even a cache written during a `pull_request` run is scoped to `refs/pull/<n>/merge` and [can't be restored by the base branch](https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching).
   - **Main already has this finding on this job.** I ran CodeQL 2.27.2 locally with the same query. Main (`bf2de26c7b`) has 11 results, including the four steps right after this checkout (L154–161: `free_up_disk_space.sh`, `make_mnt_writeable.sh`, `move_docker_to_mnt.sh`, `./.github/actions/breeze`), which run on every event. This head (`3793fc0ad5`) adds exactly one, the snapshot step, and it's the only one of the 12 restricted to `pull_request`.
   - **Why the inline revision had no alert.** `c16d395b5f` drew no annotation because its inline `docker`/`git`/`tar`/`zstd` commands aren't in the rule's model of running checked-out code (`./path` scripts, local actions, build tools like `make` or `npm`). It wasn't meaningfully safer: on `pull_request` the job has already run checked-out scripts (L154–161) before this step. Moving the logic into `docker_data_root_snapshot.sh create`, as asked in review, is what made the alert visible again.
   
   The only code changes that clear it either go back to the inline version or dodge the pattern while running the same file. Running the script from a trusted second checkout still alerts. I don't have Security-tab access, so a maintainer would need to dismiss it as a false positive.
   
   <details><summary>How to reproduce the local CodeQL comparison</summary>
   
   CodeQL CLI 2.27.2 (`codeql-bundle-v2.27.2`), run on the `.github` tree of each commit:
   
   ```console
   codeql database create db --language=actions --build-mode=none --source-root=<tree>
   codeql database analyze db codeql/actions-queries:Security/CWE-349/CachePoisoningViaPoisonableStep.ql \
     --format=sarif-latest --output=out.sarif
   ```
   
   `main` at `bf2de26c7b` (11 results):
   ```
   .github/actions/breeze/action.yml:50
   .github/workflows/ci-image-build.yml:154
   .github/workflows/ci-image-build.yml:157
   .github/workflows/ci-image-build.yml:159
   .github/workflows/ci-image-build.yml:161
   .github/workflows/publish-docs-to-s3.yml:140
   .github/workflows/publish-docs-to-s3.yml:330
   .github/workflows/publish-docs-to-s3.yml:338
   .github/workflows/publish-docs-to-s3.yml:480
   .github/workflows/publish-docs-to-s3.yml:535
   .github/workflows/release-constraints.yml:86
   ```
   
   This PR at `3793fc0ad5` (12 results, the same 11 plus one):
   ```
   .github/workflows/ci-image-build.yml:406
   ```
   </details>
   
   ---
   Drafted-by: Claude Code (Opus 5.5) (no human review before posting)
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Accelerate CI image materialization with same-run snapshots [airflow]

Posted by "shahar1 (via GitHub)" <gi...@apache.org>.
shahar1 commented on code in PR #74173:
URL: https://github.com/apache/airflow/pull/74173#discussion_r4302824303


##########
scripts/tests/ci/test_docker_data_root_snapshot.py:
##########
@@ -0,0 +1,274 @@
+# 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 os
+import shlex
+import subprocess
+from pathlib import Path
+
+import pytest
+import yaml
+
+SCRIPT = Path(__file__).resolve().parents[2] / "ci" / "docker_data_root_snapshot.sh"
+WORKFLOW = SCRIPT.parents[2] / ".github" / "workflows" / "ci-image-build.yml"
+ACTION = SCRIPT.parents[2] / ".github" / "actions" / "prepare_breeze_and_image" / "action.yml"
+FINGERPRINT = "28.5.2 overlay2 x86_64 /var/lib/docker"
+
+
+@pytest.fixture
+def fake_tools(tmp_path):
+    """Shadow ``docker``, ``sudo`` and ``zstd`` with a logger answering the queries the script makes."""
+    tools = tmp_path / "bin"
+    tools.mkdir()
+    command = tools / "command"
+    command.write_text(
+        r"""#!/usr/bin/env bash
+name="${0##*/}"
+printf '%s\n' "${name} $*" >> "${COMMAND_LOG}"
+if [[ "${name}" == "git" && "$*" == "rev-parse HEAD" ]]; then
+    echo "${CHECKOUT_SHA:-revision1}"
+fi
+if [[ "${name}" == "zstd" ]]; then
+    exit "${ZSTD_EXIT:-0}"
+fi
+if [[ "${name}" == "sudo" && "$*" == "tar "* ]]; then
+    exit "${TAR_EXIT:-0}"
+fi
+if [[ "${name}" == "sudo" && "$*" == "systemctl stop docker.socket docker" && "${STOP_EXIT:-0}" != 0 ]]; then
+    exit "${STOP_EXIT}"
+fi
+if [[ "${name}" == "sudo" && "$*" == "systemctl start docker" && "${START_FAIL_ONCE:-0}" == 1 ]]; then
+    if [[ $(grep -c 'sudo systemctl start docker' "${COMMAND_LOG}") == 1 ]]; then
+        exit 1
+    fi
+fi
+if [[ "${name}" == "docker" ]]; then
+    case "$*" in
+        "info --format "*) echo "${DAEMON_FINGERPRINT}" ;;
+        "images --quiet --filter label=org.apache.airflow.image=airflow-ci") printf '%b' "${CI_IMAGES:-}" ;;
+        "images --quiet") printf '%b' "${ALL_IMAGES:-}" ;;
+        "images --all --quiet") printf '%b' "${ALL_IMAGES:-}"; exit "${IMAGES_EXIT:-0}" ;;
+        "ps --all --quiet") printf '%b' "${CONTAINERS:-}"; exit "${CONTAINERS_EXIT:-0}" ;;
+        "run "*) exit "${RUN_EXIT:-0}" ;;
+    esac
+fi
+"""
+    )
+    command.chmod(0o755)
+    for name in ("docker", "sudo", "zstd", "git"):
+        (tools / name).symlink_to(command)
+    return {
+        "PATH": f"{tools}:{os.environ['PATH']}",
+        "COMMAND_LOG": str(tmp_path / "commands.log"),
+        "DAEMON_FINGERPRINT": FINGERPRINT,
+    }
+
+
+@pytest.fixture
+def snapshot(tmp_path):
+    snapshot_file = tmp_path / "ci-image-snapshot-linux_amd64-3.10.tar.zst"
+    snapshot_file.write_bytes(b"")
+    Path(f"{snapshot_file}.meta").write_text(f"{FINGERPRINT} abc123 revision1\n")
+    return snapshot_file
+
+
+def run_script(env, *args):
+    command = ["bash", "--noprofile", "--norc", str(SCRIPT), *args]
+    result = subprocess.run(
+        command,
+        env={**os.environ, **env},
+        capture_output=True,
+        text=True,
+        timeout=15,
+        check=False,
+    )
+    if args[0] == "restore":
+        assert not Path(args[1]).exists()
+        assert not Path(f"{args[1]}.meta").exists()
+    return result
+
+
+def read_commands(env):
+    log = Path(env["COMMAND_LOG"])
+    return [shlex.split(line) for line in log.read_text().splitlines()] if log.exists() else []
+
+
+def test_restore_unpacks_snapshot_into_stopped_daemon(fake_tools, snapshot):
+    result = run_script(fake_tools, "restore", str(snapshot))
+
+    assert result.returncode == 0, result.stdout + result.stderr
+    commands = read_commands(fake_tools)
+    stop = commands.index(["sudo", "systemctl", "stop", "docker.socket", "docker"])
+    remove = commands.index(["sudo", "rm", "-rf", "/var/lib/docker/image", "/var/lib/docker/overlay2"])
+    extract = next(i for i, c in enumerate(commands) if c[:2] == ["sudo", "tar"] and "--extract" in c)
+    start = commands.index(["sudo", "systemctl", "start", "docker"])
+    run = commands.index(["docker", "run", "--rm", "--entrypoint", "/bin/bash", "abc123", "-c", "true"])
+    assert stop < remove < extract < start < run
+    assert not snapshot.exists()
+    assert not Path(f"{snapshot}.meta").exists()
+
+
+@pytest.mark.parametrize(
+    ("env", "remove_meta", "expected_exit"),
+    [
+        pytest.param({}, True, 2, id="no-snapshot"),
+        pytest.param(
+            {"DAEMON_FINGERPRINT": "29.0.0 overlay2 x86_64 /var/lib/docker"}, False, 3, id="other-daemon"
+        ),
+        pytest.param({"ALL_IMAGES": "def456\\n"}, False, 3, id="daemon-holds-images"),
+    ],
+)
+def test_restore_leaves_daemon_alone_when_snapshot_does_not_fit(
+    fake_tools, snapshot, env, remove_meta, expected_exit
+):
+    if remove_meta:
+        Path(f"{snapshot}.meta").unlink()
+
+    result = run_script({**fake_tools, **env}, "restore", str(snapshot))
+
+    assert result.returncode == expected_exit
+    if "DAEMON_FINGERPRINT" in env:
+        assert "::warning::" in result.stdout
+    assert not [c for c in read_commands(fake_tools) if c[:2] == ["sudo", "systemctl"]]
+
+
+def test_restore_empties_store_again_when_image_does_not_run(fake_tools, snapshot):
+    result = run_script({**fake_tools, "RUN_EXIT": "1"}, "restore", str(snapshot))
+
+    assert result.returncode == 4
+    commands = read_commands(fake_tools)
+    run = next(i for i, c in enumerate(commands) if c[:2] == ["docker", "run"])
+    after_run = commands[run + 1 :]
+    assert ["sudo", "rm", "-rf", "/var/lib/docker/image", "/var/lib/docker/overlay2"] in after_run
+    assert after_run[-1] == ["sudo", "systemctl", "start", "docker"]
+
+
+def test_create_keeps_only_the_ci_image(fake_tools, tmp_path):
+    snapshot_file = tmp_path / "out.tar.zst"
+    env = {**fake_tools, "CI_IMAGES": "abc123\\nabc123\\n", "ALL_IMAGES": "abc123\\nother1\\nabc123\\n"}
+
+    result = run_script(env, "create", str(snapshot_file))
+
+    assert result.returncode == 0, result.stdout + result.stderr
+    commands = read_commands(env)
+    assert ["docker", "rmi", "--force", "other1"] in commands
+    assert not [c for c in commands if c[:2] == ["docker", "rmi"] and "abc123" in c]
+    assert ["docker", "builder", "prune", "--all", "--force"] in commands
+    assert Path(f"{snapshot_file}.meta").read_text() == f"{FINGERPRINT} abc123 revision1\n"
+    archive = next(c for c in commands if c[:2] == ["sudo", "tar"])
+    assert archive[-2:] == ["image", "overlay2"]
+
+
+def test_create_refuses_ambiguous_ci_image(fake_tools, tmp_path):
+    env = {**fake_tools, "CI_IMAGES": "abc123\\ndef456\\n"}
+
+    result = run_script(env, "create", str(tmp_path / "out.tar.zst"))
+
+    assert result.returncode == 1
+    assert not [c for c in read_commands(env) if c[:2] == ["sudo", "systemctl"]]
+
+
+@pytest.mark.parametrize("failure", [{"ZSTD_EXIT": "1"}, {"TAR_EXIT": "1"}, {"START_FAIL_ONCE": "1"}])
+def test_restore_recovers_empty_running_daemon_after_materialization_failure(fake_tools, snapshot, failure):
+    result = run_script({**fake_tools, **failure}, "restore", str(snapshot))
+    assert result.returncode != 0
+    commands = read_commands(fake_tools)
+    assert commands[-2:] == [
+        ["sudo", "rm", "-rf", "/var/lib/docker/image", "/var/lib/docker/overlay2"],
+        ["sudo", "systemctl", "start", "docker"],
+    ]
+    assert not any(command[:2] == ["docker", "run"] for command in commands)
+
+
+@pytest.mark.parametrize("failure", [{"ZSTD_EXIT": "1"}, {"TAR_EXIT": "1"}])
+def test_create_restarts_daemon_after_archive_failure(fake_tools, tmp_path, failure):
+    result = run_script(
+        {**fake_tools, **failure, "CI_IMAGES": "abc123"}, "create", str(tmp_path / "snapshot.tar.zst")
+    )
+    assert result.returncode != 0
+    assert read_commands(fake_tools)[-1] == ["sudo", "systemctl", "start", "docker"]
+
+
+@pytest.mark.parametrize("mode", ["create", "restore"])
+@pytest.mark.parametrize("daemon", ["28.5.2 btrfs x86_64 /var/lib/docker", "28.5.2 overlay2 x86_64 /other"])
+def test_unsupported_storage_does_not_modify_daemon(fake_tools, snapshot, mode, daemon):
+    result = run_script({**fake_tools, "DAEMON_FINGERPRINT": daemon}, mode, str(snapshot))
+    assert result.returncode == 3
+    assert "::warning::" in result.stdout
+    assert not any(command[0] == "sudo" for command in read_commands(fake_tools))
+
+
+def test_existing_container_prevents_restore(fake_tools, snapshot):
+    result = run_script({**fake_tools, "CONTAINERS": "container1"}, "restore", str(snapshot))
+    assert result.returncode == 3
+    assert not any(command[0] == "sudo" for command in read_commands(fake_tools))
+
+
+@pytest.mark.parametrize("failure", [{"IMAGES_EXIT": "1"}, {"CONTAINERS_EXIT": "1"}])
+def test_failed_daemon_inventory_does_not_modify_store(fake_tools, snapshot, failure):
+    result = run_script({**fake_tools, **failure}, "restore", str(snapshot))
+
+    assert result.returncode != 0
+    assert not any(command[0] == "sudo" for command in read_commands(fake_tools))
+
+
+def test_malformed_metadata_prevents_restore(fake_tools, snapshot):
+    Path(f"{snapshot}.meta").write_text("invalid\n")
+    result = run_script(fake_tools, "restore", str(snapshot))
+    assert result.returncode == 3
+    assert not any(command[0] == "sudo" for command in read_commands(fake_tools))
+
+
+def test_stale_snapshot_does_not_modify_daemon(fake_tools, snapshot):
+    result = run_script({**fake_tools, "CHECKOUT_SHA": "revision2"}, "restore", str(snapshot))
+    assert result.returncode == 3
+    assert not any(command[0] == "sudo" for command in read_commands(fake_tools))
+
+
+@pytest.mark.parametrize("mode", ["create", "restore"])
+def test_partial_stop_failure_restarts_daemon(fake_tools, snapshot, mode):
+    result = run_script({**fake_tools, "STOP_EXIT": "1", "CI_IMAGES": "abc123"}, mode, str(snapshot))
+    assert result.returncode != 0
+    assert read_commands(fake_tools)[-1] == ["sudo", "systemctl", "start", "docker"]
+    assert not any(command[:2] == ["sudo", "rm"] for command in read_commands(fake_tools))
+
+
+def test_snapshot_creation_uses_builder_after_cache_publication():
+    workflow = yaml.safe_load(WORKFLOW.read_text())
+    assert "snapshot-ci-images" not in workflow["jobs"]

Review Comment:
   **nit** (Testing): `snapshot-ci-images` only existed in earlier revisions of this branch, never on `main`, so this line guards a design nobody can reintroduce by accident. The ordering check below is what matters; I would drop this line.
   
   > Every changed or added behaviour must have a test; every test must fail without the PR's change.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Accelerate CI image materialization with same-run snapshots [airflow]

Posted by "zozo123 (via GitHub)" <gi...@apache.org>.
zozo123 commented on PR #74173:
URL: https://github.com/apache/airflow/pull/74173#issuecomment-6241787134

   @shahar1 thanks. Dropped that line in fe39ec5. On #74889, I'm glad to take you up on routing the snapshot through the stash action on your side if this lands first. @potiuk @jscheffl the only open items now are the CI budget call (figures in the PR description) and dismissing CodeQL alert 670.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Accelerate CI image materialization with same-run snapshots [airflow]

Posted by "zozo123 (via GitHub)" <gi...@apache.org>.
zozo123 commented on code in PR #74173:
URL: https://github.com/apache/airflow/pull/74173#discussion_r4308440064


##########
.github/actions/prepare_breeze_and_image/action.yml:
##########
@@ -98,3 +126,4 @@ runs:
       run: >
         breeze ${IMAGE_TYPE}-image load --platform "${PLATFORM}" --python "${PYTHON}" --image-file-dir "/mnt"
       shell: bash
+      if: steps.snapshot.outputs.restored != 'true'

Review Comment:
   The restore now goes through `breeze ci-image load --snapshot-file …`, so it behaves like a regular load:
   - it runs `perform_environment_checks()`
   - it checks that the expected image name exists
   - it prints the same verbose diagnostics
   - it honours `--tag-as`
   - it calls `mark_image_as_rebuilt()`
   
   On your general point: `prepare_breeze_and_image` and `prepare_single_ci_image` now share one `load_image` action that makes the snapshot-or-stash decision.



##########
scripts/ci/docker_data_root_snapshot.sh:
##########
@@ -0,0 +1,161 @@
+#!/usr/bin/env bash
+# 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.
+
+# Moves the CI image between jobs as a copy of the Docker data directory that holds it, so a job
+# restores it with one extraction instead of `docker image load` unpacking and checksumming every
+# layer again.
+#
+#   docker_data_root_snapshot.sh create SNAPSHOT_FILE
+#       Creates the snapshot after the builder publishes its caches.
+#   docker_data_root_snapshot.sh restore SNAPSHOT_FILE
+#       Restores the image. Incompatible snapshots leave the daemon untouched. Failed
+#       materialization cleans partial image state and restarts Docker for the normal stash path.
+set -euo pipefail
+
+DATA_ROOT="/var/lib/docker"
+DAEMON_STOPPED=false
+RESTORE_IN_PROGRESS=false
+RESTORE_FILE=""
+
+function cleanup_daemon() {
+    local result=$?
+    trap - EXIT
+    if [[ -n "${RESTORE_FILE}" ]]; then
+        rm -f "${RESTORE_FILE}" "${RESTORE_FILE}.meta"
+    fi
+    if [[ "${RESTORE_IN_PROGRESS}" == true ]]; then
+        stop_daemon
+        remove_image_store
+        start_daemon
+    elif [[ "${DAEMON_STOPPED}" == true ]]; then
+        start_daemon
+    fi
+    exit "${result}"
+}
+trap cleanup_daemon EXIT
+
+function check_supported_daemon() {
+    local daemon=$1
+    local _ driver root
+    read -r _ driver _ root <<< "${daemon}"
+    if [[ "${driver}" != overlay2 || "${root}" != "${DATA_ROOT}" ]]; then

Review Comment:
   `check_supported_daemon` runs before anything else in `create`. On a containerd store it exits 3 before pruning, and before any upload: the archive upload only runs on success, so only the few-byte `unavailable` meta is published. The builder then shows the failed `continue-on-error` step plus a `::warning::`. Consumers read the meta and skip the download. 08c9943712 adds tests that an unsupported store runs no prune, `rmi` or `sudo`, and publishes only the marker.



##########
scripts/tests/ci/test_docker_data_root_snapshot.py:
##########
@@ -0,0 +1,274 @@
+# 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 os
+import shlex
+import subprocess
+from pathlib import Path
+
+import pytest
+import yaml
+
+SCRIPT = Path(__file__).resolve().parents[2] / "ci" / "docker_data_root_snapshot.sh"
+WORKFLOW = SCRIPT.parents[2] / ".github" / "workflows" / "ci-image-build.yml"
+ACTION = SCRIPT.parents[2] / ".github" / "actions" / "prepare_breeze_and_image" / "action.yml"
+FINGERPRINT = "28.5.2 overlay2 x86_64 /var/lib/docker"
+
+
+@pytest.fixture
+def fake_tools(tmp_path):
+    """Shadow ``docker``, ``sudo`` and ``zstd`` with a logger answering the queries the script makes."""
+    tools = tmp_path / "bin"
+    tools.mkdir()
+    command = tools / "command"
+    command.write_text(
+        r"""#!/usr/bin/env bash
+name="${0##*/}"
+printf '%s\n' "${name} $*" >> "${COMMAND_LOG}"
+if [[ "${name}" == "git" && "$*" == "rev-parse HEAD" ]]; then
+    echo "${CHECKOUT_SHA:-revision1}"
+fi
+if [[ "${name}" == "zstd" ]]; then
+    exit "${ZSTD_EXIT:-0}"
+fi
+if [[ "${name}" == "sudo" && "$*" == "tar "* ]]; then
+    exit "${TAR_EXIT:-0}"
+fi
+if [[ "${name}" == "sudo" && "$*" == "systemctl stop docker.socket docker" && "${STOP_EXIT:-0}" != 0 ]]; then
+    exit "${STOP_EXIT}"
+fi
+if [[ "${name}" == "sudo" && "$*" == "systemctl start docker" && "${START_FAIL_ONCE:-0}" == 1 ]]; then
+    if [[ $(grep -c 'sudo systemctl start docker' "${COMMAND_LOG}") == 1 ]]; then
+        exit 1
+    fi
+fi
+if [[ "${name}" == "docker" ]]; then
+    case "$*" in
+        "info --format "*) echo "${DAEMON_FINGERPRINT}" ;;
+        "images --quiet --filter label=org.apache.airflow.image=airflow-ci") printf '%b' "${CI_IMAGES:-}" ;;
+        "images --quiet") printf '%b' "${ALL_IMAGES:-}" ;;
+        "images --all --quiet") printf '%b' "${ALL_IMAGES:-}"; exit "${IMAGES_EXIT:-0}" ;;
+        "ps --all --quiet") printf '%b' "${CONTAINERS:-}"; exit "${CONTAINERS_EXIT:-0}" ;;
+        "run "*) exit "${RUN_EXIT:-0}" ;;
+    esac
+fi
+"""
+    )
+    command.chmod(0o755)
+    for name in ("docker", "sudo", "zstd", "git"):
+        (tools / name).symlink_to(command)
+    return {
+        "PATH": f"{tools}:{os.environ['PATH']}",
+        "COMMAND_LOG": str(tmp_path / "commands.log"),
+        "DAEMON_FINGERPRINT": FINGERPRINT,
+    }
+
+
+@pytest.fixture
+def snapshot(tmp_path):
+    snapshot_file = tmp_path / "ci-image-snapshot-linux_amd64-3.10.tar.zst"
+    snapshot_file.write_bytes(b"")
+    Path(f"{snapshot_file}.meta").write_text(f"{FINGERPRINT} abc123 revision1\n")
+    return snapshot_file
+
+
+def run_script(env, *args):
+    command = ["bash", "--noprofile", "--norc", str(SCRIPT), *args]
+    result = subprocess.run(
+        command,
+        env={**os.environ, **env},
+        capture_output=True,
+        text=True,
+        timeout=15,
+        check=False,
+    )
+    if args[0] == "restore":
+        assert not Path(args[1]).exists()
+        assert not Path(f"{args[1]}.meta").exists()
+    return result
+
+
+def read_commands(env):
+    log = Path(env["COMMAND_LOG"])
+    return [shlex.split(line) for line in log.read_text().splitlines()] if log.exists() else []
+
+
+def test_restore_unpacks_snapshot_into_stopped_daemon(fake_tools, snapshot):
+    result = run_script(fake_tools, "restore", str(snapshot))
+
+    assert result.returncode == 0, result.stdout + result.stderr
+    commands = read_commands(fake_tools)
+    stop = commands.index(["sudo", "systemctl", "stop", "docker.socket", "docker"])
+    remove = commands.index(["sudo", "rm", "-rf", "/var/lib/docker/image", "/var/lib/docker/overlay2"])
+    extract = next(i for i, c in enumerate(commands) if c[:2] == ["sudo", "tar"] and "--extract" in c)
+    start = commands.index(["sudo", "systemctl", "start", "docker"])
+    run = commands.index(["docker", "run", "--rm", "--entrypoint", "/bin/bash", "abc123", "-c", "true"])
+    assert stop < remove < extract < start < run
+    assert not snapshot.exists()
+    assert not Path(f"{snapshot}.meta").exists()
+
+
+@pytest.mark.parametrize(
+    ("env", "remove_meta", "expected_exit"),
+    [
+        pytest.param({}, True, 2, id="no-snapshot"),
+        pytest.param(
+            {"DAEMON_FINGERPRINT": "29.0.0 overlay2 x86_64 /var/lib/docker"}, False, 3, id="other-daemon"
+        ),
+        pytest.param({"ALL_IMAGES": "def456\\n"}, False, 3, id="daemon-holds-images"),
+    ],
+)
+def test_restore_leaves_daemon_alone_when_snapshot_does_not_fit(
+    fake_tools, snapshot, env, remove_meta, expected_exit
+):
+    if remove_meta:
+        Path(f"{snapshot}.meta").unlink()
+
+    result = run_script({**fake_tools, **env}, "restore", str(snapshot))
+
+    assert result.returncode == expected_exit
+    if "DAEMON_FINGERPRINT" in env:
+        assert "::warning::" in result.stdout
+    assert not [c for c in read_commands(fake_tools) if c[:2] == ["sudo", "systemctl"]]
+
+
+def test_restore_empties_store_again_when_image_does_not_run(fake_tools, snapshot):
+    result = run_script({**fake_tools, "RUN_EXIT": "1"}, "restore", str(snapshot))
+
+    assert result.returncode == 4
+    commands = read_commands(fake_tools)
+    run = next(i for i, c in enumerate(commands) if c[:2] == ["docker", "run"])
+    after_run = commands[run + 1 :]
+    assert ["sudo", "rm", "-rf", "/var/lib/docker/image", "/var/lib/docker/overlay2"] in after_run
+    assert after_run[-1] == ["sudo", "systemctl", "start", "docker"]
+
+
+def test_create_keeps_only_the_ci_image(fake_tools, tmp_path):
+    snapshot_file = tmp_path / "out.tar.zst"
+    env = {**fake_tools, "CI_IMAGES": "abc123\\nabc123\\n", "ALL_IMAGES": "abc123\\nother1\\nabc123\\n"}
+
+    result = run_script(env, "create", str(snapshot_file))
+
+    assert result.returncode == 0, result.stdout + result.stderr
+    commands = read_commands(env)
+    assert ["docker", "rmi", "--force", "other1"] in commands
+    assert not [c for c in commands if c[:2] == ["docker", "rmi"] and "abc123" in c]
+    assert ["docker", "builder", "prune", "--all", "--force"] in commands
+    assert Path(f"{snapshot_file}.meta").read_text() == f"{FINGERPRINT} abc123 revision1\n"
+    archive = next(c for c in commands if c[:2] == ["sudo", "tar"])
+    assert archive[-2:] == ["image", "overlay2"]
+
+
+def test_create_refuses_ambiguous_ci_image(fake_tools, tmp_path):
+    env = {**fake_tools, "CI_IMAGES": "abc123\\ndef456\\n"}
+
+    result = run_script(env, "create", str(tmp_path / "out.tar.zst"))
+
+    assert result.returncode == 1
+    assert not [c for c in read_commands(env) if c[:2] == ["sudo", "systemctl"]]
+
+
+@pytest.mark.parametrize("failure", [{"ZSTD_EXIT": "1"}, {"TAR_EXIT": "1"}, {"START_FAIL_ONCE": "1"}])
+def test_restore_recovers_empty_running_daemon_after_materialization_failure(fake_tools, snapshot, failure):
+    result = run_script({**fake_tools, **failure}, "restore", str(snapshot))
+    assert result.returncode != 0
+    commands = read_commands(fake_tools)
+    assert commands[-2:] == [
+        ["sudo", "rm", "-rf", "/var/lib/docker/image", "/var/lib/docker/overlay2"],
+        ["sudo", "systemctl", "start", "docker"],
+    ]
+    assert not any(command[:2] == ["docker", "run"] for command in commands)
+
+
+@pytest.mark.parametrize("failure", [{"ZSTD_EXIT": "1"}, {"TAR_EXIT": "1"}])
+def test_create_restarts_daemon_after_archive_failure(fake_tools, tmp_path, failure):
+    result = run_script(
+        {**fake_tools, **failure, "CI_IMAGES": "abc123"}, "create", str(tmp_path / "snapshot.tar.zst")
+    )
+    assert result.returncode != 0
+    assert read_commands(fake_tools)[-1] == ["sudo", "systemctl", "start", "docker"]
+
+
+@pytest.mark.parametrize("mode", ["create", "restore"])
+@pytest.mark.parametrize("daemon", ["28.5.2 btrfs x86_64 /var/lib/docker", "28.5.2 overlay2 x86_64 /other"])
+def test_unsupported_storage_does_not_modify_daemon(fake_tools, snapshot, mode, daemon):
+    result = run_script({**fake_tools, "DAEMON_FINGERPRINT": daemon}, mode, str(snapshot))
+    assert result.returncode == 3
+    assert "::warning::" in result.stdout
+    assert not any(command[0] == "sudo" for command in read_commands(fake_tools))
+
+
+def test_existing_container_prevents_restore(fake_tools, snapshot):
+    result = run_script({**fake_tools, "CONTAINERS": "container1"}, "restore", str(snapshot))
+    assert result.returncode == 3
+    assert not any(command[0] == "sudo" for command in read_commands(fake_tools))
+
+
+@pytest.mark.parametrize("failure", [{"IMAGES_EXIT": "1"}, {"CONTAINERS_EXIT": "1"}])
+def test_failed_daemon_inventory_does_not_modify_store(fake_tools, snapshot, failure):
+    result = run_script({**fake_tools, **failure}, "restore", str(snapshot))
+
+    assert result.returncode != 0
+    assert not any(command[0] == "sudo" for command in read_commands(fake_tools))
+
+
+def test_malformed_metadata_prevents_restore(fake_tools, snapshot):
+    Path(f"{snapshot}.meta").write_text("invalid\n")
+    result = run_script(fake_tools, "restore", str(snapshot))
+    assert result.returncode == 3
+    assert not any(command[0] == "sudo" for command in read_commands(fake_tools))
+
+
+def test_stale_snapshot_does_not_modify_daemon(fake_tools, snapshot):
+    result = run_script({**fake_tools, "CHECKOUT_SHA": "revision2"}, "restore", str(snapshot))
+    assert result.returncode == 3
+    assert not any(command[0] == "sudo" for command in read_commands(fake_tools))
+
+
+@pytest.mark.parametrize("mode", ["create", "restore"])
+def test_partial_stop_failure_restarts_daemon(fake_tools, snapshot, mode):
+    result = run_script({**fake_tools, "STOP_EXIT": "1", "CI_IMAGES": "abc123"}, mode, str(snapshot))
+    assert result.returncode != 0
+    assert read_commands(fake_tools)[-1] == ["sudo", "systemctl", "start", "docker"]
+    assert not any(command[:2] == ["sudo", "rm"] for command in read_commands(fake_tools))
+
+
+def test_snapshot_creation_uses_builder_after_cache_publication():
+    workflow = yaml.safe_load(WORKFLOW.read_text())
+    assert "snapshot-ci-images" not in workflow["jobs"]

Review Comment:
   Dropped in fe39ec5285.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Accelerate CI image materialization with same-run snapshots [airflow]

Posted by "potiuk (via GitHub) via commits" <co...@airflow.apache.org>.
potiuk merged PR #74173:
URL: https://github.com/apache/airflow/pull/74173


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org