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

zhouyuan pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gluten.git


The following commit(s) were added to refs/heads/main by this push:
     new f53bb0f664 [VL][CI] Reuse tested Iceberg base results (#13456)
f53bb0f664 is described below

commit f53bb0f664ba24cee149c82fbd163d4f6a93f529
Author: inf / Hazmi <[email protected]>
AuthorDate: Sun Nov 22 10:55:56 2026 +0000

    [VL][CI] Reuse tested Iceberg base results (#13456)
    
    The Iceberg upstream gate compares each PR's head results with results for 
its base revision. Before this PR the gate retested the base far more often 
than needed:
    
    Only head results were saved, and a saved result could be reused only once 
its PR had merged at that exact head. A failed or rerun PR therefore rebuilt 
and retested its base on every attempt, even when that base had already passed.
    The baseline key contained the base's Git tree SHA. Any commit to main, 
including a docs-only one, changed the key and threw away every saved result.
---
 .github/workflows/docker_image.yml                 |   5 +
 .github/workflows/iceberg_spark_ut.yml             |  71 ++--
 .github/workflows/iceberg_upstream_revision.yml    |  11 +-
 .../workflows/util/iceberg-upstream/baseline.py    | 234 ++++++++++++--
 .github/workflows/util/iceberg-upstream/gate.py    |  81 +++++
 .github/workflows/velox_native_build.yml           |  23 +-
 .../Dockerfile.almalinux8-gcc13-static-build       |   3 +
 dev/docker/verify-native-ci-tools.sh               |  22 ++
 .../test/python/test_baseline.py                   | 357 ++++++++++++++++++++-
 .../src-iceberg-upstream/test/python/test_gate.py  | 126 ++++++++
 10 files changed, 866 insertions(+), 67 deletions(-)

diff --git a/.github/workflows/docker_image.yml 
b/.github/workflows/docker_image.yml
index 15d3715690..fd1d895237 100644
--- a/.github/workflows/docker_image.yml
+++ b/.github/workflows/docker_image.yml
@@ -358,6 +358,11 @@ jobs:
           labels: ${{ steps.meta.outputs.labels }}
           outputs: type=image,"name=${{ env.DOCKERHUB_REPO 
}}",push-by-digest=true,push=true
 
+      - name: Verify CI tools in the published image
+        env:
+          IMAGE: ${{ env.DOCKERHUB_REPO }}@${{ steps.build.outputs.digest }}
+        run: docker run --rm "$IMAGE" bash 
/usr/local/bin/verify-native-ci-tools
+
       - name: Export digest
         run: |
           mkdir -p ${{ runner.temp }}/digests
diff --git a/.github/workflows/iceberg_spark_ut.yml 
b/.github/workflows/iceberg_spark_ut.yml
index b3f4a25cee..2b49eda925 100644
--- a/.github/workflows/iceberg_spark_ut.yml
+++ b/.github/workflows/iceberg_spark_ut.yml
@@ -81,7 +81,7 @@ jobs:
         run: |
           python3 -m unittest discover -s 
gluten-ut/src-iceberg-upstream/test/python
 
-      - name: Find a baseline from merged or default-branch results
+      - name: Find a baseline from verified base, merged or default-branch 
results
         id: restore
         continue-on-error: true
         env:
@@ -135,22 +135,16 @@ jobs:
     needs: [prepare, iceberg-upstream-test, iceberg-base-test]
     if: always() && !cancelled()
     runs-on: ubuntu-24.04
+    env:
+      NATIVE_IMAGE: ${{ needs.prepare.outputs.native_image }}
+      TEST_IMAGE: ${{ needs.prepare.outputs.test_image }}
     steps:
       - uses: actions/checkout@v7
         with:
           ref: ${{ inputs.revision }}
           fetch-depth: 0
-      - name: Require complete test runs
-        env:
-          UPSTREAM_RESULT: ${{ needs.iceberg-upstream-test.result }}
-          RUN_BASE: ${{ needs.prepare.outputs.run_base }}
-          BASE_RESULT: ${{ needs.iceberg-base-test.result }}
-        run: |
-          test "$UPSTREAM_RESULT" = success
-          if [ "$RUN_BASE" = true ]; then
-            test "$BASE_RESULT" = success
-          fi
       - name: Download current shards
+        id: download-head
         if: always()
         uses: actions/download-artifact@v8
         with:
@@ -158,7 +152,10 @@ jobs:
           path: iceberg-head
       - name: Merge every current shard
         id: head
-        if: always()
+        if: >-
+          always() && needs.iceberg-upstream-test.result == 'success' &&
+          steps.download-head.outcome == 'success' &&
+          hashFiles('iceberg-head/**/execution-coverage.json') != ''
         run: python3 .github/workflows/util/iceberg-upstream/merge.py 
iceberg-head --shards "$ICEBERG_SHARD_COUNT"
       # A complete, validated result remains publishable when only comparison 
is unavailable.
       # Once this PR merges, later PRs can use the saved report without any 
base test run.
@@ -170,7 +167,8 @@ jobs:
           HEAD_SHA: ${{ inputs.revision || github.sha }}
         run: |
           python3 .github/workflows/util/iceberg-upstream/baseline.py record \
-            --directory iceberg-head --key "$HEAD_KEY" --revision "$HEAD_SHA"
+            --directory iceberg-head --key "$HEAD_KEY" --revision "$HEAD_SHA" 
--kind head \
+            --native-image "$NATIVE_IMAGE" --test-image "$TEST_IMAGE"
       - name: Save the result for reuse after merge
         if: always() && steps.head-identity.outcome == 'success'
         uses: actions/upload-artifact@v7
@@ -182,12 +180,13 @@ jobs:
           if-no-files-found: error
           overwrite: true
       - name: Download the saved baseline or lookup diagnostic
-        if: always()
+        if: always() && needs.prepare.result == 'success'
         uses: actions/download-artifact@v8
         with:
           name: iceberg-baseline-lookup
           path: iceberg-base
       - name: Download freshly tested base shards
+        id: download-base
         if: always() && needs.prepare.outputs.run_base == 'true'
         uses: actions/download-artifact@v8
         with:
@@ -195,18 +194,51 @@ jobs:
           path: iceberg-base
       - name: Merge and validate every base shard
         id: base
-        if: always() && needs.prepare.outputs.run_base == 'true'
+        if: >-
+          always() && needs.prepare.outputs.run_base == 'true' &&
+          needs.iceberg-base-test.result == 'success' &&
+          steps.download-base.outcome == 'success' &&
+          hashFiles('iceberg-base/**/execution-coverage.json') != ''
         env:
           BASELINE_KEY: ${{ needs.prepare.outputs.baseline_key }}
           BASE_SHA: ${{ needs.prepare.outputs.base_sha }}
-          BASE_RESULT: ${{ needs.iceberg-base-test.result }}
         run: |
-          test "$BASE_RESULT" = success
           python3 .github/workflows/util/iceberg-upstream/merge.py 
iceberg-base --shards "$ICEBERG_SHARD_COUNT"
           python3 .github/workflows/util/iceberg-upstream/baseline.py record \
