HyukjinKwon commented on code in PR #870:
URL: 
https://github.com/apache/spark-connect-rust/pull/870#discussion_r4635690004


##########
crates/spark-connect-server/src/service.rs:
##########
@@ -0,0 +1,1205 @@
+// 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.
+
+use std::collections::{HashMap, VecDeque};
+use std::panic::AssertUnwindSafe;
+use std::pin::Pin;
+use std::sync::{Arc, Mutex};
+
+use arrow::datatypes::{Schema, SchemaRef};
+use arrow::ipc::{reader::StreamReader, writer::StreamWriter};
+use arrow::record_batch::RecordBatch;
+use futures::{FutureExt, Stream, StreamExt};
+use prost::Message;
+use spark_connect_proto as proto;
+use tokio::sync::{mpsc, watch};
+use tokio_stream::wrappers::ReceiverStream;
+use tonic::{Request, Response, Status};
+use uuid::Uuid;
+
+use crate::engine::{Engine, EngineSession, PreparedOperation, ResultBatch, 
SessionContext};
+use crate::grpc::spark_connect_service_server::SparkConnectService;
+use crate::schema::{self, result_schema, MAX_METADATA_RESPONSE_BYTES};
+
+type Output = Pin<Box<dyn Stream<Item = Result<proto::ExecutePlanResponse, 
Status>> + Send>>;
+type SessionKey = (String, String);
+const MAX_RELEASED_SESSIONS: usize = 4096;
+const RELEASE_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
+
+fn parse_uuid(value: &str, name: &str) -> Result<Uuid, Status> {
+    crate::ids::parse_uuid(value)
+        .ok_or_else(|| Status::invalid_argument(format!("invalid UUID in 
{name}")))
+}
+
+async fn catch_engine_panic<T: Send>(
+    action: impl std::future::Future<Output = Result<T, Status>> + Send,
+) -> Result<T, Status> {
+    AssertUnwindSafe(action)
+        .catch_unwind()
+        .await
+        .unwrap_or_else(|_| Err(Status::internal("engine request panicked")))
+}
+
+struct Session {
+    id: String,
+    backend: Arc<dyn EngineSession>,
+    cancelled: watch::Sender<bool>,
+    operations: Mutex<HashMap<String, Arc<Operation>>>,
+}
+
+struct Operation {
+    cancelled: watch::Sender<bool>,
+    done: watch::Sender<bool>,
+}
+
+impl Session {
+    fn new(backend: Arc<dyn EngineSession>) -> Self {
+        Self {
+            id: Uuid::new_v4().to_string(),
+            backend,
+            cancelled: watch::channel(false).0,
+            operations: Mutex::new(HashMap::new()),
+        }
+    }
+
+    async fn while_open<T: Send>(
+        &self,
+        action: impl std::future::Future<Output = Result<T, Status>> + Send,
+    ) -> Result<T, Status> {
+        let mut cancelled = self.cancelled.subscribe();
+        if *cancelled.borrow() {
+            return Err(Status::cancelled("session released"));
+        }
+        tokio::select! {
+            biased;
+            _ = cancelled.changed() => Err(Status::cancelled("session 
released")),
+            result = action => result,
+        }
+    }
+
+    fn operation(
+        self: &Arc<Self>,
+        id: &str,
+    ) -> Result<(Arc<OperationGuard>, watch::Receiver<bool>), Status> {
+        // Subscribe before publishing: ReleaseAll can cancel as soon as the
+        // operation appears in the registry, before preparation is first 
polled.
+        let (cancelled, cancellation) = watch::channel(false);
+        let running = Arc::new(Operation {
+            cancelled,
+            done: watch::channel(false).0,
+        });
+        let mut operations = self
+            .operations
+            .lock()
+            .unwrap_or_else(std::sync::PoisonError::into_inner);
+        if operations.contains_key(id) {
+            return Err(Status::already_exists("operation is already running"));
+        }
+        operations.insert(id.to_owned(), running.clone());
+        Ok((
+            Arc::new(OperationGuard {
+                session: self.clone(),
+                id: id.to_owned(),
+                running,
+            }),
+            cancellation,
+        ))
+    }
+}
+
+// This guard spans preparation and execution, including eager commands. Drop 
the
+// backend future/stream before the guard so ReleaseAll observes completed 
teardown.
+struct OperationGuard {
+    session: Arc<Session>,
+    id: String,
+    running: Arc<Operation>,
+}
+
+impl Drop for OperationGuard {
+    fn drop(&mut self) {
+        self.session
+            .operations
+            .lock()
+            .unwrap_or_else(std::sync::PoisonError::into_inner)
+            .remove(&self.id);
+        self.running.done.send_replace(true);
+    }
+}
+
+#[derive(Default)]
+struct SessionRegistry {
+    // None is a recently released-session tombstone, retained until eviction.
+    entries: HashMap<SessionKey, Option<Arc<Session>>>,
+    // Remember the most recent distinct closed IDs in release order. Repeated
+    // releases do not refresh retention. After eviction, an old ID may create 
a
+    // fresh session; active sessions never count toward this finite budget.
+    released: VecDeque<SessionKey>,
+}
+
+impl SessionRegistry {
+    fn release(&mut self, key: SessionKey, allow_reconnect: bool) -> 
Option<Arc<Session>> {
+        // Releasing a missing or already closed session is a no-op. In
+        // particular, a later reconnecting release cannot erase a tombstone.
+        let session = self.entries.get_mut(&key)?.take()?;
+        if allow_reconnect {
+            self.entries.remove(&key);
+        } else {
+            self.released.push_back(key);
+            if self.released.len() > MAX_RELEASED_SESSIONS {
+                if let Some(oldest) = self.released.pop_front() {
+                    self.entries.remove(&oldest);
+                }
+            }
+        }
+        Some(session)
+    }
+}
+
+pub(crate) struct ConnectService {
+    engine: Arc<dyn Engine>,
+    options: crate::ServerOptions,
+    sessions: Mutex<SessionRegistry>,
+    closing: std::sync::atomic::AtomicBool,
+}
+
+impl ConnectService {
+    pub(crate) fn new(engine: Arc<dyn Engine>, options: crate::ServerOptions) 
-> Self {
+        Self {
+            engine,
+            options,
+            sessions: Mutex::new(SessionRegistry::default()),
+            closing: std::sync::atomic::AtomicBool::new(false),
+        }
+    }
+
+    fn key(id: &str, user: Option<&proto::UserContext>) -> SessionKey {
+        (
+            user.map(|u| u.user_id.clone()).unwrap_or_default(),
+            id.into(),
+        )
+    }
+
+    fn session(
+        &self,
+        id: &str,
+        user: Option<&proto::UserContext>,
+        observed: Option<&str>,
+    ) -> Result<Arc<Session>, Status> {
+        self.find_session(id, user, observed, true)
+    }
+
+    fn find_session(
+        &self,
+        id: &str,
+        user: Option<&proto::UserContext>,
+        observed: Option<&str>,
+        create: bool,
+    ) -> Result<Arc<Session>, Status> {
+        if create {
+            parse_uuid(id, "session_id")?;
+        }
+        let key = Self::key(id, user);
+        let mut sessions = self
+            .sessions
+            .lock()
+            .unwrap_or_else(std::sync::PoisonError::into_inner);
+        if self.closing.load(std::sync::atomic::Ordering::SeqCst) {
+            return Err(Status::unavailable("server is shutting down"));
+        }
+        let session = match sessions.entries.get(&key) {
+            Some(Some(session)) => session.clone(),
+            Some(None) => return Err(Status::failed_precondition("session was 
released")),
+            None if !create => return Err(Status::not_found("session does not 
exist")),
+            // An observed ID refers to a previous incarnation; a new session
+            // cannot satisfy it. Reject before allocating backend resources.
+            None if observed.is_some() => {
+                return Err(Status::failed_precondition(
+                    "server-side session ID changed",
+                ));
+            }
+            None => {
+                let backend = self.engine.create_session(SessionContext {
+                    session_id: id.to_owned(),
+                    user_context: user.cloned(),
+                })?;
+                let session = Arc::new(Session::new(backend));
+                sessions.entries.insert(key, Some(session.clone()));
+                session
+            }
+        };
+        if observed.is_some_and(|id| id != session.id) {
+            return Err(Status::failed_precondition(
+                "server-side session ID changed",
+            ));
+        }
+        Ok(session)
+    }
+
+    pub(crate) fn cancel_all(&self) {
+        self.closing
+            .store(true, std::sync::atomic::Ordering::SeqCst);
+        // Stalled HTTP/2 connections can retain the service after the bounded
+        // transport drain. Remove its registry ownership now so backend 
sessions
+        // can close once their cancelled operations finish.
+        let sessions = std::mem::take(
+            &mut *self
+                .sessions
+                .lock()
+                .unwrap_or_else(std::sync::PoisonError::into_inner),
+        );
+        for session in sessions.entries.into_values().flatten() {
+            session.cancelled.send_replace(true);
+        }
+    }
+}
+
+fn response(
+    session_id: &str,
+    session: &Session,
+    operation_id: &str,
+    response_type: Option<proto::execute_plan_response::ResponseType>,
+) -> proto::ExecutePlanResponse {
+    proto::ExecutePlanResponse {
+        session_id: session_id.into(),
+        server_side_session_id: session.id.clone(),
+        operation_id: operation_id.into(),
+        response_id: Uuid::new_v4().to_string(),
+        response_type,
+        ..Default::default()
+    }
+}
+
+fn checked_response(
+    message: proto::ExecutePlanResponse,
+) -> Result<proto::ExecutePlanResponse, Status> {
+    if message.encoded_len() > MAX_METADATA_RESPONSE_BYTES {
+        return Err(Status::resource_exhausted(
+            "schema/command response exceeds the 3 MiB limit",
+        ));
+    }
+    Ok(message)
+}
+
+fn complete(id: &str, session: &Session, operation: &str) -> 
proto::ExecutePlanResponse {
+    response(
+        id,
+        session,
+        operation,
+        Some(proto::execute_plan_response::ResponseType::ResultComplete(
+            proto::execute_plan_response::ResultComplete {},
+        )),
+    )
+}
+
+fn encode_batch(batch: &RecordBatch) -> Result<(Vec<u8>, SchemaRef), Status> {
+    use arrow::datatypes::DataType;
+    use arrow::record_batch::RecordBatchOptions;
+
+    // Materialize view arrays, including nested children, into the 
large-offset
+    // string/binary representation used for encoded RecordBatch results.
+    let source_schema = batch.schema();
+    let fields = schema::map_fields(source_schema.fields(), &|field, 
data_type| {
+        let data_type = match data_type {
+            DataType::Utf8View => DataType::LargeUtf8,
+            DataType::BinaryView => DataType::LargeBinary,
+            other => other,
+        };
+        if data_type == *field.data_type() {
+            field.clone()
+        } else {
+            Arc::new(field.as_ref().clone().with_data_type(data_type))
+        }
+    });
+    let changed = fields
+        .iter()
+        .zip(source_schema.fields())
+        .any(|(target, source)| target.data_type() != source.data_type());
+    let materialized = if changed {
+        let columns = batch
+            .columns()
+            .iter()
+            .zip(&fields)
+            .map(|(column, field)| {
+                if column.data_type() == field.data_type() {
+                    Ok(column.clone())
+                } else {
+                    arrow::compute::cast(column.as_ref(), field.data_type())
+                }
+            })
+            .collect::<Result<Vec<_>, _>>()
+            .map_err(|error| Status::internal(error.to_string()))?;
+        let target_schema = Arc::new(Schema::new_with_metadata(
+            fields,
+            source_schema.metadata().clone(),
+        ));
+        Some(
+            RecordBatch::try_new_with_options(
+                target_schema,
+                columns,
+                
&RecordBatchOptions::new().with_row_count(Some(batch.num_rows())),
+            )
+            .map_err(|error| Status::internal(error.to_string()))?,
+        )
+    } else {
+        None
+    };
+    let batch = materialized.as_ref().unwrap_or(batch);
+    let mut bytes = Vec::new();
+    {
+        let mut writer = StreamWriter::try_new(&mut bytes, 
batch.schema().as_ref())
+            .map_err(|e| Status::internal(e.to_string()))?;
+        writer
+            .write(batch)
+            .map_err(|e| Status::internal(e.to_string()))?;
+        writer
+            .finish()
+            .map_err(|e| Status::internal(e.to_string()))?;
+    }
+    Ok((bytes, batch.schema()))
+}
+
+// PySpark assembles one table from all IPC batches. Its physical types and
+// nullability must agree across batches, while field/schema metadata may 
differ.
+fn check_output_schema(schema: &Schema, expected: &mut Option<Schema>) -> 
Result<(), Status> {
+    use arrow::datatypes::Field;
+
+    let actual = Schema::new(schema::map_fields(schema.fields(), &|field, 
data_type| {
+        Arc::new(Field::new(field.name(), data_type, field.is_nullable()))
+    }));
+    match expected {
+        Some(expected) if *expected != actual => Err(Status::internal(
+            "Arrow output schema changed within one result",
+        )),
+        Some(_) => Ok(()),
+        None => {
+            *expected = Some(actual);
+            Ok(())
+        }
+    }
+}
+
+// Keep backend ownership until the batch is dropped, including on encoder 
panic.
+struct EncodingBatch {
+    batch: RecordBatch,
+    _guard: Arc<OperationGuard>,
+}
+
+impl EncodingBatch {
+    fn encode(self) -> Result<(Vec<u8>, SchemaRef), Status> {
+        encode_batch(&self.batch)
+    }
+}
+
+fn arrow_chunk_size(
+    options: &[proto::execute_plan_request::RequestOption],
+    maximum: usize,
+) -> Option<usize> {
+    use proto::execute_plan_request::request_option::RequestOption;
+
+    let mut chunking = options
+        .iter()
+        .filter_map(|option| match &option.request_option {
+            Some(RequestOption::ResultChunkingOptions(options)) => 
Some(options),
+            _ => None,
+        });
+    if maximum == 0
+        || !chunking
+            .clone()
+            .any(|options| options.allow_arrow_batch_chunking)
+    {
+        return None;
+    }
+    Some(
+        chunking
+            .find_map(|options| options.preferred_arrow_chunk_size)
+            // Validate i64 directly; Scala's toInt can wrap an invalid 
preference.
+            .and_then(|bytes| usize::try_from(bytes).ok())
+            .filter(|bytes| (1024..=maximum).contains(bytes))
+            .unwrap_or(maximum),
+    )
+}
+
+async fn send_batch(
+    sender: &mpsc::Sender<Result<proto::ExecutePlanResponse, Status>>,
+    id: &str,
+    operation: &str,
+    batch: ResultBatch,
+    batch_schema: &Schema,
+    offset: &mut i64,
+    output_schema: &mut Option<Schema>,
+    guard: &Arc<OperationGuard>,
+    chunk_size: Option<usize>,
+) -> Result<bool, Status> {
+    // Reject unrepresentable counts/offsets before encoding or sending any 
chunk.
+    let row_count = match &batch {
+        ResultBatch::Arrow(batch) => i64::try_from(batch.num_rows())
+            .map_err(|_| Status::resource_exhausted("result batch row count 
exceeds i64"))?,
+        ResultBatch::Ipc { row_count, .. } if *row_count < 0 => {
+            return Err(Status::internal("negative engine IPC row count"));
+        }
+        ResultBatch::Ipc { row_count, .. } => *row_count,
+    };
+    let next_offset = offset
+        .checked_add(row_count)
+        .ok_or_else(|| Status::resource_exhausted("result row offset exceeds 
i64"))?;
+    let data: prost::bytes::Bytes = match batch {
+        ResultBatch::Arrow(batch) => {
+            // A blocking encoder cannot be cancelled once started. Retain 
engine
+            // ownership until its batch is dropped, even if the caller goes 
away.
+            let encoding = EncodingBatch {
+                batch,
+                _guard: guard.clone(),
+            };
+            let (data, schema) = tokio::task::spawn_blocking(move || 
encoding.encode())
+                .await
+                .map_err(|_| Status::internal("Arrow result encoding task 
failed"))??;
+            check_output_schema(schema.as_ref(), output_schema)?;

Review Comment:
   **Nit (P3):** This check runs after `encode_batch` has turned 
`Utf8View`/`BinaryView` into `LargeUtf8`/`LargeBinary`, while the IPC branch at 
line 474 checks the producer's raw schema. That ordering is what lets a 
`Utf8View` record batch followed by `LargeUtf8` IPC succeed, and makes a 
`Utf8View` record batch followed by `Utf8View` IPC fail. No test exercises the 
mix: schema_consistency.rs only has record-batch-only and IPC-only results, and 
the protocol.rs view-slice cases send slices of one batch. By our reading of 
the code, if this check moved before encoding, or IPC were materialized before 
its check, the first mix would be rejected after one batch was streamed and the 
second would send `LargeUtf8` then `Utf8View` batches that a client cannot 
concatenate, with no test failing. A schema_consistency.rs case covering both 
mixes, plus a `Utf8View` record batch followed by a `LargeUtf8` record batch, 
would pin the ordering.
   
   **Verification:**
   - **Behavior:** Executing a result that mixes a Utf8View record batch with 
LargeUtf8 IPC, and another that mixes a Utf8View record batch with a LargeUtf8 
record batch, delivers every batch, the batches decode to the same LargeUtf8 
schema, and ResultComplete follows them.
   - **Regression:** Executing a result that mixes a Utf8View record batch with 
Utf8View IPC returns the INTERNAL schema-change status after exactly one 
delivered batch; the new tests fail if the output check uses a record batch's 
schema before materialization or materializes IPC.



##########
crates/spark-connect-server/src/service.rs:
##########
@@ -0,0 +1,1205 @@
+// 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.
+
+use std::collections::{HashMap, VecDeque};
+use std::panic::AssertUnwindSafe;
+use std::pin::Pin;
+use std::sync::{Arc, Mutex};
+
+use arrow::datatypes::{Schema, SchemaRef};
+use arrow::ipc::{reader::StreamReader, writer::StreamWriter};
+use arrow::record_batch::RecordBatch;
+use futures::{FutureExt, Stream, StreamExt};
+use prost::Message;
+use spark_connect_proto as proto;
+use tokio::sync::{mpsc, watch};
+use tokio_stream::wrappers::ReceiverStream;
+use tonic::{Request, Response, Status};
+use uuid::Uuid;
+
+use crate::engine::{Engine, EngineSession, PreparedOperation, ResultBatch, 
SessionContext};
+use crate::grpc::spark_connect_service_server::SparkConnectService;
+use crate::schema::{self, result_schema, MAX_METADATA_RESPONSE_BYTES};
+
+type Output = Pin<Box<dyn Stream<Item = Result<proto::ExecutePlanResponse, 
Status>> + Send>>;
+type SessionKey = (String, String);
+const MAX_RELEASED_SESSIONS: usize = 4096;
+const RELEASE_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
+
+fn parse_uuid(value: &str, name: &str) -> Result<Uuid, Status> {
+    crate::ids::parse_uuid(value)
+        .ok_or_else(|| Status::invalid_argument(format!("invalid UUID in 
{name}")))
+}
+
+async fn catch_engine_panic<T: Send>(
+    action: impl std::future::Future<Output = Result<T, Status>> + Send,
+) -> Result<T, Status> {
+    AssertUnwindSafe(action)
+        .catch_unwind()
+        .await
+        .unwrap_or_else(|_| Err(Status::internal("engine request panicked")))
+}
+
+struct Session {
+    id: String,
+    backend: Arc<dyn EngineSession>,
+    cancelled: watch::Sender<bool>,
+    operations: Mutex<HashMap<String, Arc<Operation>>>,
+}
+
+struct Operation {
+    cancelled: watch::Sender<bool>,
+    done: watch::Sender<bool>,
+}
+
+impl Session {
+    fn new(backend: Arc<dyn EngineSession>) -> Self {
+        Self {
+            id: Uuid::new_v4().to_string(),
+            backend,
+            cancelled: watch::channel(false).0,
+            operations: Mutex::new(HashMap::new()),
+        }
+    }
+
+    async fn while_open<T: Send>(
+        &self,
+        action: impl std::future::Future<Output = Result<T, Status>> + Send,
+    ) -> Result<T, Status> {
+        let mut cancelled = self.cancelled.subscribe();
+        if *cancelled.borrow() {
+            return Err(Status::cancelled("session released"));
+        }
+        tokio::select! {
+            biased;
+            _ = cancelled.changed() => Err(Status::cancelled("session 
released")),
+            result = action => result,
+        }
+    }
+
+    fn operation(
+        self: &Arc<Self>,
+        id: &str,
+    ) -> Result<(Arc<OperationGuard>, watch::Receiver<bool>), Status> {
+        // Subscribe before publishing: ReleaseAll can cancel as soon as the
+        // operation appears in the registry, before preparation is first 
polled.
+        let (cancelled, cancellation) = watch::channel(false);
+        let running = Arc::new(Operation {
+            cancelled,
+            done: watch::channel(false).0,
+        });
+        let mut operations = self
+            .operations
+            .lock()
+            .unwrap_or_else(std::sync::PoisonError::into_inner);
+        if operations.contains_key(id) {
+            return Err(Status::already_exists("operation is already running"));
+        }
+        operations.insert(id.to_owned(), running.clone());
+        Ok((
+            Arc::new(OperationGuard {
+                session: self.clone(),
+                id: id.to_owned(),
+                running,
+            }),
+            cancellation,
+        ))
+    }
+}
+
+// This guard spans preparation and execution, including eager commands. Drop 
the
+// backend future/stream before the guard so ReleaseAll observes completed 
teardown.
+struct OperationGuard {
+    session: Arc<Session>,
+    id: String,
+    running: Arc<Operation>,
+}
+
+impl Drop for OperationGuard {
+    fn drop(&mut self) {
+        self.session
+            .operations
+            .lock()
+            .unwrap_or_else(std::sync::PoisonError::into_inner)
+            .remove(&self.id);
+        self.running.done.send_replace(true);
+    }
+}
+
+#[derive(Default)]
+struct SessionRegistry {
+    // None is a recently released-session tombstone, retained until eviction.
+    entries: HashMap<SessionKey, Option<Arc<Session>>>,
+    // Remember the most recent distinct closed IDs in release order. Repeated
+    // releases do not refresh retention. After eviction, an old ID may create 
a
+    // fresh session; active sessions never count toward this finite budget.
+    released: VecDeque<SessionKey>,
+}
+
+impl SessionRegistry {
+    fn release(&mut self, key: SessionKey, allow_reconnect: bool) -> 
Option<Arc<Session>> {
+        // Releasing a missing or already closed session is a no-op. In
+        // particular, a later reconnecting release cannot erase a tombstone.
+        let session = self.entries.get_mut(&key)?.take()?;
+        if allow_reconnect {
+            self.entries.remove(&key);
+        } else {
+            self.released.push_back(key);
+            if self.released.len() > MAX_RELEASED_SESSIONS {
+                if let Some(oldest) = self.released.pop_front() {
+                    self.entries.remove(&oldest);
+                }
+            }
+        }
+        Some(session)
+    }
+}
+
+pub(crate) struct ConnectService {
+    engine: Arc<dyn Engine>,
+    options: crate::ServerOptions,
+    sessions: Mutex<SessionRegistry>,
+    closing: std::sync::atomic::AtomicBool,
+}
+
+impl ConnectService {
+    pub(crate) fn new(engine: Arc<dyn Engine>, options: crate::ServerOptions) 
-> Self {
+        Self {
+            engine,
+            options,
+            sessions: Mutex::new(SessionRegistry::default()),
+            closing: std::sync::atomic::AtomicBool::new(false),
+        }
+    }
+
+    fn key(id: &str, user: Option<&proto::UserContext>) -> SessionKey {
+        (
+            user.map(|u| u.user_id.clone()).unwrap_or_default(),
+            id.into(),
+        )
+    }
+
+    fn session(
+        &self,
+        id: &str,
+        user: Option<&proto::UserContext>,
+        observed: Option<&str>,
+    ) -> Result<Arc<Session>, Status> {
+        self.find_session(id, user, observed, true)
+    }
+
+    fn find_session(
+        &self,
+        id: &str,
+        user: Option<&proto::UserContext>,
+        observed: Option<&str>,
+        create: bool,
+    ) -> Result<Arc<Session>, Status> {
+        if create {
+            parse_uuid(id, "session_id")?;
+        }
+        let key = Self::key(id, user);
+        let mut sessions = self
+            .sessions
+            .lock()
+            .unwrap_or_else(std::sync::PoisonError::into_inner);
+        if self.closing.load(std::sync::atomic::Ordering::SeqCst) {
+            return Err(Status::unavailable("server is shutting down"));
+        }
+        let session = match sessions.entries.get(&key) {
+            Some(Some(session)) => session.clone(),
+            Some(None) => return Err(Status::failed_precondition("session was 
released")),
+            None if !create => return Err(Status::not_found("session does not 
exist")),
+            // An observed ID refers to a previous incarnation; a new session
+            // cannot satisfy it. Reject before allocating backend resources.
+            None if observed.is_some() => {
+                return Err(Status::failed_precondition(
+                    "server-side session ID changed",
+                ));
+            }
+            None => {
+                let backend = self.engine.create_session(SessionContext {
+                    session_id: id.to_owned(),
+                    user_context: user.cloned(),
+                })?;
+                let session = Arc::new(Session::new(backend));
+                sessions.entries.insert(key, Some(session.clone()));
+                session
+            }
+        };
+        if observed.is_some_and(|id| id != session.id) {
+            return Err(Status::failed_precondition(
+                "server-side session ID changed",
+            ));
+        }
+        Ok(session)
+    }
+
+    pub(crate) fn cancel_all(&self) {
+        self.closing
+            .store(true, std::sync::atomic::Ordering::SeqCst);
+        // Stalled HTTP/2 connections can retain the service after the bounded
+        // transport drain. Remove its registry ownership now so backend 
sessions
+        // can close once their cancelled operations finish.
+        let sessions = std::mem::take(
+            &mut *self
+                .sessions
+                .lock()
+                .unwrap_or_else(std::sync::PoisonError::into_inner),
+        );
+        for session in sessions.entries.into_values().flatten() {
+            session.cancelled.send_replace(true);
+        }
+    }
+}
+
+fn response(
+    session_id: &str,
+    session: &Session,
+    operation_id: &str,
+    response_type: Option<proto::execute_plan_response::ResponseType>,
+) -> proto::ExecutePlanResponse {
+    proto::ExecutePlanResponse {
+        session_id: session_id.into(),
+        server_side_session_id: session.id.clone(),
+        operation_id: operation_id.into(),
+        response_id: Uuid::new_v4().to_string(),
+        response_type,
+        ..Default::default()
+    }
+}
+
+fn checked_response(
+    message: proto::ExecutePlanResponse,
+) -> Result<proto::ExecutePlanResponse, Status> {
+    if message.encoded_len() > MAX_METADATA_RESPONSE_BYTES {
+        return Err(Status::resource_exhausted(
+            "schema/command response exceeds the 3 MiB limit",
+        ));
+    }
+    Ok(message)
+}
+
+fn complete(id: &str, session: &Session, operation: &str) -> 
proto::ExecutePlanResponse {
+    response(
+        id,
+        session,
+        operation,
+        Some(proto::execute_plan_response::ResponseType::ResultComplete(
+            proto::execute_plan_response::ResultComplete {},
+        )),
+    )
+}
+
+fn encode_batch(batch: &RecordBatch) -> Result<(Vec<u8>, SchemaRef), Status> {
+    use arrow::datatypes::DataType;
+    use arrow::record_batch::RecordBatchOptions;
+
+    // Materialize view arrays, including nested children, into the 
large-offset
+    // string/binary representation used for encoded RecordBatch results.
+    let source_schema = batch.schema();
+    let fields = schema::map_fields(source_schema.fields(), &|field, 
data_type| {
+        let data_type = match data_type {
+            DataType::Utf8View => DataType::LargeUtf8,
+            DataType::BinaryView => DataType::LargeBinary,
+            other => other,
+        };
+        if data_type == *field.data_type() {
+            field.clone()
+        } else {
+            Arc::new(field.as_ref().clone().with_data_type(data_type))
+        }
+    });
+    let changed = fields
+        .iter()
+        .zip(source_schema.fields())
+        .any(|(target, source)| target.data_type() != source.data_type());
+    let materialized = if changed {
+        let columns = batch
+            .columns()
+            .iter()
+            .zip(&fields)
+            .map(|(column, field)| {
+                if column.data_type() == field.data_type() {
+                    Ok(column.clone())
+                } else {
+                    arrow::compute::cast(column.as_ref(), field.data_type())
+                }
+            })
+            .collect::<Result<Vec<_>, _>>()
+            .map_err(|error| Status::internal(error.to_string()))?;
+        let target_schema = Arc::new(Schema::new_with_metadata(
+            fields,
+            source_schema.metadata().clone(),
+        ));
+        Some(
+            RecordBatch::try_new_with_options(
+                target_schema,
+                columns,
+                
&RecordBatchOptions::new().with_row_count(Some(batch.num_rows())),
+            )
+            .map_err(|error| Status::internal(error.to_string()))?,
+        )
+    } else {
+        None
+    };
+    let batch = materialized.as_ref().unwrap_or(batch);
+    let mut bytes = Vec::new();
+    {
+        let mut writer = StreamWriter::try_new(&mut bytes, 
batch.schema().as_ref())
+            .map_err(|e| Status::internal(e.to_string()))?;
+        writer
+            .write(batch)
+            .map_err(|e| Status::internal(e.to_string()))?;
+        writer
+            .finish()
+            .map_err(|e| Status::internal(e.to_string()))?;
+    }
+    Ok((bytes, batch.schema()))
+}
+
+// PySpark assembles one table from all IPC batches. Its physical types and
+// nullability must agree across batches, while field/schema metadata may 
differ.
+fn check_output_schema(schema: &Schema, expected: &mut Option<Schema>) -> 
Result<(), Status> {
+    use arrow::datatypes::Field;
+
+    let actual = Schema::new(schema::map_fields(schema.fields(), &|field, 
data_type| {
+        Arc::new(Field::new(field.name(), data_type, field.is_nullable()))
+    }));
+    match expected {
+        Some(expected) if *expected != actual => Err(Status::internal(
+            "Arrow output schema changed within one result",
+        )),
+        Some(_) => Ok(()),
+        None => {
+            *expected = Some(actual);
+            Ok(())
+        }
+    }
+}
+
+// Keep backend ownership until the batch is dropped, including on encoder 
panic.
+struct EncodingBatch {
+    batch: RecordBatch,
+    _guard: Arc<OperationGuard>,
+}
+
+impl EncodingBatch {
+    fn encode(self) -> Result<(Vec<u8>, SchemaRef), Status> {
+        encode_batch(&self.batch)
+    }
+}
+
+fn arrow_chunk_size(
+    options: &[proto::execute_plan_request::RequestOption],
+    maximum: usize,
+) -> Option<usize> {
+    use proto::execute_plan_request::request_option::RequestOption;
+
+    let mut chunking = options
+        .iter()
+        .filter_map(|option| match &option.request_option {
+            Some(RequestOption::ResultChunkingOptions(options)) => 
Some(options),
+            _ => None,
+        });
+    if maximum == 0
+        || !chunking
+            .clone()
+            .any(|options| options.allow_arrow_batch_chunking)
+    {
+        return None;
+    }
+    Some(
+        chunking
+            .find_map(|options| options.preferred_arrow_chunk_size)
+            // Validate i64 directly; Scala's toInt can wrap an invalid 
preference.
+            .and_then(|bytes| usize::try_from(bytes).ok())
+            .filter(|bytes| (1024..=maximum).contains(bytes))
+            .unwrap_or(maximum),
+    )
+}
+
+async fn send_batch(
+    sender: &mpsc::Sender<Result<proto::ExecutePlanResponse, Status>>,
+    id: &str,
+    operation: &str,
+    batch: ResultBatch,
+    batch_schema: &Schema,
+    offset: &mut i64,
+    output_schema: &mut Option<Schema>,
+    guard: &Arc<OperationGuard>,
+    chunk_size: Option<usize>,
+) -> Result<bool, Status> {
+    // Reject unrepresentable counts/offsets before encoding or sending any 
chunk.
+    let row_count = match &batch {
+        ResultBatch::Arrow(batch) => i64::try_from(batch.num_rows())
+            .map_err(|_| Status::resource_exhausted("result batch row count 
exceeds i64"))?,
+        ResultBatch::Ipc { row_count, .. } if *row_count < 0 => {
+            return Err(Status::internal("negative engine IPC row count"));
+        }
+        ResultBatch::Ipc { row_count, .. } => *row_count,
+    };
+    let next_offset = offset
+        .checked_add(row_count)
+        .ok_or_else(|| Status::resource_exhausted("result row offset exceeds 
i64"))?;
+    let data: prost::bytes::Bytes = match batch {
+        ResultBatch::Arrow(batch) => {
+            // A blocking encoder cannot be cancelled once started. Retain 
engine
+            // ownership until its batch is dropped, even if the caller goes 
away.
+            let encoding = EncodingBatch {
+                batch,
+                _guard: guard.clone(),
+            };
+            let (data, schema) = tokio::task::spawn_blocking(move || 
encoding.encode())
+                .await
+                .map_err(|_| Status::internal("Arrow result encoding task 
failed"))??;
+            check_output_schema(schema.as_ref(), output_schema)?;
+            data.into()
+        }
+        ResultBatch::Ipc { data, .. } => {
+            check_output_schema(batch_schema, output_schema)?;
+            data.into()
+        }
+    };
+    let mut payload = proto::execute_plan_response::ArrowBatch {
+        row_count,
+        start_offset: Some(*offset),
+        ..Default::default()
+    };
+    let Some(chunk_bytes) = chunk_size else {
+        // As on the JVM, clients without chunking opt-in receive the original
+        // whole IPC batch. Their gRPC receive limit must accommodate it.
+        payload.data = data;
+        let message = response(
+            id,
+            &guard.session,
+            operation,
+            Some(proto::execute_plan_response::ResponseType::ArrowBatch(
+                payload,
+            )),
+        );
+        *offset = next_offset;
+        return Ok(sender.send(Ok(message)).await.is_ok());
+    };
+    let chunks = data.len().div_ceil(chunk_bytes).max(1);
+    payload.num_chunks_in_batch = Some(
+        i64::try_from(chunks)
+            .map_err(|_| Status::resource_exhausted("Arrow chunk count exceeds 
i64"))?,
+    );
+    for index in 0..chunks {
+        let from = index * chunk_bytes;
+        let to = from.saturating_add(chunk_bytes).min(data.len());
+        // Bytes slices share the original IPC allocation, including compressed
+        // buffers. Clients concatenate the chunks before decoding Arrow.
+        payload.data = data.slice(from..to);
+        payload.chunk_index = Some(index as i64);
+        let message = response(
+            id,
+            &guard.session,
+            operation,
+            Some(proto::execute_plan_response::ResponseType::ArrowBatch(
+                payload.clone(),
+            )),
+        );
+        if sender.send(Ok(message)).await.is_err() {
+            return Ok(false);
+        }
+    }
+    *offset = next_offset;
+    Ok(true)
+}
+
+#[tonic::async_trait]
+impl SparkConnectService for ConnectService {
+    type ExecutePlanStream = Output;
+    type ReattachExecuteStream = Output;
+
+    async fn execute_plan(
+        &self,
+        request: Request<proto::ExecutePlanRequest>,
+    ) -> Result<Response<Output>, Status> {
+        let req = request.into_inner();
+        let chunk_size = arrow_chunk_size(&req.request_options, 
self.options.max_arrow_chunk_size);
+        let reattachable = req.request_options.iter().any(|option| {
+            matches!(
+                &option.request_option,
+                
Some(proto::execute_plan_request::request_option::RequestOption::ReattachOptions(
+                    options
+                )) if options.reattachable
+            )
+        });
+        let operation = match req.operation_id {
+            Some(id) => parse_uuid(&id, "operation_id")?,
+            None => Uuid::new_v4(),
+        }
+        .to_string();
+        let op = req
+            .plan
+            .and_then(|p| p.op_type)
+            .ok_or_else(|| Status::invalid_argument("missing plan"))?;
+        let session = self.session(
+            &req.session_id,
+            req.user_context.as_ref(),
+            req.client_observed_server_side_session_id.as_deref(),
+        )?;
+        let mut cancelled = session.cancelled.subscribe();
+        if *cancelled.borrow() {
+            return Err(Status::cancelled("session released"));
+        }
+        // Reserve before calling the backend: preparing a command can mutate 
state.
+        let (guard, mut operation_cancelled) = session.operation(&operation)?;
+        let prepared = tokio::select! {
+            biased;
+            _ = cancelled.changed() => return Err(Status::cancelled("session 
released")),

Review Comment:
   **Nit (P3):** This arm is the only thing that cancels a pending `prepare` 
when its session is released or the server shuts down, but no test reaches it. 
`operation_reservation_precedes_prepare_and_cleans_up_after_cancellation_and_errors`
 blocks prepare and cancels through `ReleaseExecute`, which takes the 
`operation_cancelled` arm below. The session-release and shutdown tests in 
engine_injection.rs all start after prepare has returned or target 
analyze/config through `while_open`. By our reading, deleting this line would 
leave a `BLOCKED_PREPARE` call pending after `ReleaseSession`, keeping the 
backend session referenced until the client disconnects, and shutdown would 
wait out the two-second drain, with every test still passing. Blocking prepare, 
then sending `ReleaseSession` (and, separately, signalling shutdown) and 
asserting `CANCELLED`, `blocked_prepares_dropped` and `sessions_dropped`, would 
cover it.
   
   **Verification:**
   - **Regression:** With prepare blocked, releasing its session returns 
CANCELLED to the pending ExecutePlan and the counters for dropped blocked 
prepares and dropped sessions each reach one; the test fails if the prepare 
select loses its session-cancellation arm.
   - **Regression:** With prepare blocked, signalling server shutdown returns 
CANCELLED to the pending ExecutePlan and drops the blocked prepare and the 
backend session well within the two-second drain window.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

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


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

Reply via email to