Pure-Rust WebAssembly, Capability-Attenuated Web Workers & Direct Kernel I/O
This document covers Slice’s Pure-Rust WebAssembly engine (wasm/ via wasmi v2.0.0), capability-attenuated MicroVM Web Workers and node:worker_threads (workers.rs), direct kernel completion rings (slice-io: Linux io_uring & Windows IOCP), and OS-native kernel event file watching (OsNativeFileWatcher).
1. Pure-Rust WebAssembly Engine (wasmi v2.0.0), Shared Per-Isolate Store & 5-Ring WASM Cage
Section titled “1. Pure-Rust WebAssembly Engine (wasmi v2.0.0), Shared Per-Isolate Store & 5-Ring WASM Cage”Implemented across crates/slice-engine/src/runtime/wasm/ (mod.rs, store.rs, memory.rs, linking.rs, values.rs) and crates/slice-engine/src/preludes/09_wasm.js:
- Zero Overhead When Unused (
Shard 9):globalThis.WebAssemblyis registered as a self-replacing lazy getter (__defLazy(["WebAssembly"], 9)viaLAZY_GETTERS_INIT_PRELUDE) and gated indetect_shards_and_boacas_flagsso non-WASM workloads pay0.00 nsand0 B.
- Speculative
GLOBAL_WASM_MODULE_CACHE& Shared Per-Isolatewasmi::Store:- A process-wide
OnceLock<wasmi::Engine>(CompilationMode::LazyTranslation,consume_fuel(true)) +RwLock<FxHashMap<(u64, usize), wasmi::Module>>validates and translates each.wasmbinary at most once per process, enabling< 15 uswarm module instantiation across isolates and worker threads. - All
WebAssembly.Instance,WebAssembly.Memory,WebAssembly.Global, andWebAssembly.Tableobjects within an isolate turn share a single per-isolatewasmi::Store<WasmStoreData>(withSavedIsolateContextGuardisolation across nestedSlice.evalSandboxcalls and full teardown onreset_thread_wasm_state()). Imported and re-exportedMemory,Global,Table, and exported Wasm functions share live underlying storage and preserve canonical JS wrapper identity (instance.exports.g === global,instance.exports.memory === memory,instance.exports.t === table).
- A process-wide
- Zero-Stat
.wasmModule Bundling (slice-cas):- Static or dynamic
.wasmimports (import wasmBytes from "./kernel.wasm") are embedded directly into.casarchives and standaloneSLICEEXEbinaries as zero-statUint8Arraypayloads (__slice_b64ToU8).
- Static or dynamic
- W3C WebAssembly JS-API 2.0 Semantics & Zero-Allocation Fast Call Path:
- Exported Wasm functions bind directly to native Rust
NativeFunction::from_copy_closureclosures backed by stack-allocatedSmallVec<[Val; 8]>, eliminating JS argument arrays and string serialization on numeric (i32/i64/f32/f64) calls. ValType::I64parameters,WebAssembly.Globali64values, and hosti64returns apply ECMAScriptToBigInt64(val.to_big_int64) with exact two’s-complement modulo-2^64wrapping for arbitrary-precisionBigInts and strictTypeErrorrejection onNumbers.- Authentic
WebAssembly.CompileError,WebAssembly.LinkError, andWebAssembly.RuntimeErrorinstances are constructed directly against realm prototypes, while JS exceptions thrown inside host import callbacks propagate unmangled (PENDING_HOST_JS_ERROR).
- Exported Wasm functions bind directly to native Rust
- 5-Ring WebAssembly Security & Resource Cage:
- Ring 1 (Binary Validation): Enforces
MAX_WASM_BINARY_BYTES = 8 MBand WASM magic header (\0asm\x01\0\0\0) validation before compilation. - Ring 2 (Unified Re-Entrant CPU Fuel Metering): Synchronizes
wasmi::Store::set_fuel/get_fuelat every JS-to-Wasm and Wasm-to-JS host callback boundary with the parentSliceIsolate’sBOA_FUEL_BUDGET, preempting infinite WASM loops deterministically withSandboxViolation::CpuFuelExhausted. - Ring 3 (Unified Linear Memory Cage via
SliceWasmLimiter): Implementswasmi::ResourceLimiteron the sharedStoreto enforceMAX_WASM_MEMORY_PAGES = 256(16 MiB) and charge net linear memory growth (desired - current) againstBOA_KV_MEM_BUDGETacross both JSmemory.grow()and native Wasm(memory.grow ...)instructions (SandboxViolation::MemoryCeilingExceeded), without double-charging importedMemoryobjects. - Ring 4 (Zero Ambient WASI Authority & Fuel-Metered Host Imports): Exposes zero ambient OS/filesystem WASI descriptors by default while supporting fuel-metered JavaScript host function imports (
importObject.<module>.*) and direct nativewasmi::Funccross-instance linking. - Ring 5 (Lazy Linear Memory Mirroring,
ResetMemoryBufferDetachment & Post-Trap Coherence): DefersWebAssembly.Memory.prototype.bufferallocation (created with[[ArrayBufferDetachKey]] = "WebAssembly.Memory") until JavaScript explicitly accesses.buffer, synchronizes modifications between JSArrayBufferviews andwasmi::Memoryusing 8-byteu64word-aligned delta scans across pre-call, host-callback, post-call, and post-trap (unreachable, out-of-bounds,(start)trap) boundaries, detaches staleArrayBuffers (detached === true,byteLength === 0) on both native Wasmmemory.growand JSmemory.grow(delta)(includingdelta === 0), and inspects all outputs through the Outbound Egress Secret DLP Firewall.
- Ring 1 (Binary Validation): Enforces
2. Capability-Attenuated MicroVM Web Workers & node:worker_threads (workers.rs)
Section titled “2. Capability-Attenuated MicroVM Web Workers & node:worker_threads (workers.rs)”Implemented in crates/slice-engine/src/runtime/workers.rs and crates/slice-engine/src/preludes/08_workers_sockets.js:
- Standards-Compliant Surface: Supports both WhatWG
new Worker(urlOrInlineSource, options)(postMessage,onmessage,terminate),MessageChannel,MessagePort,BroadcastChannel, and Node.jsnode:worker_threads(Worker,isMainThread,parentPort,workerData,threadId). - Strict Parent-Child OCap Intersection (
build_attenuated_worker_caps):- A child worker’s
CapabilityTokenis strictly intersected with its parent isolate’s capabilities (parent_capsintersectchild_requested_caps). A worker can never escalate filesystem, network, or environment privileges beyond its parent compartment, and worker CPU fuel and memory budgets are capped by the parent’s remaining limits.
- A child worker’s
- Persistent Warm Worker Pool (
IDLE_WORKER_POOL) &WORKER_SCRIPT_CACHE:- Rather than spawning a fresh OS thread and initializing a cold
Boarealm pernew Worker(), Slice maintains a warmIDLE_WORKER_POOLwith speculative pre-warming (speculative_prewarm_worker_pool) and caches transpiled worker scripts byBLAKE3fingerprint inWORKER_SCRIPT_CACHE(__SLICE_RC), keeping multi-worker cold and warm execution latency low (seetests/reports/latest.mdfor22-worker-threads-and-raw-socketsbenchmarks).
- Rather than spawning a fresh OS thread and initializing a cold
3. Direct Kernel Completion Rings (crates/slice-io) & OS-Native File Watcher
Section titled “3. Direct Kernel Completion Rings (crates/slice-io) & OS-Native File Watcher”3.1 crates/slice-io: io_uring, IOCP, & RegisteredBufferPool 4096-Byte Page-Aligned Slabs
Section titled “3.1 crates/slice-io: io_uring, IOCP, & RegisteredBufferPool 4096-Byte Page-Aligned Slabs”- Registered Page-Aligned Slab Buffers (
RegisteredBufferPool): Allocates a single contiguous4096-byte page-aligned slab (PAGE_ALIGNMENT = 4096,FIXED_BUFFER_COUNT = 64,FIXED_BUFFER_SIZE = 65536) viastd::alloc::Layout::from_size_alignwith O(1) LIFO slot acquisition (acquire/acquire_slot/buffer_mut), zeroedrelease, andin_flightDMA slot quarantine preventing CPU aliasing if a kernel submission batch fails mid-flight. Exposed safely onCompletionRingEngineviabuffer_pool(),buffer_pool_mut(), andwith_pool_config(...), and integrated intooutbound_http::send_and_read_framed_http11(SHARED_FETCH_SLAB_POOL+FetchSlabSlotGuard) andevent_loop::FetchReactorPool(MAX_FETCH_REACTOR_WORKERS = 16). - Linux
io_uring(CompletionRingEngine): Attempts kernel ring setup withIORING_SETUP_SQPOLL(IoUring::builder().setup_sqpoll(1000)), registers pinned64 KBslabiovecbuffers viaIORING_REGISTER_BUFFERS(settingRingStatus.registered_buffersstrictly from kernel registration success and callingunregister_buffers()onDrop), pre-checks SQ capacity before pushing SQEs, drains residual CQEs cleanly across batches, and falls back to positionedlibc::pread/libc::pwritewhenio_uringis restricted by unprivileged seccomp policies. - Windows NT
IOCP& Overlapped Positioned File I/O: Binds directly toCreateIoCompletionPort,PostQueuedCompletionStatus, batchedGetQueuedCompletionStatusEx, and positionedReadFile/WriteFile(OVERLAPPED64-bit file offset +GetOverlappedResult) viakernel32.dllFFI, preserving lossless 64-bituser_datatags and signedi32byte/error results acrossNop,ReadFixed, andWriteFixedbatches.
3.2 OS-Native Kernel Event File Watcher (config/mod.rs & OsNativeFileWatcher)
Section titled “3.2 OS-Native Kernel Event File Watcher (config/mod.rs & OsNativeFileWatcher)”- Uses the cross-platform
notify(v8.2) crate (inotifyon Linux,ReadDirectoryChangesWon Windows,FSEvents/kqueueon macOS) blocking directly on kernel notifications (rx.recv()) with zero idle wakeups and zero idlestatwalks in--watchmode (15 mssave-burst debounce), whileslice serve --tenant-dir=<dir>combines watcher generation tracking with a250 msstatTTL for zero-syscall warm request routing and instant.cashot-swaps.