-            --directory iceberg-base --key "$BASELINE_KEY" --revision 
"$BASE_SHA"
-      - name: Reject regressions or validate initial baseline evidence
+            --directory iceberg-base --key "$BASELINE_KEY" --revision 
"$BASE_SHA" --kind base \
+            --native-image "$NATIVE_IMAGE" --test-image "$TEST_IMAGE"
+      # Cache the validated base independently of head build/tests and 
comparison.
+      - name: Save the tested base for reuse
+        if: always() && steps.base.outcome == 'success'
+        uses: actions/upload-artifact@v7
+        with:
+          name: ${{ needs.prepare.outputs.baseline_key }}
+          path: |
+            iceberg-base/baseline-identity.json
+            iceberg-base/execution-coverage.json
+          if-no-files-found: error
+          overwrite: true
+      - name: Download available build diagnostics
         if: always()
+        uses: actions/download-artifact@v8
+        with:
+          pattern: iceberg-*-diagnostics
+          path: iceberg-diagnostics
+      - name: Require complete comparison inputs
+        id: ready
+        if: always()
+        env:
+          PREPARE_RESULT: ${{ needs.prepare.result }}
+          UPSTREAM_RESULT: ${{ needs.iceberg-upstream-test.result }}
+          HEAD_OUTCOME: ${{ steps.head.outcome }}
+          BASE_RESULT: ${{ needs.iceberg-base-test.result }}
+          BASELINE_OUTCOME: ${{ needs.prepare.outputs.baseline_outcome }}
+          RUN_BASE: ${{ needs.prepare.outputs.run_base }}
+          BASE_OUTCOME: ${{ steps.base.outcome }}
+          INITIAL_BASELINE: ${{ needs.prepare.outputs.initial_baseline }}
+        run: python3 .github/workflows/util/iceberg-upstream/gate.py
+      - name: Reject regressions or validate initial baseline evidence
+        if: always() && steps.ready.outcome == 'success'
         env:
           BASELINE_OUTCOME: ${{ needs.prepare.outputs.baseline_outcome }}
           RUN_BASE: ${{ needs.prepare.outputs.run_base }}
@@ -239,6 +271,7 @@ jobs:
           path: |
             iceberg-base/
             iceberg-head/
+            iceberg-diagnostics/
             iceberg-comparison.json
             iceberg-comparison.csv
           if-no-files-found: error
diff --git a/.github/workflows/iceberg_upstream_revision.yml 
b/.github/workflows/iceberg_upstream_revision.yml
index c82c7d626e..999b70bdac 100644
--- a/.github/workflows/iceberg_upstream_revision.yml
+++ b/.github/workflows/iceberg_upstream_revision.yml
@@ -90,11 +90,20 @@ jobs:
         shell: bash
         run: |
           $MVN_CMD clean install -pl backends-velox -am $ICEBERG_PROFILES 
-Pfast-build -DskipTests \
-            -Dstyle.color=never | tee "$RUNNER_TEMP/iceberg-build.log"
+            -Dstyle.color=never 2>&1 | tee "$RUNNER_TEMP/iceberg-build.log"
           $MVN_CMD help:evaluate -N -q -Dexpression=settings.localRepository 
-Doutput="$RUNNER_TEMP/iceberg-repository"
           python3 
"$GITHUB_WORKSPACE/.github/workflows/util/iceberg-upstream/build-artifacts.py" 
pack \
             "$PWD" "$(cat "$RUNNER_TEMP/iceberg-repository")" 
"$RUNNER_TEMP/iceberg-build.zip" \
             --install-log "$RUNNER_TEMP/iceberg-build.log"
+      - name: Upload build diagnostics
+        if: always()
+        uses: actions/upload-artifact@v7
+        with:
+          name: iceberg-build-${{ inputs.label }}-diagnostics
+          path: ${{ runner.temp }}/iceberg-build.log
+          if-no-files-found: warn
+          retention-days: 1
+          overwrite: true
       - uses: actions/upload-artifact@v7
         with:
           name: iceberg-build-${{ inputs.label }}
diff --git a/.github/workflows/util/iceberg-upstream/baseline.py 
b/.github/workflows/util/iceberg-upstream/baseline.py
index da64292aee..3c2fc5ef98 100644
--- a/.github/workflows/util/iceberg-upstream/baseline.py
+++ b/.github/workflows/util/iceberg-upstream/baseline.py
@@ -14,7 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-"""Reuse saved Iceberg results only after verifying that their tested tree was 
merged."""
+"""Reuse verified Iceberg results with identical build, test and runtime 
inputs."""
 
 import argparse
 from datetime import datetime, timezone
@@ -46,11 +46,65 @@ HARNESS_PATHS = (
     ".github/workflows/iceberg_spark_ut.yml",
     ".github/workflows/iceberg_upstream_revision.yml",
     ".github/workflows/velox_native_build.yml",
+    ".github/workflows/velox_backend_x86.yml",
     ".github/workflows/util/iceberg-upstream",
     "backends-velox/pom.xml",
     "backends-velox/src-iceberg-upstream",
     "gluten-ut/src-iceberg-upstream",
 )
+# Keep every tracked production, dependency, build and test input, including
+# new/unknown paths. Only these known non-runtime inputs are excluded. In
+# particular, do not exclude *.md/*.rst globally: they can be test resources.
+NON_RUNTIME_PATHS = (
+    "docs/",
+    ".devcontainer/",
+    ".idea/",
+    ".github/ISSUE_TEMPLATE/",
+    ".github/PULL_REQUEST_TEMPLATE.md",
+    ".github/skills/",
+    ".asf.yaml",
+    "AGENTS.md",
+    "CONTRIBUTING.md",
+    "README.md",
+    "mkdocs.yml",
+)
+
+
+def input_fingerprint(entries):
+    """Hash Git paths, modes, types and object IDs; include gitlinks and 
symlinks."""
+    digest = hashlib.sha256()
+    for entry in sorted(entries, key=lambda item: item["path"]):
+        path = entry["path"]
+        if entry["type"] == "tree" or any(
+            path.startswith(name) if name.endswith("/") else path == name
+            for name in NON_RUNTIME_PATHS
+        ):
+            continue
+        # Other workflows do not execute in this comparison. Their supporting
+        # scripts remain inputs, as do all invoked workflow definitions.
+        if (
+            path.startswith(".github/workflows/")
+            and path.endswith((".yml", ".yaml"))
+            and path not in HARNESS_PATHS
+            and "/" not in path[len(".github/workflows/") :]
+        ):
+            continue
+        for field in ("path", "mode", "type", "sha"):
+            digest.update(entry[field].encode() + b"\0")
+    return digest.hexdigest()
+
+
+def git_inputs(revision):
+    entries = []
+    tree = git_tree(revision)
+    listing = subprocess.check_output(["git", "ls-tree", "-rz", tree])
+    for record in listing.split(b"\0"):
+        if not record:
+            continue
+        metadata, path = record.decode().split("\t", 1)
+        mode, kind, sha = metadata.split()
+        entries.append({"path": path, "mode": mode, "type": kind, "sha": sha})
+    return input_fingerprint(entries)
 
 
 def overlay_harness(checkout, harness):
@@ -127,11 +181,11 @@ def harness_hash(checkout):
     return digest.hexdigest()
 
 
