byteflow/lib.rs
1//! Byteflow — embeddable **flow** runtime (package **`byteflow-actors`**).
2//!
3//! Not a language, not Tokio, not a JVM. You assemble register bytecode in
4//! host Rust ([`Program`] / [`Fn`]), spawn many lightweight **flows** on an M:N
5//! scheduler, and they talk through mailboxes with a strict hop protocol.
6//!
7//! Dependents write `use byteflow::...` (crate name) while crates.io lists
8//! the package as [`byteflow-actors`](https://crates.io/crates/byteflow-actors).
9//!
10//! # What you get
11//!
12//! | Piece | Role |
13//! |-------|------|
14//! | [`Program`] / [`Fn`] / [`Opcode`] | Assemble `.bf` programs in Rust (no source language) |
15//! | [`verify`] | Static gate for untrusted chunks — mandatory, not advisory |
16//! | [`Vm`] / [`VmResult`] | Per-flow register interpreter; effects hand off to the scheduler |
17//! | [`Runtime`] | Worker pool + timer; spawn / join / host [`Runtime::send`] |
18//! | [`FlowHandle`] | Collect an outcome: blocking [`FlowHandle::join`] or a bounded form |
19//! | [`Value::Message`] | **Atomic Hop** envelope — the only value allowed on `Send` / `Ask` |
20//! | [`Value::Cap`] | **FlowCap** address for bytecode delivery (`Send` / `Ask` targets) |
21//! | [`Cap`] / [`CapRights`] / [`NativeMask`] | Holder + rights; [`Cap::attenuate`] is the only grant path |
22//! | [`QuotaConfig`] / [`FlowQuota`] | Per-flow CPU / heap / spawn-send budgets |
23//! | [`Supervisor`] | OTP strategies (`OneForOne` / `OneForAll` / `RestForOne`) |
24//! | [`std_native_table`] | `print`, `now_ms`, `make_msg` (3-arg), `msg_*`, `msg_reply_cap` |
25//!
26//! # Atomic Hop (messaging contract)
27//!
28//! Every bytecode `Send` / `Ask` carries exactly one [`Message`]:
29//!
30//! ```text
31//! Message { sender, reply_cap, request_id, tag, payload }
32//! ```
33//!
34//! - Bare `Int` / `Pid` / `Str` on `Send` → trap / [`SendError::NotAHop`]
35//! - Scheduler **stamps** `sender` (authenticated origin) and attaches
36//! `reply_cap` (stable SEND-only Cap back to the caller, reused per pair)
37//! - Reply with [`std_native_table`]'s `msg_reply_cap` — **not** `msg_sender`
38//! (`Pid` is identity, not an address)
39//!
40//! Also: selective receive (`ReceiveMatch` / `ReceiveMatchCorr` /
41//! `ReceiveMatchKind` / `ReceiveMatchEq` / `ReceiveMatchValue` /
42//! `ReceiveMatch*Timeout` for BEAM `after`), `IsAlive`, `ExitSignal`
43//! (`exit/2`), process dictionary (`DictPut` / `DictGet` / `DictErase`;
44//! `Int` keys, scalars plus `Str` / `Bytes`), `StartSupervisor` /
45//! `StartChild`, `Ask` / `AskTimeout`, [`Fn::fresh_request_id`].
46//!
47//! # FlowCap (addressing)
48//!
49//! | Value | Use |
50//! |-------|-----|
51//! | [`Value::Cap`] | Target of `Send` / `Ask`; from `SelfPid`, `Spawn`, or `reply_cap` |
52//! | [`Value::Pid`] | Identity inside a delivered hop (`msg_sender`) |
53//!
54//! Host [`Runtime::send`] still takes [`FlowId`] (trusted embedder path)
55//! and is stamped `sender = 0` / `reply_cap = NONE`.
56//!
57//! Named discovery: [`Fn::register_name`] / [`Fn::whereis`] — `whereis`
58//! returns a SEND Cap for the caller, never a raw FlowId.
59//!
60//! Caps resolve only for the **holder** with sufficient rights. Derive a
61//! weaker grant with [`Fn::delegate`] / [`Cap::attenuate`] — never by
62//! copying a `CapId`. Host spawn is `ROOT`; bytecode [`Fn::spawn_confined`]
63//! starts at `NONE`.
64//!
65//! # Values
66//!
67//! Scalars are ABI v5: `Unit | Bool | Int | Float | Pid | Message | Cap | Str | Bytes`.
68//! A [`Value::List`] selects v6, a [`Value::Map`] selects v7, and a
69//! [`Value::Record`] selects v8. [`encode`] writes the oldest of those
70//! headers that can hold the constant pool, including a value nested in a
71//! list, map, record, or message. [`decode`] accepts v5 through v8.
72//!
73//! `CapId` is a 128-bit CSPRNG token. `Message.payload` is a nested
74//! [`Value`]. `Str` / `Bytes` are `Arc`-backed for cheap register/mailbox
75//! clones. They are **not** Atomic Hops by themselves.
76//!
77//! # Quick start — scalar
78//!
79//! ```
80//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
81//! use byteflow::{Program, FlowOutcome, Runtime, Value};
82//!
83//! let mut program = Program::new("demo");
84//! program.function("main", 0, |f| {
85//! let a = f.load_i32(41);
86//! let b = f.load_i32(1);
87//! let sum = f.add(a, b);
88//! f.return_(sum);
89//! });
90//!
91//! let rt = Runtime::new(program.build())?;
92//! let outcome = rt.spawn(0, &[])?.join();
93//! rt.shutdown();
94//! assert!(matches!(outcome, FlowOutcome::Completed(Value::Int(42))));
95//! # Ok(())
96//! # }
97//! ```
98//!
99//! # Quick start — Atomic Hop (ping-pong)
100//!
101//! Assemble with [`Program`] / [`Fn`], then run on [`Runtime`]:
102//!
103//! ```
104//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
105//! use byteflow::{FlowOutcome, Program, Runtime, Value, std_native_table};
106//!
107//! const TAG_PING: i32 = 10;
108//! const TAG_PONG: i32 = 11;
109//!
110//! let mut program = Program::new("ping-pong");
111//! let pong = program.function("pong", 0, |f| {
112//! let msg = f.receive();
113//! let payload = f.hop_payload(msg);
114//! f.add_imm(payload, 1);
115//! f.send_reply(msg, TAG_PONG, payload);
116//! f.exit(payload);
117//! });
118//! program.function("main", 0, |f| {
119//! let child = f.spawn(pong, &[]);
120//! let payload = f.load_i32(1);
121//! let req = f.hop_fresh(TAG_PING, payload);
122//! let rid = f.hop_request_id(req);
123//! f.send(child, req);
124//! let reply = f.receive_match_corr_imm(TAG_PONG as u16, rid);
125//! let out = f.hop_payload(reply);
126//! f.return_(out);
127//! });
128//!
129//! let rt = Runtime::with_natives(program.build(), std_native_table())?;
130//! let Some(main) = rt.function_index("main") else {
131//! return Err("missing main".into());
132//! };
133//! let outcome = rt.spawn(main, &[])?.join();
134//! rt.shutdown();
135//! assert!(matches!(outcome, FlowOutcome::Completed(Value::Int(2))));
136//! # Ok(())
137//! # }
138//! ```
139//!
140//! Built-in helpers for tests: [`samples::ping_pong`], [`samples::ask_reply`],
141//! [`samples::selective_receive`], forged-sender security regressions.
142//!
143//! # Collecting a result
144//!
145//! [`FlowHandle::join`] blocks, which suits a `main` with nothing else to
146//! do. Anything holding a deadline picks its own bound instead:
147//!
148//! | Call | Waits | While the flow is still running |
149//! |------|-------|---------------------------------|
150//! | [`FlowHandle::try_join`] | never | `None` |
151//! | [`FlowHandle::join_timeout`] / [`FlowHandle::join_deadline`] | up to the bound | `None` |
152//! | [`FlowHandle::join`] | unbounded | (blocks) |
153//!
154//! ```
155//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
156//! use byteflow::{Program, FlowOutcome, Runtime, Value};
157//! use std::time::Duration;
158//!
159//! let mut program = Program::new("slow");
160//! program.function("main", 0, |f| {
161//! let ms = f.load_i32(300);
162//! f.sleep(ms);
163//! let out = f.load_i32(7);
164//! f.return_(out);
165//! });
166//!
167//! let rt = Runtime::new(program.build())?;
168//! let handle = rt.spawn(0, &[])?;
169//!
170//! // Neither of these consumes the handle or the outcome.
171//! assert!(handle.try_join().is_none());
172//! assert!(handle.join_timeout(Duration::from_millis(10)).is_none());
173//!
174//! let outcome = handle.join_timeout(Duration::from_secs(10));
175//! rt.shutdown();
176//! assert!(matches!(outcome, Some(FlowOutcome::Completed(Value::Int(7)))));
177//! # Ok(())
178//! # }
179//! ```
180//!
181//! [`Runtime::shutdown`] finalizes flows still parked in the timer or a
182//! mailbox; the joiner sees `runtime shutdown` instead of blocking. A
183//! completion sender dropped without that finalize is
184//! [`RuntimeError::Abandoned`]. See [`docs::error_model`].
185//!
186//! # Design guides (rendered on docs.rs)
187//!
188//! - [`docs::atomic_hop`] — hop protocol, Cap addressing, natives table
189//! - [`docs::beam_mapping`] — BEAM / OTP mental model → Byteflow equivalents
190//! - [`docs::lifecycle`] — monitors, links, registry, `WAITING_SEND`
191//! - [`docs::mailbox`] — bounded inbox, overflow, lost-wakeup
192//! - [`docs::security`] — threat model, invariants S1–S7, Phase 3 (0.9.2+)
193//! - [`docs::error_model`] — fail-closed errors (no `unwrap`), bounded joins
194//! - [`docs::vm_safety`] — trust boundary: `verify` vs per-step `Fault`
195//! - [`docs::host_await`] — HostAwait async bridge (host ↔ flow, std-only)
196//!
197//! # What this is *not*
198//!
199//! - Not a replacement for Tokio / async Rust (no `.await` IO loop; use [`HostAwaitBridge`])
200//! - Not a distributed cluster runtime (single process, in-memory mailboxes)
201//! - Not a full object-capability OS (no distributed revocation / Cap persistence)
202//!
203//! Host owns I/O and policy. Byteflow owns cheap concurrency and hop delivery.
204#![deny(unsafe_code)]
205#![cfg_attr(docsrs, feature(doc_cfg))]
206
207pub mod attest;
208pub mod bytecode;
209pub mod entropy;
210pub mod log;
211pub mod memory;
212pub mod natives;
213pub mod output;
214pub mod prng;
215pub mod samples;
216pub mod scheduler;
217pub mod transport;
218pub mod vm;
219
220#[cfg(feature = "jit")]
221#[cfg_attr(docsrs, doc(cfg(feature = "jit")))]
222pub mod jit;
223
224/// Long-form design notes shipped inside the crate (also under `docs/` on GitHub).
225///
226/// These modules exist so [docs.rs](https://docs.rs/byteflow-actors) shows the
227/// same guides as the repository, not only API rustdoc.
228pub mod docs {
229 /// Atomic Hop: Message-only Send, FlowCap addressing, Ask, selective receive.
230 #[doc = include_str!("../docs/atomic-hop.md")]
231 pub mod atomic_hop {}
232
233 /// BEAM / OTP concepts mapped to Byteflow flows, Caps, and Atomic Hop.
234 #[doc = include_str!("../docs/beam-mapping.md")]
235 pub mod beam_mapping {}
236
237 /// Flow lifecycle: monitors, links, registry, WAITING_SEND.
238 #[doc = include_str!("../docs/lifecycle.md")]
239 pub mod lifecycle {}
240
241 /// Security model: authenticated sender, FlowCap, invariants S1–S7.
242 #[doc = include_str!("../docs/security.md")]
243 pub mod security {}
244
245 /// Fail-closed error taxonomy and mutex policy.
246 #[doc = include_str!("../docs/error-model.md")]
247 pub mod error_model {}
248
249 /// Trust boundary: what `verify` settles statically vs what the `Vm`
250 /// checks per step, and why a fault never becomes a panic.
251 #[doc = include_str!("../docs/vm-safety.md")]
252 pub mod vm_safety {}
253
254 /// Bounded mailbox: capacity contract, overflow, anti lost-wakeup.
255 #[doc = include_str!("../docs/mailbox.md")]
256 pub mod mailbox {}
257
258 /// Property / stress tests (in-house PRNG) for mailbox, decode/verify, Caps.
259 #[doc = include_str!("../docs/properties.md")]
260 pub mod properties {}
261
262 /// HostAwait: several host ops per flow; completion is a `TAG_SYS_AWAIT` hop.
263 #[doc = include_str!("../docs/host-await.md")]
264 pub mod host_await {}
265
266 /// Reference TCP/UDP framing for remote hops (host-owned socket I/O).
267 #[doc = include_str!("../docs/remote-transport.md")]
268 pub mod remote_transport {}
269
270 /// Production embedding: shutdown, remote I/O, untrusted modules.
271 #[doc = include_str!("../docs/production-embedding.md")]
272 pub mod production_embedding {}
273
274 /// Audit-derived engineering checklist (track hardening PRs).
275 #[doc = include_str!("../docs/audit-checklist.md")]
276 pub mod audit_checklist {}
277
278 /// Untrusted bytecode: verifier, capabilities, quotas, and attestation
279 /// are separate controls.
280 #[doc = include_str!("../docs/untrusted.md")]
281 pub mod untrusted {}
282}
283
284pub use attest::{decode_attested, fingerprint_bf, AttestError};
285pub use bytecode::{
286 assemble, decode, decode_with, disassemble, encode, verify, verify_with, AssembleError, Cap,
287 CapId, CapIdError, CapRights, CapTarget, Chunk, ConstantKind, Fn, FormatError, FuncId,
288 FunctionDef, Instruction, IntCmp, Label, MapKey, Message, NativeIdx, NativeMask, Opcode,
289 Program, Reg, RegWindow, RestartPolicy, RevocationCell, TrustLevel, Value, VerifyConfig,
290 VerifyError, ABI_VERSION, ABI_VERSION_LISTS, ABI_VERSION_MAPS, ABI_VERSION_RECORDS, MAGIC,
291 MAX_LIST_LEN, MAX_MAP_LEN, MAX_RECORD_LEN, TAG_SYS_AWAIT, TAG_SYS_DOWN, TAG_SYS_EXIT,
292};
293pub use log::LogSink;
294pub use memory::{HeapBytes, HeapStr, MemoryBudget, MemoryError, MemorySnapshot};
295pub use natives::{
296 std_native, std_native_map, std_native_table, std_native_table_with, std_natives,
297};
298pub use output::{NullSink, OutputSink, StdoutSink};
299#[cfg(feature = "jit")]
300pub use scheduler::JitConfig;
301pub use scheduler::{
302 check_admin, check_link, check_monitor, decode_frame, encode_frame, exec_delegate, fault_count,
303 finish_host_await, flow_id_from_u64, next_flow_id, report_fault, AdminError, CapError,
304 Capability, ChildSpec, DelegateError, Delivery, DistributionBridge, DownEvent, Flow,
305 FlowExitReason, FlowHandle, FlowId, FlowMetrics, FlowOutcome, FlowQuota, HostAwaitBridge,
306 HostAwaitCompleter, HostAwaitError, HostAwaitOp, HostAwaitRequest, JoinError, LifecycleError,
307 LinkError, LinkId, Mailbox, MailboxBytes, MailboxCapacity, MailboxConfig, MailboxFull,
308 MailboxFullReason, MailboxStats, MonitorRef, OutboundHop, OverflowPolicy, QuotaConfig,
309 QuotaError, RegistryName, RemoteFrameDedup, RemoteFrameError, RestartStrategy, Runtime,
310 RuntimeConfig, RuntimeError, RuntimeMetrics, RuntimeMetricsSnapshot, RuntimeSnapshot,
311 RuntimeSpawner, SendError, SpawnError, Supervisor, SupervisorConfig, ThreadedHostAwait,
312 WaitEpoch, DEFAULT_QUANTUM,
313};
314pub use transport::{
315 read_wire_frame, recv_wire_frame_udp, send_wire_frame_udp, spawn_tcp_inbound,
316 spawn_tcp_outbound, wait_bridge_drained, write_wire_frame, NodeRouter, StaticNodeRouter,
317 TcpInboundConfig, TcpInboundHandle, TcpOutboundConfig, TcpOutboundHandle, TransportError,
318 DEFAULT_MAX_WIRE_BYTES,
319};
320pub use vm::{
321 check_native_call, check_native_gate, expect_arg, expect_bool, expect_int, expect_message,
322 expect_u64, Fault, NativeCallError, NativeFn, NativeGate, NativeResult, NativeTable,
323 NativeTableBuilder, NativeTableError, Vm, VmResult, MAX_CALL_DEPTH,
324};
325
326#[cfg(feature = "jit")]
327pub use jit::{
328 apply_exit_to_vm, force_compile, hot_threshold, run_compiled_trace, run_compiled_trace_ref,
329 run_vm_with_jit, run_vm_with_jit_runtime, sync_slots_from_vm, try_run_hot, try_run_hot_runtime,
330 CompileError, CompiledTrace, ExitReason, HotCounter, JitContext, JitEntry, JitFrame, JitReturn,
331 JitRuntime, SyncSlotsResult, TraceCache, TraceCompiler, TraceKey, TraceSpan, HOT_THRESHOLD,
332 JIT_BUDGET, JIT_CONTINUE, JIT_DEOPT, JIT_EFFECT, JIT_RETURN, JIT_TRAP, MAX_TRACE_LENGTH,
333};
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338
339 #[test]
340 fn std_native_map_has_stable_indices() {
341 let map = std_native_map();
342 assert_eq!(map.get("print"), Some(&0));
343 assert_eq!(map.get("now_ms"), Some(&1));
344 assert_eq!(map.get("make_msg"), Some(&2));
345 assert_eq!(map.get("msg_payload"), Some(&6));
346 assert_eq!(map.get("msg_reply_cap"), Some(&7));
347 }
348
349 #[test]
350 fn std_native_chunk_runs() -> Result<(), Box<dyn std::error::Error>> {
351 let mut program = Program::new("std-natives-demo");
352 program.function("main", 0, |f| {
353 let n = f.load_i32(42);
354 f.native1_on(n, 0);
355 let ms = f.call_native0(1);
356 f.return_(ms);
357 });
358
359 let chunk = program.build();
360 verify(&chunk)?;
361
362 let rt = Runtime::with_natives(chunk, std_native_table())?;
363 let outcome = rt.spawn(0, &[])?.join();
364 rt.shutdown();
365
366 match outcome {
367 FlowOutcome::Completed(Value::Int(ms)) => {
368 assert!(ms >= 0);
369 Ok(())
370 }
371 other => Err(format!("expected Completed(Value::Int(_)), got {other:?}").into()),
372 }
373 }
374}