dbtsai commented on code in PR #474: URL: https://github.com/apache/spark-connect-rust/pull/474#discussion_r4594689908
########## crates/spark-connect-server/jni/src/lib.rs: ########## @@ -0,0 +1,528 @@ +// 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. + +//! JVM-loaded JNI host. Java objects are retained by the C shim, never by JNIEnv pointers. + +mod engine; + +use std::{ + cell::{Cell, RefCell}, + collections::HashMap, + ffi::c_void, + net::SocketAddr, + ptr, + sync::{ + atomic::{AtomicBool, AtomicI64, Ordering}, + mpsc as std_mpsc, Arc, Mutex, OnceLock, + }, + time::Duration, +}; + +use tokio::sync::oneshot; +use tonic::Code; + +const MAX_BYTES: usize = 64 * 1024 * 1024; + +#[repr(C)] +pub struct BridgeBuffer { + data: *mut u8, + len: usize, +} +impl Default for BridgeBuffer { + fn default() -> Self { + Self { + data: ptr::null_mut(), + len: 0, + } + } +} + +extern "C" { + fn spark_connect_buffer_free(buffer: *mut BridgeBuffer); +} + +fn take_buffer(mut buffer: BridgeBuffer) -> Vec<u8> { + let result = if buffer.data.is_null() || buffer.len == 0 { + Vec::new() + } else { + // C returns malloc-owned buffers valid until spark_connect_buffer_free. + unsafe { std::slice::from_raw_parts(buffer.data, buffer.len).to_vec() } + }; + unsafe { + spark_connect_buffer_free(&mut buffer); + } + result +} + +struct ServerEntry { + address: String, + shutdown: Mutex<Option<oneshot::Sender<()>>>, + done: Mutex<std_mpsc::Receiver<Result<(), String>>>, + thread: Mutex<Option<std::thread::JoinHandle<()>>>, + stopping: Mutex<()>, + drained: AtomicBool, + backend: Arc<engine::JvmEngine>, +} +fn servers() -> &'static Mutex<HashMap<i64, Arc<ServerEntry>>> { + static SERVERS: OnceLock<Mutex<HashMap<i64, Arc<ServerEntry>>>> = OnceLock::new(); + SERVERS.get_or_init(Mutex::default) +} + +thread_local! { + // Attach lazily on the first engine action. The runtime's stop hook runs on + // that same blocking worker; each individual call still restores its context. + static ENGINE_ATTACHMENT: RefCell<Option<engine::WorkerAttachment>> = const { RefCell::new(None) }; + static ENGINE_ATTACH_ERROR_REPORTED: Cell<bool> = const { Cell::new(false) }; +} +fn attach_engine_worker(engine: &Arc<engine::JvmEngine>) { + ENGINE_ATTACHMENT.with(|slot| { + if let Some(attachment) = slot.borrow().as_ref() { + debug_assert!(attachment.belongs_to(engine)); + return; + } + match engine.attach_worker() { + Ok(attachment) => *slot.borrow_mut() = Some(attachment), + Err(error) if error.code() == Code::Unavailable => { + // Shutdown can win after blocking work is reserved. Its task + // cancellation and normal per-call checks handle that race. + } + Err(error) => { + // The existing per-call JNI scope remains a safe fallback. + // Retry transient failures, but report at most once per worker. + ENGINE_ATTACH_ERROR_REPORTED.with(|reported| { + if !reported.replace(true) { + eprintln!( + "JVM worker attachment failed; using per-call attachment: {error}" + ); + } + }); + } + } + }); +} +fn start_host(address: &[u8], backend: Arc<engine::JvmEngine>) -> Result<i64, String> { + static NEXT: AtomicI64 = AtomicI64::new(1); + #[allow(deprecated)] // Renamed only in Rust 1.95; preserve the declared MSRV. + let id = NEXT + .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |id| id.checked_add(1)) + .map_err(|_| "JNI server IDs exhausted")?; + let address: SocketAddr = std::str::from_utf8(address) + .map_err(|_| "listen address must be UTF-8")? + .parse() + .map_err(|_| "listen address must be an IP:port")?; + let listener = std::net::TcpListener::bind(address).map_err(|e| e.to_string())?; + listener.set_nonblocking(true).map_err(|e| e.to_string())?; + let address = listener + .local_addr() + .map_err(|e| e.to_string())? + .to_string(); + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .max_blocking_threads(256) + .on_thread_stop(|| { + let attachment = ENGINE_ATTACHMENT.with(|slot| slot.borrow_mut().take()); + drop(attachment); + }) + .enable_all() + .build() + .map_err(|e| e.to_string())?; + let (shutdown, stopped) = oneshot::channel(); + let (done, completed) = std_mpsc::channel(); + let worker_backend = backend.clone(); + let thread = std::thread::Builder::new() + .name("spark-connect-jni-server".into()) + .spawn(move || { + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + runtime.block_on(async { + let listener = + tokio::net::TcpListener::from_std(listener).map_err(|e| e.to_string())?; + spark_connect_server::serve_with_engine( + listener, + Arc::new(engine::EngineFactory(worker_backend.clone())), + async { + let _ = stopped.await; + }, + ) + .await + .map_err(|e| e.to_string()) + }) + })) + .unwrap_or_else(|_| Err("Rust listener panicked".into())); + worker_backend.shutdown(); + // Never destroy a JVM global reference or runtime while attached work remains. + worker_backend.wait_drained(); + runtime.shutdown_timeout(Duration::from_secs(1)); + let result = result.and_then(|()| worker_backend.verify_workers_detached()); + let _ = done.send(result); + }) + .map_err(|e| e.to_string())?; + servers() + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert( + id, + Arc::new(ServerEntry { + address, + shutdown: Mutex::new(Some(shutdown)), + done: Mutex::new(completed), + thread: Mutex::new(Some(thread)), + stopping: Mutex::new(()), + drained: AtomicBool::new(false), + backend, + }), + ); + Ok(id) +} +fn find_server(id: i64) -> Result<Arc<ServerEntry>, String> { + servers() + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get(&id) + .cloned() + .ok_or_else(|| "invalid or closed native server handle".into()) +} +fn stop_server(id: i64) -> Result<(), String> { + let server = find_server(id)?; + let _stopping = server + .stopping + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + server.backend.retry_failed_cleanup(); + if server + .thread + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .is_none() + { + if !server.drained.load(Ordering::SeqCst) { + return Err("JNI server drain state is unknown after a listener-thread failure; references retained until JVM exit".into()); + } + server.backend.shutdown(); + server.backend.verify_workers_detached()?; + server.backend.release_factory()?; + servers() + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .remove(&id); + return Ok(()); + } + server.backend.shutdown(); + if let Some(shutdown) = server + .shutdown + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take() + { + let _ = shutdown.send(()); + } + let completed = server + .done + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let deadline = std::time::Instant::now() + Duration::from_secs(10); + let result = loop { + if let Some(error) = server.backend.cleanup_failure() { + // The listener thread still owns the runtime and waits for the + // retained handles/permits. A later explicit close can retry them. + return Err(error); + } + let remaining = deadline.saturating_duration_since(std::time::Instant::now()); + if remaining.is_zero() { + return Err("JNI stop is incomplete; active JVM calls retained safely, retry close after they finish".into()); + } + match completed.recv_timeout(remaining.min(Duration::from_millis(20))) { + Ok(result) => { + // Only this completion certifies drain and runtime stop. + server.drained.store(true, Ordering::SeqCst); + break result; + } + Err(std_mpsc::RecvTimeoutError::Timeout) => {} + Err(std_mpsc::RecvTimeoutError::Disconnected) => { + break Err("JNI server completion channel closed without confirming teardown; drain state unknown".into()); + } + } + }; + drop(completed); + let mut result = result; + if let Some(thread) = server + .thread + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take() + { + if thread.join().is_err() { + result = Err("JNI server thread panicked".into()); + } + } + // NativeEngineServer retains its handle on any error. Keep even a fully stopped + // entry until the owner retries, rather than returning a stale handle. + if result.is_ok() { + // Join and confirmed drain precede the synchronous Java factory close. + // Retaining server here prevents a concurrent final core Drop. + result = server.backend.release_factory(); + } + if result.is_ok() { + servers() + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .remove(&id); + } + result +} + +unsafe fn write_buffer(out: *mut BridgeBuffer, bytes: &[u8]) { + if out.is_null() { + return; + } + if bytes.is_empty() { + *out = BridgeBuffer::default(); + return; + } + let data = libc::malloc(bytes.len()).cast::<u8>(); + if data.is_null() { Review Comment: Fixed in [dce536e8d00a747b8f23df0e663fbcbca962c3cc](https://github.com/apache/spark-connect-rust/commit/dce536e8d00a747b8f23df0e663fbcbca962c3cc). `write_buffer` now returns a Result, and the address entry point propagates allocation failure instead of returning success with an empty address. An injected-allocation test exercises the helper's failure path. ########## crates/spark-connect-server/jvm/build.sh: ########## @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# 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. + +set -euo pipefail + +if [[ $# -gt 1 || ( $# -eq 1 && "$1" != "--tests" ) ]]; then + echo "usage: $0 [--tests]" >&2 + exit 1 +fi + +PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +: "${SPARK_HOME:?Set SPARK_HOME to an existing Spark 4.2 assembly with shaded Connect gRPC jars}" +SPARK_JARS="$SPARK_HOME/jars" +if [[ -d "$SPARK_HOME/assembly/target/scala-2.13/jars" ]]; then + SPARK_JARS="$SPARK_HOME/assembly/target/scala-2.13/jars" +fi +if [[ ! -d "$SPARK_JARS" ]]; then + echo "Spark jar directory does not exist: $SPARK_JARS" >&2 + exit 1 +fi +JAVAC="${JAVA_HOME:+$JAVA_HOME/bin/}javac" +JAR="${JAVA_HOME:+$JAVA_HOME/bin/}jar" +BUILD_DIR="$PROJECT_DIR/.build/jvm" +rm -rf -- "$BUILD_DIR/classes" "$BUILD_DIR/test-classes" Review Comment: Fixed in [dce536e8d00a747b8f23df0e663fbcbca962c3cc](https://github.com/apache/spark-connect-rust/commit/dce536e8d00a747b8f23df0e663fbcbca962c3cc). Each Java build now uses a private staging directory and atomically publishes complete, self-contained JARs after compilation succeeds. Adapter packaging validates the exact temporary copy before replacing the published JAR, and writes checksum files atomically. Three concurrent builds passed while a reader successfully opened the published JAR 718 times with no errors; regressions cover source replacement during copying and interrupted JAR/checksum writes. ########## crates/spark-connect-server/jvm/src/main/java/org/apache/spark/sql/connect/nativebridge/engine/EmbeddedSparkEngine.java: ########## @@ -0,0 +1,125 @@ +// 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. + +package org.apache.spark.sql.connect.nativebridge.engine; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.apache.spark.sql.SparkSession; +import org.apache.spark.sql.connect.service.SparkConnectService$; +import org.apache.spark.util.ShutdownHookManager; + +/** Spark-submit launcher: Rust protocol/session/operation ownership with Catalyst execution. */ +public final class EmbeddedSparkEngine { + static final String SHUTDOWN_COMPLETE = "Embedded Spark Engine shutdown complete"; + static final String STARTUP_CLEANUP_COMPLETE = + "Embedded Spark Engine startup failed; cleanup complete"; + private EmbeddedSparkEngine() {} + + public static void main(String[] arguments) throws InterruptedException { + if (arguments.length < 1 || arguments.length > 2) { + throw new IllegalArgumentException( + "usage: EmbeddedSparkEngine <absolute-native-library|--bundled> [listen-address]"); + } + String address = arguments.length == 2 ? arguments[1] : "127.0.0.1:15002"; + SparkSession session = SparkSession.builder().appName("Rust Spark Connect with Catalyst") + .config("spark.sql.artifact.isolation.enabled", "true") + .config("spark.sql.artifact.isolation.alwaysApplyClassloader", "true") + .getOrCreate(); + SparkJvmEngine engine = null; + NativeEngineServer server = null; + CountDownLatch stopped = new CountDownLatch(1); + AtomicBoolean launched = new AtomicBoolean(); + Object hook = null; + try { + if (SparkConnectService$.MODULE$.server() != null) { + throw new IllegalStateException("a Java Spark Connect listener was started"); + } + engine = new SparkJvmEngine(session); + server = "--bundled".equals(arguments[0]) + ? new NativeEngineServer(address, engine) + : new NativeEngineServer(arguments[0], address, engine); + // NativeEngineServer owns the engine after acquisition; the extra idempotent close also + // covers Java-side startup failures before acquisition and keeps one cleanup helper. + SparkJvmEngine shutdownEngine = engine; + NativeEngineServer shutdownServer = server; + hook = ShutdownHookManager.addShutdownHook( + ShutdownHookManager.SPARK_CONTEXT_SHUTDOWN_PRIORITY() + 1, () -> { + shutdown(shutdownServer::close, shutdownEngine::close, session::stop, stopped, + !launched.get()); + return scala.runtime.BoxedUnit.UNIT; + }); + System.out.println("Embedded Spark Connect listening on " + server.address()); + System.out.println("Embedded Spark Connect JVM PID " + ProcessHandle.current().pid() + + "; Java Connect listener absent"); + launched.set(true); + stopped.await(); Review Comment: Fixed in [dce536e8d00a747b8f23df0e663fbcbca962c3cc](https://github.com/apache/spark-connect-rust/commit/dce536e8d00a747b8f23df0e663fbcbca962c3cc). The native host exposes listener-running state independently of cleanup drain, and the launcher polls it so an unexpected listener exit triggers teardown and an error. A close retry is allowed only after confirmed drain; incomplete or unknown cleanup retains the native handle and prevents stopping shared Spark resources. A Rust test exercises the real listener exiting while retained cleanup blocks drain; stock JNI smoke calls both health methods with a live handle. Java lifecycle tests cover the failure and cleanup ordering. -- 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]
