LuciferYang commented on code in PR #13662:
URL: https://github.com/apache/gluten/pull/13662#discussion_r4614149296


##########
.github/actions/cache-maven/action.yml:
##########
@@ -0,0 +1,35 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+name: Cache Maven distribution
+description: Cache the build/mvn distribution without caching Maven 
dependencies.
+runs:
+  using: composite
+  steps:
+    - name: Read pinned Maven version
+      id: maven
+      shell: bash
+      run: |
+        version=$(awk -F '[<>]' '/<maven[.]version>/ { print $3; exit }' 
pom.xml)
+        if [ -z "$version" ]; then
+          echo "::error::Could not read maven.version from pom.xml"
+          exit 1
+        fi
+        echo "version=$version" >> "$GITHUB_OUTPUT"
+    - name: Cache Maven distribution
+      uses: actions/cache@v4

Review Comment:
   `actions/cache` saves only in its post step, after the job succeeds. A fork 
run restores only from its own branch or the fork's `main`, and no push or 
scheduled run covers `main`. So a branch's first run gets its cache from 
whichever early container job succeeds first, normally `build-fast-build-test`. 
A PR that touches only a shim for Spark 3.4 through 4.1 or only 
`tools/gluten-it` has no such job, so its Maven jobs start together when 
`build-native-lib-centos-8` finishes, and nearly all download Maven as they do 
today.
   
   If `build/mvn` moves off repo1 (see my other comment), these misses only 
cost a mirror download. Otherwise, a container job after `detect-changes` that 
checks out, runs this action, then `build/mvn --version` would seed the cache. 
A host job won't work: `actions/cache` hashes the compression method into the 
cache version, and the `ubuntu-24.04` host has zstd, while the container jobs 
in run 44182492158 used gzip.



##########
.github/actions/cache-maven/action.yml:
##########
@@ -0,0 +1,35 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+name: Cache Maven distribution
+description: Cache the build/mvn distribution without caching Maven 
dependencies.
+runs:
+  using: composite
+  steps:
+    - name: Read pinned Maven version
+      id: maven
+      shell: bash
+      run: |
+        version=$(awk -F '[<>]' '/<maven[.]version>/ { print $3; exit }' 
pom.xml)
+        if [ -z "$version" ]; then
+          echo "::error::Could not read maven.version from pom.xml"
+          exit 1
+        fi
+        echo "version=$version" >> "$GITHUB_OUTPUT"
+    - name: Cache Maven distribution
+      uses: actions/cache@v4
+      with:
+        path: build/.mvn

Review Comment:
   The 429s this targets come from one URL: `build/mvn` line 69 downloads Maven 
