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

viirya 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 dfbe0465 [SPARK-61431][CONNECT][TESTS] Share the loopback service and 
the session and golden helpers of the Rust integration tests in a common module 
of each crate
dfbe0465 is described below

commit dfbe0465b9ff32e1352e18da1e47f4208c2690b2
Author: Liang-Chi Hsieh <[email protected]>
AuthorDate: Tue Nov 10 20:26:43 2026 -0800

    [SPARK-61431][CONNECT][TESTS] Share the loopback service and the session 
and golden helpers of the Rust integration tests in a common module of each 
crate
    
    ### What changes were proposed in this pull request?
    
    This moves the helpers that the Rust integration tests copy from file to 
file into a `tests/common/mod.rs` of each crate, taken with `mod common;`.
    
    `crates/spark-connect-core/tests/common/mod.rs` has `FakeService`, a route 
table for the loopback Spark Connect service. A test names the RPCs that its 
service answers and the `tonic::server` handler of each (`unary`, 
`server_streaming`, `client_streaming`, and `fallback_unary` for every other 
method); the module has the routing, the UNIMPLEMENTED answer of a method 
without a route, and the listener, whose server stops when the returned 
`FakeServer` is dropped. It replaces the `TestSe [...]
    
    `crates/spark-connect/tests/common/mod.rs` has:
    
    - `should_run()`, from 9 identical copies.
    - `session()`, from 8 identical copies, and `live_session()`, from the 4 
identical copies of the form that returns `None` without `SPARK_REMOTE` 
(`e2e_kmeans`, `e2e_linear_regression`, `e2e_linear_svc`, `e2e_random_forest`), 
whose callers are renamed to it.
    - `load_goldens(file, normalize)`, generic over the message, from 5 copies 
that differed in the file, the message type and the normalization. Each file 
keeps a `load_goldens()` of its own that calls it.
    - `normalize_relation()`, from the 2 identical copies of `ml_golden` and 
`ml_extra_golden`, with their `normalize_ml_*` helpers.
    
    Left where they are, or removed:
    
    - The recursive `normalize_relation` of `plans_golden` differs in behaviour 
and stays there.
    - The `normalize_relation` of `catalog_golden` and of `readwriter_golden` 
were never called (the file-level `#![allow(dead_code)]` hid them) and are 
removed.
    
    No test is renamed, moved or removed, and no assertion or golden file 
changes.
    
    ### Why are the changes needed?
    
    Each of the five loopback services was about 40 lines that differed only in 
the RPCs it routes, and a change to how the tests serve a fake server had to be 
made five times. The same holds for the session and golden helpers of 
`spark-connect`. The 27 existing files lose 676 lines and gain 194; the two new 
modules are 336 lines.
    
    ### Does this PR introduce _any_ user-facing change?
    
    No. Test-only.
    
    ### How was this patch tested?
    
    - `RUSTFLAGS="-D warnings" cargo test -p apache-spark-connect -p 
apache-spark-connect-core --release`: 1152 passed, 0 failed, 29 ignored. No 
Spark Connect server was running, so the `e2e_*` tests returned early, and 
`session()` and `live_session()` were compiled but not run against a server.
    - `RUSTFLAGS="-D warnings" cargo test -p apache-spark-connect --release 
--features wasm-udf --no-run` compiles.
    - The output of `cargo test -p apache-spark-connect -p 
apache-spark-connect-core --release -- --list` before and after the change, 
taken at the commit this was written on, is identical (1157 tests).
    - `cargo fmt --all --check` is clean.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (claude-fable-5-2)
    
    Closes #507 from viirya/SPARK-61431-tests-common-harness.
    
    Authored-by: Liang-Chi Hsieh <[email protected]>
    Signed-off-by: Liang-Chi Hsieh <[email protected]>
---
 .../spark-connect-core/tests/artifact_uploads.rs   |  75 ++-----
 crates/spark-connect-core/tests/common/mod.rs      | 230 +++++++++++++++++++++
 crates/spark-connect-core/tests/deadlines.rs       |  98 +++------
 .../spark-connect-core/tests/reattach_cleanup.rs   |  92 +++------
 crates/spark-connect-core/tests/server_session.rs  |  82 +++-----
 crates/spark-connect-core/tests/user_context.rs    |  82 +++-----
 crates/spark-connect/tests/catalog_golden.rs       |  15 --
 crates/spark-connect/tests/common/mod.rs           | 106 ++++++++++
 crates/spark-connect/tests/e2e_columns.rs          |  13 +-
 crates/spark-connect/tests/e2e_coverage.rs         |  15 +-
 crates/spark-connect/tests/e2e_dataframe.rs        |  13 +-
 crates/spark-connect/tests/e2e_functions.rs        |  13 +-
 crates/spark-connect/tests/e2e_integration.rs      |   7 +-
 crates/spark-connect/tests/e2e_kmeans.rs           |  25 +--
 .../spark-connect/tests/e2e_linear_regression.rs   |  23 +--
 crates/spark-connect/tests/e2e_linear_svc.rs       |  21 +-
 crates/spark-connect/tests/e2e_new_methods.rs      |  15 +-
 crates/spark-connect/tests/e2e_ops_breadth.rs      |  15 +-
 crates/spark-connect/tests/e2e_random_forest.rs    |  23 +--
 crates/spark-connect/tests/e2e_session_catalog.rs  |  13 +-
 crates/spark-connect/tests/e2e_streaming.rs        |  16 +-
 crates/spark-connect/tests/functions_golden.rs     |  27 +--
 crates/spark-connect/tests/golden_test.rs          |  28 +--
 crates/spark-connect/tests/hof_golden.rs           |  30 +--
 crates/spark-connect/tests/ml_extra_golden.rs      |  31 +--
 crates/spark-connect/tests/ml_golden.rs            |  33 +--
 crates/spark-connect/tests/plans_golden.rs         |  28 +--
 crates/spark-connect/tests/readwriter_golden.rs    |  11 -
 crates/spark-connect/tests/window_golden.rs        |  26 +--
 29 files changed, 530 insertions(+), 676 deletions(-)

diff --git a/crates/spark-connect-core/tests/artifact_uploads.rs 
b/crates/spark-connect-core/tests/artifact_uploads.rs
index b8fecebf..becb24b2 100644
--- a/crates/spark-connect-core/tests/artifact_uploads.rs
+++ b/crates/spark-connect-core/tests/artifact_uploads.rs
@@ -19,13 +19,14 @@
 //! retries, against a loopback gRPC service that receives and acknowledges 
them; no Spark
 //! server required.
 
+mod common;
+
 use std::collections::VecDeque;
-use std::convert::Infallible;
 use std::sync::{Arc, Mutex};
-use std::task::{Context, Poll};
 use std::time::Duration;
 
-use futures::{stream, StreamExt};
+use common::{FakeServer, FakeService};
+use futures::StreamExt;
 use prost::Message;
 use spark_connect_core::bytes_codec::BytesCodec;
 use spark_connect_core::{
@@ -34,15 +35,11 @@ use spark_connect_core::{
 use spark_connect_proto::add_artifacts_request::Payload;
 use spark_connect_proto::add_artifacts_response::ArtifactSummary;
 use spark_connect_proto::{AddArtifactsRequest, AddArtifactsResponse};
-use tokio::net::TcpListener;
-use tonic::body::Body;
-use tonic::codegen::{http, BoxFuture, Service};
-use tonic::server::{ClientStreamingService, NamedService, UnaryService};
-use tonic::transport::Server;
+use tonic::codegen::BoxFuture;
+use tonic::server::{ClientStreamingService, UnaryService};
 use tonic::{Code, Request, Response, Status, Streaming};
 
 const WAIT: Duration = Duration::from_secs(5);
-const SERVICE: &str = "/spark.connect.SparkConnectService/";
 
 /// How the server handles one AddArtifacts attempt.
 #[derive(Clone, Copy)]
@@ -65,7 +62,7 @@ struct State {
 
 struct Fixture {
     state: Arc<State>,
-    server: tokio::task::JoinHandle<()>,
+    _server: FakeServer,
     address: std::net::SocketAddr,
 }
 
@@ -75,22 +72,11 @@ impl Fixture {
             attempts: Mutex::new(attempts.into_iter().collect()),
             received: Mutex::new(Vec::new()),
         });
-        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
-        let address = listener.local_addr().unwrap();
-        let incoming = stream::unfold(listener, |listener| async {
-            Some((listener.accept().await.map(|(socket, _)| socket), listener))
-        });
-        let service = TestService(state.clone());
-        let server = tokio::spawn(async move {
-            Server::builder()
-                .add_service(service)
-                .serve_with_incoming(incoming)
-                .await
-                .unwrap();
-        });
+        let server = service(state.clone()).serve().await;
+        let address = server.address;
         Self {
             state,
-            server,
+            _server: server,
             address,
         }
     }
@@ -116,12 +102,6 @@ impl Fixture {
     }
 }
 
-impl Drop for Fixture {
-    fn drop(&mut self) {
-        self.server.abort();
-    }
-}
-
 /// Bytes that differ from one position to the next, so that a misplaced chunk 
