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


##########
crates/spark-connect-server/src/lib.rs:
##########
@@ -0,0 +1,126 @@
+// 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.
+
+pub mod engine;
+mod ids;
+mod schema;
+mod service;
+
+/// Generated server bindings for custom embedding. This experimental API 
follows
+/// the protocol schema and may change with the protocol.
+pub mod grpc {
+    pub use spark_connect_proto::spark_connect_service_server;
+}
+
+/// Transport options for the experimental frontend.
+/// Start from [`ServerOptions::default()`] and assign the desired fields.
+#[derive(Clone, Debug)]
+#[non_exhaustive]
+pub struct ServerOptions {
+    /// Maximum Arrow chunk payload in bytes, excluding the protobuf envelope.
+    /// Defaults to 90% of 128 MiB, as in Spark's JVM server. A client can 
request
+    /// a smaller size. Zero disables chunking, even when the client opts in.
+    /// Clients must accept this payload plus the protobuf envelope: a 128 MiB
+    /// receive limit accommodates the default; tonic's 4 MiB default does not.
+    /// Alternatively, clients can request a smaller chunk size.
+    /// Whole batches sent without chunking are not bounded by this option.
+    pub max_arrow_chunk_size: usize,
+}
+
+impl Default for ServerOptions {
+    fn default() -> Self {
+        Self {
+            max_arrow_chunk_size: 128 * 1024 * 1024 * 9 / 10,
+        }
+    }
+}
+
+struct CancelOnDrop(std::sync::Arc<service::ConnectService>);
+
+impl Drop for CancelOnDrop {
+    fn drop(&mut self) {
+        self.0.cancel_all();
+    }
+}
+
+fn tcp_incoming(listener: tokio::net::TcpListener) -> 
tonic::transport::server::TcpIncoming {
+    // Builder socket options do not apply to serve_with_incoming_shutdown.
+    
tonic::transport::server::TcpIncoming::from(listener).with_nodelay(Some(true))
+}
+
+/// Serve with an injected execution engine and a fresh session registry.
+///
+/// The frontend binds each protocol session to the engine session created for 
it.
+/// The caller owns the engine and signals shutdown before releasing its 
resources.
+/// Dropping this future also cancels registered engine work, without waiting 
for
+/// the bounded transport drain used when shutdown is signalled.
+pub async fn serve_with_engine(
+    listener: tokio::net::TcpListener,
+    engine: std::sync::Arc<dyn engine::Engine>,
+    shutdown: impl std::future::Future<Output = ()> + Send + 'static,
+) -> Result<(), tonic::transport::Error> {
+    serve_with_engine_and_options(listener, engine, ServerOptions::default(), 
shutdown).await
+}
+
+/// Serve with an injected engine and explicit transport options.
+///
+/// Session lifetime and shutdown follow [`serve_with_engine`]. Producers 
should
+/// bound engine batches independently of this transport chunk size. Clients 
must
+/// allow protobuf overhead in their gRPC receive limits.
+pub async fn serve_with_engine_and_options(
+    listener: tokio::net::TcpListener,
+    engine: std::sync::Arc<dyn engine::Engine>,
+    options: ServerOptions,
+    shutdown: impl std::future::Future<Output = ()> + Send + 'static,
+) -> Result<(), tonic::transport::Error> {
+    let service = std::sync::Arc::new(service::ConnectService::new(engine, 
options));
+    let _cancel_on_drop = CancelOnDrop(service.clone());
+    let router = tonic::transport::Server::builder().add_service(
+        
grpc::spark_connect_service_server::SparkConnectServiceServer::from_arc(service.clone())
+            .max_decoding_message_size(128 * 1024 * 1024),
+    );
+    let (draining, drain_started) = tokio::sync::oneshot::channel();
+    let server = router.serve_with_incoming_shutdown(tcp_incoming(listener), 
async move {
+        shutdown.await;
+        service.cancel_all();
+        let _ = draining.send(());
+    });
+    tokio::pin!(server);
+    tokio::select! {
+        result = &mut server => result,
+        _ = drain_started => {
+            // A peer that stops reading must not prevent local process 
shutdown.
+            tokio::time::timeout(std::time::Duration::from_secs(2), &mut 
server)

Review Comment:
   Covered in 5d3ca37757b6: 
`shutdown_releases_backend_session_while_a_result_remains_unread` now keeps its 
unread 1 KiB-window peer connected through `server.stop()`, requires `serve` to 
return within 4 s, and drops the peer only afterwards. With the drain awaited 
without its two-second bound, the test fails at that timeout.



##########
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"));

Review Comment:
   Covered in 5d3ca37757b6 by 
`requests_handled_after_shutdown_begins_do_not_create_backend_sessions`. A raw 
h2 `ExecutePlan` for an unused session sends its headers before the shutdown 
signal, and two PING round trips confirm that the server has them. Its body 
follows once another session's live execution is cancelled. The test expects 
`UNAVAILABLE` "server is shutting down", no factory call for the new session 
and no further `prepare`. Without the check, the request creates a backend 
session and the test fails.



##########
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 => {

Review Comment:
   Covered in 5d3ca37757b6 by 
`negative_engine_ipc_row_counts_fail_before_forwarding`, next to the overflow 
cases: an IPC batch with `row_count: -1` fails with `INTERNAL` "negative engine 
IPC row count", leaves the offset and output schema unchanged, and sends 
nothing. Without the guard, the batch is forwarded and the test fails.



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