from a hardcoded `repo1.maven.org` URL. The root `pom.xml` already resolves 
dependencies from the GCS mirror first (#11545), and Spark's `build/mvn` 
downloads the distribution from that mirror, falling back to 
`archive.apache.org`. The mirror has 3.9.16.
   
   Switching that URL, with a fallback for versions the mirror hasn't synced, 
is a one-file change. It takes repo1 out of every path: the 29 jobs in other 
workflows that call `build/mvn` without this cache (two of them run inside x86, 
via `iceberg-spark-ut`), a new branch's first run, and local builds. This PR 
covers one workflow with 21 copied steps and a test to keep them in sync.
   
   Could you link a job that failed with a 429? I'd rather change the download 
source first, here or in a separate PR, and then see whether the cache is still 
worth carrying.



##########
gluten-ut/src-ci/test/python/test_maven_distribution_cache.py:
##########
@@ -0,0 +1,157 @@
+# 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 os
+from pathlib import Path
+import re
+import subprocess
+import tempfile
+import unittest
+import xml.etree.ElementTree as ET
+
+import yaml
+
+ROOT = Path(__file__).resolve().parents[4]
+ACTION = yaml.safe_load((ROOT / 
".github/actions/cache-maven/action.yml").read_text())
+VERSION_STEP = next(
+    step for step in ACTION["runs"]["steps"] if step.get("id") == "maven"
+)
+CACHE_STEP = next(
+    step
+    for step in ACTION["runs"]["steps"]
+    if step.get("uses", "").startswith("actions/cache@")
+)
+
+
+def read_version(pom):
+    with tempfile.TemporaryDirectory() as temporary:
+        root = Path(temporary)
+        (root / "pom.xml").write_text(pom)
+        binary = root / "mvn"
+        binary.write_text("#!/usr/bin/env bash\nexit 99\n")
+        binary.chmod(0o755)
+        output = root / "output"
+        result = subprocess.run(
+            [
+                "bash",
+                "--noprofile",
+                "--norc",
+                "-eo",
+                "pipefail",
+                "-c",
+                VERSION_STEP["run"],
+            ],
+            cwd=root,
+            env={
+                **os.environ,
+                "GITHUB_OUTPUT": str(output),
+                "PATH": f"{root}{os.pathsep}{os.environ['PATH']}",
+            },
+            capture_output=True,
+            text=True,
+        )
+        return result, output.read_text() if output.exists() else ""
+
+
+def cache_key(version, os_name="Linux", arch="X64"):
+    values = {
+        "runner.os": os_name,
+        "runner.arch": arch,
+        "steps.maven.outputs.version": version,
+    }
+    return re.sub(
+        r"\$\{\{\s*(.*?)\s*\}\}",
+        lambda match: values[match.group(1)],
+        CACHE_STEP["with"]["key"],
+    )
+
+
+class MavenDistributionCacheTest(unittest.TestCase):
+    def test_reads_pinned_version_without_running_maven(self):
+        pom = (ROOT / "pom.xml").read_text()
+        version = ET.fromstring(pom).findtext("{*}properties/{*}maven.version")
+        for content in (
+            pom,
+            pom.replace("<name>Gluten Parent Pom</name>", 
"<name>Other</name>"),
+        ):
+            with self.subTest(pom=content[:40]):
+                result, output = read_version(content)
+                self.assertEqual(0, result.returncode, result.stdout + 
result.stderr)
+                self.assertEqual(f"version={version}\n", output)
+
+        updated = "4.0.0-rc-3"
+        result, output = read_version(
+            pom.replace(
+                f"<maven.version>{version}</maven.version>",
+                f"<maven.version>{updated}</maven.version>",
+            )
+        )
+        self.assertEqual(0, result.returncode, result.stdout + result.stderr)
+        self.assertEqual(f"version={updated}\n", output)
+        self.assertEqual(
+            4,
+            len(
+                {
+                    cache_key(version),
+                    cache_key(updated),
+                    cache_key(version, os_name="macOS"),
+                    cache_key(version, arch="ARM64"),
+                }
+            ),
+        )
+        self.assertNotIn("restore-keys", CACHE_STEP["with"])
+        self.assertEqual("build/.mvn", CACHE_STEP["with"]["path"])
+
+    def test_missing_or_empty_version_fails(self):
+        for pom in ("<project/>", 
"<project><maven.version></maven.version></project>"):
+            with self.subTest(pom=pom):
+                result, output = read_version(pom)
+                self.assertNotEqual(0, result.returncode)
+                self.assertIn("::error::", result.stdout)
+                self.assertEqual("", output)
+
+    def test_every_direct_maven_job_restores_before_building(self):
+        workflow = yaml.safe_load(
+            (ROOT / ".github/workflows/velox_backend_x86.yml").read_text()
+        )
+        for name, job in workflow["jobs"].items():
+            steps = job.get("steps", [])
+            builds = [
+                index
+                for index, step in enumerate(steps)
+                if re.search(r"\$MVN_CMD\b|\bbuild/mvn\s", step.get("run", ""))

Review Comment:
   The job detection here matches `$MVN_CMD` and `build/mvn` followed by 
whitespace, but not `${MVN_CMD}`, `${{ env.MVN_CMD }}`, or a quoted 
`"$GITHUB_WORKSPACE/build/mvn"`. A Maven step written one of those ways isn't 
detected, so its job passes without the cache step. Nothing in the file uses 
those forms today.
   
   `r"\$\{?MVN_CMD\b|env\.MVN_CMD\b|\bbuild/mvn[\s\"']"` covers them and still 
classifies every current job the same way. Plain `\bbuild/mvn\b` is too loose: 
it matches the `build/mvn)` in the `detect-changes` path regexes.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to