byteflow-actors 0.9.28

Embeddable flow runtime: M:N scheduler, Atomic Hop (Message+Cap), supervisor — use byteflow::
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Byteflow — embeddable **flow** runtime (package **`byteflow-actors`**).
//!
//! Not a language, not Tokio, not a JVM. You assemble register bytecode in
//! host Rust ([`Program`] / [`Fn`]), spawn many lightweight **flows** on an M:N
//! scheduler, and they talk through mailboxes with a strict hop protocol.
//!
//! Dependents write `use byteflow::...` (crate name) while crates.io lists
//! the package as [`byteflow-actors`](https://crates.io/crates/byteflow-actors).
//!
//! # What you get
//!
//! | Piece | Role |
//! |-------|------|
//! | [`Program`] / [`Fn`] / [`Opcode`] | Assemble `.bf` programs in Rust (no source language) |
//! | [`verify`] | Static gate for untrusted chunks — mandatory, not advisory |
//! | [`Vm`] / [`VmResult`] | Per-flow register interpreter; effects hand off to the scheduler |
//! | [`Runtime`] | Worker pool + timer; spawn / join / host [`Runtime::send`] |
//! | [`FlowHandle`] | Collect an outcome: blocking [`FlowHandle::join`] or a bounded form |
//! | [`Value::Message`] | **Atomic Hop** envelope — the only value allowed on `Send` / `Ask` |
//! | [`Value::Cap`] | **FlowCap** address for bytecode delivery (`Send` / `Ask` targets) |
//! | [`Cap`] / [`CapRights`] / [`NativeMask`] | Holder + rights; [`Cap::attenuate`] is the only grant path |
//! | [`QuotaConfig`] / [`FlowQuota`] | Per-flow CPU / heap / spawn-send budgets |
//! | [`Supervisor`] | OTP strategies (`OneForOne` / `OneForAll` / `RestForOne`) |
//! | [`std_native_table`] | `print`, `now_ms`, `make_msg` (3-arg), `msg_*`, `msg_reply_cap` |
//! | [`install_supplement_door`] | Door flow: up to eight supplement Caps judged before an owner |
//!
//! # Atomic Hop (messaging contract)
//!
//! Every bytecode `Send` / `Ask` carries exactly one [`Message`]:
//!
//! ```text
//! Message { sender, reply_cap, request_id, tag, payload }
//! ```
//!
//! - Bare `Int` / `Pid` / `Str` on `Send` → trap / [`SendError::NotAHop`]
//! - Scheduler **stamps** `sender` (authenticated origin) and attaches
//!   `reply_cap` (stable SEND-only Cap back to the caller, reused per pair)
//! - Reply with [`std_native_table`]'s `msg_reply_cap` — **not** `msg_sender`
//!   (`Pid` is identity, not an address)
//!
//! Also: selective receive (`ReceiveMatch` / `ReceiveMatchCorr` /
//! `ReceiveMatchKind` / `ReceiveMatchEq` / `ReceiveMatchValue` /
//! `ReceiveMatch*Timeout` for BEAM `after`), `IsAlive`, `ExitSignal`
//! (`exit/2`), process dictionary (`DictPut` / `DictGet` / `DictErase`;
//! `Int` keys, scalars plus `Str` / `Bytes`), `StartSupervisor` /
//! `StartChild`, `Ask` / `AskTimeout`, [`Fn::fresh_request_id`].
//!
//! # FlowCap (addressing)
//!
//! | Value | Use |
//! |-------|-----|
//! | [`Value::Cap`] | Target of `Send` / `Ask`; from `SelfPid`, `Spawn`, or `reply_cap` |
//! | [`Value::Pid`] | Identity inside a delivered hop (`msg_sender`) |
//!
//! Host [`Runtime::send`] still takes [`FlowId`] (trusted embedder path)
//! and is stamped `sender = 0` / `reply_cap = NONE`.
//!
//! Named discovery: [`Fn::register_name`] / [`Fn::whereis`] — `whereis`
//! returns a SEND Cap for the caller, never a raw FlowId.
//!
//! Caps resolve only for the **holder** with sufficient rights. Derive a
//! weaker grant with [`Fn::delegate`] / [`Cap::attenuate`] — never by
//! copying a `CapId`. Host [`Runtime::spawn`] follows
//! [`RootAuthorityPolicy`] (default trusted `ROOT`); use
//! [`Runtime::spawn_untrusted`] for minimum authority. Bytecode
//! [`Fn::spawn_confined`] starts at `NONE`.
//!
//! # Values
//!
//! Scalars are ABI v5: `Unit | Bool | Int | Float | Pid | Message | Cap | Str | Bytes`.
//! A [`Value::List`] selects v6, a [`Value::Map`] selects v7, and a
//! [`Value::Record`] selects v8. [`encode`] writes the oldest of those
//! headers that can hold the constant pool, including a value nested in a
//! list, map, record, or message. [`decode`] accepts v5 through v8.
//!
//! `CapId` is a 128-bit CSPRNG token. `Message.payload` is a nested
//! [`Value`]. `Str` / `Bytes` are `Arc`-backed for cheap register/mailbox
//! clones. They are **not** Atomic Hops by themselves.
//!
//! # Quick start — scalar
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use byteflow::{Program, FlowOutcome, Runtime, Value};
//!
//! let mut program = Program::new("demo");
//! program.function("main", 0, |f| {
//!     let a = f.load_i32(41);
//!     let b = f.load_i32(1);
//!     let sum = f.add(a, b);
//!     f.return_(sum);
//! });
//!
//! let rt = Runtime::new(program.build())?;
//! let outcome = rt.spawn(0, &[])?.join();
//! rt.shutdown();
//! assert!(matches!(outcome, FlowOutcome::Completed(Value::Int(42))));
//! # Ok(())
//! # }
//! ```
//!
//! # Quick start — Atomic Hop (ping-pong)
//!
//! Assemble with [`Program`] / [`Fn`], then run on [`Runtime`]:
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use byteflow::{FlowOutcome, Program, Runtime, Value, std_native_table};
//!
//! const TAG_PING: i32 = 10;
//! const TAG_PONG: i32 = 11;
//!
//! let mut program = Program::new("ping-pong");
//! let pong = program.function("pong", 0, |f| {
//!     let msg = f.receive();
//!     let payload = f.hop_payload(msg);
//!     f.add_imm(payload, 1);
//!     f.send_reply(msg, TAG_PONG, payload);
//!     f.exit(payload);
//! });
//! program.function("main", 0, |f| {
//!     let child = f.spawn(pong, &[]);
//!     let payload = f.load_i32(1);
//!     let req = f.hop_fresh(TAG_PING, payload);
//!     let rid = f.hop_request_id(req);
//!     f.send(child, req);
//!     let reply = f.receive_match_corr_imm(TAG_PONG as u16, rid);
//!     let out = f.hop_payload(reply);
//!     f.return_(out);
//! });
//!
//! let rt = Runtime::with_natives(program.build(), std_native_table())?;
//! let Some(main) = rt.function_index("main") else {
//!     return Err("missing main".into());
//! };
//! let outcome = rt.spawn(main, &[])?.join();
//! rt.shutdown();
//! assert!(matches!(outcome, FlowOutcome::Completed(Value::Int(2))));
//! # Ok(())
//! # }
//! ```
//!
//! Built-in helpers for tests: [`samples::ping_pong`], [`samples::ask_reply`],
//! [`samples::selective_receive`], forged-sender security regressions.
//!
//! # Collecting a result
//!
//! [`FlowHandle::join`] blocks, which suits a `main` with nothing else to
//! do. Anything holding a deadline picks its own bound instead:
//!
//! | Call | Waits | While the flow is still running |
//! |------|-------|---------------------------------|
//! | [`FlowHandle::try_join`] | never | `None` |
//! | [`FlowHandle::join_timeout`] / [`FlowHandle::join_deadline`] | up to the bound | `None` |
//! | [`FlowHandle::join`] | unbounded | (blocks) |
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use byteflow::{Program, FlowOutcome, Runtime, Value};
//! use std::time::Duration;
//!
//! let mut program = Program::new("slow");
//! program.function("main", 0, |f| {
//!     let ms = f.load_i32(300);
//!     f.sleep(ms);
//!     let out = f.load_i32(7);
//!     f.return_(out);
//! });
//!
//! let rt = Runtime::new(program.build())?;
//! let handle = rt.spawn(0, &[])?;
//!
//! // Neither of these consumes the handle or the outcome.
//! assert!(handle.try_join().is_none());
//! assert!(handle.join_timeout(Duration::from_millis(10)).is_none());
//!
//! let outcome = handle.join_timeout(Duration::from_secs(10));
//! rt.shutdown();
//! assert!(matches!(outcome, Some(FlowOutcome::Completed(Value::Int(7)))));
//! # Ok(())
//! # }
//! ```
//!
//! [`Runtime::shutdown`] finalizes flows still parked in the timer or a
//! mailbox; the joiner sees `runtime shutdown` instead of blocking. A
//! completion sender dropped without that finalize is
//! [`RuntimeError::Abandoned`]. See [`docs::error_model`].
//!
//! # Design guides (rendered on docs.rs)
//!
//! - [`docs::atomic_hop`] — hop protocol, Cap addressing, natives table
//! - [`docs::beam_mapping`] — BEAM / OTP mental model → Byteflow equivalents
//! - [`docs::lifecycle`] — monitors, links, registry, `WAITING_SEND`
//! - [`docs::mailbox`] — bounded inbox, overflow, lost-wakeup
//! - [`docs::security`] — threat model, invariants S1–S7, Phase 3 (0.9.2+)
//! - [`docs::error_model`] — fail-closed errors (no `unwrap`), bounded joins
//! - [`docs::vm_safety`] — trust boundary: `verify` vs per-step `Fault`
//! - [`docs::host_await`] — HostAwait async bridge (host ↔ flow, std-only)
//!
//! # Diagnostics
//!
//! Scheduler lines go through [`log`]. A call site passes `format_args!`,
//! so nothing is formatted or allocated unless `BYTEFLOW_LOG`, a
//! [`LogSink`], or — with the optional `tracing` feature — a `tracing`
//! subscriber will receive the line. Those events use the target `byteflow`.
//! The default build does not depend on `tracing`.
//!
//! # What this is *not*
//!
//! - Not a replacement for Tokio / async Rust (no `.await` IO loop; use [`HostAwaitBridge`])
//! - Not a distributed cluster runtime (single process, in-memory mailboxes)
//! - Not a full object-capability OS (no distributed revocation / Cap persistence)
//!
//! Host owns I/O and policy. Byteflow owns cheap concurrency and hop delivery.
#![deny(unsafe_code)]
#![cfg_attr(docsrs, feature(doc_cfg))]

