dbtsai commented on code in PR #474:
URL: 
https://github.com/apache/spark-connect-rust/pull/474#discussion_r4594686037


##########
Cargo.toml:
##########
@@ -25,6 +25,8 @@ members = [
     "crates/spark-connect-build",
     "crates/pyspark-rs",
     "examples",
+    "crates/spark-connect-server",
+    "crates/spark-connect-server/jni",

Review Comment:
   The toolchain requirement is intentional for `--workspace`, and is 
documented immediately below this comment: workspace commands include the JNI 
host and require macOS/Linux, a C compiler and a JDK. The earlier “without it” 
refers specifically to the optional wasm target. Default workspace members 
remain unchanged and exclude the server/JNI crates. I kept this policy rather 
than adding a separate JNI feature gate; client-only workspace commands can use 
`--exclude spark-connect-jni`.



##########
crates/spark-connect-server/jni/native/bridge.c:
##########
@@ -0,0 +1,986 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "bridge.h"
+
+#include <jni.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <pthread.h>
+#include <stdatomic.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+typedef struct {
+  JavaVM *vm;
+  jobject loader;
+  jclass thread_class;
+  jmethodID current_thread;
+  jmethodID get_loader;
+  jmethodID set_loader;
+  atomic_uint references;
+} JavaContext;
+
+typedef struct {
+  JavaContext *context;
+  JNIEnv *env;
+  jobject thread;
+  jobject previous_loader;
+  int attached;
+  int framed;
+  int loader_changed;
+} JavaScope;
+
+typedef struct {
+  JavaContext *context;
+  pthread_t owner;
+  int attached;
+} EngineThread;
+
+extern int64_t spark_connect_engine_start(const uint8_t *, size_t, void *, 
BridgeBuffer *);
+extern int spark_connect_address(int64_t, BridgeBuffer *, BridgeBuffer *);
+extern int spark_connect_stop(int64_t, BridgeBuffer *);
+
+static void clear_buffer(BridgeBuffer *buffer) {
+  if (buffer != NULL) {
+    buffer->data = NULL;
+    buffer->len = 0;
+  }
+}
+
+static void set_error(BridgeBuffer *error, const char *message) {
+  if (error == NULL || error->data != NULL) {
+    return;
+  }
+  size_t len = strlen(message);
+  uint8_t *data = malloc(len == 0 ? 1 : len);
+  if (data != NULL) {
+    memcpy(data, message, len);
+    error->data = data;
+    error->len = len;
+  }
+}
+
+void spark_connect_buffer_free(BridgeBuffer *buffer) {
+  if (buffer != NULL) {
+    free(buffer->data);
+    clear_buffer(buffer);
+  }
+}
+
+/* GetStringUTFChars uses modified UTF-8, so encode UTF-16 explicitly instead. 
*/
+static int string_buffer(JNIEnv *env, jstring value, BridgeBuffer *out) {
+  jsize len = (*env)->GetStringLength(env, value);
+  const jchar *chars = (*env)->GetStringChars(env, value, NULL);
+  if (chars == NULL) {
+    return -1;
+  }
+  uint8_t *data = malloc((size_t) len * 3 + 1);
+  if (data == NULL) {
+    (*env)->ReleaseStringChars(env, value, chars);
+    return -1;
+  }
+  size_t written = 0;
+  for (jsize i = 0; i < len; i++) {
+    uint32_t code = chars[i];
+    if (code >= 0xd800 && code <= 0xdbff && i + 1 < len
+        && chars[i + 1] >= 0xdc00 && chars[i + 1] <= 0xdfff) {
+      code = 0x10000 + ((code - 0xd800) << 10) + chars[++i] - 0xdc00;
+    } else if (code >= 0xd800 && code <= 0xdfff) {
+      code = 0xfffd;
+    }
+    if (code < 0x80) {
+      data[written++] = (uint8_t) code;
+    } else if (code < 0x800) {
+      data[written++] = (uint8_t) (0xc0 | (code >> 6));
+      data[written++] = (uint8_t) (0x80 | (code & 0x3f));
+    } else if (code < 0x10000) {
+      data[written++] = (uint8_t) (0xe0 | (code >> 12));
+      data[written++] = (uint8_t) (0x80 | ((code >> 6) & 0x3f));
+      data[written++] = (uint8_t) (0x80 | (code & 0x3f));
+    } else {
+      data[written++] = (uint8_t) (0xf0 | (code >> 18));
+      data[written++] = (uint8_t) (0x80 | ((code >> 12) & 0x3f));
+      data[written++] = (uint8_t) (0x80 | ((code >> 6) & 0x3f));
+      data[written++] = (uint8_t) (0x80 | (code & 0x3f));
+    }
+  }
+  (*env)->ReleaseStringChars(env, value, chars);
+  out->data = data;
+  out->len = written;
+  return 0;
+}
+
+static int exception_error(JNIEnv *env, BridgeBuffer *error) {
+  if (!(*env)->ExceptionCheck(env)) {
+    return 0;
+  }
+  jthrowable throwable = (*env)->ExceptionOccurred(env);
+  (*env)->ExceptionClear(env);
+  jclass type = throwable == NULL ? NULL : (*env)->GetObjectClass(env, 
throwable);
+  jmethodID to_string = type == NULL ? NULL
+      : (*env)->GetMethodID(env, type, "toString", "()Ljava/lang/String;");
+  jstring description = to_string == NULL ? NULL
+      : (*env)->CallObjectMethod(env, throwable, to_string);
+  if (!(*env)->ExceptionCheck(env) && description != NULL && error != NULL
+      && error->data == NULL) {
+    (void) string_buffer(env, description, error);
+  }
+  if ((*env)->ExceptionCheck(env)) {
+    (*env)->ExceptionClear(env);
+  }
+  if (description != NULL) (*env)->DeleteLocalRef(env, description);
+  if (type != NULL) (*env)->DeleteLocalRef(env, type);
+  if (throwable != NULL) (*env)->DeleteLocalRef(env, throwable);
+  set_error(error, "Java bridge operation failed");
+  return -1;
+}
+
+static void scope_restore_loader(JavaScope *scope) {
+  JNIEnv *env = scope->env;
+  if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
+  if (scope->loader_changed) {
+    (*env)->CallVoidMethod(env, scope->thread, scope->context->set_loader,
+        scope->previous_loader);
+    if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
+    scope->loader_changed = 0;
+  }
+}
+
+static void scope_leave(JavaScope *scope) {
+  if (scope->env == NULL) return;
+  JNIEnv *env = scope->env;
+  scope_restore_loader(scope);
+  if (scope->previous_loader != NULL) (*env)->DeleteLocalRef(env, 
scope->previous_loader);
+  if (scope->thread != NULL) (*env)->DeleteLocalRef(env, scope->thread);
+  if (scope->framed) (*env)->PopLocalFrame(env, NULL);
+  if (scope->attached) 
(*scope->context->vm)->DetachCurrentThread(scope->context->vm);
+  scope->env = NULL;
+}
+
+static int scope_enter(JavaContext *context, JavaScope *scope, BridgeBuffer 
*error) {
+  memset(scope, 0, sizeof(*scope));
+  scope->context = context;
+  jint state = (*context->vm)->GetEnv(context->vm, (void **) &scope->env, 
JNI_VERSION_1_8);
+  if (state == JNI_EDETACHED) {
+    if ((*context->vm)->AttachCurrentThreadAsDaemon(
+        context->vm, (void **) &scope->env, NULL) != JNI_OK) {
+      scope->env = NULL;
+      set_error(error, "cannot attach Rust worker to JVM");
+      return -1;
+    }
+    scope->attached = 1;
+  } else if (state != JNI_OK) {
+    scope->env = NULL;
+    set_error(error, "cannot access JVM from Rust worker");
+    return -1;
+  }
+  JNIEnv *env = scope->env;
+  if ((*env)->PushLocalFrame(env, 32) < 0) {
+    (void) exception_error(env, error);
+    set_error(error, "cannot allocate Java local reference frame");
+    goto failed;
+  }
+  scope->framed = 1;
+  scope->thread = (*env)->CallStaticObjectMethod(env, context->thread_class,
+      context->current_thread);
+  if (exception_error(env, error) != 0 || scope->thread == NULL) goto failed;
+  scope->previous_loader = (*env)->CallObjectMethod(env, scope->thread, 
context->get_loader);
+  if (exception_error(env, error) != 0) goto failed;
+  if (!(*env)->IsSameObject(env, scope->previous_loader, context->loader)) {
+    (*env)->CallVoidMethod(env, scope->thread, context->set_loader, 
context->loader);
+    if (exception_error(env, error) != 0) goto failed;
+    scope->loader_changed = 1;
+  }
+  return 0;
+failed:
+  set_error(error, "cannot prepare JVM worker context");
+  scope_leave(scope);
+  return -1;
+}
+
+static void context_release(JavaContext *context) {
+  if (atomic_fetch_sub_explicit(&context->references, 1, memory_order_acq_rel) 
!= 1) return;
+  // The factory cannot be freed while worker guards exist. Consequently detach
+  // never owns the last context reference, and must not reattach just to 
destroy it.
+  // Preserve an unexpected orphan rather than deleting globals without a 
valid env.
+  atomic_store_explicit(&context->references, 1, memory_order_release);
+  fputs("JNI cleanup is incomplete; retained cleanup failed: orphaned Java 
worker context\n",
+      stderr);
+}
+
+static jbyteArray byte_array(JNIEnv *env, const uint8_t *data, size_t len,
+    BridgeBuffer *error) {
+  if (len > INT_MAX || (len != 0 && data == NULL)) {
+    set_error(error, "Java bridge byte array is too large or invalid");
+    return NULL;
+  }
+  jbyteArray array = (*env)->NewByteArray(env, (jsize) len);
+  if (exception_error(env, error) != 0 || array == NULL) return NULL;
+  if (len != 0) (*env)->SetByteArrayRegion(env, array, 0, (jsize) len, (const 
jbyte *) data);
+  if (exception_error(env, error) != 0) {
+    (*env)->DeleteLocalRef(env, array);
+    return NULL;
+  }
+  return array;
+}
+
+static jstring utf8_string(JNIEnv *env, const uint8_t *data, size_t len,
+    BridgeBuffer *error) {
+  jbyteArray bytes = byte_array(env, data, len, error);
+  if (bytes == NULL) return NULL;
+  jclass type = (*env)->FindClass(env, "java/lang/String");
+  jmethodID constructor = type == NULL ? NULL
+      : (*env)->GetMethodID(env, type, "<init>", "([BLjava/lang/String;)V");
+  jstring encoding = constructor == NULL ? NULL : (*env)->NewStringUTF(env, 
"UTF-8");
+  jstring value = NULL;
+  if (exception_error(env, error) == 0 && encoding != NULL) {
+    value = (*env)->NewObject(env, type, constructor, bytes, encoding);
+    if (exception_error(env, error) != 0) value = NULL;
+  }
+  if (encoding != NULL) (*env)->DeleteLocalRef(env, encoding);
+  if (type != NULL) (*env)->DeleteLocalRef(env, type);
+  (*env)->DeleteLocalRef(env, bytes);
+  return value;
+}
+
+static int array_buffer(JNIEnv *env, jbyteArray array, BridgeBuffer *out,
+    BridgeBuffer *error) {
+  jsize len = (*env)->GetArrayLength(env, array);
+  if (exception_error(env, error) != 0) return -1;
+  uint8_t *data = malloc(len == 0 ? 1 : (size_t) len);
+  if (data == NULL) {
+    set_error(error, "cannot allocate Java bridge buffer");
+    return -1;
+  }
+  if (len != 0) (*env)->GetByteArrayRegion(env, array, 0, len, (jbyte *) data);
+  if (exception_error(env, error) != 0) {
+    free(data);
+    return -1;
+  }
+  out->data = data;
+  out->len = (size_t) len;
+  return 0;
+}
+
+static void throw_error(JNIEnv *env, BridgeBuffer *error) {
+  if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
+  if (error->data == NULL) set_error(error, "native Spark Connect operation 
failed");
+  jstring message = utf8_string(env, error->data, error->len, NULL);
+  jclass type = (*env)->FindClass(env, "java/lang/IllegalStateException");
+  if (!(*env)->ExceptionCheck(env) && message != NULL && type != NULL) {

Review Comment:
   Fixed in 
[dce536e8d00a747b8f23df0e663fbcbca962c3cc](https://github.com/apache/spark-connect-rust/commit/dce536e8d00a747b8f23df0e663fbcbca962c3cc).
 `throw_error` preserves an existing pending exception and uses a fixed-message 
`ThrowNew` fallback if constructing the detailed message fails. Allocation 
failures in the fallback also leave their exception pending. The C mock tests 
exercise these paths, including message-allocation failures, and pass normally 
and under ASan/UBSan.



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

To unsubscribe, e-mail: [email protected]

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


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

Reply via email to