Skip to content

slice-engine: Hybrid Three-Tier Execution Pipeline, WarmBoaRealm & Native Intrinsics

crates/slice-engine is designed around a single principle: use the lightest execution tier capable of running the workload, pay 0.00 ns and 0 B for unused Web/Node globals via compile-time minified lazy prelude shards, and accelerate hot standard-library primitives in native Rust.


1. Default Tier-1 SLICEBC\x01 Precompiled Boa CodeBlock CAS & Zero-Copy Framing (0.02 us - 0.21 us Instantiation)

Section titled “1. Default Tier-1 SLICEBC\x01 Precompiled Boa CodeBlock CAS & Zero-Copy Framing (0.02 us - 0.21 us Instantiation)”
  • The Problem Eliminated:
    1. Wrapping bundled JS inside a JSON-serialized BytecodeModule (SLICESNP) required serde_json::from_slice to allocate and unescape a 30 KB - 130 KB String on every isolate run (~229 microseconds).
    2. Even with raw UTF-8 SLICEBOA framing, boa_engine::Context::eval had to run the full ECMAScript lexer, recursive-descent AST parser, ScopeAnalyzer identifier resolution, and ByteCompiler on ULTRA_CORE_PRELUDE, needed feature shards, node:* built-in scripts, and the user’s bundled JS on every cold process launch.
  • Default SLICEBC\x01 Precompiled CodeBlock Architecture (crates/slice-engine/src/vm/boacas.rs & vendor/boa_engine/SLICE_PATCH.md):
    • By default (boacas = true), compile_source_to_bytecode calls pack_boacas_container, which emits a 32-byte BoaCasHeader (b"SLICEBC\x01") containing:
      • feature_flags: u16 (BOACAS_FLAG_HAS_WORKER, BOACAS_FLAG_HAS_NEXT_TICK, BOACAS_FLAG_HAS_HTTP_BRIDGE, BOACAS_FLAG_HAS_SEMVER_FAST, BOACAS_FLAG_HAS_KV_SANDBOX, BOACAS_FLAG_NEEDS_LAZY_GETTERS, BOACAS_FLAG_NEEDS_SES_CHECK, BOACAS_FLAG_IS_RC_BUNDLE, BOACAS_FLAG_STARTS_WITH_BRACE) + shards_mask: u32: Computed together in a single $O(N)$ aho_corasick::AhoCorasick DFA pass via detect_shards_and_boacas_flags inside compute_boacas_metadata (eliminating 38 separate .contains() linear substring scans over bundled JS).
      • rc_key: u64 (pre-extracted persistent realm cache fingerprint)
      • precompiled_len: u32 (SLCB\x01 binary CodeBlock payload) + fallback_js_len: u32
    • Pre-Fused Prelude + JS Shards (1..=18, 29) + node:* Built-Ins (19..=28, 30) + 2-Hit AtomicU8 Prelude Cache: At build time, pack_boacas_container expands transitive shard prerequisites via expand_shard_prerequisites (e.g. ensuring EventTarget Shard 13 precedes WebSocket/Worker/AbortSignal Shards 7, 8, 10 and Buffer Shard 5 precedes node:zlib Bit 30) and fuses ULTRA_CORE_PRELUDE, all required runtime JS shards (1..=18 and bit 29 in topological SHARD_LOAD_ORDER), and all statically referenced node:* built-in modules (19..=28 and 30) directly with the user script into a single unified Gc<CodeBlock>, serialized via boa_engine::Script::compile_to_slicebc. For dynamic or child-sandbox prelude/builtin evaluations at runtime, eval_static_js_with_2hit_slicebc_cache evaluates directly on the caller’s Context on the 1st cold hit (zero throwaway Context allocation) and populates OnceLock SLCB\x01 caches only on the 2nd+ realm in long-lived processes.
    • Lazy Stringified Cold Modules: Unreachable or cold-method node_modules factories deferred by collect_eager_module_indices (__slice_modules[id] = "...") are skipped by is_in_lazy_string_module_line during shard scanning and remain inert string constants inside SLCB\x01 until dynamically required at runtime.
    • Zero-Parse & Zero-Syscall Runtime Execution: At runtime, slice-cli uses mimalloc on Windows (#[cfg(windows)] in slice-cli only, replacing HeapAlloc while preserving glibc tcache’s sub-8 MB RSS footprint on Linux and keeping slice-engine allocator-agnostic for embedders) and SliceIsolate::exec_boacas_vm decodes headers via BoaCasHeader::decode_raw (deferring fallback_js UTF-8 scans), creates a bare boa_engine::Context wired with IdleModuleLoader (create_bare_boa_realm, 0 host realpath syscalls), registers only the required native Rust host functions in a single pass, deserializes the Gc<CodeBlock> directly from the mmap slice via boa_engine::Script::from_slicebc_bytes, and executes it on the VM - eliminating 100% of runtime JS lexing, AST parsing, scope analysis, and bytecode compilation on cold start (see tests/reports/latest.md for measured cold and warm latencies).
    • Legacy SLICEBOA Source-in-CAS Fallback (--no-boacas): If --no-boacas (or // @slice-boacas: false / SLICE_BOACAS=0 / [engine] boacas = false) is set, compile_source_to_bytecode emits the 8-byte b"SLICEBOA" header followed by raw UTF-8 transpiled JS.

2. Pre-Warmed Boa Context Pool (BOA_CONTEXT_POOL), __slice_rc Persistent Realm Cache, & Sharded Preludes

Section titled “2. Pre-Warmed Boa Context Pool (BOA_CONTEXT_POOL), __slice_rc Persistent Realm Cache, & Sharded Preludes”
  1. Maintains a thread-local pool of pre-initialized WarmBoaRealm instances (SliceIsolate::prewarm_boa_pool(count)), wrapped in std::mem::ManuallyDrop<Vec<WarmBoaRealm>> so thread exit on Windows never runs boa_engine::Context::drop after boa_gc’s TLS collector has already torn down.
  2. Wraps executed scripts inside a lexical block ({\n<js_code>\n}) in exec_boa_full_es_vm so top-level const, let, and class declarations are scoped to that invocation and never collide when the warm context is reused across requests in slice serve or slice run --warm.
  3. Routes console.log directly through a native Rust __slice_console_log host function writing straight into thread-local BOA_STDOUT.

2.2 Persistent Realm Module Cache (__slice_rc), Precompiled __slice_drain_wu, & BOA_DIRTY_SUBSYSTEMS Teardown

Section titled “2.2 Persistent Realm Module Cache (__slice_rc), Precompiled __slice_drain_wu, & BOA_DIRTY_SUBSYSTEMS Teardown”
  • bundle_entrypoint_with_deps emits a 16-hex-char BLAKE3 fingerprint header (//__SLICE_RC:<16_hex_chars>) and caches evaluated node_modules exports (__slice_cache) plus the compiled entrypoint closure in globalThis.__slice_rc.
  • On warm hits (slice serve or slice run --warm), WarmBoaRealm::loaded_bundles stores the compiled boa_engine::JsObject entrypoint function handle and invokes fn_obj.call(...) directly in Rust with 0 JS parser passes and 0 node_modules CJS factory re-evaluations.
  • WarmBoaRealm::drain_wu_fn caches the precompiled globalThis.__slice_drain_wu function handle so SliceIsolate::drain_wait_until_tasks drains background ctx.waitUntil(...) callbacks via direct JsObject::call without invoking Context::eval (boa_parser + ByteCompiler) on every HTTP request (see tests/reports/latest.md for slice serve Tier-0 and Tier-1 keep-alive throughput).
  • BOA_DIRTY_SUBSYSTEMS tracks a single-byte bitmask (DIRTY_EVENT_LOOP, DIRTY_ALS, DIRTY_FETCH_MOCK, DIRTY_WEBSOCKET, DIRTY_SOCKETS, DIRTY_WORKERS, DIRTY_WASM) so isolate teardown in teardown_boa_compartment_thread_locals and clear_event_loop_state skips clearing subsystems that were never touched during the isolate turn.

2.3 Compile-Time Minified 32-Bit shards_mask Surgical Preludes (00_ultra_core.js + JS Shards 01..19 + Pre-Fused node:* Bits 19..=28, 30)

Section titled “2.3 Compile-Time Minified 32-Bit shards_mask Surgical Preludes (00_ultra_core.js + JS Shards 01..19 + Pre-Fused node:* Bits 19..=28, 30)”
  • Implemented in crates/slice-engine/build.rs, crates/slice-engine/src/preludes/js_preludes.rs, and crates/slice-engine/src/runtime/boa_realm.rs (WarmBoaRealm::loaded_shards_mask: u32, paired with 16-bit BOACAS_FLAG_* feature flags in boacas.rs):
    • Instead of evaluating a monolithic JS prelude on every cold process launch, 00_ultra_core.js (~2 KB minified, preserving native Boa Date.now and Math.random fast paths unless --deterministic is active) is always-on, LAZY_GETTERS_INIT_PRELUDE (bit 0, __defLazy(names, shardId)) is evaluated only when BOACAS_FLAG_NEEDS_LAZY_GETTERS is set, and the remaining bits of shards_mask: u32 selectively fuse or lazy-load 19 orthogonal JS prelude shards plus 11 pre-fused node:* modules:
      • Bit 0 (LAZY_GETTERS_INIT_PRELUDE): Self-replacing Object.defineProperty lazy global getters (__defLazy) when dynamic globalThis.* probes are detected (BOACAS_FLAG_NEEDS_LAZY_GETTERS).
      • Shard 1 (01_web_fetch_url.js): URL and URLSearchParams (backed by native Rust url_and_usp.rs).
      • Shard 2 (02_encoding_events.js): TextEncoder, TextDecoder, btoa, atob.
      • Shard 3 (03_streams_formdata.js): ReadableStream.
      • Shard 4 (04_webcrypto_clone.js): crypto, CryptoKey (with tenant-scoped CRYPTO_KEY_HANDLE_TABLE pre-expanded key handles), crypto.subtle (digest, generateKey, importKey, exportKey, encrypt, decrypt, sign, verify, deriveBits, deriveKey, timingSafeEqual), randomUUID, getRandomValues.
      • Shard 5 (05_full_buffer.js): Core Uint8Array-backed Buffer (from, alloc, concat, byteLength, compare, toString, subarray, equals) with lazy Shard 17 prototype forwarders.
      • Shard 6 (06_console_ext.js): Extended console.* inspection and profiling methods (table, dir, dirxml, group, groupCollapsed, groupEnd, time, timeLog, timeEnd, count, countReset, trace, assert, clear).
      • Shard 7 (07_websocket.js): WebSocket, MessageEvent, CloseEvent.
      • Shard 8 (08_workers_sockets.js): Worker, MessageChannel, MessagePort, Slice.connect.
      • Shard 9 (09_wasm.js): WebAssembly (Module, Instance, Memory, Table, Global, compile, instantiate, validate).
      • Shard 10 (10_outbound_fetch_sse.js): fetch, AbortController, AbortSignal (timeout, any, abort), EventSource, Slice.streamSSE, Response.sse.
      • Shard 11 (11_fetch_headers_req_res.js): Headers (with _isHeaders fast copy, O(1) lowercase get(), and getSetCookie()), Request, Response, __slice_make_web_request.
      • Shard 12 (12_url_pattern.js): URLPattern.
      • Shard 13 (13_dom_events.js): DOMException, Event, CustomEvent, EventTarget.
      • Shard 14 (14_transform_compression_streams.js): WritableStream, TransformStream, TextEncoderStream, TextDecoderStream, CompressionStream, DecompressionStream.
      • Shard 15 (15_blob_formdata.js): Blob, File, FormData.
      • Shard 16 (16_structured_clone.js): structuredClone.
      • Shard 17 (17_buffer_binary_rw.js): Buffer.prototype binary integer readers/writers (readUInt*, readInt*, readBig*, writeUInt*, writeInt*, writeBig*) and slice mutators (copy, fill, write, compare, toJSON).
      • Shard 18 (18_intl.js): Zero-ICU-bloat WinterTC Intl (DateTimeFormat, NumberFormat, Collator, PluralRules, Segmenter, getCanonicalLocales, supportedValuesOf).
      • Bits 19..=28, 30, and 31 (node_builtins::builtin_snippet_for_bit): Pre-fused node:* built-in modules (19 = node:crypto core hashes/HMAC/CSPRNG with lazy PKI getters, 31 = slice:crypto-pki PKI/KeyObject/Cipheriv/KDF shard pre-fused only when PKI symbols are statically referenced, 20 = node:fs & fs/promises, 21 = node:path, 22 = node:events, 23 = node:os, 24 = node:util, 25 = node:assert, 26 = node:buffer, 27 = node:url, 28 = node:timers, 30 = node:zlib).
      • Bit 29 (19_process_cli.js): WinterTC navigator and location, plus complete process CLI surface (stdout, stderr, stdin, memoryUsage + .rss(), hrtime + .bigint(), uptime, argv0, execArgv, execPath, ppid, emitWarning, on/once/off/emit/listeners/removeListener/removeAllListeners/listenerCount).

3. Native Rust Fast-Path Intrinsics (url_and_usp, SHA-NI, Asymmetric Crypto, DEFLATE/Gzip, AsyncLocalStorage, & In-Memory VFS Slab)

Section titled “3. Native Rust Fast-Path Intrinsics (url_and_usp, SHA-NI, Asymmetric Crypto, DEFLATE/Gzip, AsyncLocalStorage, & In-Memory VFS Slab)”

Implemented in crates/slice-engine/src/intrinsics/, crates/slice-engine/src/runtime/boa_realm.rs, and crates/slice-engine/src/bindings/:

  1. Native Rust WHATWG URL & URLSearchParams Primitives (crates/slice-engine/src/intrinsics/url_and_usp.rs):
  2. Hardware SHA-NI Block Compression (Sha256State::compress_block_sha_ni):
    • Uses Intel/AMD SHA-NI instructions (_mm_sha256rnds2_epu32, _mm_sha256msg1_epu32, _mm_sha256msg2_epu32) with cached AtomicU8 runtime feature detection (sha,sse4.1,ssse3) and automatic fallback to Sha256State::compress_block_soft.
  3. Native ring + x25519-dalek + FIPS-180-4 WebCrypto & node:crypto Suite with Asymmetric Ed25519 / X25519 / ECDSA / RSA & Tenant-Scoped Key Handle Cache (asymmetric_and_keys.rs, symmetric_and_kdf.rs, bindings/crypto.rs):
    • Direct JsArrayBuffer / JsUint8Array zero-copy Rust host functions (__slice_crypto_sha256, __slice_crypto_hmac_sha256, __slice_crypto_digest, __slice_crypto_hmac_sign, __slice_crypto_key_register, __slice_crypto_cipher, __slice_crypto_asym_keygen, __slice_crypto_asym_import, __slice_crypto_asym_sign, __slice_crypto_asym_verify, __slice_crypto_ecdh, __slice_crypto_kdf, __slice_crypto_random_int, __slice_base64_encode, __slice_base64_decode), including zero-allocation unbiased 48-bit bitmask rejection sampling for crypto.randomInt (sample_unbiased_u64_below).
    • Supports symmetric AES-GCM / AES-CBC, runtime asymmetric key generation (Ed25519, RFC 7748 X25519, and ECDSA P-256 / P-384), PKCS#8 / PKCS#1 / SPKI / JWK / raw import & export, Ed25519 / ECDSA / imported 2048-8192-bit RSA (RSASSA-PKCS1-v1_5 & RSA-PSS over SHA-256/SHA-384/SHA-512) signing & verification, and constant-time RFC 7748 X25519 Diffie-Hellman key agreement (crypto.diffieHellman & subtle.deriveBits/deriveKey), while failing closed on unbounded runtime RSA/DSA prime generation.
    • Pre-expanded ring::aead::LessSafeKey, ring::hmac::Key, AesExpandedKey, Ed25519 keypairs, ECDSA (P-256/P-384) keys, RSA key material, and X25519 keys are cached in thread-local CRYPTO_KEY_HANDLE_TABLE (CachedCryptoKeyMaterial) scoped by BOA_ACTIVE_TENANT so repeated cryptographic operations skip key schedule/DER parsing while preventing cross-tenant handle access.
    • KDF operations (PBKDF2, HKDF, scrypt) charge proportional CPU fuel against BOA_FUEL_BUDGET (consume_crypto_kdf_fuel), deterministically trapping hostile iteration/cost parameters with SandboxViolation::CpuFuelExhausted.
  4. Self-Contained RFC 1951 (deflate-raw), RFC 1950 (deflate), & RFC 1952 (gzip) Compression Engine:
    • Implemented in zlib_compress_bytes and zlib_decompress_bytes with LZ77 32 KB sliding-window compression, Stored/Fixed/Dynamic Huffman decompression, Adler-32, and CRC-32 validation, powering both WinterTC CompressionStream / DecompressionStream and node:zlib with zero external crate dependencies.
  5. Zero-Overhead SliceJobExecutor for node:async_hooks (AsyncLocalStorage & AsyncResource):
    • Implemented in SliceJobExecutor and event_loop.rs: when BOA_ALS_ACTIVE is false, promise microtasks execute with zero snapshot overhead; when AsyncLocalStorage is active, SliceJobExecutor and the event loop capture and restore BOA_ALS_SNAP across every await, .then(), Promise.all, setTimeout, setImmediate, queueMicrotask, process.nextTick, and fetch boundary.
  6. Zero-Regex Native Rust SemVer & Utility Scanners:
  7. Thread-Local Inode-Backed VFS & Open FD Slab (BOA_VFS_STATE in bindings/fs/):
    • Ephemeral files, directories, and symlinks (writeFileSync, appendFileSync, mkdirSync, symlinkSync, openSync) are stored in a dense Vec<Option<VfsInode>> slab with typed VfsEntryKind variants (File(Arc<Vec<u8>>), Directory, Symlink(String)), a unified FxHashMap<String, PathEntry> (Present(InodeId) | Tombstone) anchored to cached_normalized_cwd(), a Rust OpenFd descriptor table (fds: Vec<Option<OpenFd>>), and unified per-hop RESOLVE_BENEATH VFS + host symlink/junction resolution (symlink_resolver.rs, MAX_SYMLINK_HOPS = 40) enforcing OCap allow_read/allow_write containment on every intermediate and target hop while maintaining 0 host stat() syscalls on .cas bundles. Open file descriptors survive renameSync, atomic path replacement, and unlinkSync until closeSync, charge signed byte deltas against BOA_KV_MEM_BUDGET, clean up automatically across warm-pool turns (DIRTY_VFS), and fall back transparently to std::fs for unmasked host files.
  8. Lazy On-Demand Host Binding Registration by Category (crates/slice-engine/src/bindings/mod.rs):
    • Cold create_warm_boa_realm() initialization registers only the ultra-core host functions (__slice_console_log, __slice_map_error_stack, __slice_load_builtin, __slice_lazy_prelude, timers, env, SHA-256, Base64, UTF-8), while specialized host bindings (register_http_bridge_host_functions, register_kv_and_sandbox_host_functions, register_semver_and_fast_intrinsics_host_functions, register_wintertc_phase_n3_host_functions, register_async_hooks_host_functions) are registered lazily only when their corresponding shard or built-in module is loaded.
  9. Vendored boa_engine Monomorphic Inline Caching (InlineCache::get_fast), %Promise% 1-Alloc Fast Path, DefineOwnPropertyByName Fast Path, Direct ECMA-404 JSON Fast Paths, & SLICEBC\x01 SourceMap Stack Traces:
    • Zero-Borrow Monomorphic Inline Cache (Own + 1-Hop Prototype), Add-Property Transition IC, Computed Dictionary Access, & Object Literal Fast Path (vendor/boa_engine/src/vm/inline_cache/mod.rs, get/property.rs, set/property.rs, own_property.rs, unique_shape.rs): Caches (mono_shape_id: Cell<u64>, mono_proto_shape_id: Cell<u64>, mono_slot: Cell<Slot>) with boxed cold IcSlowState for $O(1)$ zero-GcRefCell-borrow GetPropertyByName (both own properties and 1-hop prototype methods/getters) and SetPropertyByName replace hits, caches AddTransitionEntry (S_from -> S_to + prototype Shape::id() chain verification, invalidated immediately on UniqueShape::insert_property_transition, change_attributes_transition, and override_internal) for $O(1)$ SetPropertyByName own-property additions in constructors and Object.create factories, accelerates string-keyed dictionary get_by_value and SetPropertyByValue on ordinary/null-prototype objects, and uses PropertyMap::try_fast_define_own_data_property in DefineOwnPropertyByName so object literals ({ key: value }) transition SharedShape slots directly without virtual descriptor dispatch.
    • ECMA-262 %Promise% 1-Allocation Promise.resolve, Zero-GC Settled Await, FastForInState, & Intrinsic Array Species Fast Paths (vendor/boa_engine/src/builtins/promise/mod.rs, await/mod.rs, iterable/mod.rs, array/mod.rs): Constructs fulfilled %Promise% instances directly in 1 GC allocation (0 PromiseCapability records, 0 NativeFunction closures, 0 dynamic VM calls) for primitives and non-thenable ordinary/array objects with unmodified prototype chains, enqueues a direct zero-GC-allocation PromiseJob resuming GeneratorContext by value when awaiting already-settled intrinsic promises without active AsyncLocalStorage (and masks any store entered synchronously afterwards via HostHooks::enter_empty_job_context), iterates ordinary for..in loops via FastForInState with zero ForInIterator / { value, done } GC allocations (preserving non-enumerable own-key prototype shadowing, live property deletion, and mid-loop mutation deoptimization), and bypasses species/constructor dispatch and element-by-element descriptor insertion on unmodified intrinsic Array methods (slice, map, filter, Object.keys).
    • Direct Rust JSON::parse_ecma404 & Json::try_fast_stringify Fast Paths (vendor/boa_engine/src/builtins/json/mod.rs): JSON::parse_ecma404 runs an iterative ECMA-404 state-machine parser (MAX_DEPTH = 2048) over Latin1 and Utf16 inputs with 8-byte SWAR unescaped string scanning, exact integer accumulation + fast-float2 float parsing, and per-depth SharedShape / ShapeChain prediction so homogeneous arrays of JSON objects construct directly with populated monomorphic Shape slots. Complementarily, Json::try_fast_stringify serializes ordinary JsObjects and dense Arrays (DenseI32, DenseF64, DenseElement) into a single Vec<u8> buffer using Shape::with_property_keys, 8-byte SWAR ASCII scanning, and ryu_js number formatting when no replacer or space argument is supplied.
    • Lazy Multi-Frame Source-Map Stack Translation & Prelude SourceMap Elision (crates/slice-cas/src/bundler/source_map.rs & vendor/boa_engine/src/script.rs): SLICEBC\x01 serializes user-code bytecode-to-line SourceMap entries inside encode_codeblock / decode_codeblock (omitting internal prelude source-map entries via compile_to_slicebc_with_min_line and pooling short Latin1 identifiers on decode), and Error.prototype.stack lazily invokes __slice_map_error_stack to translate bundled frames via embedded //@sm: / // #slice-source: markers back to file.ts:line:col with 0.00 ns overhead when .stack is not read.
    • Chrome DevTools / Perfetto Execution Tracer (SliceIsolate::export_chrome_trace_json): slice run --trace=<out.json> (or SLICE_TRACE=<out.json>) emits a standard Chrome Trace Event Format (ph: "X") JSON timeline capturing isolate.instantiate, isolate.execute, state.checkpoint, state.restore, and sandbox.eval spans.

  • Binary SLICESNP\x02 Snapshot Codec, Zero-Copy LLInt Execution, & Content-Verified Cache:

    • encode_slicesnp_v2 serializes Tier-0 BytecodeModules (<= 128 KiB ASCII source) into a compact bounds-checked binary snapshot (b"SLICESNP\x02" + flags, bounded MAX_CODEC_DEPTH, retaining legacy SLICESNP{...} JSON fallback).
    • Modules with SLICESNP_FLAG_FLAT_LLINT (ConstNum, ConstStr, ImportCas, AddAssignVar, ConsoleLogVar, MonomorphicForLoop, etc.) execute directly over &[u8] via SnpCursor in SliceIsolate::execute_slicesnp_v2_flat_llint using inline CompactString env_vars keys (<= 24 bytes, 0 heap key allocations) and zero-copy visit_pure_static_exports iteration on imported SLICESNP\x02 .cas blobs.
    • General AST SLICESNP\x02 modules cache decoded Arc<BytecodeModule> entries in SNP_LAST_HIT + SNP_MODULE_CACHE (MAX_SNP_CACHE_ENTRIES = 1024), storing an owned Arc<[u8]> copy of the snapshot payload and verifying exact byte equality on every hit so mimalloc LIFO equal-length buffer reuse never causes ABA collisions.
  • Tier-1 Multi-Blob MappedCasArchive Loader (__slice_cas_require):

    • ActiveCasArchiveGuard binds cas: Option<&MappedCasArchive> onto BOA_ACTIVE_CAS for the active turn (isolating nested Slice.evalSandbox calls and restoring state on Drop/unwind), while eval_cas_require_module resolves sibling/nested .cas blobs, caches CommonJS module.exports for diamond and circular require() graphs, auto-loads required JS prelude shards, and folds resolved module counts into ExecutionMetrics::cas_modules_resolved.
  • Zero Name Heuristics: Every JS/TS function (Stmt::FuncDecl, Expr::ArrowFunc, and function expressions) is analyzed structurally by try_compile_numeric_func regardless of function or parameter names.

  • Unboxed 32-Register Execution ([f64; 32]): Pure numeric functions compile into 8-byte/16-byte NumericOp instructions (LoadConst, Move, BinaryReg, BinaryImm, UnaryReg, MathIntrinsic, Jump, JumpIfFalse, CallSelf1, CallSelf2, LinearRecurrence2, Return). Execution inside NumericFunc::execute operates entirely on unboxed f64 and i64/i32 bitwise values on the CPU stack (256 bytes, fitting in 4 CPU L1 cache lines) with 0 heap allocations and 0 FxHashMap variable lookups.

  • Structural Linear Recurrence Lowering (detect_linear_recurrence_ast): Recognizes any 1-parameter self-recursive function matching if (param <= 1) return ...; return c1 * f(param - 1) + c2 * f(param - 2); (including unweighted Fibonacci-style and weighted Pell/Lucas-style recurrences under any identifier name) and lowers it to NumericOp::LinearRecurrence2, reducing $O(2^n)$ call trees to an $O(n)$ 2-register IEEE-754 f64 loop over exact integer inputs (0 <= n <= 78) while cleanly falling back when out-of-domain arguments occur.

  • Amortized Fuel Metering: Checks (local_steps & 255) == 0 every 256 register instructions (and at every recursive call and loop recurrence), guaranteeing deterministic SandboxViolation::CpuFuelExhausted preemption on infinite numeric loops with < 0.4% branch overhead.