shows.
 fn pattern(len: usize) -> Vec<u8> {
     (0..len).map(|i| (i % 251) as u8).collect()
@@ -328,33 +308,14 @@ async fn a_missing_file_fails_before_any_attempt() {
 }
 
 /// The AddArtifacts service, which receives each attempt's frames and 
acknowledges them.
-#[derive(Clone)]
-struct TestService(Arc<State>);
-
-impl NamedService for TestService {
-    const NAME: &'static str = "spark.connect.SparkConnectService";
-}
-
-impl Service<http::Request<Body>> for TestService {
-    type Response = http::Response<Body>;
-    type Error = Infallible;
-    type Future = BoxFuture<Self::Response, Self::Error>;
-
-    fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), 
Self::Error>> {
-        Poll::Ready(Ok(()))
-    }
-
-    fn call(&mut self, request: http::Request<Body>) -> Self::Future {
-        let method = 
request.uri().path().trim_start_matches(SERVICE).to_string();
-        let state = self.0.clone();
-        Box::pin(async move {
-            let mut grpc = tonic::server::Grpc::new(BytesCodec);
-            Ok(match method.as_str() {
-                "AddArtifacts" => grpc.client_streaming(AddArtifacts(state), 
request).await,
-                _ => grpc.unary(Unary, request).await,
-            })
-        })
-    }
+fn service(state: Arc<State>) -> FakeService {
+    FakeService::new()
+        .client_streaming(
+            "AddArtifacts",
+            || BytesCodec,
+            move |_| AddArtifacts(state.clone()),
+        )
+        .fallback_unary(|| BytesCodec, |_| Unary)
 }
 
 struct AddArtifacts(Arc<State>);
diff --git a/crates/spark-connect-core/tests/common/mod.rs 
b/crates/spark-connect-core/tests/common/mod.rs
new file mode 100644
index 00000000..3dd05de4
--- /dev/null
+++ b/crates/spark-connect-core/tests/common/mod.rs
@@ -0,0 +1,230 @@
+// 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.
+
+//! The loopback Spark Connect service of the integration tests of this crate. 
A test file
+//! takes it with `mod common;`, names the RPCs that its service answers and 
the handler of
+//! each, and serves them on a loopback port:
+//!
+//! ```ignore
+//! let server = FakeService::new()
+//!     .server_streaming("ExecutePlan", ProstCodec::default, {
+//!         let state = state.clone();
+//!         move |_| Execute(state.clone())
+//!     })
+//!     .unary("ReleaseExecute", ProstCodec::default, move |_| 
ReleaseRpc(state.clone()))
+//!     .serve()
+//!     .await;
+//! let url = format!("sc://{}", server.address);
+//! ```
+//!
+//! The handlers are the `tonic::server` service traits (`UnaryService`,
+//! `ServerStreamingService`, `ClientStreamingService`), so that a test keeps 
what its RPCs do
+//! next to its cases; this module has only the routing and the listener.
+
+#![allow(dead_code)] // every test binary compiles this module and uses only a 
part of it
+
+use std::convert::Infallible;
+use std::net::SocketAddr;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use futures::stream;
+use tokio::net::TcpListener;
+use tonic::body::Body;
+use tonic::codec::Codec;
+use tonic::codegen::{http, BoxFuture, Service};
+use tonic::server::{
+    ClientStreamingService, Grpc, NamedService, ServerStreamingService, 
UnaryService,
+};
+use tonic::transport::Server;
+
+/// The path of an RPC of the service is this prefix followed by the name of 
its method.
+pub const SERVICE: &str = "/spark.connect.SparkConnectService/";
+
+type Reply = BoxFuture<http::Response<Body>, Infallible>;
+/// Answers one HTTP request of a method, whose name it is given.
+type Handler = Arc<dyn Fn(&str, http::Request<Body>) -> Reply + Send + Sync>;
+
+/// A Spark Connect service that answers the RPCs a test names, each with the 
handler the test
+/// gives for it. A method without a route goes to the fallback, when the test 
sets one, and is
+/// answered as UNIMPLEMENTED otherwise.
+#[derive(Clone, Default)]
+pub struct FakeService {
+    routes: Vec<(&'static str, Handler)>,
+    fallback: Option<Handler>,
+}
+
+impl FakeService {
+    pub fn new() -> Self {
+        Self::default()
+    }
+
+    /// Answers the unary RPC `method` with the service that `service` makes 
for each call.
+    /// `service` is given the name of the method.
+    pub fn unary<C, S>(
+        mut self,
+        method: &'static str,
+        codec: impl Fn() -> C + Send + Sync + 'static,
+        service: impl Fn(&str) -> S + Send + Sync + 'static,
+    ) -> Self
+    where
+        C: Codec + Send + 'static,
+        S: UnaryService<C::Decode, Response = C::Encode> + Send + 'static,
+        S::Future: Send,
+    {
+        self.routes.push((method, unary_handler(codec, service)));
+        self
+    }
+
+    /// Answers the server-streaming RPC `method` with the service that 
`service` makes for
+    /// each call. `service` is given the name of the method.
+    pub fn server_streaming<C, S>(
+        mut self,
+        method: &'static str,
+        codec: impl Fn() -> C + Send + Sync + 'static,
+        service: impl Fn(&str) -> S + Send + Sync + 'static,
+    ) -> Self
+    where
+        C: Codec + Send + 'static,
+        S: ServerStreamingService<C::Decode, Response = C::Encode> + Send + 
'static,
+        S::Future: Send,
+        S::ResponseStream: Send + 'static,
+    {
+        let handler: Handler = Arc::new(move |method, request| {
+            let service = service(method);
+            let mut grpc = Grpc::new(codec());
+            Box::pin(async move { Ok(grpc.server_streaming(service, 
request).await) })
+        });
+        self.routes.push((method, handler));
+        self
+    }
+
+    /// Answers the client-streaming RPC `method` with the service that 
`service` makes for
+    /// each call. `service` is given the name of the method.
+    pub fn client_streaming<C, S>(
+        mut self,
+        method: &'static str,
+        codec: impl Fn() -> C + Send + Sync + 'static,
+        service: impl Fn(&str) -> S + Send + Sync + 'static,
+    ) -> Self
+    where
+        C: Codec + Send + 'static,
+        S: ClientStreamingService<C::Decode, Response = C::Encode> + Send + 
'static,
+        S::Future: Send,
+    {
+        let handler: Handler = Arc::new(move |method, request| {
+            let service = service(method);
+            let mut grpc = Grpc::new(codec());
+            Box::pin(async move { Ok(grpc.client_streaming(service, 
request).await) })
+        });
+        self.routes.push((method, handler));
+        self
+    }
+
+    /// Answers every method that has no route as a unary RPC, with the 
service that `service`
+    /// makes for each call. `service` is given the name of the method.
+    pub fn fallback_unary<C, S>(
+        mut self,
+        codec: impl Fn() -> C + Send + Sync + 'static,
+        service: impl Fn(&str) -> S + Send + Sync + 'static,
+    ) -> Self
+    where
+        C: Codec + Send + 'static,
+        S: UnaryService<C::Decode, Response = C::Encode> + Send + 'static,
+        S::Future: Send,
+    {
+        self.fallback = Some(unary_handler(codec, service));
+        self
+    }
+
+    /// Serves the service on a loopback port of its own, until the returned 
server is dropped.
+    pub async fn serve(self) -> FakeServer {
+        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+        let address = listener.local_addr().unwrap();
+        let incoming = stream::unfold(listener, |listener| async {
+            Some((listener.accept().await.map(|(socket, _)| socket), listener))
+        });
+        let task = tokio::spawn(async move {
+            Server::builder()
+                .add_service(self)
+                .serve_with_incoming(incoming)
+                .await
+                .unwrap();
+        });
+        FakeServer { address, task }
+    }
+}
+
+fn unary_handler<C, S>(
+    codec: impl Fn() -> C + Send + Sync + 'static,
+    service: impl Fn(&str) -> S + Send + Sync + 'static,
+) -> Handler
+where
+    C: Codec + Send + 'static,
+    S: UnaryService<C::Decode, Response = C::Encode> + Send + 'static,
+    S::Future: Send,
+{
+    Arc::new(move |method, request| {
+        let service = service(method);
+        let mut grpc = Grpc::new(codec());
+        Box::pin(async move { Ok(grpc.unary(service, request).await) })
+    })
+}
+
+impl NamedService for FakeService {
+    const NAME: &'static str = "spark.connect.SparkConnectService";
+}
+
+impl Service<http::Request<Body>> for FakeService {
+    type Response = http::Response<Body>;
+    type Error = Infallible;
+    type Future = Reply;
+
+    fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), 
Self::Error>> {
+        Poll::Ready(Ok(()))
+    }
+
+    fn call(&mut self, request: http::Request<Body>) -> Self::Future {
+        let method = 
request.uri().path().trim_start_matches(SERVICE).to_string();
+        let route = self.routes.iter().find(|(name, _)| *name == method);
+        match route.map(|(_, handler)| handler).or(self.fallback.as_ref()) {
+            Some(handler) => handler(&method, request),
+            // UNIMPLEMENTED, as a tonic server answers a method that it does 
not have.
+            None => Box::pin(async {
+                Ok(http::Response::builder()
+                    .status(200)
+                    .header("grpc-status", "12")
+                    .header("content-type", "application/grpc")
+                    .body(Body::empty())
+                    .unwrap())
+            }),
+        }
+    }
+}
+
+/// A served [`FakeService`]. Dropping it stops the server.
+pub struct FakeServer {
+    /// The loopback address that the server listens on.
+    pub address: SocketAddr,
+    task: tokio::task::JoinHandle<()>,
+}
+
+impl Drop for FakeServer {
+    fn drop(&mut self) {
+        self.task.abort();
+    }
+}
diff --git a/crates/spark-connect-core/tests/deadlines.rs 
b/crates/spark-connect-core/tests/deadlines.rs
index 690da763..10dba6c6 100644
--- a/crates/spark-connect-core/tests/deadlines.rs
+++ b/crates/spark-connect-core/tests/deadlines.rs
@@ -19,14 +19,15 @@
 //! execution that the server does not know. No Spark server required: a 
loopback tonic
 //! service stalls its calls before they send headers, as a stalled connection 
does.
 
+mod common;
+
 use std::collections::{HashSet, VecDeque};
-use std::convert::Infallible;
 use std::future::Future;
 use std::pin::Pin;
 use std::sync::{Arc, Mutex};
-use std::task::{Context, Poll};
 use std::time::{Duration, Instant};
 
+use common::{FakeServer, FakeService};
 use futures::{stream, Stream};
 use spark_connect_core::{ChannelBuilder, RetryPolicy, RpcDeadlines, 
SparkConnectClient};
 use spark_connect_proto::execute_plan_response::{ResponseType, ResultComplete};
@@ -35,13 +36,11 @@ use spark_connect_proto::{
     ConfigRequest, ConfigResponse, ExecutePlanRequest, ExecutePlanResponse, 
ReattachExecuteRequest,
     ReleaseExecuteRequest, ReleaseExecuteResponse, UserContext,
 };
-use tokio::net::TcpListener;
-use tonic::body::Body;
-use tonic::codegen::{http, BoxFuture, Service};
+use tonic::codegen::BoxFuture;
 use tonic::metadata::MetadataMap;
-use tonic::server::{NamedService, ServerStreamingService, UnaryService};
-use tonic::transport::Server;
+use tonic::server::{ServerStreamingService, UnaryService};
 use tonic::{Code, Request, Response, Status};
+use tonic_prost::ProstCodec;
 
 /// The per-RPC deadline of the tests: short, so that the stalls end quickly.
 const DEADLINE: Duration = Duration::from_millis(200);