-def artifact_key(tree, harness, native_image, test_image):
+def artifact_key(inputs, harness, native_image, test_image):
     runtime = hashlib.sha256(
         (harness + "\0" + native_image + "\0" + test_image).encode()
     ).hexdigest()
-    return "iceberg-baseline-v2-" + tree + "-" + runtime
+    return "iceberg-baseline-v3-" + inputs + "-" + runtime
 
 
 def git_tree(revision):
@@ -161,17 +215,30 @@ def initial_baseline(revision):
     return not existing.strip()
 
 
-def record(directory, key, revision):
+def record(directory, key, revision, kind, native_image, test_image):
     # Called only after all shards succeeded and their complete union was 
merged.
     index(json.loads((directory / "execution-coverage.json").read_text()))
     tree = git_tree(revision)
-    if not key.startswith("iceberg-baseline-v2-" + tree + "-"):
-        raise ValueError("Baseline key does not identify the tested tree")
+    inputs = git_inputs(revision)
+    harness = harness_hash(Path.cwd())
+    if key != artifact_key(inputs, harness, native_image, test_image):
+        raise ValueError(
+            "Baseline key does not identify the tested inputs and runtimes"
+        )
+    if kind not in ("head", "base"):
+        raise ValueError("Unknown baseline result kind")
     event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text())
     identity = {
         "key": key,
+        "kind": kind,
         "revision": revision,
         "tree": tree,
+        "inputs": inputs,
+        "harness": harness,
+        "harness_revision": os.environ["GITHUB_SHA"],
+        "native_image": native_image,
+        "test_image": test_image,
+        "shard_count": int(os.environ["ICEBERG_SHARD_COUNT"]),
         "repository": os.environ["GITHUB_REPOSITORY"],
         "run_id": int(os.environ["GITHUB_RUN_ID"]),
         "run_attempt": int(os.environ["GITHUB_RUN_ATTEMPT"]),
@@ -218,6 +285,23 @@ class GitHub:
             raise ValueError("Invalid baseline commit")
         return self.request("git/commits/" + revision)
 
+    def inputs(self, tree):
+        result = self.request("git/trees/" + tree + "?recursive=1")
+        if result.get("truncated"):
+            raise ValueError("Cannot verify inputs from a truncated Git tree")
+        return input_fingerprint(result["tree"])
+
+    def jobs(self, run_id, attempt):
+        jobs, page = [], 1
+        while True:
+            result = self.request(
+                
f"actions/runs/{run_id}/attempts/{attempt}/jobs?per_page=100&page={page}"
+            )["jobs"]
+            jobs.extend(result)
+            if len(result) < 100:
+                return jobs
+            page += 1
+
 
 def read_artifact(data):
     # Read two JSON documents, never extract or execute downloaded files.
@@ -233,18 +317,58 @@ def read_artifact(data):
         )
 
 
-def verify_source(api, artifact, identity, key, tree, branch):
+def verify_jobs(api, identity, workflow):
+    """A failed head or comparison does not invalidate successful base jobs."""
+    kind = identity["kind"]
+    prefix = "iceberg-base-test" if kind == "base" else "iceberg-upstream-test"
+    shared_native = workflow == ".github/workflows/velox_backend_x86.yml"
+    if shared_native:
+        prefix = "iceberg-spark-ut / " + prefix
+    # The x86 caller supplies head libraries; base still builds its own 
revision.
+    native = (
+        "build-native-lib-centos-8"
+        if shared_native and kind == "head"
+        else f"{prefix} / native / build"
+    )
+    count = identity.get("shard_count")
+    if type(count) is not int or count != int(
+        os.environ.get("ICEBERG_SHARD_COUNT", "5")
+    ):
+        raise ValueError("Baseline has an incompatible shard count")
+    expected = {native, f"{prefix} / build"} | {
+        f"{prefix} / iceberg-upstream-test (3.5, {kind}, {shard})"
+        for shard in range(count)
+    }
+    jobs = api.jobs(identity["run_id"], identity["run_attempt"])
+    for name in expected:
+        matches = [job for job in jobs if job["name"] == name]
+        if (
+            len(matches) != 1
+            or matches[0]["status"] != "completed"
+            or matches[0]["conclusion"] != "success"
+        ):
+            raise ValueError("Baseline requires a successful job: " + name)
+
+
+def verify_source(api, artifact, identity, key, inputs, branch):
     run_id = artifact["workflow_run"]["id"]
     attempt = identity.get("run_attempt")
     if (
         identity.get("key") != key
-        or identity.get("tree") != tree
+        or identity.get("inputs") != inputs
+        or identity.get("kind") not in ("head", "base")
         or identity.get("repository") != api.repository
         or identity.get("run_id") != run_id
         or type(attempt) is not int
         or attempt < 1
     ):
         raise ValueError("Baseline identity does not match this comparison")
+    if key != artifact_key(
+        inputs, identity["harness"], identity["native_image"], 
identity["test_image"]
+    ):
+        raise ValueError(
+            "Baseline harness or image identities differ from this comparison"
+        )
     run = api.request(f"actions/runs/{run_id}/attempts/{attempt}")
     if (
         run["repository"]["full_name"] != api.repository
@@ -254,39 +378,64 @@ def verify_source(api, artifact, identity, key, tree, 
branch):
     ):
         raise ValueError("Baseline is not from a completed Iceberg workflow")
     tested = api.tree(identity["revision"])
-    if tested["tree"]["sha"] != tree:
-        raise ValueError("Baseline tested tree differs from the base tree")
+    tree = tested["tree"]["sha"]
+    if identity.get("tree") != tree or api.inputs(tree) != inputs:
+        raise ValueError("Baseline tested inputs differ from the base inputs")
+    harness = api.tree(identity["harness_revision"])
     if run["event"] == "pull_request":
         number = identity.get("pull_request")
         if type(number) is not int or number < 1:
             raise ValueError("Baseline has no source pull request")
         pr = api.request(f"pulls/{number}")
         if (
-            not pr["merged"]
-            or pr["base"]["repo"]["full_name"] != api.repository
+            pr["base"]["repo"]["full_name"] != api.repository
             or pr["base"]["ref"] != branch
-            or pr["head"]["sha"] != run["head_sha"]
             or (pr["head"].get("repo") or {}).get("full_name")
             != (run.get("head_repository") or {}).get("full_name")
-            or len(tested["parents"]) != 2
-            or tested["parents"][1]["sha"] != run["head_sha"]
+            or len(harness["parents"]) != 2
+            or harness["parents"][1]["sha"] != run["head_sha"]
         ):
