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 (ABI v5)
66//!
67//! `Unit | Bool | Int | Float | Pid | Message | Cap | Str | Bytes`
68//!
69//! `CapId` is a 128-bit CSPRNG token. `Message.payload` is a nested
70//! [`Value`]. `Str` / `Bytes` are `Arc`-backed for cheap register/mailbox
71//! clones. They are **not** Atomic Hops by themselves.
72//!
73//! # Quick start — scalar
74//!
75//! ```
76//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
77//! use byteflow::{Program, FlowOutcome, Runtime, Value};
78//!
79//! let mut program = Program::new("demo");
80//! program.function("main", 0, |f| {
81//! let a = f.load_i32(41);
82//! let b = f.load_i32(1);
83//! let sum = f.add(a, b);
84//! f.return_(sum);
85//! });
86//!
87//! let rt = Runtime::new(program.build())?;
88//! let outcome = rt.spawn(0, &[])?.join();
89//! rt.shutdown();
90//! assert!(matches!(outcome, FlowOutcome::Completed(Value::Int(42))));
91//! # Ok(())
92//! # }
93//! ```
94//!
95//! # Quick start — Atomic Hop (ping-pong)
96//!
97//! Assemble with [`Program`] / [`Fn`], then run on [`Runtime`]:
98//!
99//! ```
100//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
101//! use byteflow::{FlowOutcome, Program, Runtime, Value, std_native_table};
102//!
103//! const TAG_PING: i32 = 10;
104//! const TAG_PONG: i32 = 11;
105//!
106//! let mut program = Program::new("ping-pong");
107//! let pong = program.function("pong", 0, |f| {
108//! let msg = f.receive();
109//! let payload = f.hop_payload(msg);
110//! f.add_imm(payload, 1);
111//! f.send_reply(msg, TAG_PONG, payload);
112//! f.exit(payload);
113//! });
114//! program.function("main", 0, |f| {
115//! let child = f.spawn(pong, &[]);
116//! let payload = f.load_i32(1);
117//! let req = f.hop_fresh(TAG_PING, payload);
118//! let rid = f.hop_request_id(req);
119//! f.send(child, req);
120//! let reply = f.receive_match_corr_imm(TAG_PONG as u16, rid);
121//! let out = f.hop_payload(reply);
122//! f.return_(out);
123//! });
124//!
125//! let rt = Runtime::with_natives(program.build(), std_native_table())?;
126//! let Some(main) = rt.function_index("main") else {
127//! return Err("missing main".into());
128//! };
129//! let outcome = rt.spawn(main, &[])?.join();
130//! rt.shutdown();
131//! assert!(matches!(outcome, FlowOutcome::Completed(Value::Int(2))));
132//! # Ok(())
133//! # }
134//! ```
135//!
136//! Built-in helpers for tests: [`samples::ping_pong`], [`samples::ask_reply`],
137//! [`samples::selective_receive`], forged-sender security regressions.
138//!
139//! # Collecting a result
140//!
141//! [`FlowHandle::join`] blocks, which suits a `main` with nothing else to
142//! do. Anything holding a deadline picks its own bound instead:
143//!
144//! | Call | Waits | While the flow is still running |
145//! |------|-------|---------------------------------|
146//! | [`FlowHandle::try_join`] | never | `None` |
147//! | [`FlowHandle::join_timeout`] / [`FlowHandle::join_deadline`] | up to the bound | `None` |
148//! | [`FlowHandle::join`] | unbounded | (blocks) |
149//!
150//! ```
151//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
152//! use byteflow::{Program, FlowOutcome, Runtime, Value};
153//! use std::time::Duration;
154//!
155//! let mut program = Program::new("slow");
156//! program.function("main", 0, |f| {
157//! let ms = f.load_i32(300);
158//! f.sleep(ms);
159//! let out = f.load_i32(7);
160//! f.return_(out);
161//! });
162//!
163//! let rt = Runtime::new(program.build())?;
164//! let handle = rt.spawn(0, &[])?;
165//!
166//! // Neither of these consumes the handle or the outcome.
167//! assert!(handle.try_join().is_none());
168//! assert!(handle.join_timeout(Duration::from_millis(10)).is_none());
169//!
170//! let outcome = handle.join_timeout(Duration::from_secs(10));
171//! rt.shutdown();
172//! assert!(matches!(outcome, Some(FlowOutcome::Completed(Value::Int(7)))));
173//! # Ok(())
174//! # }
175//! ```
176//!
177//! [`Runtime::shutdown`] finalizes flows still parked in the timer or a
178//! mailbox; the joiner sees `runtime shutdown` instead of blocking. A
179//! completion sender dropped without that finalize is
180//! [`RuntimeError::Abandoned`]. See [`docs::error_model`].
181//!
182//! # Design guides (rendered on docs.rs)
183//!
184//! - [`docs::atomic_hop`] — hop protocol, Cap addressing, natives table
185//! - [`docs::beam_mapping`] — BEAM / OTP mental model → Byteflow equivalents
186//! - [`docs::lifecycle`] — monitors, links, registry, `WAITING_SEND`
187//! - [`docs::mailbox`] — bounded inbox, overflow, lost-wakeup
188//! - [`docs::security`] — threat model, invariants S1–S7, Phase 3 (0.9.2+)
189//! - [`docs::error_model`] — fail-closed errors (no `unwrap`), bounded joins
190//! - [`docs::vm_safety`] — trust boundary: `verify` vs per-step `Fault`
191//! - [`docs::host_await`] — HostAwait async bridge (host ↔ flow, std-only)
192//!
193//! # What this is *not*
194//!
195//! - Not a replacement for Tokio / async Rust (no `.await` IO loop; use [`HostAwaitBridge`])
196//! - Not a distributed cluster runtime (single process, in-memory mailboxes)
197//! - Not a full object-capability OS (no distributed revocation / Cap persistence)
198//!
199//! Host owns I/O and policy. Byteflow owns cheap concurrency and hop delivery.
200#![deny(unsafe_code)]
201#![cfg_attr(docsrs, feature(doc_cfg))]
202
203pub mod attest;
204pub mod bytecode;
205pub mod entropy;
206pub mod log;
207pub mod memory;
208pub mod natives;
209pub mod output;
210pub mod prng;
211pub mod samples;
212pub mod scheduler;
213pub mod vm;
214
215#[cfg(feature = "jit")]
216#[cfg_attr(docsrs, doc(cfg(feature = "jit")))]
217pub mod jit;
218
219/// Long-form design notes shipped inside the crate (also under `docs/` on GitHub).
220///
221/// These modules exist so [docs.rs](https://docs.rs/byteflow-actors) shows the
222/// same guides as the repository, not only API rustdoc.
223pub mod docs {
224 /// Atomic Hop: Message-only Send, FlowCap addressing, Ask, selective receive.
225 #[doc = include_str!("../docs/atomic-hop.md")]
226 pub mod atomic_hop {}
227
228 /// BEAM / OTP concepts mapped to Byteflow flows, Caps, and Atomic Hop.
229 #[doc = include_str!("../docs/beam-mapping.md")]
230 pub mod beam_mapping {}
231
232 /// Flow lifecycle: monitors, links, registry, WAITING_SEND.
233 #[doc = include_str!("../docs/lifecycle.md")]
234 pub mod lifecycle {}
235
236 /// Security model: authenticated sender, FlowCap, invariants S1–S7.
237 #[doc = include_str!("../docs/security.md")]
238 pub mod security {}
239
240 /// Fail-closed error taxonomy and mutex policy.
241 #[doc = include_str!("../docs/error-model.md")]
242 pub mod error_model {}
243
244 /// Trust boundary: what `verify` settles statically vs what the `Vm`
245 /// checks per step, and why a fault never becomes a panic.
246 #[doc = include_str!("../docs/vm-safety.md")]
247 pub mod vm_safety {}
248
249 /// Bounded mailbox: capacity contract, overflow, anti lost-wakeup.
250 #[doc = include_str!("../docs/mailbox.md")]
251 pub mod mailbox {}
252
253 /// Property / stress tests (in-house PRNG) for mailbox, decode/verify, Caps.
254 #[doc = include_str!("../docs/properties.md")]
255 pub mod properties {}
256
257 /// HostAwait: several host ops per flow; completion is a `TAG_SYS_AWAIT` hop.
258 #[doc = include_str!("../docs/host-await.md")]
259 pub mod host_await {}
260}
261
262pub use attest::{decode_attested, fingerprint_bf, AttestError};
263pub use bytecode::{
264 decode, decode_with, disassemble, encode, verify, verify_with, Cap, CapId, CapIdError,
265 CapRights, CapTarget, Chunk, ConstantKind, Fn, FormatError, FuncId, FunctionDef, Instruction,
266 IntCmp, Label, MapKey, Message, NativeIdx, NativeMask, Opcode, Program, Reg, RegWindow,
267 RestartPolicy, RevocationCell, TrustLevel, Value, VerifyConfig, VerifyError, ABI_VERSION,
268 ABI_VERSION_LISTS, ABI_VERSION_MAPS, MAGIC, MAX_MAP_LEN, TAG_SYS_AWAIT, TAG_SYS_DOWN,
269 TAG_SYS_EXIT,
270};
271pub use memory::{HeapBytes, HeapStr, MemoryBudget, MemoryError, MemoryLimit, MemorySnapshot};
272pub use natives::{
273 std_native, std_native_map, std_native_table, std_native_table_with, std_natives,
274};
275pub use output::{NullSink, OutputSink, StdoutSink};
276#[cfg(feature = "jit")]
277pub use scheduler::JitConfig;
278pub use scheduler::{
279 check_admin, check_link, check_monitor, decode_frame, encode_frame, exec_delegate, fault_count,
280 flow_id_from_u64, next_flow_id, report_fault, AdminError, CapError, Capability, ChildSpec,
281 DelegateError, Delivery, DistributionBridge, DownEvent, Flow, FlowExitReason, FlowHandle,
282 FlowId, FlowMetrics, FlowOutcome, FlowQuota, HostAwaitBridge, HostAwaitCompleter,
283 HostAwaitError, HostAwaitOp, HostAwaitRequest, JoinError, LifecycleError, LinkError, LinkId,
284 Mailbox, MailboxBytes, MailboxCapacity, MailboxConfig, MailboxFull, MailboxFullReason,
285 MailboxStats, MonitorRef, OutboundHop, OverflowPolicy, QuotaConfig, QuotaError, RegistryName,
286 RemoteFrameError, RestartStrategy, Runtime, RuntimeConfig, RuntimeError, RuntimeMetrics,
287 RuntimeMetricsSnapshot, RuntimeSpawner, SendError, SpawnError, Supervisor, SupervisorConfig,
288 WaitEpoch, DEFAULT_QUANTUM,
289};
290pub use vm::{
291 check_native_call, check_native_gate, expect_arg, expect_bool, expect_int, expect_message,
292 expect_u64, Fault, NativeCallError, NativeFn, NativeGate, NativeResult, NativeTable,
293 NativeTableBuilder, NativeTableError, Vm, VmResult, MAX_CALL_DEPTH,
294};
295
296#[cfg(feature = "jit")]
297pub use jit::{
298 apply_exit_to_vm, force_compile, hot_threshold, run_compiled_trace, run_compiled_trace_ref,
299 run_vm_with_jit, run_vm_with_jit_runtime, sync_slots_from_vm, try_run_hot, try_run_hot_runtime,
300 CompileError, CompiledTrace, ExitReason, HotCounter, JitContext, JitEntry, JitFrame, JitReturn,
301 JitRuntime, SyncSlotsResult, TraceCache, TraceCompiler, TraceKey, TraceSpan, HOT_THRESHOLD,
302 JIT_BUDGET, JIT_CONTINUE, JIT_DEOPT, JIT_EFFECT, JIT_RETURN, JIT_TRAP, MAX_TRACE_LENGTH,
303};
304
305#[cfg(test)]
306mod tests {
307 use super::*;
308
309 #[test]
310 fn std_native_map_has_stable_indices() {
311 let map = std_native_map();
312 assert_eq!(map.get("print"), Some(&0));
313 assert_eq!(map.get("now_ms"), Some(&1));
314 assert_eq!(map.get("make_msg"), Some(&2));
315 assert_eq!(map.get("msg_payload"), Some(&6));
316 assert_eq!(map.get("msg_reply_cap"), Some(&7));
317 }
318
319 #[test]
320 fn std_native_chunk_runs() -> Result<(), Box<dyn std::error::Error>> {
321 let mut program = Program::new("std-natives-demo");
322 program.function("main", 0, |f| {
323 let n = f.load_i32(42);
324 f.native1_on(n, 0);
325 let ms = f.call_native0(1);
326 f.return_(ms);
327 });
328
329 let chunk = program.build();
330 verify(&chunk)?;
331
332 let rt = Runtime::with_natives(chunk, std_native_table())?;
333 let outcome = rt.spawn(0, &[])?.join();
334 rt.shutdown();
335
336 match outcome {
337 FlowOutcome::Completed(Value::Int(ms)) => {
338 assert!(ms >= 0);
339 Ok(())
340 }
341 other => Err(format!("expected Completed(Value::Int(_)), got {other:?}").into()),
342 }
343 }
344}