pub mod attest;
pub mod bytecode;
mod digest;
pub mod entropy;
pub mod log;
pub mod memory;
pub mod natives;
pub mod output;
pub mod prng;
pub mod samples;
pub mod scheduler;
pub mod supplement;
pub mod transport;
pub mod vm;

#[cfg(feature = "jit")]
#[cfg_attr(docsrs, doc(cfg(feature = "jit")))]
pub mod jit;

/// Every `rust` block in the README is compiled and run by `cargo test --doc`,
/// so the examples on crates.io cannot drift from the API.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
pub struct ReadmeDoctests;

/// Long-form design notes shipped inside the crate (also under `docs/` on GitHub).
///
/// These modules exist so [docs.rs](https://docs.rs/byteflow-actors) shows the
/// same guides as the repository, not only API rustdoc.
pub mod docs {
    /// Atomic Hop: Message-only Send, FlowCap addressing, Ask, selective receive.
    #[doc = include_str!("../docs/atomic-hop.md")]
    pub mod atomic_hop {}

    /// BEAM / OTP concepts mapped to Byteflow flows, Caps, and Atomic Hop.
    #[doc = include_str!("../docs/beam-mapping.md")]
    pub mod beam_mapping {}

    /// Flow lifecycle: monitors, links, registry, WAITING_SEND.
    #[doc = include_str!("../docs/lifecycle.md")]
    pub mod lifecycle {}

