byteflow-actors
Byteflow is a small, embeddable flow runtime for Rust: register-based bytecode, lightweight flows, Atomic Hop messaging (Value::Message only on Send), cooperative scheduling, and an OTP-style supervisor (one-for-one / one-for-all / rest-for-one) — without a separate scripting language.
You assemble programs with Program and Fn in host Rust. The host owns I/O; Byteflow owns cheap concurrency.
Package name:
byteflow-actorson crates.io
Rust import:use byteflow::...(the library crate is namedbyteflow)
Why this exists
Use Byteflow when you need many isolated units of work that talk through messages, share a handful of OS threads, and can fail without taking the worker down:
- plugin / rule / workflow engines inside a larger binary
- simulations and game logic (not the render loop)
- sandboxed “virtual processes” with a host-defined FFI table
It is not a Tokio replacement, not a distributed cluster, and not a JVM.
Module ABI
encode writes the oldest header that can hold the constants. v5 has neither lists, maps, nor records. v6 adds lists (wire tag 9). v7 adds maps (wire tag 10). v8 adds positional records (wire tag 11, opcodes RecordPack 0x8A, RecordGet 0x8B, RecordLen 0x8C). Decode accepts all four. A module without a record stays on v5, v6, or v7. Lists, maps, and records each hold at most 256 items. See byteflow/docs/beam-mapping.md.
Install
[]
= "0.9.22"
use ;
CLI (same package):
cargo install byteflow-actors
byteflow demo ping-pong
Quick start
use ;
Collecting a result without committing the thread
join() blocks until the flow finishes, which is right for a main that
has nothing else to do. Anything with a deadline — a control loop, a
watchdog, a test harness — picks its own bound instead:
| Call | Waits | While the flow is still running |
|---|---|---|
try_join() |
never | None |
join_timeout(d) / join_deadline(t) |
up to the bound | None |
join() |
unbounded | (blocks) |
use ;
use Duration;
The bounds are anchored on an absolute Instant, so a spurious condvar
wakeup cannot silently restart the budget. And a flow destroyed before
producing an outcome (shutdown does not drain suspended flows) wakes its
joiner with a failure rather than leaving it parked forever — see
docs/error-model.md.
Std natives (print, now_ms, make_msg, …)
Stable indices: print = 0, now_ms = 1, make_msg = 2 (3-arg: request_id, tag, payload; sender stamped on Send/Ask), msg_* = 3–6, msg_reply_cap = 7.
use ;
Or std_natives() → (NativeTable, HashMap<name, index>) so host registration stays aligned with bytecode.
Messaging (Atomic Hop)
Every Send carries one Value::Message envelope (scalars trap):
cargo run --example ping_pong
cargo run --example atomic_actors
# optional scheduler logs on stderr:
# BYTEFLOW_LOG=info cargo run --example atomic_actors
Hop-heavy code uses helpers such as hop_fresh, send, receive, and ask on Fn — see examples/ping_pong.rs (assembles Program + runs Runtime via use byteflow::{...}).
Built-in test helpers: byteflow::samples::{ping_pong, atomic_actors, named_service, …}.
Architecture
| Layer | Responsibility |
|---|---|
| Bytecode | ISA, Program / Fn, BFV0 (.bf) encode/decode, static verify |
| VM | One flow: registers, call stack, cooperative slice (min(quantum, CPU quota)), CallNative (gated) |
| Scheduler | M:N workers, bounded FIFO mailboxes (park/wake), CapTable, quotas, hierarchical timer wheel, one table per flow, supervisor |
JIT (feature jit) |
Trace JIT for hot loops via Cranelift |
| Facade | Public API + std natives + samples + byteflow CLI |
Flow lifecycle (sketch):
- Worker runs at most
min(quantum, remaining CPU quota)instructions (default quantum 10 000). Yield/ budget → run queue (stealable). CPU quota exhaustion fails the flow (QuotaError).Sleep→ timer wheel → injector. The thread waits until the next exact deadline.- Empty
Receive→ flow parks inside its mailbox; the next Atomic Hop wakes under the same lock (no lost wakeup). Fault/Trap→FlowOutcome::Failed→ supervisor (Always/OnFailure/Never; default intensity 3 / 5s).
join() and its bounded forms are for the embedder’s native thread only —
workers never block on them.
Untrusted .bf files go through Opcode::from_u8 + verify before
execution. The verifier settles what is a property of the chunk (jump
targets, constant/function indices, arity ≤ num_registers); the VM checks
what depends on runtime state (register bounds, index overflow, types,
division, call depth) and turns each into a Fault on that one flow — see
docs/vm-safety.md.
CLI
byteflow demo [ping-pong|atomic|selective|selective-after|match-eq|exit|dict|ask|ask-timeout|server-loop|monitor|alive|add]
byteflow pack <demo> <out.bf>
byteflow verify <file.bf>
byteflow disasm <file.bf>
byteflow run <file.bf> [function]
run and hop demos attach the std native table (print, now_ms, make_msg, msg_*).
Safety & design notes
#- Default runtime dependency:
getrandomforCapId(OS CSPRNG). Optionalfeature = "jit"adds Cranelift. - Flow panics are caught at the worker boundary so one bad flow cannot kill the OS thread.
- Malformed bytecode is a
Faulton one flow, never a panic on the thread that spawned it (seedocs/vm-safety.md). - Register indices are never computed with plain
u8arithmetic — no “panics in debug, silently wraps in release” divergence. - Native functions must not block — they run inline on a worker.
- Host APIs return
Result(SpawnError/RuntimeError) — nounwrap/expect/unwrap_or*anywhere (seedocs/error-model.md). - Blocking APIs are bounded by choice:
try_join/join_timeout/join_deadline, and an abandoned flow wakes its joiner instead of hanging it. - Values today:
Unit | Bool | Int | Float | Pid | Message | Cap | Str | Bytes | List | Map | Record. - Atomic Hop: only
Value::Messagemay crossSend. - FlowCap (ABI v5): 128-bit CSPRNG
CapId; holder + rights resolution;Cap::attenuateis the only grant path (Fn::delegate, confined spawn). - Natives (S7):
CALL_NATIVEis gated byCapRights::NATIVE+NativeMaskbefore the table is indexed. - Quotas: per-flow CPU / heap / spawn-send buckets via
QuotaConfig(RuntimeConfig::quota). Default ispermissive;sandboxis the isolation starting point.Str/Bytesregister stores charge heap with release-on-overwrite (delta accounting). Process-wide ceiling:RuntimeConfig::max_runtime_bytes+MemoryBudget/HeapStr. Distinct from the scheduler quantum. - Registry: bytecode
register_name/whereis— lookup returns a SEND Cap, never a FlowId. make_msg: 3-arg (request_id,tag,payload);senderis stamped only onSend/Ask.- Security: authenticated hop sender + FlowCap + Phase 3–5 gates
(quotas, integrity fingerprint, relation caps,
with_attested).Jump/Branchare bounds-checked in every config;verifyalso refuses a jump into another function, a fall-through onto the next function's body, and aCall/Spawn/CallNative/StartChildregister window that reaches past the calling frame's register file. Seedocs/security.mdanddocs/vm-safety.md.
Status (v0.9.22)
Included: register ISA + Program/Fn assembler, BFV0 (ABI v5, ABI v6 when a constant contains a list, ABI v7 when a constant contains a map, ABI v8 when a constant contains a record: 128-bit CapId, nested Message.payload, lists, maps, and records of at most 256 elements, map keys Int or Str), verifier (TrustLevel::Untrusted rejects Cap/Pid/Message in the constant pool), per-flow VM, M:N scheduler, bounded mailboxes (safe growable ring; MailboxConfig: 256 hops + 4 MiB / Reject by default), Atomic Hop, FlowCap holder model, Cap::attenuate / Opcode::Delegate, NativeMask gate on CALL_NATIVE, per-flow quotas (QuotaConfig::permissive / sandbox), bytecode register_name / whereis (SEND Cap, never FlowId), host Runtime::send on the same hop auth path (sender = 0, reply_cap = NONE), LINK/MONITOR/ADMIN, Fn::spawn_confined, trap_exit (Opcode::SetTrapExit / Runtime::set_trap_exit), ReceiveMatchKind (payload wire-tag selective receive), ReceiveMatchEq (tag + Int payload), ReceiveMatchValue (tag + any Value), ReceiveMatch*Timeout (BEAM after), IsAlive, ExitSignal (BEAM exit/2, needs LINK), process dictionary (DictPut / DictGet / DictErase; Int keys, scalars plus Str / Bytes), StartSupervisor (0x72: one-for-one / one-for-all / rest-for-one), StartChild (child of that supervisor, or of the host supervisor that started this flow), SetRestartPolicy (flow-local restart at exit), MulImm / EqImm / LeImm, integer BitAnd / BitOr / BitXor / BitNot / Shl / Shr, HostAwait (several in-flight host ops per flow; completion is a TAG_SYS_AWAIT hop; max_host_awaits), host-side bytecode integrity fingerprint (fingerprint_bf / decode_attested / Runtime::with_attested), Phase 5 relation caps (max_links / max_monitors / max_registry_names), 3-arg make_msg, monitors / links / registry (link insert re-checks liveness; teardown is O(degree)), WAITING_SEND, AskTimeout, RuntimeConfig.max_flows / max_ask_waits, OTP supervisor strategies, OutputSink for print, std natives, CLI, examples, fail-closed error model, optional trace JIT (feature = "jit"), in-house stress suite (mailbox / decode / CapTable), Criterion benches, hermetic CI (cargo fetch then --locked --offline).
Also included: MapPack / MapGet / MapLen; ReceiveMatchCmp (tag plus Eq / Lt / Le on an Int payload — a miss stays queued); one named table per flow (TableOpen / TableGet / TablePut, RECV reads, SEND writes, gone when the owner exits); remote hop frames (encode_frame / decode_frame / Runtime::deliver_frame — the envelope is a .bf value, the header sender is the envelope sender, and a Cap or Pid stays on the node); reference host transport (transport module, docs/remote-transport.md, examples/remote_hop_tcp.rs); sleep and receive timeouts on a hierarchical timing wheel.
Not yet: a cluster protocol (the host still owns the socket) and BEAM ETS (the table is per owner, not a global store). Selective receive covers tag, payload wire-tag (0..=10, including List and Map), Int equality, an integer comparison, structural payload equality, and after. No tuples.
Design guides: docs/atomic-hop.md ·
docs/beam-mapping.md ·
docs/lifecycle.md ·
docs/mailbox.md ·
docs/properties.md ·
docs/host-await.md ·
docs/remote-transport.md ·
docs/vm-safety.md ·
docs/error-model.md ·
docs/untrusted.md ·
docs/security.md ·
docs/production-embedding.md ·
docs/audit-checklist.md
See CHANGELOG.md.
Links
- Repository: github.com/mchael158/byteflow-actors
- Docs: docs.rs/byteflow-actors
- License: MIT OR Apache-2.0