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