    /// Security model: authenticated sender, FlowCap, invariants S1–S7.
    #[doc = include_str!("../docs/security.md")]
    pub mod security {}

    /// Fail-closed error taxonomy and mutex policy.
    #[doc = include_str!("../docs/error-model.md")]
    pub mod error_model {}

    /// Trust boundary: what `verify` settles statically vs what the `Vm`
    /// checks per step, and why a fault never becomes a panic.
    #[doc = include_str!("../docs/vm-safety.md")]
    pub mod vm_safety {}

    /// Bounded mailbox: capacity contract, overflow, anti lost-wakeup.
    #[doc = include_str!("../docs/mailbox.md")]
    pub mod mailbox {}

    /// Property / stress tests (in-house PRNG) for mailbox, decode/verify, Caps.
    #[doc = include_str!("../docs/properties.md")]
    pub mod properties {}

    /// HostAwait: several host ops per flow; completion is a `TAG_SYS_AWAIT` hop.
    #[doc = include_str!("../docs/host-await.md")]
    pub mod host_await {}

    /// Reference TCP/UDP framing for remote hops (host-owned socket I/O).
    #[doc = include_str!("../docs/remote-transport.md")]
    pub mod remote_transport {}

    /// Production embedding: shutdown, remote I/O, untrusted modules.
    #[doc = include_str!("../docs/production-embedding.md")]
    pub mod production_embedding {}

