From f951042ef080ea9e4b65fcb8799a0a7d1403e539 Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Tue, 7 Jul 2026 17:42:59 +0500 Subject: [PATCH 1/2] refactor(bindings): use zapi js.io() instead of local io module MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bump zapi to v3.0.0, whose js.exportModule retains a shared std.Io.Threaded before the init hook and releases it after cleanup — same lifecycle bindings/napi/io.zig implemented by hand, plus refcounting across N-API environments. v3.0.0 also rejects non-DSL pub decls in exportModule instead of silently skipping them: de-pub internal State types and move the blst thread pool lifecycle behind a pub var so they stay native-only. Co-Authored-By: Claude Fable 5 --- bindings/napi/BeaconStateView.zig | 9 +++--- bindings/napi/blst.zig | 54 +++++++++++++++++-------------- bindings/napi/config.zig | 4 +-- bindings/napi/io.zig | 48 --------------------------- bindings/napi/metrics.zig | 3 +- bindings/napi/pool.zig | 7 ++-- bindings/napi/pubkeys.zig | 7 ++-- bindings/napi/root.zig | 11 ++----- build.zig.zon | 4 +-- 9 files changed, 50 insertions(+), 97 deletions(-) delete mode 100644 bindings/napi/io.zig diff --git a/bindings/napi/BeaconStateView.zig b/bindings/napi/BeaconStateView.zig index 80a24982e..34581932b 100644 --- a/bindings/napi/BeaconStateView.zig +++ b/bindings/napi/BeaconStateView.zig @@ -16,7 +16,6 @@ const pubkey = @import("./pubkeys.zig"); const js_types = @import("./js_types.zig"); const sszValueToNapiValue = @import("./to_napi_value.zig").sszValueToNapiValue; const numberSliceToNapiValue = @import("./to_napi_value.zig").numberSliceToNapiValue; -const napi_io = @import("./io.zig"); /// Allocator used for all BeaconStateView instances. var gpa: std.heap.DebugAllocator(.{}) = .init; @@ -72,7 +71,7 @@ pub const js_meta = js.class(.{ .properties = .{ } }); cached_state: ?*CachedBeaconState = null, -pool_rc: ?*pool.PoolRc = null, +pool_rc: @TypeOf(pool.state.pool_rc) = null, const BeaconStateView = @This(); pub fn init() BeaconStateView { @@ -1037,7 +1036,7 @@ pub fn createMultiProof(self: *const BeaconStateView, descriptor: js.Uint8Array) pub fn computeUnrealizedCheckpoints(self: *const BeaconStateView) !js_types.UnrealizedCheckpoints { const env = js.env(); const cached_state = try self.requireState(); - const result = try st.computeUnrealizedCheckpoints(allocator, napi_io.get(), cached_state); + const result = try st.computeUnrealizedCheckpoints(allocator, js.io(), cached_state); const obj = try env.createObject(); try obj.setNamedProperty( @@ -1280,7 +1279,7 @@ pub fn processSlots(self: *const BeaconStateView, slot_arg: js.Number, options: allocator.destroy(post_state); } - try st.processSlots(allocator, napi_io.get(), post_state, slot_value, .{}); + try st.processSlots(allocator, js.io(), post_state, slot_value, .{}); return .{ .cached_state = post_state, .pool_rc = pool.state.poolRc().ref(), @@ -1309,7 +1308,7 @@ pub fn stateTransition(self: *const BeaconStateView, signed_block_bytes: js.Uint const signed_block = try AnySignedBeaconBlock.deserialize(allocator, .full, fork_seq, bytes); defer signed_block.deinit(allocator); - const post_state = try st.stateTransition(allocator, napi_io.get(), cached_state, signed_block, opts); + const post_state = try st.stateTransition(allocator, js.io(), cached_state, signed_block, opts); return .{ .cached_state = post_state, .pool_rc = pool.state.poolRc().ref(), diff --git a/bindings/napi/blst.zig b/bindings/napi/blst.zig index c48298e78..4a7f5e064 100644 --- a/bindings/napi/blst.zig +++ b/bindings/napi/blst.zig @@ -15,7 +15,6 @@ const zapi = @import("zapi:zapi"); const js = zapi.js; const napi = zapi.napi; const bls = @import("bls"); -const napi_io = @import("./io.zig"); const NativePublicKey = bls.PublicKey; const NativeSignature = bls.Signature; @@ -39,25 +38,32 @@ const BATCH_VERIFY_SIZE = 32; /// Initialized lazily on first use, torn down via `deinitThreadPool`. var thread_pool: ?*ThreadPool = null; -pub fn initThreadPool(n_workers: u16) !void { - if (thread_pool != null) return error.PoolExists; - thread_pool = try ThreadPool.init(std.heap.page_allocator, napi_io.get(), .{ .n_workers = n_workers }); -} +/// Native-only thread pool lifecycle, reached from `root.zig` through the pub +/// `lifecycle` var. Not a pub type: zapi's `exportModule` walks pub type decls +/// and rejects their non-DSL pub fns, while pub vars are skipped. +const Lifecycle = struct { + pub fn initThreadPool(_: *Lifecycle, n_workers: u16) !void { + if (thread_pool != null) return error.PoolExists; + thread_pool = try ThreadPool.init(std.heap.page_allocator, js.io(), .{ .n_workers = n_workers }); + } -/// Closes the `ThreadPool` used for blst operations. -/// -/// Note: this can invalidate any inflight verification requests. Consumer is responsible -/// for the lifecycle of their program and should only call this when all work is done. -/// -/// This note is however application dependent. For the use case of lodestar, -/// it's likely that this would not be called at all. -/// Same goes for any other long-lived processes. -pub fn deinitThreadPool() void { - if (thread_pool) |p| { - p.deinit(napi_io.get()); - thread_pool = null; + /// Closes the `ThreadPool` used for blst operations. + /// + /// Note: this can invalidate any inflight verification requests. Consumer is responsible + /// for the lifecycle of their program and should only call this when all work is done. + /// + /// This note is however application dependent. For the use case of lodestar, + /// it's likely that this would not be called at all. + /// Same goes for any other long-lived processes. + pub fn deinitThreadPool(_: *Lifecycle) void { + if (thread_pool) |p| { + p.deinit(js.io()); + thread_pool = null; + } } -} +}; + +pub var lifecycle: Lifecycle = .{}; var gpa: std.heap.DebugAllocator(.{}) = .init; const allocator = if (builtin.mode == .Debug) @@ -375,7 +381,7 @@ pub fn aggregateVerify(msgs: js.Array, pks: js.Array, sig: Signature, pks_valida const pool = thread_pool orelse return error.ThreadPoolNotInitialized; const result = pool.aggregateVerify( - napi_io.get(), + js.io(), &sig.raw, try boolOrDefault(sig_groupcheck, false), msg_bufs, @@ -473,7 +479,7 @@ pub fn verifyMultipleAggregateSignatures(sets: js.Array, pks_validate: ?js.Boole }; var seed_bytes: [8]u8 = undefined; - const io = napi_io.get(); + const io = js.io(); io.random(&seed_bytes); var prng = std.Random.DefaultPrng.init(std.mem.readInt(u64, &seed_bytes, .little)); const rand = prng.random(); @@ -503,7 +509,7 @@ pub fn verifyMultipleAggregateSignatures(sets: js.Array, pks_validate: ?js.Boole const pool = thread_pool orelse return error.ThreadPoolNotInitialized; const result = pool.verifyMultipleAggregateSignatures( - napi_io.get(), + js.io(), n_elems, msgs, DST, @@ -613,7 +619,7 @@ pub fn aggregateWithRandomness(sets: js.Array) !js.Value { var sig_ptrs: [MAX_AGGREGATE_PER_JOB]*const NativeSignature = undefined; var seed_bytes: [8]u8 = undefined; - const io = napi_io.get(); + const io = js.io(); io.random(&seed_bytes); var prng = std.Random.DefaultPrng.init(std.mem.readInt(u64, &seed_bytes, .little)); const rand = prng.random(); @@ -720,7 +726,7 @@ fn asyncAggRand_execute(_: napi.Env, data: *AsyncAggRandData) void { return; }; pool.aggregateWithRandomness( - napi_io.get(), + js.io(), data.pk_ptrs[0..data.n], data.sig_ptrs[0..data.n], data.randomness[0 .. data.n * 32], @@ -816,7 +822,7 @@ pub fn asyncAggregateWithRandomness(sets: js.Array) !js.Value { data.err = null; data.deferred = undefined; data.work = undefined; - napi_io.get().random(data.randomness[0 .. n * 32]); + js.io().random(data.randomness[0 .. n * 32]); for (0..n) |i| { const set = (try sets.get(@intCast(i))).toValue(); diff --git a/bindings/napi/config.zig b/bindings/napi/config.zig index 0132bd02f..a59092fe3 100644 --- a/bindings/napi/config.zig +++ b/bindings/napi/config.zig @@ -9,7 +9,7 @@ const Preset = @import("preset").Preset; const max_blob_schedule_entries = 16; -pub const State = struct { +const State = struct { config: BeaconConfig = undefined, initialized: bool = false, config_name: [64]u8 = undefined, @@ -71,7 +71,7 @@ pub fn set(object: js.Value, genesis_root: js.Uint8Array) !void { state.initialized = true; } -pub fn chainConfigFromObject(env: napi.Env, obj: napi.Value) !ChainConfig { +fn chainConfigFromObject(env: napi.Env, obj: napi.Value) !ChainConfig { var chain_config: ChainConfig = undefined; inline for (std.meta.fields(ChainConfig)) |field| { diff --git a/bindings/napi/io.zig b/bindings/napi/io.zig deleted file mode 100644 index 537e6799c..000000000 --- a/bindings/napi/io.zig +++ /dev/null @@ -1,48 +0,0 @@ -const std = @import("std"); - -/// Process-wide `Io` for NAPI callbacks, mirroring the `init.io` that a Zig -/// binary receives from `std.process.Init` (see `std.start.zig`'s -/// `std.Io.Threaded.init(gpa, .{})`). -/// -/// Why not `init_single_threaded`? -/// -/// Today the only Io operations we invoke inside NAPI callbacks are -/// `Clock.Timestamp.now`, `Io.Mutex` lock/unlock, and `io.random` — all -/// backed by direct OS syscalls that don't touch the Threaded executor's -/// allocator / worker pool, so `init_single_threaded` would technically -/// suffice. But that instance pins `allocator = .failing` and -/// `async_limit = .nothing`, so the moment any code path starts calling -/// `io.async(...)` / `io.concurrent(...)` / group scheduling, it panics. -/// Matching the `init.io` defaults keeps us future-proof at essentially -/// zero cost — the worker pool is lazy: threads are only spawned on the -/// first async/concurrent call, up to `async_limit` (cpu_count - 1). -/// -/// Initialized once on the first `register()` call (env_refcount 0→1) and -/// torn down when the last NAPI env closes (env_refcount 1→0). Safe to share -/// across Node.js worker threads — `std.Io.Threaded` protects its own -/// internal state with mutexes. -var instance: std.Io.Threaded = undefined; -var initialized: bool = false; - -const gpa: std.mem.Allocator = std.heap.page_allocator; - -/// Initialize the shared `Threaded`. Idempotent. -pub fn init() !void { - if (initialized) return; - instance = std.Io.Threaded.init(gpa, .{}); - initialized = true; -} - -/// Get the shared `Io`. Caller must ensure `init()` has been invoked -/// (guaranteed by the `register()` flow in `root.zig`). -pub fn get() std.Io { - std.debug.assert(initialized); - return instance.io(); -} - -/// Tear down the shared `Threaded`. Idempotent. -pub fn deinit() void { - if (!initialized) return; - instance.deinit(); - initialized = false; -} diff --git a/bindings/napi/metrics.zig b/bindings/napi/metrics.zig index 389cea57a..6e387d936 100644 --- a/bindings/napi/metrics.zig +++ b/bindings/napi/metrics.zig @@ -2,7 +2,6 @@ const std = @import("std"); const builtin = @import("builtin"); const js = @import("zapi:zapi").js; const state_transition = @import("state_transition"); -const napi_io = @import("./io.zig"); var gpa: std.heap.DebugAllocator(.{}) = .init; const allocator = if (builtin.mode == .Debug) @@ -15,7 +14,7 @@ var initialized: bool = false; /// JS: metrics.init() → void pub fn init() !void { if (initialized) return; - try state_transition.metrics.init(allocator, napi_io.get(), .{}); + try state_transition.metrics.init(allocator, js.io(), .{}); initialized = true; } diff --git a/bindings/napi/pool.zig b/bindings/napi/pool.zig index 2e0ec480b..5c2b9ab38 100644 --- a/bindings/napi/pool.zig +++ b/bindings/napi/pool.zig @@ -9,14 +9,17 @@ const allocator = std.heap.page_allocator; const default_pool_size: u32 = 0; -pub const PoolRc = RefCount(Node.Pool); +/// Not `pub`: zapi's `exportModule` walks pub type decls and rejects their +/// non-DSL pub fns. Cross-file consumers reach this type through the pub +/// `state` var (e.g. `@TypeOf(pool.state.pool_rc)`). +const PoolRc = RefCount(Node.Pool); /// Pool is wrapped in `RefCount` so binding objects holding pool refs at /// process exit keep the pool alive until their JS finalizer runs. NAPI /// env cleanup hook fires before module-level JS holders are finalized, /// so an unconditional `pool.deinit()` there would free memory that /// `pool.unref()` calls in those finalizers still need. -pub const State = struct { +const State = struct { pool_rc: ?*PoolRc = null, pub fn init(self: *State) !void { diff --git a/bindings/napi/pubkeys.zig b/bindings/napi/pubkeys.zig index e65813520..9d0520c53 100644 --- a/bindings/napi/pubkeys.zig +++ b/bindings/napi/pubkeys.zig @@ -4,7 +4,6 @@ const bls = @import("bls"); const blst_bindings = @import("./blst.zig"); const PubkeyIndexMap = @import("state_transition").PubkeyIndexMap; const Index2PubkeyCache = @import("state_transition").Index2PubkeyCache; -const napi_io = @import("./io.zig"); /// Uses page allocator for internal allocations. /// It's recommended to never reallocate the pubkey2index after initialization. @@ -13,7 +12,7 @@ const allocator = std.heap.page_allocator; const default_initial_capacity: u32 = 0; const max_stack_aggregate_pubkeys = 512; -pub const State = struct { +const State = struct { pubkey2index: PubkeyIndexMap = undefined, index2pubkey: Index2PubkeyCache = undefined, initialized: bool = false, @@ -81,7 +80,7 @@ fn pubkey2indexWrittenSize() usize { pub fn save(file_path: js.String) !void { var file_path_buf: [1024]u8 = undefined; const path = try file_path.toSlice(&file_path_buf); - const io = napi_io.get(); + const io = js.io(); const file = try std.Io.Dir.createFile(.cwd(), io, path, .{}); defer file.close(io); @@ -110,7 +109,7 @@ pub fn save(file_path: js.String) !void { pub fn load(file_path: js.String) !void { var file_path_buf: [1024]u8 = undefined; const path = try file_path.toSlice(&file_path_buf); - const io = napi_io.get(); + const io = js.io(); const file = try std.Io.Dir.openFile(.cwd(), io, path, .{}); defer file.close(io); diff --git a/bindings/napi/root.zig b/bindings/napi/root.zig index 5cd6a8d38..e2edcb888 100644 --- a/bindings/napi/root.zig +++ b/bindings/napi/root.zig @@ -10,7 +10,6 @@ pub const blst = @import("./blst.zig"); pub const pubkeys = @import("./pubkeys.zig"); const options = @import("bls_options"); -const napi_io = @import("./io.zig"); var gpa: std.heap.DebugAllocator(.{}) = .init; const allocator = if (builtin.mode == .Debug) gpa.allocator() else std.heap.c_allocator; @@ -18,9 +17,6 @@ const allocator = if (builtin.mode == .Debug) gpa.allocator() else std.heap.c_al fn init(old_ref_count: u32) !void { if (old_ref_count == 0) { // First environment — initialize shared state in your threadpool init. - try napi_io.init(); - errdefer napi_io.deinit(); - var cpu_count: u64 = options.thread_count; if (options.thread_count == 0) { cpu_count = @max(try detectCpuCount(), 2) - 1; @@ -31,7 +27,7 @@ fn init(old_ref_count: u32) !void { } const n_workers = @min(cpu_count, @import("bls").ThreadPool.MAX_WORKERS); - try blst.initThreadPool(@intCast(n_workers)); + try blst.lifecycle.initThreadPool(@intCast(n_workers)); try pool.state.init(); try pubkeys.state.init(); config.state.init(); @@ -42,7 +38,7 @@ fn init(old_ref_count: u32) !void { /// not prevent the module from loading: warn and fall back to the affinity /// count (what `std.Thread.getCpuCount()` reports). fn detectCpuCount() !usize { - return @import("cpu_count").getNumCpus(allocator, napi_io.get()) catch |err| { + return @import("cpu_count").getNumCpus(allocator, js.io()) catch |err| { std.debug.print( "Warning: cgroup CPU detection failed ({s}), using affinity count\n", .{@errorName(err)}, @@ -54,12 +50,11 @@ fn detectCpuCount() !usize { fn cleanup(new_ref_count: u32) void { if (new_ref_count == 0) { // Last environment — tear down shared state. - blst.deinitThreadPool(); + blst.lifecycle.deinitThreadPool(); config.state.deinit(); pubkeys.state.deinit(); pool.state.deinit(); metrics.deinit(); - napi_io.deinit(); } } diff --git a/build.zig.zon b/build.zig.zon index d844799f7..939840652 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -40,8 +40,8 @@ .hash = "zig_yaml-0.1.0-C1161kFWAwDxjKAFmklKwWVDvz2mmq0Q__bDhGGjeyd3", }, .zapi = .{ - .url = "https://github.com/ChainSafe/zapi/archive/refs/tags/zapi-v2.2.0.tar.gz", - .hash = "zapi-2.2.0-rIqzUXBaBADUsvvvB2N5kOBdLEO0rGPhowTqmIXe3qVh", + .url = "https://github.com/ChainSafe/zapi/archive/refs/tags/zapi-v3.0.0.tar.gz", + .hash = "zapi-3.0.0-rIqzUQJsBAB4NLcumPdgG1fXtWjLnkTixzr6xsX5XAVO", }, .zbench = .{ .url = "git+https://github.com/hendriknielaender/zBench#b2b89c475e3ef1bb2bd71255c80478a82d3e0ca8", From 690cb48184d74a3b24533d8d458bdb45d688d07f Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Tue, 14 Jul 2026 18:27:24 +0500 Subject: [PATCH 2/2] docs(bindings): move exportModule workaround rationale to PR Co-Authored-By: Claude Fable 5 --- bindings/napi/blst.zig | 5 ++--- bindings/napi/pool.zig | 3 --- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/bindings/napi/blst.zig b/bindings/napi/blst.zig index 4a7f5e064..b04e26eb7 100644 --- a/bindings/napi/blst.zig +++ b/bindings/napi/blst.zig @@ -38,9 +38,8 @@ const BATCH_VERIFY_SIZE = 32; /// Initialized lazily on first use, torn down via `deinitThreadPool`. var thread_pool: ?*ThreadPool = null; -/// Native-only thread pool lifecycle, reached from `root.zig` through the pub -/// `lifecycle` var. Not a pub type: zapi's `exportModule` walks pub type decls -/// and rejects their non-DSL pub fns, while pub vars are skipped. +/// Native-only thread pool lifecycle, reached from `root.zig` through the +/// pub `lifecycle` var so it is not part of the JS module surface. const Lifecycle = struct { pub fn initThreadPool(_: *Lifecycle, n_workers: u16) !void { if (thread_pool != null) return error.PoolExists; diff --git a/bindings/napi/pool.zig b/bindings/napi/pool.zig index 5c2b9ab38..c23dcec40 100644 --- a/bindings/napi/pool.zig +++ b/bindings/napi/pool.zig @@ -9,9 +9,6 @@ const allocator = std.heap.page_allocator; const default_pool_size: u32 = 0; -/// Not `pub`: zapi's `exportModule` walks pub type decls and rejects their -/// non-DSL pub fns. Cross-file consumers reach this type through the pub -/// `state` var (e.g. `@TypeOf(pool.state.pool_rc)`). const PoolRc = RefCount(Node.Pool); /// Pool is wrapped in `RefCount` so binding objects holding pool refs at