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