    /// Audit-derived engineering checklist (track hardening PRs).
    #[doc = include_str!("../docs/audit-checklist.md")]
    pub mod audit_checklist {}

    /// Untrusted bytecode: verifier, capabilities, quotas, and attestation
    /// are separate controls.
    #[doc = include_str!("../docs/untrusted.md")]
    pub mod untrusted {}

    /// Sandbox architecture: trust, Caps, quotas, enforcement boundary.
    #[doc = include_str!("../docs/sandbox/architecture.md")]
    pub mod sandbox_architecture {}

    /// TrustLevel tiers and host-only elevation.
    #[doc = include_str!("../docs/sandbox/trust-model.md")]
    pub mod sandbox_trust {}

    /// CapId, CapTable, attenuation, revocation, attestation.
    #[doc = include_str!("../docs/sandbox/capabilities.md")]
    pub mod sandbox_capabilities {}

    /// Independent resource ceilings and sandbox defaults.
    #[doc = include_str!("../docs/sandbox/quotas.md")]
    pub mod sandbox_quotas {}

    /// What the sandbox assumes and rejects.
    #[doc = include_str!("../docs/sandbox/threat-model.md")]
    pub mod sandbox_threat {}

    /// In-process limits — not OS isolation.
    #[doc = include_str!("../docs/sandbox/limitations.md")]
    pub mod sandbox_limitations {}
}

