spark-test commented on code in PR #57645:
URL: https://github.com/apache/spark/pull/57645#discussion_r4508616583


##########
dev/validate-distribution:
##########
@@ -0,0 +1,247 @@
+#!/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.
+#
+
+"""
+Validate a built Spark distribution.
+"""
+
+import argparse
+import os
+import re
+import subprocess
+import sys
+import tarfile
+import tempfile
+from contextlib import contextmanager
+from pathlib import Path
+
+
+REQUIRED_DIST_PATHS = [
+    "bin",
+    "jars",
+    "python/lib/pyspark.zip",
+    "sbin/start-master.sh",
+    "sbin/stop-master.sh",
+    "sbin/start-worker.sh",
+    "sbin/stop-worker.sh",
+    "sbin/start-history-server.sh",
+    "sbin/stop-history-server.sh",
+    "LICENSE",
+    "NOTICE",
+    "RELEASE",
+]
+
+SMOKE_TESTS = [
+    ("bin/spark-submit", "--master", "local[1]", 
"examples/src/main/python/pi.py", "1"),

Review Comment:
   **Blocking (P1):** With `-Phadoop-provided`, `jars/` contains no Hadoop 
client jars, and the launcher adds Hadoop jars only from `SPARK_DIST_CLASSPATH` 
(`AbstractCommandBuilder.buildClassPath`). Nothing sets that variable during a 
build, and `SparkSubmit.prepareSubmitEnvironment` creates a Hadoop 
`Configuration` on every submission, so this `pi.py` run fails. Unless the 
caller happens to export `SPARK_DIST_CLASSPATH`, the validator then exits 1, 
and so does `make-distribution.sh`, after a correct Hadoop-free build. The same 
failure occurs for the `without-hadoop` package that `release-build.sh` builds. 
One fix: when `jars/` has no `hadoop-client-api` jar and `SPARK_DIST_CLASSPATH` 
is unset, skip this smoke test with a clear "skipped: Hadoop-free distribution" 
message and keep running the other checks.
   
   **Verification:**
   - **Regression:** Validating a correct Hadoop-free distribution with 
SPARK_DIST_CLASSPATH unset passes and reports the PySpark smoke test as skipped.
   - **Behavior:** Validating a Hadoop-bundled distribution whose spark-submit 
fails still reports the smoke-test failure and exits non-zero.



##########
dev/validate-distribution:
##########
@@ -0,0 +1,247 @@
+#!/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.
+#
+
+"""
+Validate a built Spark distribution.
+"""
+
+import argparse
+import os
+import re
+import subprocess
+import sys
+import tarfile
+import tempfile
+from contextlib import contextmanager
+from pathlib import Path
+
+
+REQUIRED_DIST_PATHS = [
+    "bin",
+    "jars",
+    "python/lib/pyspark.zip",
+    "sbin/start-master.sh",
+    "sbin/stop-master.sh",
+    "sbin/start-worker.sh",
+    "sbin/stop-worker.sh",
+    "sbin/start-history-server.sh",
+    "sbin/stop-history-server.sh",
+    "LICENSE",

Review Comment:
   **Blocking (P1):** `make-distribution.sh` copies `LICENSE` and `NOTICE` into 
the distribution only when `LICENSE-binary` exists, and otherwise deliberately 
continues with "Skipping copying LICENSE files". `release-build.sh` removes 
`LICENSE-binary`, `NOTICE-binary` and `licenses-binary` from the official 
source release tarball. Building a distribution from that release with the 
documented `./dev/make-distribution.sh` workflow therefore now ends with 
`MISSING: LICENSE`, `MISSING: NOTICE` and exit 1 after a full build. Binary 
release builds always have `LICENSE-binary`, so only source trees without it 
are affected. One fix: have `make-distribution.sh` pass a flag when it skipped 
the license files, so the validator reports them as not bundled in that case 
and still requires them whenever they were copied.
   
   **Verification:**
   - **Regression:** A distribution built from a source tree without 
LICENSE-binary passes validation, with the license files reported as not 
bundled.
   - **Behavior:** A distribution built with LICENSE-binary but missing LICENSE 
or NOTICE still fails the structure check.



##########
dev/validate-distribution:
##########
@@ -0,0 +1,247 @@
+#!/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.
+#
+
+"""
+Validate a built Spark distribution.
+"""
+
+import argparse
+import os
+import re
+import subprocess
+import sys
+import tarfile
+import tempfile
+from contextlib import contextmanager
+from pathlib import Path
+
+
+REQUIRED_DIST_PATHS = [
+    "bin",
+    "jars",
+    "python/lib/pyspark.zip",
+    "sbin/start-master.sh",
+    "sbin/stop-master.sh",
+    "sbin/start-worker.sh",
+    "sbin/stop-worker.sh",
+    "sbin/start-history-server.sh",
+    "sbin/stop-history-server.sh",
+    "LICENSE",
+    "NOTICE",
+    "RELEASE",
+]
+
+SMOKE_TESTS = [
+    ("bin/spark-submit", "--master", "local[1]", 
"examples/src/main/python/pi.py", "1"),
+    ("sbin/start-thriftserver.sh", "--help"),
+    ("sbin/start-connect-server.sh", "--help"),
+]
+
+SMOKE_TEST_TIMEOUT = 120
+
+# Scripts that must have SPARK_CONNECT_MODE set in the Connect distribution.
+CONNECT_MODE_SCRIPTS = [
+    "bin/pyspark",
+    "bin/spark-shell",
+    "bin/spark-submit",
+]
+
+
+@contextmanager
+def resolve_distribution(dist_input: Path):
+    """Yield a directory path to a distribution, unpacking a .tgz to a temp 
dir if needed."""
+    if dist_input.is_dir():
+        yield dist_input.resolve()
+    elif dist_input.is_file():
+        with tempfile.TemporaryDirectory() as tmp:
+            work_dir = Path(tmp)
+            print(f"Unpacking {dist_input} into {work_dir}")
+            with tarfile.open(dist_input) as tf:
+                tf.extractall(work_dir, filter="data")
+            top_level = list(work_dir.iterdir())
+            if len(top_level) != 1:
+                print(
+                    f"Expected one top-level entry, got: {top_level}",
+                    file=sys.stderr,
+                )
+                sys.exit(1)
+            yield top_level[0]
+    else:
+        print(f"Not found: {dist_input}", file=sys.stderr)
+        sys.exit(1)
+
+
+def check_distribution(spark_dist: Path) -> list[str]:
+    errors = []
+    print(f"Testing distribution at: {spark_dist}\n")
+
+    print("Checking distribution structure...", end=" ", flush=True)
+    missing = [p for p in REQUIRED_DIST_PATHS if not (spark_dist / p).exists()]
+    for p in missing:
+        errors.append(f"MISSING: {p}")
+    if missing:
+        print("FAILED")
+        for p in missing:
+            print(f"  MISSING: {p}")
+    else:
+        print("OK")
+
+    # Isolate from the caller's Spark/Python environment so a source checkout
+    # cannot mask a broken distribution (e.g. SPARK-58428 / missing 
pyspark.zip).
+    env = os.environ.copy()
+    env["SPARK_HOME"] = str(spark_dist)
+    env["SPARK_CONNECT_MODE"] = "0"
+    env.pop("PYTHONPATH", None)
+    env.pop("SPARK_PREPEND_CLASSES", None)
+
+    for rel_path, *args in SMOKE_TESTS:
+        label = " ".join([rel_path, *args])
+        print(f"Checking {label}...", end=" ", flush=True)
+        try:
+            result = subprocess.run(
+                [str(spark_dist / rel_path), *args],
+                stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
+                timeout=SMOKE_TEST_TIMEOUT,
+                cwd=spark_dist,
+                env=env,
+            )
+        except subprocess.TimeoutExpired:
+            print("FAILED")
+            errors.append(f"{label}: timed out after {SMOKE_TEST_TIMEOUT}s")
+            continue
+        except OSError as e:
+            print("FAILED")
+            errors.append(f"{label}: {e}")
+            continue
+        if result.returncode != 0:
+            print("FAILED")
+            for line in result.stdout.splitlines():
+                print(f"  {line}")
+            errors.append(f"{label}: exited {result.returncode}")
+        else:
+            print("OK")
+
+    return errors
+
+
+def check_tar_has_license_notice(tar_path: Path, label: str) -> list[str]:
+    """
+    Verify LICENSE and NOTICE are at the package root per ASF policy.
+    See: 
https://www.apache.org/legal/release-policy.html#licensing-documentation
+    """
+    errors = []
+    print(f"Checking {label} for LICENSE and NOTICE...", end=" ", flush=True)
+    with tarfile.open(tar_path) as tf:
+        names = tf.getnames()
+    for required in ["LICENSE", "NOTICE"]:
+        pattern = re.compile(r"^[^/]+/" + re.escape(required) + r"$")
+        if not any(pattern.match(name) for name in names):
+            errors.append(f"{tar_path.name}: missing {required} at the package 
root")
+    if errors:
+        print("FAILED")
+        for e in errors:
+            print(f"  {e}")
+    else:
+        print("OK")
+    return errors
+
+
+def check_connect_scripts(spark_dist: Path) -> list[str]:
+    """Verify the Connect distribution has SPARK_CONNECT_MODE set in key 
scripts."""
+    errors = []
+    print("Checking Connect environment variables...", end=" ", flush=True)
+    for script in CONNECT_MODE_SCRIPTS:
+        path = spark_dist / script
+        if not path.exists():
+            errors.append(f"{script}: not found in Connect distribution")
+            continue
+        content = path.read_text()
+        if "SPARK_CONNECT_MODE" not in content:

Review Comment:
   **Nit (P3):** The unmodified `bin/pyspark` already contains 
`SPARK_CONNECT_MODE` (lines 86-90). This check therefore passes for 
`bin/pyspark` whether or not `make-distribution.sh` injected `export 
SPARK_CONNECT_MODE=${SPARK_CONNECT_MODE:-1}`, and a failing `awk` in that 
injection does not stop the build. The `SPARK_CONNECT_BEELINE` default in 
`bin/beeline` and the four `.cmd` defaults are never checked. The smoke tests 
run with `SPARK_CONNECT_MODE=0`, so nothing else would notice a missing default 
either. One fix: match the exact lines `make-distribution.sh` injects, 
including the ones for `bin/beeline` and the `.cmd` scripts.
   
   **Verification:**
   - **Regression:** Removing the injected default from bin/pyspark or 
bin/beeline in a Connect tarball makes validation fail for that script.
   - **Behavior:** A normally built Connect tarball passes the Connect script 
check.



##########
dev/validate-distribution:
##########
@@ -0,0 +1,247 @@
+#!/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.
+#
+
+"""
+Validate a built Spark distribution.
+"""
+
+import argparse
+import os
+import re
+import subprocess
+import sys
+import tarfile
+import tempfile
+from contextlib import contextmanager
+from pathlib import Path
+
+
+REQUIRED_DIST_PATHS = [
+    "bin",
+    "jars",
+    "python/lib/pyspark.zip",
+    "sbin/start-master.sh",
+    "sbin/stop-master.sh",
+    "sbin/start-worker.sh",
+    "sbin/stop-worker.sh",
+    "sbin/start-history-server.sh",
+    "sbin/stop-history-server.sh",
+    "LICENSE",
+    "NOTICE",
+    "RELEASE",
+]
+
+SMOKE_TESTS = [
+    ("bin/spark-submit", "--master", "local[1]", 
"examples/src/main/python/pi.py", "1"),
+    ("sbin/start-thriftserver.sh", "--help"),
+    ("sbin/start-connect-server.sh", "--help"),
+]
+
+SMOKE_TEST_TIMEOUT = 120
+
+# Scripts that must have SPARK_CONNECT_MODE set in the Connect distribution.
+CONNECT_MODE_SCRIPTS = [
+    "bin/pyspark",
+    "bin/spark-shell",
+    "bin/spark-submit",
+]
+
+
+@contextmanager
+def resolve_distribution(dist_input: Path):
+    """Yield a directory path to a distribution, unpacking a .tgz to a temp 
dir if needed."""
+    if dist_input.is_dir():
+        yield dist_input.resolve()
+    elif dist_input.is_file():
+        with tempfile.TemporaryDirectory() as tmp:
+            work_dir = Path(tmp)
+            print(f"Unpacking {dist_input} into {work_dir}")
+            with tarfile.open(dist_input) as tf:
+                tf.extractall(work_dir, filter="data")

Review Comment:
   **Non-blocking (P2):** The `filter` argument of `TarFile.extractall` was 
added in Python 3.12 and backported to 3.11.4, but Spark still supports Python 
3.11 from 3.11.0 (`python_requires=">=3.11"`), and `python/pyspark/install.py` 
avoids `filter="data"` for this reason. On 3.11.0-3.11.3 this line raises 
`TypeError` before any check runs, so every `--tgz` build on those interpreters 
exits 1 even when the distribution is correct. The release image installs 
Ubuntu jammy's apt `python3.11`, and whether that package includes the backport 
is unverified. One fix: pass `filter="data"` only when `hasattr(tarfile, 
"data_filter")`. Otherwise, reject any member whose resolved path escapes the 
extraction directory, as `_extract_tar` in `install.py` does, and extract 
without the argument.
   
   **Verification:**
   - **Compatibility:** Tarball validation succeeds both on an interpreter 
whose tarfile lacks the filter argument and on one that has it.
   - **Regression:** A tarball containing a path-traversal member is rejected 
on both extraction paths.



##########
dev/validate-distribution:
##########
@@ -0,0 +1,247 @@
+#!/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.
+#
+
+"""
+Validate a built Spark distribution.
+"""
+
+import argparse
+import os
+import re
+import subprocess
+import sys
+import tarfile
+import tempfile
+from contextlib import contextmanager
+from pathlib import Path
+
+
+REQUIRED_DIST_PATHS = [
+    "bin",
+    "jars",
+    "python/lib/pyspark.zip",
+    "sbin/start-master.sh",
+    "sbin/stop-master.sh",
+    "sbin/start-worker.sh",
+    "sbin/stop-worker.sh",
+    "sbin/start-history-server.sh",
+    "sbin/stop-history-server.sh",
+    "LICENSE",
+    "NOTICE",
+    "RELEASE",
+]
+
+SMOKE_TESTS = [
+    ("bin/spark-submit", "--master", "local[1]", 
"examples/src/main/python/pi.py", "1"),
+    ("sbin/start-thriftserver.sh", "--help"),
+    ("sbin/start-connect-server.sh", "--help"),
+]
+
+SMOKE_TEST_TIMEOUT = 120
+
+# Scripts that must have SPARK_CONNECT_MODE set in the Connect distribution.
+CONNECT_MODE_SCRIPTS = [
+    "bin/pyspark",
+    "bin/spark-shell",
+    "bin/spark-submit",
+]
+
+
+@contextmanager
+def resolve_distribution(dist_input: Path):
+    """Yield a directory path to a distribution, unpacking a .tgz to a temp 
dir if needed."""
+    if dist_input.is_dir():
+        yield dist_input.resolve()
+    elif dist_input.is_file():
+        with tempfile.TemporaryDirectory() as tmp:
+            work_dir = Path(tmp)
+            print(f"Unpacking {dist_input} into {work_dir}")
+            with tarfile.open(dist_input) as tf:
+                tf.extractall(work_dir, filter="data")
+            top_level = list(work_dir.iterdir())
+            if len(top_level) != 1:
+                print(
+                    f"Expected one top-level entry, got: {top_level}",
+                    file=sys.stderr,
+                )
+                sys.exit(1)
+            yield top_level[0]
+    else:
+        print(f"Not found: {dist_input}", file=sys.stderr)
+        sys.exit(1)
+
+
+def check_distribution(spark_dist: Path) -> list[str]:
+    errors = []
+    print(f"Testing distribution at: {spark_dist}\n")
+
+    print("Checking distribution structure...", end=" ", flush=True)
+    missing = [p for p in REQUIRED_DIST_PATHS if not (spark_dist / p).exists()]
+    for p in missing:
+        errors.append(f"MISSING: {p}")
+    if missing:
+        print("FAILED")
+        for p in missing:
+            print(f"  MISSING: {p}")
+    else:
+        print("OK")
+
+    # Isolate from the caller's Spark/Python environment so a source checkout
+    # cannot mask a broken distribution (e.g. SPARK-58428 / missing 
pyspark.zip).

Review Comment:
   **Nit (P3):** SPARK-58428 is "Fix optimizer hang in DSv2 expression 
pushdown" (24774823041), an unrelated SQL fix. The missing `pyspark.zip` 
problem this comment refers to is apache/spark pull request 58428, so cite that 
pull request or its own JIRA ID instead.
   
   **Verification:**
   - **Inspection:** The comment no longer cites SPARK-58428, and its reference 
identifies the pyspark.zip packaging problem.



##########
dev/make-distribution.sh:
##########
@@ -414,3 +395,21 @@ if [ "$MAKE_TGZ" == "true" ]; then
     rm -rf "$TARDIR"
   fi
 fi
+
+echo "Running distribution validation..."
+if [ "$MAKE_TGZ" == "true" ]; then
+  DIST_ARG="$SPARK_HOME/spark-$VERSION-bin-$NAME.tgz"
+else
+  DIST_ARG="$DISTDIR"
+fi
+VALIDATE_CMD=("$SPARK_HOME/dev/validate-distribution" "$DIST_ARG")
+if [ "$MAKE_PIP" == "true" ]; then
+  VALIDATE_CMD+=(--pip "$SPARK_HOME/python/dist")
+fi
+if [ "$MAKE_R" == "true" ]; then
+  VALIDATE_CMD+=(--r "$SPARK_HOME/R/SparkR_$VERSION.tar.gz")
+fi
+if [[ "$MAKE_TGZ" == "true" && "$MAKE_SPARK_CONNECT" == "true" ]]; then
+  VALIDATE_CMD+=(--connect "$SPARK_HOME/spark-$VERSION-bin-$NAME-connect.tgz")
+fi
+"${VALIDATE_CMD[@]}"

Review Comment:
   **Non-blocking (P2):** Running every check here, after the sdists, the 
SparkR package and the tarballs exist, changes what `release-build.sh` does 
when a check fails. It calls `make-distribution.sh` inside 
`make_binary_release` and only ever invokes that as `if ! make_binary_release 
...`, so `set -e` is off inside the function and its status is that of its last 
command. Before this PR, a failed LICENSE/NOTICE guard exited before any 
tarball existed, so the hadoop3 package's final Connect-tarball `shasum` failed 
and the release aborted. Now every artifact exists, so the function copies, 
signs and checksums them and returns 0. In a release, any validation failure, 
including a PySpark sdist or SparkR package missing `LICENSE` or `NOTICE` (the 
case SPARK-57393 was added to catch), shows up only on the console and in the 
per-package log while the release continues. Direct `make-distribution.sh` runs 
still exit non-zero.
   
   **Recommended change:** Make the release driver stop when a distribution 
build fails: check make-distribution.sh's exit status explicitly right after 
the call in make_binary_release and return a failure, so the existing 
package-failure error aborts the release instead of relying on missing 
artifacts.
   
   **Why this works:** An explicit status check works even though errexit is 
suppressed in the `if !` context. Any validation failure, including a PySpark 
or SparkR package missing LICENSE or NOTICE, then aborts the release before 
that package's artifacts are signed or staged.
   
   **Scope:** Release driver: honor the distribution build's exit status before 
signing and staging artifacts.
   
   **Compatibility:** Successful release packaging is unchanged: the same 
artifact names, signatures and checksums.
   
   **Risks:** Every false validation failure becomes a release blocker. The 
without-hadoop package fails the PySpark smoke test until Hadoop-free 
distributions are handled. Every tarball validation could also fail if the 
release image's python3.11 lacks tarfile's filter argument, or if the image has 
cpio and so omits python/lib/pyspark.zip.
   
   **Constraints:** Land this together with the fix that lets the PySpark smoke 
test accept Hadoop-free distributions, and confirm the release image's Python 
version and whether it has cpio before relying on the restored gate.
   
   **Success:** When make-distribution.sh exits non-zero for a package, 
release-build.sh reports that package as failed and aborts before signing or 
staging its artifacts. A release whose packages all pass validation proceeds 
exactly as before.
   
   **Verification:**
   - **Regression:** With a distribution build that writes all of its artifacts 
and then fails validation, the release driver aborts with its package-failure 
error and stages nothing for that package.
   - **Behavior:** With a distribution build that passes validation, the 
release driver copies, signs and checksums the same artifacts as before.



-- 
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