@@ -135,7 +134,7 @@ impl State {
 
 struct Fixture {
     state: Arc<State>,
-    server: tokio::task::JoinHandle<()>,
+    _server: FakeServer,
     client: SparkConnectClient,
 }
 
@@ -144,19 +143,8 @@ impl Fixture {
     /// the given retry policy.
     async fn start(execute: Vec<Step>, reattach: Vec<Step>, retry_policy: 
RetryPolicy) -> Self {
         let state = Arc::new(State::new(execute, reattach));
-        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
-        let address = listener.local_addr().unwrap();
-        let incoming = stream::unfold(listener, |listener| async {
-            Some((listener.accept().await.map(|(socket, _)| socket), listener))
-        });
-        let service = TestService(state.clone());
-        let server = tokio::spawn(async move {
-            Server::builder()
-                .add_service(service)
-                .serve_with_incoming(incoming)
-                .await
-                .unwrap();
-        });
+        let server = service(state.clone()).serve().await;
+        let address = server.address;
         let builder = ChannelBuilder::parse(&format!(
             
"sc://localhost:{}/;user_id=transport-user;token=fixture-token;session_id=00000000-0000-4000-8000-000000000001",
             address.port()
@@ -174,7 +162,7 @@ impl Fixture {
         });
         Self {
             state,
-            server,
+            _server: server,
             client,
         }
     }
@@ -194,12 +182,6 @@ impl Fixture {
     }
 }
 
-impl Drop for Fixture {
-    fn drop(&mut self) {
-        self.server.abort();
-    }
-}
-
 fn execute_request() -> ExecutePlanRequest {
     ExecutePlanRequest {
         session_id: "00000000-0000-4000-8000-000000000001".into(),
@@ -701,51 +683,21 @@ fn error_info_details() -> Vec<u8> {
 }
 
 /// The loopback service: ExecutePlan, ReattachExecute, ReleaseExecute and 
Config.
-#[derive(Clone)]
-struct TestService(Arc<State>);
-
-impl NamedService for TestService {
-    const NAME: &'static str = "spark.connect.SparkConnectService";
-}
-
-impl Service<http::Request<Body>> for TestService {
-    type Response = http::Response<Body>;
-    type Error = Infallible;
-    type Future = BoxFuture<Self::Response, Self::Error>;
-
-    fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), 
Self::Error>> {
-        Poll::Ready(Ok(()))
-    }
-
-    fn call(&mut self, request: http::Request<Body>) -> Self::Future {
-        let state = self.0.clone();
-        match request.uri().path() {
-            "/spark.connect.SparkConnectService/ExecutePlan" => Box::pin(async 
move {
-                let mut grpc = 
tonic::server::Grpc::new(tonic_prost::ProstCodec::default());
-                Ok(grpc.server_streaming(Execute(state), request).await)
-            }),
-            "/spark.connect.SparkConnectService/ReattachExecute" => 
Box::pin(async move {
-                let mut grpc = 
tonic::server::Grpc::new(tonic_prost::ProstCodec::default());
-                Ok(grpc.server_streaming(Reattach(state), request).await)
-            }),
-            "/spark.connect.SparkConnectService/ReleaseExecute" => 
Box::pin(async move {
-                let mut grpc = 
tonic::server::Grpc::new(tonic_prost::ProstCodec::default());
-                Ok(grpc.unary(ReleaseRpc(state), request).await)
-            }),
-            "/spark.connect.SparkConnectService/Config" => Box::pin(async move 
{
-                let mut grpc = 
tonic::server::Grpc::new(tonic_prost::ProstCodec::default());
-                Ok(grpc.unary(Config(state), request).await)
-            }),
-            _ => Box::pin(async {
-                Ok(http::Response::builder()
-                    .status(200)
-                    .header("grpc-status", "12")
-                    .header("content-type", "application/grpc")
-                    .body(Body::empty())
-                    .unwrap())
-            }),
-        }
-    }
+fn service(state: Arc<State>) -> FakeService {
+    let (execute, reattach, release) = (state.clone(), state.clone(), 
state.clone());
+    FakeService::new()
+        .server_streaming("ExecutePlan", ProstCodec::default, move |_| {
+            Execute(execute.clone())
+        })
+        .server_streaming("ReattachExecute", ProstCodec::default, move |_| {
+            Reattach(reattach.clone())
+        })
+        .unary("ReleaseExecute", ProstCodec::default, move |_| {
+            ReleaseRpc(release.clone())
+        })
+        .unary("Config", ProstCodec::default, move |_| {
+            Config(state.clone())
+        })
 }
 
 /// Serves the next step of `script`, a call that stalls never returning its 
headers.
diff --git a/crates/spark-connect-core/tests/reattach_cleanup.rs 
b/crates/spark-connect-core/tests/reattach_cleanup.rs
index 9827a2bd..b28d5986 100644
--- a/crates/spark-connect-core/tests/reattach_cleanup.rs
+++ b/crates/spark-connect-core/tests/reattach_cleanup.rs
@@ -17,15 +17,16 @@
 
 //! Real-wire lifecycle tests; no Spark server or generated server bindings 
required.
 
+mod common;
+
 use std::collections::VecDeque;
-use std::convert::Infallible;
 use std::future::Future;
 use std::pin::Pin;
 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
 use std::sync::{Arc, Mutex};
-use std::task::{Context, Poll};
 use std::time::Duration;
 
+use common::{FakeServer, FakeService};
 use futures::{stream, Stream, StreamExt};
 use spark_connect_core::{ChannelBuilder, RetryPolicy, RpcDeadlines, 
SparkConnectClient};
 use spark_connect_proto::execute_plan_response::{ResponseType, ResultComplete};
@@ -34,14 +35,12 @@ use spark_connect_proto::{
     ExecutePlanRequest, ExecutePlanResponse, ReattachExecuteRequest, 
ReleaseExecuteRequest,
     ReleaseExecuteResponse, UserContext,
 };
-use tokio::net::TcpListener;
 use tokio::sync::{oneshot, Notify};
-use tonic::body::Body;
-use tonic::codegen::{http, BoxFuture, Service};
+use tonic::codegen::BoxFuture;
 use tonic::metadata::MetadataMap;
-use tonic::server::{NamedService, ServerStreamingService, UnaryService};
-use tonic::transport::Server;
+use tonic::server::{ServerStreamingService, UnaryService};
 use tonic::{Code, Request, Response, Status};
+use tonic_prost::ProstCodec;
 
 const WAIT: Duration = Duration::from_secs(3);
 type Responses = Pin<Box<dyn Stream<Item = Result<ExecutePlanResponse, 
Status>> + Send>>;
@@ -124,7 +123,7 @@ impl State {
 
 struct Fixture {
     state: Arc<State>,
-    server: tokio::task::JoinHandle<()>,
+    _server: FakeServer,
     client: SparkConnectClient,
 }
 
@@ -145,19 +144,8 @@ impl Fixture {
             changed: Notify::new(),
             timeouts: Mutex::new(Vec::new()),
         });
-        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
-        let address = listener.local_addr().unwrap();
-        let incoming = stream::unfold(listener, |listener| async {
-            Some((listener.accept().await.map(|(socket, _)| socket), listener))
-        });
-        let service = TestService(state.clone());
-        let server = tokio::spawn(async move {
-            Server::builder()
-                .add_service(service)
-                .serve_with_incoming(incoming)
-                .await
-                .unwrap();
-        });
+        let server = service(state.clone()).serve().await;
+        let address = server.address;
         let builder = ChannelBuilder::parse(&format!(
             
"sc://localhost:{}/;user_id=transport-user;token=fixture-token;x-cleanup=fixture-value;session_id=00000000-0000-4000-8000-000000000001",
             address.port()
@@ -174,7 +162,7 @@ impl Fixture {
         });
         Self {
             state,
-            server,
+            _server: server,
             client,
         }
     }
@@ -208,12 +196,6 @@ impl Fixture {
     }
 }
 
-impl Drop for Fixture {
-    fn drop(&mut self) {
-        self.server.abort();
-    }
-}
-
 fn execute_request() -> ExecutePlanRequest {
     ExecutePlanRequest {
         session_id: "00000000-0000-4000-8000-000000000001".into(),
@@ -260,47 +242,19 @@ fn assert_metadata(metadata: &MetadataMap) {
     assert!(metadata.get("user-agent").is_some());
 }
 
-#[derive(Clone)]
-struct TestService(Arc<State>);
-
-impl NamedService for TestService {
-    const NAME: &'static str = "spark.connect.SparkConnectService";
-}
-
-impl Service<http::Request<Body>> for TestService {
-    type Response = http::Response<Body>;
-    type Error = Infallible;
-    type Future = BoxFuture<Self::Response, Self::Error>;
-
-    fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), 
Self::Error>> {
-        Poll::Ready(Ok(()))
-    }
-
-    fn call(&mut self, request: http::Request<Body>) -> Self::Future {
-        let state = self.0.clone();
-        match request.uri().path() {
-            "/spark.connect.SparkConnectService/ExecutePlan" => Box::pin(async 
move {
-                let mut grpc = 
tonic::server::Grpc::new(tonic_prost::ProstCodec::default());
-                Ok(grpc.server_streaming(Execute(state), request).await)
-            }),
-            "/spark.connect.SparkConnectService/ReattachExecute" => 
Box::pin(async move {
-                let mut grpc = 
tonic::server::Grpc::new(tonic_prost::ProstCodec::default());
-                Ok(grpc.server_streaming(Reattach(state), request).await)
-            }),
-            "/spark.connect.SparkConnectService/ReleaseExecute" => 
Box::pin(async move {
-                let mut grpc = 
tonic::server::Grpc::new(tonic_prost::ProstCodec::default());
-                Ok(grpc.unary(ReleaseRpc(state), request).await)
-            }),
-            _ => Box::pin(async {
-                Ok(http::Response::builder()
-                    .status(200)
-                    .header("grpc-status", "12")
-                    .header("content-type", "application/grpc")
-                    .body(Body::empty())
-                    .unwrap())
-            }),
-        }
-    }
+/// The loopback service: ExecutePlan, ReattachExecute and ReleaseExecute.
+fn service(state: Arc<State>) -> FakeService {
+    let (execute, reattach) = (state.clone(), state.clone());
+    FakeService::new()
+        .server_streaming("ExecutePlan", ProstCodec::default, move |_| {
+            Execute(execute.clone())
+        })
+        .server_streaming("ReattachExecute", ProstCodec::default, move |_| {
+            Reattach(reattach.clone())
+        })
+        .unary("ReleaseExecute", ProstCodec::default, move |_| {
+            ReleaseRpc(state.clone())
+        })
 }
 
 struct Execute(Arc<State>);
diff --git a/crates/spark-connect-core/tests/server_session.rs 
b/crates/spark-connect-core/tests/server_session.rs
index 6d9df9bb..3621298b 100644
--- a/crates/spark-connect-core/tests/server_session.rs
+++ b/crates/spark-connect-core/tests/server_session.rs
@@ -19,13 +19,14 @@
 //! server-side session ID of the server, which a test changes to restart it: 
the observed ID of
 //! the requests, the check of the responses, and the close of the client on a 
restart.
 
+mod common;
+
 use std::collections::HashMap;
 use std::collections::VecDeque;
-use std::convert::Infallible;
 use std::pin::Pin;
 use std::sync::{Arc, Mutex};
-use std::task::{Context, Poll};
 
+use common::{FakeServer, FakeService};
 use futures::{stream, Stream};
 use prost::Message;
 use spark_connect_core::bytes_codec::BytesCodec;
@@ -35,14 +36,10 @@ use spark_connect_proto::{
     ConfigRequest, ConfigResponse, ExecutePlanRequest, ExecutePlanResponse, 
ReattachExecuteRequest,
     ReleaseExecuteRequest, ReleaseExecuteResponse,
 };
-use tokio::net::TcpListener;
-use tonic::body::Body;
-use tonic::codegen::{http, BoxFuture, Service};
-use tonic::server::{NamedService, ServerStreamingService, UnaryService};
-use tonic::transport::Server;
+use tonic::codegen::BoxFuture;
+use tonic::server::{ServerStreamingService, UnaryService};
 use tonic::{Code, Request, Response, Status};
 
-const SERVICE: &str = "/spark.connect.SparkConnectService/";
 const FIRST_SERVER_ID: &str = "server-1";
 const RESTARTED_SERVER_ID: &str = "server-2";
 type Frames = Pin<Box<dyn Stream<Item = Result<Vec<u8>, Status>> + Send>>;
@@ -93,7 +90,7 @@ impl State {
 
 struct Fixture {
     state: Arc<State>,
-    server: tokio::task::JoinHandle<()>,
+    _server: FakeServer,
     address: std::net::SocketAddr,
 }
 
@@ -105,22 +102,11 @@ impl Fixture {
             failures: Mutex::new(VecDeque::new()),
             requests: Mutex::new(Vec::new()),
         });
-        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
-        let address = listener.local_addr().unwrap();
-        let incoming = futures::stream::unfold(listener, |listener| async {
-            Some((listener.accept().await.map(|(socket, _)| socket), listener))
-        });
-        let service = TestService(state.clone());
-        let server = tokio::spawn(async move {
-            Server::builder()
-                .add_service(service)
-                .serve_with_incoming(incoming)
-                .await
-                .unwrap();
-        });
+        let server = service(state.clone()).serve().await;
+        let address = server.address;
         Self {
             state,
-            server,
+            _server: server,
             address,
         }
     }
@@ -139,12 +125,6 @@ impl Fixture {
     }
 }
 
-impl Drop for Fixture {
-    fn drop(&mut self) {
-        self.server.abort();
-    }
-}
-
 /// The session ID of a request of `method`, which the server echoes in its 
response.
 fn session_of(method: &str, bytes: &[u8]) -> String {
     match method {
@@ -179,36 +159,20 @@ fn first_response(session_id: &str, server_session_id: 
&str) -> Vec<u8> {
     .encode_to_vec()
 }
 
-#[derive(Clone)]
-struct TestService(Arc<State>);
-
-impl NamedService for TestService {
-    const NAME: &'static str = "spark.connect.SparkConnectService";
-}
-
-impl Service<http::Request<Body>> for TestService {
-    type Response = http::Response<Body>;
-    type Error = Infallible;
-    type Future = BoxFuture<Self::Response, Self::Error>;
-
-    fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), 
Self::Error>> {
-        Poll::Ready(Ok(()))
-    }
-
-    fn call(&mut self, request: http::Request<Body>) -> Self::Future {
-        let method = 
request.uri().path().trim_start_matches(SERVICE).to_string();
-        let state = self.0.clone();
-        Box::pin(async move {
-            let mut grpc = tonic::server::Grpc::new(BytesCodec);
-            Ok(match method.as_str() {
-                "ExecutePlan" | "ReattachExecute" => {
-                    grpc.server_streaming(Streamed(state, method), request)
-                        .await
-                }
-                _ => grpc.unary(Unary(state, method), request).await,
-            })
-        })
-    }
+/// The loopback service: ExecutePlan and ReattachExecute stream, and every 
other method is
+/// unary.
+fn service(state: Arc<State>) -> FakeService {
+    let streamed = {
+        let state = state.clone();
+        move |method: &str| Streamed(state.clone(), method.to_string())
+    };
+    FakeService::new()
+        .server_streaming("ExecutePlan", || BytesCodec, streamed.clone())
+        .server_streaming("ReattachExecute", || BytesCodec, streamed)
+        .fallback_unary(
+            || BytesCodec,
+            move |method| Unary(state.clone(), method.to_string()),
+        )
 }
 
 /// ExecutePlan and ReattachExecute.
diff --git a/crates/spark-connect-core/tests/user_context.rs 
b/crates/spark-connect-core/tests/user_context.rs
index 590a518c..0cfb4021 100644
--- a/crates/spark-connect-core/tests/user_context.rs
+++ b/crates/spark-connect-core/tests/user_context.rs
@@ -18,13 +18,14 @@
 //! The user context of typed requests on the wire, against a loopback gRPC 
service that
 //! records the bytes of every request; no Spark server required.
 
+mod common;
+
 use std::collections::VecDeque;
-use std::convert::Infallible;
 use std::pin::Pin;
 use std::sync::{Arc, Mutex};
-use std::task::{Context, Poll};
 use std::time::Duration;
 
+use common::{FakeServer, FakeService};
 use futures::{stream, Stream, StreamExt};
 use prost::Message;
 use spark_connect_core::bytes_codec::BytesCodec;
@@ -37,16 +38,12 @@ use spark_connect_proto::{
     InterruptResponse, ReattachExecuteRequest, ReleaseExecuteRequest, 
ReleaseExecuteResponse,
     UserContext,
 };
-use tokio::net::TcpListener;
 use tokio::sync::Notify;
-use tonic::body::Body;
-use tonic::codegen::{http, BoxFuture, Service};
-use tonic::server::{NamedService, ServerStreamingService, UnaryService};
-use tonic::transport::Server;
+use tonic::codegen::BoxFuture;
+use tonic::server::{ServerStreamingService, UnaryService};
 use tonic::{Request, Response, Status};
 
 const WAIT: Duration = Duration::from_secs(5);
-const SERVICE: &str = "/spark.connect.SparkConnectService/";
 type Frames = Pin<Box<dyn Stream<Item = Result<Vec<u8>, Status>> + Send>>;
 
 /// What an ExecutePlan call streams. A ReattachExecute call streams the rest 
of the result.
@@ -89,7 +86,7 @@ impl State {
 
 struct Fixture {
     state: Arc<State>,
-    server: tokio::task::JoinHandle<()>,
+    _server: FakeServer,
     address: std::net::SocketAddr,
 }
 
@@ -100,22 +97,11 @@ impl Fixture {
             requests: Mutex::new(Vec::new()),
             changed: Notify::new(),
         });
-        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
-        let address = listener.local_addr().unwrap();
-        let incoming = stream::unfold(listener, |listener| async {
-            Some((listener.accept().await.map(|(socket, _)| socket), listener))
-        });
-        let service = TestService(state.clone());
-        let server = tokio::spawn(async move {
-            Server::builder()
-                .add_service(service)
-                .serve_with_incoming(incoming)
-                .await
-                .unwrap();
-        });
+        let server = service(state.clone()).serve().await;
+        let address = server.address;
         Self {
             state,
-            server,
+            _server: server,
             address,
         }
     }
@@ -167,12 +153,6 @@ impl Fixture {
     }
 }
 
-impl Drop for Fixture {
-    fn drop(&mut self) {
-        self.server.abort();
-    }
-}
-
 fn response(session_id: &str, id: &str, complete: bool) -> Vec<u8> {
     ExecutePlanResponse {
         // The server echoes the session ID of the request.
@@ -184,36 +164,20 @@ fn response(session_id: &str, id: &str, complete: bool) 
-> Vec<u8> {
     .encode_to_vec()
 }
 
-#[derive(Clone)]
-struct TestService(Arc<State>);
-
-impl NamedService for TestService {
-    const NAME: &'static str = "spark.connect.SparkConnectService";
-}
-
-impl Service<http::Request<Body>> for TestService {
-    type Response = http::Response<Body>;
-    type Error = Infallible;
-    type Future = BoxFuture<Self::Response, Self::Error>;
-
-    fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), 
Self::Error>> {
-        Poll::Ready(Ok(()))
-    }
-
-    fn call(&mut self, request: http::Request<Body>) -> Self::Future {
-        let method = 
request.uri().path().trim_start_matches(SERVICE).to_string();
-        let state = self.0.clone();
-        Box::pin(async move {
-            let mut grpc = tonic::server::Grpc::new(BytesCodec);
-            Ok(match method.as_str() {
-                "ExecutePlan" | "ReattachExecute" => {
-                    grpc.server_streaming(Streamed(state, method), request)
-                        .await
-                }
-                _ => grpc.unary(Unary(state, method), request).await,
-            })
-        })
-    }
+/// The loopback service: ExecutePlan and ReattachExecute stream, and every 
other method is
+/// unary.
+fn service(state: Arc<State>) -> FakeService {
+    let streamed = {
+        let state = state.clone();
+        move |method: &str| Streamed(state.clone(), method.to_string())
+    };
+    FakeService::new()
+        .server_streaming("ExecutePlan", || BytesCodec, streamed.clone())
+        .server_streaming("ReattachExecute", || BytesCodec, streamed)
+        .fallback_unary(
+            || BytesCodec,
+            move |method| Unary(state.clone(), method.to_string()),
+        )
 }
 
 /// ExecutePlan and ReattachExecute.
diff --git a/crates/spark-connect/tests/catalog_golden.rs 
b/crates/spark-connect/tests/catalog_golden.rs
index a21f7bf6..1658343d 100644
--- a/crates/spark-connect/tests/catalog_golden.rs
+++ b/crates/spark-connect/tests/catalog_golden.rs
@@ -17,21 +17,6 @@ use prost::Message;
 
 use spark_connect_proto as proto;
 
-/// Recursively clear fields that vary run-to-run and are not client-authored:
-/// `common` (holds Python origin) everywhere, and relation/attribute 
`plan_id`.
-fn normalize_relation(r: &mut proto::Relation) {
-    r.common = None;
-    if let Some(rel_type) = &mut r.rel_type {
-        use proto::relation::RelType;
-        match rel_type {
-            RelType::Catalog(_) => {}
-            _ => {
-                // Handle other relation types if needed
-            }
-        }
-    }
-}
-
 /// Normalize expression fields (plan_id, origin/source_info)
 fn normalize_expression(e: &mut proto::Expression) {
     if let Some(expr_type) = &mut e.expr_type {
diff --git a/crates/spark-connect/tests/common/mod.rs 
b/crates/spark-connect/tests/common/mod.rs
new file mode 100644
index 00000000..cf9305ae
--- /dev/null
+++ b/crates/spark-connect/tests/common/mod.rs
@@ -0,0 +1,106 @@
+// 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.
+
+//! Helpers shared by the integration tests of this crate. A test file takes 
them with
+//! `mod common;`.
+
+#![allow(dead_code)] // every test binary compiles this module and uses only a 
part of it
+
+use std::collections::HashMap;
+use std::fs::File;
+use std::io::{BufRead, BufReader};
+
+use base64::{engine::general_purpose::STANDARD, Engine};
+use prost::Message;
+use spark_connect::SparkSession;
+use spark_connect_proto as proto;
+
+/// Whether the tests of a live server run: only when `SPARK_REMOTE` is set.
+pub fn should_run() -> bool {
+    std::env::var("SPARK_REMOTE").is_ok()
+}
+
+/// A session of the server at `SPARK_REMOTE`, or of `sc://localhost:15002` 
without it. The
+/// tests that use it return early when [`should_run`] is false.
+pub fn session() -> SparkSession {
+    let url = std::env::var("SPARK_REMOTE").unwrap_or_else(|_| 
"sc://localhost:15002".to_string());
+    SparkSession::builder()
+        .remote(&url)
+        .get_or_create()
+        .expect("session")
+}
+
+/// A session of the server at `SPARK_REMOTE`, or `None` without it, for the 
tests that skip
+/// themselves with `let Some(spark) = live_session() else { return }`.
+pub fn live_session() -> Option<SparkSession> {
+    let remote = std::env::var("SPARK_REMOTE").ok()?;
+    Some(
+        SparkSession::builder()
+            .remote(&remote)
+            .get_or_create()
+            .unwrap(),
+    )
+}
+
+/// The cases of `tests/golden/<file>` at the repository root, by name. Each 
line of the file
+/// is a JSON object with the `name` of the case and the `b64` of its message, 
which is decoded
+/// as `M` and passed to `normalize` before it is kept.
+pub fn load_goldens<M: Message + Default>(
+    file: &str,
+    mut normalize: impl FnMut(&mut M),
+) -> HashMap<String, M> {
+    // Goldens live at the repo root; tests run with CWD at the crate dir.
+    let path = format!("{}/../../tests/golden/{file}", 
env!("CARGO_MANIFEST_DIR"));
+    let file = File::open(path).unwrap_or_else(|_| panic!("golden file {file} 
missing"));
+    let mut out = HashMap::new();
+    for line in BufReader::new(file).lines() {
+        let line = line.unwrap();
+        if line.trim().is_empty() {
+            continue;
+        }
+        let obj: serde_json::Value = serde_json::from_str(&line).unwrap();
+        let name = obj["name"].as_str().unwrap().to_string();
+        let b64 = obj["b64"].as_str().unwrap();
+        let bytes = STANDARD.decode(b64).unwrap();
+        let mut message = M::decode(&bytes[..]).unwrap();
+        normalize(&mut message);
+        out.insert(name, message);
+    }
+    out
+}
+
+/// Clears what varies from run to run in the relation of an ML golden: 
`common` of the
+/// relation itself and, for an `MlRelation` transform, the UID of its 
transformer. It does not
+/// descend into the inputs of the relation; `plans_golden.rs` has the 
recursive form for plans.
+pub fn normalize_relation(r: &mut proto::Relation) {
+    r.common = None;
+    if let Some(proto::relation::RelType::MlRelation(ml_rel)) = &mut 
r.rel_type {
+        normalize_ml_relation(ml_rel);
+    }
+}
+
+fn normalize_ml_relation(ml_rel: &mut proto::MlRelation) {
+    if let Some(proto::ml_relation::MlType::Transform(transform)) = 
ml_rel.ml_type.as_mut() {
+        if let Some(proto::ml_relation::transform::Operator::Transformer(op)) =
+            transform.operator.as_mut()
+        {
+            // UIDs are instance identifiers, so they differ across runs.
+            op.uid.clear();
+        }
+        // The values of `MlParams.params` are literals, with no plan ID or 
origin to clear.
+    }
+}
diff --git a/crates/spark-connect/tests/e2e_columns.rs 
b/crates/spark-connect/tests/e2e_columns.rs
index 54a4785f..a0e0a5d1 100644
--- a/crates/spark-connect/tests/e2e_columns.rs
+++ b/crates/spark-connect/tests/e2e_columns.rs
@@ -4,22 +4,15 @@
 //! bitwise, membership, struct/array/map access, window). This both covers 
column.rs
 //! and pins correct behavior. Run with SPARK_REMOTE set.
 
+mod common;
+
+use common::{session, should_run};
 use spark_connect::column::{col, lit, lit_boolean, lit_double, lit_string, 
when, Column};
 use spark_connect::dataframe::DataFrame;
 use spark_connect::functions as f;
 use spark_connect::row::Value;
 use spark_connect::session::SparkSession;
 
-fn should_run() -> bool {
-    std::env::var("SPARK_REMOTE").is_ok()
-}
-fn session() -> SparkSession {
-    let url = std::env::var("SPARK_REMOTE").unwrap_or_else(|_| 
"sc://localhost:15002".to_string());
-    SparkSession::builder()
-        .remote(&url)
-        .get_or_create()
-        .expect("session")
-}
 fn base(s: &SparkSession) -> DataFrame {
     s.sql(
         "SELECT * FROM VALUES (1,'apple',10.0),(2,'banana',20.0),(3,NULL,30.0) 
\
diff --git a/crates/spark-connect/tests/e2e_coverage.rs 
b/crates/spark-connect/tests/e2e_coverage.rs
index fd89a724..c908874e 100644
--- a/crates/spark-connect/tests/e2e_coverage.rs
+++ b/crates/spark-connect/tests/e2e_coverage.rs
@@ -8,24 +8,15 @@
 //!
 //! Run with: `SPARK_REMOTE=sc://localhost:15002 cargo test --test 
e2e_coverage`
 
+mod common;
+
 use std::collections::HashMap;
 
+use common::{session, should_run};
 use spark_connect::column::{col, lit, lit_string};
 use spark_connect::functions as f;
 use spark_connect::session::SparkSession;
 
-fn should_run() -> bool {
-    std::env::var("SPARK_REMOTE").is_ok()
-}
-
-fn session() -> SparkSession {
-    let url = std::env::var("SPARK_REMOTE").unwrap_or_else(|_| 
"sc://localhost:15002".to_string());
-    SparkSession::builder()
-        .remote(&url)
-        .get_or_create()
-        .expect("session")
-}
-
 /// A small typed DataFrame with a null, for na/stat/agg coverage.
 fn sample(s: &SparkSession) -> spark_connect::dataframe::DataFrame {
     s.sql(
diff --git a/crates/spark-connect/tests/e2e_dataframe.rs 
b/crates/spark-connect/tests/e2e_dataframe.rs
index fb3bbb30..dacfc361 100644
--- a/crates/spark-connect/tests/e2e_dataframe.rs
+++ b/crates/spark-connect/tests/e2e_dataframe.rs
@@ -3,22 +3,15 @@
 //! surface of dataframe.rs (set ops, dedup, joins, reshape, metadata, JSON, 
temp
 //! views, semantics). Run with SPARK_REMOTE set.
 
+mod common;
+
+use common::{session, should_run};
 use spark_connect::column::{col, lit};
 use spark_connect::dataframe::DataFrame;
 use spark_connect::functions as f;
 use spark_connect::plan::JoinType;
 use spark_connect::session::SparkSession;
 
-fn should_run() -> bool {
-    std::env::var("SPARK_REMOTE").is_ok()
-}
-fn session() -> SparkSession {
-    let url = std::env::var("SPARK_REMOTE").unwrap_or_else(|_| 
"sc://localhost:15002".to_string());
-    SparkSession::builder()
-        .remote(&url)
-        .get_or_create()
-        .expect("session")
-}
 // 4 rows, with a duplicate (2,'b') for dedup/set-op assertions.
 fn df4(s: &SparkSession) -> DataFrame {
     s.sql("SELECT * FROM VALUES (1,'a'),(2,'b'),(2,'b'),(3,'c') AS t(id, 
name)")
diff --git a/crates/spark-connect/tests/e2e_functions.rs 
b/crates/spark-connect/tests/e2e_functions.rs
index 60fb81cc..6decbb1e 100644
--- a/crates/spark-connect/tests/e2e_functions.rs
+++ b/crates/spark-connect/tests/e2e_functions.rs
@@ -3,22 +3,15 @@
 //! (Full byte-for-byte builder parity lives in functions_golden.rs; this pins 
runtime
 //! behavior and covers the exec path.) Run with SPARK_REMOTE set.
 
+mod common;
+
+use common::{session, should_run};
 use spark_connect::column::{col, lit, lit_double, lit_string, Column};
 use spark_connect::dataframe::DataFrame;
 use spark_connect::functions as f;
 use spark_connect::row::Value;
 use spark_connect::session::SparkSession;
 
-fn should_run() -> bool {
-    std::env::var("SPARK_REMOTE").is_ok()
-}
-fn session() -> SparkSession {
-    let url = std::env::var("SPARK_REMOTE").unwrap_or_else(|_| 
"sc://localhost:15002".to_string());
-    SparkSession::builder()
-        .remote(&url)
-        .get_or_create()
-        .expect("session")
-}
 fn base(s: &SparkSession) -> DataFrame {
     s.sql(
         "SELECT -5 AS neg, 4.0 AS four, 'abc' AS s, array(3,1,2) AS arr, \
diff --git a/crates/spark-connect/tests/e2e_integration.rs 
b/crates/spark-connect/tests/e2e_integration.rs
index 08174994..4e7b86d6 100644
--- a/crates/spark-connect/tests/e2e_integration.rs
+++ b/crates/spark-connect/tests/e2e_integration.rs
@@ -6,8 +6,11 @@
 //! Run with: `SPARK_REMOTE=sc://localhost:15002 cargo test --test 
e2e_integration`
 //! Or simply skip with: `cargo test --test e2e_integration` (will skip all 
tests)
 
+mod common;
+
 use std::time::Duration;
 
+use common::should_run;
 use spark_connect::column::{col, lit};
 use spark_connect::row::Value;
 use spark_connect::session::SparkSession;
@@ -16,10 +19,6 @@ use spark_connect_core::runtime::block_on;
 use spark_connect_core::{ChannelBuilder, SparkConnectClient};
 use spark_connect_proto as proto;
 
-fn should_run() -> bool {
-    std::env::var("SPARK_REMOTE").is_ok()
-}
-
 fn remote_url() -> String {
     std::env::var("SPARK_REMOTE").unwrap_or_else(|_| 
"sc://localhost:15002".to_string())
 }
diff --git a/crates/spark-connect/tests/e2e_kmeans.rs 
b/crates/spark-connect/tests/e2e_kmeans.rs
index 684d11d2..02337eb8 100644
--- a/crates/spark-connect/tests/e2e_kmeans.rs
+++ b/crates/spark-connect/tests/e2e_kmeans.rs
@@ -1,18 +1,11 @@
 //! Native KMeans tests. Set SPARK_REMOTE to run against a live Connect server.
+mod common;
+
+use common::live_session;
 use spark_connect::column::{col, lit};
 use spark_connect::expression::Expression;
 use spark_connect::ml::{Estimator, KMeans};
-use spark_connect::{Column, DataFrame, SparkSession};
-
-fn session() -> Option<SparkSession> {
-    let remote = std::env::var("SPARK_REMOTE").ok()?;
-    Some(
-        SparkSession::builder()
-            .remote(&remote)
-            .get_or_create()
-            .unwrap(),
-    )
-}
+use spark_connect::{Column, DataFrame};
 
 fn vectorize(df: DataFrame, name: &str) -> DataFrame {
     df.with_column(
@@ -50,7 +43,7 @@ fn assert_partition(actual: &[i64], expected: &[i64]) {
 
 #[test]
 fn kmeans_learns_distinct_models_and_keeps_lazy_predictions_alive() {
-    let Some(s) = session() else {
+    let Some(s) = live_session() else {
         return;
     };
     let training = vectorize(
@@ -132,7 +125,7 @@ fn 
kmeans_learns_distinct_models_and_keeps_lazy_predictions_alive() {
 
 #[test]
 fn kmeans_weights_move_the_boundary_with_default_columns() {
-    let Some(s) = session() else {
+    let Some(s) = live_session() else {
         return;
     };
     let training = vectorize(
@@ -165,7 +158,7 @@ fn kmeans_weights_move_the_boundary_with_default_columns() {
 
 #[test]
 fn kmeans_block_solver_random_initialization_and_three_clusters() {
-    let Some(s) = session() else {
+    let Some(s) = live_session() else {
         return;
     };
     let training = vectorize(s.sql(
@@ -192,7 +185,7 @@ fn 
kmeans_block_solver_random_initialization_and_three_clusters() {
 
 #[test]
 fn kmeans_cosine_distance_groups_vectors_by_direction() {
-    let Some(s) = session() else {
+    let Some(s) = live_session() else {
         return;
     };
     let training = vectorize(s.sql(
@@ -221,7 +214,7 @@ fn kmeans_cosine_distance_groups_vectors_by_direction() {
 
 #[test]
 fn kmeans_fit_rejects_invalid_data_and_parameters() {
-    let Some(s) = session() else {
+    let Some(s) = live_session() else {
         return;
     };
     assert!(KMeans::new().fit(&s.range(3).unwrap()).is_err());
diff --git a/crates/spark-connect/tests/e2e_linear_regression.rs 
b/crates/spark-connect/tests/e2e_linear_regression.rs
index d0b55a8a..5bc0234c 100644
--- a/crates/spark-connect/tests/e2e_linear_regression.rs
+++ b/crates/spark-connect/tests/e2e_linear_regression.rs
@@ -1,18 +1,11 @@
 //! Numerical tests of native LinearRegression. Set SPARK_REMOTE to use a live 
server.
+mod common;
+
+use common::live_session;
 use spark_connect::column::{col, lit};
 use spark_connect::expression::Expression;
 use spark_connect::ml::{Estimator, Evaluator, LinearRegression, 
RegressionEvaluator};
-use spark_connect::{Column, DataFrame, SparkSession};
-
-fn session() -> Option<SparkSession> {
-    let remote = std::env::var("SPARK_REMOTE").ok()?;
-    Some(
-        SparkSession::builder()
-            .remote(&remote)
-            .get_or_create()
-            .unwrap(),
-    )
-}
+use spark_connect::{Column, DataFrame};
 
 fn vectorize(df: DataFrame, name: &str) -> DataFrame {
     df.with_column(
@@ -43,7 +36,7 @@ fn assert_close(actual: Vec<f64>, expected: &[f64], 
tolerance: f64) {
 
 #[test]
 fn linear_regression_fits_different_lines_and_keeps_lazy_predictions_alive() {
-    let Some(s) = session() else {
+    let Some(s) = live_session() else {
         return;
     };
     let training = vectorize(
@@ -133,7 +126,7 @@ fn 
linear_regression_fits_different_lines_and_keeps_lazy_predictions_alive() {
 
 #[test]
 fn linear_regression_default_columns_and_zero_weight_outlier() {
-    let Some(s) = session() else {
+    let Some(s) = live_session() else {
         return;
     };
     let training = vectorize(s.sql(
@@ -169,7 +162,7 @@ fn 
linear_regression_default_columns_and_zero_weight_outlier() {
 
 #[test]
 fn linear_regression_iterative_elastic_net_and_huber_loss() {
-    let Some(s) = session() else {
+    let Some(s) = live_session() else {
         return;
     };
     let training = vectorize(
@@ -217,7 +210,7 @@ fn linear_regression_iterative_elastic_net_and_huber_loss() 
{
 
 #[test]
 fn linear_regression_fit_propagates_invalid_data_and_parameter_errors() {
-    let Some(s) = session() else {
+    let Some(s) = live_session() else {
         return;
     };
     assert!(LinearRegression::new().fit(&s.range(3).unwrap()).is_err());
diff --git a/crates/spark-connect/tests/e2e_linear_svc.rs 
b/crates/spark-connect/tests/e2e_linear_svc.rs
index 1b4f8e61..7f026749 100644
--- a/crates/spark-connect/tests/e2e_linear_svc.rs
+++ b/crates/spark-connect/tests/e2e_linear_svc.rs
@@ -1,19 +1,12 @@
 //! Native LinearSVC tests. Set SPARK_REMOTE to run against a live Spark 
Connect server.
+mod common;
+
+use common::live_session;
 use spark_connect::column::{col, lit};
 use spark_connect::expression::Expression;
 use spark_connect::ml::{Estimator, LinearSVC};
 use spark_connect::{Column, DataFrame, SparkSession};
 
-fn session() -> Option<SparkSession> {
-    let remote = std::env::var("SPARK_REMOTE").ok()?;
-    Some(
-        SparkSession::builder()
-            .remote(&remote)
-            .get_or_create()
-            .unwrap(),
-    )
-}
-
 fn vectorize(df: DataFrame, name: &str) -> DataFrame {
     df.with_column(
         name,
@@ -36,7 +29,7 @@ fn predictions(df: DataFrame, name: &str) -> Vec<f64> {
 
 #[test]
 fn linear_svc_fits_separate_models_and_predicts_on_unseen_data() {
-    let Some(s) = session() else {
+    let Some(s) = live_session() else {
         return;
     };
     let training = vectorize(
@@ -112,7 +105,7 @@ fn 
linear_svc_fits_separate_models_and_predicts_on_unseen_data() {
 
 #[test]
 fn linear_svc_defaults_and_zero_weight_training_examples() {
-    let Some(s) = session() else {
+    let Some(s) = live_session() else {
         return;
     };
     let training = vectorize(s.sql(
@@ -146,7 +139,7 @@ fn linear_svc_defaults_and_zero_weight_training_examples() {
 
 #[test]
 fn linear_svc_fit_rejects_invalid_training_data_and_parameters() {
-    let Some(s) = session() else {
+    let Some(s) = live_session() else {
         return;
     };
     assert!(LinearSVC::new().fit(&s.range(3).unwrap()).is_err());
@@ -209,7 +202,7 @@ fn wait_for_cached_models(s: &SparkSession, expected: 
usize) -> usize {
 
 #[test]
 fn 
linear_svc_model_is_deleted_from_the_server_when_its_last_owner_is_dropped() {
-    let Some(s) = session() else {
+    let Some(s) = live_session() else {
         return;
     };
     let training = vectorize(
diff --git a/crates/spark-connect/tests/e2e_new_methods.rs 
b/crates/spark-connect/tests/e2e_new_methods.rs
index f61d9ce5..a643d520 100644
--- a/crates/spark-connect/tests/e2e_new_methods.rs
+++ b/crates/spark-connect/tests/e2e_new_methods.rs
@@ -7,24 +7,15 @@
 //!
 //! Run with: `SPARK_REMOTE=sc://localhost:15002 cargo test --test 
e2e_new_methods`
 
+mod common;
+
 use std::collections::HashMap;
 
+use common::{session, should_run};
 use spark_connect::column::{col, lit};
 use spark_connect::session::SparkSession;
 use spark_connect::types::DataType;
 
-fn should_run() -> bool {
-    std::env::var("SPARK_REMOTE").is_ok()
-}
-
-fn session() -> SparkSession {
-    let url = std::env::var("SPARK_REMOTE").unwrap_or_else(|_| 
"sc://localhost:15002".to_string());
-    SparkSession::builder()
-        .remote(&url)
-        .get_or_create()
-        .expect("session")
-}
-
 fn numeric(s: &SparkSession) -> spark_connect::dataframe::DataFrame {
     s.sql("SELECT * FROM VALUES (0,1.0),(1,2.0),(1,3.0),(2,4.0),(3,5.0) AS 
t(g, v)")
         .expect("numeric df")
diff --git a/crates/spark-connect/tests/e2e_ops_breadth.rs 
b/crates/spark-connect/tests/e2e_ops_breadth.rs
index d874972e..11cf3388 100644
--- a/crates/spark-connect/tests/e2e_ops_breadth.rs
+++ b/crates/spark-connect/tests/e2e_ops_breadth.rs
@@ -5,6 +5,9 @@
 //! execution surface, so most calls are resilient (`let _ = ...`) and a few 
safe ones
 //! are asserted. Run with SPARK_REMOTE set.
 
+mod common;
+
+use common::{session, should_run};
 use spark_connect::column::{col, lit};
 use spark_connect::dataframe::DataFrame;
 use spark_connect::functions as f;
@@ -12,18 +15,6 @@ use spark_connect::plan::JoinType;
 use spark_connect::session::SparkSession;
 use spark_connect::types::DataType;
 
-fn should_run() -> bool {
-    std::env::var("SPARK_REMOTE").is_ok()
-}
-
-fn session() -> SparkSession {
-    let url = std::env::var("SPARK_REMOTE").unwrap_or_else(|_| 
"sc://localhost:15002".to_string());
-    SparkSession::builder()
-        .remote(&url)
-        .get_or_create()
-        .expect("session")
-}
-
 // (id, name, v) with a duplicate row for dedup/set-op paths.
 fn base(s: &SparkSession) -> DataFrame {
     s.sql("SELECT * FROM VALUES 
(1,'a',1.0),(2,'b',2.0),(2,'b',2.0),(3,'c',3.0) AS t(id, name, v)")
diff --git a/crates/spark-connect/tests/e2e_random_forest.rs 
b/crates/spark-connect/tests/e2e_random_forest.rs
index 865e2e58..75057ce6 100644
--- a/crates/spark-connect/tests/e2e_random_forest.rs
+++ b/crates/spark-connect/tests/e2e_random_forest.rs
@@ -1,19 +1,12 @@
 //! Native random forest tests. Set SPARK_REMOTE to run against a live Connect 
server.
+mod common;
+
+use common::live_session;
 use spark_connect::column::{col, lit_double, lit_string};
 use spark_connect::expression::Expression;
 use spark_connect::ml::{Estimator, RandomForestClassifier};
 use spark_connect::{Column, DataFrame, SparkSession};
 
-fn session() -> Option<SparkSession> {
-    let remote = std::env::var("SPARK_REMOTE").ok()?;
-    Some(
-        SparkSession::builder()
-            .remote(&remote)
-            .get_or_create()
-            .unwrap(),
-    )
-}
-
 fn vectors(s: &SparkSession, sql: &str, name: &str) -> DataFrame {
     s.sql(sql).unwrap().with_column(
         name,
@@ -54,7 +47,7 @@ fn deterministic() -> RandomForestClassifier {
 
 #[test]
 fn random_forest_learns_nonlinear_labels_and_keeps_cached_models_alive() {
-    let Some(s) = session() else {
+    let Some(s) = live_session() else {
         return;
     };
     let training = vectors(
@@ -151,7 +144,7 @@ fn 
random_forest_learns_nonlinear_labels_and_keeps_cached_models_alive() {
 
 #[test]
 fn random_forest_supports_multiclass_probabilities_and_leaf_indices() {
-    let Some(s) = session() else {
+    let Some(s) = live_session() else {
         return;
     };
     let training = vectors(
@@ -204,7 +197,7 @@ fn 
random_forest_supports_multiclass_probabilities_and_leaf_indices() {
 
 #[test]
 fn random_forest_weights_and_class_thresholds_change_predictions() {
-    let Some(s) = session() else {
+    let Some(s) = live_session() else {
         return;
     };
     // No split: the class probability is the (weighted) label frequency.
@@ -243,7 +236,7 @@ fn 
random_forest_weights_and_class_thresholds_change_predictions() {
 
 #[test]
 fn random_forest_bootstrap_and_feature_sampling_train_reproducibly() {
-    let Some(s) = session() else {
+    let Some(s) = live_session() else {
         return;
     };
     let training = vectors(
@@ -273,7 +266,7 @@ fn 
random_forest_bootstrap_and_feature_sampling_train_reproducibly() {
 
 #[test]
 fn random_forest_rejects_invalid_parameters_and_data() {
-    let Some(s) = session() else {
+    let Some(s) = live_session() else {
         return;
     };
     let data = vectors(
diff --git a/crates/spark-connect/tests/e2e_session_catalog.rs 
b/crates/spark-connect/tests/e2e_session_catalog.rs
index b19ee856..8337c160 100644
--- a/crates/spark-connect/tests/e2e_session_catalog.rs
+++ b/crates/spark-connect/tests/e2e_session_catalog.rs
@@ -7,18 +7,9 @@
 //!
 //! Run with: `SPARK_REMOTE=sc://localhost:15002 cargo test --test 
e2e_session_catalog`
 
-use spark_connect::session::SparkSession;
+mod common;
 
-fn should_run() -> bool {
-    std::env::var("SPARK_REMOTE").is_ok()
-}
-fn session() -> SparkSession {
-    let url = std::env::var("SPARK_REMOTE").unwrap_or_else(|_| 
"sc://localhost:15002".to_string());
-    SparkSession::builder()
-        .remote(&url)
-        .get_or_create()
-        .expect("session")
-}
+use common::{session, should_run};
 
 /// Exercise the whole Catalog RPC surface. Most `list_*`/`get_*` calls return 
a lazy
 /// DataFrame, so we collect them (tolerantly) to actually drive the server.
diff --git a/crates/spark-connect/tests/e2e_streaming.rs 
b/crates/spark-connect/tests/e2e_streaming.rs
index 3486e1be..564f7600 100644
--- a/crates/spark-connect/tests/e2e_streaming.rs
+++ b/crates/spark-connect/tests/e2e_streaming.rs
@@ -5,20 +5,10 @@
 //!
 //! Run with: `SPARK_REMOTE=sc://localhost:15002 cargo test --test 
e2e_streaming`
 
-use spark_connect::session::SparkSession;
-use spark_connect::streaming::Trigger;
-
-fn should_run() -> bool {
-    std::env::var("SPARK_REMOTE").is_ok()
-}
+mod common;
 
-fn session() -> SparkSession {
-    let url = std::env::var("SPARK_REMOTE").unwrap_or_else(|_| 
"sc://localhost:15002".to_string());
-    SparkSession::builder()
-        .remote(&url)
-        .get_or_create()
-        .expect("session")
-}
+use common::{session, should_run};
+use spark_connect::streaming::Trigger;
 
 /// A short-lived query on the `rate` source into an in-memory sink, so the 
whole
 /// reader -> writer.start -> StreamingQuery -> stop path runs against the 
server.
diff --git a/crates/spark-connect/tests/functions_golden.rs 
b/crates/spark-connect/tests/functions_golden.rs
index 1999b9d9..a0d636a4 100644
--- a/crates/spark-connect/tests/functions_golden.rs
+++ b/crates/spark-connect/tests/functions_golden.rs
@@ -5,12 +5,10 @@
 //! PySpark client output captured in `tests/golden/functions.jsonl`. Any 
missing
 //! or mismatched case FAILS the test - no silent skips.
 
+mod common;
+
 use std::collections::HashMap;
-use std::fs::File;
-use std::io::{BufRead, BufReader};
 
-use base64::{engine::general_purpose::STANDARD, Engine};
-use prost::Message;
 use spark_connect_proto as proto;
 
 /// Random-seed functions whose trailing `long` seed is non-deterministic
@@ -85,26 +83,7 @@ fn normalize(e: &mut proto::Expression) {
 }
 
 fn load_goldens() -> HashMap<String, proto::Expression> {
-    let path = concat!(
-        env!("CARGO_MANIFEST_DIR"),
-        "/../../tests/golden/functions.jsonl"
-    );
-    let file = File::open(path).expect("golden file functions.jsonl missing");
-    let mut out = HashMap::new();
-    for line in BufReader::new(file).lines() {
-        let line = line.unwrap();
-        if line.trim().is_empty() {
-            continue;
-        }
-        let obj: serde_json::Value = serde_json::from_str(&line).unwrap();
-        let name = obj["name"].as_str().unwrap().to_string();
-        let b64 = obj["b64"].as_str().unwrap();
-        let bytes = STANDARD.decode(b64).unwrap();
-        let mut expr = proto::Expression::decode(&bytes[..]).unwrap();
-        normalize(&mut expr);
-        out.insert(name, expr);
-    }
-    out
+    common::load_goldens("functions.jsonl", normalize)
 }
 
 #[test]
diff --git a/crates/spark-connect/tests/golden_test.rs 
b/crates/spark-connect/tests/golden_test.rs
index fbb4707e..647bb7d4 100644
--- a/crates/spark-connect/tests/golden_test.rs
+++ b/crates/spark-connect/tests/golden_test.rs
@@ -7,12 +7,10 @@
 //! on BOTH sides, then require byte-equality. A required case that is missing
 //! from the goldens or mismatches FAILS the test - no silent skips.
 
+mod common;
+
 use std::collections::HashMap;
-use std::fs::File;
-use std::io::{BufRead, BufReader};
 
-use base64::{engine::general_purpose::STANDARD, Engine};
-use prost::Message;
 use spark_connect::column::{col, lit_string, when};
 use spark_connect::expression::{Expression, LiteralExpression};
 use spark_connect::types::DataType;
@@ -66,27 +64,7 @@ fn normalize(e: &mut proto::Expression) {
 }
 
 fn load_goldens() -> HashMap<String, proto::Expression> {
-    // Goldens live at the repo root; tests run with CWD at the crate dir.
-    let path = concat!(
-        env!("CARGO_MANIFEST_DIR"),
-        "/../../tests/golden/exprs.jsonl"
-    );
-    let file = File::open(path).expect("golden file exprs.jsonl missing");
-    let mut out = HashMap::new();
-    for line in BufReader::new(file).lines() {
-        let line = line.unwrap();
-        if line.trim().is_empty() {
-            continue;
-        }
-        let obj: serde_json::Value = serde_json::from_str(&line).unwrap();
-        let name = obj["name"].as_str().unwrap().to_string();
-        let b64 = obj["b64"].as_str().unwrap();
-        let bytes = STANDARD.decode(b64).unwrap();
-        let mut expr = proto::Expression::decode(&bytes[..]).unwrap();
-        normalize(&mut expr);
-        out.insert(name, expr);
-    }
-    out
+    common::load_goldens("exprs.jsonl", normalize)
 }
 
 /// Build the Rust expression for each golden case name we are responsible for.
diff --git a/crates/spark-connect/tests/hof_golden.rs 
b/crates/spark-connect/tests/hof_golden.rs
index e4a8ed2a..bb4e4e0d 100644
--- a/crates/spark-connect/tests/hof_golden.rs
+++ b/crates/spark-connect/tests/hof_golden.rs
@@ -6,12 +6,10 @@
 //! before comparing: rename every distinct UnresolvedNamedLambdaVariable 
name_parts
 //! to v0, v1, ... in first-appearance order.
 
+mod common;
+
 use std::collections::HashMap;
-use std::fs::File;
-use std::io::{BufRead, BufReader};
 
-use base64::{engine::general_purpose::STANDARD, Engine};
-use prost::Message;
 use spark_connect::column::col;
 use spark_connect::expression::Expression;
 use spark_connect::functions::{
@@ -109,30 +107,12 @@ fn canonicalize_lambda_vars(
 }
 
 fn load_goldens() -> HashMap<String, proto::Expression> {
-    // Goldens live at the repo root; tests run with CWD at the crate dir.
-    let path = concat!(
-        env!("CARGO_MANIFEST_DIR"),
-        "/../../tests/golden/functions_hof.jsonl"
-    );
-    let file = File::open(path).expect("golden file functions_hof.jsonl 
missing");
-    let mut out = HashMap::new();
-    for line in BufReader::new(file).lines() {
-        let line = line.unwrap();
-        if line.trim().is_empty() {
-            continue;
-        }
-        let obj: serde_json::Value = serde_json::from_str(&line).unwrap();
-        let name = obj["name"].as_str().unwrap().to_string();
-        let b64 = obj["b64"].as_str().unwrap();
-        let bytes = STANDARD.decode(b64).unwrap();
-        let mut expr = proto::Expression::decode(&bytes[..]).unwrap();
+    common::load_goldens("functions_hof.jsonl", |expr| {
         // Canonicalize reference golden
         let mut name_map = HashMap::new();
         let mut counter = 0;
-        canonicalize_lambda_vars(&mut expr, &mut name_map, &mut counter);
-        out.insert(name, expr);
-    }
-    out
+        canonicalize_lambda_vars(expr, &mut name_map, &mut counter);
+    })
 }
 
 fn build(name: &str) -> Option<Expression> {
diff --git a/crates/spark-connect/tests/ml_extra_golden.rs 
b/crates/spark-connect/tests/ml_extra_golden.rs
index c2b7907c..80b972fe 100644
--- a/crates/spark-connect/tests/ml_extra_golden.rs
+++ b/crates/spark-connect/tests/ml_extra_golden.rs
@@ -5,6 +5,8 @@
 
 #![allow(dead_code)] // golden-test helpers are copy-shared across suites; 
each binary uses a subset
 
+mod common;
+
 use std::collections::HashMap;
 use std::fs::File;
 use std::io::{BufRead, BufReader};
@@ -12,6 +14,7 @@ use std::io::{BufRead, BufReader};
 use base64::{engine::general_purpose::STANDARD, Engine};
 use prost::Message;
 
+use common::normalize_relation;
 use spark_connect::ml::{
     BinaryClassificationEvaluator, Estimator, Evaluator, LogisticRegression, 
MaxAbsScaler,
     MlOperator, OperatorType, Params, Pipeline, PipelineModel, 
RegressionEvaluator, StringIndexer,
@@ -19,38 +22,10 @@ use spark_connect::ml::{
 };
 use spark_connect_proto as proto;
 
-fn normalize_ml_operator(op: &mut proto::MlOperator) {
-    op.uid.clear();
-}
-
 fn normalize_expression(e: &mut proto::Expression) {
     e.common = None;
 }
 
-fn normalize_ml_params(_params: &mut proto::MlParams) {
-    // MlParams.params values are `Literal` (no plan_id/origin to clear here).
-}
-
-fn normalize_ml_relation(ml_rel: &mut proto::MlRelation) {
-    if let Some(proto::ml_relation::MlType::Transform(transform)) = 
ml_rel.ml_type.as_mut() {
-        if let Some(proto::ml_relation::transform::Operator::Transformer(op)) =
-            transform.operator.as_mut()
-        {
-            normalize_ml_operator(op);
-        }
-        if let Some(params) = transform.params.as_mut() {
-            normalize_ml_params(params);
-        }
-    }
-}
-
-fn normalize_relation(r: &mut proto::Relation) {
-    r.common = None;
-    if let Some(proto::relation::RelType::MlRelation(ml_rel)) = &mut 
r.rel_type {
-        normalize_ml_relation(ml_rel);
-    }
-}
-
 fn load_ml_extra_goldens() -> HashMap<String, proto::Relation> {
     let path = concat!(
         env!("CARGO_MANIFEST_DIR"),
diff --git a/crates/spark-connect/tests/ml_golden.rs 
b/crates/spark-connect/tests/ml_golden.rs
index 20f85ae1..9974188c 100644
--- a/crates/spark-connect/tests/ml_golden.rs
+++ b/crates/spark-connect/tests/ml_golden.rs
@@ -5,6 +5,8 @@
 
 #![allow(dead_code)] // golden-test helpers are copy-shared across suites; 
each binary uses a subset
 
+mod common;
+
 use std::collections::HashMap;
 use std::fs::File;
 use std::io::{BufRead, BufReader};
@@ -12,16 +14,11 @@ use std::io::{BufRead, BufReader};
 use base64::{engine::general_purpose::STANDARD, Engine};
 use prost::Message;
 
+use common::normalize_relation;
 use spark_connect::ml::Estimator;
 use spark_connect::ml::{MlOperator, OperatorType, Params};
 use spark_connect_proto as proto;
 
-/// Recursively clear non-deterministic fields from protobuf messages.
-fn normalize_ml_operator(op: &mut proto::MlOperator) {
-    // Clear UID to normalize across runs (UIDs are instance identifiers)
-    op.uid.clear();
-}
-
 fn normalize_expression(e: &mut proto::Expression) {
     use proto::expression::ExprType as T;
     e.common = None;
@@ -30,30 +27,6 @@ fn normalize_expression(e: &mut proto::Expression) {
     }
 }
 
-fn normalize_ml_params(_params: &mut proto::MlParams) {
-    // MlParams.params values are `Literal` (no plan_id/origin to clear here).
-}
-
-fn normalize_ml_relation(ml_rel: &mut proto::MlRelation) {
-    if let Some(proto::ml_relation::MlType::Transform(transform)) = 
ml_rel.ml_type.as_mut() {
-        if let Some(proto::ml_relation::transform::Operator::Transformer(op)) =
-            transform.operator.as_mut()
-        {
-            normalize_ml_operator(op);
-        }
-        if let Some(params) = transform.params.as_mut() {
-            normalize_ml_params(params);
-        }
-    }
-}
-
-fn normalize_relation(r: &mut proto::Relation) {
-    r.common = None;
-    if let Some(proto::relation::RelType::MlRelation(ml_rel)) = &mut 
r.rel_type {
-        normalize_ml_relation(ml_rel);
-    }
-}
-
 fn load_ml_goldens() -> HashMap<String, proto::Relation> {
     let path = concat!(env!("CARGO_MANIFEST_DIR"), 
"/../../tests/golden/ml.jsonl");
     let file = match File::open(path) {
diff --git a/crates/spark-connect/tests/plans_golden.rs 
b/crates/spark-connect/tests/plans_golden.rs
index 1768b251..ae4cc1b2 100644
--- a/crates/spark-connect/tests/plans_golden.rs
+++ b/crates/spark-connect/tests/plans_golden.rs
@@ -6,12 +6,9 @@
 //! (`common`/origin, attribute `plan_id`) on BOTH sides, then require 
byte-equality.
 //! A required case that is missing or mismatches FAILS the test - no silent 
skips.
 
-use std::collections::HashMap;
-use std::fs::File;
-use std::io::{BufRead, BufReader};
+mod common;
 
-use base64::{engine::general_purpose::STANDARD, Engine};
-use prost::Message;
+use std::collections::HashMap;
 
 use spark_connect::column::col;
 use spark_connect::expression::{Expression, ExpressionNode};
@@ -258,28 +255,11 @@ fn normalize_expression(e: &mut proto::Expression) {
 }
 
 fn load_goldens() -> HashMap<String, proto::Plan> {
-    let path = concat!(
-        env!("CARGO_MANIFEST_DIR"),
-        "/../../tests/golden/plans.jsonl"
-    );
-    let file = File::open(path).expect("golden file plans.jsonl missing");
-    let mut out = HashMap::new();
-    for line in BufReader::new(file).lines() {
-        let line = line.unwrap();
-        if line.trim().is_empty() {
-            continue;
-        }
-        let obj: serde_json::Value = serde_json::from_str(&line).unwrap();
-        let name = obj["name"].as_str().unwrap().to_string();
-        let b64 = obj["b64"].as_str().unwrap();
-        let bytes = STANDARD.decode(b64).unwrap();
-        let mut plan = proto::Plan::decode(&bytes[..]).unwrap();
+    common::load_goldens("plans.jsonl", |plan: &mut proto::Plan| {
         if let Some(proto::plan::OpType::Root(root)) = &mut plan.op_type {
             normalize_relation(root);
         }
-        out.insert(name, plan);
-    }
-    out
+    })
 }
 
 fn build(name: &str) -> Option<LogicalPlan> {
diff --git a/crates/spark-connect/tests/readwriter_golden.rs 
b/crates/spark-connect/tests/readwriter_golden.rs
index 542dfabb..30b52c1a 100644
--- a/crates/spark-connect/tests/readwriter_golden.rs
+++ b/crates/spark-connect/tests/readwriter_golden.rs
@@ -11,17 +11,6 @@ use spark_connect::plan::LogicalPlan;
 use spark_connect::readwriter::{ReadType, SaveMode, TableSaveMethod};
 use spark_connect_proto as proto;
 
-/// Normalize a relation by clearing non-deterministic fields.
-fn normalize_relation(r: &mut proto::Relation) {
-    r.common = None;
-    if let Some(_rel_type) = &mut r.rel_type {
-        use proto::relation::RelType;
-        if let RelType::Read(_read) = _rel_type {
-            // No recursive normalization needed for Read
-        }
-    }
-}
-
 #[test]
 fn test_read_json() {
     // Test reading JSON format
diff --git a/crates/spark-connect/tests/window_golden.rs 
b/crates/spark-connect/tests/window_golden.rs
index 41ffb22b..73b8be8d 100644
--- a/crates/spark-connect/tests/window_golden.rs
+++ b/crates/spark-connect/tests/window_golden.rs
@@ -6,11 +6,10 @@
 
 #![allow(dead_code)] // golden-test helpers are copy-shared across suites; 
each binary uses a subset
 
+mod common;
+
 use std::collections::HashMap;
-use std::fs::File;
-use std::io::{BufRead, BufReader};
 
-use base64::{engine::general_purpose::STANDARD, Engine};
 use prost::Message;
 use spark_connect::column::col;
 use spark_connect::expression::{Expression, LiteralExpression};
@@ -79,26 +78,7 @@ fn normalize(e: &mut proto::Expression) {
 }
 
 fn load_goldens() -> HashMap<String, proto::Expression> {
-    let path = concat!(
-        env!("CARGO_MANIFEST_DIR"),
-        "/../../tests/golden/window.jsonl"
-    );
-    let file = File::open(path).expect("golden file window.jsonl missing");
-    let mut out = HashMap::new();
-    for line in BufReader::new(file).lines() {
-        let line = line.unwrap();
-        if line.trim().is_empty() {
-            continue;
-        }
-        let obj: serde_json::Value = serde_json::from_str(&line).unwrap();
-        let name = obj["name"].as_str().unwrap().to_string();
-        let b64 = obj["b64"].as_str().unwrap();
-        let bytes = STANDARD.decode(b64).unwrap();
-        let mut expr = proto::Expression::decode(&bytes[..]).unwrap();
-        normalize(&mut expr);
-        out.insert(name, expr);
-    }
-    out
+    common::load_goldens("window.jsonl", normalize)
 }
 
 /// Build the Rust window expression for each golden case name.


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

Reply via email to