wings-vm manages native artifact loading, coroutine stack pooling, per-process precise GC, capability addressing, multi-worker M:N scheduling, timers, monitors, three-level resource admission, and network serving.
Microprocesses & Capability Addressing
- Zero-Stack Idle Actors & Lock-Free Direct Spawn: An actor borrows a native coroutine stack only while actively executing a handler or suspended across a managed checkpoint; once a handler returns, its stack returns to the worker pool immediately so idle sessions hold zero native stack memory. Actor spawn claims slots through a sharded lock-free
SlotPooland initializes state directly without temporaryStackPoolmmap, coroutine setup, or global scheduler mutexes, and each scheduler tableSlotfits within a single 64-byte cache line (<= 64 B) by deduplicatingmodule/account/capabilitythroughSharedMailboxInnerand storing compactu32actor byte charges. - O(1)
slot + generationAddressing: BothWorkerPidandSchedulerPidencode a table slot index plus a monotonically increasinggeneration. Retiring an actor increments its slot generation so stalepidsends, requests, or monitors fail immediately in O(1) without ABA misdelivery or linear scans. - Exclusive Ownership & Deep-Copy Messaging: At most one scheduler worker owns an actor at any instant; cross-actor messages and replies deep-copy values into the destination heap so microprocesses never share mutable heap pointers.
Coroutine Stack Pool & Chunked Precise GC
- Bounded Reusable Stack Pool (
StackPool/WorkerFibers):- Each fiber slot provides a fixed usable native stack (256 KiB) guarded by hardware
PROT_NONEguard pages, reserved under tenant quotas and net-transferred to the target process account while borrowed. - Normal returns, managed faults, and cancellations recycle coroutine frames cleanly on the worker thread without per-message
mmap/mprotectsyscalls; excess idle stacks remap toPROT_NONEto release physical pages.
- Each fiber slot provides a fixed usable native stack (256 KiB) guarded by hardware
- Direct Fast Path, Register Args, Tail Calls & Suspendable Fibers: Managed handler entries pass up to 3 leading arguments directly in CPU registers, inline small-frame leaf handlers without outer wrapper calls, and compile managed procedures with
CallConv::Tailtrue tail-call optimization. Pure scalar DAG handlers export a zero-contextDirectScalarEntry(single cancellation load and upfront worst-case step deduction), while short heap/effect handlers (self_pidand scalarsend) run directly on the worker thread via a batch-reusedDirectBatchContext; preemptible or effect-yielding handlers run on pooled fibers—sharing identical step budgets, stack-limit checks, and atomic state commit rules. - Bitmap Mark-Sweep GC, Flat Heap Pools & Zero-Copy Multi-Buffer Transfer (
RecordHeap/aot_heap): Non-moving precise bitmap mark-sweep GC (FreeBitsinlineu64fast path) polls step budgets and the unified safepoint control word every 16 roots or heap nodes.RecordHeapstores records, lists, and byte metadata in flat 32-byte inline slots backed by flatOverflowPoolandBufferStorage(with aBufferStorage::Oneinline fast path that eliminatesBox<BufferPool>+Vecallocations for single-buffer actors), lazily allocates GC worklists, shrink-wrappedShadowFramelinks, andByteUndologs, pairs inline ABI allocation/read fast paths with FBIP linear-ownership in-placeBytesupdates and Perceus unique-slot in-placeFormatStringappends, reuses spare byte buffers via a 4-slot inline pool, and shares multi-fieldbytes/strpayloads (>= 1 KiB) zero-copy viaArc<[u8]>while preserving validated UTF-8char_lenmetadata across messages and replies. Elastic heaps grow by doubling up to their declared ceiling under three-level admission, sweep dead leaf temporaries on idle detach, and automatically hibernate when an expanded actor’s mailbox drains to idle (or on explicitSchedulerHandle::hibernate(pid)), shrinking back towardmin_capacityto refund unused quota.
Lock-Free Fast Mailboxes & M:N Scheduler
- Per-Sender FIFO & Explicit Backpressure: Every actor owns a bounded mailbox; full queues reject immediately with an explicit
mailbox_fullerror rather than silently dropping messages or growing memory without bound. - Segmented Lock-Free Mailboxes, 64B Envelopes & Intrusive Ready Lists:
Schedulermaintains#[repr(C, align(64))]cache-line-partitionedSharedMailboxInnerblocks (<= 448 BviaAlign64barriers with colocatedexec_locked+ActorExecState) backed by lazy 8-slot exact-sized mailbox segments (seg0stored inline so small mailboxes avoid a segment table allocation), 64-byteEnvelopeslots with 8-byteReplyand Arc-free charges, zero-allocation intrusiveWorkerRunQueueready lists, per-worker cache-padded completion/failure counters, TTAS exponential spin backoff (Backoff), lazily allocated owner-local prefetch stashes that elastically reclaim backing memory on idle/retire, per-worker wake bitmasks (WorkerWakeHub), Go/Tokio-style bounded per-worker LIFO slots (MAX_LIFO_STREAK = 3) for same-worker actor wakeups, sticky worker affinity with zero-allocation highest-load batch work-stealing (up to half of a congested peer queue, capped at 16), reply-before-cleanup external response publication, and bounded backlog batching (up to 32 fast messages when no sibling work is queued), while interleaving short direct/reusable claims 1-for-1 with suspended long-running fibers. - Preemptive Fairness & Shared Timer:
- Compiled code tracks effective step budgets in registers and polls a single 32-bit atomic
ScalarContext::controlword (CONTROL_CANCELLED | CONTROL_YIELD_REQUESTED) at branches, loop backedges, and calls while a single shared scheduler timer thread (SharedDeadlineTimerwith cache-line-isolated per-worker slots) atomically mirrors quantum-expiry yield requests into the active control word;send_aftertimers run through a sharded 64-slot Hashed Timing Wheel (TimerHub) with O(1) per-actor exit cancellation, monitors use an indexedMonitorArenafor O(k) exit notification, and in-VMaskrequests, cancellations, replies, and timeouts run through a shardedRequestHub+FastSlotfast path off the global scheduler lock. - Compute-heavy or infinite-loop handlers suspend their live stack at the next safepoint and re-queue at the tail of the ready list so sibling actors on the same worker continue making progress.
- Compiled code tracks effective step budgets in registers and polls a single 32-bit atomic
- Native OS Event Parking: Idle workers park on platform event primitives (
kqueueon macOS,epoll+eventfdon Linux) until woken by new work or the earliest timer deadline (.asktimeouts andsend_aftertimers), avoiding busy-spin CPU burn.
Fault Isolation, Monitors & Bounded Supervision
- Managed Fault Containment: Integer overflow, division by zero, slice bounds violations, step exhaustion, heap quota errors, and stack-limit faults trap into
ExecutionFault, roll back uncommitted state mutations, record alast_exitdiagnostic snapshot, and leave peer actors unaffected. - Language-Level
monitor& HostSupervisor:- Actors subscribe to child exit notifications via
monitor(child_pid, callback)to implement stateful recovery policies inwings-lang(seeexamples/session-service.wings). - Host Rust APIs also provide
ScalarSupervisorandSchedulerSupervisorforone-for-onerestarts bounded by sliding-window restart intensity limits.
- Actors subscribe to child exit notifications via
Three-Level Resource Ledger & Network Serving
- 3-Level, 4-Dimension Ledger (
Resources) & Zero-RMW Global Allocator (WingsAllocator): Tracksbytes,processes,messages, andrequestsacross aVM -> Tenant -> Processhierarchy backed by compact 128-byteAccountNodes. Reservations charge atomically prior to allocation, roll back immediately if any ancestor exceeds quota, update only non-shared ancestors on transfer, and release automatically onDrop.WingsAllocatoravoids hot-path global atomic RMWs while tracking global Rust heap requested/usable bytes, size-class fragmentation, peak usable bytes, optional hard global heap limits, and kernel process footprint (ri_phys_footprinton macOS,/proc/self/smaps_rollupPsson Linux) vianative_memory_ledger. - CLI Entry Points:
wings-vm run --trusted <artifact-dir>: Single-actorstdioJSON Lines runner.wings-vm serve --trusted <dir> [--workers N] [--tcp ADDR | --http ADDR]: Serves single-actor artifacts or multi-actor bundles (bundle.json) using a multi-reactor shard pool (1..=16nativekqueue/epollloops matching scheduler concurrency, generation-tagged connection slabs, read-cursor framing, zero-allocation borrowedJsonScratcharena decoding,O(pending)in-flight reply polling with per-shard targetedReplyTablewakeups, andsigactionself-pipe), bounded connection/body limits, automatic JSON-to-struct/str/bytes/[int]marshaling, and streaming JSON-RPC responses.
Observability, Graceful Drain & Capability Hostcalls
- Unified Telemetry & Structured Fault Log:
SchedulerHandle::metrics()returns a read-onlySchedulerMetricssnapshot (workers, draining/closed state, live/active actors, queued/completed/failed/rejected messages, fault count,WingsAllocatorrequested/usable/fragmentation bytes, and process RSS) with Prometheus text export (to_prometheus_text()). Optional lock contention observation supports power-of-two timing sampling (SchedulerConfig::lock_statistics_sample_stride) to skipInstant::now()on unsampled acquisitions. Managed actor faults also append structuredFaultReportrecords into a bounded 64-entry ring buffer (recent_faults()/drain_faults()).wings-vm serve --httpexposesGET /healthz(503while draining),GET /metrics,GET /metrics/prometheus, andGET /faults. - Graceful Drain (
begin_drain/drain): Entering drain mode rejects new ingress immediately while allowing queued messages and in-flight requests to finish within a bounded timeout viaCondvarnotification (no polling loops) before shutdown.wings-vm serve --tcpand--httpwireSIGTERM/SIGINThandlers directly into this drain state machine. - Capability-Based Hostcalls (
HostCapabilityRegistry): Actors invoke host-provided capabilities viahostcall(capability, payload, timeout_ms) -> bytes(EFFECT_HOSTCALL). Each actor starts with an emptyCapabilityGrant(least privilege) and must be explicitly granted capabilities viaSchedulerHandle::grant_actor_capability. Hostcalls execute outside the scheduler lock under three-level resource accounting, payload size bounds, timeout, and cancellation checks, and return managedbyteson the caller’sAotHeap(with built-inclock.now_ms).