Managed Microprocess Runtime

O(1) slot+generation capability handles, pooled coroutine stacks, chunked precise GC, lock-free mailboxes, M:N preemption, and 3-tier admission.

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 SlotPool and initializes state directly without temporary StackPool mmap, coroutine setup, or global scheduler mutexes, and each scheduler table Slot fits within a single 64-byte cache line (<= 64 B) by deduplicating module/account/capability through SharedMailboxInner and storing compact u32 actor byte charges.
  • O(1) slot + generation Addressing: Both WorkerPid and SchedulerPid encode a table slot index plus a monotonically increasing generation. Retiring an actor increments its slot generation so stale pid sends, 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_NONE guard 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/mprotect syscalls; excess idle stacks remap to PROT_NONE to release physical pages.
  • 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::Tail true tail-call optimization. Pure scalar DAG handlers export a zero-context DirectScalarEntry (single cancellation load and upfront worst-case step deduction), while short heap/effect handlers (self_pid and scalar send) run directly on the worker thread via a batch-reused DirectBatchContext; 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 (FreeBits inline u64 fast path) polls step budgets and the unified safepoint control word every 16 roots or heap nodes. RecordHeap stores records, lists, and byte metadata in flat 32-byte inline slots backed by flat OverflowPool and BufferStorage (with a BufferStorage::One inline fast path that eliminates Box<BufferPool> + Vec allocations for single-buffer actors), lazily allocates GC worklists, shrink-wrapped ShadowFrame links, and ByteUndo logs, pairs inline ABI allocation/read fast paths with FBIP linear-ownership in-place Bytes updates and Perceus unique-slot in-place FormatString appends, reuses spare byte buffers via a 4-slot inline pool, and shares multi-field bytes/str payloads (>= 1 KiB) zero-copy via Arc<[u8]> while preserving validated UTF-8 char_len metadata 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 explicit SchedulerHandle::hibernate(pid)), shrinking back toward min_capacity to 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_full error rather than silently dropping messages or growing memory without bound.
  • Segmented Lock-Free Mailboxes, 64B Envelopes & Intrusive Ready Lists: Scheduler maintains #[repr(C, align(64))] cache-line-partitioned SharedMailboxInner blocks (<= 448 B via Align64 barriers with colocated exec_locked + ActorExecState) backed by lazy 8-slot exact-sized mailbox segments (seg0 stored inline so small mailboxes avoid a segment table allocation), 64-byte Envelope slots with 8-byte Reply and Arc-free charges, zero-allocation intrusive WorkerRunQueue ready 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::control word (CONTROL_CANCELLED | CONTROL_YIELD_REQUESTED) at branches, loop backedges, and calls while a single shared scheduler timer thread (SharedDeadlineTimer with cache-line-isolated per-worker slots) atomically mirrors quantum-expiry yield requests into the active control word; send_after timers run through a sharded 64-slot Hashed Timing Wheel (TimerHub) with O(1) per-actor exit cancellation, monitors use an indexed MonitorArena for O(k) exit notification, and in-VM ask requests, cancellations, replies, and timeouts run through a sharded RequestHub + FastSlot fast 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.
  • Native OS Event Parking: Idle workers park on platform event primitives (kqueue on macOS, epoll + eventfd on Linux) until woken by new work or the earliest timer deadline (.ask timeouts and send_after timers), 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 a last_exit diagnostic snapshot, and leave peer actors unaffected.
  • Language-Level monitor & Host Supervisor:
    • Actors subscribe to child exit notifications via monitor(child_pid, callback) to implement stateful recovery policies in wings-lang (see examples/session-service.wings).
    • Host Rust APIs also provide ScalarSupervisor and SchedulerSupervisor for one-for-one restarts bounded by sliding-window restart intensity limits.

Three-Level Resource Ledger & Network Serving

  • 3-Level, 4-Dimension Ledger (Resources) & Zero-RMW Global Allocator (WingsAllocator): Tracks bytes, processes, messages, and requests across a VM -> Tenant -> Process hierarchy backed by compact 128-byte AccountNodes. Reservations charge atomically prior to allocation, roll back immediately if any ancestor exceeds quota, update only non-shared ancestors on transfer, and release automatically on Drop. WingsAllocator avoids 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_footprint on macOS, /proc/self/smaps_rollup Pss on Linux) via native_memory_ledger.
  • CLI Entry Points:
    • wings-vm run --trusted <artifact-dir>: Single-actor stdio JSON 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..=16 native kqueue / epoll loops matching scheduler concurrency, generation-tagged connection slabs, read-cursor framing, zero-allocation borrowed JsonScratch arena decoding, O(pending) in-flight reply polling with per-shard targeted ReplyTable wakeups, and sigaction self-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-only SchedulerMetrics snapshot (workers, draining/closed state, live/active actors, queued/completed/failed/rejected messages, fault count, WingsAllocator requested/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 skip Instant::now() on unsampled acquisitions. Managed actor faults also append structured FaultReport records into a bounded 64-entry ring buffer (recent_faults() / drain_faults()). wings-vm serve --http exposes GET /healthz (503 while draining), GET /metrics, GET /metrics/prometheus, and GET /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 via Condvar notification (no polling loops) before shutdown. wings-vm serve --tcp and --http wire SIGTERM / SIGINT handlers directly into this drain state machine.
  • Capability-Based Hostcalls (HostCapabilityRegistry): Actors invoke host-provided capabilities via hostcall(capability, payload, timeout_ms) -> bytes (EFFECT_HOSTCALL). Each actor starts with an empty CapabilityGrant (least privilege) and must be explicitly granted capabilities via SchedulerHandle::grant_actor_capability. Hostcalls execute outside the scheduler lock under three-level resource accounting, payload size bounds, timeout, and cancellation checks, and return managed bytes on the caller’s AotHeap (with built-in clock.now_ms).