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

HyukjinKwon pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark-connect-rust.git


The following commit(s) were added to refs/heads/master by this push:
     new 8768cc4f [SPARK-61240][CONNECT][INFRA][TESTS] Run the official Connect 
suites against the drop-in in CI
8768cc4f is described below

commit 8768cc4f780c7fb144e0b7a72ed5d5be14005023
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Mon Nov 9 22:25:04 2026 +0900

    [SPARK-61240][CONNECT][INFRA][TESTS] Run the official Connect suites 
against the drop-in in CI
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61240](https://issues.apache.org/jira/browse/SPARK-61240): Run the 
official Spark Connect test suites against the drop-in in CI.
    
    - `scripts/run_official_tests.py` gets a `--dropin` mode. It builds an 
overlay of our `python/` tree with the built `_pyspark.so` and the official 
test packages our tree lacks (never overwriting our files), and runs each 
official Connect file with our own `pyspark` on the path, without the Rust 
transport injection. Discovery covers `sql/tests/connect`, `ml/tests/connect`, 
`errors/tests/connect` and `logger/tests/connect`, minus the three 
local-cluster-only files. Retries for `FLAKY_FI [...]
    - `scripts/dropin_deselect_plugin.py` is a small pytest plugin that applies 
the node-id suffix deselection, without loading the extension.
    - `scripts/dropin_known_failures.txt` is the manifest: whole files by 
design (gRPC client internals; the torch-based `pyspark.ml.connect` API 
replaced by the native ML API) and the four tests the official 4.3.0 reference 
also fails here. Real open gaps are not listed.
    - `.github/workflows/build_python_connect.yml` gets a `connect-dropin` job, 
parallel to `connect-parity`, with the same setup, serial run, and log upload.
    - Unit tests for discovery, overlay construction, dropin/transport runner 
selection and the deselect plugin.
    
    ### Why are the changes needed?
    
    The official Connect suites reach our code only through the transport in 
CI, with official PySpark building every plan. So the drop-in's own Rust-backed 
classes (DataFrame, Column, functions, readers) are only covered by our own 
tests. Locally the official files run against the drop-in with 2688 passed; 
nothing in CI gates that. Running them as a gate exposes the remaining gaps, 
which are listed in the PR description and tracked separately: 
`test_connect_session.py`, `test_connect_con [...]
    
    ### Does this PR introduce _any_ user-facing change?
    
    No. Test infrastructure only.
    
    ### How was this patch tested?
    
    - Local run of `run_official_tests.py --dropin` on master against a Spark 
4.3.0 Connect server, all 119 discovered files: 2688 passed, 9 failed, 2 
collection errors, 553 skipped. The 11 failing items are the open gaps above; 
the manifest entries are the reference-also-fails tests, which the official 
4.3.0 PySpark also fails on the same server.
    - New unit tests in `scripts/tests/test_run_official_tests.py` (discovery 
scope and exclusions, overlay adds official files without overwriting ours, 
dropin runner uses the deselect plugin and not the transport, transport mode 
unchanged, manifest lists no open gap, deselect plugin select/deselect 
semantics).
    - ruff check and ruff format --check on `scripts/` pass (ruff 0.14.0).
    - `python3 -m unittest discover -s scripts/tests` (22 tests) and ruff 
0.14.0 on `scripts/` pass. A local run of the new `--dropin` mode over its 
whole scope (119 files) on master's build against a Spark 4.3.0 Connect server 
(cwd `SPARK_HOME`, `SPARK_TESTING=1`): 2688 passed, 9 failed, 2 collection 
errors, 553 skipped, 15 files skipped by the manifest. The failures are the 
open drop-in gaps, which are deliberately not in the manifest and are fixed by 
SPARK-61235 (#416, `test_connect_co [...]
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5 and Claude Haiku 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #417 from HyukjinKwon/SPARK-61240-ci-dropin.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 .github/workflows/build_python_connect.yml | 157 ++++++++++++++++++++++
 scripts/dropin_deselect_plugin.py          |  41 ++++++
 scripts/dropin_known_failures.txt          |  38 ++++++
 scripts/run_official_tests.py              | 151 ++++++++++++++++++++--
 scripts/tests/test_run_official_tests.py   | 201 +++++++++++++++++++++++++++++
 5 files changed, 576 insertions(+), 12 deletions(-)

diff --git a/.github/workflows/build_python_connect.yml 
b/.github/workflows/build_python_connect.yml
index 9c3930f2..5ac2f101 100644
--- a/.github/workflows/build_python_connect.yml
+++ b/.github/workflows/build_python_connect.yml
@@ -288,6 +288,163 @@ jobs:
             /tmp/connect-server-localcluster.log
           if-no-files-found: warn
 
+  # ---------------------------------------------------------------------------
+  # Drop-in gate: the official connect suites run against OUR drop-in itself 
(the
+  # Rust-backed DataFrame, Column, functions, readers, ...), not through the 
transport.
+  # The parity gate above only exercises the transport under official PySpark 
classes,
+  # so without this job the drop-in's own classes are covered by our tests 
alone.
+  # Known by-design and environmental failures: 
scripts/dropin_known_failures.txt.
+  # ---------------------------------------------------------------------------
+  connect-dropin:
+    name: Connect drop-in (official suite against our drop-in)
+    runs-on: ubuntu-latest
+    # Serial, like connect-parity: sql, ml, errors and logger connect files, 
~45-60 min.
+    timeout-minutes: 120
+    steps:
+      - uses: actions/checkout@v4
+
+      - name: Set up Python 3.11
+        uses: actions/setup-python@v5
+        with:
+          python-version: "3.11"
+          cache: pip
+
+      - name: Set up JDK 17
+        uses: actions/setup-java@v4
+        with:
+          distribution: temurin
+          java-version: "17"
+
+      - name: Install Rust toolchain
+        run: |
+          rustup toolchain install stable --profile minimal
+          rustup default stable
+
+      - name: Cache cargo & target
+        uses: actions/cache@v4
+        with:
+          path: |
+            ~/.cargo/registry
+            ~/.cargo/git
+            target
+          key: ${{ runner.os }}-cargo-dropin-${{ hashFiles('**/Cargo.lock') }}
+          restore-keys: ${{ runner.os }}-cargo-dropin-
+
+      - name: Install system dependencies
+        run: |
+          sudo apt-get update
+          sudo apt-get install -y protobuf-compiler
+
+      - name: Install Python dependencies
+        run: |
+          python -m pip install --upgrade pip
+          # Same environment as the parity gate (pandas 2.x; Spark 4.2+ is not 
compatible
+          # with pandas 3). torch and scikit-learn are NOT installed: the ML 
tests that need
+          # them skip themselves (pyspark.testing guards), and the torch-based 
pyspark.ml.connect
+          # files are by design (scripts/dropin_known_failures.txt).
+          python -m pip install pytest 'pandas>=2.2,<3.0' pyarrow numpy grpcio 
grpcio-status googleapis-common-protos cloudpickle zstandard py4j
+
+      - name: Build the Rust extension into the skin
+        run: |
+          cargo build -p pyspark-rs --release
+          cp target/release/lib_pyspark.so python/pyspark/_pyspark.so
+
+      - name: Cache Spark ${{ env.SPARK_VERSION }} distribution
+        uses: actions/cache@v4
+        with:
+          path: ~/spark-dist
+          key: spark-dist-${{ env.SPARK_VERSION }}-hadoop3
+
+      - name: Download Apache Spark ${{ env.SPARK_VERSION }} (Connect server)
+        id: spark-download
+        run: |
+          PKG="spark-${SPARK_VERSION}-bin-hadoop3-connect"
+          if [ ! -d "${HOME}/spark-dist/spark-4.3.0-bin-hadoop3"* ]; then
+            
URL="https://archive.apache.org/dist/spark/spark-${SPARK_VERSION}/${PKG}.tgz";
+            mkdir -p "${HOME}/spark-dist"
+            echo "Downloading ${URL}"
+            wget -q -O "${HOME}/spark-dist/${PKG}.tgz" "${URL}"
+            tar -xzf "${HOME}/spark-dist/${PKG}.tgz" -C "${HOME}/spark-dist"
+            rm -f "${HOME}/spark-dist/${PKG}.tgz"
+          else
+            echo "Using cached Spark distribution."
+          fi
+          SPARK_HOME=$(find "${HOME}/spark-dist" -maxdepth 1 -type d -name 
'spark-4.3.0-bin-hadoop3*' | head -1)
+          echo "SPARK_HOME=${SPARK_HOME}" >> "$GITHUB_OUTPUT"
+
+      - name: Cache Spark ${{ env.SPARK_VERSION }} source (official test files)
+        uses: actions/cache@v4
+        with:
+          path: ~/spark-source
+          key: spark-source-${{ env.SPARK_VERSION }}
+
+      - name: Clone Apache Spark v${{ env.SPARK_VERSION }} (official test 
files)
+        id: spark-source
+        run: |
+          if [ ! -d "${HOME}/spark-source/python" ]; then
+            git clone --depth 1 --branch "v${SPARK_VERSION}" \
+              https://github.com/apache/spark.git "${HOME}/spark-source"
+          else
+            echo "Using cached Spark source."
+          fi
+          echo "SPARK_SOURCE=${HOME}/spark-source" >> "$GITHUB_OUTPUT"
+
+      - name: Start Spark Connect server
+        env:
+          PYSPARK_PYTHON: python
+          PYSPARK_DRIVER_PYTHON: python
+        run: |
+          SPARK_HOME="${{ steps.spark-download.outputs.SPARK_HOME }}"
+          echo "Starting Connect server on ${SPARK_CONNECT_TESTING_REMOTE}"
+          # The server resolves the relative data paths of the official tests 
(such as the
+          # data/mllib files of the ML tests) against its working directory, 
as Apache's CI,
+          # which starts it from SPARK_HOME.
+          cd "${SPARK_HOME}"
+          # Same server settings as the parity gate (see connect-parity).
+          "${SPARK_HOME}/sbin/start-connect-server.sh" \
+            --driver-memory 3g \
+            --conf spark.sql.session.localRelationSizeLimit=1073741824 \
+            > /tmp/connect-server.log 2>&1 &
+          for i in $(seq 1 90); do
+            if (echo > /dev/tcp/localhost/15002) 2>/dev/null; then
+              echo "Connect server is up (after ${i}s)."; break
+            fi
+            if [ "$i" -eq 90 ]; then echo "Server failed to start:"; cat 
/tmp/connect-server.log; exit 1; fi
+            sleep 1
+          done
+
+      - name: Drop-in - official connect suites against OUR drop-in
+        id: dropin
+        env:
+          PYTHONUNBUFFERED: "1"
+          RUST_PYSPARK_SO: ${{ github.workspace }}/python/pyspark/_pyspark.so
+          RUST_PARITY_LOG_DIR: /tmp/dropin-test-logs
+          TZ: UTC
+          SPARK_HOME: ${{ steps.spark-download.outputs.SPARK_HOME }}
+        run: |
+          # --dropin runs each official file with our pyspark (an overlay of 
python/ with the
+          # built extension and the official test files), so the failures that 
remain are the
+          # drop-in's own: the manifest scripts/dropin_known_failures.txt 
holds only the by-design
+          # and environmental ones, and everything else fails the gate. Serial 
(--jobs 1).
+          set -o pipefail
+          python scripts/run_official_tests.py \
+            --dropin \
+            --spark "${{ steps.spark-source.outputs.SPARK_SOURCE }}" \
+            --remote "${SPARK_CONNECT_TESTING_REMOTE}" \
+            --jobs 1 \
+            2>&1 | tee /tmp/dropin_official.log
+
+      - name: Upload drop-in logs + server log
+        if: always()
+        uses: actions/upload-artifact@v4
+        with:
+          name: dropin-official-py3.11
+          path: |
+            /tmp/dropin-test-logs/
+            /tmp/dropin_official.log
+            /tmp/connect-server.log
+          if-no-files-found: warn
+
   # ---------------------------------------------------------------------------
   # Behavioral e2e tests (Rust drop-in against a live 4.3.0 server), in their 
OWN job
   # with a separate Connect server so they never share server state with the
diff --git a/scripts/dropin_deselect_plugin.py 
b/scripts/dropin_deselect_plugin.py
new file mode 100644
index 00000000..8b988277
--- /dev/null
+++ b/scripts/dropin_deselect_plugin.py
@@ -0,0 +1,41 @@
+"""pytest plugin: apply the known-failure manifest to the official suite run 
against the drop-in.
+
+The drop-in mode of run_official_tests.py (``--dropin``) runs the official 
test files
+against our own ``pyspark`` (the Rust-backed drop-in), so unlike 
rust_transport_plugin.py
+it must NOT load the extension or inject a transport. This plugin only 
deselects (or, for
+the drift check, selects only) the tests named in the environment, by node-id 
suffix, the
+same way rust_transport_plugin.py does:
+
+    RUST_PARITY_DESELECT     - newline-separated "Class::method" suffixes to 
drop
+    RUST_PARITY_SELECT_ONLY  - newline-separated suffixes to keep (the drift 
check)
+"""
+
+import os
+
+
+def _suffixes(raw):
+    return [s.strip() for s in raw.splitlines() if s.strip()]
+
+
+def pytest_collection_modifyitems(config, items):
+    select_only = os.environ.get("RUST_PARITY_SELECT_ONLY", "")
+    deselect = os.environ.get("RUST_PARITY_DESELECT", "")
+    suffixes = _suffixes(select_only or deselect)
+    if not suffixes:
+        return
+
+    def matches(nid):
+        # "...::Class::method" or a parametrized "...::Class::method[param]".
+        return any(nid.endswith(s) or f"::{s}[" in nid for s in suffixes)
+
+    keep, drop = [], []
+    for item in items:
+        hit = matches(item.nodeid)
+        # select-only keeps the hits and drops the rest; deselect does the 
opposite.
+        if hit == bool(select_only):
+            keep.append(item)
+        else:
+            drop.append(item)
+    if drop:
+        config.hook.pytest_deselected(items=drop)
+        items[:] = keep
diff --git a/scripts/dropin_known_failures.txt 
b/scripts/dropin_known_failures.txt
new file mode 100644
index 00000000..82a88357
--- /dev/null
+++ b/scripts/dropin_known_failures.txt
@@ -0,0 +1,38 @@
+# Known failures of the official Spark Connect test suite run against OUR 
drop-in
+# (run_official_tests.py --dropin). Format as 
scripts/parity_known_failures.txt:
+#   <relpath>                    # whole file skipped: by design for the 
drop-in
+#   <relpath>::Class::method     # one test deselected: environmental, or as 
the reference fails
+# relpath is relative to the overlay's python/ dir (the Spark python/ layout).
+#
+# Only BY-DESIGN and ENVIRONMENTAL entries belong here. A real drop-in gap (a 
test the
+# official suite passes on PySpark 4.3.0 and our drop-in fails) must stay 
visible: the gate
+# then fails until it is fixed (the gaps found first, in 
test_connect_session.py,
+# test_connect_context.py, test_connect_error.py, test_connect_column.py and 
the ML cache and
+# offloading tests, are fixed by SPARK-61235, SPARK-61238 and SPARK-61246). An 
entry that only
+# fails on a developer machine does not belong here either: CI's parity gate 
is the reference.
+
+# --- whole files: the gRPC client internals, which the Rust transport 
replaces by design ---
+pyspark/sql/tests/connect/client/test_client.py  # tests grpcio channel/stub 
internals; this client's transport is Rust (SPARK-61111 module audit)
+pyspark/sql/tests/connect/client/test_client_retries.py  # tests the grpcio 
retry policy of the Python client; the Rust transport has its own
+pyspark/sql/tests/connect/client/test_client_call_stack_trace.py  # tests the 
Python client's call-stack trace plumbing, which the Rust transport replaces
+pyspark/sql/tests/connect/test_connect_channel.py  # tests the grpcio channel 
builder; ChannelBuilder is Rust-backed here
+pyspark/sql/tests/connect/test_connect_retry.py  # tests the grpcio retry 
policy of the Python client; the Rust transport has its own
+pyspark/sql/tests/connect/test_connect_local_server.py  # starts a local 
grpcio server for the Python client; the Rust transport has no such server
+pyspark/sql/tests/connect/test_connect_plan.py  # tests the Python client's 
proto plan internals (LogicalPlan classes), built in Rust here
+
+# --- whole files: the deprecated torch-based pyspark.ml.connect API, replaced 
by the native ML API ---
+pyspark/ml/tests/connect/test_connect_classification.py  # imports 
LogisticRegressionModel from the torch-based pyspark.ml.connect; this client 
has the native ML API (dev/parity/4.3.0-module-audit.md)
+pyspark/ml/tests/connect/test_connect_feature.py  # imports MaxAbsScalerModel 
from the torch-based pyspark.ml.connect; native ML API (module audit)
+pyspark/ml/tests/connect/test_legacy_mode_classification.py  # legacy mode of 
the torch-based pyspark.ml.connect (classic SparkContext); native ML API 
(module audit)
+pyspark/ml/tests/connect/test_legacy_mode_evaluation.py  # legacy mode of the 
torch-based pyspark.ml.connect (classic SparkContext); native ML API (module 
audit)
+pyspark/ml/tests/connect/test_legacy_mode_feature.py  # legacy mode of the 
torch-based pyspark.ml.connect (classic SparkContext); native ML API (module 
audit)
+pyspark/ml/tests/connect/test_legacy_mode_pipeline.py  # legacy mode of the 
torch-based pyspark.ml.connect (classic SparkContext); native ML API (module 
audit)
+pyspark/ml/tests/connect/test_legacy_mode_summarizer.py  # legacy mode of the 
torch-based pyspark.ml.connect (classic SparkContext); native ML API (module 
audit)
+pyspark/ml/tests/connect/test_legacy_mode_tuning.py  # legacy mode of the 
torch-based pyspark.ml.connect (classic SparkContext); native ML API (module 
audit)
+
+# --- tests the reference client (official PySpark 4.3.0 over the same server) 
also fails here ---
+pyspark/sql/tests/connect/test_parity_dataframe.py::DataFrameParityTests::test_metadata_column
  # requires InMemoryCatalog for 'testcat' - a test-only catalog class absent 
from the Spark distribution
+pyspark/sql/tests/connect/test_parity_window.py::DataFrameParityTests::test_metadata_column
  # same test-only 'testcat' InMemoryCatalog as the DataFrame test; the 
reference fails it too
+
+# --- tests by design for the drop-in ---
+pyspark/sql/tests/connect/test_connect_error.py::SparkConnectErrorTests::test_recursion_handling_for_plan_logging
  # logs the Python plan of a deep DataFrame; the Rust core builds plans, so 
DataFrame._plan has no Python proto (dev/parity/known-differences.md)
diff --git a/scripts/run_official_tests.py b/scripts/run_official_tests.py
index 9107dad7..4f47af14 100755
--- a/scripts/run_official_tests.py
+++ b/scripts/run_official_tests.py
@@ -16,25 +16,63 @@ commit the update if it is environmental.
 Set ``RUST_PARITY_LOG_DIR`` to retain each pytest attempt (including 
tracebacks,
 retries, drift checks, and partial output on timeout). CI uploads these logs.
 
+Drop-in mode (``--dropin``) runs the same official files against OUR drop-in 
instead of
+through the transport: an overlay copy of our python/ tree (with the built 
extension) plus
+the official test packages that our tree lacks is put on PYTHONPATH, and the 
files run
+with our own ``pyspark`` classes (DataFrame, Column, functions, readers, ...). 
The local
+manifest is scripts/dropin_known_failures.txt. Discovery covers the Connect 
suites of sql,
+ml, errors and logger, minus the local-cluster-only files.
+
 Usage:
     RUST_PYSPARK_SO=/repo/python/pyspark/_pyspark.so \
     SPARK_CONNECT_TESTING_REMOTE=sc://localhost:15002 \
     python3 scripts/run_official_tests.py --spark ~/spark-source [--jobs 1]
+
+    RUST_PYSPARK_SO=/repo/python/pyspark/_pyspark.so \
+    SPARK_CONNECT_TESTING_REMOTE=sc://localhost:15002 \
+    python3 scripts/run_official_tests.py --dropin --spark ~/spark-source
 """
 
 from __future__ import annotations
 
 import argparse
 import concurrent.futures
+import functools
 import os
 import re
+import shutil
 import subprocess
 import sys
+import tempfile
 import time
 from pathlib import Path
 
 REPO = Path(__file__).resolve().parent.parent
 DEFAULT_MANIFEST = REPO / "scripts" / "parity_known_failures.txt"
+DROPIN_MANIFEST = REPO / "scripts" / "dropin_known_failures.txt"
+
+# Drop-in mode: the official packages copied into the overlay (only the files 
our tree
+# lacks; ours are never overwritten), the Connect suites discovered, and the 
files that
+# need a real multi-executor cluster (run by the local-cluster phase, not 
here).
+DROPIN_TEST_PACKAGES = (
+    "pyspark/sql/tests",
+    "pyspark/ml/tests",
+    "pyspark/errors/tests",
+    "pyspark/logger/tests",
+    "pyspark/resource/tests",
+    "pyspark/tests",
+)
+DROPIN_SCOPE = (
+    "pyspark/sql/tests/connect/",
+    "pyspark/ml/tests/connect/",
+    "pyspark/errors/tests/connect/",
+    "pyspark/logger/tests/connect/",
+)
+DROPIN_LOCAL_CLUSTER_ONLY = {
+    "test_artifact.py",
+    "test_artifact_localcluster.py",
+    "test_parity_resources.py",
+}
 
 # The only files whose failures are genuinely event-timing-driven: they wait on
 # real server-pushed events (streaming query progress/listener callbacks, 
observed
@@ -86,6 +124,44 @@ def discover(spark_py: Path):
     return out
 
 
+def discover_dropin(spark_py: Path):
+    """The official Connect suites of sql, ml, errors and logger, for the 
drop-in run."""
+    out = []
+    for p in sorted(spark_py.rglob("test_*.py")):
+        rel = p.relative_to(spark_py).as_posix()
+        if not rel.startswith(DROPIN_SCOPE):
+            continue
+        if p.name in DROPIN_LOCAL_CLUSTER_ONLY:
+            continue
+        out.append(p)
+    return out
+
+
+def build_dropin_overlay(repo_python: Path, spark_py: Path, so: Path, root: 
Path) -> Path:
+    """Build ``root/python``: our python/ tree, the built extension, and the 
official test packages.
+
+    Official files are copied only where our tree has no file of that path, so 
none of our
+    own files are overwritten. Returns the overlay's ``python`` dir (the new 
spark_py).
+    """
+    dst = root / "python"
+    shutil.copytree(
+        repo_python,
+        dst,
+        ignore=shutil.ignore_patterns("__pycache__", "*.pyc", ".pytest_cache"),
+    )
+    shutil.copy2(so, dst / "pyspark" / "_pyspark.so")
+    for pkg in DROPIN_TEST_PACKAGES:
+        for src in sorted((spark_py / pkg).rglob("*")):
+            if src.is_dir() or "__pycache__" in src.parts or src.suffix == 
".pyc":
+                continue
+            target = dst / src.relative_to(spark_py)
+            if target.exists():
+                continue
+            target.parent.mkdir(parents=True, exist_ok=True)
+            shutil.copy2(src, target)
+    return dst
+
+
 def resolve_only(spec: str, spark_py: Path):
     """Resolve a comma-separated `--only` list to explicit test-file Paths 
under spark_py.
 
@@ -156,14 +232,27 @@ def write_test_log(test_file: Path, spark_py: Path, text: 
str, select_only: bool
 
 
 def run_ours(
-    test_file: Path, spark_py: Path, remote: str, deselect, timeout: int, 
select_only=False
+    test_file: Path,
+    spark_py: Path,
+    remote: str,
+    deselect,
+    timeout: int,
+    select_only=False,
+    dropin=False,
 ):
     env = dict(os.environ)
     env["SPARK_CONNECT_TESTING_REMOTE"] = remote
     env["SPARK_TESTING"] = "1"
     env["SPARK_SKIP_CONNECT_COMPAT_TESTS"] = "1"
-    env["PYTHONPATH"] = os.pathsep.join([str(REPO / "scripts"), str(spark_py)])
-    env["RUST_PYSPARK_SO"] = os.environ["RUST_PYSPARK_SO"]
+    if dropin:
+        # The drop-in itself: no transport. scripts/ is on the path only for 
the deselect
+        # plugin; spark_py (the overlay) comes first, so our pyspark is the 
one imported.
+        env["PYTHONPATH"] = os.pathsep.join([str(spark_py), str(REPO / 
"scripts")])
+        plugin = "dropin_deselect_plugin"
+    else:
+        env["PYTHONPATH"] = os.pathsep.join([str(REPO / "scripts"), 
str(spark_py)])
+        env["RUST_PYSPARK_SO"] = os.environ["RUST_PYSPARK_SO"]
+        plugin = "rust_transport_plugin"
     # Deselection is done by the transport plugin 
(pytest_collection_modifyitems) via
     # this env var - matching node-id *suffixes* - rather than pytest's own 
--deselect.
     # --deselect compares against a node id relative to pytest's rootdir, 
which differs
@@ -185,7 +274,7 @@ def run_ours(
         "-p",
         "no:cacheprovider",
         "-p",
-        "rust_transport_plugin",
+        plugin,
     ]
     args.append(rel_file)
     try:
@@ -224,7 +313,15 @@ def main():
     ap.add_argument(
         "--remote", default=os.environ.get("SPARK_CONNECT_TESTING_REMOTE", 
"sc://localhost:15002")
     )
-    ap.add_argument("--manifest", default=str(DEFAULT_MANIFEST))
+    ap.add_argument(
+        "--dropin",
+        action="store_true",
+        help="Run the official Connect suites (sql, ml, errors, logger) 
against OUR drop-in "
+        "(an overlay of our python/ tree with the built extension and the 
official test "
+        "files) instead of through the Rust transport. Uses 
scripts/dropin_known_failures.txt "
+        "unless --manifest is given.",
+    )
+    ap.add_argument("--manifest", default=None)
     ap.add_argument("--jobs", type=int, default=1)
     ap.add_argument("--timeout", type=int, default=360)
     ap.add_argument(
@@ -266,13 +363,42 @@ def main():
     if not os.environ.get("RUST_PYSPARK_SO"):
         print("!! set RUST_PYSPARK_SO to the built extension")
         return 2
-    spark_py = Path(os.path.expanduser(args.spark)) / "python"
+    official_py = Path(os.path.expanduser(args.spark)) / "python"
+    manifest = (
+        Path(args.manifest)
+        if args.manifest
+        else (DROPIN_MANIFEST if args.dropin else DEFAULT_MANIFEST)
+    )
+    overlay = None
+    if args.dropin:
+        # The drop-in runs from an overlay (a scratch copy), so the repo tree 
is never
+        # touched by the official test files. Removed when the run ends.
+        overlay = Path(tempfile.mkdtemp(prefix="dropin-overlay-"))
+        spark_py = build_dropin_overlay(
+            REPO / "python", official_py, Path(os.environ["RUST_PYSPARK_SO"]), 
overlay
+        )
+        print(f"Drop-in overlay: {spark_py}", flush=True)
+    else:
+        spark_py = official_py
+    try:
+        return _run(args, spark_py, manifest)
+    finally:
+        if overlay is not None:
+            shutil.rmtree(overlay, ignore_errors=True)
+
+
+def _run(args, spark_py: Path, manifest: Path):
     if args.only:
         files = resolve_only(args.only, spark_py)
         missing = [f for f in files if not f.exists()]
         if missing:
             print("!! --only test file(s) not found:", *(str(m) for m in 
missing))
             return 2
+    elif args.dropin:
+        files = discover_dropin(spark_py)
+        if args.exclude:
+            drop = {x.strip() for x in args.exclude.split(",") if x.strip()}
+            files = [f for f in files if f.name not in drop]
     else:
         files = discover(spark_py)
         if args.exclude:
@@ -282,7 +408,10 @@ def main():
         print("!! no connect test files found under", spark_py)
         return 2
 
-    per_file, whole_file = load_manifest(Path(args.manifest))
+    # Every run (tests, retries, drift check) goes through the same runner, in 
the mode.
+    run = functools.partial(run_ours, dropin=args.dropin)
+
+    per_file, whole_file = load_manifest(manifest)
     n_skip = sum(len(v) for v in per_file.values())
     print(
         f"Discovered {len(files)} connect test files; manifest skips "
@@ -309,7 +438,7 @@ def main():
         # Slow-but-deterministic files get a larger per-file timeout (see
         # SLOW_FILE_TIMEOUTS); everything else uses the default cap.
         file_timeout = SLOW_FILE_TIMEOUTS.get(tf.name, args.timeout)
-        counts, failed_ids = run_ours(tf, spark_py, args.remote, deselect, 
file_timeout)
+        counts, failed_ids = run(tf, spark_py, args.remote, deselect, 
file_timeout)
         # Retry ONLY the event-timing-driven files (see FLAKY_FILES): for them 
a flake
         # clears on a fresh run while a genuine failure persists. 
Deterministic files
         # are NOT retried, so a non-deterministic bug there surfaces 
immediately rather
@@ -318,7 +447,7 @@ def main():
         attempts = 1
         while is_bad(counts) and attempts <= retries:
             attempts += 1
-            counts, failed_ids = run_ours(tf, spark_py, args.remote, deselect, 
file_timeout)
+            counts, failed_ids = run(tf, spark_py, args.remote, deselect, 
file_timeout)
         return tf.name, counts, failed_ids, False, attempts
 
     failures = []  # (file, [nodeids])
@@ -361,9 +490,7 @@ def main():
             tf = files_by_rel.get(rel)
             if tf is None:
                 continue
-            counts, _ = run_ours(
-                tf, spark_py, args.remote, suffixes, args.timeout, 
select_only=True
-            )
+            counts, _ = run(tf, spark_py, args.remote, suffixes, args.timeout, 
select_only=True)
             # All selected tests passed (some ran, and pytest exited clean).
             if counts.get("passed", 0) and not is_bad(counts):
                 now_passing.append((rel, counts.get("passed", 0), 
counts.get("skipped", 0)))
diff --git a/scripts/tests/test_run_official_tests.py 
b/scripts/tests/test_run_official_tests.py
index 6f926e2e..a414d4da 100644
--- a/scripts/tests/test_run_official_tests.py
+++ b/scripts/tests/test_run_official_tests.py
@@ -93,5 +93,206 @@ class ParityLogTests(unittest.TestCase):
             self.assertIn("TIMEOUT after 10s", log)
 
 
+class DropinTests(unittest.TestCase):
+    def _touch(self, root: Path, rel: str, text: str = "") -> Path:
+        path = root / rel
+        path.parent.mkdir(parents=True, exist_ok=True)
+        path.write_text(text)
+        return path
+
+    def 
test_discovery_covers_the_connect_suites_minus_local_cluster_files(self):
+        with tempfile.TemporaryDirectory() as td:
+            spark_py = Path(td) / "python"
+            for rel in (
+                "pyspark/sql/tests/connect/test_parity_types.py",
+                "pyspark/sql/tests/connect/arrow/test_parity_arrow_map.py",
+                "pyspark/sql/tests/connect/client/test_client.py",
+                "pyspark/sql/tests/connect/test_parity_resources.py",
+                "pyspark/sql/tests/connect/client/test_artifact.py",
+                
"pyspark/sql/tests/connect/client/test_artifact_localcluster.py",
+                "pyspark/ml/tests/connect/test_parity_als.py",
+                "pyspark/errors/tests/connect/test_parity_traceback.py",
+                "pyspark/logger/tests/connect/test_parity_logger.py",
+                # Outside the scope: classic sql, resource, top-level and 
ml/pandas tests.
+                "pyspark/sql/tests/test_dataframe.py",
+                "pyspark/resource/tests/test_connect_resources.py",
+                "pyspark/tests/test_context.py",
+                "pyspark/pandas/tests/connect/test_parity_frame.py",
+            ):
+                self._touch(spark_py, rel)
+            found = [p.relative_to(spark_py).as_posix() for p in 
runner.discover_dropin(spark_py)]
+        self.assertEqual(
+            found,
+            [
+                "pyspark/errors/tests/connect/test_parity_traceback.py",
+                "pyspark/logger/tests/connect/test_parity_logger.py",
+                "pyspark/ml/tests/connect/test_parity_als.py",
+                "pyspark/sql/tests/connect/arrow/test_parity_arrow_map.py",
+                "pyspark/sql/tests/connect/client/test_client.py",
+                "pyspark/sql/tests/connect/test_parity_types.py",
+            ],
+        )
+
+    def test_overlay_adds_official_files_and_never_overwrites_ours(self):
+        with tempfile.TemporaryDirectory() as td:
+            root = Path(td)
+            repo_python = root / "repo" / "python"
+            official = root / "spark" / "python"
+            self._touch(repo_python, "pyspark/__init__.py", "ours")
+            self._touch(repo_python, "pyspark/sql/tests/connect/test_own.py", 
"ours")
+            self._touch(repo_python, "pyspark/__pycache__/x.pyc", "stale")
+            self._touch(repo_python, "pyspark/_pyspark.so", "old")
+            self._touch(official, "pyspark/sql/tests/connect/test_own.py", 
"official")
+            self._touch(official, 
"pyspark/sql/tests/connect/test_official.py", "official")
+            self._touch(official, 
"pyspark/sql/tests/connect/__pycache__/t.pyc", "stale")
+            self._touch(official, 
"pyspark/ml/tests/connect/test_parity_als.py", "official")
+            self._touch(official, "pyspark/tests/test_context.py", "official")
+            self._touch(official, "pyspark/pandas/tests/test_frame.py", "not 
copied")
+            so = self._touch(root, "built/_pyspark.so", "built")
+            overlay = root / "overlay"
+            overlay.mkdir()
+
+            dst = runner.build_dropin_overlay(repo_python, official, so, 
overlay)
+
+            self.assertEqual(dst, overlay / "python")
+            self.assertEqual((dst / "pyspark/_pyspark.so").read_text(), 
"built")
+            self.assertEqual((dst / "pyspark/__init__.py").read_text(), "ours")
+            self.assertEqual((dst / 
"pyspark/sql/tests/connect/test_own.py").read_text(), "ours")
+            self.assertEqual(
+                (dst / 
"pyspark/sql/tests/connect/test_official.py").read_text(), "official"
+            )
+            self.assertEqual((dst / 
"pyspark/ml/tests/connect/test_parity_als.py").exists(), True)
+            self.assertTrue((dst / "pyspark/tests/test_context.py").exists())
+            self.assertFalse((dst / "pyspark/pandas").exists())
+            self.assertFalse((dst / "pyspark/__pycache__").exists())
+            self.assertFalse((dst / 
"pyspark/sql/tests/connect/__pycache__").exists())
+            # The repo tree itself is untouched.
+            self.assertEqual((repo_python / 
"pyspark/_pyspark.so").read_text(), "old")
+            self.assertFalse((repo_python / 
"pyspark/sql/tests/connect/test_official.py").exists())
+
+    def 
test_dropin_runs_without_the_transport_and_with_the_deselect_plugin(self):
+        result = subprocess.CompletedProcess([], 0, "1 passed in 0.1s", "")
+        with tempfile.TemporaryDirectory() as td:
+            spark_py = Path(td) / "overlay" / "python"
+            test_file = spark_py / "pyspark/sql/tests/connect/test_example.py"
+            with (
+                patch.dict(os.environ, {"RUST_PYSPARK_SO": "test.so"}),
+                patch.object(runner.subprocess, "run", return_value=result) as 
run,
+            ):
+                runner.run_ours(
+                    test_file, spark_py, "sc://localhost", ["Cls::test_a"], 
10, dropin=True
+                )
+                runner.run_ours(
+                    test_file,
+                    spark_py,
+                    "sc://localhost",
+                    ["Cls::test_b"],
+                    10,
+                    select_only=True,
+                    dropin=True,
+                )
+        deselect_call, drift_call = run.call_args_list
+        argv, kwargs = deselect_call.args[0], deselect_call.kwargs
+        env = kwargs["env"]
+        self.assertIn("dropin_deselect_plugin", argv)
+        self.assertNotIn("rust_transport_plugin", argv)
+        self.assertEqual(kwargs["cwd"], str(spark_py))
+        self.assertEqual(env["PYTHONPATH"].split(os.pathsep)[0], str(spark_py))
+        self.assertNotIn(str(runner.REPO / "python"), 
env["PYTHONPATH"].split(os.pathsep))
+        self.assertEqual(env["RUST_PARITY_DESELECT"], "Cls::test_a")
+        self.assertNotIn("RUST_PARITY_SELECT_ONLY", env)
+        # The drift check selects only the listed tests.
+        self.assertEqual(drift_call.kwargs["env"]["RUST_PARITY_SELECT_ONLY"], 
"Cls::test_b")
+
+    def test_transport_mode_is_unchanged(self):
+        result = subprocess.CompletedProcess([], 0, "1 passed in 0.1s", "")
+        with tempfile.TemporaryDirectory() as td:
+            spark_py = Path(td) / "python"
+            test_file = spark_py / "pyspark/sql/tests/connect/test_example.py"
+            with (
+                patch.dict(os.environ, {"RUST_PYSPARK_SO": "test.so"}),
+                patch.object(runner.subprocess, "run", return_value=result) as 
run,
+            ):
+                runner.run_ours(test_file, spark_py, "sc://localhost", [], 10)
+        argv, kwargs = run.call_args.args[0], run.call_args.kwargs
+        self.assertIn("rust_transport_plugin", argv)
+        self.assertNotIn("dropin_deselect_plugin", argv)
+        self.assertEqual(kwargs["env"]["RUST_PYSPARK_SO"], "test.so")
+
+    def test_dropin_manifest_lists_no_open_gap(self):
+        per_file, whole_file = runner.load_manifest(runner.DROPIN_MANIFEST)
+        gaps = (
+            "test_connect_session.py",
+            "test_connect_context.py",
+            "test_connect_error.py",
+            "test_connect_column.py",
+            "test_connect_cache.py",
+            "test_connect_model_offloading.py",
+        )
+        # The one test of those files that is by design: the Rust core builds 
the plans.
+        by_design = {
+            "pyspark/sql/tests/connect/test_connect_error.py": [
+                
"SparkConnectErrorTests::test_recursion_handling_for_plan_logging"
+            ],
+        }
+        for name in gaps:
+            self.assertFalse(any(p.endswith(name) for p in whole_file), name)
+            for path, tests in per_file.items():
+                if path.endswith(name):
+                    self.assertEqual(tests, by_design.get(path, []), path)
+        listed = list(per_file) + list(whole_file)
+        self.assertTrue(all(p.startswith(runner.DROPIN_SCOPE) for p in listed))
+
+
+def _load_deselect_plugin():
+    spec = importlib.util.spec_from_file_location(
+        "dropin_deselect_plugin", Path(__file__).resolve().parents[1] / 
"dropin_deselect_plugin.py"
+    )
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    return module
+
+
+class DropinDeselectPluginTests(unittest.TestCase):
+    class _Item:
+        def __init__(self, nodeid):
+            self.nodeid = nodeid
+
+    def _apply(self, env, nodeids):
+        from unittest.mock import MagicMock
+
+        plugin = _load_deselect_plugin()
+        items = [self._Item(n) for n in nodeids]
+        config = MagicMock()
+        with patch.dict(os.environ, env, clear=False):
+            for var in ("RUST_PARITY_DESELECT", "RUST_PARITY_SELECT_ONLY"):
+                if var not in env:
+                    os.environ.pop(var, None)
+            plugin.pytest_collection_modifyitems(config, items)
+        return [i.nodeid for i in items], config
+
+    def test_deselects_suffix_and_parametrized_matches_only(self):
+        nodeids = [
+            "pyspark/x/test_a.py::A::test_one",
+            "pyspark/x/test_a.py::A::test_one[param]",
+            "pyspark/x/test_a.py::A::test_two",
+            "pyspark/x/test_a.py::B::test_one_more",
+        ]
+        kept, config = self._apply({"RUST_PARITY_DESELECT": "A::test_one\n"}, 
nodeids)
+        self.assertEqual(kept, [nodeids[2], nodeids[3]])
+        config.hook.pytest_deselected.assert_called_once()
+
+    def test_select_only_keeps_the_listed_tests(self):
+        nodeids = ["pyspark/x/test_a.py::A::test_one", 
"pyspark/x/test_a.py::A::test_two"]
+        kept, _ = self._apply({"RUST_PARITY_SELECT_ONLY": "A::test_two"}, 
nodeids)
+        self.assertEqual(kept, [nodeids[1]])
+
+    def test_no_env_keeps_everything(self):
+        nodeids = ["pyspark/x/test_a.py::A::test_one"]
+        kept, config = self._apply({}, nodeids)
+        self.assertEqual(kept, nodeids)
+        config.hook.pytest_deselected.assert_not_called()
+
+
 if __name__ == "__main__":
     unittest.main()


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

Reply via email to