dbtsai commented on code in PR #474: URL: https://github.com/apache/spark-connect-rust/pull/474#discussion_r4598375887
########## crates/spark-connect-server/jvm/src/main/java/org/apache/spark/sql/connect/nativebridge/engine/SparkJvmEngine.java: ########## @@ -0,0 +1,1003 @@ +// 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 java.util.regex.Pattern; + +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.errors.QueryExecutionErrors$; +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 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 Pattern redactionPattern; + 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(); + // SparkContext configuration is fixed after startup. Cache the host policy rather + // than cloning the whole SparkConf for each Config RPC or reading session overrides. + redactionPattern = sparkContext.getConf().get( + org.apache.spark.internal.config.package$.MODULE$.SECRET_REDACTION_PATTERN()).pattern(); + 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) { + String value = spark.conf().get(pair.key); + if (isRedacted(redactionPattern, pair.key, value)) { + throw QueryExecutionErrors$.MODULE$.sqlConfigNotFoundError(pair.key); + } + output.add(new Pair(pair.key, value)); + } + break; + case 2: + for (Pair pair : input) { + Option<String> stored = spark.conf().getOption(pair.key); + String value = stored.isDefined() ? stored.get() : null; + output.add(new Pair(pair.key, + isRedacted(redactionPattern, pair.key, value) ? null : value)); + } + break; + case 3: + for (Pair pair : input) { + String value = spark.conf().get(pair.key, pair.value); + output.add(new Pair(pair.key, + isRedacted(redactionPattern, pair.key, value) ? pair.value : 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 -> !isRedacted(redactionPattern, entry.getKey(), entry.getValue())) + .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; + case 8: + // A separate result preserves setter-error provenance. JNI/task/admission + // failures still fail the call rather than becoming silent Set warnings. + if (input.size() != 1) throw new EngineException(3, "silent set accepts one key"); + String warning = applyConfig(opcode, input, task); + if (warning != null) output.add(new Pair(input.get(0).key, warning)); + 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..8 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 String applyConfig(int opcode, List<Pair> input, Task task) { + boolean silent = opcode == 8; + 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(); + Throwable setterFailure = null; + 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 != 7) spark.conf().set(pair.key, pair.value); + else spark.conf().unset(pair.key); + } catch (Throwable error) { + setterFailure = error; + if (!silent && error instanceof IllegalArgumentException) { + if (!(error instanceof SparkThrowable) || !((SparkThrowable) error).isInternalError()) { + throw new EngineException(3, error.getMessage(), error); + } + } + throw error; + } + } + synchronized (task) { + task.check(); + task.complete(); + } + } catch (Throwable error) { + Map<String, String> current = null; + boolean restored = true; + try { current = spark.conf().getAllAsJava(); } catch (Throwable inspection) { + recordFailure(error, inspection); + restored = false; + } + 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); + restored = false; + } + } + if (silent && error == setterFailure && restored) { + // Match Spark's silent Set diagnostics without retaining rejected values/messages. + String reason = error instanceof SparkThrowable + ? ((SparkThrowable) error).getCondition() : null; + if (reason == null) reason = error.getClass().getName(); + synchronized (task) { + task.check(); + if (error instanceof InterruptedException || Thread.currentThread().isInterrupted()) { + throw new EngineException(1, "JVM engine operation was interrupted", error); + } + task.complete(); + } + return reason; + } + throw error; + } + return null; + } + + @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()) { Review Comment: Added a DataSource READ regression through prepare and all Analyze modes, asserting UNIMPLEMENTED and the named-table guard message, plus a named-table temp-view query that decodes and checks its row value and batch counts. The live JVM suite passes, and removing the guard in an isolated control makes the new test fail at the intended assertion. Fixed in ac55ecd6a8d0464b6b8f85b602c8c5b5200d5e1e. ########## crates/spark-connect-server/src/service.rs: ########## @@ -0,0 +1,1232 @@ +// 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>> { + // Releasing a missing or already closed session is a no-op. In + // particular, a later reconnecting release cannot erase a tombstone. + let session = self.entries.get_mut(&key)?.take()?; + if allow_reconnect { + self.entries.remove(&key); + } else { + self.released.push_back(key); + if self.released.len() > MAX_RELEASED_SESSIONS { + if let Some(oldest) = self.released.pop_front() { + self.entries.remove(&oldest); + } + } + } + Some(session) + } +} + +// None is a recently released-session tombstone, retained by SessionRegistry. +pub(crate) struct ConnectService { + engine: Arc<dyn Engine>, + sessions: Mutex<SessionRegistry>, + closing: std::sync::atomic::AtomicBool, +} + +impl ConnectService { + pub(crate) fn new(engine: Arc<dyn Engine>) -> Self { + Self { + engine, + sessions: Mutex::new(SessionRegistry::default()), + closing: std::sync::atomic::AtomicBool::new(false), + } + } + + fn key(id: &str, user: Option<&proto::UserContext>) -> Result<SessionKey, Status> { + Uuid::parse_str(id).map_err(|_| Status::invalid_argument("session_id must be a UUID"))?; + Ok(( + user.map(|u| u.user_id.clone()).unwrap_or_default(), + id.into(), + )) + } + + fn session( + &self, + id: &str, + user: Option<&proto::UserContext>, + observed: Option<&str>, + ) -> Result<Arc<Session>, Status> { + self.find_session(id, user, observed, true) + } + + fn find_session( + &self, + id: &str, + user: Option<&proto::UserContext>, + observed: Option<&str>, + create: bool, + ) -> Result<Arc<Session>, Status> { + let key = Self::key(id, user)?; + let mut sessions = self + .sessions + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if self.closing.load(std::sync::atomic::Ordering::SeqCst) { + return Err(Status::unavailable("server is shutting down")); + } + let session = match sessions.entries.get(&key) { + Some(Some(session)) => session.clone(), + Some(None) => return Err(Status::failed_precondition("session was released")), + None if !create => return Err(Status::not_found("session does not exist")), + // An observed ID refers to a previous incarnation; a new session + // cannot satisfy it. Reject before allocating backend resources. + None if observed.is_some() => { + return Err(Status::failed_precondition( + "server-side session ID changed", + )); + } + None => { + let backend = self.engine.create_session(SessionContext { + session_id: id.to_owned(), + user_context: user.cloned(), + })?; + let session = Arc::new(Session::new(backend)); + sessions.entries.insert(key, Some(session.clone())); + session + } + }; + if observed.is_some_and(|id| id != session.id) { + return Err(Status::failed_precondition( + "server-side session ID changed", + )); + } + Ok(session) + } + + pub(crate) fn cancel_all(&self) { + self.closing + .store(true, std::sync::atomic::Ordering::SeqCst); + // Stalled HTTP/2 connections can retain the service after the bounded + // transport drain. Remove its registry ownership now so backend sessions + // can close once their cancelled operations finish. + let sessions = std::mem::take( + &mut *self + .sessions + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner), + ); + for session in sessions.entries.into_values().flatten() { + session.cancelled.send_replace(true); + } + } +} + +fn response( + session_id: &str, + session: &Session, + operation_id: &str, + response_type: Option<proto::execute_plan_response::ResponseType>, +) -> proto::ExecutePlanResponse { + proto::ExecutePlanResponse { + session_id: session_id.into(), + server_side_session_id: session.id.clone(), + operation_id: operation_id.into(), + response_id: Uuid::new_v4().to_string(), + response_type, + ..Default::default() + } +} + +fn checked_response( + message: proto::ExecutePlanResponse, +) -> Result<proto::ExecutePlanResponse, Status> { + if message.encoded_len() > MAX_ARROW_IPC_BYTES { + return Err(Status::resource_exhausted( + "ExecutePlan response exceeds the 3 MiB result limit", + )); + } + Ok(message) +} + +fn complete(id: &str, session: &Session, operation: &str) -> proto::ExecutePlanResponse { + response( + id, + session, + operation, + Some(proto::execute_plan_response::ResponseType::ResultComplete( + proto::execute_plan_response::ResultComplete {}, + )), + ) +} + +fn encode_batch(batch: &RecordBatch) -> Result<Vec<u8>, Status> { + use arrow::datatypes::{DataType, FieldRef, Schema}; + use arrow::record_batch::RecordBatchOptions; + + fn materialized_field(field: &FieldRef) -> FieldRef { + let data_type = materialized_type(field.data_type()); + if data_type == *field.data_type() { + field.clone() + } else { + Arc::new(field.as_ref().clone().with_data_type(data_type)) + } + } + + fn materialized_type(data_type: &DataType) -> DataType { + match data_type { + DataType::Utf8View => DataType::LargeUtf8, + DataType::BinaryView => DataType::LargeBinary, + DataType::List(field) => DataType::List(materialized_field(field)), + DataType::LargeList(field) => DataType::LargeList(materialized_field(field)), + DataType::Struct(fields) => { + DataType::Struct(fields.iter().map(materialized_field).collect()) + } + DataType::Map(field, sorted) => DataType::Map(materialized_field(field), *sorted), + other => other.clone(), + } + } + + // IPC writes all backing buffers of view arrays even after a row slice. Materialize + // their bytes, including nested children, so splitting measures only retained rows. + // Use 64-bit offsets so materializing a batch cannot overflow 32-bit byte offsets + // before the result-size check has a chance to split it. + let source_schema = batch.schema(); + let fields: Vec<_> = source_schema + .fields() + .iter() + .map(materialized_field) + .collect(); + let changed = fields + .iter() + .zip(source_schema.fields()) + .any(|(target, source)| target.data_type() != source.data_type()); + let materialized = if changed { + let columns = batch + .columns() + .iter() + .zip(&fields) + .map(|(column, field)| { + if column.data_type() == field.data_type() { + Ok(column.clone()) + } else { + arrow::compute::cast(column.as_ref(), field.data_type()) + } + }) + .collect::<Result<Vec<_>, _>>() + .map_err(|error| Status::internal(error.to_string()))?; + let target_schema = Arc::new(Schema::new_with_metadata( + fields, + source_schema.metadata().clone(), + )); + Some( + RecordBatch::try_new_with_options( + target_schema, + columns, + &RecordBatchOptions::new().with_row_count(Some(batch.num_rows())), + ) + .map_err(|error| Status::internal(error.to_string()))?, + ) + } else { + None + }; + let batch = materialized.as_ref().unwrap_or(batch); + let mut bytes = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut bytes, batch.schema().as_ref()) + .map_err(|e| Status::internal(e.to_string()))?; + writer + .write(batch) + .map_err(|e| Status::internal(e.to_string()))?; + writer + .finish() + .map_err(|e| Status::internal(e.to_string()))?; + } + Ok(bytes) +} + +fn estimated_rows_per_batch(batch: &RecordBatch) -> usize { + let bytes = batch.get_array_memory_size(); + // Start below the exact IPC limit to allow schema/offset overhead. This is + // only an estimate: skewed rows and annotations are checked after encoding. + // Include retained backing allocations so even sliced/view inputs begin + // conservatively without materializing an entire oversized engine batch. + rows_for_bytes(batch.num_rows(), bytes) +} + +fn rows_for_bytes(rows: usize, bytes: usize) -> usize { + (rows as u128 * (MAX_ARROW_IPC_BYTES / 2) as u128 / bytes.max(1) as u128) + .clamp(1, rows.max(1) as u128) as usize +} + +// Fields drop in declaration order, including when encoding panics or a +// cancelled caller drops a completed JoinHandle without observing its output. +struct EncodingBatch { + batch: RecordBatch, + _guard: Arc<OperationGuard>, +} + +impl EncodingBatch { + fn encode(self) -> Result<(Self, Vec<u8>), Status> { + let data = encode_batch(&self.batch)?; + Ok((self, data)) + } +} + +async fn send_batch( + sender: &mpsc::Sender<Result<proto::ExecutePlanResponse, Status>>, + id: &str, + operation: &str, + batch: ResultBatch, + offset: &mut i64, + guard: &Arc<OperationGuard>, +) -> Result<bool, Status> { + let (batch, rows_per_batch) = match batch { + ResultBatch::Arrow(batch) => { + let rows = estimated_rows_per_batch(&batch); + (batch, rows) + } + ResultBatch::Ipc { data, row_count } => { + if row_count < 0 { + return Err(Status::internal("negative engine IPC row count")); + } + let batch = proto::execute_plan_response::ArrowBatch { + row_count, + data: data.into(), + start_offset: Some(*offset), + ..Default::default() + }; + let result = response( + id, + &guard.session, + operation, + Some(proto::execute_plan_response::ResponseType::ArrowBatch( + batch.clone(), + )), + ); + if result.encoded_len() <= MAX_ARROW_IPC_BYTES { + *offset = offset + .checked_add(row_count) + .ok_or_else(|| Status::resource_exhausted("result row offset exceeds i64"))?; + return Ok(sender.send(Ok(result)).await.is_ok()); + } + drop(result); + // Ordinary IPC is forwarded unchanged. Only oversized payloads need + // vectors so the existing row splitter can enforce the envelope limit. + let guard = guard.clone(); + tokio::task::spawn_blocking(move || { + let _guard = guard; + let ipc_bytes = batch.data.len(); + let mut reader = StreamReader::try_new(&batch.data[..], None) + .map_err(|e| Status::internal(format!("invalid engine IPC: {e}")))?; + let batch = reader + .next() + .transpose() + .map_err(|e| Status::internal(format!("invalid engine IPC: {e}")))? + .ok_or_else(|| Status::internal("engine IPC contains no record batch"))?; + if i64::try_from(batch.num_rows()).ok() != Some(row_count) + || reader.next().is_some() + { + return Err(Status::internal( + "engine IPC batch count differs from its declaration", + )); + } + // Decoded columns can share the full IPC allocation. Use its + // serialized size instead of counting that allocation per column. + let rows = rows_for_bytes(batch.num_rows(), ipc_bytes); + Ok((batch, rows)) + }) + .await + .map_err(|_| Status::internal("Arrow IPC decoding task failed"))?? + } + }; + send_arrow_batch(sender, id, operation, batch, rows_per_batch, offset, guard).await +} + +async fn send_arrow_batch( + sender: &mpsc::Sender<Result<proto::ExecutePlanResponse, Status>>, + id: &str, + operation: &str, + batch: RecordBatch, + rows_per_batch: usize, + offset: &mut i64, + guard: &Arc<OperationGuard>, +) -> Result<bool, Status> { + let mut pending = vec![(batch, rows_per_batch)]; + while let Some((batch, rows_per_batch)) = pending.pop() { + // Keep the remainder as one slice instead of allocating a pending entry + // per row in a large engine batch. + let batch = if batch.num_rows() > rows_per_batch { + pending.push(( + batch.slice(rows_per_batch, batch.num_rows() - rows_per_batch), + rows_per_batch, + )); + batch.slice(0, rows_per_batch) + } else { + batch + }; + // Arrow materialization/IPC encoding is CPU work. Retain operation + // ownership if cancellation drops the JoinHandle, so ReleaseAll cannot + // claim drain while a result batch is still being encoded. + let encoding = EncodingBatch { + batch, + _guard: guard.clone(), + }; + let (encoded, data) = tokio::task::spawn_blocking(move || encoding.encode()) + .await + .map_err(|_| Status::internal("Arrow result encoding task failed"))??; + let batch = &encoded.batch; + let result = response( + id, + &guard.session, + operation, + Some(proto::execute_plan_response::ResponseType::ArrowBatch( + proto::execute_plan_response::ArrowBatch { + row_count: batch.num_rows() as i64, + data: data.into(), + start_offset: Some(*offset), + ..Default::default() + }, + )), + ); + let result_bytes = result.encoded_len(); + if result_bytes > MAX_ARROW_IPC_BYTES { + if batch.num_rows() <= 1 { + return Err(Status::resource_exhausted( + "one Arrow row/schema exceeds the 3 MiB result limit", + )); + } + // Recheck every slice including the envelope: skew and schema + // overhead can exceed the initial memory estimate. + let rows_per_batch = ((batch.num_rows() as u128 * MAX_ARROW_IPC_BYTES as u128 * 9 + / (result_bytes as u128 * 10)) as usize) + .clamp(1, batch.num_rows() - 1); + drop(result); + pending.push((batch.clone(), rows_per_batch)); + continue; + } + *offset = offset + .checked_add(batch.num_rows() as i64) + .ok_or_else(|| Status::resource_exhausted("result row offset exceeds i64"))?; + if sender.send(Ok(result)).await.is_err() { + return Ok(false); + } + } + Ok(true) +} + +#[tonic::async_trait] +impl SparkConnectService for ConnectService { + type ExecutePlanStream = Output; + type ReattachExecuteStream = Output; + + async fn execute_plan( + &self, + request: Request<proto::ExecutePlanRequest>, + ) -> Result<Response<Output>, Status> { + let req = request.into_inner(); + let operation = req + .operation_id + .unwrap_or_else(|| Uuid::new_v4().to_string()); + Uuid::parse_str(&operation) + .map_err(|_| Status::invalid_argument("operation_id must be a UUID"))?; + let op = req + .plan + .and_then(|p| p.op_type) + .ok_or_else(|| Status::invalid_argument("missing plan"))?; + let session = self.session( + &req.session_id, + req.user_context.as_ref(), + req.client_observed_server_side_session_id.as_deref(), + )?; + let mut cancelled = session.cancelled.subscribe(); + if *cancelled.borrow() { + return Err(Status::cancelled("session released")); + } + // Reserve before calling the backend: preparing a command can mutate state. + let (guard, mut operation_cancelled) = session.operation(&operation)?; + let prepared = tokio::select! { + biased; + _ = cancelled.changed() => return Err(Status::cancelled("session released")), + _ = operation_cancelled.changed() => return Err(Status::cancelled("operation released")), + prepared = session.backend.prepare(op) => prepared?, + }; + let query = match prepared { + PreparedOperation::Query(query) => query, + PreparedOperation::Command(payloads) => { + let mut messages = payloads + .into_iter() + .map(|payload| { + let message = + response(&req.session_id, &session, &operation, Some(payload)); + checked_response(message) + }) + .collect::<Result<Vec<_>, Status>>()?; + messages.push(checked_response(complete( + &req.session_id, + &session, + &operation, + ))?); + return Ok(Response::new(Box::pin(tokio_stream::iter( + messages.into_iter().map(Ok), + )))); + } + }; + let arrow_schema = query.schema(); + let spark_schema = result_schema(&arrow_schema)?; + let expected_batch_schema = schema::comparable_schema(&arrow_schema)?; + let (sender, receiver) = mpsc::channel(2); + tokio::spawn(async move { + let run = async { + let mut header = response(&req.session_id, &session, &operation, None); + header.schema = Some(spark_schema); + let header = checked_response(header)?; + if sender.send(Ok(header)).await.is_err() { + return Ok(()); + } + let mut batches = query.execute().await?; + let mut offset = 0; + let mut sent = false; + while let Some(batch) = batches.next().await { + let batch = batch?; + let batch_schema = match &batch { + ResultBatch::Arrow(batch) => batch.schema(), + ResultBatch::Ipc { data, .. } => { Review Comment: Added real IPC fixture modes for a schema mismatch and malformed bytes. The gRPC test checks the schema header followed immediately by INTERNAL, before any Arrow batch or completion. It passes normally; isolated controls that disable schema checking or bypass IPC parsing each fail at the expected assertion. Fixed in ac55ecd6a8d0464b6b8f85b602c8c5b5200d5e1e. ########## crates/spark-connect-server/README.md: ########## @@ -0,0 +1,460 @@ +<!-- + ~ 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. +--> + +# Rust Spark Connect frontend with an embedded JVM engine (WIP) + +This prototype embeds a Rust Spark Connect listener inside a Spark JVM through +JNI. Rust owns request decoding, protocol sessions, operation IDs, response +framing and stream lifetimes. The Java adapter calls Spark planning and execution +APIs through an in-process engine interface. + +The frontend uses the workspace's `apache-spark-connect-proto` messages. It sends +serialized `Relation` inputs through JNI; Java decodes them with Spark's protobuf +classes and uses `SparkConnectPlanner` to construct Catalyst plans. Spark executes +those plans in the JVM that hosts the Rust listener. This boundary does not pass +Spark Connect service requests, responses or operation registries to Java. + +This is a work in progress for local trusted workloads, with a limited protocol +surface. It does not provide authentication, authorization or TLS. Keep its +listener on loopback and read the [security policy](../../SECURITY.md) before use. + +## Build requirements and compatibility + +- Rust 1.88 or newer, Cargo and `protoc` 3.15 or newer (proto3 optional support). +- JDK 21, a C compiler with C11/pthread support and JNI headers. Set `JAVA_HOME` + to the JDK directory. +- Python 3.9 or newer for artifact metadata and packaging. Java build scripts use + `python3`; set `NATIVE_BUILD_PYTHON` to select another interpreter. +- macOS or Linux. Windows is not supported by this prototype. +- A compatible Spark assembly containing the shaded Connect protobuf/gRPC jars. + Set `SPARK_HOME` to its directory. The scripts accept jars in either + `$SPARK_HOME/jars` or `$SPARK_HOME/assembly/target/scala-2.13/jars`. + +The workspace currently tracks the Spark 4.3.0 protocol; its pin is recorded in +[PROTO_VERSION.txt](../spark-connect-proto/proto/PROTO_VERSION.txt). The JNI +implementation was developed and validated with Spark `4.2.0-SNAPSHOT`, revision +`250ccca3f2b5f043e20b415adf17bda5d202c60f`, Scala 2.13.17 and JDK 21.0.10. It depends +on internal Spark APIs, including `SessionHolder`, `SparkConnectPlanner`, +`QueryExecution` and Arrow conversion helpers. That validation does not establish +Spark 4.3.0 assembly compatibility or support for every 4.3.0 protocol feature. +Other assemblies may require Java source changes and fresh acceptance checks. + +The range-query JNI smoke test uses that unmodified Spark snapshot. The broader +acceptance run used a separate local repair to +`ArrowConverters.InternalRowIteratorFromIPCStream` for Arrow input resource +cleanup at EOF and on failure. That repair is not bundled with this prototype. +The smoke test does not cover Arrow IPC input, and the broader result does not +establish full acceptance on the unmodified snapshot. + +The `spark-connect-server` and nested `spark-connect-jni` crates are unpublished, +optional workspace members excluded from `default-members`. Build them explicitly +with `-p`; the server crate provides the frontend library and the JNI crate builds +the JVM-loaded native library. There is no standalone server executable. + +All commands below run from the repository root. Cargo places native artifacts in +`target/`; the JVM scripts place generated Java artifacts and acceptance reports +under `crates/spark-connect-server/.build/`. + +## Run the embedded server + +With `JAVA_HOME` and `SPARK_HOME` set, build the native library: + +```bash +cargo build --release -p spark-connect-jni +``` + +On macOS: + +```bash +export NATIVE_LIBRARY="$PWD/target/release/libspark_connect_jni.dylib" +crates/spark-connect-server/jvm/run-engine.sh "$NATIVE_LIBRARY" 127.0.0.1:15002 +``` + +On Linux, set `NATIVE_LIBRARY` to +`$PWD/target/release/libspark_connect_jni.so` instead. The launcher requires an +absolute library path, compiles the Java adapter and starts `EmbeddedSparkEngine` +with `spark-submit`. `SPARK_MASTER` defaults to `local[2]`. + +In another terminal, use the official Rust client example: + +```bash +SPARK_REMOTE=sc://127.0.0.1:15002 cargo run -p spark-connect-server --example rust_client +``` + +It collects a range aggregate and a SQL result. A compatible official PySpark +Connect client can also run: + +```bash +SPARK_REMOTE=sc://127.0.0.1:15002 python crates/spark-connect-server/examples/jvm_client.py +``` + +Stop the launcher with Ctrl-C. Native shutdown cancels and drains owned work, +releases engine sessions and closes the Rust listener before Spark is stopped. +The native library is process-lived; unloading it while the JVM continues running +is unsupported. A failed drain is reported, and resources can remain retained +until teardown succeeds or the process exits. + +If `NativeEngineServer.close()` reports a JNI attachment failure, the server keeps +its cleanup handles and admission reservations; a later explicit `close()` can +retry after attachment recovers. Worker detachment must run on the owning OS +thread. A detach failure that persists through its bounded same-thread retry +retains the attachment and makes shutdown fail; a later close on another thread +cannot release it. Restart the hosting JVM to recover. A Java cleanup exception +can occur after Spark or Arrow has released only part of a resource. Such failures +retain their owners and the original error until JVM exit. Repeated `close()` calls +report that error without replaying potentially non-idempotent cleanup or claiming +a successful drain. Restart the hosting JVM to recover from a persistent cleanup +failure. + +## Bundle native libraries in JARs + +The Java adapter is shared across operating systems and CPU architectures for a +compatible Spark/Scala/JDK combination. Native code is packaged separately for +`linux-x86_64`, `linux-aarch64`, `macos-x86_64` and `macos-aarch64`. Each platform +JAR contains the library and version, ABI and SHA-256 metadata under +`META-INF/native/<platform>/`. The artifact version comes from `jni/Cargo.toml`; +it currently is `0.1.0`, independently of the client workspace's Spark version. + +After building the native library and Java adapter, package them with Python 3: + +```bash +crates/spark-connect-server/jvm/build.sh +python3 crates/spark-connect-server/jvm/package-native.py \ + --library "$NATIVE_LIBRARY" \ + --adapter-jar crates/spark-connect-server/.build/jvm/spark-connect-native-bridge.jar \ + --output-dir crates/spark-connect-server/.build/jars +``` + +This produces a shared `spark-connect-native-adapter-0.1.0.jar`, the current +platform's `spark-connect-native-0.1.0-<platform>.jar`, and checksum sidecars. +The packager checks the actual ELF or Mach-O header against the selected +platform. Selecting another platform does not cross-compile the library. +Native JAR entries use ZIP DEFLATE compression at level 9. Archive metadata is +normalized for reproducible packaging with the same toolchain; compressed bytes +can differ between zlib versions. + +Every platform, all-platform and macOS universal JAR includes the license and +notice texts for the JNI library's normal, non-proc-macro dependencies across +all four supported Cargo targets. They are stored in `META-INF/LICENSE`, +`META-INF/NOTICE` and `META-INF/native-dependencies.json`. The inventory records +whole-file hashes of `Cargo.lock`, root `Cargo.toml`, the `spark-connect-proto`, +`spark-connect-server` and nested JNI `Cargo.toml` files, `LICENSE`, `NOTICE`, +`scripts/gen_binary_licenses.py` and `scripts/gen_native_binary_licenses.py`. +After any change to these files, run `python3 scripts/gen_native_binary_licenses.py` +and commit the regenerated `jvm/native-licenses/` assets, even if the JNI dependency +closure is unchanged. Packaging checks input and content hashes without running Cargo. + +For example, launch the packaged native library on macOS ARM64: + +```bash +crates/spark-connect-server/jvm/run-engine.sh --native-jar \ + "$PWD/crates/spark-connect-server/.build/jars/spark-connect-native-0.1.0-macos-aarch64.jar" \ + 127.0.0.1:15002 +``` + +For a deployment using already built JARs, pass the platform JAR with +`spark-submit --jars`, use the shared adapter JAR as the application JAR, and +invoke `EmbeddedSparkEngine --bundled [listen-address]`. An existing host can +use `new NativeEngineServer(listenAddress, engine)` with both JARs on its +classpath. The shared adapter JAR must also be available to Spark executors, +where its Java code converts result rows to Arrow. Using it as the application +JAR with `spark-submit` distributes it automatically. A host that creates its +own SparkContext must distribute the adapter through `spark.jars` at context +creation or `SparkContext.addJar` before querying. The host owns this classpath +configuration; the adapter does not change a shared context's submitted JARs. +Executors do not load the native library. The explicit absolute-library-path +constructor remains available. + +The loader detects the host platform, checks matching artifact and ABI versions +and the library checksum, then extracts the library into a private temporary +directory before calling `System.load`. Exactly one matching adapter metadata, +platform metadata and library resource must be visible to the adapter's defining +classloader. Mixing duplicate or incompatible native JARs fails explicitly. +Use one defining Java adapter classloader per JVM. The loader's singleton guard +is scoped to that classloader; loading another adapter copy can load a separate +native library and independent runtime state. +The extracted library stays available for the process lifetime and is removed +at normal JVM exit. Abrupt process termination can leave the temporary directory. +If the default temporary filesystem is mounted `noexec`, set `-Djava.io.tmpdir` +(through `spark.driver.extraJavaOptions` for Spark) to a private directory on a +filesystem that permits loading native libraries. + +The native CI matrix builds and tests each of the four targets on a runner with +the matching architecture, uploads the platform JARs, and combines them into +`spark-connect-native-0.1.0-all.jar` and a macOS universal JAR. Applications still +need the shared Java adapter JAR. The `--combine` command requires all four +platform artifacts: + +```bash +python3 crates/spark-connect-server/jvm/package-native.py \ + --combine /path/to/platform-jars/spark-connect-native-0.1.0-linux-x86_64.jar \ + /path/to/platform-jars/spark-connect-native-0.1.0-linux-aarch64.jar \ + /path/to/platform-jars/spark-connect-native-0.1.0-macos-x86_64.jar \ + /path/to/platform-jars/spark-connect-native-0.1.0-macos-aarch64.jar \ + --output-dir crates/spark-connect-server/.build/jars +``` + +To bundle both macOS architectures in one JAR: + +```bash +python3 crates/spark-connect-server/jvm/package-native.py \ + --combine-macos /path/to/platform-jars/spark-connect-native-0.1.0-macos-x86_64.jar \ + /path/to/platform-jars/spark-connect-native-0.1.0-macos-aarch64.jar \ + --output-dir crates/spark-connect-server/.build/jars +``` + +This requires exactly the two macOS platform artifacts and produces +`spark-connect-native-0.1.0-macos-universal.jar`. It contains both thin native +libraries; the loader selects the JVM's architecture, including under Rosetta, +and extracts only that library. Pass this JAR with `--native-jar` or +`spark-submit --jars` using the same launch commands above. CI checks loading the +same universal JAR on both macOS architectures. + +A Universal2 Mach-O library also contains both architectures' machine code, so +combining them into a fat binary does not itself remove those bytes. ZIP +compression reduces the universal JAR's stored and transfer size; the selected +library is decompressed when extracted. + +Linux artifacts are built on Ubuntu 22.04 and require glibc 2.35 or newer; musl +is outside this matrix. macOS artifacts target macOS 11 or newer. These are +development CI artifacts, with no Maven Central publication in this WIP. Native +packaging does not expand the Spark assembly compatibility described above. + +## Supported scope + +The frontend implements execution, configuration, session and operation release, +and the schema, `isLocal` and `isStreaming` analyses. The engine accepts these +relation messages, including their nested inputs: + +- `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`. + +The protobuf `READ` message accepts only its named-table form. This restricts the +message shape, not data access: `SQL` and named-table resolution follow the +hosting Spark session's semantics, including SQL-on-files and built-in reflective +functions when enabled there. Clients can change modifiable session SQL settings, +such as `spark.sql.runSQLOnFiles`, through Config Set. Queries execute with the +hosting process's resource access. This list does not establish support for every +expression or result type inside the accepted messages. Writes, streaming +execution and user-defined functions are outside this prototype's scope. + +Spark-owned internal annotations such as `__autoGeneratedAlias` are intentionally +omitted from returned schemas. User field metadata, including column comments, +non-default string collations, user-defined types and CHAR/VARCHAR return +`UNIMPLEMENTED`; Arrow schema conversion cannot preserve their information. +CHAR/VARCHAR annotations on string-typed table columns +(`__CHAR_VARCHAR_TYPE_STRING`) are also rejected. Ordinary unaliased computed +columns and aggregates remain supported within the other prototype limits. + +SQL commands such as `SHOW`, `DESCRIBE`, `SET`, `USE` and `CACHE`, Catalog API +relations and `CACHED_LOCAL_RELATION` are also rejected. Streaming relations are +rejected during planning, including `isStreaming` analysis; that analysis does +not return `true` for unsupported streaming inputs. + +Common unsupported client calls include `df.show()`, `df.printSchema()`, +`df.explain()`, `spark.version`, `df.describe()`, `df.summary()`, `df.sample()`, +`df.na.*`, `df.unpivot()`, `spark.read.parquet()` and `df.cache()`. + +Configuration is session scoped. Preparation captures analysis and Arrow +metadata, while physical planning starts on the first fetch. These stages do +not share a transactional configuration snapshot; a concurrent configuration +change can affect later physical planning. Config reads apply the hosting +SparkContext's `spark.redaction.regex` to keys and values; a session setting with +the same name does not replace that policy. This follows newer Spark Config +redaction behavior, which is absent from the pinned Spark 4.2 smoke-test assembly. + +Silent Config Set applies keys sequentially and is not atomic across keys. +Earlier successful writes remain applied if a later key encounters cancellation, +an admission timeout or another operation-level failure. All keys share the +original RPC's admission deadline; a long list does not reset that budget. + +Each batch fetch creates a separate Spark SQL execution ID. The Spark UI and Review Comment: Corrected this to one execution per partition fetch, with explicit wording for multi-partition queries and zero-partition initialization. The shuffle-cleanup explanation now also refers to partition fetches. Fixed in ac55ecd6a8d0464b6b8f85b602c8c5b5200d5e1e. ########## crates/spark-connect-server/jvm/src/main/java/org/apache/spark/sql/connect/nativebridge/engine/SparkJvmEngine.java: ########## @@ -0,0 +1,1003 @@ +// 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 java.util.regex.Pattern; + +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.errors.QueryExecutionErrors$; +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 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 Pattern redactionPattern; + 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(); + // SparkContext configuration is fixed after startup. Cache the host policy rather + // than cloning the whole SparkConf for each Config RPC or reading session overrides. + redactionPattern = sparkContext.getConf().get( + org.apache.spark.internal.config.package$.MODULE$.SECRET_REDACTION_PATTERN()).pattern(); + 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. Review Comment: Updated the comment to describe partition, batch and task-step checks observing cross-thread cancellation. Fixed in ac55ecd6a8d0464b6b8f85b602c8c5b5200d5e1e. ########## crates/spark-connect-server/jvm/src/main/java/org/apache/spark/sql/connect/nativebridge/engine/SparkJvmEngine.java: ########## @@ -0,0 +1,1003 @@ +// 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 java.util.regex.Pattern; + +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.errors.QueryExecutionErrors$; +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 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 Pattern redactionPattern; + 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(); + // SparkContext configuration is fixed after startup. Cache the host policy rather + // than cloning the whole SparkConf for each Config RPC or reading session overrides. + redactionPattern = sparkContext.getConf().get( + org.apache.spark.internal.config.package$.MODULE$.SECRET_REDACTION_PATTERN()).pattern(); + 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 Review Comment: Corrected the ABI Javadoc to a non-negative big-endian signed 32-bit count. The Rust encoder now also uses checked i32 conversion; native tests and strict Clippy pass on Rust 1.100 and 1.88. Fixed in ac55ecd6a8d0464b6b8f85b602c8c5b5200d5e1e. -- 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]