pub use attest::{decode_attested, fingerprint_bf, AttestError};
pub use bytecode::{
    assemble, decode, decode_with, disassemble, encode, verify, verify_with, AssembleError, Cap,
    CapId, CapIdError, CapRights, CapTarget, Chunk, ConstantKind, Fn, FormatError, FuncId,
    FunctionDef, Instruction, IntCmp, Label, MapKey, Message, NativeIdx, NativeMask, Opcode,
    Program, Reg, RegWindow, RestartPolicy, RevocationCell, TrustLevel, Value, VerifyConfig,
    VerifyError, ABI_VERSION, ABI_VERSION_LISTS, ABI_VERSION_MAPS, ABI_VERSION_RECORDS, MAGIC,
    MAX_LIST_LEN, MAX_MAP_LEN, MAX_RECORD_LEN, TAG_SYS_AWAIT, TAG_SYS_DOWN, TAG_SYS_EXIT,
};
pub use log::LogSink;
pub use memory::{HeapBytes, HeapStr, MemoryBudget, MemoryError, MemorySnapshot};
pub use natives::{
    std_native, std_native_map, std_native_table, std_native_table_with, std_natives,
};
pub use output::{NullSink, OutputSink, StdoutSink};
#[cfg(feature = "jit")]
pub use scheduler::JitConfig;
pub use scheduler::{
    check_admin, check_link, check_monitor, decode_frame, encode_frame, exec_delegate, fault_count,
    finish_host_await, flow_id_from_u64, next_flow_id, policy_fingerprint, report_fault,
    AdminError, CapError, Capability, CapabilityAttestation, CapabilityGrantView, ChildSpec,
    DedupState, DedupTicket, DelegateError, Delivery, DistributionBridge, DistributionConfig,
    DownEvent, Flow, FlowExitReason, FlowHandle, FlowId, FlowMetrics, FlowOutcome, FlowQuota,
    HostAwaitBridge, HostAwaitCompleter, HostAwaitError, HostAwaitOp, HostAwaitRequest, JoinError,
    LifecycleError, LinkError, LinkId, Mailbox, MailboxBytes, MailboxCapacity, MailboxConfig,
    MailboxFull, MailboxFullReason, MailboxStats, MonitorRef, OutboundHop, OverflowPolicy,
    PolicyFingerprint, QuotaConfig, QuotaError, RegistryName, RemoteFrameDedup, RemoteFrameError,
    RestartStrategy, RootAuthorityPolicy, Runtime, RuntimeConfig, RuntimeError, RuntimeMetrics,
    RuntimeMetricsSnapshot, RuntimeSnapshot, RuntimeSpawner, SecurityAuditSink, SecurityCounters,
    SecurityCountersSnapshot, SecurityEvent, SendError, SpawnError, Supervisor, SupervisorConfig,
    ThreadedHostAwait, WaitEpoch, DEFAULT_MAX_PENDING_BYTES, DEFAULT_MAX_PENDING_HOPS,
    DEFAULT_QUANTUM,
};
pub use supplement::{
    install_supplement_door, supplement_attach, supplement_detach, supplement_enter,
    SupplementError, SUPPLEMENT_SLOTS, TAG_SUPP_ATTACH, TAG_SUPP_DELIVER, TAG_SUPP_DETACH,
    TAG_SUPP_ENTER, TAG_SUPP_FOLLOW, TAG_SUPP_JUDGE, TAG_SUPP_REJECT, TAG_SUPP_REPLACE,
};
pub use transport::{
    read_wire_frame, recv_wire_frame_udp, resolve_hop_peer, send_wire_frame_udp, spawn_tcp_inbound,
    spawn_tcp_outbound, spawn_tcp_outbound_routed, wait_bridge_drained, write_wire_frame,
    FixedPeerRouter, NodeRouter, StaticNodeRouter, TcpInboundConfig, TcpInboundHandle,
    TcpOutboundConfig, TcpOutboundHandle, TransportError, DEFAULT_MAX_WIRE_BYTES,
    DEFAULT_SOCKET_TIMEOUT,
};
pub use vm::{
    check_native_call, check_native_gate, expect_arg, expect_bool, expect_int, expect_message,
    expect_u64, Fault, NativeCallError, NativeFn, NativeGate, NativeResult, NativeTable,
    NativeTableBuilder, NativeTableError, Vm, VmResult, MAX_CALL_DEPTH,
};

#[cfg(feature = "jit")]
pub use jit::{
    apply_exit_to_vm, force_compile, hot_threshold, run_compiled_trace, run_compiled_trace_ref,
    run_vm_with_jit, run_vm_with_jit_runtime, sync_slots_from_vm, try_run_hot, try_run_hot_runtime,
    CompileError, CompiledTrace, ExitReason, HotCounter, JitContext, JitEntry, JitFrame, JitReturn,
    JitRuntime, SyncSlotsResult, TraceCache, TraceCompiler, TraceKey, TraceSpan, HOT_THRESHOLD,
    JIT_BUDGET, JIT_CONTINUE, JIT_DEOPT, JIT_EFFECT, JIT_RETURN, JIT_TRAP, MAX_TRACE_LENGTH,
};

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn std_native_map_has_stable_indices() {
        let map = std_native_map();
        assert_eq!(map.get("print"), Some(&0));
        assert_eq!(map.get("now_ms"), Some(&1));
        assert_eq!(map.get("make_msg"), Some(&2));
        assert_eq!(map.get("msg_payload"), Some(&6));
        assert_eq!(map.get("msg_reply_cap"), Some(&7));
    }

    #[test]
    fn std_native_chunk_runs() -> Result<(), Box<dyn std::error::Error>> {
        let mut program = Program::new("std-natives-demo");
        program.function("main", 0, |f| {
            let n = f.load_i32(42);
            f.native1_on(n, 0);
            let ms = f.call_native0(1);
            f.return_(ms);
        });

        let chunk = program.build();
        verify(&chunk)?;

        let rt = Runtime::with_natives(chunk, std_native_table())?;
        let outcome = rt.spawn(0, &[])?.join();
        rt.shutdown();

        match outcome {
            FlowOutcome::Completed(Value::Int(ms)) => {
                assert!(ms >= 0);
                Ok(())
            }
            other => Err(format!("expected Completed(Value::Int(_)), got {other:?}").into()),
        }
    }
}