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 817b5dc8 [SPARK-61246][CONNECT][PYTHON] Add the ChannelBuilder 
classes, the session registry, the observed server-side session ID and the 
other Connect session and client members of PySpark
817b5dc8 is described below

commit 817b5dc8032ea509d46e55bb9efbdc07bed80e21
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Mon Nov 9 21:35:59 2026 +0900

    [SPARK-61246][CONNECT][PYTHON] Add the ChannelBuilder classes, the session 
registry, the observed server-side session ID and the other Connect session and 
client members of PySpark
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61246](https://issues.apache.org/jira/browse/SPARK-61246): Add the 
Connect session and client members of PySpark 4.3.0 that the drop-in lacks, 
found by an item-by-item comparison of the `pyspark-client` API and by running 
the official test files against the drop-in itself.
    
    - `pyspark.sql.connect.client` exports `ChannelBuilder` and 
`DefaultChannelBuilder`. They parse an `sc://` connection string as PySpark's 
do (`host`, `port`, `endpoint`, `get`/`set`, `userId`, `token`, `session_id`, 
`use_ssl`, `secure`, `metadata()`), and 
`SparkSession.builder.channelBuilder(DefaultChannelBuilder(url))` honors them. 
The gRPC channel members (`toChannel`, interceptors, channel options) are not 
provided: the transport is native (`dev/parity/known-differences.md`).
    - The Connect `SparkSession` gets PySpark's class-level registry that its 
tests use (`_default_session`, `_active_session`, `_get_default_session()`, 
`_lock`), `release_session_on_close` (honored by `stop()`), and direct 
construction `SparkSession(connection=..., userId=..., hook_factories=...)`, 
which makes a session that is neither the default nor the active one, as 
PySpark's constructor does.
    - `SparkConnectClient` gets `host`, `_closed`, `_proto_to_string`, and 
`_server_session_id`: the server-side session ID that the client observed (None 
before the first response), settable as PySpark's tests do to simulate a server 
restart.
    
    ### Why are the changes needed?
    
    Code written for PySpark Connect could not use them: `from 
pyspark.sql.connect.client import DefaultChannelBuilder` failed, and the 
official `pyspark/sql/tests/connect/test_connect_session.py` failed at import 
against the drop-in.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, the members above, as PySpark has them.
    
    ### How was this patch tested?
    
    - The official test files, run against the drop-in itself (not through the 
transport plugin), as official PySpark 4.3.0 on the same server:
      - `test_connect_session.py`: import error -> 10 passed, 17 skipped 
(official: 10 passed, 17 skipped)
      - `test_connect_context.py`: 9 passed, 1 failed -> 10 passed (official: 
10 passed)
      - `test_connect_error.py`: 11 passed, 2 failed -> 12 passed, 1 failed 
(official: 13 passed). The remaining `test_recursion_handling_for_plan_logging` 
needs the Python plan of a deep DataFrame, which the Rust core builds instead 
(recorded in `known-differences.md`).
    - New offline tests in `test_dropin_offline.py` and live tests in 
`test_dropin_e2e.py`, and a Rust unit test of the session's accessors.
    - The lib tests of both crates (666 passed), the build of all tests, also 
with `wasm-udf`, the offline Python suites (2825 passed, 8 skipped), and the 
live drop-in and Arrow suites (234 passed) and live cases (13 passed) against a 
local Spark 4.3.0 server. rustfmt passes. Clippy's only diagnostic on a changed 
line is `result_large_err` of the execute-plan hook closure, which this moves 
unchanged from the builder into a helper (master has the same diagnostic 
there). The official `strea [...]
    
    ### 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 #426 from HyukjinKwon/SPARK-61246-connect-session-client.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/session.rs              | 435 +++++++++++++++++++++-----
 crates/spark-connect-core/src/client.rs       |  43 ++-
 crates/spark-connect/src/session.rs           |  32 ++
 dev/parity/known-differences.md               |  44 +++
 python/pyspark/sql/connect/client/__init__.py | 287 ++++++++++++++++-
 python/pyspark/sql/connect/session.py         |  13 +
 python/tests/test_dropin_e2e.py               |  28 ++
 python/tests/test_dropin_offline.py           | 170 ++++++++++
 python/tests/test_ml_offline.py               |   9 +-
 9 files changed, 971 insertions(+), 90 deletions(-)

diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index 6d51ded1..489c3515 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -28,6 +28,9 @@ pub struct PySparkSessionBuilder {
     /// The hook factories of `_registerHook`, which a new session calls with 
itself, as
     /// PySpark's builder does.
     hook_factories: Vec<std::sync::Arc<Py<PyAny>>>,
+    /// The channel builder of `channelBuilder`, which the session connects 
with, instead of
+    /// `remote()`: PySpark's `_channel_builder`, which is not an option.
+    channel_builder: Option<std::sync::Arc<Py<PyAny>>>,
 }
 
 impl PySparkSessionBuilder {
@@ -36,6 +39,7 @@ impl PySparkSessionBuilder {
             remote_url: None,
             configs: Vec::new(),
             hook_factories: Vec::new(),
+            channel_builder: None,
         }
     }
 }
@@ -170,36 +174,10 @@ impl PySparkSessionBuilder {
         mut slf: PyRefMut<'py, Self>,
         channelBuilder: &Bound<'_, PyAny>,
     ) -> PyResult<PyRefMut<'py, Self>> {
-        // Endpoint: prefer the builder's host/port (DefaultChannelBuilder 
exposes both).
-        let host: String = channelBuilder
-            .getattr("host")
-            .and_then(|h| h.extract::<String>())
-            .map_err(|_| {
-                PyErr::new::<pyo3::exceptions::PyValueError, _>(
-                    "channelBuilder must expose a `host` (e.g. 
DefaultChannelBuilder); \
-                     otherwise configure the endpoint via .remote(url)",
-                )
-            })?;
-        let port: i64 = channelBuilder
-            .getattr("port")
-            .and_then(|p| p.extract::<i64>())
-            .unwrap_or(15002);
-        let mut url = format!("sc://{host}:{port}");
-        // Preserve connection params (token/use_ssl/user_id/...) if present 
as `_params`.
-        if let Ok(params) = channelBuilder.getattr("_params") {
-            if let Ok(dict) = params.cast::<pyo3::types::PyDict>() {
-                if !dict.is_empty() {
-                    let mut parts: Vec<String> = Vec::new();
-                    for (k, v) in dict.iter() {
-                        parts.push(format!("{}={}", k.str()?, v.str()?));
-                    }
-                    url.push_str("/;");
-                    url.push_str(&parts.join(";"));
-                }
-            }
-        }
-        let py = slf.py();
-        slf.set_option(py, "spark.remote", url)?;
+        // A builder without an endpoint is an error here, not when the 
session is created; the
+        // URL itself is read then, with the parameters of the builder as they 
are by then.
+        url_of_channel_builder(channelBuilder)?;
+        slf.channel_builder = 
Some(std::sync::Arc::new(channelBuilder.clone().unbind()));
         Ok(slf)
     }
 
@@ -216,12 +194,12 @@ impl PySparkSessionBuilder {
     /// whatever its URL.
     #[pyo3(name = "getOrCreate")]
     fn get_or_create(&self, py: Python<'_>) -> PyResult<Py<PySparkSession>> {
-        let url = self.url(py)?;
         let (session, created) = {
             let _creating = session_lock();
             match active_session(py).or_else(|| default_session(py)) {
                 Some(session) => (session, false),
-                None => (new_session(py, &url)?, true),
+                // The URL is needed only to create a session, as PySpark's 
getOrCreate.
+                None => (new_session(py, &self.connection_url(py)?)?, true),
             }
         };
         if created {
@@ -235,7 +213,7 @@ impl PySparkSessionBuilder {
     /// `create()` - a new session, which is the default session, and the 
active one of this
     /// thread, only when they are not set. Mirrors PySpark's.
     fn create(&self, py: Python<'_>) -> PyResult<Py<PySparkSession>> {
-        let url = self.url(py)?;
+        let url = self.connection_url(py)?;
         let session = {
             let _creating = session_lock();
             new_session(py, &url)?
@@ -249,30 +227,30 @@ impl PySparkSessionBuilder {
 
 impl PySparkSessionBuilder {
     /// The hooks of the factories of `_registerHook` for `session`, a session 
that the builder
-    /// created, as PySpark's `SparkSession(hook_factories=...)` makes them: 
of each factory
-    /// called with the session, of whose `on_execute_plan` the session's 
executions send the
-    /// requests. The factories run after the lock of the creation of sessions 
is released, as
-    /// Python code may release the GIL that the lock is held with.
+    /// created, as PySpark's `SparkSession(hook_factories=...)` makes them.
     fn install_hooks(&self, py: Python<'_>, session: &Py<PySparkSession>) -> 
PyResult<()> {
-        if self.hook_factories.is_empty() {
-            return Ok(());
-        }
-        let hooks = self
+        let factories: Vec<Py<PyAny>> = self
             .hook_factories
             .iter()
-            .map(|factory| {
-                factory
-                    .bind(py)
-                    .call1((session.clone_ref(py),))
-                    .map(Bound::unbind)
-            })
-            .collect::<PyResult<Vec<_>>>()?;
-        let hook: spark_connect::ExecutePlanHook = std::sync::Arc::new(move 
|request| {
-            Python::attach(|py| call_execute_plan_hooks(py, &hooks, request))
-                .map_err(crate::errors::callback_error)
-        });
-        session.borrow(py).session.set_execute_plan_hook(Some(hook));
-        Ok(())
+            .map(|factory| factory.clone_ref(py))
+            .collect();
+        install_hook_factories(py, &factories, session)
+    }
+
+    /// The connection URL of the session that the builder creates: that of 
the channel builder
+    /// of `channelBuilder`, or else of `remote()` or `SPARK_REMOTE`. As 
PySpark's `create`, it
+    /// is an error to give both a channel builder and a URL.
+    fn connection_url(&self, py: Python<'_>) -> PyResult<String> {
+        match &self.channel_builder {
+            Some(_) if self.remote_url.is_some() => 
Err(crate::column::raise_pyspark(
+                py,
+                "PySparkValueError",
+                "SESSION_NEED_CONN_STR_OR_BUILDER",
+                &[],
+            )),
+            Some(channel_builder) => 
url_of_channel_builder(channel_builder.bind(py)),
+            None => self.url(py),
+        }
     }
 
     /// Set an option, capturing `spark.remote` as the endpoint, and validate 
the startup URLs
@@ -347,12 +325,7 @@ impl PySparkSessionBuilder {
             .or_else(|| std::env::var("SPARK_REMOTE").ok())
         {
             Some(url) => Ok(url),
-            None => Err(crate::column::raise_pyspark(
-                py,
-                "PySparkRuntimeError",
-                "CONNECT_URL_NOT_SET",
-                &[],
-            )),
+            None => Err(connect_url_not_set(py)),
         }
     }
 
@@ -386,12 +359,137 @@ impl PySparkSessionBuilder {
     }
 }
 
-/// The default session: the first session created, of every thread, until it 
stops. Mirrors
-/// `SparkSession._default_session`. The Python object, which `getOrCreate()` 
returns as it is.
-fn default_slot() -> &'static std::sync::Mutex<Option<Py<PySparkSession>>> {
-    static SLOT: 
std::sync::OnceLock<std::sync::Mutex<Option<Py<PySparkSession>>>> =
-        std::sync::OnceLock::new();
-    SLOT.get_or_init(|| std::sync::Mutex::new(None))
+/// The `sc://` URL of the channel builder `channel_builder`, which has the 
`host` and the `port`
+/// of its endpoint and the `_params` of its connection, as PySpark's 
`ChannelBuilder` does. Its
+/// parameters are percent-encoded, as the URL parser of the transport decodes 
them.
+pub(crate) fn url_of_channel_builder(channel_builder: &Bound<'_, PyAny>) -> 
PyResult<String> {
+    // Endpoint: the builder's host and port, which DefaultChannelBuilder 
exposes.
+    let host: String = channel_builder
+        .getattr("host")
+        .and_then(|h| h.extract::<String>())
+        .map_err(|_| {
+            PyErr::new::<pyo3::exceptions::PyValueError, _>(
+                "channelBuilder must expose a `host` (e.g. 
DefaultChannelBuilder); \
+                 otherwise configure the endpoint via .remote(url)",
+            )
+        })?;
+    let port: i64 = channel_builder
+        .getattr("port")
+        .and_then(|p| p.extract::<i64>())
+        .unwrap_or(15002);
+    let mut url = format!("sc://{host}:{port}");
+    // Preserve connection params (token/use_ssl/user_id/...) if present as 
`_params`.
+    if let Ok(params) = channel_builder.getattr("_params") {
+        if let Ok(dict) = params.cast::<pyo3::types::PyDict>() {
+            if !dict.is_empty() {
+                let mut parts: Vec<String> = Vec::new();
+                for (k, v) in dict.iter() {
+                    parts.push(format!(
+                        "{}={}",
+                        k.str()?,
+                        quote_param(&v.str()?.to_string())
+                    ));
+                }
+                url.push_str("/;");
+                url.push_str(&parts.join(";"));
+            }
+        }
+    }
+    Ok(url)
+}
+
+/// `value`, percent-encoded outside the unreserved characters, so that it is 
one value of a
+/// `;`-separated URL parameter.
+fn quote_param(value: &str) -> String {
+    value
+        .bytes()
+        .map(|b| {
+            if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
+                (b as char).to_string()
+            } else {
+                format!("%{b:02X}")
+            }
+        })
+        .collect()
+}
+
+/// `url`, with the parameter `user_id` set to `user`, unless it has one, 
which takes precedence,
+/// as PySpark's `SparkSession(userId=...)` gives it to the connection.
+fn with_user_id(url: &str, user: &str) -> PyResult<String> {
+    if spark_connect_core::channel::ChannelBuilder::parse(url)
+        .to_pyerr()?
+        .get("user_id")
+        .is_some()
+    {
+        return Ok(url.to_string());
+    }
+    let param = format!("user_id={}", quote_param(user));
+    let base = url.trim_end_matches('/');
+    Ok(if base.contains(';') {
+        format!("{base};{param}")
+    } else {
+        format!("{base}/;{param}")
+    })
+}
+
+/// The `CONNECT_URL_NOT_SET` error of a builder without a URL: see 
`_ConnectUrlNotSetError`.
+fn connect_url_not_set(py: Python<'_>) -> PyErr {
+    let error = py
+        .import("pyspark.sql.connect.session")
+        .and_then(|module| module.getattr("_connect_url_not_set_error"))
+        .and_then(|make| make.call0());
+    match error {
+        Ok(error) => PyErr::from_value(error),
+        Err(error) => error,
+    }
+}
+
+/// Install on `session` the hooks that `factories` make of it, each called 
with the session, as
+/// PySpark's `SparkSession(hook_factories=...)`.
+fn install_hook_factories(
+    py: Python<'_>,
+    factories: &[Py<PyAny>],
+    session: &Py<PySparkSession>,
+) -> PyResult<()> {
+    if factories.is_empty() {
+        return Ok(());
+    }
+    let hooks = factories
+        .iter()
+        .map(|factory| {
+            factory
+                .bind(py)
+                .call1((session.clone_ref(py),))
+                .map(Bound::unbind)
+        })
+        .collect::<PyResult<Vec<_>>>()?;
+    let hook: spark_connect::ExecutePlanHook = std::sync::Arc::new(move 
|request| {
+        Python::attach(|py| call_execute_plan_hooks(py, &hooks, request))
+            .map_err(crate::errors::callback_error)
+    });
+    session.borrow(py).session.set_execute_plan_hook(Some(hook));
+    Ok(())
+}
+
+/// The default session, which is the class attribute `_default_session` of 
`SparkSession`, as
+/// PySpark's: the first session created, of every thread, until it stops. The 
attribute is the
+/// one value, which the Python code may also set, as PySpark's tests do.
+fn default_slot(py: Python<'_>) -> Option<Py<PySparkSession>> {
+    let value = py
+        .get_type::<PySparkSession>()
+        .getattr("_default_session")
+        .ok()?;
+    if value.is_none() {
+        return None;
+    }
+    value.cast_into::<PySparkSession>().ok().map(Bound::unbind)
+}
+
+/// Set the default session, as the class attribute `_default_session`.
+fn set_default_slot(py: Python<'_>, session: Option<Py<PySparkSession>>) {
+    let _ = py
+        .get_type::<PySparkSession>()
+        .setattr("_default_session", session);
 }
 
 thread_local! {
@@ -459,11 +557,7 @@ fn active_session(py: Python<'_>) -> 
Option<Py<PySparkSession>> {
 
 /// The default session, unless it stopped.
 fn default_session(py: Python<'_>) -> Option<Py<PySparkSession>> {
-    default_slot()
-        .lock()
-        .unwrap_or_else(|e| e.into_inner())
-        .as_ref()
-        .and_then(|session| unless_stopped(py, session))
+    default_slot(py).and_then(|session| unless_stopped(py, &session))
 }
 
 /// A new session of `url`, which is the default session, and the active 
session of this
@@ -554,11 +648,8 @@ pub(crate) fn session_object(
 /// Make `session` the default session, and the active session of this thread, 
when they are
 /// not set, as PySpark's `SparkSession._set_default_and_active_session`.
 fn set_default_and_active(py: Python<'_>, session: &Py<PySparkSession>) {
-    {
-        let mut default = default_slot().lock().unwrap_or_else(|e| 
e.into_inner());
-        if default.is_none() {
-            *default = Some(session.clone_ref(py));
-        }
+    if default_slot(py).is_none() {
+        set_default_slot(py, Some(session.clone_ref(py)));
     }
     ACTIVE_SESSION.with(|active| {
         let mut active = active.borrow_mut();
@@ -596,6 +687,32 @@ fn log_client_banner(py: Python<'_>) {
     });
 }
 
+/// The active session of the current thread, as PySpark's 
`SparkSession._active_session`, a
+/// thread-local whose `session` attribute is the session: the 
`ACTIVE_SESSION` of this thread.
+#[pyclass(name = "_ActiveSession", module = "pyspark.sql.session", frozen)]
+pub struct PyActiveSession;
+
+#[pymethods]
+impl PyActiveSession {
+    /// The active session of this thread, which may be stopped, as the 
attribute of the
+    /// thread-local of PySpark.
+    #[getter]
+    fn session(&self, py: Python<'_>) -> Option<Py<PySparkSession>> {
+        ACTIVE_SESSION.with(|active| {
+            active
+                .borrow()
+                .as_ref()
+                .map(|session| session.clone_ref(py))
+        })
+    }
+
+    /// Set the active session of this thread; None clears it.
+    #[setter]
+    fn set_session(&self, session: Option<Py<PySparkSession>>) {
+        ACTIVE_SESSION.with(|active| *active.borrow_mut() = session);
+    }
+}
+
 /// `SparkSession.Hook` - injects behavior around plan execution, as PySpark's
 /// `SparkSession.Hook`: a session calls the `on_execute_plan` of each hook of 
the factories of
 /// `_registerHook` with each `ExecutePlanRequest`, as a message of the 
generated
@@ -657,6 +774,9 @@ pub struct PySparkSession {
     pub(crate) session: SparkSession,
     /// The `StreamingQueryManager` of `spark.streams`, made at its first 
access.
     streams: std::sync::OnceLock<Py<PyStreamingQueryManager>>,
+    /// Whether `stop()` releases the session on the server, as PySpark's
+    /// `release_session_on_close`, which tests set to False to skip the 
release.
+    release_session_on_close: std::sync::atomic::AtomicBool,
 }
 
 struct PandasArrowColumn {
@@ -761,6 +881,7 @@ impl PySparkSession {
         PySparkSession {
             session,
             streams: std::sync::OnceLock::new(),
+            release_session_on_close: std::sync::atomic::AtomicBool::new(true),
         }
     }
 
@@ -2313,7 +2434,17 @@ impl PySparkSession {
     fn stop(&self, py: Python<'_>) -> PyResult<()> {
         crate::progress::forget_session(&self.session);
         crate::profiler::forget_session(&self.session);
-        if let Err(e) = py.detach(|| self.session.stop().map_err(Box::new)) {
+        let released = if self
+            .release_session_on_close
+            .load(std::sync::atomic::Ordering::SeqCst)
+        {
+            py.detach(|| self.session.stop().map_err(Box::new))
+        } else {
+            // As PySpark's stop: without the release, the client is closed 
all the same.
+            py.detach(|| self.session.close());
+            Ok(())
+        };
+        if let Err(e) = released {
             let logger = py
                 .import("logging")?
                 .call_method1("getLogger", ("pyspark",))?;
@@ -2328,11 +2459,8 @@ impl PySparkSession {
         // session of this thread.
         let sid = self.session.session_id();
         let is_this = |s: &Py<PySparkSession>| 
s.borrow(py).session.session_id() == sid;
-        {
-            let mut default = default_slot().lock().unwrap_or_else(|e| 
e.into_inner());
-            if default.as_ref().is_some_and(is_this) {
-                *default = None;
-            }
+        if default_slot(py).as_ref().is_some_and(is_this) {
+            set_default_slot(py, None);
         }
         ACTIVE_SESSION.with(|active| {
             let mut active = active.borrow_mut();
@@ -2609,6 +2737,61 @@ impl PySparkSession {
         self.session.is_stopped()
     }
 
+    /// `SparkSession(connection, userId=None, hook_factories=None)`, as 
PySpark Connect's: a
+    /// session of the URL or channel builder `connection`, which is neither 
the default nor the
+    /// active session, as PySpark's constructor does not make it either.
+    #[new]
+    #[pyo3(signature = (connection, userId=None, hook_factories=None))]
+    #[allow(non_snake_case)]
+    fn py_new(
+        py: Python<'_>,
+        connection: &Bound<'_, PyAny>,
+        userId: Option<String>,
+        hook_factories: Option<Bound<'_, PyAny>>,
+    ) -> PyResult<Py<Self>> {
+        let url = match connection.extract::<String>() {
+            Ok(url) => url,
+            Err(_) => url_of_channel_builder(connection)?,
+        };
+        let url = match userId {
+            Some(user) => with_user_id(&url, &user)?,
+            None => url,
+        };
+        let session = py
+            .detach(|| {
+                SparkSession::builder()
+                    .remote(&url)
+                    .get_or_create()
+                    .map_err(Box::new)
+            })
+            .to_pyerr()?;
+        let session = session_object(py, &session)?;
+        let factories = match hook_factories {
+            Some(factories) => factories
+                .try_iter()?
+                .map(|factory| factory.map(Bound::unbind))
+                .collect::<PyResult<Vec<_>>>()?,
+            None => Vec::new(),
+        };
+        install_hook_factories(py, &factories, &session)?;
+        log_client_banner(py);
+        Ok(session)
+    }
+
+    /// Whether `stop()` releases the session on the server, as PySpark's
+    /// `release_session_on_close`, which is True unless set otherwise.
+    #[getter]
+    fn release_session_on_close(&self) -> bool {
+        self.release_session_on_close
+            .load(std::sync::atomic::Ordering::SeqCst)
+    }
+
+    #[setter]
+    fn set_release_session_on_close(&self, value: bool) {
+        self.release_session_on_close
+            .store(value, std::sync::atomic::Ordering::SeqCst);
+    }
+
     /// The builder CLASS, reached as `SparkSession.Builder` (mirrors pyspark, 
which
     /// exposes the nested `Builder` type so `SparkSession.Builder()` works).
     #[classattr]
@@ -2617,6 +2800,53 @@ impl PySparkSession {
         py.get_type::<PySparkSessionBuilder>().unbind()
     }
 
+    /// The class attribute `_default_session`, the default session or None, 
as PySpark's:
+    /// `_get_default_session` reads it, and `stop()` clears it. It is set as 
a class attribute
+    /// (`set_default_slot`), so Python code that sets it changes the session 
that is default.
+    #[classattr]
+    fn _default_session(py: Python<'_>) -> Py<PyAny> {
+        py.None()
+    }
+
+    /// The class attribute `_active_session`, whose `session` is the active 
session of the
+    /// current thread, as PySpark's thread-local 
`SparkSession._active_session`.
+    #[classattr]
+    fn _active_session(py: Python<'_>) -> PyResult<Py<PyActiveSession>> {
+        Py::new(py, PyActiveSession)
+    }
+
+    /// The class attribute `_lock`, PySpark's `threading.RLock` of the 
session registry, for the
+    /// Python code that takes it. The drop-in serializes the creation of 
sessions with its own
+    /// lock, as `getOrCreate` does with `_lock`.
+    #[classattr]
+    fn _lock(py: Python<'_>) -> PyResult<Py<PyAny>> {
+        Ok(py.import("threading")?.call_method0("RLock")?.unbind())
+    }
+
+    /// The default session, unless it stopped, as PySpark's 
`_get_default_session`.
+    #[staticmethod]
+    #[pyo3(name = "_get_default_session")]
+    fn get_default_session(py: Python<'_>) -> Option<Py<PySparkSession>> {
+        default_session(py)
+    }
+
+    /// The host of the endpoint of the session, as PySpark's 
`SparkConnectClient.host`.
+    fn _endpoint_host(&self) -> String {
+        self.session.host().to_string()
+    }
+
+    /// The server-side session ID that the responses of the session carried, 
or None before the
+    /// first response, as PySpark's `SparkConnectClient._server_session_id`.
+    fn _observed_server_session_id(&self) -> Option<String> {
+        self.session.server_session_id()
+    }
+
+    /// Set the server-side session ID that the session observed, as PySpark's
+    /// `SparkConnectClient._server_session_id` is settable.
+    fn _set_observed_server_session_id(&self, id: Option<String>) {
+        self.session.set_server_session_id(id);
+    }
+
     /// The execution hook base class, reached as `SparkSession.Hook` (mirrors 
pyspark).
     #[classattr]
     #[allow(non_snake_case)]
@@ -3800,3 +4030,44 @@ mod decimal_text_tests {
         }
     }
 }
+
+#[cfg(test)]
+mod connection_url_tests {
+    use super::{quote_param, with_user_id};
+
+    #[test]
+    fn 
a_parameter_value_is_percent_encoded_outside_the_unreserved_characters() {
+        assert_eq!(quote_param("a-b_c.d~e9"), "a-b_c.d~e9");
+        assert_eq!(quote_param("a b;c=d%"), "a%20b%3Bc%3Dd%25");
+    }
+
+    #[test]
+    fn user_id_is_added_to_the_url_unless_it_has_one() {
+        assert_eq!(
+            with_user_id("sc://h", "bob").unwrap(),
+            "sc://h/;user_id=bob"
+        );
+        assert_eq!(
+            with_user_id("sc://h/", "bob").unwrap(),
+            "sc://h/;user_id=bob"
+        );
+        assert_eq!(
+            with_user_id("sc://h/;token=t", "bob").unwrap(),
+            "sc://h/;token=t;user_id=bob"
+        );
+        // The user ID of the connection string takes precedence, as PySpark's 
does.
+        assert_eq!(
+            with_user_id("sc://h/;user_id=ann", "bob").unwrap(),
+            "sc://h/;user_id=ann"
+        );
+    }
+
+    #[test]
+    fn a_user_id_with_separators_reads_back_as_given() {
+        let url = with_user_id("sc://h:114", "a b;c=d").unwrap();
+        let parsed = 
spark_connect_core::channel::ChannelBuilder::parse(&url).unwrap();
+        assert_eq!(parsed.get("user_id"), Some("a b;c=d"));
+        assert_eq!(parsed.host(), "h");
+        assert_eq!(parsed.port(), 114);
+    }
+}
diff --git a/crates/spark-connect-core/src/client.rs 
b/crates/spark-connect-core/src/client.rs
index fca1639a..6ff337b3 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -265,6 +265,8 @@ pub type ExecutePlanHook =
 pub struct SparkConnectClient {
     /// The tonic gRPC channel.
     channel: Channel,
+    /// The display host of the endpoint of the channel, as 
`ChannelBuilder::host`.
+    host: String,
     /// The generated gRPC client stub.
     stub: SparkConnectServiceClient<Channel>,
     /// Session ID (UUID v4) identifying this session on the server.
@@ -403,6 +405,7 @@ impl SparkConnectClient {
 
         Ok(Self {
             channel,
+            host: builder.host().to_string(),
             stub,
             session_id,
             user_id: 
builder.user_id().map(String::from).or_else(default_user_id),
@@ -430,6 +433,7 @@ impl SparkConnectClient {
     pub fn with_new_session_id(&self) -> Self {
         SparkConnectClient {
             channel: self.channel.clone(),
+            host: self.host.clone(),
             stub: self.stub.clone(),
             session_id: Uuid::new_v4().to_string(),
             user_id: self.user_id.clone(),
@@ -471,11 +475,26 @@ impl SparkConnectClient {
         Ok(())
     }
 
-    /// The server-side session ID that the responses have carried, if one has.
-    fn observed_server_session_id(&self) -> Option<String> {
+    /// The server-side session ID that the responses have carried, if one 
has, as PySpark's
+    /// `_server_session_id`: None before the first response.
+    pub fn observed_server_session_id(&self) -> Option<String> {
         observed_of(&self.server_session_id)
     }
 
+    /// Set the server-side session ID that the requests observe, as PySpark's
+    /// `_server_session_id` is settable: a response that carries another one 
closes the client.
+    pub fn set_observed_server_session_id(&self, id: Option<String>) {
+        *self
+            .server_session_id
+            .lock()
+            .unwrap_or_else(|e| e.into_inner()) = id;
+    }
+
+    /// The display host of the endpoint of the channel, as PySpark's 
`SparkConnectClient.host`.
+    pub fn host(&self) -> &str {
+        &self.host
+    }
+
     /// Sets the observed server-side session ID of a request, once a response 
has set it, as
     /// PySpark's requests do.
     fn observe_on(&self, observed: &mut Option<String>) {
@@ -2671,4 +2690,24 @@ mod tests {
         );
         assert_eq!(extension_ids(&client), vec![main, late]);
     }
+
+    #[test]
+    fn host_and_observed_server_session_id_of_the_client() {
+        let client = connect_blocking("sc://Other:114");
+        assert_eq!(client.host(), "other");
+        assert_eq!(client.observed_server_session_id(), None);
+        client.set_observed_server_session_id(Some("server-a".to_string()));
+        assert_eq!(
+            client.observed_server_session_id().as_deref(),
+            Some("server-a")
+        );
+        // The clones of a client share its observed ID, and a client of a new 
session has none.
+        assert_eq!(
+            client.clone().observed_server_session_id().as_deref(),
+            Some("server-a")
+        );
+        let other = client.with_new_session_id();
+        assert_eq!(other.host(), "other");
+        assert_eq!(other.observed_server_session_id(), None);
+    }
 }
diff --git a/crates/spark-connect/src/session.rs 
b/crates/spark-connect/src/session.rs
index f8fc76de..bb250724 100644
--- a/crates/spark-connect/src/session.rs
+++ b/crates/spark-connect/src/session.rs
@@ -893,6 +893,22 @@ impl SparkSession {
         self.client.session_id()
     }
 
+    /// The display host of the endpoint of this session, as PySpark's 
`SparkConnectClient.host`.
+    pub fn host(&self) -> &str {
+        self.client.host()
+    }
+
+    /// The server-side session ID that the responses of this session carried, 
or None before the
+    /// first response, as PySpark's `SparkConnectClient._server_session_id`.
+    pub fn server_session_id(&self) -> Option<String> {
+        self.client.observed_server_session_id()
+    }
+
+    /// Set the server-side session ID that the requests of this session 
observe.
+    pub fn set_server_session_id(&self, id: Option<String>) {
+        self.client.set_observed_server_session_id(id);
+    }
+
     /// Add `extension` to the user context of the requests that the current 
thread sends from
     /// this session, and return its ID. Mirrors PySpark's
     /// `SparkConnectClient.add_threadlocal_user_context_extension`.
@@ -3906,4 +3922,20 @@ mod tests {
         );
         assert!(spark.stopped.load(Ordering::SeqCst));
     }
+
+    #[test]
+    fn host_and_server_session_id_are_the_clients_of_the_session() {
+        let spark = session();
+        assert_eq!(spark.host(), "localhost");
+        assert_eq!(spark.server_session_id(), None);
+        spark.set_server_session_id(Some("server-a".to_string()));
+        assert_eq!(spark.server_session_id().as_deref(), Some("server-a"));
+        // The session is a clone of the same client, which shares the 
observed ID.
+        assert_eq!(
+            spark.clone().server_session_id().as_deref(),
+            Some("server-a")
+        );
+        spark.set_server_session_id(None);
+        assert_eq!(spark.server_session_id(), None);
+    }
 }
diff --git a/dev/parity/known-differences.md b/dev/parity/known-differences.md
index 26fcd152..3fcb44cb 100644
--- a/dev/parity/known-differences.md
+++ b/dev/parity/known-differences.md
@@ -194,3 +194,47 @@ difference is intentional or tracked for a fix.
   by the fixed-hash passes. API inspection records the public-base and
   concrete-class differences; inherited signature and annotation differences 
remain.
   These results do not establish complete DataFrame or ML parity.
+
+## Session and client (Connect)
+
+- **Custom gRPC channels** (intentional; the transport is native). 
`ChannelBuilder` and
+  `DefaultChannelBuilder` parse the connection string and hold its parameters, 
`host`,
+  `port`, `endpoint`, `get`, `set`, `userId`, `token`, `session_id`, 
`use_ssl`, `secure`
+  and `metadata()`. The transport reads them as a `sc://` URL, so they apply. 
The gRPC
+  channel members do not: `toChannel`, `add_interceptor`, `setChannelOption`, 
the
+  keepalive properties and `userAgent`. A `channelOptions` argument raises
+  `NOT_IMPLEMENTED` instead of being ignored. A subclass that overrides 
`userId` or
+  `token` is not read by the transport, which uses the parameters.
+- **Retry and reattach** (intentional; DESIGN). `RpcDeadlines`, 
`client.retries`
+  (`RetryPolicy`, `Retrying`, `DefaultPolicy`, `RetryException`) and 
`client.reattach`
+  are not provided. Retries and reattachment live in the Rust transport, which 
has no
+  policy to configure from Python.
+- **Default port** (intentional). `DefaultChannelBuilder.default_port()` is 
15002. PySpark
+  takes the port of a local JVM server in its testing mode; the drop-in has no 
JVM.
+- **Missing URL error** (intentional). The one builder of the drop-in serves
+  `pyspark.sql.SparkSession.builder` and 
`pyspark.sql.connect.session.SparkSession.builder`.
+  Without a URL or a channel builder it raises `CONNECT_URL_NOT_SET`, which is 
both a
+  `PySparkRuntimeError` (the unified builder) and a `PySparkValueError` (the 
Connect
+  builder's `SESSION_NEED_CONN_STR_OR_BUILDER` family). Giving both a channel 
builder and
+  a URL raises `SESSION_NEED_CONN_STR_OR_BUILDER`. A channel builder without a 
host is
+  rejected at `channelBuilder(...)`, not when the session is created.
+- **Plan logging of a deep DataFrame** (intentional; DESIGN). 
`DataFrame._plan` is a
+  placeholder over the relation of the Rust core, so `_plan.to_proto` is not 
provided.
+  Python protobuf refuses to decode a relation nested beyond its limit (`too 
many levels
+  of nesting`), and the drop-in never decodes a deep plan. 
`SparkConnectClient._proto_to_string`
+  renders any message, including a deep one built in Python, as PySpark's 
does. Plan
+  logging of a deep DataFrame therefore does not reach the recursion handling 
that the
+  test `test_recursion_handling_for_plan_logging` exercises.
+- **Client session ID** (not provided). `SparkConnectClient._session_id` is 
not exposed and
+  is not settable; the session ID belongs to the Rust core. 
`_server_session_id` is
+  exposed and settable, as PySpark's, and a changed value closes the session.
+- **`_closed`** (tracked). Reading `_closed` gives the session's stopped 
state. Setting it
+  to True closes the session, as a test's stand-in for the client's close. 
Setting it to
+  False does not reopen a closed session.
+- **Session registry lock** (intentional). `SparkSession._lock` is a 
`threading.RLock`
+  for the Python code that takes it. The drop-in serializes its own session 
creation with
+  a Rust lock, not with this one.
+- **Direct construction** (intentional). `SparkSession(connection=..., 
userId=...,
+  hook_factories=...)` makes a session that is neither default nor active, as 
PySpark's
+  constructor does. `userId` is added to the URL unless the URL has a 
`user_id`, which
+  takes precedence, as PySpark's does.
diff --git a/python/pyspark/sql/connect/client/__init__.py 
b/python/pyspark/sql/connect/client/__init__.py
index 9bd85ce7..9fb30a07 100644
--- a/python/pyspark/sql/connect/client/__init__.py
+++ b/python/pyspark/sql/connect/client/__init__.py
@@ -18,15 +18,207 @@
 """Compatibility shim for pyspark.sql.connect.client: ``SparkConnectClient``, 
the class of
 ``SparkSession.client``, and related classes."""
 
-__all__ = ["SparkConnectClient"]
+__all__ = ["ChannelBuilder", "DefaultChannelBuilder", "SparkConnectClient"]
 
 
+import copy
+import os
+import sys
+import urllib.parse
+import uuid
 import weakref
-from typing import Any, Dict, List, Mapping, Optional, Tuple
+from typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple
 
+from pyspark.errors import PySparkNotImplementedError, PySparkValueError
 from pyspark.sql.metrics import ObservedMetrics
 
 
+class ChannelBuilder:
+    """The parameters of a Spark Connect connection, as PySpark Connect's 
``ChannelBuilder``:
+    what ``SparkSession.builder.channelBuilder`` and 
``SparkSession(connection=...)`` take. The
+    Rust transport opens the channel of the session from the ``host``, the 
``port`` and the
+    ``_params`` of the builder, as a ``sc://`` connection string, so the 
endpoint and the
+    parameters apply. A custom gRPC channel (``toChannel``), its interceptors 
and its channel
+    options do not: the transport has no gRPC channel to give them to."""
+
+    PARAM_USE_SSL = "use_ssl"
+    PARAM_TOKEN = "token"
+    PARAM_USER_ID = "user_id"
+    PARAM_SESSION_ID = "session_id"
+
+    def __init__(
+        self,
+        channelOptions: Optional[List[Tuple[str, Any]]] = None,
+        params: Optional[Dict[str, str]] = None,
+    ):
+        if channelOptions:
+            raise PySparkNotImplementedError(
+                errorClass="NOT_IMPLEMENTED", messageParameters={"feature": 
"channelOptions"}
+            )
+        self._params: Dict[str, str] = params or dict()
+
+    def get(self, key: str) -> Any:
+        """The value of the parameter ``key``; raises ``KeyError`` if it is 
not set."""
+        return self._params[key]
+
+    def getDefault(self, key: str, default: Any) -> Any:
+        """The value of the parameter ``key``, or ``default`` if it is not 
set."""
+        return self._params.get(key, default)
+
+    def set(self, key: str, value: Any) -> None:
+        """Set the parameter ``key`` to ``value``."""
+        self._params[key] = value
+
+    @property
+    def host(self) -> str:
+        """The hostname where this client intends to connect."""
+        raise PySparkNotImplementedError(
+            errorClass="NOT_IMPLEMENTED", messageParameters={"feature": "host"}
+        )
+
+    @property
+    def userId(self) -> Optional[str]:
+        """The user_id, extracted from the connection string or configured by 
other means."""
+        return self._params.get(ChannelBuilder.PARAM_USER_ID, None)
+
+    @property
+    def token(self) -> Optional[str]:
+        """The authentication token: of the parameters, else of the 
environment variable
+        ``SPARK_CONNECT_AUTHENTICATE_TOKEN``."""
+        return self._params.get(
+            ChannelBuilder.PARAM_TOKEN, 
os.environ.get("SPARK_CONNECT_AUTHENTICATE_TOKEN")
+        )
+
+    @property
+    def session_id(self) -> Optional[str]:
+        """The session_id of the parameters, or None if it is not set."""
+        session_id = self._params.get(ChannelBuilder.PARAM_SESSION_ID, None)
+        if session_id is not None:
+            try:
+                uuid.UUID(session_id, version=4)
+            except ValueError as ve:
+                raise PySparkValueError(
+                    errorClass="INVALID_SESSION_UUID_ID",
+                    messageParameters={"arg_name": "session_id", "origin": 
str(ve)},
+                )
+        return session_id
+
+    def metadata(self) -> Iterable[Tuple[str, str]]:
+        """The parameters that are not used by the channel, as gRPC metadata 
of each request."""
+        reserved = [
+            ChannelBuilder.PARAM_TOKEN,
+            ChannelBuilder.PARAM_USE_SSL,
+            ChannelBuilder.PARAM_USER_ID,
+            "user_agent",
+            ChannelBuilder.PARAM_SESSION_ID,
+            "grpc_keepalive_enabled",
+            "grpc_keepalive_time_ms",
+            "grpc_keepalive_timeout_ms",
+            "grpc_keepalive_without_calls",
+        ]
+        return [(k, self._params[k]) for k in self._params if k not in 
reserved]
+
+
+class DefaultChannelBuilder(ChannelBuilder):
+    """The channel builder of a ``sc://`` connection string, as PySpark 
Connect's
+    ``DefaultChannelBuilder``.
+
+    Examples
+    --------
+    >>> cb = DefaultChannelBuilder("sc://localhost")
+    >>> cb.endpoint
+    'localhost:15002'
+    >>> cb = DefaultChannelBuilder("sc://localhost/;use_ssl=true;token=aaa")
+    >>> cb.secure
+    True
+    """
+
+    @staticmethod
+    def default_port() -> int:
+        # The port of a Spark Connect server, which the drop-in does not 
discover from a local
+        # JVM as PySpark does in the testing mode.
+        return 15002
+
+    def __init__(self, url: str, channelOptions: Optional[List[Tuple[str, 
Any]]] = None) -> None:
+        """Construct a channel builder of the connection string ``url``, such 
as
+        ``sc://hostname:port/;key=value``."""
+        super().__init__(channelOptions=channelOptions)
+
+        # Explicitly check the scheme of the URL.
+        if url[:5] != "sc://":
+            raise PySparkValueError(
+                errorClass="INVALID_CONNECT_URL",
+                messageParameters={
+                    "detail": "The URL must start with 'sc://'. Please update 
the URL to "
+                    "follow the correct format, e.g., 'sc://hostname:port'.",
+                },
+            )
+        # Rewrite the URL to use http as the scheme so that we can leverage 
Python's parser.
+        tmp_url = "http" + url[2:]
+        self.url = urllib.parse.urlparse(tmp_url)
+        if len(self.url.path) > 0 and self.url.path != "/":
+            raise PySparkValueError(
+                errorClass="INVALID_CONNECT_URL",
+                messageParameters={
+                    "detail": f"The path component '{self.url.path}' must be 
empty. Please update "
+                    f"the URL to follow the correct format, e.g., 
'sc://hostname:port'.",
+                },
+            )
+        self._extract_attributes()
+
+    def _extract_attributes(self) -> None:
+        if len(self.url.params) > 0:
+            parts = self.url.params.split(";")
+            for p in parts:
+                kv = p.split("=")
+                if len(kv) != 2:
+                    raise PySparkValueError(
+                        errorClass="INVALID_CONNECT_URL",
+                        messageParameters={
+                            "detail": f"Parameter '{p}' should be provided as 
a "
+                            f"key-value pair separated by an equal sign (=). 
Please update "
+                            f"the parameter to follow the correct format, 
e.g., 'key=value'.",
+                        },
+                    )
+                self.set(kv[0], urllib.parse.unquote(kv[1]))
+
+        if not self.url.hostname:
+            raise PySparkValueError(
+                errorClass="INVALID_CONNECT_URL",
+                messageParameters={
+                    "detail": f"Hostname is missing in the URL: 
'{self.url.geturl()}'. "
+                    "Please update the URL to follow the correct format, "
+                    "e.g., 'sc://hostname:port'.",
+                },
+            )
+        self._host = f"[{self.url.hostname}]" if ":" in self.url.hostname else 
self.url.hostname
+        self._port = self.url.port if self.url.port is not None else 
self.default_port()
+
+    @property
+    def secure(self) -> bool:
+        """Whether the connection is secured: by TLS, or by a token."""
+        return self.use_ssl or self.token is not None
+
+    @property
+    def use_ssl(self) -> bool:
+        return self.getDefault(ChannelBuilder.PARAM_USE_SSL, "").lower() == 
"true"
+
+    @property
+    def host(self) -> str:
+        """The hostname where this client intends to connect."""
+        return self._host
+
+    @property
+    def port(self) -> int:
+        """The port where this client intends to connect."""
+        return self._port
+
+    @property
+    def endpoint(self) -> str:
+        """The ``host:port`` of the connection."""
+        return f"{self._host}:{self._port}"
+
+
 class _UnsupportedLiteral:
     """An observed-metric literal of a kind ``LiteralExpression._to_value`` 
rejects. The
     Rust transport decodes eagerly, so it leaves this marker and ``pairs`` 
raises the
@@ -136,8 +328,32 @@ class SparkConnectClient:
         return _extensions_of(self._session._user_context_extensions(True))
 
     @property
-    def _server_session_id(self) -> str:
-        return self._session.session_id
+    def host(self) -> str:
+        """The hostname where this client intends to connect, as 
SparkConnectClient's ``host``."""
+        return self._session._endpoint_host()
+
+    @property
+    def _server_session_id(self) -> Optional[str]:
+        """The server-side session ID that the responses carried, or None 
before the first
+        response, as SparkConnectClient's. Set it to simulate a server-side 
session change: the
+        next response then closes the client, as a changed ID does."""
+        return self._session._observed_server_session_id()
+
+    @_server_session_id.setter
+    def _server_session_id(self, value: Optional[str]) -> None:
+        self._session._set_observed_server_session_id(value)
+
+    @property
+    def _closed(self) -> bool:
+        """Whether the client is closed, as SparkConnectClient's ``_closed``. 
Setting it to True
+        closes the session, which the session registry then no longer returns; 
a closed client
+        stays closed."""
+        return self._session.is_stopped
+
+    @_closed.setter
+    def _closed(self, value: bool) -> None:
+        if value:
+            self._session._close()
 
     @property
     def is_closed(self) -> bool:
@@ -145,6 +361,69 @@ class SparkConnectClient:
         whether its channel is closed."""
         return self._session.is_stopped
 
+    def _proto_to_string(self, p: Any, truncate: bool = False) -> str:
+        """A one-line string of the protobuf message ``p``, truncated if 
``truncate``, as
+        SparkConnectClient's ``_proto_to_string``, which plan logging uses."""
+        from google.protobuf import text_format
+
+        try:
+            max_level = 8 if truncate else sys.maxsize
+            p2 = self._truncate(p, max_level) if truncate else p
+            return text_format.MessageToString(p2, as_one_line=True)
+        except RecursionError:
+            return "<Truncated message due to recursion error>"
+        except Exception:
+            return "<Truncated message due to truncation error>"
+
+    def _truncate(self, p: Any, allowed_recursion_depth: int) -> Any:
+        """A copy of ``p`` with its nested messages cut at 
``allowed_recursion_depth``, and its
+        long strings and bytes cut, as SparkConnectClient's ``_truncate``."""
+
+        def truncate_str(s: str) -> str:
+            if len(s) > 1024:
+                return s[:1024] + "[truncated]"
+            return s
+
+        def truncate_bytes(b: bytes) -> bytes:
+            if len(b) > 8:
+                return b[:8] + b"[truncated]"
+            return b
+
+        p2 = copy.deepcopy(p)
+
+        for descriptor, value in p.ListFields():
+            if value is not None:
+                field_name = descriptor.name
+
+                if descriptor.type == descriptor.TYPE_MESSAGE:
+                    if allowed_recursion_depth == 0:
+                        p2.ClearField(field_name)
+                    elif descriptor.label == descriptor.LABEL_REPEATED:
+                        p2.ClearField(field_name)
+                        getattr(p2, field_name).extend(
+                            [self._truncate(v, allowed_recursion_depth - 1) 
for v in value]
+                        )
+                    else:
+                        getattr(p2, field_name).CopyFrom(
+                            self._truncate(value, allowed_recursion_depth - 1)
+                        )
+
+                elif descriptor.type == descriptor.TYPE_STRING:
+                    if descriptor.label == descriptor.LABEL_REPEATED:
+                        p2.ClearField(field_name)
+                        getattr(p2, field_name).extend([truncate_str(v) for v 
in value])
+                    else:
+                        setattr(p2, field_name, truncate_str(value))
+
+                elif descriptor.type == descriptor.TYPE_BYTES:
+                    if descriptor.label == descriptor.LABEL_REPEATED:
+                        p2.ClearField(field_name)
+                        getattr(p2, field_name).extend([truncate_bytes(v) for 
v in value])
+                    else:
+                        setattr(p2, field_name, truncate_bytes(value))
+
+        return p2
+
     def get_configs(self, *keys: str) -> Tuple[Optional[str], ...]:
         """The values of the configurations ``keys``, in one request, as 
SparkConnectClient's
         ``get_configs``."""
diff --git a/python/pyspark/sql/connect/session.py 
b/python/pyspark/sql/connect/session.py
index 0403bf17..423b7cdb 100644
--- a/python/pyspark/sql/connect/session.py
+++ b/python/pyspark/sql/connect/session.py
@@ -17,11 +17,24 @@
 """Rust-backed SparkSession under the connect import path 
(testing/connectutils imports from here)."""
 from typing import Callable, Tuple
 
+from pyspark.errors import PySparkRuntimeError, PySparkValueError
 from pyspark.sql.session import SparkSession
 
 __all__ = ["SparkSession"]
 
 
+class _ConnectUrlNotSetError(PySparkRuntimeError, PySparkValueError):
+    """``CONNECT_URL_NOT_SET``, which the one builder of the drop-in raises 
when neither a URL
+    nor a channel builder is given. PySpark raises it as a RuntimeError from 
its builder, and
+    as a ValueError (``SESSION_NEED_CONN_STR_OR_BUILDER``) from the Connect 
builder: this is both,
+    so that either is caught."""
+
+
+def _connect_url_not_set_error() -> Exception:
+    """The ``CONNECT_URL_NOT_SET`` error of the builder, see 
``_ConnectUrlNotSetError``."""
+    return _ConnectUrlNotSetError(errorClass="CONNECT_URL_NOT_SET", 
messageParameters={})
+
+
 def _reduce_session(session_id: str) -> Tuple[Callable[[str], "SparkSession"], 
Tuple[str]]:
     """The ``__reduce__`` of the session of ``session_id``, as PySpark 
Connect's: a function,
     which cloudpickle pickles by value, that gives back the active session of 
that ID. It reads
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 3883736d..2dbb346c 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -270,6 +270,34 @@ def 
test_repr_shows_the_rows_with_eager_evaluation_as_pyspark(session):
     assert repr(df) == "DataFrame[id: bigint]"
 
 
+def 
test_server_session_id_is_observed_and_a_changed_one_closes_the_session_as_pyspark():
+    # SparkConnectClient._server_session_id: None before the first response, 
then the server's
+    # ID; a changed one makes the next response close the client, as a 
server-side change does.
+    import uuid
+
+    from pyspark.errors.exceptions.connect import SparkConnectException
+    from pyspark.sql.connect.session import SparkSession as ConnectSession
+
+    remote = os.environ.get("SPARK_REMOTE")
+    if not remote:
+        pytest.skip("SPARK_REMOTE is required for live-server tests")
+    session = ConnectSession(connection=remote)
+    try:
+        assert session._client._server_session_id is None
+        assert session.range(3).count() == 3
+        assert session._client._server_session_id
+        assert not session.is_stopped
+
+        session._client._server_session_id = str(uuid.uuid4())
+        with pytest.raises(SparkConnectException) as error:
+            session.range(3).collect()
+        assert "SESSION_CHANGED" in str(error.value)
+        assert session.is_stopped
+    finally:
+        session.release_session_on_close = False
+        session.stop()
+
+
 def 
test_udtfs_and_udfs_of_a_dataframe_or_the_session_raise_no_active_session_as_pyspark(session):
     # As PySpark Connect's: a UDTF or a UDF that captures a DataFrame or the 
session pickles it
     # of its session, which raises NO_ACTIVE_SESSION on the Python worker of 
the server, where
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 8d7fb8ad..ad20a874 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -2144,6 +2144,176 @@ def 
test_udf_and_udtf_calls_pass_named_arguments_as_pyspark(mock_connect):
     assert parse_message(first[2][0])[1] == [b"x"] and key == "b" and 
set(value) == {1}
 
 
+def 
test_channel_builder_parses_the_connection_string_and_the_session_honors_it_as_pyspark():
+    # ChannelBuilder and DefaultChannelBuilder of pyspark.sql.connect.client, 
as PySpark's: the
+    # endpoint and the parameters of a sc:// URL, which channelBuilder hands 
to the transport.
+    from pyspark.errors import PySparkValueError
+    from pyspark.sql.connect.client import ChannelBuilder, 
DefaultChannelBuilder
+
+    builder = DefaultChannelBuilder("sc://Other:114/;token=abc;user_id=bob")
+    assert isinstance(builder, ChannelBuilder)
+    assert (builder.host, builder.port, builder.endpoint) == ("other", 114, 
"other:114")
+    assert builder._params == {"token": "abc", "user_id": "bob"}
+    assert builder.get("token") == "abc" and builder.getDefault("missing", 1) 
== 1
+    assert builder.userId == "bob"
+    assert builder.secure and not builder.use_ssl
+    assert list(builder.metadata()) == []
+    builder.set("x-custom", "1")
+    assert list(builder.metadata()) == [("x-custom", "1")]
+    with pytest.raises(PySparkValueError) as error:
+        DefaultChannelBuilder("http://other";)
+    assert error.value.getCondition() == "INVALID_CONNECT_URL"
+
+    session = 
SparkSession.builder.channelBuilder(DefaultChannelBuilder("sc://other:114")).create()
+    try:
+        assert session.client.host == "other"
+        assert session.client._server_session_id is None
+    finally:
+        session.release_session_on_close = False
+        session.stop()
+
+
+def test_session_constructor_and_its_flags_as_pyspark_connect():
+    import threading
+
+    from pyspark.sql.connect.client import DefaultChannelBuilder
+    from pyspark.sql.connect.session import SparkSession as ConnectSession
+
+    shared = SparkSession.getActiveSession()
+    session = ConnectSession(connection="sc://other:114", userId="alice")
+    other = ConnectSession(connection=DefaultChannelBuilder("sc://other:115"))
+    try:
+        # The constructor makes a session of its own: neither the default nor 
the active one.
+        assert session is not SparkSession.getActiveSession()
+        assert ConnectSession._default_session is not session
+        assert session.release_session_on_close is True
+        assert session.client.host == "other" and other.client.host == "other"
+        assert other.is_stopped is False
+        # The session of a DataFrame is the object of the session, as the 
other sessions are.
+        assert other.range(2).sparkSession is other
+        assert SparkSession.getActiveSession() is shared
+        # A stopped session is not the default one, and the lock is an RLock.
+        assert isinstance(ConnectSession._lock, type(threading.RLock()))
+    finally:
+        for s in (session, other):
+            s.release_session_on_close = False
+            s.stop()
+    assert session.is_stopped and other.is_stopped
+
+
+def 
test_session_registry_is_the_class_attributes_of_the_connect_session_as_pyspark():
+    from pyspark.sql.connect.session import SparkSession as ConnectSession
+
+    saved_default = ConnectSession._default_session
+    saved_active = ConnectSession._active_session.session
+    try:
+        ConnectSession._default_session = None
+        ConnectSession._active_session.session = None
+        assert ConnectSession._get_default_session() is None
+        assert ConnectSession.getActiveSession() is None
+
+        session = ConnectSession.builder.remote("sc://other:114").create()
+        assert ConnectSession._default_session is session
+        assert ConnectSession._get_default_session() is session
+        assert ConnectSession._active_session.session is session
+        assert ConnectSession.getActiveSession() is session
+        assert ConnectSession.builder.remote("sc://other:114").getOrCreate() 
is session
+
+        # Setting the attribute changes the registry, as in PySpark: the 
default session of
+        # the thread is cleared, so the next getOrCreate makes a session.
+        ConnectSession._active_session.session = None
+        assert ConnectSession.getActiveSession() is None
+        assert ConnectSession.active() is session
+
+        session.release_session_on_close = False
+        session.stop()
+        assert ConnectSession._default_session is None
+        assert ConnectSession._get_default_session() is None
+    finally:
+        ConnectSession._default_session = saved_default
+        ConnectSession._active_session.session = saved_active
+
+
+def test_connect_builder_errors_as_pyspark_connect(monkeypatch):
+    from pyspark.errors import PySparkValueError
+    from pyspark.sql.connect.client import DefaultChannelBuilder
+    from pyspark.sql.connect.session import SparkSession as ConnectSession
+
+    monkeypatch.delenv("SPARK_REMOTE", raising=False)
+    # A channel builder and a URL are mutually exclusive, whatever the order.
+    with pytest.raises(PySparkValueError) as error:
+        builder = 
ConnectSession.builder.channelBuilder(DefaultChannelBuilder("sc://a"))
+        builder.remote("sc://b").create()
+    assert error.value.getCondition() == "SESSION_NEED_CONN_STR_OR_BUILDER"
+    with pytest.raises(PySparkValueError):
+        builder = ConnectSession.builder.remote("sc://b")
+        builder.channelBuilder(DefaultChannelBuilder("sc://a")).create()
+    # Neither is: a ValueError as PySpark Connect's builder, and 
CONNECT_URL_NOT_SET as the
+    # RuntimeError of the builder of pyspark.sql, which is the same class here.
+    with pytest.raises(ValueError) as error:
+        ConnectSession.builder.create()
+    assert isinstance(error.value, RuntimeError)
+    assert error.value.getCondition() == "CONNECT_URL_NOT_SET"
+    # A session of a channel builder, not the URL of SPARK_REMOTE, is what 
PySpark connects.
+    monkeypatch.setenv("SPARK_REMOTE", "sc://elsewhere:1")
+    builder = 
ConnectSession.builder.channelBuilder(DefaultChannelBuilder("sc://other:114"))
+    session = builder.create()
+    try:
+        assert session.client.host == "other"
+    finally:
+        session.release_session_on_close = False
+        session.stop()
+
+
+def 
test_stop_releases_the_session_on_the_server_unless_released_on_close_is_false(mock_connect):
+    from pyspark.sql.connect.session import SparkSession as ConnectSession
+
+    spark, service = mock_connect
+    before = service.release_session_calls
+    session = ConnectSession(connection=service.remote)
+    session.release_session_on_close = False
+    session.stop()
+    assert session.is_stopped
+    assert service.release_session_calls == before
+
+    session = ConnectSession(connection=service.remote)
+    session.stop()
+    assert session.is_stopped
+    assert service.release_session_calls == before + 1
+    session.stop()
+    assert service.release_session_calls == before + 1
+
+
+def test_plan_logging_string_of_a_protobuf_message_as_pyspark_connect():
+    # SparkConnectClient._proto_to_string: the one-line text of a plan, 
truncated when asked,
+    # and the placeholder of a message too deep for text formatting.
+    import pyspark.sql.connect.proto as pb2
+    from pyspark.sql.connect.client import SparkConnectClient
+
+    class Session:
+        session_id = "x"
+
+    client = SparkConnectClient(Session())
+    relation = pb2.Relation()
+    relation.sql.query = "q" * 2000
+    text = client._proto_to_string(relation, True)
+    try:
+        # PySpark's truncation reads FieldDescriptor.label, which protobuf 7 
no longer has.
+        relation.DESCRIPTOR.fields_by_name["sql"].label
+    except Exception:
+        assert text == "<Truncated message due to truncation error>"
+    else:
+        assert "[truncated]" in text and "q" * 1100 not in text
+    assert "q" * 2000 in client._proto_to_string(relation)
+
+    deep = pb2.Relation()
+    node = deep
+    for _ in range(400):
+        node.project.input.SetInParent()
+        node = node.project.input
+    assert "recursion" in client._proto_to_string(deep)
+
+
 def 
test_subqueries_are_sent_with_the_plans_they_refer_to_as_pyspark(mock_connect):
     # As PySpark's DataFrame.scalar(), DataFrame.exists() and Column.isin(df): 
Columns of
     # SubqueryExpressions of the plan of the DataFrame, sent in a 
WithRelations of the plans
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index a5c79f64..f6102c7e 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -632,11 +632,16 @@ def 
test_ml_session_client_is_one_object_of_the_session(ml_mock):
     client = spark.client
     assert isinstance(client, SparkConnectClient)
     assert spark.client is client
-    assert client._server_session_id == spark.session_id
+    # The server-side session ID is None until a response carries one, as 
PySpark's is, and
+    # it is settable, as PySpark's tests set it.
+    assert client._server_session_id is None
+    client._server_session_id = "srv-A"
+    assert client._server_session_id == "srv-A"
+    client._server_session_id = None
     other = SparkSession.builder.remote(service.remote).create()
     try:
         assert other.client is not client
-        assert other.client._server_session_id == other.session_id
+        assert other.client._server_session_id is None
     finally:
         other.stop()
 


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

Reply via email to