From 414dcc444eacfa43a908c1fa8630e2b6daf4ff17 Mon Sep 17 00:00:00 2001 From: AztecBot Date: Thu, 21 May 2026 13:07:22 +0000 Subject: [PATCH] fix: pin AVM NAPI worker thread stack size to prevent SIGBUS on macOS --- .../nodejs_module/util/async_op.hpp | 52 ++++++++++++++++++- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/barretenberg/cpp/src/barretenberg/nodejs_module/util/async_op.hpp b/barretenberg/cpp/src/barretenberg/nodejs_module/util/async_op.hpp index ad62bc2bf4a..e91306c7a62 100644 --- a/barretenberg/cpp/src/barretenberg/nodejs_module/util/async_op.hpp +++ b/barretenberg/cpp/src/barretenberg/nodejs_module/util/async_op.hpp @@ -1,11 +1,16 @@ #pragma once #include "barretenberg/serialize/msgpack_impl.hpp" +#include #include #include #include #include +#ifndef _WIN32 +#include +#endif + namespace bb::nodejs { using async_fn = std::function; @@ -109,10 +114,17 @@ class ThreadedAsyncOperation : public std::enable_shared_from_this_fn(self->_result); self->_success = true; @@ -138,7 +150,43 @@ class ThreadedAsyncOperation : public std::enable_shared_from_this_completion_tsfn.Release(); }); - }).detach(); + }); + } + + // Launch `work` on a detached OS thread with an explicitly large stack (see WORKER_STACK_SIZE). + // std::thread cannot set a stack size, so use pthreads where available and fall back to a + // default-stack std::thread only if pthread creation is unavailable or fails. + static void launch_detached_with_large_stack(std::function work) + { +#ifndef _WIN32 + pthread_attr_t attr; + if (pthread_attr_init(&attr) == 0) { + pthread_attr_setstacksize(&attr, WORKER_STACK_SIZE); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + + auto* heap_work = new std::function(std::move(work)); + pthread_t tid; + int rc = pthread_create( + &tid, + &attr, + [](void* arg) -> void* { + std::unique_ptr> fn(static_cast*>(arg)); + (*fn)(); + return nullptr; + }, + heap_work); + pthread_attr_destroy(&attr); + + if (rc == 0) { + return; + } + + // pthread_create failed; reclaim the work and fall back to a default std::thread. + std::unique_ptr> reclaimed(heap_work); + work = std::move(*reclaimed); + } +#endif + std::thread(std::move(work)).detach(); } async_fn _fn;