dbtsai commented on code in PR #474: URL: https://github.com/apache/spark-connect-rust/pull/474#discussion_r4594687733
########## crates/spark-connect-server/src/service.rs: ########## @@ -0,0 +1,1214 @@ +// 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::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}; + +type Output = Pin<Box<dyn Stream<Item = Result<proto::ExecutePlanResponse, Status>> + Send>>; +type SessionKey = (String, String); +const MAX_ARROW_IPC_BYTES: usize = crate::schema::MAX_RESULT_BYTES; +const MAX_RELEASED_SESSIONS: usize = 4096; +const RELEASE_WAIT: std::time::Duration = std::time::Duration::from_secs(2); + +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 { + 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>> { + if allow_reconnect { Review Comment: Fixed in [dce536e8d00a747b8f23df0e663fbcbca962c3cc](https://github.com/apache/spark-connect-rust/commit/dce536e8d00a747b8f23df0e663fbcbca962c3cc). Release now acts only on a live session. A later `allow_reconnect=true` release cannot remove an existing tombstone, and releasing an unknown session is a no-op. Tests also verify that duplicate/unknown releases do not evict bounded tombstone history or disturb active sessions. ########## crates/spark-connect-server/jvm/src/main/java/org/apache/spark/sql/connect/nativebridge/engine/SparkJvmEngine.java: ########## @@ -0,0 +1,950 @@ +// 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.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.Properties; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import org.apache.arrow.memory.OutOfMemoryException; +import org.apache.spark.SparkContext; +import org.apache.spark.SparkEnv; +import org.apache.spark.SparkException; +import org.apache.spark.SparkThrowable; +import org.apache.spark.api.java.JavaRDD; +import org.apache.spark.connect.proto.Relation; +import org.apache.spark.sql.AnalysisException; +import org.apache.spark.sql.Encoders; +import org.apache.spark.sql.Row; +import org.apache.spark.sql.SparkSession; +import org.apache.spark.sql.catalyst.analysis.UnresolvedExecuteImmediate; +import org.apache.spark.sql.catalyst.plans.logical.Command; +import org.apache.spark.sql.catalyst.plans.logical.InsertIntoDir; +import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan; +import org.apache.spark.sql.catalyst.plans.logical.ParsedStatement; +import org.apache.spark.sql.classic.Dataset; +import org.apache.spark.sql.connect.common.InvalidPlanInput; +import org.apache.spark.sql.connect.planner.SparkConnectPlanner; +import org.apache.spark.sql.connect.service.SessionHolder; +import org.apache.spark.sql.execution.CommandExecutionMode; +import org.apache.spark.sql.execution.QueryExecution; +import org.apache.spark.sql.execution.SQLExecution; +import org.apache.spark.sql.execution.SparkPlan; +import org.apache.spark.sql.execution.arrow.ArrowConverters$; +import org.apache.spark.sql.types.ArrayType; +import org.apache.spark.sql.types.CharType; +import org.apache.spark.sql.types.DataType; +import org.apache.spark.sql.types.DataTypes; +import org.apache.spark.sql.types.MapType; +import org.apache.spark.sql.types.StringType; +import org.apache.spark.sql.types.StructField; +import org.apache.spark.sql.types.StructType; +import org.apache.spark.sql.types.UserDefinedType; +import org.apache.spark.sql.types.VarcharType; +import org.sparkproject.connect.protobuf.InvalidProtocolBufferException; +import org.sparkproject.connect.protobuf.Message; + +import scala.Option; +import scala.Tuple2; +import scala.reflect.ClassTag; +import scala.reflect.ClassTag$; +import scala.runtime.AbstractFunction0; +import scala.runtime.AbstractFunction1; + +/** + * A query engine for the Rust-owned frontend. The JNI boundary passes Catalyst inputs and Arrow + * batches, never service RPC requests, responses, observers, or operation registries. + * + * This intentionally targets the cached Spark 4.2 assembly. SessionHolder is a planner resource + * container only: its service-managed close() and SparkSession.close() are never called. + * + * Passing this engine to NativeEngineServer transfers its lifetime to that server. Native stop + * closes it, and a failed native start can close it too; do not share or reuse it afterwards. + * close() is idempotent, so callers may also close it while cleaning up a failed constructor. + * The caller retains ownership of the original SparkSession and shared SparkContext. + */ +public final class SparkJvmEngine implements AutoCloseable { + static final int MAX_IPC_BYTES = 64 * 1024 * 1024; + private static final int MAX_BATCH_ROWS = 10000; + private static final int MAX_CONFIG_FIELDS = 10000; + private static final String SHUFFLE_FILE_CLEANUP = + "spark.sql.classic.shuffleDependency.fileCleanup.enabled"; + private static final Set<String> RELATIONS = Set.of( + "RANGE", "LOCAL_RELATION", "SQL", "PROJECT", "FILTER", "LIMIT", "OFFSET", "TAIL", + "JOIN", "SORT", "AGGREGATE", "DEDUPLICATE", "SET_OP", "SUBQUERY_ALIAS", "TO_DF", + "WITH_COLUMNS_RENAMED", "WITH_COLUMNS", "DROP", "REPARTITION", + "REPARTITION_BY_EXPRESSION", "HINT", "READ"); + + private final org.apache.spark.sql.classic.SparkSession base; + private final SparkContext sparkContext; + private final SparkEnv sparkEnv; + private final ClassLoader classLoader; + private final AtomicBoolean closed = new AtomicBoolean(); + private final Set<Session> sessions = ConcurrentHashMap.newKeySet(); + private final Set<Task> tasks = ConcurrentHashMap.newKeySet(); + private boolean closeComplete; + private Throwable closeFailure; + + public SparkJvmEngine(SparkSession session) { + if (!(Objects.requireNonNull(session, "session") + instanceof org.apache.spark.sql.classic.SparkSession)) { + throw new IllegalArgumentException("a classic Spark session is required"); + } + base = (org.apache.spark.sql.classic.SparkSession) session; + sparkContext = base.sparkContext(); + sparkEnv = SparkEnv.get(); + ClassLoader current = Thread.currentThread().getContextClassLoader(); + classLoader = current == null ? getClass().getClassLoader() : current; + } + + /** Allocate this control before invoking a blocking planner or cursor method. */ + public Task newTask(String description) { + ensureOpen(); + Task task = new Task(Objects.requireNonNull(description, "description")); + tasks.add(task); + if (closed.get()) task.cancel(); + return task; + } + + public Session openSession(String userId, String sessionId, Task task) { + Objects.requireNonNull(userId, "userId"); + Objects.requireNonNull(sessionId, "sessionId"); + return task.run(null, () -> { + ensureOpen(); + Session session = new Session(userId, sessionId); + sessions.add(session); + if (closed.get() || task.isCancelled()) { + session.close(); + task.check(); + ensureOpen(); + } + task.complete(); + return session; + }); + } + + boolean isClosed() { + return closed.get(); + } + + private void ensureOpen() { + if (closed.get()) throw new EngineException(9, "JVM engine is closed"); + } + + /** + * Idempotently release this engine's tasks and sessions without stopping the shared + * SparkContext. Once passed to NativeEngineServer, drain that server before calling this. + * A partial cleanup failure remains visible on later closes without replaying its side effects. + */ + @Override + public synchronized void close() { + throwFailure(closeFailure); + if (closeComplete) return; + closed.set(true); + Throwable failure = null; + for (Task task : tasks) { + try { task.close(); } catch (Throwable error) { failure = recordFailure(failure, error); } + } + for (Session session : sessions) { + try { session.close(); } catch (Throwable error) { failure = recordFailure(failure, error); } + } + closeFailure = failure; + throwFailure(failure); + closeComplete = true; + } + + @FunctionalInterface + private interface Action<T> { T run() throws Exception; } + + /** A small stable error surface for the native adapter's tonic Status mapping. */ + public static final class EngineException extends RuntimeException { + private static final long serialVersionUID = 1L; + private final int code; + + public EngineException(int code, String message) { + super(message); + this.code = code; + } + + public EngineException(int code, String message, Throwable cause) { + super(message, cause); + this.code = code; + } + + public int code() { return code; } + } + + private static EngineException engineError(Exception error) { + if (error instanceof EngineException) return (EngineException) error; + if (error instanceof OutOfMemoryException) { + return arrowAllocationFailure((OutOfMemoryException) error); + } + if (error instanceof SparkException) { + // Executor conversion errors arrive inside Spark's task-failure wrapper. Preserve only + // resource errors from that cause chain; an arbitrary nested argument error is not a + // client validation failure. + Set<Throwable> seen = Collections.newSetFromMap(new IdentityHashMap<>()); + for (Throwable cause = error.getCause(); cause != null && seen.add(cause); + cause = cause.getCause()) { + if (cause instanceof EngineException && ((EngineException) cause).code() == 8) { + return new EngineException(8, cause.getMessage(), error); + } + } + } + int code = 13; + // The pinned planner uses InvalidPlanInput for malformed client plans even though its + // legacy message-only constructor labels them INTERNAL_ERROR. Its concrete type is the + // input-validation contract; arbitrary Spark internal exceptions still map to INTERNAL. + if (error instanceof InvalidProtocolBufferException || error instanceof InvalidPlanInput) { + code = 3; + } else if (error instanceof SparkThrowable && !((SparkThrowable) error).isInternalError()) { + if (error instanceof NoSuchElementException) code = 5; + else if (error instanceof AnalysisException || error instanceof IllegalArgumentException) code = 3; + } + return new EngineException(code, error.getMessage(), error); + } + + static EngineException arrowAllocationFailure(OutOfMemoryException error) { + return new EngineException(8, "JVM Arrow allocation failed: " + error.getMessage(), error); + } + + /** Cancellation is independent of a query/session lock and remains usable during preparation. */ + public final class Task implements AutoCloseable { + private final String jobGroup = "spark-connect-engine-" + UUID.randomUUID(); + private final String description; + // Row iteration reads cancellation frequently; compound task transitions remain locked. + private volatile boolean cancelled; + private boolean completed; + private boolean executionStarted; + private Thread running; + private final Object cancellation = new Object(); + private Throwable cancellationFailure; + + private Task(String description) { this.description = description; } + + public void cancel() { + synchronized (cancellation) { + throwFailure(cancellationFailure); + try { + boolean cancelJobs; + synchronized (this) { + if (completed || cancelled) return; + cancelled = true; + if (running != null) running.interrupt(); + cancelJobs = executionStarted || running != null; + } + // Active preparation/analysis can submit Spark jobs too (for example, parallel file + // listing). An idle task that never began fetching has no scheduler work to cancel. + if (cancelJobs) sparkContext.cancelJobGroupAndFutureJobs(jobGroup); + } catch (Throwable error) { + cancellationFailure = error; + throw error; + } + } + } + + private boolean isCancelled() { return cancelled; } + + private void check() { + if (cancelled) throw new EngineException(1, "JVM engine operation was cancelled"); + } + + private synchronized void complete() { completed = true; } + + private synchronized void beginExecution() { + check(); + executionStarted = true; + } + + private EngineException taskError(Exception error) { + if (isCancelled() && !(error instanceof EngineException)) { + return new EngineException(1, "JVM engine operation was cancelled", error); + } + return engineError(error); + } + + private <T> T run(Session session, Action<T> action) { + Thread thread = Thread.currentThread(); + boolean previousInterrupted; + synchronized (this) { + check(); + if (running != null) throw new EngineException(9, "task is already executing"); + previousInterrupted = Thread.interrupted(); + running = thread; + } + try { + // Capture can fail too (for example, a caller's context-class-loader accessor). Keep + // the running mark covered before any caller/Spark code and until restoration ends. + Properties previousProperties = sparkContext.getLocalProperties(); + ClassLoader previousLoader = thread.getContextClassLoader(); + SparkEnv previousEnv = SparkEnv.get(); + Option<SparkSession> previousSession = SparkSession.getActiveSession(); + try { + if (session != null) session.activeTasks.add(this); + SparkEnv.set(sparkEnv); + thread.setContextClassLoader(classLoader); + sparkContext.setLocalProperties(new Properties()); + sparkContext.setJobGroup(jobGroup, description, true); + SparkSession.setActiveSession(session == null ? base : session.spark); + check(); + if (session == null) return action.run(); + session.ensureOpen(); + return session.holder.withSession( + new AbstractFunction1<org.apache.spark.sql.classic.SparkSession, T>() { + @Override + public T apply(org.apache.spark.sql.classic.SparkSession ignored) { + try { + check(); + return action.run(); + } catch (InterruptedException error) { + throw new EngineException(1, "JVM engine operation was interrupted", error); + } catch (Exception error) { + throw taskError(error); + } + } + }); + } finally { + if (session != null) session.activeTasks.remove(this); + if (previousSession.isDefined()) SparkSession.setActiveSession(previousSession.get()); + else SparkSession.clearActiveSession(); + sparkContext.setLocalProperties(previousProperties); + thread.setContextClassLoader(previousLoader); + SparkEnv.set(previousEnv); + } + } catch (InterruptedException error) { + throw new EngineException(1, "JVM engine operation was interrupted", error); + } catch (Exception error) { + throw taskError(error); + } finally { + synchronized (this) { running = null; } + Thread.interrupted(); + if (previousInterrupted) thread.interrupt(); + } + } + + @Override + public void close() { + cancel(); + tasks.remove(this); + } + } + + /** Independent Catalyst catalog/configuration; identity and wire lifetime remain in Rust. */ + public final class Session implements AutoCloseable { + private final org.apache.spark.sql.classic.SparkSession spark; + private final SessionHolder holder; + private final ReentrantReadWriteLock catalog = new ReentrantReadWriteLock(true); + private final AtomicBoolean released = new AtomicBoolean(); + private final Set<Query> queries = ConcurrentHashMap.newKeySet(); + private final Set<Task> activeTasks = ConcurrentHashMap.newKeySet(); + private boolean closeComplete; + private Throwable closeFailure; + + private Session(String userId, String sessionId) { + spark = base.newSession(); + try { + holder = new SessionHolder(userId, sessionId, spark); + } catch (Throwable error) { + // Never close SparkSession: its clone shares the caller's SparkContext. Use the same + // owned-resource cleanup as a published session, retaining any partial cleanup failure + // for engine close even though this constructor cannot return a handle to JNI. + abandonUnpublished(error); + throw error; + } + } + + // Package-local so the unpublished ownership path can be exercised without breaking a + // Spark constructor. This cleanup deliberately never accesses the uninitialized holder. + void abandonUnpublished(Throwable error) { + sessions.add(this); + try { close(); } catch (Throwable cleanup) { recordFailure(error, cleanup); } + } + + private void ensureOpen() { + SparkJvmEngine.this.ensureOpen(); + if (released.get()) throw new EngineException(9, "JVM engine session is closed"); + } + + public Query prepare(byte[] relationBytes, Task task) { + Objects.requireNonNull(relationBytes, "relationBytes"); + return task.run(this, () -> { + // Preparation only analyzes read-only plans and registers a concurrent query handle. + // Share admission with metadata/config readers; config mutation and close stay exclusive. + catalog.readLock().lockInterruptibly(); + try { + Query query = new Query(this, analyzedFrame(relationBytes, task), task); + queries.add(query); + if (released.get()) { + query.close(); + ensureOpen(); + } + if (task.isCancelled()) { + query.close(); + task.check(); + } + return query; + } finally { + catalog.readLock().unlock(); + } + }); + } + + /** + * Analysis modes 0/1/2 are schema/local/streaming. A strict boolean byte precedes the same + * schema IPC used by prepare; schema and streaming modes return a zero prefix. + */ + public byte[] analyze(int opcode, byte[] relationBytes, Task task) { + Objects.requireNonNull(relationBytes, "relationBytes"); + return task.run(this, () -> { + if (opcode < 0 || opcode > 2) { + throw new EngineException(12, "unsupported analysis opcode: " + opcode); + } + catalog.readLock().lockInterruptibly(); + try { + Dataset<Row> frame = analyzedFrame(relationBytes, task); + PlanMetadata metadata = new PlanMetadata(this, frame); + byte[] output = new byte[metadata.schemaIpc.length + 1]; + output[0] = (byte) (opcode == 1 && metadata.local ? 1 : 0); + System.arraycopy(metadata.schemaIpc, 0, output, 1, metadata.schemaIpc.length); + synchronized (task) { + task.check(); + ensureOpen(); + task.complete(); + } + return output; + } finally { + catalog.readLock().unlock(); + } + }); + } + + // The caller holds a catalog read/write lock inside Task.run and its session/artifact scopes. + private Dataset<Row> analyzedFrame(byte[] relationBytes, Task task) throws IOException { + task.check(); + ensureOpen(); + if (Boolean.parseBoolean(spark.conf().get(SHUFFLE_FILE_CLEANUP))) { + throw new EngineException(12, SHUFFLE_FILE_CLEANUP + + " is unsupported with per-partition SQL execution scopes"); + } + Relation relation = Relation.parseFrom(relationBytes); + validateRelations(relation); + LogicalPlan logical = new SparkConnectPlanner(holder, Option.empty()) + .transformRelation(relation); + rejectCommands(logical); + // Dataset.ofRows uses ALL and may eagerly execute a write produced by analysis. + // Inspect with SKIP first, then keep that same execution through the Dataset constructor. + QueryExecution execution = spark.sessionState().executePlan(logical, CommandExecutionMode.SKIP()); + execution.assertAnalyzed(); + rejectCommands(execution.analyzed()); + Dataset<Row> frame = new Dataset<>(execution, Encoders.row(execution.analyzed().schema())); + if (frame.isStreaming()) { + throw new EngineException(12, "streaming queries are unsupported"); + } + return frame; + } + + private void rejectCommands(LogicalPlan logical) { + if (logical.exists(new AbstractFunction1<LogicalPlan, Object>() { + @Override + public Object apply(LogicalPlan node) { + // InsertIntoStatement extends ParsedStatement, and InsertIntoDir extends UnaryNode; + // neither is a Command until analysis. SQL scripts and dynamic SQL can execute + // their statements during analysis itself, before the post-analysis guard runs. + // CompoundBody already implements Command in the pinned assembly. Use actual types + // so a Spark internal API rename fails compilation instead of weakening the guard. + return node instanceof Command || node instanceof ParsedStatement + || node instanceof InsertIntoDir || node instanceof UnresolvedExecuteImmediate; + } + })) { + throw new EngineException(12, "SQL commands and external writes are unsupported"); + } + } + + /** + * Internal typed fields: BE u32 pair count, then UTF-8 key length/data and nullable value + * length/data (signed -1 means absent). No Spark Connect request/response envelopes cross here. + */ + public byte[] config(int opcode, byte[] fields, Task task) { + List<Pair> input = decodePairs(fields); + return task.run(this, () -> { + Lock access = configLock(opcode); + access.lockInterruptibly(); + try { + task.check(); + ensureOpen(); + List<Pair> output = new ArrayList<>(); + switch (opcode) { + case 1: + for (Pair pair : input) output.add(new Pair(pair.key, spark.conf().get(pair.key))); + break; + case 2: + for (Pair pair : input) { + Option<String> value = spark.conf().getOption(pair.key); + output.add(new Pair(pair.key, value.isDefined() ? value.get() : null)); + } + break; + case 3: + for (Pair pair : input) { + output.add(new Pair(pair.key, spark.conf().get(pair.key, pair.value))); + } + break; + case 4: + if (input.size() > 1) throw new EngineException(3, "getAll accepts one prefix"); + String prefix = input.isEmpty() ? "" : input.get(0).key; + spark.conf().getAllAsJava().entrySet().stream() + .filter(entry -> entry.getKey().startsWith(prefix)) + .sorted(Map.Entry.comparingByKey()) + .forEach(entry -> output.add(new Pair( + entry.getKey().substring(prefix.length()), entry.getValue()))); + break; + case 5: + for (Pair pair : input) { + output.add(new Pair(pair.key, Boolean.toString(spark.conf().isModifiable(pair.key)))); + } + break; + case 6: + case 7: + applyConfig(opcode, input, task); + break; + default: + throw new EngineException(12, "unsupported config opcode: " + opcode); + } + task.complete(); + return encodePairs(output); + } finally { + access.unlock(); + } + }); + } + + private Lock configLock(int opcode) { + // JNI contract: 1..5 are reads; 6..7 mutate. Unknown opcodes cannot come from Rust; + // conservatively keep them exclusive until the task's normal validation rejects them. + switch (opcode) { + case 1: + case 2: + case 3: + case 4: + case 5: + return catalog.readLock(); + default: + return catalog.writeLock(); + } + } + + private void applyConfig(int opcode, List<Pair> input, Task task) { + Map<String, String> previous = new LinkedHashMap<>(); + Set<String> attempted = new LinkedHashSet<>(); + Map<String, String> explicit = spark.conf().getAllAsJava(); + for (Pair pair : input) { + if (opcode == 6 && pair.value == null) throw new EngineException(3, "missing config value"); + if (!previous.containsKey(pair.key)) previous.put(pair.key, explicit.get(pair.key)); + } + task.check(); + try { + for (Pair pair : input) { + task.check(); + // A setter can modify state before throwing, so record its key before calling it. + attempted.add(pair.key); + // RuntimeConfig accepts unregistered spark.* keys even when isModifiable is false; + // let its setters reject static/core entries and invalid registered values. Only this + // input-validation boundary maps an unstructured IllegalArgumentException to a client + // error; the same exception from arbitrary Spark execution is INTERNAL. + try { + if (opcode == 6) spark.conf().set(pair.key, pair.value); + else spark.conf().unset(pair.key); + } catch (IllegalArgumentException error) { + if (error instanceof SparkThrowable && ((SparkThrowable) error).isInternalError()) { + throw error; + } + throw new EngineException(3, error.getMessage(), error); + } + } + synchronized (task) { + task.check(); + task.complete(); + } + } catch (Throwable error) { + Map<String, String> current = null; + try { current = spark.conf().getAllAsJava(); } catch (Throwable inspection) { + recordFailure(error, inspection); + } + for (String key : attempted) { + String value = previous.get(key); + // Skip rejected static entries and other unchanged keys. If inspection failed, + // conservatively restore every attempted key; unvisited keys never need rollback. + if (current != null && Objects.equals(value, current.get(key))) continue; + try { + if (value == null) spark.conf().unset(key); + else spark.conf().set(key, value); + } catch (Throwable rollback) { + if (rollback != error) error.addSuppressed(rollback); + } + } + throw error; + } + } + + @Override + public synchronized void close() { + throwFailure(closeFailure); + if (closeComplete) return; + released.set(true); + Throwable failure = null; + for (Task task : activeTasks) { + try { task.cancel(); } catch (Throwable error) { failure = recordFailure(failure, error); } + } + for (Query query : queries) { + try { query.close(); } catch (Throwable error) { failure = recordFailure(failure, error); } + } + // A partial Spark cleanup is not generally replayable (for example, artifact cache + // cleanup decrements reference counts). Preserve the failure and its owners instead. + if (failure == null) { + catalog.writeLock().lock(); + try { + // These resources belong to this newSession only. Never close SessionHolder or Spark. + try { + spark.sessionState().catalog().clearTempTables(); + } catch (Throwable error) { + failure = recordFailure(failure, error); + } + try { + spark.artifactManager().close(); + } catch (Throwable error) { + failure = recordFailure(failure, error); + } + } finally { + catalog.writeLock().unlock(); + } + } + closeFailure = failure; + throwFailure(failure); + sessions.remove(this); + closeComplete = true; + } + } + + /** Shared metadata evaluation order for analysis and executable query preparation. */ + private static final class PlanMetadata { + private final StructType schema; + private final String timeZone; + private final boolean largeVarTypes; + private final int maxRows; + private final boolean local; + private final byte[] schemaIpc; + + private PlanMetadata(Session session, Dataset<Row> frame) { + schema = frame.schema(); + validateResultType(schema); + timeZone = session.spark.sessionState().conf().sessionLocalTimeZone(); + largeVarTypes = session.spark.sessionState().conf().arrowUseLargeVarTypes(); + int configured = session.spark.sessionState().conf().arrowMaxRecordsPerBatch(); + maxRows = configured > 0 ? configured : MAX_BATCH_ROWS; + local = frame.isLocal(); + schemaIpc = createSchemaIpc(schema, timeZone, largeVarTypes); + } + } + + /** An analyzed Catalyst query and a lazy pull cursor. Only one caller may fetch at a time. */ + public final class Query implements AutoCloseable { + private final Session session; + private final QueryExecution execution; + private final ArrowPartitionConverter converter; + private final Task task; + private final byte[] schemaIpc; + private final boolean local; + private final ReentrantLock cursor = new ReentrantLock(); + private boolean released; + private Throwable closeFailure; + private boolean ended; + private Throwable pullFailure; + private SparkPlan plan; + private boolean planCleanupAttempted; + private JavaRDD<Tuple2<byte[], Long>> arrowPartitions; + private int nextPartition; + private ArrayDeque<Tuple2<byte[], Long>> partitionBatches; + + private Query(Session session, Dataset<Row> frame, Task task) { + this.session = session; + this.execution = frame.queryExecution(); + PlanMetadata metadata = new PlanMetadata(session, frame); + this.converter = new ArrowPartitionConverter( + metadata.schema, metadata.timeZone, metadata.largeVarTypes, metadata.maxRows); + this.task = task; + this.local = metadata.local; + this.schemaIpc = metadata.schemaIpc; + } + + public byte[] schemaIpc() { return schemaIpc.clone(); } + public boolean isLocal() { return local; } + public boolean isStreaming() { return false; } + + private void loadNextPartition() { + task.check(); + SQLExecution.withNewExecutionId(execution, + Option.apply("spark-connect-engine-arrow-partition"), + new AbstractFunction0<Object>() { + @Override + public Object apply() { + if (arrowPartitions == null) { + if (plan == null) plan = execution.executedPlan(); + ClassTag<Tuple2<byte[], Long>> batchesClass = ClassTag$.MODULE$.apply(Tuple2.class); + arrowPartitions = JavaRDD.fromRDD( + plan.execute().mapPartitionsInternal(converter, false, batchesClass), + batchesClass); + } + if (nextPartition < arrowPartitions.getNumPartitions()) { + // The pending heap owner is one partition, matching Spark's local iterator. + // Conversion happens before transfer, avoiding compressed UnsafeRow round trips. + List<Tuple2<byte[], Long>>[] fetched = + arrowPartitions.collectPartitions(new int[] {nextPartition}); + task.check(); + nextPartition++; + partitionBatches = new ArrayDeque<>(fetched[0]); + } + return null; + } + }); + } + + /** Pull a self-contained IPC batch produced by Spark's executor-side converter. */ + public NativeIpcBatch nextIpcBatch() { + return task.run(session, () -> { + cursor.lockInterruptibly(); + try { + throwFailure(pullFailure); + if (released) throw new EngineException(9, "query cursor is closed"); + if (ended) return null; + task.beginExecution(); + try { + while (partitionBatches == null || partitionBatches.isEmpty()) { + partitionBatches = null; + if (arrowPartitions != null && nextPartition == arrowPartitions.getNumPartitions()) { + ended = true; + task.complete(); + return null; + } + loadNextPartition(); + } + task.check(); + Tuple2<byte[], Long> batch = partitionBatches.removeFirst(); + return new NativeIpcBatch(batch._1(), batch._2()); + } catch (Throwable error) { + pullFailure = error instanceof InterruptedException + ? new EngineException(1, "JVM engine operation was interrupted", error) + : error instanceof Exception ? task.taskError((Exception) error) : error; + partitionBatches = null; + arrowPartitions = null; + ended = true; + throwFailure(pullFailure); + return null; + } + } finally { + cursor.unlock(); + } + }); + } + + @Override + public void close() { + Throwable failure = null; + try { task.close(); } catch (Throwable error) { failure = error; } + cursor.lock(); + try { + // Release buffered results and never replay partial plan cleanup. + partitionBatches = null; + arrowPartitions = null; + released = true; + if (!planCleanupAttempted) { + planCleanupAttempted = true; + try { + if (plan != null) plan.cleanupResources(); + } catch (Throwable error) { + failure = recordFailure(failure, error); + } + } + closeFailure = failure == null ? closeFailure : recordFailure(closeFailure, failure); + throwFailure(closeFailure); + session.queries.remove(this); + } finally { + cursor.unlock(); + } + } + } + + private static byte[] createSchemaIpc(StructType schema, String timeZone, boolean largeVarTypes) { + return checkedIpc(ArrowConverters$.MODULE$.createEmptyArrowBatch( + schema, timeZone, false, largeVarTypes)); + } + + // Package-local so tests can cover exact Spark types that earlier Spark planning can normalize. + static void validateResultType(DataType type) { + if (type instanceof UserDefinedType || type instanceof CharType || type instanceof VarcharType + || (type instanceof StringType && ((StringType) type).collationId() + != ((StringType) DataTypes.StringType).collationId())) { + throw new EngineException(12, "result type cannot be preserved by Arrow schema transport: " + + type.catalogString()); + } + if (type instanceof StructType) { + StructType original = (StructType) type; + StructField[] fields = org.apache.spark.sql.catalyst.util.package$.MODULE$ + .removeInternalMetadata(original).fields(); + for (int i = 0; i < fields.length; i++) { + StructField field = fields[i]; + // CHAR/VARCHAR's raw type annotation is semantic even though its name is internal. + if (original.fields()[i].metadata().contains("__CHAR_VARCHAR_TYPE_STRING")) { + throw new EngineException(12, + "CHAR/VARCHAR result metadata cannot be preserved by Arrow schema transport: " + + field.name()); + } + if (!field.metadata().isEmpty()) { + throw new EngineException(12, + "result field metadata cannot be preserved by Arrow schema transport: " + field.name()); + } + validateResultType(field.dataType()); + } + } else if (type instanceof ArrayType) { + validateResultType(((ArrayType) type).elementType()); + } else if (type instanceof MapType) { + validateResultType(((MapType) type).keyType()); + validateResultType(((MapType) type).valueType()); + } + } + + static byte[] checkedIpc(byte[] bytes) { + if (bytes.length > MAX_IPC_BYTES) throw new EngineException(8, "Arrow batch exceeds 64 MiB"); + return bytes; + } + + private static Throwable recordFailure(Throwable previous, Throwable error) { + if (previous == null) return error; + if (previous != error) previous.addSuppressed(error); + return previous; + } + + private static void throwFailure(Throwable failure) { + if (failure instanceof Error) throw (Error) failure; + if (failure instanceof RuntimeException) throw (RuntimeException) failure; + if (failure != null) throw new EngineException(13, "JVM engine cleanup failed", failure); + } + + private static void validateRelations(Message message) { + if (message instanceof Relation) { + Relation relation = (Relation) message; + String kind = relation.getRelTypeCase().name(); + if (!RELATIONS.contains(kind)) { + throw new EngineException(12, "unsupported JVM engine relation: " + kind); + } + if (relation.hasRead() && !relation.getRead().hasNamedTable()) { + throw new EngineException(12, "only named-table reads are supported in this prototype"); + } + } + String type = message.getDescriptorForType().getFullName(); + if (type.endsWith("CommonInlineUserDefinedFunction") || type.endsWith("CommonInlineUserDefinedTableFunction")) { + throw new EngineException(12, "user-defined functions are unsupported in this prototype"); + } + for (Object field : message.getAllFields().values()) { + if (field instanceof Message) validateRelations((Message) field); + else if (field instanceof List<?>) { + for (Object item : (List<?>) field) { + if (item instanceof Message) validateRelations((Message) item); + } + } + } + } + + private static final class Pair { + private final String key; + private final String value; + private Pair(String key, String value) { this.key = key; this.value = value; } + } + + private static List<Pair> decodePairs(byte[] bytes) { + Objects.requireNonNull(bytes, "fields"); + if (bytes.length > MAX_IPC_BYTES) throw new EngineException(8, "config fields exceed 64 MiB"); + try (DataInputStream input = new DataInputStream(new ByteArrayInputStream(bytes))) { + int count = input.readInt(); + if (count < 0 || count > MAX_CONFIG_FIELDS || count > input.available() / 8) { Review Comment: Fixed in [dce536e8d00a747b8f23df0e663fbcbca962c3cc](https://github.com/apache/spark-connect-rust/commit/dce536e8d00a747b8f23df0e663fbcbca962c3cc). The arbitrary 10,000-pair cap is removed. The 64 MiB encoded-payload bound and count-versus-remaining-bytes checks remain. Regression tests accept 10,001 well-formed pairs and reject malformed counts. ########## crates/spark-connect-server/jni/native/bridge.c: ########## @@ -0,0 +1,986 @@ +// 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. + +#include "bridge.h" + +#include <jni.h> +#include <inttypes.h> +#include <limits.h> +#include <pthread.h> +#include <stdatomic.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +typedef struct { + JavaVM *vm; + jobject loader; + jclass thread_class; + jmethodID current_thread; + jmethodID get_loader; + jmethodID set_loader; + atomic_uint references; +} JavaContext; + +typedef struct { + JavaContext *context; + JNIEnv *env; + jobject thread; + jobject previous_loader; + int attached; + int framed; + int loader_changed; +} JavaScope; + +typedef struct { + JavaContext *context; + pthread_t owner; + int attached; +} EngineThread; + +extern int64_t spark_connect_engine_start(const uint8_t *, size_t, void *, BridgeBuffer *); +extern int spark_connect_address(int64_t, BridgeBuffer *, BridgeBuffer *); +extern int spark_connect_stop(int64_t, BridgeBuffer *); + +static void clear_buffer(BridgeBuffer *buffer) { + if (buffer != NULL) { + buffer->data = NULL; + buffer->len = 0; + } +} + +static void set_error(BridgeBuffer *error, const char *message) { + if (error == NULL || error->data != NULL) { + return; + } + size_t len = strlen(message); + uint8_t *data = malloc(len == 0 ? 1 : len); + if (data != NULL) { + memcpy(data, message, len); + error->data = data; + error->len = len; + } +} + +void spark_connect_buffer_free(BridgeBuffer *buffer) { + if (buffer != NULL) { + free(buffer->data); + clear_buffer(buffer); + } +} + +/* GetStringUTFChars uses modified UTF-8, so encode UTF-16 explicitly instead. */ +static int string_buffer(JNIEnv *env, jstring value, BridgeBuffer *out) { + jsize len = (*env)->GetStringLength(env, value); + const jchar *chars = (*env)->GetStringChars(env, value, NULL); + if (chars == NULL) { + return -1; + } + uint8_t *data = malloc((size_t) len * 3 + 1); + if (data == NULL) { + (*env)->ReleaseStringChars(env, value, chars); + return -1; + } + size_t written = 0; + for (jsize i = 0; i < len; i++) { + uint32_t code = chars[i]; + if (code >= 0xd800 && code <= 0xdbff && i + 1 < len + && chars[i + 1] >= 0xdc00 && chars[i + 1] <= 0xdfff) { + code = 0x10000 + ((code - 0xd800) << 10) + chars[++i] - 0xdc00; + } else if (code >= 0xd800 && code <= 0xdfff) { + code = 0xfffd; + } + if (code < 0x80) { + data[written++] = (uint8_t) code; + } else if (code < 0x800) { + data[written++] = (uint8_t) (0xc0 | (code >> 6)); + data[written++] = (uint8_t) (0x80 | (code & 0x3f)); + } else if (code < 0x10000) { + data[written++] = (uint8_t) (0xe0 | (code >> 12)); + data[written++] = (uint8_t) (0x80 | ((code >> 6) & 0x3f)); + data[written++] = (uint8_t) (0x80 | (code & 0x3f)); + } else { + data[written++] = (uint8_t) (0xf0 | (code >> 18)); + data[written++] = (uint8_t) (0x80 | ((code >> 12) & 0x3f)); + data[written++] = (uint8_t) (0x80 | ((code >> 6) & 0x3f)); + data[written++] = (uint8_t) (0x80 | (code & 0x3f)); + } + } + (*env)->ReleaseStringChars(env, value, chars); + out->data = data; + out->len = written; + return 0; +} + +static int exception_error(JNIEnv *env, BridgeBuffer *error) { + if (!(*env)->ExceptionCheck(env)) { + return 0; + } + jthrowable throwable = (*env)->ExceptionOccurred(env); + (*env)->ExceptionClear(env); + jclass type = throwable == NULL ? NULL : (*env)->GetObjectClass(env, throwable); + jmethodID to_string = type == NULL ? NULL + : (*env)->GetMethodID(env, type, "toString", "()Ljava/lang/String;"); + jstring description = to_string == NULL ? NULL + : (*env)->CallObjectMethod(env, throwable, to_string); + if (!(*env)->ExceptionCheck(env) && description != NULL && error != NULL + && error->data == NULL) { + (void) string_buffer(env, description, error); + } + if ((*env)->ExceptionCheck(env)) { + (*env)->ExceptionClear(env); + } + if (description != NULL) (*env)->DeleteLocalRef(env, description); + if (type != NULL) (*env)->DeleteLocalRef(env, type); + if (throwable != NULL) (*env)->DeleteLocalRef(env, throwable); + set_error(error, "Java bridge operation failed"); + return -1; +} + +static void scope_restore_loader(JavaScope *scope) { + JNIEnv *env = scope->env; + if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); + if (scope->loader_changed) { + (*env)->CallVoidMethod(env, scope->thread, scope->context->set_loader, + scope->previous_loader); + if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); + scope->loader_changed = 0; + } +} + +static void scope_leave(JavaScope *scope) { + if (scope->env == NULL) return; + JNIEnv *env = scope->env; + scope_restore_loader(scope); + if (scope->previous_loader != NULL) (*env)->DeleteLocalRef(env, scope->previous_loader); + if (scope->thread != NULL) (*env)->DeleteLocalRef(env, scope->thread); + if (scope->framed) (*env)->PopLocalFrame(env, NULL); + if (scope->attached) (*scope->context->vm)->DetachCurrentThread(scope->context->vm); + scope->env = NULL; +} + +static int scope_enter(JavaContext *context, JavaScope *scope, BridgeBuffer *error) { + memset(scope, 0, sizeof(*scope)); + scope->context = context; + jint state = (*context->vm)->GetEnv(context->vm, (void **) &scope->env, JNI_VERSION_1_8); + if (state == JNI_EDETACHED) { + if ((*context->vm)->AttachCurrentThreadAsDaemon( + context->vm, (void **) &scope->env, NULL) != JNI_OK) { + scope->env = NULL; + set_error(error, "cannot attach Rust worker to JVM"); + return -1; + } + scope->attached = 1; + } else if (state != JNI_OK) { + scope->env = NULL; + set_error(error, "cannot access JVM from Rust worker"); + return -1; + } + JNIEnv *env = scope->env; + if ((*env)->PushLocalFrame(env, 32) < 0) { + (void) exception_error(env, error); + set_error(error, "cannot allocate Java local reference frame"); + goto failed; + } + scope->framed = 1; + scope->thread = (*env)->CallStaticObjectMethod(env, context->thread_class, + context->current_thread); + if (exception_error(env, error) != 0 || scope->thread == NULL) goto failed; + scope->previous_loader = (*env)->CallObjectMethod(env, scope->thread, context->get_loader); + if (exception_error(env, error) != 0) goto failed; + if (!(*env)->IsSameObject(env, scope->previous_loader, context->loader)) { + (*env)->CallVoidMethod(env, scope->thread, context->set_loader, context->loader); + if (exception_error(env, error) != 0) goto failed; + scope->loader_changed = 1; + } + return 0; +failed: + set_error(error, "cannot prepare JVM worker context"); + scope_leave(scope); + return -1; +} + +static void context_release(JavaContext *context) { + if (atomic_fetch_sub_explicit(&context->references, 1, memory_order_acq_rel) != 1) return; + // The factory cannot be freed while worker guards exist. Consequently detach + // never owns the last context reference, and must not reattach just to destroy it. + // Preserve an unexpected orphan rather than deleting globals without a valid env. + atomic_store_explicit(&context->references, 1, memory_order_release); + fputs("JNI cleanup is incomplete; retained cleanup failed: orphaned Java worker context\n", + stderr); +} + +static jbyteArray byte_array(JNIEnv *env, const uint8_t *data, size_t len, + BridgeBuffer *error) { + if (len > INT_MAX || (len != 0 && data == NULL)) { + set_error(error, "Java bridge byte array is too large or invalid"); + return NULL; + } + jbyteArray array = (*env)->NewByteArray(env, (jsize) len); + if (exception_error(env, error) != 0 || array == NULL) return NULL; + if (len != 0) (*env)->SetByteArrayRegion(env, array, 0, (jsize) len, (const jbyte *) data); + if (exception_error(env, error) != 0) { + (*env)->DeleteLocalRef(env, array); + return NULL; + } + return array; +} + +static jstring utf8_string(JNIEnv *env, const uint8_t *data, size_t len, + BridgeBuffer *error) { + jbyteArray bytes = byte_array(env, data, len, error); + if (bytes == NULL) return NULL; + jclass type = (*env)->FindClass(env, "java/lang/String"); + jmethodID constructor = type == NULL ? NULL + : (*env)->GetMethodID(env, type, "<init>", "([BLjava/lang/String;)V"); + jstring encoding = constructor == NULL ? NULL : (*env)->NewStringUTF(env, "UTF-8"); + jstring value = NULL; + if (exception_error(env, error) == 0 && encoding != NULL) { + value = (*env)->NewObject(env, type, constructor, bytes, encoding); + if (exception_error(env, error) != 0) value = NULL; + } + if (encoding != NULL) (*env)->DeleteLocalRef(env, encoding); + if (type != NULL) (*env)->DeleteLocalRef(env, type); + (*env)->DeleteLocalRef(env, bytes); + return value; +} + +static int array_buffer(JNIEnv *env, jbyteArray array, BridgeBuffer *out, + BridgeBuffer *error) { + jsize len = (*env)->GetArrayLength(env, array); + if (exception_error(env, error) != 0) return -1; + uint8_t *data = malloc(len == 0 ? 1 : (size_t) len); + if (data == NULL) { + set_error(error, "cannot allocate Java bridge buffer"); + return -1; + } + if (len != 0) (*env)->GetByteArrayRegion(env, array, 0, len, (jbyte *) data); + if (exception_error(env, error) != 0) { + free(data); + return -1; + } + out->data = data; + out->len = (size_t) len; + return 0; +} + +static void throw_error(JNIEnv *env, BridgeBuffer *error) { + if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); + if (error->data == NULL) set_error(error, "native Spark Connect operation failed"); + jstring message = utf8_string(env, error->data, error->len, NULL); + jclass type = (*env)->FindClass(env, "java/lang/IllegalStateException"); + if (!(*env)->ExceptionCheck(env) && message != NULL && type != NULL) { + jmethodID constructor = (*env)->GetMethodID(env, type, "<init>", "(Ljava/lang/String;)V"); + if (!(*env)->ExceptionCheck(env) && constructor != NULL) { + jthrowable throwable = (*env)->NewObject(env, type, constructor, message); + if (!(*env)->ExceptionCheck(env) && throwable != NULL) { + (*env)->Throw(env, throwable); + (*env)->DeleteLocalRef(env, throwable); + } + } + } + if (message != NULL) (*env)->DeleteLocalRef(env, message); + if (type != NULL) (*env)->DeleteLocalRef(env, type); + spark_connect_buffer_free(error); +} + +void *spark_connect_engine_native_address(void *raw_env, void *clazz, int64_t id) { + (void) clazz; + JNIEnv *env = raw_env; + BridgeBuffer address = {0}; + BridgeBuffer error = {0}; + if (spark_connect_address(id, &address, &error) != 0) { + spark_connect_buffer_free(&address); + throw_error(env, &error); + return NULL; + } + jbyteArray result = byte_array(env, address.data, address.len, &error); + spark_connect_buffer_free(&address); + if (result == NULL) throw_error(env, &error); + else spark_connect_buffer_free(&error); + return result; +} + +void spark_connect_engine_native_stop(void *raw_env, void *clazz, int64_t id) { + (void) clazz; + BridgeBuffer error = {0}; + if (spark_connect_stop(id, &error) != 0) throw_error(raw_env, &error); + else spark_connect_buffer_free(&error); +} + +/* Typed JVM query engine implementation. */ +typedef enum { + ENGINE_FACTORY, + ENGINE_TASK, + ENGINE_SESSION, + ENGINE_QUERY, + ENGINE_EXCEPTION, + ENGINE_BATCH, + ENGINE_CLASS_COUNT +} EngineKind; + +typedef struct { + JavaContext *context; + atomic_uint references; + jclass classes[ENGINE_CLASS_COUNT]; + jmethodID close[ENGINE_EXCEPTION]; + jmethodID new_task; + jmethodID open_session; + jmethodID prepare; + jmethodID analyze; + jmethodID config; + jmethodID schema; + jmethodID next_ipc; + jmethodID batch_data; + jmethodID batch_row_count; + jmethodID cancel; + jmethodID exception_code; +} EngineApi; + +typedef struct { + EngineApi *api; + jobject object; + EngineKind kind; +} EngineHandle; + +static void engine_error_bytes(BridgeBuffer *error, int code, + const uint8_t *message, size_t len) { + if (error == NULL || error->data != NULL) return; + char prefix[40]; + int prefix_len = snprintf(prefix, sizeof(prefix), "JVM_ENGINE_ERROR:%d:", code); + if (prefix_len < 0 || (size_t) prefix_len >= sizeof(prefix) + || len > SIZE_MAX - (size_t) prefix_len) return; + uint8_t *data = malloc((size_t) prefix_len + len); + if (data == NULL) return; + memcpy(data, prefix, (size_t) prefix_len); + if (len != 0) memcpy(data + prefix_len, message, len); + error->data = data; + error->len = (size_t) prefix_len + len; +} + +static void engine_error(BridgeBuffer *error, int code, const char *message) { + engine_error_bytes(error, code, (const uint8_t *) message, strlen(message)); +} + +/* Shared low-level helpers report plain text. Frame it at this ABI's boundary. */ +static void engine_normalize_error(BridgeBuffer *error, const char *fallback) { + static const char prefix[] = "JVM_ENGINE_ERROR:"; + if (error == NULL) return; + if (error->len >= sizeof(prefix) - 1 && error->data != NULL + && memcmp(error->data, prefix, sizeof(prefix) - 1) == 0) return; + BridgeBuffer previous = *error; + clear_buffer(error); + if (previous.data != NULL) { + engine_error_bytes(error, 13, previous.data, previous.len); + spark_connect_buffer_free(&previous); + } else { + engine_error(error, 13, fallback); + } +} + +static int engine_exception(JNIEnv *env, EngineApi *api, BridgeBuffer *error) { + if (!(*env)->ExceptionCheck(env)) return 0; + jthrowable throwable = (*env)->ExceptionOccurred(env); + (*env)->ExceptionClear(env); + int code = 13; + int typed = throwable != NULL && api != NULL + && api->classes[ENGINE_EXCEPTION] != NULL && api->exception_code != NULL + && (*env)->IsInstanceOf(env, throwable, api->classes[ENGINE_EXCEPTION]); + if (typed) { + jint reported = (*env)->CallIntMethod(env, throwable, api->exception_code); + if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); + else if (reported >= 1 && reported <= 16) code = reported; + } + jclass type = throwable == NULL ? NULL : (*env)->GetObjectClass(env, throwable); + if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); + jmethodID describe = type == NULL ? NULL : (*env)->GetMethodID(env, type, + typed ? "getMessage" : "toString", "()Ljava/lang/String;"); + if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); + jstring description = describe == NULL ? NULL + : (*env)->CallObjectMethod(env, throwable, describe); + if ((*env)->ExceptionCheck(env)) { + (*env)->ExceptionClear(env); + description = NULL; + } + BridgeBuffer message = {0}; + if (description != NULL) (void) string_buffer(env, description, &message); + if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); + if (message.data != NULL) engine_error_bytes(error, code, message.data, message.len); + else engine_error(error, code, "Java engine operation failed"); + spark_connect_buffer_free(&message); + if (description != NULL) (*env)->DeleteLocalRef(env, description); + if (type != NULL) (*env)->DeleteLocalRef(env, type); + if (throwable != NULL) (*env)->DeleteLocalRef(env, throwable); + return -1; +} + +static void engine_delete_classes(JNIEnv *env, EngineApi *api) { + for (int i = 0; i < ENGINE_CLASS_COUNT; i++) { + if (api->classes[i] != NULL) (*env)->DeleteGlobalRef(env, api->classes[i]); + } +} + +static void engine_api_release(JNIEnv *env, EngineApi *api) { + if (atomic_fetch_sub_explicit(&api->references, 1, memory_order_acq_rel) != 1) return; + // Startup already supplies a valid Java environment. Do not risk another + // attachment after disposing the last handle. + engine_delete_classes(env, api); + JavaContext *context = api->context; + if (atomic_fetch_sub_explicit(&context->references, 1, memory_order_acq_rel) == 1) { + if (context->loader != NULL) (*env)->DeleteGlobalRef(env, context->loader); + (*env)->DeleteGlobalRef(env, context->thread_class); + free(context); + } + free(api); +} + +static jclass engine_class(JNIEnv *env, EngineApi *api, const char *name, + BridgeBuffer *error) { + jclass local = (*env)->FindClass(env, name); + if (engine_exception(env, api, error) != 0 || local == NULL) return NULL; + jclass global = (*env)->NewGlobalRef(env, local); + (*env)->DeleteLocalRef(env, local); + if (engine_exception(env, api, error) != 0) return NULL; + return global; +} + +static int engine_method(JNIEnv *env, EngineApi *api, EngineKind kind, + jmethodID *out, const char *name, const char *signature, BridgeBuffer *error) { + *out = (*env)->GetMethodID(env, api->classes[kind], name, signature); + if (engine_exception(env, api, error) != 0 || *out == NULL) return -1; + return 0; +} + +static EngineHandle *engine_handle(JNIEnv *env, EngineApi *api, jobject object, + EngineKind kind, BridgeBuffer *error) { + EngineHandle *handle = calloc(1, sizeof(*handle)); + if (handle != NULL) { + handle->object = (*env)->NewGlobalRef(env, object); + (void) engine_exception(env, api, error); + } + if (handle == NULL || handle->object == NULL) { + engine_error(error, 13, "cannot retain Java engine handle"); + (*env)->CallVoidMethod(env, object, api->close[kind]); + (void) engine_exception(env, api, NULL); + free(handle); + return NULL; + } + handle->api = api; + handle->kind = kind; + atomic_fetch_add_explicit(&api->references, 1, memory_order_relaxed); + return handle; +} + +static EngineHandle *engine_factory(JNIEnv *env, jobject factory, BridgeBuffer *error) { + EngineApi *api = calloc(1, sizeof(*api)); + JavaContext *context = calloc(1, sizeof(*context)); + if (api == NULL || context == NULL) { + free(api); + free(context); + engine_error(error, 13, "cannot allocate Java engine context"); + return NULL; + } + api->context = context; + atomic_init(&api->references, 1); + atomic_init(&context->references, 1); + if ((*env)->GetJavaVM(env, &context->vm) != JNI_OK) goto failed; + context->thread_class = engine_class(env, api, "java/lang/Thread", error); + if (context->thread_class == NULL) goto failed; + context->current_thread = (*env)->GetStaticMethodID(env, context->thread_class, + "currentThread", "()Ljava/lang/Thread;"); + if (engine_exception(env, api, error) != 0 || context->current_thread == NULL) goto failed; + context->get_loader = (*env)->GetMethodID(env, context->thread_class, + "getContextClassLoader", "()Ljava/lang/ClassLoader;"); + if (engine_exception(env, api, error) != 0 || context->get_loader == NULL) goto failed; + context->set_loader = (*env)->GetMethodID(env, context->thread_class, + "setContextClassLoader", "(Ljava/lang/ClassLoader;)V"); + if (engine_exception(env, api, error) != 0 || context->set_loader == NULL) goto failed; + jobject current = (*env)->CallStaticObjectMethod(env, context->thread_class, + context->current_thread); + if (engine_exception(env, api, error) != 0 || current == NULL) goto failed; + jobject loader = (*env)->CallObjectMethod(env, current, context->get_loader); + (*env)->DeleteLocalRef(env, current); + if (engine_exception(env, api, error) != 0) goto failed; + if (loader != NULL) { + context->loader = (*env)->NewGlobalRef(env, loader); + (*env)->DeleteLocalRef(env, loader); + if (engine_exception(env, api, error) != 0 || context->loader == NULL) goto failed; + } + jclass factory_class = (*env)->GetObjectClass(env, factory); + if (engine_exception(env, api, error) != 0 || factory_class == NULL) goto failed; + api->classes[ENGINE_FACTORY] = (*env)->NewGlobalRef(env, factory_class); + (*env)->DeleteLocalRef(env, factory_class); + if (engine_exception(env, api, error) != 0 || api->classes[ENGINE_FACTORY] == NULL) goto failed; + api->classes[ENGINE_TASK] = engine_class(env, api, + "org/apache/spark/sql/connect/nativebridge/engine/SparkJvmEngine$Task", error); + if (api->classes[ENGINE_TASK] == NULL) goto failed; + api->classes[ENGINE_SESSION] = engine_class(env, api, + "org/apache/spark/sql/connect/nativebridge/engine/SparkJvmEngine$Session", error); + if (api->classes[ENGINE_SESSION] == NULL) goto failed; + api->classes[ENGINE_QUERY] = engine_class(env, api, + "org/apache/spark/sql/connect/nativebridge/engine/SparkJvmEngine$Query", error); + if (api->classes[ENGINE_QUERY] == NULL) goto failed; + api->classes[ENGINE_BATCH] = engine_class(env, api, + "org/apache/spark/sql/connect/nativebridge/engine/NativeIpcBatch", error); + if (api->classes[ENGINE_BATCH] == NULL) goto failed; + api->classes[ENGINE_EXCEPTION] = engine_class(env, api, + "org/apache/spark/sql/connect/nativebridge/engine/SparkJvmEngine$EngineException", error); + if (api->classes[ENGINE_EXCEPTION] == NULL) goto failed; + for (int i = ENGINE_FACTORY; i < ENGINE_EXCEPTION; i++) { + if (engine_method(env, api, (EngineKind) i, &api->close[i], "close", "()V", error) != 0) + goto failed; + } + if (engine_method(env, api, ENGINE_EXCEPTION, &api->exception_code, "code", "()I", error) != 0 + || engine_method(env, api, ENGINE_FACTORY, &api->new_task, "newTask", + "(Ljava/lang/String;)Lorg/apache/spark/sql/connect/nativebridge/engine/SparkJvmEngine$Task;", + error) != 0 + || engine_method(env, api, ENGINE_FACTORY, &api->open_session, "openSession", + "(Ljava/lang/String;Ljava/lang/String;Lorg/apache/spark/sql/connect/nativebridge/engine/SparkJvmEngine$Task;)Lorg/apache/spark/sql/connect/nativebridge/engine/SparkJvmEngine$Session;", + error) != 0 + || engine_method(env, api, ENGINE_SESSION, &api->prepare, "prepare", + "([BLorg/apache/spark/sql/connect/nativebridge/engine/SparkJvmEngine$Task;)Lorg/apache/spark/sql/connect/nativebridge/engine/SparkJvmEngine$Query;", + error) != 0 + || engine_method(env, api, ENGINE_SESSION, &api->analyze, "analyze", + "(I[BLorg/apache/spark/sql/connect/nativebridge/engine/SparkJvmEngine$Task;)[B", + error) != 0 + || engine_method(env, api, ENGINE_SESSION, &api->config, "config", + "(I[BLorg/apache/spark/sql/connect/nativebridge/engine/SparkJvmEngine$Task;)[B", + error) != 0 + || engine_method(env, api, ENGINE_TASK, &api->cancel, "cancel", "()V", error) != 0 + || engine_method(env, api, ENGINE_QUERY, &api->schema, "schemaIpc", "()[B", error) != 0 + || engine_method(env, api, ENGINE_QUERY, &api->next_ipc, "nextIpcBatch", + "()Lorg/apache/spark/sql/connect/nativebridge/engine/NativeIpcBatch;", error) != 0 + || engine_method(env, api, ENGINE_BATCH, &api->batch_data, "data", "()[B", error) != 0 + || engine_method(env, api, ENGINE_BATCH, &api->batch_row_count, "rowCount", "()J", error) != 0) + goto failed; + EngineHandle *handle = engine_handle(env, api, factory, ENGINE_FACTORY, error); + engine_api_release(env, api); + return handle; +failed: + (void) engine_exception(env, api, error); + engine_normalize_error(error, "cannot initialize Java engine ABI"); + engine_delete_classes(env, api); + if (context->loader != NULL) (*env)->DeleteGlobalRef(env, context->loader); + if (context->thread_class != NULL) (*env)->DeleteGlobalRef(env, context->thread_class); + free(context); + free(api); + return NULL; +} + +static int engine_check(EngineHandle *handle, EngineKind kind, BridgeBuffer *error) { + if (handle != NULL && handle->kind == kind) return 0; + engine_error(error, 13, "invalid Java engine handle"); + return -1; +} + +static int engine_task_check(EngineHandle *handle, EngineHandle *task, BridgeBuffer *error) { + if (engine_check(task, ENGINE_TASK, error) != 0) return -1; + if (handle->api == task->api) return 0; + engine_error(error, 13, "Java engine task belongs to another engine"); + return -1; +} + +static int engine_scope(EngineHandle *handle, JavaScope *scope, BridgeBuffer *error) { + if (scope_enter(handle->api->context, scope, error) == 0) return 0; + engine_normalize_error(error, "cannot enter Java engine context"); + return -1; +} + +void *spark_connect_engine_thread_attach(void *raw_engine, BridgeBuffer *error) { + clear_buffer(error); + EngineHandle *engine = raw_engine; + if (engine_check(engine, ENGINE_FACTORY, error) != 0) return NULL; + EngineThread *thread = calloc(1, sizeof(*thread)); + if (thread == NULL) { + engine_error(error, 8, "cannot allocate Java worker attachment"); + return NULL; + } + JavaContext *context = engine->api->context; + JNIEnv *env = NULL; + jint state = (*context->vm)->GetEnv(context->vm, (void **) &env, JNI_VERSION_1_8); + if (state == JNI_EDETACHED) { + static atomic_uint_fast64_t next_worker = 1; + uint_fast64_t id = atomic_load_explicit(&next_worker, memory_order_relaxed); + do { + if (id == UINT_FAST64_MAX) { + engine_error(error, 8, "Java engine worker identifiers are exhausted"); + free(thread); + return NULL; + } + } while (!atomic_compare_exchange_weak_explicit(&next_worker, &id, id + 1, + memory_order_relaxed, memory_order_relaxed)); + char name[64]; + (void) snprintf(name, sizeof(name), "spark-connect-engine-worker-%" PRIuFAST64, id); + /* JNI consumes the name during attachment; the VM keeps its own copy. */ + JavaVMAttachArgs args = { + .version = JNI_VERSION_1_8, + .name = name, + .group = NULL, + }; + if ((*context->vm)->AttachCurrentThreadAsDaemon( + context->vm, (void **) &env, &args) != JNI_OK) { + engine_error(error, 13, "cannot attach Java engine worker"); + free(thread); + return NULL; + } + thread->attached = 1; + } else if (state != JNI_OK) { + engine_error(error, 13, "cannot access Java engine worker context"); + free(thread); + return NULL; + } + if (env == NULL) { + if (thread->attached) (*context->vm)->DetachCurrentThread(context->vm); + engine_error(error, 13, "Java engine worker has no JNI environment"); + free(thread); + return NULL; + } + thread->context = context; + thread->owner = pthread_self(); + atomic_fetch_add_explicit(&context->references, 1, memory_order_relaxed); + return thread; +} + +int spark_connect_engine_thread_detach(void *raw_attachment, BridgeBuffer *error) { + clear_buffer(error); + EngineThread *thread = raw_attachment; + if (thread == NULL) return 0; + if (!pthread_equal(thread->owner, pthread_self())) { + engine_error(error, 13, "Java worker attachment belongs to another thread"); + return -1; + } + JavaContext *context = thread->context; + if (thread->attached && (*context->vm)->DetachCurrentThread(context->vm) != JNI_OK) { + engine_error(error, 13, "cannot detach Java engine worker"); + return -1; + } + context_release(context); + free(thread); + return 0; +} + +void *spark_connect_engine_task_new(void *raw_engine, BridgeBuffer *error) { + clear_buffer(error); + EngineHandle *engine = raw_engine; + if (engine_check(engine, ENGINE_FACTORY, error) != 0) return NULL; + static atomic_uint_fast64_t next_task = 1; + uint_fast64_t id = atomic_load_explicit(&next_task, memory_order_relaxed); + do { + if (id == UINT_FAST64_MAX) { + engine_error(error, 8, "Java engine task identifiers are exhausted"); + return NULL; + } + } while (!atomic_compare_exchange_weak_explicit(&next_task, &id, id + 1, + memory_order_relaxed, memory_order_relaxed)); + char name[64]; + int len = snprintf(name, sizeof(name), "spark-engine-%" PRIuFAST64, id); + JavaScope scope; + if (engine_scope(engine, &scope, error) != 0) return NULL; + JNIEnv *env = scope.env; + jstring description = utf8_string(env, (const uint8_t *) name, (size_t) len, error); + jobject object = description == NULL ? NULL : (*env)->CallObjectMethod(env, + engine->object, engine->api->new_task, description); + EngineHandle *task = NULL; + if (engine_exception(env, engine->api, error) == 0 && object != NULL) + task = engine_handle(env, engine->api, object, ENGINE_TASK, error); + if (object != NULL) (*env)->DeleteLocalRef(env, object); + if (description != NULL) (*env)->DeleteLocalRef(env, description); + scope_leave(&scope); + if (task == NULL) engine_normalize_error(error, "Java engine did not create a task"); + return task; +} + +void *spark_connect_engine_open_session(void *raw_engine, const uint8_t *user, size_t user_len, + const uint8_t *id, size_t id_len, void *raw_task, BridgeBuffer *error) { + clear_buffer(error); + EngineHandle *engine = raw_engine; + EngineHandle *task = raw_task; + if (engine_check(engine, ENGINE_FACTORY, error) != 0 + || engine_task_check(engine, task, error) != 0) return NULL; + JavaScope scope; + if (engine_scope(engine, &scope, error) != 0) return NULL; + JNIEnv *env = scope.env; + jstring user_string = utf8_string(env, user, user_len, error); + jstring id_string = user_string == NULL ? NULL : utf8_string(env, id, id_len, error); + jobject object = id_string == NULL ? NULL : (*env)->CallObjectMethod(env, + engine->object, engine->api->open_session, user_string, id_string, task->object); + EngineHandle *session = NULL; + if (engine_exception(env, engine->api, error) == 0 && object != NULL) + session = engine_handle(env, engine->api, object, ENGINE_SESSION, error); + if (object != NULL) (*env)->DeleteLocalRef(env, object); + if (id_string != NULL) (*env)->DeleteLocalRef(env, id_string); + if (user_string != NULL) (*env)->DeleteLocalRef(env, user_string); + scope_leave(&scope); + if (session == NULL) engine_normalize_error(error, "Java engine did not open a session"); + return session; +} + +void *spark_connect_engine_prepare(void *raw_session, const uint8_t *relation, size_t len, + void *raw_task, BridgeBuffer *error) { + clear_buffer(error); + EngineHandle *session = raw_session; + EngineHandle *task = raw_task; + if (engine_check(session, ENGINE_SESSION, error) != 0 + || engine_task_check(session, task, error) != 0) return NULL; + JavaScope scope; + if (engine_scope(session, &scope, error) != 0) return NULL; + JNIEnv *env = scope.env; + jbyteArray input = byte_array(env, relation, len, error); + jobject object = input == NULL ? NULL : (*env)->CallObjectMethod(env, + session->object, session->api->prepare, input, task->object); + EngineHandle *query = NULL; + if (engine_exception(env, session->api, error) == 0 && object != NULL) + query = engine_handle(env, session->api, object, ENGINE_QUERY, error); + if (object != NULL) (*env)->DeleteLocalRef(env, object); + if (input != NULL) (*env)->DeleteLocalRef(env, input); + scope_leave(&scope); + if (query == NULL) engine_normalize_error(error, "Java engine did not prepare a query"); + return query; +} + +int spark_connect_engine_schema(void *raw_query, BridgeBuffer *out, BridgeBuffer *error) { + EngineHandle *query = raw_query; + clear_buffer(out); + clear_buffer(error); + if (engine_check(query, ENGINE_QUERY, error) != 0) return -1; + if (out == NULL) { + engine_error(error, 13, "missing Java engine result buffer"); + return -1; + } + JavaScope scope; + if (engine_scope(query, &scope, error) != 0) return -1; + JNIEnv *env = scope.env; + jbyteArray bytes = (*env)->CallObjectMethod(env, query->object, query->api->schema); + int result = engine_exception(env, query->api, error); + if (result == 0 && bytes != NULL) { + result = array_buffer(env, bytes, out, error); + } else if (result == 0) { + engine_error(error, 13, "Java engine returned no schema"); + result = -1; + } + if (bytes != NULL) (*env)->DeleteLocalRef(env, bytes); + scope_leave(&scope); + if (result < 0) engine_normalize_error(error, "cannot read Java engine query"); + return result; +} + +int spark_connect_engine_next_ipc(void *raw_query, BridgeBuffer *out, int64_t *row_count, + BridgeBuffer *error) { + clear_buffer(out); + clear_buffer(error); + if (row_count != NULL) *row_count = 0; + EngineHandle *query = raw_query; + if (engine_check(query, ENGINE_QUERY, error) != 0) return -1; + if (out == NULL || row_count == NULL) { + engine_error(error, 13, "missing Java engine IPC destination"); + return -1; + } + JavaScope scope; + if (engine_scope(query, &scope, error) != 0) return -1; + JNIEnv *env = scope.env; + jobject batch = (*env)->CallObjectMethod(env, query->object, query->api->next_ipc); + int result = engine_exception(env, query->api, error); + jbyteArray bytes = NULL; + if (result == 0 && batch != NULL) { + jlong count = (*env)->CallLongMethod(env, batch, query->api->batch_row_count); + result = engine_exception(env, query->api, error); + if (result == 0 && count < 0) { + engine_error(error, 13, "negative Java engine IPC row count"); + result = -1; + } + if (result == 0) { + bytes = (*env)->CallObjectMethod(env, batch, query->api->batch_data); + result = engine_exception(env, query->api, error); + if (result == 0 && bytes == NULL) { + engine_error(error, 13, "Java engine returned no IPC data"); + result = -1; + } + } + if (result == 0) { + jsize len = (*env)->GetArrayLength(env, bytes); + result = engine_exception(env, query->api, error); + if (result == 0 && len > 64 * 1024 * 1024) { + engine_error(error, 8, "Spark Arrow batch exceeds JNI limit"); + result = -1; + } + } + if (result == 0) result = array_buffer(env, bytes, out, error); + if (result == 0) { + *row_count = (int64_t) count; + result = 1; + } + } + if (bytes != NULL) (*env)->DeleteLocalRef(env, bytes); + if (batch != NULL) (*env)->DeleteLocalRef(env, batch); + scope_leave(&scope); + if (result < 0) engine_normalize_error(error, "cannot read Java engine IPC batch"); + return result; +} + +int spark_connect_engine_analyze(void *raw_session, int32_t opcode, const uint8_t *relation, size_t len, + void *raw_task, BridgeBuffer *out, BridgeBuffer *error) { + clear_buffer(out); + clear_buffer(error); + EngineHandle *session = raw_session; + EngineHandle *task = raw_task; + if (engine_check(session, ENGINE_SESSION, error) != 0 + || engine_task_check(session, task, error) != 0) return -1; + if (out == NULL) { + engine_error(error, 13, "missing Java engine analysis buffer"); + return -1; + } + JavaScope scope; + if (engine_scope(session, &scope, error) != 0) return -1; + JNIEnv *env = scope.env; + jbyteArray input = byte_array(env, relation, len, error); + jbyteArray bytes = input == NULL ? NULL : (*env)->CallObjectMethod(env, + session->object, session->api->analyze, (jint) opcode, input, task->object); + int result = engine_exception(env, session->api, error); + if (result == 0 && bytes != NULL) result = array_buffer(env, bytes, out, error); + else if (result == 0) { + engine_normalize_error(error, "Java engine returned no analysis result"); + result = -1; + } + if (bytes != NULL) (*env)->DeleteLocalRef(env, bytes); + if (input != NULL) (*env)->DeleteLocalRef(env, input); + scope_leave(&scope); + if (result < 0) engine_normalize_error(error, "cannot analyze Java engine relation"); + return result; +} + +int spark_connect_engine_config(void *raw_session, int32_t opcode, const uint8_t *fields, size_t len, + void *raw_task, BridgeBuffer *out, BridgeBuffer *error) { + clear_buffer(out); + clear_buffer(error); + EngineHandle *session = raw_session; + EngineHandle *task = raw_task; + if (engine_check(session, ENGINE_SESSION, error) != 0 + || engine_task_check(session, task, error) != 0) return -1; + if (out == NULL) { + engine_error(error, 13, "missing Java engine config buffer"); + return -1; + } + JavaScope scope; + if (engine_scope(session, &scope, error) != 0) return -1; + JNIEnv *env = scope.env; + jbyteArray input = byte_array(env, fields, len, error); + jbyteArray bytes = input == NULL ? NULL : (*env)->CallObjectMethod(env, + session->object, session->api->config, (jint) opcode, input, task->object); + int result = engine_exception(env, session->api, error); + if (result == 0 && bytes != NULL) result = array_buffer(env, bytes, out, error); + else if (result == 0) { + engine_normalize_error(error, "Java engine returned no config result"); + result = -1; + } + if (bytes != NULL) (*env)->DeleteLocalRef(env, bytes); + if (input != NULL) (*env)->DeleteLocalRef(env, input); + scope_leave(&scope); + if (result < 0) engine_normalize_error(error, "cannot configure Java engine session"); + return result; +} + +void spark_connect_engine_cancel(void *raw_task) { + EngineHandle *task = raw_task; + if (engine_check(task, ENGINE_TASK, NULL) != 0) return; + JavaScope scope; + if (engine_scope(task, &scope, NULL) != 0) return; + (*scope.env)->CallVoidMethod(scope.env, task->object, task->api->cancel); + (void) engine_exception(scope.env, task->api, NULL); Review Comment: Fixed in [dce536e8d00a747b8f23df0e663fbcbca962c3cc](https://github.com/apache/spark-connect-rust/commit/dce536e8d00a747b8f23df0e663fbcbca962c3cc). Cancellation now returns status and an error buffer across the C ABI. Both Rust callers retain failed cancellation ownership and admission permits for an explicit close retry instead of marking delivery successful. C and Rust tests cover scope-entry and Java failures. A partially failed Java cancellation remains sticky: retrying delivery does not claim to undo a terminal host failure. -- 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]
