From a23200ed14437601fa04d22a91d70d895654c5e2 Mon Sep 17 00:00:00 2001 From: Benoit Chesneau Date: Fri, 27 Nov 2026 01:27:41 +0100 Subject: [PATCH 1/4] Harden NIF resource ownership Prevent SharedDict lock inversion and cross-interpreter object access by storing serialized values in native memory. Guard partial resource construction, allocation failures and size arithmetic so cleanup and oversized inputs cannot corrupt or stall the VM. --- CHANGELOG.md | 8 + c_src/py_buffer.c | 26 +- c_src/py_buffer.h | 2 + c_src/py_callback.c | 72 ++- c_src/py_channel.c | 26 +- c_src/py_channel.h | 4 + c_src/py_event_loop.c | 175 +++--- c_src/py_event_loop.h | 10 + c_src/py_logging.c | 24 +- c_src/py_nif.c | 15 +- c_src/py_nif.h | 21 +- c_src/py_reactor_buffer.c | 1 + c_src/py_shared_dict.c | 989 +++++++++++-------------------- c_src/py_thread_worker.c | 15 +- test/py_SUITE.erl | 23 + test/py_context_owngil_SUITE.erl | 25 +- 16 files changed, 671 insertions(+), 765 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f73e9c6..60b249a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,14 @@ ### Fixed +- Shared dictionaries could deadlock the node when Erlang and Python used + one at the same time, or when pickling a value accessed the same dictionary. + Their stored values are now independent of any Python interpreter, so they + also work safely from `owngil` contexts. Native buffers, channels and event + loops now clean up safely when construction stops partway through instead + of freeing or destroying the same resource state twice. Oversized buffers, + callback frames and internal tables now fail instead of wrapping their + lengths or growing forever. - On an owngil context, the process-local environment of an Erlang process (`py:call/eval/exec` on the context) was kept until the context stopped: 300 short-lived processes each leaving 1 MB grew the node by 300 MB. The diff --git a/c_src/py_buffer.c b/c_src/py_buffer.c index 1ee1927..0a9f509 100644 --- a/c_src/py_buffer.c +++ b/c_src/py_buffer.c @@ -75,8 +75,14 @@ void py_buffer_resource_dtor(ErlNifEnv *env, void *obj) { (void)env; py_buffer_resource_t *buf = (py_buffer_resource_t *)obj; - pthread_mutex_destroy(&buf->mutex); - pthread_cond_destroy(&buf->data_ready); + if (buf->cond_initialized) { + pthread_cond_destroy(&buf->data_ready); + buf->cond_initialized = false; + } + if (buf->mutex_initialized) { + pthread_mutex_destroy(&buf->mutex); + buf->mutex_initialized = false; + } if (buf->data != NULL) { enif_free(buf->data); @@ -94,6 +100,7 @@ py_buffer_resource_t *py_buffer_alloc(ssize_t content_length) { if (resource == NULL) { return NULL; } + memset(resource, 0, sizeof(*resource)); /* Determine initial capacity */ size_t capacity; @@ -118,17 +125,16 @@ py_buffer_resource_t *py_buffer_alloc(ssize_t content_length) { resource->view_count = 0; if (pthread_mutex_init(&resource->mutex, NULL) != 0) { - enif_free(resource->data); enif_release_resource(resource); return NULL; } + resource->mutex_initialized = true; if (pthread_cond_init(&resource->data_ready, NULL) != 0) { - pthread_mutex_destroy(&resource->mutex); - enif_free(resource->data); enif_release_resource(resource); return NULL; } + resource->cond_initialized = true; return resource; } @@ -163,6 +169,10 @@ int py_buffer_write(py_buffer_resource_t *buf, const unsigned char *data, size_t /* Calculate new capacity */ size_t new_capacity = buf->capacity; while (new_capacity < required) { + if (new_capacity > SIZE_MAX / PY_BUFFER_GROW_FACTOR) { + pthread_mutex_unlock(&buf->mutex); + return -1; + } new_capacity *= PY_BUFFER_GROW_FACTOR; } @@ -601,6 +611,12 @@ static PyObject *PyBuffer_readlines(PyBufferObject *self, PyObject *args) { } Py_DECREF(line); + if (line_len > PY_SSIZE_T_MAX - total_size) { + Py_DECREF(empty_args); + Py_DECREF(lines); + PyErr_SetString(PyExc_OverflowError, "readlines result is too large"); + return NULL; + } total_size += line_len; /* Check hint */ diff --git a/c_src/py_buffer.h b/c_src/py_buffer.h index 8140d59..b2db0db 100644 --- a/c_src/py_buffer.h +++ b/c_src/py_buffer.h @@ -82,6 +82,8 @@ typedef struct { ssize_t content_length; /**< Expected total size, -1 for chunked */ pthread_mutex_t mutex; /**< Mutex for thread-safe access */ pthread_cond_t data_ready; /**< Condition for blocking reads */ + bool mutex_initialized; /**< Partial-construction guard */ + bool cond_initialized; /**< Partial-construction guard */ bool eof; /**< End of data flag (close called) */ bool closed; /**< Buffer closed flag */ int view_count; /**< Active Python buffer view count */ diff --git a/c_src/py_callback.c b/c_src/py_callback.c index 5d754db..d468e68 100644 --- a/c_src/py_callback.c +++ b/c_src/py_callback.c @@ -359,6 +359,15 @@ static void cleanup_callback_registry(void) { * @param kwargs_term Original kwargs term * @return suspended_context_state_t* or NULL on error */ +static void release_failed_suspended_context_state( + suspended_context_state_t *state) { + /* Constructors run with the owning interpreter's GIL. Clear the Python + * reference here because the resource destructor may run on a scheduler + * thread whose current thread state belongs to another interpreter. */ + Py_CLEAR(state->callback_args); + enif_release_resource(state); +} + static suspended_context_state_t *create_suspended_context_state_for_call( ErlNifEnv *env, py_context_t *ctx, @@ -377,6 +386,7 @@ static suspended_context_state_t *create_suspended_context_state_for_call( /* Initialize to zero */ memset(state, 0, sizeof(suspended_context_state_t)); + atomic_fetch_add(&g_counters.suspended_created, 1); state->ctx = ctx; enif_keep_resource(ctx); /* Keep ctx alive while suspended state exists */ @@ -390,7 +400,7 @@ static suspended_context_state_t *create_suspended_context_state_for_call( /* Copy callback function name */ state->callback_func_name = enif_alloc(tl_pending_func_name_len + 1); if (state->callback_func_name == NULL) { - enif_release_resource(state); + release_failed_suspended_context_state(state); return NULL; } memcpy(state->callback_func_name, tl_pending_func_name, tl_pending_func_name_len); @@ -404,29 +414,20 @@ static suspended_context_state_t *create_suspended_context_state_for_call( /* Create environment to hold copied terms */ state->orig_env = enif_alloc_env(); if (state->orig_env == NULL) { - Py_DECREF(state->callback_args); - enif_free(state->callback_func_name); - enif_release_resource(state); + release_failed_suspended_context_state(state); return NULL; } /* Copy module binary */ if (!enif_alloc_binary(module_bin->size, &state->orig_module)) { - enif_free_env(state->orig_env); - Py_DECREF(state->callback_args); - enif_free(state->callback_func_name); - enif_release_resource(state); + release_failed_suspended_context_state(state); return NULL; } memcpy(state->orig_module.data, module_bin->data, module_bin->size); /* Copy function binary */ if (!enif_alloc_binary(func_bin->size, &state->orig_func)) { - enif_release_binary(&state->orig_module); - enif_free_env(state->orig_env); - Py_DECREF(state->callback_args); - enif_free(state->callback_func_name); - enif_release_resource(state); + release_failed_suspended_context_state(state); return NULL; } memcpy(state->orig_func.data, func_bin->data, func_bin->size); @@ -435,7 +436,6 @@ static suspended_context_state_t *create_suspended_context_state_for_call( state->orig_args = enif_make_copy(state->orig_env, args_term); state->orig_kwargs = enif_make_copy(state->orig_env, kwargs_term); - atomic_fetch_add(&g_counters.suspended_created, 1); return state; } @@ -469,6 +469,7 @@ static suspended_context_state_t *create_suspended_context_state_for_eval( /* Initialize to zero */ memset(state, 0, sizeof(suspended_context_state_t)); + atomic_fetch_add(&g_counters.suspended_created, 1); state->ctx = ctx; enif_keep_resource(ctx); /* Keep ctx alive while suspended state exists */ @@ -482,7 +483,7 @@ static suspended_context_state_t *create_suspended_context_state_for_eval( /* Copy callback function name */ state->callback_func_name = enif_alloc(tl_pending_func_name_len + 1); if (state->callback_func_name == NULL) { - enif_release_resource(state); + release_failed_suspended_context_state(state); return NULL; } memcpy(state->callback_func_name, tl_pending_func_name, tl_pending_func_name_len); @@ -496,18 +497,13 @@ static suspended_context_state_t *create_suspended_context_state_for_eval( /* Create environment to hold copied terms */ state->orig_env = enif_alloc_env(); if (state->orig_env == NULL) { - Py_DECREF(state->callback_args); - enif_free(state->callback_func_name); - enif_release_resource(state); + release_failed_suspended_context_state(state); return NULL; } /* Copy code binary */ if (!enif_alloc_binary(code_bin->size, &state->orig_code)) { - enif_free_env(state->orig_env); - Py_DECREF(state->callback_args); - enif_free(state->callback_func_name); - enif_release_resource(state); + release_failed_suspended_context_state(state); return NULL; } memcpy(state->orig_code.data, code_bin->data, code_bin->size); @@ -515,7 +511,6 @@ static suspended_context_state_t *create_suspended_context_state_for_eval( /* Copy locals to our environment */ state->orig_locals = enif_make_copy(state->orig_env, locals_term); - atomic_fetch_add(&g_counters.suspended_created, 1); return state; } @@ -535,7 +530,12 @@ static ERL_NIF_TERM build_suspended_context_result(ErlNifEnv *env, suspended_con ERL_NIF_TERM func_name_term; unsigned char *fn_buf = enif_make_new_binary(env, tl_pending_func_name_len, &func_name_term); - memcpy(fn_buf, tl_pending_func_name, tl_pending_func_name_len); + if (fn_buf == NULL && tl_pending_func_name_len > 0) { + return make_error(env, "alloc_failed"); + } + if (tl_pending_func_name_len > 0) { + memcpy(fn_buf, tl_pending_func_name, tl_pending_func_name_len); + } ERL_NIF_TERM args_term = py_to_term(env, tl_pending_args); @@ -1801,7 +1801,13 @@ static PyObject *erlang_call_impl(PyObject *self, PyObject *args) { ERL_NIF_TERM func_term; { unsigned char *buf = enif_make_new_binary(msg_env, func_name_len, &func_term); - memcpy(buf, func_name, func_name_len); + if (buf == NULL && func_name_len > 0) { + enif_free_env(msg_env); + Py_DECREF(call_args); + PyErr_SetString(PyExc_MemoryError, "Failed to allocate callback name"); + return NULL; + } + if (func_name_len > 0) memcpy(buf, func_name, func_name_len); } ERL_NIF_TERM args_term = py_to_term(msg_env, call_args); @@ -2043,6 +2049,7 @@ typedef struct { * insert under the lock. */ pthread_mutex_t async_futures_mutex; + bool async_futures_mutex_initialized; bool pipe_initialized; /* Set on hard read error (EIO/EBADF/EOF mid-frame). New @@ -3438,8 +3445,10 @@ static void erlang_module_free(void *module) { Py_XDECREF(state->async_pending_futures); state->async_pending_futures = NULL; - /* Always destroy mutex - it was always initialized in create_erlang_module */ - pthread_mutex_destroy(&state->async_futures_mutex); + if (state->async_futures_mutex_initialized) { + pthread_mutex_destroy(&state->async_futures_mutex); + state->async_futures_mutex_initialized = false; + } state->pipe_initialized = false; } @@ -3518,7 +3527,14 @@ static int create_erlang_module(void) { state->async_callback_pipe[0] = -1; state->async_callback_pipe[1] = -1; state->async_pending_futures = NULL; - pthread_mutex_init(&state->async_futures_mutex, NULL); + state->async_futures_mutex_initialized = false; + if (pthread_mutex_init(&state->async_futures_mutex, NULL) != 0) { + Py_DECREF(module); + PyErr_SetString(PyExc_RuntimeError, + "failed to initialize async callback mutex"); + return -1; + } + state->async_futures_mutex_initialized = true; state->pipe_initialized = false; } diff --git a/c_src/py_channel.c b/c_src/py_channel.c index c78ba38..ee37262 100644 --- a/c_src/py_channel.c +++ b/c_src/py_channel.c @@ -70,9 +70,15 @@ void channel_resource_dtor(ErlNifEnv *env, void *obj) { } /* Wake any threads waiting on the condition before destroying */ - pthread_cond_broadcast(&channel->data_cond); - pthread_cond_destroy(&channel->data_cond); - pthread_mutex_destroy(&channel->mutex); + if (channel->cond_initialized) { + pthread_cond_broadcast(&channel->data_cond); + pthread_cond_destroy(&channel->data_cond); + channel->cond_initialized = false; + } + if (channel->mutex_initialized) { + pthread_mutex_destroy(&channel->mutex); + channel->mutex_initialized = false; + } } py_channel_t *channel_alloc(size_t max_size) { @@ -85,6 +91,7 @@ py_channel_t *channel_alloc(size_t max_size) { if (channel == NULL) { return NULL; } + memset(channel, 0, sizeof(*channel)); channel->queue = enif_ioq_create(ERL_NIF_IOQ_NORMAL); if (channel->queue == NULL) { @@ -103,17 +110,16 @@ py_channel_t *channel_alloc(size_t max_size) { channel->channel_id = atomic_fetch_add(&g_channel_id_counter, 1); if (pthread_mutex_init(&channel->mutex, NULL) != 0) { - enif_ioq_destroy(channel->queue); enif_release_resource(channel); return NULL; } + channel->mutex_initialized = true; if (pthread_cond_init(&channel->data_cond, NULL) != 0) { - pthread_mutex_destroy(&channel->mutex); - enif_ioq_destroy(channel->queue); enif_release_resource(channel); return NULL; } + channel->cond_initialized = true; return channel; } @@ -127,7 +133,9 @@ int channel_send(py_channel_t *channel, const unsigned char *data, size_t size) } /* Check backpressure */ - if (channel->max_size > 0 && channel->current_size + size > channel->max_size) { + if (size > SIZE_MAX - channel->current_size || + (channel->max_size > 0 && + channel->current_size + size > channel->max_size)) { pthread_mutex_unlock(&channel->mutex); return 1; /* Busy - backpressure */ } @@ -211,7 +219,9 @@ int channel_send_owned_binary(py_channel_t *channel, ErlNifBinary *bin) { } /* Check backpressure */ - if (channel->max_size > 0 && channel->current_size + bin->size > channel->max_size) { + if (bin->size > SIZE_MAX - channel->current_size || + (channel->max_size > 0 && + channel->current_size + bin->size > channel->max_size)) { enif_release_binary(bin); pthread_mutex_unlock(&channel->mutex); return 1; /* Busy - backpressure */ diff --git a/c_src/py_channel.h b/c_src/py_channel.h index f8fc456..d18da28 100644 --- a/c_src/py_channel.h +++ b/c_src/py_channel.h @@ -89,6 +89,10 @@ typedef struct { /** @brief Condition variable for blocking receives */ pthread_cond_t data_cond; + /** @brief Partial-construction guards for synchronization objects */ + bool mutex_initialized; + bool cond_initialized; + /** @brief Event loop for async waiter (ref-counted via enif_keep_resource) */ struct erlang_event_loop *waiter_loop; diff --git a/c_src/py_event_loop.c b/c_src/py_event_loop.c index d089c8e..b83d834 100644 --- a/c_src/py_event_loop.c +++ b/c_src/py_event_loop.c @@ -417,12 +417,14 @@ void event_loop_destructor(ErlNifEnv *env, void *obj) { loop->shutdown = true; /* Wake up any waiting threads */ - pthread_mutex_lock(&loop->mutex); - pthread_cond_broadcast(&loop->event_cond); - pthread_mutex_unlock(&loop->mutex); + if (loop->mutex_initialized && loop->event_cond_initialized) { + pthread_mutex_lock(&loop->mutex); + pthread_cond_broadcast(&loop->event_cond); + pthread_mutex_unlock(&loop->mutex); + } /* Clear pending events (returns them to freelist) */ - event_loop_clear_pending(loop); + if (loop->mutex_initialized) event_loop_clear_pending(loop); /* Free the freelist itself (Phase 7: clear freelist on destruction) */ pending_event_t *freelist_item = loop->event_freelist; @@ -452,7 +454,10 @@ void event_loop_destructor(ErlNifEnv *env, void *obj) { } } loop->env_pool_count = 0; - pthread_mutex_destroy(&loop->env_pool_mutex); + if (loop->env_pool_mutex_initialized) { + pthread_mutex_destroy(&loop->env_pool_mutex); + loop->env_pool_mutex_initialized = false; + } /* Release Python loop reference if held */ if (loop->py_loop_valid && loop->py_loop != NULL) { @@ -496,7 +501,8 @@ void event_loop_destructor(ErlNifEnv *env, void *obj) { * Just free the native structs without Py_DECREF - Python objects will be * cleaned up when the interpreter is destroyed. */ - if (runtime_is_running() && loop->interp_id == 0 && + if (loop->namespaces_mutex_initialized && + runtime_is_running() && loop->interp_id == 0 && PyGILState_GetThisThreadState() == NULL && !PyGILState_Check()) { /* Main interpreter: GIL first, then mutex */ @@ -528,7 +534,7 @@ void event_loop_destructor(ErlNifEnv *env, void *obj) { pthread_mutex_unlock(&loop->namespaces_mutex); PyGILState_Release(gstate); - } else { + } else if (loop->namespaces_mutex_initialized) { /* Subinterpreter or runtime not running. Namespaces created in the * subinterpreter went (or go) with it; those created in the main * interpreter (event_loop_exec/eval) are released under the main @@ -575,11 +581,20 @@ void event_loop_destructor(ErlNifEnv *env, void *obj) { pthread_mutex_unlock(&loop->namespaces_mutex); } - pthread_mutex_destroy(&loop->namespaces_mutex); + if (loop->namespaces_mutex_initialized) { + pthread_mutex_destroy(&loop->namespaces_mutex); + loop->namespaces_mutex_initialized = false; + } /* Destroy synchronization primitives */ - pthread_mutex_destroy(&loop->mutex); - pthread_cond_destroy(&loop->event_cond); + if (loop->event_cond_initialized) { + pthread_cond_destroy(&loop->event_cond); + loop->event_cond_initialized = false; + } + if (loop->mutex_initialized) { + pthread_mutex_destroy(&loop->mutex); + loop->mutex_initialized = false; + } } /** @@ -1185,17 +1200,16 @@ ERL_NIF_TERM nif_event_loop_new(ErlNifEnv *env, int argc, enif_release_resource(loop); return make_error(env, "mutex_init_failed"); } + loop->mutex_initialized = true; if (pthread_cond_init(&loop->event_cond, NULL) != 0) { - pthread_mutex_destroy(&loop->mutex); enif_release_resource(loop); return make_error(env, "cond_init_failed"); } + loop->event_cond_initialized = true; loop->msg_env = enif_alloc_env(); if (loop->msg_env == NULL) { - pthread_cond_destroy(&loop->event_cond); - pthread_mutex_destroy(&loop->mutex); enif_release_resource(loop); return make_error(env, "env_alloc_failed"); } @@ -1213,18 +1227,11 @@ ERL_NIF_TERM nif_event_loop_new(ErlNifEnv *env, int argc, /* Initialize async task queue (uvloop-inspired) */ loop->task_queue = enif_ioq_create(ERL_NIF_IOQ_NORMAL); if (loop->task_queue == NULL) { - pthread_cond_destroy(&loop->event_cond); - pthread_mutex_destroy(&loop->mutex); - enif_free_env(loop->msg_env); enif_release_resource(loop); return make_error(env, "task_queue_alloc_failed"); } if (pthread_mutex_init(&loop->task_queue_mutex, NULL) != 0) { - enif_ioq_destroy(loop->task_queue); - pthread_cond_destroy(&loop->event_cond); - pthread_mutex_destroy(&loop->mutex); - enif_free_env(loop->msg_env); enif_release_resource(loop); return make_error(env, "task_queue_mutex_init_failed"); } @@ -1249,28 +1256,19 @@ ERL_NIF_TERM nif_event_loop_new(ErlNifEnv *env, int argc, memset(loop->env_pool, 0, sizeof(loop->env_pool)); loop->env_pool_count = 0; if (pthread_mutex_init(&loop->env_pool_mutex, NULL) != 0) { - pthread_mutex_destroy(&loop->task_queue_mutex); - enif_ioq_destroy(loop->task_queue); - pthread_cond_destroy(&loop->event_cond); - pthread_mutex_destroy(&loop->mutex); - enif_free_env(loop->msg_env); enif_release_resource(loop); return make_error(env, "env_pool_mutex_init_failed"); } + loop->env_pool_mutex_initialized = true; /* Initialize per-process namespace registry */ loop->namespaces_head = NULL; loop->pid_env_head = NULL; if (pthread_mutex_init(&loop->namespaces_mutex, NULL) != 0) { - pthread_mutex_destroy(&loop->env_pool_mutex); - pthread_mutex_destroy(&loop->task_queue_mutex); - enif_ioq_destroy(loop->task_queue); - pthread_cond_destroy(&loop->event_cond); - pthread_mutex_destroy(&loop->mutex); - enif_free_env(loop->msg_env); enif_release_resource(loop); return make_error(env, "namespaces_mutex_init_failed"); } + loop->namespaces_mutex_initialized = true; /* Create result */ ERL_NIF_TERM loop_term = enif_make_resource(env, loop); @@ -4075,7 +4073,14 @@ ERL_NIF_TERM nif_loop_import_function(ErlNifEnv *env, int argc, } /* Build cache key "module.func" */ - size_t key_len = module_bin.size + 1 + func_bin.size + 1; + if (module_bin.size > SIZE_MAX - 2 || + func_bin.size > SIZE_MAX - module_bin.size - 2) { + PyGILState_Release(gstate); + enif_free(module_name); + enif_free(func_name); + return make_error(env, "name_too_long"); + } + size_t key_len = module_bin.size + func_bin.size + 2; char *cache_key = enif_alloc(key_len); if (cache_key == NULL) { PyGILState_Release(gstate); @@ -4332,6 +4337,11 @@ ERL_NIF_TERM nif_loop_import_list(ErlNifEnv *env, int argc, size_t key_len = strlen(key_str); ERL_NIF_TERM mod_bin; unsigned char *buf = enif_make_new_binary(env, key_len, &mod_bin); + if (buf == NULL && key_len > 0) { + Py_DECREF(keys); + PyGILState_Release(gstate); + return make_error(env, "alloc_failed"); + } memcpy(buf, key_str, key_len); /* Start with empty function list */ @@ -4357,11 +4367,21 @@ ERL_NIF_TERM nif_loop_import_list(ErlNifEnv *env, int argc, /* Create module binary */ ERL_NIF_TERM mod_bin; unsigned char *mod_buf = enif_make_new_binary(env, mod_len, &mod_bin); + if (mod_buf == NULL && mod_len > 0) { + Py_DECREF(keys); + PyGILState_Release(gstate); + return make_error(env, "alloc_failed"); + } memcpy(mod_buf, key_str, mod_len); /* Create function binary */ ERL_NIF_TERM func_bin; unsigned char *func_buf = enif_make_new_binary(env, func_len, &func_bin); + if (func_buf == NULL && func_len > 0) { + Py_DECREF(keys); + PyGILState_Release(gstate); + return make_error(env, "alloc_failed"); + } memcpy(func_buf, func_str, func_len); /* Get existing function list for this module */ @@ -5515,6 +5535,10 @@ ERL_NIF_TERM nif_recvfrom_test_udp(ErlNifEnv *env, int argc, ERL_NIF_TERM host_bin; size_t host_len = strlen(host_str); unsigned char *host_buf = enif_make_new_binary(env, host_len, &host_bin); + if (host_buf == NULL && host_len > 0) { + enif_release_binary(&bin); + return make_error(env, "alloc_failed"); + } memcpy(host_buf, host_str, host_len); int from_port = ntohs(from_addr.sin_port); @@ -5954,7 +5978,11 @@ ERL_NIF_TERM nif_reactor_on_read_ready(ErlNifEnv *env, int argc, if (str != NULL) { size_t len = strlen(str); unsigned char *buf = enif_make_new_binary(env, len, &action); - memcpy(buf, str, len); + if (buf != NULL || len == 0) { + if (len > 0) memcpy(buf, str, len); + } else { + action = enif_make_atom(env, "unknown"); + } } else { action = enif_make_atom(env, "unknown"); } @@ -6035,7 +6063,11 @@ ERL_NIF_TERM nif_reactor_on_write_ready(ErlNifEnv *env, int argc, if (str != NULL) { size_t len = strlen(str); unsigned char *buf = enif_make_new_binary(env, len, &action); - memcpy(buf, str, len); + if (buf != NULL || len == 0) { + if (len > 0) memcpy(buf, str, len); + } else { + action = enif_make_atom(env, "unknown"); + } } else { action = enif_make_atom(env, "unknown"); } @@ -6482,7 +6514,11 @@ ERL_NIF_TERM owngil_reactor_on_read_ready(ErlNifEnv *env, int fd, void *buffer_p if (str != NULL) { size_t len = strlen(str); unsigned char *buf = enif_make_new_binary(env, len, &action); - memcpy(buf, str, len); + if (buf != NULL || len == 0) { + if (len > 0) memcpy(buf, str, len); + } else { + action = enif_make_atom(env, "unknown"); + } } else { action = enif_make_atom(env, "unknown"); } @@ -6528,7 +6564,11 @@ ERL_NIF_TERM owngil_reactor_on_write_ready(ErlNifEnv *env, int fd) { if (str != NULL) { size_t len = strlen(str); unsigned char *buf = enif_make_new_binary(env, len, &action); - memcpy(buf, str, len); + if (buf != NULL || len == 0) { + if (len > 0) memcpy(buf, str, len); + } else { + action = enif_make_atom(env, "unknown"); + } } else { action = enif_make_atom(env, "unknown"); } @@ -6877,8 +6917,20 @@ static pthread_mutex_t g_fd_reg_mutex = PTHREAD_MUTEX_INITIALIZER; * existing resource reference becomes owned by the table entry. */ static uint64_t fd_reg_add(fd_resource_t *res) { pthread_mutex_lock(&g_fd_reg_mutex); + if (g_fd_reg_next_id == 0) { + pthread_mutex_unlock(&g_fd_reg_mutex); + return 0; + } if (g_fd_reg_len == g_fd_reg_cap) { + if (g_fd_reg_cap > SIZE_MAX / 2) { + pthread_mutex_unlock(&g_fd_reg_mutex); + return 0; + } size_t ncap = g_fd_reg_cap ? g_fd_reg_cap * 2 : 16; + if (ncap > SIZE_MAX / sizeof(*g_fd_reg)) { + pthread_mutex_unlock(&g_fd_reg_mutex); + return 0; + } fd_reg_entry_t *n = enif_realloc(g_fd_reg, ncap * sizeof(*n)); if (n == NULL) { pthread_mutex_unlock(&g_fd_reg_mutex); @@ -6888,7 +6940,6 @@ static uint64_t fd_reg_add(fd_resource_t *res) { g_fd_reg_cap = ncap; } uint64_t id = g_fd_reg_next_id++; - if (id == 0) id = g_fd_reg_next_id++; /* never hand out 0 */ g_fd_reg[g_fd_reg_len].id = id; g_fd_reg[g_fd_reg_len].res = res; g_fd_reg_len++; @@ -7418,18 +7469,17 @@ static PyObject *py_loop_new(PyObject *self, PyObject *args) { PyErr_SetString(PyExc_RuntimeError, "Failed to initialize mutex"); return NULL; } + loop->mutex_initialized = true; if (pthread_cond_init(&loop->event_cond, NULL) != 0) { - pthread_mutex_destroy(&loop->mutex); enif_release_resource(loop); PyErr_SetString(PyExc_RuntimeError, "Failed to initialize condition variable"); return NULL; } + loop->event_cond_initialized = true; loop->msg_env = enif_alloc_env(); if (loop->msg_env == NULL) { - pthread_cond_destroy(&loop->event_cond); - pthread_mutex_destroy(&loop->mutex); enif_release_resource(loop); PyErr_SetString(PyExc_MemoryError, "Failed to allocate message environment"); return NULL; @@ -7448,19 +7498,12 @@ static PyObject *py_loop_new(PyObject *self, PyObject *args) { /* Initialize async task queue (uvloop-inspired) */ loop->task_queue = enif_ioq_create(ERL_NIF_IOQ_NORMAL); if (loop->task_queue == NULL) { - pthread_cond_destroy(&loop->event_cond); - pthread_mutex_destroy(&loop->mutex); - enif_free_env(loop->msg_env); enif_release_resource(loop); PyErr_SetString(PyExc_MemoryError, "Failed to allocate task queue"); return NULL; } if (pthread_mutex_init(&loop->task_queue_mutex, NULL) != 0) { - enif_ioq_destroy(loop->task_queue); - pthread_cond_destroy(&loop->event_cond); - pthread_mutex_destroy(&loop->mutex); - enif_free_env(loop->msg_env); enif_release_resource(loop); PyErr_SetString(PyExc_RuntimeError, "Failed to initialize task queue mutex"); return NULL; @@ -7494,9 +7537,6 @@ static PyObject *py_loop_new(PyObject *self, PyObject *args) { /* Create a capsule wrapping the loop pointer */ PyObject *capsule = PyCapsule_New(loop, LOOP_CAPSULE_NAME, loop_capsule_destructor); if (capsule == NULL) { - pthread_cond_destroy(&loop->event_cond); - pthread_mutex_destroy(&loop->mutex); - enif_free_env(loop->msg_env); enif_release_resource(loop); return NULL; } @@ -8578,17 +8618,16 @@ int create_default_event_loop(ErlNifEnv *env) { enif_release_resource(loop); return -1; } + loop->mutex_initialized = true; if (pthread_cond_init(&loop->event_cond, NULL) != 0) { - pthread_mutex_destroy(&loop->mutex); enif_release_resource(loop); return -1; } + loop->event_cond_initialized = true; loop->msg_env = enif_alloc_env(); if (loop->msg_env == NULL) { - pthread_cond_destroy(&loop->event_cond); - pthread_mutex_destroy(&loop->mutex); enif_release_resource(loop); return -1; } @@ -8605,15 +8644,11 @@ int create_default_event_loop(ErlNifEnv *env) { * nif_event_loop_new: a default loop must accept submit_task too, since * OWN_GIL contexts only ever have this loop. */ loop->task_queue = enif_ioq_create(ERL_NIF_IOQ_NORMAL); - if (loop->task_queue == NULL || - pthread_mutex_init(&loop->task_queue_mutex, NULL) != 0) { - if (loop->task_queue != NULL) { - enif_ioq_destroy(loop->task_queue); - loop->task_queue = NULL; - } - enif_free_env(loop->msg_env); - pthread_cond_destroy(&loop->event_cond); - pthread_mutex_destroy(&loop->mutex); + if (loop->task_queue == NULL) { + enif_release_resource(loop); + return -1; + } + if (pthread_mutex_init(&loop->task_queue_mutex, NULL) != 0) { enif_release_resource(loop); return -1; } @@ -8625,18 +8660,16 @@ int create_default_event_loop(ErlNifEnv *env) { loop->py_cache_valid = false; loop->callable_cache_count = 0; loop->env_pool_count = 0; - if (pthread_mutex_init(&loop->env_pool_mutex, NULL) != 0 || - pthread_mutex_init(&loop->namespaces_mutex, NULL) != 0) { - pthread_mutex_destroy(&loop->task_queue_mutex); - loop->task_queue_initialized = false; - enif_ioq_destroy(loop->task_queue); - loop->task_queue = NULL; - enif_free_env(loop->msg_env); - pthread_cond_destroy(&loop->event_cond); - pthread_mutex_destroy(&loop->mutex); + if (pthread_mutex_init(&loop->env_pool_mutex, NULL) != 0) { + enif_release_resource(loop); + return -1; + } + loop->env_pool_mutex_initialized = true; + if (pthread_mutex_init(&loop->namespaces_mutex, NULL) != 0) { enif_release_resource(loop); return -1; } + loop->namespaces_mutex_initialized = true; loop->namespaces_head = NULL; loop->pid_env_head = NULL; diff --git a/c_src/py_event_loop.h b/c_src/py_event_loop.h index db7220a..130af01 100644 --- a/c_src/py_event_loop.h +++ b/c_src/py_event_loop.h @@ -337,6 +337,10 @@ typedef struct erlang_event_loop { /** @brief Condition variable for event notification */ pthread_cond_t event_cond; + /** @brief Partial-construction guards for base synchronization objects */ + bool mutex_initialized; + bool event_cond_initialized; + /** @brief Counter for generating unique callback IDs */ _Atomic uint64_t next_callback_id; @@ -432,6 +436,12 @@ typedef struct erlang_event_loop { /** @brief Whether task_queue has been initialized */ bool task_queue_initialized; + /** @brief Partial-construction guard for the environment pool mutex */ + bool env_pool_mutex_initialized; + + /** @brief Partial-construction guard for the namespace registry mutex */ + bool namespaces_mutex_initialized; + /** @brief Atomic counter for pending tasks */ _Atomic uint_fast64_t task_count; diff --git a/c_src/py_logging.c b/c_src/py_logging.c index 1ca5077..1591f25 100644 --- a/c_src/py_logging.c +++ b/c_src/py_logging.c @@ -147,15 +147,19 @@ static PyObject *erlang_log_impl(PyObject *self, PyObject *args) { ERL_NIF_TERM logger_term; unsigned char *logger_buf = enif_make_new_binary(msg_env, logger_name_len, &logger_term); - if (logger_buf != NULL) { - memcpy(logger_buf, logger_name, logger_name_len); + if (logger_buf == NULL && logger_name_len > 0) { + enif_free_env(msg_env); + Py_RETURN_NONE; } + if (logger_name_len > 0) memcpy(logger_buf, logger_name, logger_name_len); ERL_NIF_TERM message_term; unsigned char *msg_buf = enif_make_new_binary(msg_env, message_len, &message_term); - if (msg_buf != NULL) { - memcpy(msg_buf, message, message_len); + if (msg_buf == NULL && message_len > 0) { + enif_free_env(msg_env); + Py_RETURN_NONE; } + if (message_len > 0) memcpy(msg_buf, message, message_len); /* Convert metadata dict to Erlang map */ ERL_NIF_TERM meta_term = py_to_term(msg_env, metadata); @@ -223,9 +227,11 @@ static PyObject *erlang_trace_start_impl(PyObject *self, PyObject *args) { ERL_NIF_TERM name_term; unsigned char *name_buf = enif_make_new_binary(msg_env, name_len, &name_term); - if (name_buf != NULL) { - memcpy(name_buf, name, name_len); + if (name_buf == NULL && name_len > 0) { + enif_free_env(msg_env); + Py_RETURN_NONE; } + if (name_len > 0) memcpy(name_buf, name, name_len); ERL_NIF_TERM attrs_term = py_to_term(msg_env, attrs); @@ -331,9 +337,11 @@ static PyObject *erlang_trace_event_impl(PyObject *self, PyObject *args) { ERL_NIF_TERM name_term; unsigned char *name_buf = enif_make_new_binary(msg_env, name_len, &name_term); - if (name_buf != NULL) { - memcpy(name_buf, name, name_len); + if (name_buf == NULL && name_len > 0) { + enif_free_env(msg_env); + Py_RETURN_NONE; } + if (name_len > 0) memcpy(name_buf, name, name_len); ERL_NIF_TERM attrs_term = py_to_term(msg_env, attrs); diff --git a/c_src/py_nif.c b/c_src/py_nif.c index 5406cae..4396558 100644 --- a/c_src/py_nif.c +++ b/c_src/py_nif.c @@ -1005,6 +1005,7 @@ static ERL_NIF_TERM nif_version(ErlNifEnv *env, int argc, const ERL_NIF_TERM arg ERL_NIF_TERM version_bin; unsigned char *buf = enif_make_new_binary(env, strlen(version), &version_bin); + if (buf == NULL) return make_error(env, "alloc_failed"); memcpy(buf, version, strlen(version)); return enif_make_tuple2(env, ATOM_OK, version_bin); @@ -2545,7 +2546,12 @@ static PyObject *ctx_call_erlang_inline(py_context_t *ctx, const char *func_name } ERL_NIF_TERM name_term; unsigned char *name_buf = enif_make_new_binary(msg_env, func_name_len, &name_term); - memcpy(name_buf, func_name, func_name_len); + if (name_buf == NULL && func_name_len > 0) { + enif_free_env(msg_env); + PyErr_SetString(PyExc_MemoryError, "Failed to allocate callback name"); + return NULL; + } + if (func_name_len > 0) memcpy(name_buf, func_name, func_name_len); ERL_NIF_TERM args_term = py_to_term(msg_env, call_args); ERL_NIF_TERM msg = enif_make_tuple4(msg_env, enif_make_atom(msg_env, "py_callback"), @@ -3618,6 +3624,7 @@ static ERL_NIF_TERM nif_context_create(ErlNifEnv *env, int argc, const ERL_NIF_T } /* Initialize fields */ + memset(ctx, 0, sizeof(*ctx)); ctx->interp_id = atomic_fetch_add(&g_context_id_counter, 1); atomic_init(&ctx->env_gc_head, NULL); ctx->is_subinterp = use_owngil; @@ -3667,8 +3674,7 @@ static ERL_NIF_TERM nif_context_create(ErlNifEnv *env, int argc, const ERL_NIF_T if (use_owngil) { /* OWN_GIL mode: create dedicated pthread with OWN_GIL subinterpreter */ if (owngil_context_init(ctx) != 0) { - close(ctx->callback_pipe[0]); - close(ctx->callback_pipe[1]); + close_pipe_pair(ctx->callback_pipe); enif_release_resource(ctx); return make_error(env, "owngil_init_failed"); } @@ -3683,8 +3689,7 @@ static ERL_NIF_TERM nif_context_create(ErlNifEnv *env, int argc, const ERL_NIF_T /* Worker mode: create dedicated pthread with main interpreter * This provides stable thread affinity for numpy/torch/tensorflow */ if (worker_context_init(ctx) != 0) { - close(ctx->callback_pipe[0]); - close(ctx->callback_pipe[1]); + close_pipe_pair(ctx->callback_pipe); enif_release_resource(ctx); return make_error(env, "worker_init_failed"); } diff --git a/c_src/py_nif.h b/c_src/py_nif.h index c701a97..fdf1278 100644 --- a/c_src/py_nif.h +++ b/c_src/py_nif.h @@ -255,6 +255,15 @@ static inline bool runtime_is_shutting_down(void) { * to help detect resource leaks and imbalanced operations. At shutdown, * paired counters should be equal. */ +typedef struct py_shared_dict_entry { + struct py_shared_dict_entry *next; + size_t key_len; + size_t value_len; + unsigned char data[]; +} py_shared_dict_entry_t; + +#define PY_SHARED_DICT_BUCKETS 64 + typedef struct { /* GIL operations */ _Atomic uint64_t gil_ensure_count; /**< PyGILState_Ensure calls */ @@ -1346,11 +1355,17 @@ typedef struct { /** @brief Whether the monitor is currently active */ bool monitor_active; - /** @brief Mutex for thread-safe dict operations */ + /** @brief Mutex for thread-safe native table operations */ pthread_mutex_t mutex; - /** @brief Python dict storing keys -> pickled bytes */ - PyObject *dict; + /** @brief Whether mutex was initialized (partial-construction guard) */ + bool mutex_initialized; + + /** @brief Native table storing byte keys -> pickled byte values */ + py_shared_dict_entry_t *buckets[PY_SHARED_DICT_BUCKETS]; + + /** @brief Number of entries in buckets */ + size_t size; /** @brief Atomic flag: true if dict has been destroyed (owner died) */ _Atomic bool destroyed; diff --git a/c_src/py_reactor_buffer.c b/c_src/py_reactor_buffer.c index fa3fd63..47fa7af 100644 --- a/c_src/py_reactor_buffer.c +++ b/c_src/py_reactor_buffer.c @@ -79,6 +79,7 @@ reactor_buffer_resource_t *reactor_buffer_alloc(size_t capacity) { if (resource == NULL) { return NULL; } + memset(resource, 0, sizeof(*resource)); resource->data = enif_alloc(capacity); if (resource->data == NULL) { diff --git a/c_src/py_shared_dict.c b/c_src/py_shared_dict.c index 265b860..7de5694 100644 --- a/c_src/py_shared_dict.c +++ b/c_src/py_shared_dict.c @@ -1,825 +1,546 @@ -/* - * Copyright 2026 Benoit Chesneau - * - * Licensed 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. - */ +/* Copyright 2026 Benoit Chesneau. Licensed under the Apache License, Version 2.0. */ /** - * py_shared_dict.c - SharedDict implementation for Erlang-Python bridge + * Native storage for SharedDict. * - * This file implements process-scoped shared dictionaries that allow - * Python code running in different contexts to share data safely. - * - * Features: - * - Process-scoped: owned by an Erlang process, destroyed when process dies - * - Thread-safe: mutex-protected operations - * - Cross-interpreter safe: values stored as pickled bytes + * Only byte strings cross interpreters. Pickling and unpickling happen before + * or after the table lock, never while it is held. Consequently Python code + * runs under its own interpreter's GIL and cannot invert the GIL/table-lock + * order or re-enter a locked dictionary from pickle callbacks. */ -/* ============================================================================ - * Resource Callbacks - * ============================================================================ */ - -/** - * @brief Destructor for py_shared_dict_t - * - * Called when the resource is garbage collected. - * Cleans up the monitor, Python dict, and mutex. - */ -static void shared_dict_destructor(ErlNifEnv *env, void *obj) { - py_shared_dict_t *sd = (py_shared_dict_t *)obj; - - /* Demonitor if still active */ - if (sd->monitor_active && env != NULL) { - enif_demonitor_process(env, sd, &sd->monitor); - sd->monitor_active = false; - } +typedef struct { unsigned char *data; size_t len; } shared_dict_bytes_t; +typedef struct { unsigned char *data; size_t len; } shared_dict_key_t; - /* Clear Python dict if runtime is still running */ - if (runtime_is_running() && sd->dict != NULL) { - PyGILState_STATE gstate = PyGILState_Ensure(); - Py_CLEAR(sd->dict); - PyGILState_Release(gstate); +static uint64_t shared_dict_hash(const unsigned char *key, size_t len) { + uint64_t hash = UINT64_C(1469598103934665603); + for (size_t i = 0; i < len; i++) { + hash ^= key[i]; + hash *= UINT64_C(1099511628211); } - - /* Destroy mutex */ - pthread_mutex_destroy(&sd->mutex); + return hash; } -/* ============================================================================ - * NIF Functions - * ============================================================================ */ - -/** - * @brief Create a new process-scoped SharedDict - * - * Creates a SharedDict owned by the calling process. The dict is automatically - * destroyed when the owning process terminates. - * - * @return {ok, Reference} on success, {error, Reason} on failure - */ -static ERL_NIF_TERM nif_shared_dict_new(ErlNifEnv *env, int argc, - const ERL_NIF_TERM argv[]) { - (void)argc; - (void)argv; - - RUNTIME_CHECK_ERROR(env); +static unsigned char *shared_dict_value(py_shared_dict_entry_t *entry) { + return entry->data + entry->key_len; +} - /* Allocate resource */ - py_shared_dict_t *sd = enif_alloc_resource( - PY_SHARED_DICT_RESOURCE_TYPE, sizeof(py_shared_dict_t)); - if (sd == NULL) { - return make_error_atom(env, "alloc_failed"); +static py_shared_dict_entry_t *shared_dict_find_locked( + py_shared_dict_t *sd, const unsigned char *key, size_t key_len, + py_shared_dict_entry_t ***link_out) { + size_t bucket = (size_t)(shared_dict_hash(key, key_len) % PY_SHARED_DICT_BUCKETS); + py_shared_dict_entry_t **link = &sd->buckets[bucket]; + while (*link != NULL) { + py_shared_dict_entry_t *entry = *link; + if (entry->key_len == key_len && + (key_len == 0 || memcmp(entry->data, key, key_len) == 0)) { + if (link_out != NULL) *link_out = link; + return entry; + } + link = &entry->next; } + if (link_out != NULL) *link_out = link; + return NULL; +} - /* Initialize fields */ - memset(sd, 0, sizeof(py_shared_dict_t)); - atomic_store(&sd->destroyed, false); - pthread_mutex_init(&sd->mutex, NULL); +static py_shared_dict_entry_t *shared_dict_entry_new( + const unsigned char *key, size_t key_len, + const unsigned char *value, size_t value_len) { + if (key_len > SIZE_MAX - value_len || + sizeof(py_shared_dict_entry_t) > SIZE_MAX - key_len - value_len) return NULL; + py_shared_dict_entry_t *entry = enif_alloc( + sizeof(*entry) + key_len + value_len); + if (entry == NULL) return NULL; + entry->next = NULL; + entry->key_len = key_len; + entry->value_len = value_len; + if (key_len > 0) memcpy(entry->data, key, key_len); + if (value_len > 0) memcpy(entry->data + key_len, value, value_len); + return entry; +} - /* Create Python dict for storage */ - PyGILState_STATE gstate = PyGILState_Ensure(); - sd->dict = PyDict_New(); - if (sd->dict == NULL) { - PyGILState_Release(gstate); - pthread_mutex_destroy(&sd->mutex); - enif_release_resource(sd); - return make_error_atom(env, "dict_alloc_failed"); +static void shared_dict_free_entries(py_shared_dict_entry_t *entry) { + while (entry != NULL) { + py_shared_dict_entry_t *next = entry->next; + enif_free(entry); + entry = next; } - PyGILState_Release(gstate); - - /* SharedDict is GC-scoped: the resource destructor runs once the - * last term reference is dropped (or at process exit), at which - * point the underlying Python dict is cleared. There is no - * per-process monitor — callers that want eager release must call - * shared_dict_destroy/1 explicitly. */ - sd->monitor_active = false; - - /* Create reference term and release our reference */ - ERL_NIF_TERM ref = enif_make_resource(env, sd); - enif_release_resource(sd); - - return enif_make_tuple2(env, ATOM_OK, ref); } -/** - * @brief Get a value from SharedDict - * - * @param Handle SharedDict reference - * @param Key Binary key - * @param Default Default value if key not found - * @return Value or Default, badarg if destroyed - */ -static ERL_NIF_TERM nif_shared_dict_get(ErlNifEnv *env, int argc, - const ERL_NIF_TERM argv[]) { - (void)argc; - - py_shared_dict_t *sd; - GET_RESOURCE_OR_BADARG(env, argv[0], PY_SHARED_DICT_RESOURCE_TYPE, &sd); - CHECK_NOT_DESTROYED(env, sd); - - /* Get key as binary */ - ErlNifBinary key_bin; - INSPECT_BINARY_OR_BADARG(env, argv[1], key_bin); +static py_shared_dict_entry_t *shared_dict_detach_all_locked(py_shared_dict_t *sd) { + py_shared_dict_entry_t *head = NULL; + for (size_t i = 0; i < PY_SHARED_DICT_BUCKETS; i++) { + py_shared_dict_entry_t *entry = sd->buckets[i]; + while (entry != NULL) { + py_shared_dict_entry_t *next = entry->next; + entry->next = head; + head = entry; + entry = next; + } + sd->buckets[i] = NULL; + } + sd->size = 0; + return head; +} - /* Lock and access dict */ +static void shared_dict_destroy_contents(py_shared_dict_t *sd) { + if (!sd->mutex_initialized) return; pthread_mutex_lock(&sd->mutex); + atomic_store(&sd->destroyed, true); + py_shared_dict_entry_t *entries = shared_dict_detach_all_locked(sd); + pthread_mutex_unlock(&sd->mutex); + shared_dict_free_entries(entries); +} - /* Check destroyed again after acquiring lock */ - if (atomic_load(&sd->destroyed) || sd->dict == NULL) { +static int shared_dict_store(py_shared_dict_t *sd, + const unsigned char *key, size_t key_len, + const unsigned char *value, size_t value_len) { + py_shared_dict_entry_t *new_entry = shared_dict_entry_new( + key, key_len, value, value_len); + if (new_entry == NULL) return -1; + pthread_mutex_lock(&sd->mutex); + if (atomic_load(&sd->destroyed)) { pthread_mutex_unlock(&sd->mutex); - return enif_make_badarg(env); + enif_free(new_entry); + return 1; } + py_shared_dict_entry_t **link; + py_shared_dict_entry_t *old = shared_dict_find_locked(sd, key, key_len, &link); + new_entry->next = old != NULL ? old->next : NULL; + *link = new_entry; + if (old == NULL) sd->size++; + pthread_mutex_unlock(&sd->mutex); + if (old != NULL) enif_free(old); + return 0; +} - PyGILState_STATE gstate = PyGILState_Ensure(); +/* 1 found, 0 absent, -1 destroyed, -2 allocation failure. */ +static int shared_dict_copy_value(py_shared_dict_t *sd, + const unsigned char *key, size_t key_len, + shared_dict_bytes_t *out) { + out->data = NULL; + out->len = 0; + pthread_mutex_lock(&sd->mutex); + if (atomic_load(&sd->destroyed)) { + pthread_mutex_unlock(&sd->mutex); + return -1; + } + py_shared_dict_entry_t *entry = shared_dict_find_locked(sd, key, key_len, NULL); + if (entry == NULL) { + pthread_mutex_unlock(&sd->mutex); + return 0; + } + unsigned char *copy = enif_alloc(entry->value_len > 0 ? entry->value_len : 1); + if (copy == NULL) { + pthread_mutex_unlock(&sd->mutex); + return -2; + } + if (entry->value_len > 0) memcpy(copy, shared_dict_value(entry), entry->value_len); + out->data = copy; + out->len = entry->value_len; + pthread_mutex_unlock(&sd->mutex); + return 1; +} - /* Create Python key from binary */ - PyObject *py_key = PyBytes_FromStringAndSize((char *)key_bin.data, key_bin.size); - if (py_key == NULL) { - PyGILState_Release(gstate); +static int shared_dict_delete(py_shared_dict_t *sd, + const unsigned char *key, size_t key_len) { + pthread_mutex_lock(&sd->mutex); + if (atomic_load(&sd->destroyed)) { pthread_mutex_unlock(&sd->mutex); - return enif_make_badarg(env); + return -1; + } + py_shared_dict_entry_t **link; + py_shared_dict_entry_t *entry = shared_dict_find_locked(sd, key, key_len, &link); + if (entry != NULL) { + *link = entry->next; + sd->size--; } + pthread_mutex_unlock(&sd->mutex); + if (entry != NULL) enif_free(entry); + return entry != NULL ? 1 : 0; +} - /* Look up value (pickled bytes) */ - PyObject *pickled = PyDict_GetItem(sd->dict, py_key); - Py_DECREF(py_key); +static PyObject *shared_dict_pickle_dumps(PyObject *value) { + PyObject *pickle = PyImport_ImportModule("pickle"); + if (pickle == NULL) return NULL; + PyObject *dumps = PyObject_GetAttrString(pickle, "dumps"); + Py_DECREF(pickle); + if (dumps == NULL) return NULL; + PyObject *result = PyObject_CallFunctionObjArgs(dumps, value, NULL); + Py_DECREF(dumps); + return result; +} - if (pickled == NULL) { - /* Key not found, return default */ - PyGILState_Release(gstate); - pthread_mutex_unlock(&sd->mutex); - return argv[2]; /* Return default */ +static PyObject *shared_dict_pickle_loads(const unsigned char *data, size_t len) { + if (len > (size_t)PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, "stored SharedDict value is too large"); + return NULL; } + PyObject *bytes = PyBytes_FromStringAndSize((const char *)data, (Py_ssize_t)len); + if (bytes == NULL) return NULL; + PyObject *pickle = PyImport_ImportModule("pickle"); + if (pickle == NULL) { Py_DECREF(bytes); return NULL; } + PyObject *loads = PyObject_GetAttrString(pickle, "loads"); + Py_DECREF(pickle); + if (loads == NULL) { Py_DECREF(bytes); return NULL; } + PyObject *result = PyObject_CallFunctionObjArgs(loads, bytes, NULL); + Py_DECREF(loads); + Py_DECREF(bytes); + return result; +} - /* Unpickle the value */ - PyObject *pickle_mod = PyImport_ImportModule("pickle"); - if (pickle_mod == NULL) { - PyErr_Clear(); - PyGILState_Release(gstate); +static int shared_dict_snapshot_keys(py_shared_dict_t *sd, + shared_dict_key_t **keys_out, + size_t *count_out) { + *keys_out = NULL; + *count_out = 0; + pthread_mutex_lock(&sd->mutex); + if (atomic_load(&sd->destroyed)) { pthread_mutex_unlock(&sd->mutex); - return make_error_atom(env, "pickle_unavailable"); + return -1; } - - PyObject *loads = PyObject_GetAttrString(pickle_mod, "loads"); - Py_DECREF(pickle_mod); - if (loads == NULL) { - PyErr_Clear(); - PyGILState_Release(gstate); + if (sd->size > SIZE_MAX / sizeof(shared_dict_key_t)) { + pthread_mutex_unlock(&sd->mutex); + return -2; + } + shared_dict_key_t *keys = sd->size > 0 + ? enif_alloc(sd->size * sizeof(*keys)) : NULL; + if (sd->size > 0 && keys == NULL) { pthread_mutex_unlock(&sd->mutex); - return make_error_atom(env, "pickle_loads_unavailable"); + return -2; } + size_t count = 0; + for (size_t i = 0; i < PY_SHARED_DICT_BUCKETS; i++) { + for (py_shared_dict_entry_t *entry = sd->buckets[i]; + entry != NULL; entry = entry->next) { + unsigned char *copy = enif_alloc(entry->key_len > 0 ? entry->key_len : 1); + if (copy == NULL) { + for (size_t j = 0; j < count; j++) enif_free(keys[j].data); + enif_free(keys); + pthread_mutex_unlock(&sd->mutex); + return -2; + } + if (entry->key_len > 0) memcpy(copy, entry->data, entry->key_len); + keys[count].data = copy; + keys[count].len = entry->key_len; + count++; + } + } + pthread_mutex_unlock(&sd->mutex); + *keys_out = keys; + *count_out = count; + return 0; +} - PyObject *value = PyObject_CallFunctionObjArgs(loads, pickled, NULL); - Py_DECREF(loads); +static void shared_dict_free_keys(shared_dict_key_t *keys, size_t count) { + for (size_t i = 0; i < count; i++) enif_free(keys[i].data); + enif_free(keys); +} + +/* Resource callback. */ +static void shared_dict_destructor(ErlNifEnv *env, void *obj) { + py_shared_dict_t *sd = obj; + if (sd->monitor_active && env != NULL) { + enif_demonitor_process(env, sd, &sd->monitor); + sd->monitor_active = false; + } + shared_dict_destroy_contents(sd); + if (sd->mutex_initialized) { + pthread_mutex_destroy(&sd->mutex); + sd->mutex_initialized = false; + } +} +/* Erlang NIFs. */ +static ERL_NIF_TERM nif_shared_dict_new(ErlNifEnv *env, int argc, + const ERL_NIF_TERM argv[]) { + (void)argc; (void)argv; + RUNTIME_CHECK_ERROR(env); + py_shared_dict_t *sd = enif_alloc_resource( + PY_SHARED_DICT_RESOURCE_TYPE, sizeof(*sd)); + if (sd == NULL) return make_error_atom(env, "alloc_failed"); + memset(sd, 0, sizeof(*sd)); + atomic_store(&sd->destroyed, false); + if (pthread_mutex_init(&sd->mutex, NULL) != 0) { + enif_release_resource(sd); + return make_error_atom(env, "mutex_init_failed"); + } + sd->mutex_initialized = true; + ERL_NIF_TERM ref = enif_make_resource(env, sd); + enif_release_resource(sd); + return enif_make_tuple2(env, ATOM_OK, ref); +} + +static ERL_NIF_TERM nif_shared_dict_get(ErlNifEnv *env, int argc, + const ERL_NIF_TERM argv[]) { + (void)argc; + py_shared_dict_t *sd; + GET_RESOURCE_OR_BADARG(env, argv[0], PY_SHARED_DICT_RESOURCE_TYPE, &sd); + CHECK_NOT_DESTROYED(env, sd); + ErlNifBinary key; + INSPECT_BINARY_OR_BADARG(env, argv[1], key); + shared_dict_bytes_t stored; + int found = shared_dict_copy_value(sd, key.data, key.size, &stored); + if (found == 0) return argv[2]; + if (found == -1) return enif_make_badarg(env); + if (found == -2) return make_error_atom(env, "alloc_failed"); + PyGILState_STATE gstate = PyGILState_Ensure(); + PyObject *value = shared_dict_pickle_loads(stored.data, stored.len); + enif_free(stored.data); if (value == NULL) { PyErr_Clear(); PyGILState_Release(gstate); - pthread_mutex_unlock(&sd->mutex); return make_error_atom(env, "unpickle_failed"); } - - /* Convert Python value to Erlang term */ ERL_NIF_TERM result = py_to_term(env, value); Py_DECREF(value); - PyGILState_Release(gstate); - pthread_mutex_unlock(&sd->mutex); - return result; } -/** - * @brief Set a value in SharedDict - * - * @param Handle SharedDict reference - * @param Key Binary key - * @param Value Erlang term value (will be pickled) - * @return ok on success, badarg if destroyed - */ static ERL_NIF_TERM nif_shared_dict_set(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) { (void)argc; - py_shared_dict_t *sd; GET_RESOURCE_OR_BADARG(env, argv[0], PY_SHARED_DICT_RESOURCE_TYPE, &sd); CHECK_NOT_DESTROYED(env, sd); - - /* Get key as binary */ - ErlNifBinary key_bin; - INSPECT_BINARY_OR_BADARG(env, argv[1], key_bin); - - /* Lock and access dict */ - pthread_mutex_lock(&sd->mutex); - - /* Check destroyed again after acquiring lock */ - if (atomic_load(&sd->destroyed) || sd->dict == NULL) { - pthread_mutex_unlock(&sd->mutex); - return enif_make_badarg(env); - } - + ErlNifBinary key; + INSPECT_BINARY_OR_BADARG(env, argv[1], key); PyGILState_STATE gstate = PyGILState_Ensure(); - - /* Convert Erlang term to Python object */ - PyObject *py_value = term_to_py(env, argv[2]); - if (py_value == NULL) { - PyErr_Clear(); - PyGILState_Release(gstate); - pthread_mutex_unlock(&sd->mutex); - return make_error_atom(env, "term_conversion_failed"); - } - - /* Pickle the value for cross-interpreter safety */ - PyObject *pickle_mod = PyImport_ImportModule("pickle"); - if (pickle_mod == NULL) { - PyErr_Clear(); - Py_DECREF(py_value); - PyGILState_Release(gstate); - pthread_mutex_unlock(&sd->mutex); - return make_error_atom(env, "pickle_unavailable"); - } - - PyObject *dumps = PyObject_GetAttrString(pickle_mod, "dumps"); - Py_DECREF(pickle_mod); - if (dumps == NULL) { - PyErr_Clear(); - Py_DECREF(py_value); - PyGILState_Release(gstate); - pthread_mutex_unlock(&sd->mutex); - return make_error_atom(env, "pickle_dumps_unavailable"); - } - - PyObject *pickled = PyObject_CallFunctionObjArgs(dumps, py_value, NULL); - Py_DECREF(dumps); - Py_DECREF(py_value); - + PyObject *value = term_to_py(env, argv[2]); + PyObject *pickled = value != NULL ? shared_dict_pickle_dumps(value) : NULL; + Py_XDECREF(value); if (pickled == NULL) { PyErr_Clear(); PyGILState_Release(gstate); - pthread_mutex_unlock(&sd->mutex); return make_error_atom(env, "pickle_failed"); } - - /* Create Python key from binary */ - PyObject *py_key = PyBytes_FromStringAndSize((char *)key_bin.data, key_bin.size); - if (py_key == NULL) { + char *data; + Py_ssize_t len; + if (PyBytes_AsStringAndSize(pickled, &data, &len) < 0) { Py_DECREF(pickled); - PyGILState_Release(gstate); - pthread_mutex_unlock(&sd->mutex); - return enif_make_badarg(env); - } - - /* Store pickled value in dict */ - int set_result = PyDict_SetItem(sd->dict, py_key, pickled); - Py_DECREF(py_key); - Py_DECREF(pickled); - - if (set_result < 0) { PyErr_Clear(); PyGILState_Release(gstate); - pthread_mutex_unlock(&sd->mutex); - return make_error_atom(env, "dict_set_failed"); + return make_error_atom(env, "pickle_failed"); } - + int result = shared_dict_store(sd, key.data, key.size, + (unsigned char *)data, (size_t)len); + Py_DECREF(pickled); PyGILState_Release(gstate); - pthread_mutex_unlock(&sd->mutex); - + if (result == 1) return enif_make_badarg(env); + if (result < 0) return make_error_atom(env, "alloc_failed"); return ATOM_OK; } -/** - * @brief Delete a key from SharedDict - * - * @param Handle SharedDict reference - * @param Key Binary key - * @return ok on success (even if key didn't exist), badarg if destroyed - */ static ERL_NIF_TERM nif_shared_dict_del(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) { (void)argc; - py_shared_dict_t *sd; GET_RESOURCE_OR_BADARG(env, argv[0], PY_SHARED_DICT_RESOURCE_TYPE, &sd); CHECK_NOT_DESTROYED(env, sd); - - /* Get key as binary */ - ErlNifBinary key_bin; - INSPECT_BINARY_OR_BADARG(env, argv[1], key_bin); - - /* Lock and access dict */ - pthread_mutex_lock(&sd->mutex); - - /* Check destroyed again after acquiring lock */ - if (atomic_load(&sd->destroyed) || sd->dict == NULL) { - pthread_mutex_unlock(&sd->mutex); - return enif_make_badarg(env); - } - - PyGILState_STATE gstate = PyGILState_Ensure(); - - /* Create Python key from binary */ - PyObject *py_key = PyBytes_FromStringAndSize((char *)key_bin.data, key_bin.size); - if (py_key == NULL) { - PyGILState_Release(gstate); - pthread_mutex_unlock(&sd->mutex); - return enif_make_badarg(env); - } - - /* Delete key (ignore if not found) */ - PyDict_DelItem(sd->dict, py_key); - PyErr_Clear(); /* Clear KeyError if key didn't exist */ - Py_DECREF(py_key); - - PyGILState_Release(gstate); - pthread_mutex_unlock(&sd->mutex); - - return ATOM_OK; + ErlNifBinary key; + INSPECT_BINARY_OR_BADARG(env, argv[1], key); + return shared_dict_delete(sd, key.data, key.size) < 0 + ? enif_make_badarg(env) : ATOM_OK; } -/** - * @brief Get all keys from SharedDict - * - * @param Handle SharedDict reference - * @return List of binary keys, badarg if destroyed - */ static ERL_NIF_TERM nif_shared_dict_keys(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) { (void)argc; - py_shared_dict_t *sd; GET_RESOURCE_OR_BADARG(env, argv[0], PY_SHARED_DICT_RESOURCE_TYPE, &sd); CHECK_NOT_DESTROYED(env, sd); - - /* Lock and access dict */ - pthread_mutex_lock(&sd->mutex); - - /* Check destroyed again after acquiring lock */ - if (atomic_load(&sd->destroyed) || sd->dict == NULL) { - pthread_mutex_unlock(&sd->mutex); - return enif_make_badarg(env); - } - - PyGILState_STATE gstate = PyGILState_Ensure(); - - /* Get keys */ - PyObject *keys = PyDict_Keys(sd->dict); - if (keys == NULL) { - PyGILState_Release(gstate); - pthread_mutex_unlock(&sd->mutex); - return enif_make_list(env, 0); - } - - Py_ssize_t len = PyList_Size(keys); - ERL_NIF_TERM *key_terms = enif_alloc(sizeof(ERL_NIF_TERM) * len); - if (key_terms == NULL) { - Py_DECREF(keys); - PyGILState_Release(gstate); - pthread_mutex_unlock(&sd->mutex); - return enif_make_list(env, 0); + shared_dict_key_t *keys; + size_t count; + int snapshot = shared_dict_snapshot_keys(sd, &keys, &count); + if (snapshot == -1) return enif_make_badarg(env); + if (snapshot == -2) return make_error_atom(env, "alloc_failed"); + if (count > UINT_MAX || count > SIZE_MAX / sizeof(ERL_NIF_TERM)) { + shared_dict_free_keys(keys, count); + return make_error_atom(env, "too_many_keys"); + } + ERL_NIF_TERM *terms = count > 0 ? enif_alloc(count * sizeof(*terms)) : NULL; + if (count > 0 && terms == NULL) { + shared_dict_free_keys(keys, count); + return make_error_atom(env, "alloc_failed"); } - - for (Py_ssize_t i = 0; i < len; i++) { - PyObject *py_key = PyList_GetItem(keys, i); - if (PyBytes_Check(py_key)) { - char *data; - Py_ssize_t size; - PyBytes_AsStringAndSize(py_key, &data, &size); - ERL_NIF_TERM bin; - unsigned char *buf = enif_make_new_binary(env, size, &bin); - if (buf != NULL) { - memcpy(buf, data, size); - key_terms[i] = bin; - } else { - key_terms[i] = enif_make_atom(env, "error"); - } - } else { - key_terms[i] = enif_make_atom(env, "error"); + for (size_t i = 0; i < count; i++) { + unsigned char *buf = enif_make_new_binary(env, keys[i].len, &terms[i]); + if (buf == NULL && keys[i].len > 0) { + enif_free(terms); + shared_dict_free_keys(keys, count); + return make_error_atom(env, "alloc_failed"); } + if (keys[i].len > 0) memcpy(buf, keys[i].data, keys[i].len); } - - ERL_NIF_TERM result = enif_make_list_from_array(env, key_terms, len); - enif_free(key_terms); - Py_DECREF(keys); - - PyGILState_Release(gstate); - pthread_mutex_unlock(&sd->mutex); - + ERL_NIF_TERM result = enif_make_list_from_array(env, terms, (unsigned)count); + enif_free(terms); + shared_dict_free_keys(keys, count); return result; } -/** - * @brief Explicitly destroy a SharedDict. - * - * Marks the SharedDict as destroyed and clears its Python dict. - * This is idempotent - calling on an already-destroyed dict returns ok. - * - * @param Handle SharedDict reference - * @return ok atom - */ static ERL_NIF_TERM nif_shared_dict_destroy(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) { (void)argc; - py_shared_dict_t *sd; GET_RESOURCE_OR_BADARG(env, argv[0], PY_SHARED_DICT_RESOURCE_TYPE, &sd); - - /* Check if already destroyed - idempotent */ - if (atomic_load(&sd->destroyed)) { - return ATOM_OK; - } - - /* Mark as destroyed */ - atomic_store(&sd->destroyed, true); - - /* Clear the Python dict */ - pthread_mutex_lock(&sd->mutex); - if (sd->dict != NULL && runtime_is_running()) { - PyGILState_STATE gstate = PyGILState_Ensure(); - Py_CLEAR(sd->dict); - PyGILState_Release(gstate); - } - sd->dict = NULL; - pthread_mutex_unlock(&sd->mutex); - + shared_dict_destroy_contents(sd); return ATOM_OK; } -/* ============================================================================ - * Python Methods - * ============================================================================ - * These functions implement the Python-side API for SharedDict, allowing - * Python code to access process-scoped shared dictionaries. - */ - -/** - * Extract py_shared_dict_t* from a PyCapsule. - * Returns NULL and sets exception on error. - */ +/* Python methods. The caller already holds its own interpreter's GIL. */ static py_shared_dict_t *get_shared_dict_from_capsule(PyObject *capsule) { if (!PyCapsule_IsValid(capsule, "py_shared_dict")) { PyErr_SetString(PyExc_TypeError, "Invalid SharedDict handle"); return NULL; } - py_shared_dict_t *sd = (py_shared_dict_t *)PyCapsule_GetPointer(capsule, "py_shared_dict"); - if (sd == NULL) { - PyErr_SetString(PyExc_ValueError, "SharedDict handle is NULL"); - return NULL; - } - if (atomic_load(&sd->destroyed)) { + py_shared_dict_t *sd = PyCapsule_GetPointer(capsule, "py_shared_dict"); + if (sd != NULL && atomic_load(&sd->destroyed)) { PyErr_SetString(PyExc_RuntimeError, "SharedDict has been destroyed"); return NULL; } return sd; } -/** - * Python implementation of SharedDict.get(key, default=None) - * Usage: erlang._shared_dict_get(handle, key) - */ static PyObject *py_shared_dict_get_impl(PyObject *self, PyObject *args) { (void)self; PyObject *handle; const char *key; Py_ssize_t key_len; - - if (!PyArg_ParseTuple(args, "Os#", &handle, &key, &key_len)) { - return NULL; - } - + if (!PyArg_ParseTuple(args, "Os#", &handle, &key, &key_len)) return NULL; py_shared_dict_t *sd = get_shared_dict_from_capsule(handle); if (sd == NULL) return NULL; - - pthread_mutex_lock(&sd->mutex); - - if (atomic_load(&sd->destroyed) || sd->dict == NULL) { - pthread_mutex_unlock(&sd->mutex); + shared_dict_bytes_t stored; + int found = shared_dict_copy_value(sd, (unsigned char *)key, (size_t)key_len, &stored); + if (found == 0) Py_RETURN_NONE; + if (found == -1) { PyErr_SetString(PyExc_RuntimeError, "SharedDict has been destroyed"); return NULL; } - - /* Create Python key from bytes */ - PyObject *py_key = PyBytes_FromStringAndSize(key, key_len); - if (py_key == NULL) { - pthread_mutex_unlock(&sd->mutex); - return NULL; - } - - /* Look up pickled value */ - PyObject *pickled = PyDict_GetItem(sd->dict, py_key); - Py_DECREF(py_key); - - if (pickled == NULL) { - pthread_mutex_unlock(&sd->mutex); - Py_RETURN_NONE; - } - - /* Unpickle the value */ - PyObject *pickle_mod = PyImport_ImportModule("pickle"); - if (pickle_mod == NULL) { - pthread_mutex_unlock(&sd->mutex); - return NULL; - } - - PyObject *loads = PyObject_GetAttrString(pickle_mod, "loads"); - Py_DECREF(pickle_mod); - if (loads == NULL) { - pthread_mutex_unlock(&sd->mutex); - return NULL; - } - - PyObject *value = PyObject_CallFunctionObjArgs(loads, pickled, NULL); - Py_DECREF(loads); - - pthread_mutex_unlock(&sd->mutex); + if (found == -2) return PyErr_NoMemory(); + PyObject *value = shared_dict_pickle_loads(stored.data, stored.len); + enif_free(stored.data); return value; } -/** - * Python implementation of SharedDict.set(key, value) - * Usage: erlang._shared_dict_set(handle, key, value) - */ static PyObject *py_shared_dict_set_impl(PyObject *self, PyObject *args) { (void)self; - PyObject *handle; + PyObject *handle, *value; const char *key; Py_ssize_t key_len; - PyObject *value; - - if (!PyArg_ParseTuple(args, "Os#O", &handle, &key, &key_len, &value)) { - return NULL; - } - + if (!PyArg_ParseTuple(args, "Os#O", &handle, &key, &key_len, &value)) return NULL; py_shared_dict_t *sd = get_shared_dict_from_capsule(handle); if (sd == NULL) return NULL; - - pthread_mutex_lock(&sd->mutex); - - if (atomic_load(&sd->destroyed) || sd->dict == NULL) { - pthread_mutex_unlock(&sd->mutex); - PyErr_SetString(PyExc_RuntimeError, "SharedDict has been destroyed"); - return NULL; - } - - /* Pickle the value */ - PyObject *pickle_mod = PyImport_ImportModule("pickle"); - if (pickle_mod == NULL) { - pthread_mutex_unlock(&sd->mutex); - return NULL; - } - - PyObject *dumps = PyObject_GetAttrString(pickle_mod, "dumps"); - Py_DECREF(pickle_mod); - if (dumps == NULL) { - pthread_mutex_unlock(&sd->mutex); - return NULL; - } - - PyObject *pickled = PyObject_CallFunctionObjArgs(dumps, value, NULL); - Py_DECREF(dumps); - if (pickled == NULL) { - pthread_mutex_unlock(&sd->mutex); - return NULL; - } - - /* Create Python key */ - PyObject *py_key = PyBytes_FromStringAndSize(key, key_len); - if (py_key == NULL) { + PyObject *pickled = shared_dict_pickle_dumps(value); + if (pickled == NULL) return NULL; + char *data; + Py_ssize_t len; + if (PyBytes_AsStringAndSize(pickled, &data, &len) < 0) { Py_DECREF(pickled); - pthread_mutex_unlock(&sd->mutex); return NULL; } - - /* Store in dict */ - int result = PyDict_SetItem(sd->dict, py_key, pickled); - Py_DECREF(py_key); + int result = shared_dict_store(sd, (unsigned char *)key, (size_t)key_len, + (unsigned char *)data, (size_t)len); Py_DECREF(pickled); - - pthread_mutex_unlock(&sd->mutex); - - if (result < 0) { + if (result == 1) { + PyErr_SetString(PyExc_RuntimeError, "SharedDict has been destroyed"); return NULL; } + if (result < 0) return PyErr_NoMemory(); Py_RETURN_NONE; } -/** - * Python implementation of SharedDict.delete(key) - * Usage: erlang._shared_dict_del(handle, key) - * Returns True if key existed, False otherwise - */ static PyObject *py_shared_dict_del_impl(PyObject *self, PyObject *args) { (void)self; PyObject *handle; const char *key; Py_ssize_t key_len; - - if (!PyArg_ParseTuple(args, "Os#", &handle, &key, &key_len)) { - return NULL; - } - + if (!PyArg_ParseTuple(args, "Os#", &handle, &key, &key_len)) return NULL; py_shared_dict_t *sd = get_shared_dict_from_capsule(handle); if (sd == NULL) return NULL; - - pthread_mutex_lock(&sd->mutex); - - if (atomic_load(&sd->destroyed) || sd->dict == NULL) { - pthread_mutex_unlock(&sd->mutex); + int result = shared_dict_delete(sd, (unsigned char *)key, (size_t)key_len); + if (result < 0) { PyErr_SetString(PyExc_RuntimeError, "SharedDict has been destroyed"); return NULL; } - - /* Create Python key */ - PyObject *py_key = PyBytes_FromStringAndSize(key, key_len); - if (py_key == NULL) { - pthread_mutex_unlock(&sd->mutex); - return NULL; - } - - /* Check if key exists */ - int exists = PyDict_Contains(sd->dict, py_key); - if (exists > 0) { - PyDict_DelItem(sd->dict, py_key); - PyErr_Clear(); - } - Py_DECREF(py_key); - - pthread_mutex_unlock(&sd->mutex); - - if (exists > 0) { - Py_RETURN_TRUE; - } - Py_RETURN_FALSE; + return PyBool_FromLong(result); } -/** - * Python implementation of SharedDict.contains(key) - * Usage: erlang._shared_dict_contains(handle, key) - */ static PyObject *py_shared_dict_contains_impl(PyObject *self, PyObject *args) { (void)self; PyObject *handle; const char *key; Py_ssize_t key_len; - - if (!PyArg_ParseTuple(args, "Os#", &handle, &key, &key_len)) { - return NULL; - } - + if (!PyArg_ParseTuple(args, "Os#", &handle, &key, &key_len)) return NULL; py_shared_dict_t *sd = get_shared_dict_from_capsule(handle); if (sd == NULL) return NULL; - pthread_mutex_lock(&sd->mutex); - - if (atomic_load(&sd->destroyed) || sd->dict == NULL) { - pthread_mutex_unlock(&sd->mutex); + bool destroyed = atomic_load(&sd->destroyed); + bool found = !destroyed && shared_dict_find_locked( + sd, (unsigned char *)key, (size_t)key_len, NULL) != NULL; + pthread_mutex_unlock(&sd->mutex); + if (destroyed) { PyErr_SetString(PyExc_RuntimeError, "SharedDict has been destroyed"); return NULL; } - - /* Create Python key */ - PyObject *py_key = PyBytes_FromStringAndSize(key, key_len); - if (py_key == NULL) { - pthread_mutex_unlock(&sd->mutex); - return NULL; - } - - int exists = PyDict_Contains(sd->dict, py_key); - Py_DECREF(py_key); - - pthread_mutex_unlock(&sd->mutex); - - if (exists > 0) { - Py_RETURN_TRUE; - } else if (exists == 0) { - Py_RETURN_FALSE; - } else { - return NULL; /* Error occurred */ - } + return PyBool_FromLong(found); } -/** - * Python implementation of SharedDict.destroy() - * Usage: erlang._shared_dict_destroy(handle) - * - * Explicitly destroys the SharedDict, invalidating all references. - * This is idempotent - calling on already-destroyed dict returns None. - */ static PyObject *py_shared_dict_destroy_impl(PyObject *self, PyObject *args) { (void)self; PyObject *capsule; - - if (!PyArg_ParseTuple(args, "O", &capsule)) { - return NULL; - } - + if (!PyArg_ParseTuple(args, "O", &capsule)) return NULL; if (!PyCapsule_IsValid(capsule, "py_shared_dict")) { PyErr_SetString(PyExc_TypeError, "Invalid SharedDict handle"); return NULL; } - - py_shared_dict_t *sd = (py_shared_dict_t *)PyCapsule_GetPointer(capsule, "py_shared_dict"); - if (sd == NULL) { - PyErr_SetString(PyExc_ValueError, "SharedDict handle is NULL"); - return NULL; - } - - /* If already destroyed, return None (idempotent) */ - if (atomic_load(&sd->destroyed)) { - Py_RETURN_NONE; - } - - /* Mark as destroyed */ - atomic_store(&sd->destroyed, true); - - /* Clear the Python dict */ - pthread_mutex_lock(&sd->mutex); - Py_CLEAR(sd->dict); - pthread_mutex_unlock(&sd->mutex); - + py_shared_dict_t *sd = PyCapsule_GetPointer(capsule, "py_shared_dict"); + if (sd == NULL) return NULL; + shared_dict_destroy_contents(sd); Py_RETURN_NONE; } -/** - * Python implementation of SharedDict.keys() - * Usage: erlang._shared_dict_keys(handle) - */ static PyObject *py_shared_dict_keys_impl(PyObject *self, PyObject *args) { (void)self; PyObject *handle; - - if (!PyArg_ParseTuple(args, "O", &handle)) { - return NULL; - } - + if (!PyArg_ParseTuple(args, "O", &handle)) return NULL; py_shared_dict_t *sd = get_shared_dict_from_capsule(handle); if (sd == NULL) return NULL; - - pthread_mutex_lock(&sd->mutex); - - if (atomic_load(&sd->destroyed) || sd->dict == NULL) { - pthread_mutex_unlock(&sd->mutex); + shared_dict_key_t *keys; + size_t count; + int snapshot = shared_dict_snapshot_keys(sd, &keys, &count); + if (snapshot == -1) { PyErr_SetString(PyExc_RuntimeError, "SharedDict has been destroyed"); return NULL; } - - /* Get keys and decode them to strings */ - PyObject *keys = PyDict_Keys(sd->dict); - if (keys == NULL) { - pthread_mutex_unlock(&sd->mutex); - return NULL; + if (snapshot == -2) return PyErr_NoMemory(); + if (count > (size_t)PY_SSIZE_T_MAX) { + shared_dict_free_keys(keys, count); + return PyErr_NoMemory(); } - - Py_ssize_t len = PyList_Size(keys); - PyObject *result = PyList_New(len); + PyObject *result = PyList_New((Py_ssize_t)count); if (result == NULL) { - Py_DECREF(keys); - pthread_mutex_unlock(&sd->mutex); + shared_dict_free_keys(keys, count); return NULL; } - - for (Py_ssize_t i = 0; i < len; i++) { - PyObject *py_key = PyList_GetItem(keys, i); - if (PyBytes_Check(py_key)) { - /* Decode bytes to string */ - PyObject *str_key = PyUnicode_DecodeUTF8( - PyBytes_AS_STRING(py_key), - PyBytes_GET_SIZE(py_key), - "replace"); - if (str_key == NULL) { - Py_DECREF(result); - Py_DECREF(keys); - pthread_mutex_unlock(&sd->mutex); - return NULL; - } - PyList_SET_ITEM(result, i, str_key); - } else { - Py_INCREF(py_key); - PyList_SET_ITEM(result, i, py_key); + for (size_t i = 0; i < count; i++) { + PyObject *key = PyUnicode_DecodeUTF8( + (const char *)keys[i].data, (Py_ssize_t)keys[i].len, "replace"); + if (key == NULL) { + Py_DECREF(result); + shared_dict_free_keys(keys, count); + return NULL; } + PyList_SET_ITEM(result, (Py_ssize_t)i, key); } - - Py_DECREF(keys); - pthread_mutex_unlock(&sd->mutex); + shared_dict_free_keys(keys, count); return result; } -/* NIF table entries of this file; py_nif.c concatenates them into nif_funcs[]. - * Flags: ERL_NIF_DIRTY_JOB_* for anything that can block or run Python. */ #define PY_SHARED_DICT_NIFS \ {"shared_dict_new", 0, nif_shared_dict_new, 0}, \ {"shared_dict_get", 3, nif_shared_dict_get, ERL_NIF_DIRTY_JOB_IO_BOUND}, \ {"shared_dict_set", 3, nif_shared_dict_set, ERL_NIF_DIRTY_JOB_IO_BOUND}, \ {"shared_dict_del", 2, nif_shared_dict_del, ERL_NIF_DIRTY_JOB_IO_BOUND}, \ {"shared_dict_keys", 1, nif_shared_dict_keys, ERL_NIF_DIRTY_JOB_IO_BOUND}, \ - {"shared_dict_destroy", 1, nif_shared_dict_destroy, 0} + {"shared_dict_destroy", 1, nif_shared_dict_destroy, ERL_NIF_DIRTY_JOB_IO_BOUND} diff --git a/c_src/py_thread_worker.c b/c_src/py_thread_worker.c index 7656583..b8004ae 100644 --- a/c_src/py_thread_worker.c +++ b/c_src/py_thread_worker.c @@ -310,7 +310,12 @@ static thread_worker_t *create_thread_worker(void) { (void)fcntl(tw->response_pipe[1], F_SETFL, wflags | O_NONBLOCK); } - pthread_mutex_init(&tw->mutex, NULL); + if (pthread_mutex_init(&tw->mutex, NULL) != 0) { + close(tw->response_pipe[0]); + close(tw->response_pipe[1]); + enif_free(tw); + return NULL; + } /* Add to pool */ tw->next = g_thread_pool_head; @@ -716,6 +721,10 @@ static ERL_NIF_TERM nif_thread_worker_write_with_id(ErlNifEnv *env, int argc, if (!enif_inspect_binary(env, argv[2], &response)) { return make_error(env, "invalid_response"); } + if (response.size > UINT32_MAX || + response.size > SIZE_MAX - sizeof(callback_id) - sizeof(uint32_t)) { + return make_error(env, "response_too_large"); + } size_t total = sizeof(callback_id) + sizeof(uint32_t) + response.size; char stack_buf[THREAD_WORKER_STACK_FRAME_LIMIT]; @@ -811,6 +820,10 @@ static ERL_NIF_TERM nif_async_callback_response(ErlNifEnv *env, int argc, if (!enif_inspect_binary(env, argv[2], &response)) { return make_error(env, "invalid_response"); } + if (response.size > UINT32_MAX || + response.size > SIZE_MAX - sizeof(callback_id) - sizeof(uint32_t)) { + return make_error(env, "response_too_large"); + } size_t total = sizeof(callback_id) + sizeof(uint32_t) + response.size; char stack_buf[THREAD_WORKER_STACK_FRAME_LIMIT]; diff --git a/test/py_SUITE.erl b/test/py_SUITE.erl index 1cc62d6..325c223 100644 --- a/test/py_SUITE.erl +++ b/test/py_SUITE.erl @@ -63,6 +63,7 @@ test_shared_dict_types/1, test_shared_dict_process_death/1, test_shared_dict_python_access/1, + test_shared_dict_reentrant_pickle/1, test_shared_dict_destroy/1, %% SharedDict concurrent tests test_shared_dict_concurrent_same_key/1, @@ -126,6 +127,7 @@ all() -> test_shared_dict_types, test_shared_dict_process_death, test_shared_dict_python_access, + test_shared_dict_reentrant_pickle, test_shared_dict_destroy, %% SharedDict concurrent tests test_shared_dict_concurrent_same_key, @@ -1377,6 +1379,27 @@ test_shared_dict_python_access(_Config) -> ct:pal("SharedDict Python access test passed~n"), ok. +%% Pickle may execute user code. It must run without the native table lock, +%% otherwise the nested write below deadlocks on the same SharedDict. +test_shared_dict_reentrant_pickle(_Config) -> + {ok, SD} = py:shared_dict_new(), + {ok, _} = py:eval( + <<"(globals().__setitem__('_reentrant_sd_handle', handle), None)[-1]">>, + #{<<"handle">> => SD} + ), + ok = py:exec(<< + "from erlang import SharedDict\n" + "_reentrant_sd = SharedDict(_reentrant_sd_handle)\n" + "class _ReentrantPickle:\n" + " def __reduce__(self):\n" + " _reentrant_sd['inner'] = 7\n" + " return (dict, ())\n" + "_reentrant_sd['outer'] = _ReentrantPickle()\n" + >>), + 7 = py:shared_dict_get(SD, <<"inner">>), + #{} = py:shared_dict_get(SD, <<"outer">>), + ok. + %% Test explicit SharedDict destroy test_shared_dict_destroy(_Config) -> %% Create SharedDict and populate it diff --git a/test/py_context_owngil_SUITE.erl b/test/py_context_owngil_SUITE.erl index c0bf0af..8110c8c 100644 --- a/test/py_context_owngil_SUITE.erl +++ b/test/py_context_owngil_SUITE.erl @@ -55,7 +55,8 @@ %% Feature tests -export([ test_owngil_state_persistence/1, - test_owngil_module_import/1 + test_owngil_module_import/1, + test_owngil_shared_dict/1 ]). all() -> @@ -95,7 +96,8 @@ groups() -> ]}, {features, [sequence], [ test_owngil_state_persistence, - test_owngil_module_import + test_owngil_module_import, + test_owngil_shared_dict ]} ]. @@ -378,3 +380,22 @@ test_owngil_module_import(_Config) -> {ok, <<"{\"a\": 1}">>} = py_context:eval(Ctx, <<"json.dumps({'a': 1})">>, #{}), py_context:stop(Ctx). + +%% @doc SharedDict stores no interpreter-owned objects and is therefore safe +%% to use from an OWN_GIL subinterpreter and from Erlang in either direction. +test_owngil_shared_dict(_Config) -> + {ok, SD} = py:shared_dict_new(), + ok = py:shared_dict_set(SD, <<"from_erlang">>, 41), + {ok, Ctx} = py_context:start_link(1, owngil), + {ok, 41} = py_context:eval( + Ctx, + <<"__import__('erlang').SharedDict(handle)['from_erlang']">>, + #{<<"handle">> => SD} + ), + {ok, true} = py_context:eval( + Ctx, + <<"(__import__('erlang').SharedDict(handle).__setitem__('from_owngil', 42), True)[1]">>, + #{<<"handle">> => SD} + ), + 42 = py:shared_dict_get(SD, <<"from_owngil">>), + py_context:stop(Ctx). From 9ec2f7545d96b53312b89835896a6ce127c96422 Mon Sep 17 00:00:00 2001 From: Benoit Chesneau Date: Fri, 27 Nov 2026 09:49:32 +0100 Subject: [PATCH 2/4] Make session timeout soak deterministic Keep the timed operation well beyond its deadline so sanitizer scheduling overhead cannot let it complete before Erlang processes the timeout. The following call continues to verify that the reimport session recovers. --- test/py_session_soak_SUITE.erl | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/py_session_soak_SUITE.erl b/test/py_session_soak_SUITE.erl index 022bcdd..38a22d4 100644 --- a/test/py_session_soak_SUITE.erl +++ b/test/py_session_soak_SUITE.erl @@ -138,7 +138,9 @@ rchurn(T, Deadline, N, Errs) -> expect([{ok, 1}, {ok, 2}, {ok, 3}], R); 2 -> {ok, S} = py_session:new(T), - R = py_context:call(S, py_test_reimport, sleep, [0.2], #{}, 50), + %% Keep the operation far beyond the deadline so ASan + %% scheduler overhead cannot let it finish first. + R = py_context:call(S, py_test_reimport, sleep, [10], #{}, 50), {ok, 1} = py_context:call(S, py_test_reimport, bump, []), ok = py_session:close(S), expect({error, timeout}, R); From 6b9a96686b5fbbba8e24f56d0a7c4c1ef7c2ac3b Mon Sep 17 00:00:00 2001 From: Benoit Chesneau Date: Fri, 27 Nov 2026 14:04:11 +0100 Subject: [PATCH 3/4] Bound session timeout soak delay Use a one-second timed operation so sanitizer overhead cannot beat the deadline while Python versions that finish the sleep before recovery still keep the soak suite within its timetrap. --- test/py_session_soak_SUITE.erl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/py_session_soak_SUITE.erl b/test/py_session_soak_SUITE.erl index 38a22d4..f9f59a9 100644 --- a/test/py_session_soak_SUITE.erl +++ b/test/py_session_soak_SUITE.erl @@ -140,7 +140,7 @@ rchurn(T, Deadline, N, Errs) -> {ok, S} = py_session:new(T), %% Keep the operation far beyond the deadline so ASan %% scheduler overhead cannot let it finish first. - R = py_context:call(S, py_test_reimport, sleep, [10], #{}, 50), + R = py_context:call(S, py_test_reimport, sleep, [1], #{}, 50), {ok, 1} = py_context:call(S, py_test_reimport, bump, []), ok = py_session:close(S), expect({error, timeout}, R); From 3c8fa32b86eb78ac7b137cc0a142da1ccbd736d7 Mon Sep 17 00:00:00 2001 From: Benoit Chesneau Date: Fri, 27 Nov 2026 23:31:49 +0100 Subject: [PATCH 4/4] Close re-import sessions without waiting Queue Python namespace cleanup behind in-flight work instead of waiting during stop, so a timed-out call cannot make close kill the linked session owner. Gate timeout tests on an explicit release signal so scheduler delays cannot invert their result. --- CHANGELOG.md | 4 ++ src/py_reimport_session.erl | 18 ++++++--- test/py_session_SUITE.erl | 74 ++++++++++++++++++++++++++++++++++ test/py_session_soak_SUITE.erl | 53 ++++++++++++++++++++---- test/py_test_reimport.py | 14 ++++++- 5 files changed, 148 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 60b249a..f9f4ac0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,10 @@ ### Fixed +- Closing a re-import session after a call timed out could wait behind the + Python code that was still running. After five seconds the session and its + linked owner were killed. Closing now returns without waiting for Python, + and its state is freed after the running call finishes. - Shared dictionaries could deadlock the node when Erlang and Python used one at the same time, or when pickling a value accessed the same dictionary. Their stored values are now independent of any Python interpreter, so they diff --git a/src/py_reimport_session.erl b/src/py_reimport_session.erl index fc55bf3..3c9d675 100644 --- a/src/py_reimport_session.erl +++ b/src/py_reimport_session.erl @@ -194,7 +194,10 @@ handle_info({cancel_ctrl, _MRef}, St) -> %% ---- lifecycle ------------------------------------------------------------- handle_info({stop, From, MRef}, St) -> - close_session(St), + %% A timed-out call can still be running in the shared context. Queue the + %% cleanup behind it, but do not wait: a synchronous close could block + %% until py_context:stop/1 kills this linked process and its owner. + close_session_async(St), From ! {MRef, ok}, {stop, normal, St#st{exited = closed}}; handle_info({'DOWN', Mon, process, _Ctx, Reason}, #st{ctx_mon = Mon, pending = Pending} = St) -> @@ -213,7 +216,7 @@ handle_info(_Other, St) -> {noreply, St}. terminate(_Reason, St) -> - close_session(St), + close_session_async(St), try ets:delete(?REF_TAB, self()) catch @@ -244,9 +247,12 @@ forward(From, MRef, Fun, Args, #st{ctx = Ctx, sid = Sid, pending = Pending} = St reply(exec, {ok, _}) -> ok; reply(_Kind, Reply) -> Reply. -%% Idempotent on the Python side; nothing to do once the context is gone -close_session(#st{exited = undefined, ctx = Ctx, sid = Sid}) -> - _ = py_context:call(Ctx, ?IMPL, session_close, [Sid], #{}, 5000), +%% Requests from this process reach the context in order, so cleanup runs +%% after any call that the session already forwarded. The reply can be sent +%% to this process after it has exited; the template monitor is the fallback +%% if the session is killed before terminate/2 can queue this request. +close_session_async(#st{exited = undefined, ctx = Ctx, sid = Sid}) -> + Ctx ! {call, self(), make_ref(), ?IMPL, <<"session_close">>, [Sid], #{}}, ok; -close_session(_St) -> +close_session_async(_St) -> ok. diff --git a/test/py_session_SUITE.erl b/test/py_session_SUITE.erl index 08b8522..4d56c4f 100644 --- a/test/py_session_SUITE.erl +++ b/test/py_session_SUITE.erl @@ -60,6 +60,7 @@ test_rsession_concurrent/1, test_rsession_cleanup/1, test_rsession_timeout/1, + test_rsession_close_during_timed_out_call/1, test_rsession_context_died/1, test_rsession_unsupported/1, test_rsession_threads_see_context/1, @@ -116,6 +117,7 @@ groups() -> test_rsession_concurrent, test_rsession_cleanup, test_rsession_timeout, + test_rsession_close_during_timed_out_call, test_rsession_context_died, test_rsession_unsupported, test_rsession_threads_see_context, @@ -861,6 +863,62 @@ test_rsession_timeout(Config) -> py_session:close(S), py_session:close(Other). +%% Closing must not wait behind Python that kept running after its caller +%% timed out. In particular, stop's five-second fallback must not kill the +%% session and the owner linked to it. +test_rsession_close_during_timed_out_call(Config) -> + T = rtemplate(Config, #{contexts => 1}), + #{contexts := [Ctx]} = py_session:info(T), + {Started, Release} = gate_paths(Config, "close_timeout"), + Self = self(), + {Owner, OwnerMon} = spawn_monitor(fun() -> + {ok, S0} = py_session:new(T), + Self ! {session, self(), S0}, + receive + close -> Self ! {close_result, self(), py_session:close(S0)} + end + end), + S = + receive + {session, Owner, S0} -> S0 + after 10000 -> ct:fail(no_session) + end, + Caller = spawn(fun() -> + R = py_context:call( + S, + ?RMOD, + wait_for_release, + [list_to_binary(Started), list_to_binary(Release)], + #{}, + 50 + ), + Self ! {call_result, self(), R} + end), + try + ok = wait_file(Started, 500), + receive + {call_result, Caller, {error, timeout}} -> ok + after 10000 -> ct:fail(call_did_not_time_out) + end, + Owner ! close, + receive + {close_result, Owner, ok} -> ok; + {'DOWN', OwnerMon, process, Owner, killed} -> ct:fail(owner_killed) + after 3000 -> ct:fail(close_blocked) + end + after + ok = file:write_file(Release, <<>>) + end, + receive + {'DOWN', OwnerMon, process, Owner, normal} -> ok + after 10000 -> ct:fail(owner_did_not_exit) + end, + ok = wait_count(fun() -> session_count(Ctx) end, 0, 500), + 0 = wait_rsessions(T, 0, 500), + file:delete(Started), + file:delete(Release), + ok. + %% The context under a session goes: the session answers with that until %% closed, and does not take its linked owner down. test_rsession_context_died(Config) -> @@ -958,6 +1016,22 @@ wait_rsessions(T, Want, N) -> wait_rsessions(T, Want, N - 1) end. +gate_paths(Config, Label) -> + Base = Label ++ "_" ++ integer_to_list(erlang:unique_integer([positive])), + Dir = ?config(priv_dir, Config), + {filename:join(Dir, Base ++ ".started"), filename:join(Dir, Base ++ ".release")}. + +wait_file(_Path, 0) -> + ct:fail(python_call_did_not_start); +wait_file(Path, N) -> + case filelib:is_file(Path) of + true -> + ok; + false -> + timer:sleep(20), + wait_file(Path, N - 1) + end. + test_reimport_refresh(Config) -> T = rtemplate(Config, #{contexts => 2}), #{contexts := Old} = py_session:info(T), diff --git a/test/py_session_soak_SUITE.erl b/test/py_session_soak_SUITE.erl index f9f59a9..1e2233d 100644 --- a/test/py_session_soak_SUITE.erl +++ b/test/py_session_soak_SUITE.erl @@ -66,7 +66,7 @@ test_session_churn_no_leak(Config) -> {done, self(), case I rem 4 of 0 -> churn(Spawn, Deadline, 0, []); - 1 -> rchurn(Reimport, Deadline, 0, []); + 1 -> rchurn(Reimport, Deadline, 0, [], ?config(priv_dir, Config)); _ -> churn(Fork, Deadline, 0, []) end} end) @@ -121,7 +121,7 @@ churn(T, Deadline, N, Errs) -> %% A re-import session: several calls on one fresh state, then closed, %% timed out, or abandoned by an owner that crashes -rchurn(T, Deadline, N, Errs) -> +rchurn(T, Deadline, N, Errs, PrivDir) -> case erlang:monotonic_time(millisecond) < Deadline of false -> {N, Errs}; @@ -138,12 +138,9 @@ rchurn(T, Deadline, N, Errs) -> expect([{ok, 1}, {ok, 2}, {ok, 3}], R); 2 -> {ok, S} = py_session:new(T), - %% Keep the operation far beyond the deadline so ASan - %% scheduler overhead cannot let it finish first. - R = py_context:call(S, py_test_reimport, sleep, [1], #{}, 50), - {ok, 1} = py_context:call(S, py_test_reimport, bump, []), + {R, Bump} = timed_out_call(S, PrivDir), ok = py_session:close(S), - expect({error, timeout}, R); + expect({{error, timeout}, {ok, 1}}, {R, Bump}); 3 -> Self = self(), {Owner, Mon} = spawn_monitor(fun() -> @@ -168,10 +165,50 @@ rchurn(T, Deadline, N, Errs) -> case Got of ok -> Errs; Bad -> [Bad | Errs] - end + end, + PrivDir ) end. +timed_out_call(S, PrivDir) -> + Base = "soak_timeout_" ++ integer_to_list(erlang:unique_integer([positive])), + Started = filename:join(PrivDir, Base ++ ".started"), + Release = filename:join(PrivDir, Base ++ ".release"), + Self = self(), + Caller = spawn(fun() -> + R = py_context:call( + S, + py_test_reimport, + wait_for_release, + [list_to_binary(Started), list_to_binary(Release)], + #{}, + 50 + ), + Self ! {timeout_result, self(), R} + end), + ok = wait_file(Started, 500), + R = + receive + {timeout_result, Caller, Result} -> Result + after 10000 -> timeout_result_missing + end, + ok = file:write_file(Release, <<>>), + Bump = py_context:call(S, py_test_reimport, bump, []), + file:delete(Started), + file:delete(Release), + {R, Bump}. + +wait_file(_Path, 0) -> + {error, python_call_did_not_start}; +wait_file(Path, N) -> + case filelib:is_file(Path) of + true -> + ok; + false -> + timer:sleep(20), + wait_file(Path, N - 1) + end. + wait_freed(Ctx, 0) -> {ok, N} = py_context:call(Ctx, <<"_erlang_impl._reimport">>, session_count, []), N; diff --git a/test/py_test_reimport.py b/test/py_test_reimport.py index f33ccaa..a799f8e 100644 --- a/test/py_test_reimport.py +++ b/test/py_test_reimport.py @@ -1,7 +1,10 @@ """Imported again in every re-import run (py_session_SUITE reimport groups).""" import json +import os import pickle +import pathlib +import time import typing from dataclasses import dataclass @@ -70,11 +73,20 @@ def whoami(): def sleep(seconds): - import time time.sleep(seconds) return 'slept' +def wait_for_release(started_path, release_path): + """Tell Erlang the call is running, then hold its context until released.""" + started_path = os.fsdecode(started_path) + release_path = os.fsdecode(release_path) + pathlib.Path(started_path).touch() + while not os.path.exists(release_path): + time.sleep(0.01) + return 'released' + + def bump_via_callback(session): """Calls Erlang, whose callback calls back into this same session.""" from_callback = erlang.call('rsess_cb', session)