-            raise ValueError("Baseline was not tested at the merged PR's final 
head")
-        if api.tree(pr["merge_commit_sha"])["tree"]["sha"] != tree:
-            raise ValueError("PR merged different code than the saved test 
run")
-    elif (
-        run["event"] not in ("schedule", "workflow_dispatch")
-        or run["head_branch"] != branch
-        or run["head_repository"]["full_name"] != api.repository
-        or run["head_sha"] != identity["revision"]
-    ):
-        raise ValueError("Baseline is not a merged PR or a target-branch run")
+            raise ValueError(
+                "Baseline harness is not from a PR run for the target branch"
+            )
+        if identity["kind"] == "base":
+            # A base result tests the first parent of this run's merge checkout
+            # under its harness. The PR need not be merged or its head 
successful.
+            if harness["parents"][0]["sha"] != identity["revision"]:
+                raise ValueError("Baseline did not test the PR run's base 
revision")
+        else:
+            if (
+                not pr["merged"]
+                or pr["head"]["sha"] != run["head_sha"]
+                or identity["harness_revision"] != identity["revision"]
+            ):
+                raise ValueError(
+                    "Baseline was not tested at the merged PR's final head"
+                )
+            if api.tree(pr["merge_commit_sha"])["tree"]["sha"] != tree:
+                raise ValueError("PR merged different code than the saved test 
run")
+    else:
+        if (
+            run["event"] not in ("schedule", "workflow_dispatch")
+            or run["head_branch"] != branch
+            or run["head_repository"]["full_name"] != api.repository
+            or run["head_sha"] != identity["harness_revision"]
+        ):
+            raise ValueError("Baseline is not a merged PR or a target-branch 
run")
+        expected = (
+            harness["parents"][0]["sha"]
+            if identity["kind"] == "base"
+            else run["head_sha"]
+        )
+        if identity["revision"] != expected:
+            raise ValueError("Baseline did not test the target-branch run's 
revision")
+    verify_jobs(api, identity, run["path"])
 
 
 def restore(directory, key, revision, branch, api):
-    tree = api.tree(revision)["tree"]["sha"]
-    if not key.startswith("iceberg-baseline-v2-" + tree + "-"):
-        raise ValueError("Baseline key does not identify the base tree")
+    inputs = git_inputs(revision)
+    if not key.startswith("iceberg-baseline-v3-" + inputs + "-"):
+        raise ValueError("Baseline key does not identify the base inputs")
     errors = []
     page = 1
     while True:
@@ -299,9 +448,16 @@ def restore(directory, key, revision, branch, api):
                 identity, report = read_artifact(
                     api.request(f"actions/artifacts/{artifact['id']}/zip", 
binary=True)
                 )
-                verify_source(api, artifact, identity, key, tree, branch)
+                verify_source(api, artifact, identity, key, inputs, branch)
                 index(report)
-            except (ValueError, KeyError, OSError, zipfile.BadZipFile) as 
error:
+            except (
+                ValueError,
+                KeyError,
+                TypeError,
+                IndexError,
+                OSError,
+                zipfile.BadZipFile,
+            ) as error:
                 errors.append(f"Artifact {artifact['id']}: {error}")
                 continue
             directory.mkdir(parents=True, exist_ok=True)
@@ -339,6 +495,9 @@ if __name__ == "__main__":
     parser.add_argument("--harness", type=Path)
     parser.add_argument("--key")
     parser.add_argument("--branch")
+    parser.add_argument("--kind", choices=("head", "base"))
+    parser.add_argument("--native-image")
+    parser.add_argument("--test-image")
     args = parser.parse_args()
     if args.mode == "overlay":
         if args.directory is None or args.harness is None:
@@ -357,14 +516,23 @@ if __name__ == "__main__":
         print("test_image=" + test)
         print(
             "baseline_key="
-            + artifact_key(git_tree(args.revision), harness, native, test)
+            + artifact_key(git_inputs(args.revision), harness, native, test)
         )
-        print("head_key=" + artifact_key(git_tree("HEAD"), harness, native, 
test))
+        print("head_key=" + artifact_key(git_inputs("HEAD"), harness, native, 
test))
     else:
         if args.directory is None or args.key is None:
             parser.error("record/restore require --directory and --key")
         if args.mode == "record":
-            record(args.directory, args.key, args.revision)
+            if not all((args.kind, args.native_image, args.test_image)):
+                parser.error("record requires --kind, --native-image and 
--test-image")
+            record(
+                args.directory,
+                args.key,
+                args.revision,
+                args.kind,
+                args.native_image,
+                args.test_image,
+            )
         else:
             if not args.branch:
                 parser.error("restore requires --branch")
diff --git a/.github/workflows/util/iceberg-upstream/gate.py 
b/.github/workflows/util/iceberg-upstream/gate.py
new file mode 100644
index 0000000000..b49a3687ed
--- /dev/null
+++ b/.github/workflows/util/iceberg-upstream/gate.py
@@ -0,0 +1,81 @@
+#!/usr/bin/env python3
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Explain infrastructure failures before attempting an Iceberg comparison."""
+
+import json
+import os
+from pathlib import Path
+
+from compare import write_changes
+
+
+def unavailable_reasons(directory, status):
+    errors = []
+    for name, label in (
+        ("PREPARE_RESULT", "Baseline preparation"),
+        ("UPSTREAM_RESULT", "Upstream head build/tests"),
+    ):
+        if status.get(name) != "success":
+            errors.append(f"{label}: {status.get(name) or 'unavailable'}")
+    if (
+        status.get("HEAD_OUTCOME") != "success"
+        or not (directory / "iceberg-head/execution-coverage.json").is_file()
+    ):
+        errors.append("Complete head shard reports are unavailable")
+    if status.get("RUN_BASE") == "true":
+        if status.get("BASE_RESULT") != "success":
+            errors.append(
+                f"Base build/tests: {status.get('BASE_RESULT') or 
'unavailable'}"
+            )
+        baseline_ready = status.get("BASE_OUTCOME") == "success"
+    else:
+        baseline_ready = status.get("BASELINE_OUTCOME") == "success"
+    if status.get("INITIAL_BASELINE") != "true" and (
+        not baseline_ready
+        or not (directory / "iceberg-base/execution-coverage.json").is_file()
+    ):
+        errors.append("A complete, validated baseline is unavailable")
+    return errors
+
+
+def main():
+    errors = unavailable_reasons(Path.cwd(), os.environ)
+    if not errors:
+        return 0
+    text = (
+        "Iceberg comparison could not run. The gate remains failed; available "
+        "build diagnostics and test reports are retained.\n\n"
+        + "\n".join("- " + error for error in errors)
+        + "\n"
+    )
+    print(text)
+    if os.environ.get("GITHUB_STEP_SUMMARY"):
+        with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as output:
+            output.write(text)
+    Path("iceberg-comparison.json").write_text(
+        json.dumps(
+            {"comparison_performed": False, "validation_errors": errors, 
"changes": []},
+            indent=2,
+        )
+        + "\n"
+    )
+    write_changes(Path("iceberg-comparison.csv"), [])
+    return 1
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/.github/workflows/velox_native_build.yml 
b/.github/workflows/velox_native_build.yml
index aed0ab7c92..e7872c63c3 100644
--- a/.github/workflows/velox_native_build.yml
+++ b/.github/workflows/velox_native_build.yml
@@ -41,7 +41,15 @@ jobs:
       CCACHE_DIR: '${{ github.workspace }}/.ccache'
     steps:
       - name: Install CI tools (temporary - until image is rebuilt with 
gh/jq/bison/python3.9)
+        # Remove the legacy bootstrap after docker_image.yml publishes and 
verifies
+        # the rebuilt image on both architectures. New images require no 
downloads.
+        shell: bash
         run: |
+          exec > >(tee "$RUNNER_TEMP/velox-native-setup.log") 2>&1
+          if [ -f /usr/local/bin/verify-native-ci-tools ]; then
+            bash /usr/local/bin/verify-native-ci-tools
+            exit 0
+          fi
           dnf install -y jq bison tzdata
           dnf module -y install python39 && alternatives --set python3 
/usr/bin/python3.9
           dnf config-manager --add-repo 
https://cli.github.com/packages/rpm/gh-cli.repo
@@ -64,13 +72,26 @@ jobs:
           restore-keys: |
             ccache-almalinux8-release-default
       - name: Build Gluten native libraries
+        shell: bash
         run: |
           df -a
           export CCACHE_MAXSIZE=1G
           ccache -sz
-          bash dev/ci-velox-buildstatic-centos-8.sh
+          bash dev/ci-velox-buildstatic-centos-8.sh 2>&1 | tee 
"$RUNNER_TEMP/velox-native-build.log"
           ccache -s
 
+      - name: Upload native build diagnostics
+        if: always()
+        uses: actions/upload-artifact@v7
+        with:
+          name: ${{ inputs.artifact }}-diagnostics
+          path: |
+            ${{ runner.temp }}/velox-native-setup.log
+            ${{ runner.temp }}/velox-native-build.log
+          if-no-files-found: warn
+          retention-days: 1
+          overwrite: true
+
       - name: "Save ccache"
         if: always() && inputs.save-cache
         uses: 
apache/infrastructure-actions/stash/save@0ba14156c9f4c3cfbe4b0c9f36339ab0f8d81e53
diff --git a/dev/docker/Dockerfile.almalinux8-gcc13-static-build 
b/dev/docker/Dockerfile.almalinux8-gcc13-static-build
index 0115519619..6587ef6711 100644
--- a/dev/docker/Dockerfile.almalinux8-gcc13-static-build
+++ b/dev/docker/Dockerfile.almalinux8-gcc13-static-build
@@ -36,6 +36,8 @@ ENV VCPKG_PATH=/var/cache/vcpkg
 # Set vcpkg cache path.
 ENV VCPKG_BINARY_SOURCES=clear;files,${VCPKG_PATH},readwrite
 
+COPY dev/docker/verify-native-ci-tools.sh /usr/local/bin/verify-native-ci-tools
+
 RUN 
--mount=type=bind,source=dev/docker/install-ci-tools.sh,target=/tmp/install-ci-tools.sh
 \
     set -ex; \
     # AlmaLinux 8 repos are live — no mirror fixup needed. \
@@ -76,6 +78,7 @@ RUN 
--mount=type=bind,source=dev/docker/install-ci-tools.sh,target=/tmp/install-
     dnf module -y install python39; \
     alternatives --set python3 /usr/bin/python3.9; \
     bash /tmp/install-ci-tools.sh; \
+    bash /usr/local/bin/verify-native-ci-tools; \
     dnf clean all; \
     rm -rf /opt/gluten; \
     rm -rf /root/.cache/ccache;
diff --git a/dev/docker/verify-native-ci-tools.sh 
b/dev/docker/verify-native-ci-tools.sh
new file mode 100644
index 0000000000..450573b0ea
--- /dev/null
+++ b/dev/docker/verify-native-ci-tools.sh
@@ -0,0 +1,22 @@
+#!/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.
+
+set -euo pipefail
+
+gh --version
+jq --version
+bison --version
+python3 -c 'import sys; from zoneinfo import ZoneInfo; assert sys.version_info 
>= (3, 9); print(sys.version); print(ZoneInfo("UTC"), 
ZoneInfo("America/Los_Angeles"))'
diff --git a/gluten-ut/src-iceberg-upstream/test/python/test_baseline.py 
b/gluten-ut/src-iceberg-upstream/test/python/test_baseline.py
index cf5032b429..f1af91296f 100644
--- a/gluten-ut/src-iceberg-upstream/test/python/test_baseline.py
+++ b/gluten-ut/src-iceberg-upstream/test/python/test_baseline.py
@@ -38,7 +38,8 @@ baseline = importlib.util.module_from_spec(SPEC)
 SPEC.loader.exec_module(baseline)
 
 BASE, TESTED, HEAD, TREE = (character * 40 for character in "bcte")
-KEY = baseline.artifact_key(TREE, "harness", "native-digest", "test-digest")
+INPUTS = "f" * 64
+KEY = baseline.artifact_key(INPUTS, "harness", "native-digest", "test-digest")
 REPORT = {
     "version": 2,
     "tests": [{"class": "TestIceberg", "name": "read", "status": 
"PASSED_FALLBACK"}],
@@ -56,11 +57,18 @@ def archive(identity, report=REPORT):
 class Source:
     repository = "apache/gluten"
 
-    def __init__(self):
+    def __init__(self, x86=False):
         self.identity = {
             "key": KEY,
+            "kind": "head",
             "revision": TESTED,
             "tree": TREE,
+            "inputs": INPUTS,
+            "harness": "harness",
+            "harness_revision": TESTED,
+            "native_image": "native-digest",
+            "test_image": "test-digest",
+            "shard_count": 5,
             "repository": self.repository,
             "run_id": 123,
             "run_attempt": 1,
@@ -92,15 +100,53 @@ class Source:
             BASE: {"tree": {"sha": TREE}},
             TESTED: {
                 "tree": {"sha": TREE},
-                "parents": [{"sha": "a" * 40}, {"sha": HEAD}],
+                "parents": [{"sha": BASE}, {"sha": HEAD}],
             },
         }
+        self.fingerprints = {TREE: INPUTS}
+        self.job_results = []
+        for kind, prefix in (
+            ("head", "iceberg-upstream-test"),
+            ("base", "iceberg-base-test"),
+        ):
+            for name in ["native / build", "build"] + [
+                f"iceberg-upstream-test (3.5, {kind}, {shard})" for shard in 
range(5)
+            ]:
+                self.job_results.append(
+                    {
+                        "name": f"{prefix} / {name}",
+                        "status": "completed",
+                        "conclusion": "success",
+                    }
+                )
+        if x86:
+            self.run["path"] = ".github/workflows/velox_backend_x86.yml"
+            for job in self.job_results:
+                if job["name"] == "iceberg-upstream-test / native / build":
+                    job.update(
+                        name="iceberg-upstream-test / native", 
conclusion="skipped"
+                    )
+                job["name"] = "iceberg-spark-ut / " + job["name"]
+            self.job_results.append(
+                {
+                    "name": "build-native-lib-centos-8",
+                    "status": "completed",
+                    "conclusion": "success",
+                }
+            )
         self.artifacts = [self.artifact]
         self.report = copy.deepcopy(REPORT)
 
     def tree(self, revision):
         return self.commits[revision]
 
+    def inputs(self, tree):
+        return self.fingerprints[tree]
+
+    def jobs(self, run_id, attempt):
+        assert (run_id, attempt) == (123, 1)
+        return self.job_results
+
     def request(self, path, binary=False):
         if path.startswith("actions/artifacts?"):
             return {"artifacts": self.artifacts}
@@ -113,10 +159,15 @@ class Source:
         raise AssertionError("Unexpected API request: " + path)
 
     def verify(self):
-        baseline.verify_source(self, self.artifact, self.identity, KEY, TREE, 
"main")
+        baseline.verify_source(self, self.artifact, self.identity, KEY, 
INPUTS, "main")
 
 
 class BaselineTest(unittest.TestCase):
+    def setUp(self):
+        inputs = patch.object(baseline, "git_inputs", return_value=INPUTS)
+        self.inputs = inputs.start()
+        self.addCleanup(inputs.stop)
+
     def 
test_changed_harness_runs_on_base_without_copying_production_changes(self):
         namespace = "{http://maven.apache.org/POM/4.0.0}";
         with tempfile.TemporaryDirectory() as temporary:
@@ -142,7 +193,7 @@ class BaselineTest(unittest.TestCase):
             stale = base / 
"backends-velox/src-iceberg-upstream/RemovedObserver.java"
             stale.touch()
             key = baseline.artifact_key(
-                TREE, baseline.harness_hash(head), "native", "jdk"
+                INPUTS, baseline.harness_hash(head), "native", "jdk"
             )
             source = Source()
             # Even a valid saved base result cannot be reused with a changed 
harness.
@@ -260,19 +311,34 @@ class BaselineTest(unittest.TestCase):
                 "GITHUB_REPOSITORY": "apache/gluten",
                 "GITHUB_RUN_ID": "123",
                 "GITHUB_RUN_ATTEMPT": "1",
+                "GITHUB_SHA": TESTED,
+                "ICEBERG_SHARD_COUNT": "5",
             }
             with patch.dict(os.environ, env), patch.object(
                 baseline, "git_tree", return_value=TREE
-            ):
-                baseline.record(root, KEY, TESTED)
+            ), patch.object(baseline, "harness_hash", return_value="harness"):
+                baseline.record(
+                    root, KEY, TESTED, "head", "native-digest", "test-digest"
+                )
                 identity = json.loads((root / 
"baseline-identity.json").read_text())
                 self.assertEqual(TESTED, identity["revision"])
                 self.assertEqual(99, identity["pull_request"])
+                self.assertEqual("head", identity["kind"])
+                self.assertEqual(INPUTS, identity["inputs"])
+                baseline.record(root, KEY, BASE, "base", "native-digest", 
"test-digest")
+                identity = json.loads((root / 
"baseline-identity.json").read_text())
+                self.assertEqual("base", identity["kind"])
+                self.assertEqual(BASE, identity["revision"])
+                self.assertEqual(TESTED, identity["harness_revision"])
+                with self.assertRaisesRegex(ValueError, "tested inputs and 
runtimes"):
+                    baseline.record(root, KEY, BASE, "base", "old-image", 
"test-digest")
                 invalid = copy.deepcopy(REPORT)
                 invalid["tests"][0]["status"] = "PASSED_NATIVE"
                 (root / 
"execution-coverage.json").write_text(json.dumps(invalid))
                 with self.assertRaisesRegex(ValueError, "Unproven native"):
-                    baseline.record(root, KEY, TESTED)
+                    baseline.record(
+                        root, KEY, TESTED, "head", "native-digest", 
"test-digest"
+                    )
 
     def 
test_squash_merge_reuses_the_tested_tree_despite_a_different_commit_sha(self):
         source = Source()
@@ -297,9 +363,131 @@ class BaselineTest(unittest.TestCase):
             source.verify()
         source = Source()
         source.commits[TESTED]["parents"][1]["sha"] = "d" * 40
-        with self.assertRaisesRegex(ValueError, "final head"):
+        with self.assertRaisesRegex(ValueError, "target branch"):
             source.verify()
 
+    def 
test_successful_base_survives_a_failed_unmerged_and_updated_pr_head(self):
+        source = Source()
+        source.identity.update(kind="base", revision=BASE)
+        source.pr.update(merged=False, merge_commit_sha=None)
+        # The source PR can have new commits since the saved run. The run's
+        # original merge parents, not the latest head, identify its tested 
base.
+        source.pr["head"]["sha"] = "d" * 40
+        for job in source.job_results:
+            if job["name"].startswith("iceberg-upstream-test / "):
+                job["conclusion"] = "failure"
+        source.verify()
+        with tempfile.TemporaryDirectory() as temporary:
+            root = Path(temporary)
+            baseline.restore(root, KEY, BASE, "main", source)
+            saved = json.loads((root / "baseline-identity.json").read_text())
+            self.assertEqual("base", saved["kind"])
+            self.assertTrue((root / "fallback.csv").is_file())
+
+    def 
test_every_base_build_and_shard_must_succeed_in_the_recorded_attempt(self):
+        for job_index in range(7, 14):
+            for failure in (
+                "failure",
+                "cancelled",
+                "skipped",
+                "missing",
+                "duplicate",
+                "in_progress",
+            ):
+                source = Source()
+                source.identity.update(kind="base", revision=BASE)
+                if failure == "missing":
+                    del source.job_results[job_index]
+                elif failure == "duplicate":
+                    
source.job_results.append(source.job_results[job_index].copy())
+                elif failure == "in_progress":
+                    source.job_results[job_index]["status"] = failure
+                else:
+                    source.job_results[job_index]["conclusion"] = failure
+                with self.subTest(
+                    job=job_index, failure=failure
+                ), self.assertRaisesRegex(ValueError, "successful job"):
+                    source.verify()
+
+    def 
test_base_revision_and_runtime_identities_are_not_accepted_on_trust(self):
+        for field in ("harness", "native_image", "test_image"):
+            source = Source()
+            source.identity.update(kind="base", revision=BASE)
+            source.identity[field] = "incompatible"
+            with self.subTest(field=field), self.assertRaisesRegex(
+                ValueError, "harness or image"
+            ):
+                source.verify()
+        source = Source()
+        source.identity.update(kind="base", revision=TESTED)
+        with self.assertRaisesRegex(ValueError, "base revision"):
+            source.verify()
+        source = Source()
+        source.identity.update(kind="base", revision=BASE)
+        source.fingerprints[TREE] = "changed-production-inputs"
+        with self.assertRaisesRegex(ValueError, "tested inputs"):
+            source.verify()
+        source = Source()
+        source.identity.update(kind="base", revision=BASE, shard_count=1)
+        with self.assertRaisesRegex(ValueError, "shard count"):
+            source.verify()
+
+    def test_base_result_from_a_target_branch_run_tests_its_first_parent(self):
+        source = Source()
+        source.identity.update(kind="base", revision=BASE)
+        source.run.update(
+            event="workflow_dispatch",
+            head_sha=TESTED,
+            head_branch="main",
+            head_repository={"full_name": source.repository},
+        )
+        source.verify()
+        source.identity["revision"] = TESTED
+        with self.assertRaisesRegex(ValueError, "run's revision"):
+            source.verify()
+
+    def test_older_report_is_reusable_after_unrelated_commits(self):
+        source = Source()
+        current = "d" * 40
+        source.commits[current] = {"tree": {"sha": "e" * 40}}
+        with tempfile.TemporaryDirectory() as temporary:
+            root = Path(temporary)
+            baseline.restore(root, KEY, current, "main", source)
+            saved = json.loads((root / "baseline-identity.json").read_text())
+            self.assertEqual(current, saved["compared_revision"])
+            self.assertEqual(TESTED, saved["revision"])
+            self.inputs.assert_called_with(current)
+        self.inputs.return_value = "changed-inputs"
+        with tempfile.TemporaryDirectory() as temporary, 
self.assertRaisesRegex(
+            ValueError, "base inputs"
+        ):
+            baseline.restore(Path(temporary), KEY, current, "main", source)
+
+    def test_truncated_remote_tree_cannot_establish_input_compatibility(self):
+        api = baseline.GitHub("apache/gluten")
+        with patch.object(api, "request", return_value={"truncated": True, 
"tree": []}):
+            with self.assertRaisesRegex(ValueError, "truncated"):
+                api.inputs(TREE)
+
+    def test_job_lookup_paginates_only_the_recorded_attempt(self):
+        api = baseline.GitHub("apache/gluten")
+        with patch.object(
+            api,
+            "request",
+            side_effect=[
+                {"jobs": [{"name": "first-page"}] * 100},
+                {"jobs": [{"name": "last-page"}]},
+            ],
+        ) as request:
+            self.assertEqual(101, len(api.jobs(123, 2)))
+            self.assertEqual(
+                [call.args[0] for call in request.call_args_list],
+                [
+                    
f"actions/runs/123/attempts/2/jobs?per_page=100&page={page}"
+                    for page in (1, 2)
+                ],
+            )
+
     def test_unmerged_or_wrong_target_pr_is_not_a_baseline(self):
         for change in ("unmerged", "branch", "repository"):
             source = Source()
@@ -310,7 +498,7 @@ class BaselineTest(unittest.TestCase):
             else:
                 source.pr["base"]["repo"]["full_name"] = "other/repo"
             with self.subTest(change=change), self.assertRaisesRegex(
-                ValueError, "final head"
+                ValueError, "final head|target branch"
             ):
                 source.verify()
 
@@ -321,11 +509,13 @@ class BaselineTest(unittest.TestCase):
             ("run_id", 999),
             ("run_attempt", "1"),
             ("tree", "different"),
+            ("inputs", "different"),
+            ("kind", "unknown"),
         ):
             source = Source()
             source.identity[field] = value
             with self.subTest(field=field), self.assertRaisesRegex(
-                ValueError, "identity"
+                ValueError, "identity|tested inputs"
             ):
                 source.verify()
         for field, value in (
@@ -341,9 +531,44 @@ class BaselineTest(unittest.TestCase):
                 source.verify()
 
     def test_result_from_the_x86_backend_workflow_is_a_baseline(self):
-        source = Source()
-        source.run["path"] = ".github/workflows/velox_backend_x86.yml"
+        source = Source(x86=True)
+        source.verify()
+
+    def test_x86_head_requires_the_shared_native_build(self):
+        for result in ("failure", "skipped", "missing"):
+            source = Source(x86=True)
+            native = next(
+                job
+                for job in source.job_results
+                if job["name"] == "build-native-lib-centos-8"
+            )
+            if result == "missing":
+                source.job_results.remove(native)
+            else:
+                native["conclusion"] = result
+            with self.subTest(result=result), self.assertRaisesRegex(
+                ValueError, "successful job: build-native-lib-centos-8"
+            ):
+                source.verify()
+
+    def test_x86_base_reuse_is_independent_of_failed_head_tests(self):
+        source = Source(x86=True)
+        source.identity.update(kind="base", revision=BASE)
+        source.pr.update(merged=False, merge_commit_sha=None)
+        for job in source.job_results:
+            if job["name"].startswith("iceberg-spark-ut / 
iceberg-upstream-test / "):
+                job["conclusion"] = "failure"
         source.verify()
+        with tempfile.TemporaryDirectory() as temporary:
+            baseline.restore(Path(temporary), KEY, BASE, "main", source)
+        # The successful shared head build cannot stand in for the base build.
+        source.job_results = [
+            job
+            for job in source.job_results
+            if job["name"] != "iceberg-spark-ut / iceberg-base-test / native / 
build"
+        ]
+        with self.assertRaisesRegex(ValueError, "successful job: .*native / 
build"):
+            source.verify()
 
     def 
test_manual_main_result_can_seed_baseline_without_a_passing_comparison(self):
         source = Source()
@@ -397,5 +622,111 @@ class BaselineTest(unittest.TestCase):
         self.assertIsNone(redirected.get_header("Authorization"))
 
 
+class InputFingerprintTest(unittest.TestCase):
+    def setUp(self):
+        self.temporary = tempfile.TemporaryDirectory()
+        self.addCleanup(self.temporary.cleanup)
+        self.root = Path(self.temporary.name)
+        self.git = ["git", "-C", str(self.root)]
+        subprocess.run(self.git + ["init", "-q"], check=True)
+        self.original = Path.cwd()
+        os.chdir(self.root)
+        self.addCleanup(os.chdir, self.original)
+
+    def tree(self):
+        subprocess.run(self.git + ["add", "."], check=True)
+        return subprocess.check_output(self.git + ["write-tree"], 
text=True).strip()
+
+    def write(self, name, data):
+        path = self.root / name
+        path.parent.mkdir(parents=True, exist_ok=True)
+        path.write_text(data)
+
+    def test_only_known_non_runtime_changes_preserve_the_fingerprint(self):
+        self.write("pom.xml", "production dependency versions")
+        first = self.tree()
+        fingerprint = baseline.git_inputs(first)
+        for name in (
+            "docs/developers/Guide.md",
+            "README.md",
+            "AGENTS.md",
+            ".github/ISSUE_TEMPLATE/bug.yml",
+            ".devcontainer/devcontainer.json",
+            ".github/workflows/unrelated.yml",
+        ):
+            self.write(name, "unrelated change")
+            with self.subTest(name=name):
+                self.assertNotEqual(first, self.tree())
+                self.assertEqual(fingerprint, baseline.git_inputs(self.tree()))
+        for name in (
+            "pom.xml",
+            "backends-velox/pom.xml",
+            "gluten-core/src/main/Runtime.scala",
+            "gluten-ui/src/main/Listener.scala",
+            "gluten-iceberg/src/main/Scan.java",
+            "gluten-substrait/src/main/plan.proto",
+            "gluten-arrow/pom.xml",
+            "backends-velox/src/test/resources/schema.md",
+            "shims/spark35/pom.xml",
+            "cpp/velox/Scan.cc",
+            "ep/build-velox/src/velox.patch",
+            ".gitmodules",
+            "dev/vcpkg/vcpkg.json",
+            "dev/builddeps-veloxbe.sh",
+            "build/mvn",
+            ".mvn/maven.config",
+            "new-module/src/main/Dependency.java",
+            ".github/workflows/util/build.sh",
+            ".github/workflows/velox_native_build.yml",
+            ".github/workflows/velox_backend_x86.yml",
+            "backends-velox/src-iceberg-upstream/test/java/Observer.java",
+        ):
+            self.write(name, "runtime change")
+            changed = baseline.git_inputs(self.tree())
+            with self.subTest(name=name):
+                self.assertNotEqual(fingerprint, changed)
+            fingerprint = changed
+
+    def test_renames_deletions_modes_symlinks_and_submodules_are_inputs(self):
+        self.write("build/mvn", "build script")
+        previous = baseline.git_inputs(self.tree())
+        (self.root / "build/mvn").chmod(0o755)
+        changed = baseline.git_inputs(self.tree())
+        self.assertNotEqual(previous, changed)
+        previous = changed
+        (self.root / "build/mvn").rename(self.root / "build/renamed")
+        changed = baseline.git_inputs(self.tree())
+        self.assertNotEqual(previous, changed)
+        previous = changed
+        (self.root / "build/renamed").unlink()
+        self.assertNotEqual(previous, baseline.git_inputs(self.tree()))
+        for kind, mode in (("blob", "120000"), ("commit", "160000")):
+            entry = {"path": "dependency", "mode": mode, "type": kind, "sha": 
"a" * 40}
+            previous = baseline.input_fingerprint([entry])
+            entry["sha"] = "b" * 40
+            self.assertNotEqual(previous, baseline.input_fingerprint([entry]))
+
+    def test_local_and_api_trees_use_the_same_fingerprint(self):
+        self.write("build/mvn", "script")
+        (self.root / "linked-input").symlink_to("build/mvn")
+        self.write("docs/ignored.md", "doc")
+        tree = self.tree()
+        entries = []
+        for record in subprocess.check_output(
+            self.git + ["ls-tree", "-rz", tree]
+        ).split(b"\0"):
+            if record:
+                metadata, path = record.decode().split("\t", 1)
+                mode, kind, sha = metadata.split()
+                entries.append(dict(path=path, mode=mode, type=kind, sha=sha))
+        # GitHub's recursive response also contains intermediate trees.
+        entries.append(dict(path="build", mode="040000", type="tree", sha="c" 
* 40))
+        api = baseline.GitHub("apache/gluten")
+        with patch.object(
+            api, "request", return_value={"truncated": False, "tree": entries}
+        ):
+            self.assertEqual(baseline.git_inputs(tree), api.inputs(tree))
+
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/gluten-ut/src-iceberg-upstream/test/python/test_gate.py 
b/gluten-ut/src-iceberg-upstream/test/python/test_gate.py
new file mode 100644
index 0000000000..9652dad720
--- /dev/null
+++ b/gluten-ut/src-iceberg-upstream/test/python/test_gate.py
@@ -0,0 +1,126 @@
+# 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.
+
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+
+SCRIPT = (
+    Path(__file__).resolve().parents[4]
+    / ".github/workflows/util/iceberg-upstream/gate.py"
+)
+sys.path.insert(0, str(SCRIPT.parent))
+from gate import unavailable_reasons
+
+
+class GateTest(unittest.TestCase):
+    def setUp(self):
+        self.temporary = tempfile.TemporaryDirectory()
+        self.addCleanup(self.temporary.cleanup)
+        self.root = Path(self.temporary.name)
+        self.status = {
+            "PREPARE_RESULT": "success",
+            "UPSTREAM_RESULT": "success",
+            "HEAD_OUTCOME": "success",
+            "RUN_BASE": "false",
+            "BASELINE_OUTCOME": "success",
+            "BASE_RESULT": "skipped",
+            "BASE_OUTCOME": "skipped",
+            "INITIAL_BASELINE": "false",
+        }
+        for name in ("iceberg-base", "iceberg-head"):
+            (self.root / name).mkdir()
+            (self.root / name / "execution-coverage.json").write_text("{}")
+
+    def test_cached_and_fresh_baselines_allow_comparison(self):
+        self.assertEqual([], unavailable_reasons(self.root, self.status))
+        self.status.update(
+            RUN_BASE="true",
+            BASELINE_OUTCOME="failure",
+            BASE_RESULT="success",
+            BASE_OUTCOME="success",
+        )
+        self.assertEqual([], unavailable_reasons(self.root, self.status))
+
+    def test_failed_jobs_or_missing_inputs_cannot_claim_a_comparison(self):
+        for field in (
+            "PREPARE_RESULT",
+            "UPSTREAM_RESULT",
+            "HEAD_OUTCOME",
+            "BASELINE_OUTCOME",
+        ):
+            for result in ("failure", "skipped", "cancelled", ""):
+                with self.subTest(field=field, result=result):
+                    self.assertTrue(
+                        unavailable_reasons(
+                            self.root, dict(self.status, **{field: result})
+                        )
+                    )
+        for name in ("iceberg-base", "iceberg-head"):
+            path = self.root / name / "execution-coverage.json"
+            path.unlink()
+            with self.subTest(name=name):
+                self.assertTrue(unavailable_reasons(self.root, self.status))
+            path.write_text("{}")
+
+    def 
test_failed_base_does_not_use_partial_reports_or_successful_lookup(self):
+        self.status.update(
+            RUN_BASE="true", BASE_RESULT="failure", BASE_OUTCOME="skipped"
+        )
+        errors = unavailable_reasons(self.root, self.status)
+        self.assertIn("Base build/tests: failure", errors)
+        self.assertIn("A complete, validated baseline is unavailable", errors)
+
+    def test_bootstrap_still_requires_a_complete_successful_head(self):
+        (self.root / "iceberg-base/execution-coverage.json").unlink()
+        self.status.update(INITIAL_BASELINE="true", BASELINE_OUTCOME="failure")
+        self.assertEqual([], unavailable_reasons(self.root, self.status))
+        self.status["UPSTREAM_RESULT"] = "failure"
+        self.assertTrue(unavailable_reasons(self.root, self.status))
+
+    def 
test_failed_build_exports_explicit_diagnostics_and_preserves_base(self):
+        (self.root / "iceberg-head/execution-coverage.json").unlink()
+        (self.root / "iceberg-diagnostics").mkdir()
+        log = self.root / "iceberg-diagnostics/native-build.log"
+        log.write_text("dependency download failed")
+        identity = self.root / "iceberg-base/baseline-identity.json"
+        identity.write_text('{"kind": "base"}')
+        self.status.update(UPSTREAM_RESULT="failure", HEAD_OUTCOME="skipped")
+        summary = self.root / "summary.md"
+        result = subprocess.run(
+            [sys.executable, str(SCRIPT)],
+            cwd=self.root,
+            env=dict(os.environ, **self.status, 
GITHUB_STEP_SUMMARY=str(summary)),
+            text=True,
+            capture_output=True,
+        )
+        self.assertEqual(1, result.returncode, result.stderr)
+        self.assertIn("comparison could not run", result.stdout)
+        self.assertIn("Upstream head build/tests: failure", 
summary.read_text())
+        self.assertNotIn("Traceback", result.stderr)
+        diagnostic = json.loads((self.root / 
"iceberg-comparison.json").read_text())
+        self.assertFalse(diagnostic["comparison_performed"])
+        self.assertTrue(diagnostic["validation_errors"])
+        self.assertTrue((self.root / "iceberg-comparison.csv").is_file())
+        self.assertEqual('{"kind": "base"}', identity.read_text())
+        self.assertEqual("dependency download failed", log.read_text())
+
+
+if __name__ == "__main__":
+    unittest.main()


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to