Serverless Edge KV, AI Agent "Code Mode" Sandbox, Time-Travel Testing & MCP Server
This document covers Slice’s 16-way sharded in-memory Edge KV (Slice.kv), zero-downtime multi-tenant .cas hot-swapping (--tenant-dir), SplitMix64 deterministic replay (--deterministic), AI Agent “Code Mode” (Slice.evalSandbox, < 5 us Slice.checkpoint/Slice.restore), the Time-Travel slice test runner, and the built-in JSON-RPC 2.0 Model Context Protocol server (slice mcp).
1. Multi-Tenant Serverless & Edge KV Primitives (Slice.kv, --tenant-dir, --deterministic)
Section titled “1. Multi-Tenant Serverless & Edge KV Primitives (Slice.kv, --tenant-dir, --deterministic)”- 16-Way Sharded In-Memory Edge KV & Atomic Counter Slab (
EDGE_KV_SLAB):- Backed by
OnceLock<[Mutex<FxHashMap<(String, String), KvEntry>>; 16]>partitioned by(tenant_id, key)usingFxHasherlow 4 bits (0..15) for lock-free multi-core scaling across--workers=N(< 1 us/op; seetests/reports/latest.md). - Supports
Slice.kv.get(key),Slice.kv.set(key, val, ttlMs),Slice.kv.del(key), and atomic 64-bitSlice.kv.incr(key, delta). Every write computes its exact signed retained-byte delta (new_bytes - old_bytes) atomically inside the shard lock (edge_kv_set_checked/edge_kv_incr_checked), reclaiming expired keys under memory pressure and adjustingBOA_KV_MEM_BUDGET(try_adjust_isolate_memory_ctx) while immediately preempting guest loops with uncatchableSandboxViolation::MemoryCeilingExceededif a tenant exceeds its memory ceiling.
- Backed by
- Multi-Tenant Dynamic
.casRouter & Zero-Downtime Atomic Hot-Swap (resolve_tenant_bytecode_hotswap):- When
slice serve --tenant-dir=<dir>is active, each worker resolvesX-Slice-Tenant: <id>or URL prefix/t/<id>/...to<dir>/<id>.cas(falling back to<dir>/default.cas). - Thread-local
TENANT_CAS_CACHEtracks(mtime_ns, file_len, Arc<Vec<u8>>). When a.casfile is atomically replaced on disk, the worker automatically maps the new.casarchive and pre-warms its__slice_rcclosure with zero dropped TCP connections.
- When
- Opt-In Deterministic Replay Mode (
SliceIsolate::set_deterministic_seed):- When
--deterministic=<seed>is passed (Noneby default =0.00 nsoverhead),Math.random(),Date.now(),performance.now(),crypto.randomUUID(),crypto.randomInt(), andcrypto.getRandomValues()route through a deterministic SplitMix64 PRNG (splitmix64_next_f64/sample_unbiased_u64_below) and a monotonic virtual clock (1700000000000 + tick_ms).
- When
2. AI Agent “Code Mode” Sandbox, < 5 us VFS/KV Checkpoints, & Native MCP Server (slice mcp)
Section titled “2. AI Agent “Code Mode” Sandbox, < 5 us VFS/KV Checkpoints, & Native MCP Server (slice mcp)”+---------------------------------------------------------------------------------------------------+| AI Agent "Code Mode" & Native MCP Architecture || || Claude Code / Cursor / LLM Agent || | JSON-RPC 2.0 over stdio (`slice mcp [--audit-egress=SECRET]`) || v || +---------------------------------------------------------------------------------------------+ || | Parent Orchestrator Isolate (`mcp-agent-host` or `slice run tot_agent.ts`) | || | - `Slice.checkpoint()` -> Snapshots `BOA_VFS_STATE` + Tenant `EDGE_KV_SLAB` in < 5 us | || | - `Slice.evalSandbox(code, opts)` -> Saves Parent TLS -> Spawns Attenuated Child Isolate | || | | | || | +---> [Child SliceIsolate] | || | * Capabilities = Parent Caps INTERSECT Child `opts.allowRead` / `allowWrite` | || | * Fuel & Memory = min(Parent Remaining, Child `opts.fuel` / `memoryBytes`) | || | * Egress Guard = Scans stdout & returnValue for raw/base64/base64url secrets | || | - If `!branch.ok` -> `Slice.restore(snapId)` rolls back VFS + KV state in < 5 us! | || +---------------------------------------------------------------------------------------------+ |+---------------------------------------------------------------------------------------------------+- Dynamic Sub-Isolate Spawning with Strict Capability Attenuation (
SliceIsolate::eval_sandbox):- An orchestrator script or MCP host can evaluate untrusted AI-generated TypeScript/JavaScript strings via
Slice.evalSandbox(code, opts). - Child
allowed_read_prefixes,allowed_write_prefixes, andallowed_net_hostsare strictly intersected with the parent isolate’sCapabilityToken(a child can never escalate privileges beyond its parent), and childfuel_consumedis deducted directly from the parent isolate’s remaining fuel budget. - Inline source directives (
// @slice-allow-*,// @slice-fuel,// @slice-memory-kb) insideSlice.evalSandboxandslice mcp(slice_eval_ts) are ignored for capabilities and limits, and default CLI runs (trust_directives = false) enforce monotonic attenuation inResolvedExecutionConfig::apply_inline_directivesso AI-generated entrypoints cannot self-grant permissions. - Re-entrant
SavedIsolateContextGuarduses zero-allocationstd::mem::takeswaps forBOA_ACTIVE_TENANTandBOA_ENV_MAP,Option<SavedEventLoopSnapshot>fast-path skipping when no parent async timers/fetches are pending, and a per-subsystemBOA_DIRTY_SUBSYSTEMSbitmask (DIRTY_EVENT_LOOP,DIRTY_ALS,DIRTY_FETCH_MOCK,DIRTY_WEBSOCKET,DIRTY_SOCKETS,DIRTY_WORKERS,DIRTY_WASM), whilecompile_source_for_sandbox_evalcaches compiled bytecode in a 64-entry thread-localSANDBOX_EVAL_BC_CACHE(FxHashMap<u64, Rc<[u8]>>) so nested sub-isolates execute in microseconds with zero TLS interference.
- An orchestrator script or MCP host can evaluate untrusted AI-generated TypeScript/JavaScript strings via
- Sub-5us VFS & KV Checkpointing (
Slice.checkpoint()&Slice.restore(id)):checkpoint_tenant_statecaptures a point-in-timeArcCoW snapshot (VfsSnapshot) of the thread-local inode-backednode:fsVFS & open FD slab (BOA_VFS_STATE) and every entry belonging totenant_idacross all 16 shards ofEDGE_KV_SLAB, recording exactstate_bytesand returning a monotonicu64snapshot ID.restore_tenant_state_checkedrestores the VFS slab, open FD cursors, the tenant’s sharded KV keys, and the signedBOA_KV_MEM_BUDGETdelta (snap.state_bytes - pre_restore_bytes) in< 5 microseconds(skipping empty shard hash-table probes whenshard_snap.is_none()), andprewarm_boa_bundlepurgesCHECKPOINT_SLABafter pre-warming so warm pools start with zero orphaned snapshots.
- Time-Travel
slice testRunner (slice:test):- Implemented in
crates/slice-cli/src/commands/test_runner.rsandslice:test(describe,test,it,expect). - Automatically checkpoints and restores VFS + KV state around every
test()block in< 5 us, warps virtual timer deadlines in0 ns, and provides first-class OCap security matchers (.toViolate(),.toStayWithinFuel(),.toStayWithinMemory()).
- Implemented in
- Built-In Model Context Protocol Server (
slice mcp) & Interactive REPL (slice repl):- Implemented in
crates/slice-cli/src/diagnostics/mcp.rsandcrates/slice-cli/src/diagnostics/repl.rs, exposingslice_eval_ts,slice_kv_get,slice_kv_set, andslice_checkpointover JSON-RPC 2.0stdio, with monotonic session-wide--fuel,--memory, and--max-checkpointsenforcement across bothslice_eval_tsandslice_checkpoint.
- Implemented in