Skip to main content

Runtime

Struct Runtime 

Source
pub struct Runtime { /* private fields */ }
Expand description

A running Byteflow runtime: worker pool + timer thread over one shared Chunk.

Owns M:N scheduling for flows (spawn, yield, sleep, mailboxes, FlowCap resolution, supervised restarts). Optional trace JIT when built with feature = "jit" and enabled in RuntimeConfig::jit.

Construct with Runtime::new (no natives) or Runtime::with_natives when the chunk uses CallNative / crate::std_native_table.

Implementations§

Source§

impl Runtime

Source

pub fn new(chunk: Chunk) -> Result<Self, SpawnError>

Convenience constructor for chunks that never call out through Opcode::CallNative. Equivalent to Runtime::with_natives(chunk, NativeTable::empty()).

Returns SpawnError instead of panicking: verify failures and OS thread-spawn refusals are category-A errors (see docs::error_model).

Source

pub fn with_natives( chunk: Chunk, natives: Arc<NativeTable>, ) -> Result<Self, SpawnError>

Construct a runtime whose flows can call into natives via Opcode::CallNative — the host FFI boundary.

Source

pub fn with_config( chunk: Chunk, config: RuntimeConfig, ) -> Result<Self, SpawnError>

Examples found in repository?
examples/jit_loop.rs (lines 28-39)
26fn run_once(jit: bool) -> Result<(), Box<dyn std::error::Error>> {
27    let chunk = loop_chunk(1_000_000);
28    let rt = Runtime::with_config(
29        chunk,
30        RuntimeConfig {
31            workers: 1,
32            quantum: 50_000_000,
33            jit: JitConfig {
34                enabled: jit,
35                hot_threshold: 1,
36            },
37            ..Default::default()
38        },
39    )?;
40    let start = Instant::now();
41    let outcome = rt.spawn(0, &[])?.join();
42    let snapshot = rt.metrics();
43    rt.shutdown();
44    let elapsed = start.elapsed();
45    match outcome {
46        FlowOutcome::Completed(Value::Int(n)) => {
47            println!("jit={jit} result={n} elapsed={elapsed:?} metrics={snapshot}");
48            Ok(())
49        }
50        other => Err(format!("unexpected outcome: {other:?}").into()),
51    }
52}
More examples
Hide additional examples
examples/crash_and_restart.rs (lines 25-33)
24fn main() {
25    let rt = match Runtime::with_config(
26        boom_chunk(),
27        RuntimeConfig {
28            workers: 1,
29            quantum: 1_000,
30            mailbox: MailboxConfig::DEFAULT,
31            ..Default::default()
32        },
33    ) {
34        Ok(rt) => rt,
35        Err(e) => {
36            eprintln!("runtime: {e}");
37            std::process::exit(1);
38        }
39    };
40    let Some(boom) = rt.function_index("boom") else {
41        eprintln!("missing boom");
42        std::process::exit(1);
43    };
44    let sup = match Supervisor::with_config(
45        rt.spawner(),
46        SupervisorConfig {
47            max_restarts: 2,
48            max_period: Duration::from_secs(5),
49            strategy: RestartStrategy::OneForOne,
50        },
51    ) {
52        Ok(s) => s,
53        Err(e) => {
54            eprintln!("supervisor: {e}");
55            std::process::exit(1);
56        }
57    };
58    if let Err(e) = sup.start_child(ChildSpec::new("boom", boom).restart(RestartPolicy::OnFailure))
59    {
60        eprintln!("start_child: {e}");
61        std::process::exit(1);
62    }
63
64    let start = std::time::Instant::now();
65    while !sup.intensity_exceeded() {
66        if start.elapsed() > Duration::from_secs(2) {
67            eprintln!("supervisor did not hit intensity in time");
68            std::process::exit(1);
69        }
70        thread::sleep(Duration::from_millis(5));
71    }
72
73    let metrics = rt.metrics();
74    println!("intensity exceeded after {} failures", metrics.processes_failed);
75    println!("{metrics}");
76    sup.shutdown();
77    rt.shutdown();
78}
examples/throughput.rs (lines 38-46)
24fn main() {
25    let n: u32 = match std::env::args().nth(1) {
26        Some(s) => match s.parse() {
27            Ok(v) => v,
28            Err(_) => 50_000,
29        },
30        None => 50_000,
31    };
32
33    let workers = match std::thread::available_parallelism() {
34        Ok(p) => p.get(),
35        Err(_) => 1,
36    };
37
38    let rt = match Runtime::with_config(
39        trivial_chunk(),
40        RuntimeConfig {
41            workers,
42            quantum: DEFAULT_QUANTUM,
43            mailbox: MailboxConfig::DEFAULT,
44            ..Default::default()
45        },
46    ) {
47        Ok(rt) => rt,
48        Err(e) => {
49            eprintln!("runtime: {e}");
50            std::process::exit(1);
51        }
52    };
53    let Some(worker_fn) = rt.function_index("worker") else {
54        eprintln!("missing worker");
55        std::process::exit(1);
56    };
57
58    let start = Instant::now();
59    let mut handles = Vec::with_capacity(n as usize);
60    for _ in 0..n {
61        match rt.spawn(worker_fn, &[]) {
62            Ok(h) => handles.push(h),
63            Err(e) => {
64                eprintln!("spawn: {e}");
65                std::process::exit(1);
66            }
67        }
68    }
69    let mut ok = 0u32;
70    for h in handles {
71        if matches!(h.join(), FlowOutcome::Completed(Value::Int(1))) {
72            ok += 1;
73        }
74    }
75    let elapsed = start.elapsed();
76    let metrics = rt.metrics();
77    rt.shutdown();
78
79    let secs = elapsed.as_secs_f64().max(1e-9);
80    println!("processes={ok}/{n}");
81    println!("workers={workers}");
82    println!("elapsed_ms={:.2}", elapsed.as_secs_f64() * 1000.0);
83    println!("spawns_per_sec={:.0}", ok as f64 / secs);
84    println!("{metrics}");
85}
Source

pub fn with_std_natives_and_config( chunk: Chunk, config: RuntimeConfig, ) -> Result<Self, SpawnError>

Like Runtime::with_config but wires crate::std_native_table_with using RuntimeConfig::output for the print native.

Source

pub fn with_natives_and_config( chunk: Chunk, natives: Arc<NativeTable>, config: RuntimeConfig, ) -> Result<Self, SpawnError>

Verify chunk, spawn the worker pool + timer thread, and return a live Runtime.

Failures here mean the runtime was never started (no orphan threads): either the bytecode is invalid (SpawnError::VerifyFailed) or the OS refused a thread (SpawnError::ThreadSpawnFailed).

Examples found in repository?
examples/ping_pong.rs (lines 41-50)
40fn main() {
41    let rt = match Runtime::with_natives_and_config(
42        ping_pong_chunk(),
43        std_native_table(),
44        RuntimeConfig {
45            workers: 1,
46            quantum: DEFAULT_QUANTUM,
47            mailbox: MailboxConfig::DEFAULT,
48            ..Default::default()
49        },
50    ) {
51        Ok(rt) => rt,
52        Err(e) => {
53            eprintln!("runtime: {e}");
54            std::process::exit(1);
55        }
56    };
57    let Some(main_fn) = rt.function_index("main") else {
58        eprintln!("missing main");
59        std::process::exit(1);
60    };
61    let handle = match rt.spawn(main_fn, &[]) {
62        Ok(h) => h,
63        Err(e) => {
64            eprintln!("spawn: {e}");
65            std::process::exit(1);
66        }
67    };
68    let outcome = handle.join();
69    let metrics = rt.metrics();
70    rt.shutdown();
71
72    match outcome {
73        FlowOutcome::Completed(Value::Int(2)) => {
74            println!("pong replied 2 (Atomic Hop)");
75            println!("{metrics}");
76        }
77        other => {
78            eprintln!("unexpected {other:?}");
79            std::process::exit(1);
80        }
81    }
82}
More examples
Hide additional examples
examples/atomic_actors.rs (lines 73-82)
72fn main() {
73    let rt = match Runtime::with_natives_and_config(
74        atomic_actors_chunk(),
75        std_native_table(),
76        RuntimeConfig {
77            workers: 2,
78            quantum: DEFAULT_QUANTUM,
79            mailbox: MailboxConfig::DEFAULT,
80            ..Default::default()
81        },
82    ) {
83        Ok(rt) => rt,
84        Err(e) => {
85            eprintln!("runtime: {e}");
86            std::process::exit(1);
87        }
88    };
89    let Some(main_fn) = rt.function_index("main") else {
90        eprintln!("missing main");
91        std::process::exit(1);
92    };
93    let handle = match rt.spawn(main_fn, &[]) {
94        Ok(h) => h,
95        Err(e) => {
96            eprintln!("spawn: {e}");
97            std::process::exit(1);
98        }
99    };
100    let outcome = handle.join();
101    let metrics = rt.metrics();
102    rt.shutdown();
103
104    match outcome {
105        FlowOutcome::Completed(Value::Int(72)) => {
106            println!("atomic actors ok: two clients × 8 Ask = 72");
107            println!("{metrics}");
108        }
109        other => {
110            eprintln!("unexpected {other:?}");
111            std::process::exit(1);
112        }
113    }
114}
Source

pub fn spawn( &self, function: u32, args: &[Value], ) -> Result<FlowHandle, SpawnError>

Spawn a top-level flow starting at function in this runtime’s chunk, returning a FlowHandle the caller can .join().

Returns SpawnError::BadFunction if function is out of range.

Examples found in repository?
examples/jit_loop.rs (line 41)
26fn run_once(jit: bool) -> Result<(), Box<dyn std::error::Error>> {
27    let chunk = loop_chunk(1_000_000);
28    let rt = Runtime::with_config(
29        chunk,
30        RuntimeConfig {
31            workers: 1,
32            quantum: 50_000_000,
33            jit: JitConfig {
34                enabled: jit,
35                hot_threshold: 1,
36            },
37            ..Default::default()
38        },
39    )?;
40    let start = Instant::now();
41    let outcome = rt.spawn(0, &[])?.join();
42    let snapshot = rt.metrics();
43    rt.shutdown();
44    let elapsed = start.elapsed();
45    match outcome {
46        FlowOutcome::Completed(Value::Int(n)) => {
47            println!("jit={jit} result={n} elapsed={elapsed:?} metrics={snapshot}");
48            Ok(())
49        }
50        other => Err(format!("unexpected outcome: {other:?}").into()),
51    }
52}
More examples
Hide additional examples
examples/ping_pong.rs (line 61)
40fn main() {
41    let rt = match Runtime::with_natives_and_config(
42        ping_pong_chunk(),
43        std_native_table(),
44        RuntimeConfig {
45            workers: 1,
46            quantum: DEFAULT_QUANTUM,
47            mailbox: MailboxConfig::DEFAULT,
48            ..Default::default()
49        },
50    ) {
51        Ok(rt) => rt,
52        Err(e) => {
53            eprintln!("runtime: {e}");
54            std::process::exit(1);
55        }
56    };
57    let Some(main_fn) = rt.function_index("main") else {
58        eprintln!("missing main");
59        std::process::exit(1);
60    };
61    let handle = match rt.spawn(main_fn, &[]) {
62        Ok(h) => h,
63        Err(e) => {
64            eprintln!("spawn: {e}");
65            std::process::exit(1);
66        }
67    };
68    let outcome = handle.join();
69    let metrics = rt.metrics();
70    rt.shutdown();
71
72    match outcome {
73        FlowOutcome::Completed(Value::Int(2)) => {
74            println!("pong replied 2 (Atomic Hop)");
75            println!("{metrics}");
76        }
77        other => {
78            eprintln!("unexpected {other:?}");
79            std::process::exit(1);
80        }
81    }
82}
examples/atomic_actors.rs (line 93)
72fn main() {
73    let rt = match Runtime::with_natives_and_config(
74        atomic_actors_chunk(),
75        std_native_table(),
76        RuntimeConfig {
77            workers: 2,
78            quantum: DEFAULT_QUANTUM,
79            mailbox: MailboxConfig::DEFAULT,
80            ..Default::default()
81        },
82    ) {
83        Ok(rt) => rt,
84        Err(e) => {
85            eprintln!("runtime: {e}");
86            std::process::exit(1);
87        }
88    };
89    let Some(main_fn) = rt.function_index("main") else {
90        eprintln!("missing main");
91        std::process::exit(1);
92    };
93    let handle = match rt.spawn(main_fn, &[]) {
94        Ok(h) => h,
95        Err(e) => {
96            eprintln!("spawn: {e}");
97            std::process::exit(1);
98        }
99    };
100    let outcome = handle.join();
101    let metrics = rt.metrics();
102    rt.shutdown();
103
104    match outcome {
105        FlowOutcome::Completed(Value::Int(72)) => {
106            println!("atomic actors ok: two clients × 8 Ask = 72");
107            println!("{metrics}");
108        }
109        other => {
110            eprintln!("unexpected {other:?}");
111            std::process::exit(1);
112        }
113    }
114}
examples/throughput.rs (line 61)
24fn main() {
25    let n: u32 = match std::env::args().nth(1) {
26        Some(s) => match s.parse() {
27            Ok(v) => v,
28            Err(_) => 50_000,
29        },
30        None => 50_000,
31    };
32
33    let workers = match std::thread::available_parallelism() {
34        Ok(p) => p.get(),
35        Err(_) => 1,
36    };
37
38    let rt = match Runtime::with_config(
39        trivial_chunk(),
40        RuntimeConfig {
41            workers,
42            quantum: DEFAULT_QUANTUM,
43            mailbox: MailboxConfig::DEFAULT,
44            ..Default::default()
45        },
46    ) {
47        Ok(rt) => rt,
48        Err(e) => {
49            eprintln!("runtime: {e}");
50            std::process::exit(1);
51        }
52    };
53    let Some(worker_fn) = rt.function_index("worker") else {
54        eprintln!("missing worker");
55        std::process::exit(1);
56    };
57
58    let start = Instant::now();
59    let mut handles = Vec::with_capacity(n as usize);
60    for _ in 0..n {
61        match rt.spawn(worker_fn, &[]) {
62            Ok(h) => handles.push(h),
63            Err(e) => {
64                eprintln!("spawn: {e}");
65                std::process::exit(1);
66            }
67        }
68    }
69    let mut ok = 0u32;
70    for h in handles {
71        if matches!(h.join(), FlowOutcome::Completed(Value::Int(1))) {
72            ok += 1;
73        }
74    }
75    let elapsed = start.elapsed();
76    let metrics = rt.metrics();
77    rt.shutdown();
78
79    let secs = elapsed.as_secs_f64().max(1e-9);
80    println!("processes={ok}/{n}");
81    println!("workers={workers}");
82    println!("elapsed_ms={:.2}", elapsed.as_secs_f64() * 1000.0);
83    println!("spawns_per_sec={:.0}", ok as f64 / secs);
84    println!("{metrics}");
85}
Source

pub fn spawner(&self) -> RuntimeSpawner

A cheap, Send + Sync handle that can spawn processes into this runtime from any thread, independent of Runtime’s own lifetime bookkeeping (worker JoinHandles). Used by super::supervisor::Supervisor.

Examples found in repository?
examples/crash_and_restart.rs (line 45)
24fn main() {
25    let rt = match Runtime::with_config(
26        boom_chunk(),
27        RuntimeConfig {
28            workers: 1,
29            quantum: 1_000,
30            mailbox: MailboxConfig::DEFAULT,
31            ..Default::default()
32        },
33    ) {
34        Ok(rt) => rt,
35        Err(e) => {
36            eprintln!("runtime: {e}");
37            std::process::exit(1);
38        }
39    };
40    let Some(boom) = rt.function_index("boom") else {
41        eprintln!("missing boom");
42        std::process::exit(1);
43    };
44    let sup = match Supervisor::with_config(
45        rt.spawner(),
46        SupervisorConfig {
47            max_restarts: 2,
48            max_period: Duration::from_secs(5),
49            strategy: RestartStrategy::OneForOne,
50        },
51    ) {
52        Ok(s) => s,
53        Err(e) => {
54            eprintln!("supervisor: {e}");
55            std::process::exit(1);
56        }
57    };
58    if let Err(e) = sup.start_child(ChildSpec::new("boom", boom).restart(RestartPolicy::OnFailure))
59    {
60        eprintln!("start_child: {e}");
61        std::process::exit(1);
62    }
63
64    let start = std::time::Instant::now();
65    while !sup.intensity_exceeded() {
66        if start.elapsed() > Duration::from_secs(2) {
67            eprintln!("supervisor did not hit intensity in time");
68            std::process::exit(1);
69        }
70        thread::sleep(Duration::from_millis(5));
71    }
72
73    let metrics = rt.metrics();
74    println!("intensity exceeded after {} failures", metrics.processes_failed);
75    println!("{metrics}");
76    sup.shutdown();
77    rt.shutdown();
78}
Source

pub fn supervisor(&self) -> Result<Supervisor, SpawnError>

A super::supervisor::Supervisor bound to this runtime, ready to take supervised children (design notes §15).

Source

pub fn function_index(&self, name: &str) -> Option<u32>

Look up a function by name in the runtime’s chunk — convenience for callers that built their chunk with crate::Program and don’t want to thread raw indices through their own code.

Examples found in repository?
examples/ping_pong.rs (line 57)
40fn main() {
41    let rt = match Runtime::with_natives_and_config(
42        ping_pong_chunk(),
43        std_native_table(),
44        RuntimeConfig {
45            workers: 1,
46            quantum: DEFAULT_QUANTUM,
47            mailbox: MailboxConfig::DEFAULT,
48            ..Default::default()
49        },
50    ) {
51        Ok(rt) => rt,
52        Err(e) => {
53            eprintln!("runtime: {e}");
54            std::process::exit(1);
55        }
56    };
57    let Some(main_fn) = rt.function_index("main") else {
58        eprintln!("missing main");
59        std::process::exit(1);
60    };
61    let handle = match rt.spawn(main_fn, &[]) {
62        Ok(h) => h,
63        Err(e) => {
64            eprintln!("spawn: {e}");
65            std::process::exit(1);
66        }
67    };
68    let outcome = handle.join();
69    let metrics = rt.metrics();
70    rt.shutdown();
71
72    match outcome {
73        FlowOutcome::Completed(Value::Int(2)) => {
74            println!("pong replied 2 (Atomic Hop)");
75            println!("{metrics}");
76        }
77        other => {
78            eprintln!("unexpected {other:?}");
79            std::process::exit(1);
80        }
81    }
82}
More examples
Hide additional examples
examples/atomic_actors.rs (line 89)
72fn main() {
73    let rt = match Runtime::with_natives_and_config(
74        atomic_actors_chunk(),
75        std_native_table(),
76        RuntimeConfig {
77            workers: 2,
78            quantum: DEFAULT_QUANTUM,
79            mailbox: MailboxConfig::DEFAULT,
80            ..Default::default()
81        },
82    ) {
83        Ok(rt) => rt,
84        Err(e) => {
85            eprintln!("runtime: {e}");
86            std::process::exit(1);
87        }
88    };
89    let Some(main_fn) = rt.function_index("main") else {
90        eprintln!("missing main");
91        std::process::exit(1);
92    };
93    let handle = match rt.spawn(main_fn, &[]) {
94        Ok(h) => h,
95        Err(e) => {
96            eprintln!("spawn: {e}");
97            std::process::exit(1);
98        }
99    };
100    let outcome = handle.join();
101    let metrics = rt.metrics();
102    rt.shutdown();
103
104    match outcome {
105        FlowOutcome::Completed(Value::Int(72)) => {
106            println!("atomic actors ok: two clients × 8 Ask = 72");
107            println!("{metrics}");
108        }
109        other => {
110            eprintln!("unexpected {other:?}");
111            std::process::exit(1);
112        }
113    }
114}
examples/crash_and_restart.rs (line 40)
24fn main() {
25    let rt = match Runtime::with_config(
26        boom_chunk(),
27        RuntimeConfig {
28            workers: 1,
29            quantum: 1_000,
30            mailbox: MailboxConfig::DEFAULT,
31            ..Default::default()
32        },
33    ) {
34        Ok(rt) => rt,
35        Err(e) => {
36            eprintln!("runtime: {e}");
37            std::process::exit(1);
38        }
39    };
40    let Some(boom) = rt.function_index("boom") else {
41        eprintln!("missing boom");
42        std::process::exit(1);
43    };
44    let sup = match Supervisor::with_config(
45        rt.spawner(),
46        SupervisorConfig {
47            max_restarts: 2,
48            max_period: Duration::from_secs(5),
49            strategy: RestartStrategy::OneForOne,
50        },
51    ) {
52        Ok(s) => s,
53        Err(e) => {
54            eprintln!("supervisor: {e}");
55            std::process::exit(1);
56        }
57    };
58    if let Err(e) = sup.start_child(ChildSpec::new("boom", boom).restart(RestartPolicy::OnFailure))
59    {
60        eprintln!("start_child: {e}");
61        std::process::exit(1);
62    }
63
64    let start = std::time::Instant::now();
65    while !sup.intensity_exceeded() {
66        if start.elapsed() > Duration::from_secs(2) {
67            eprintln!("supervisor did not hit intensity in time");
68            std::process::exit(1);
69        }
70        thread::sleep(Duration::from_millis(5));
71    }
72
73    let metrics = rt.metrics();
74    println!("intensity exceeded after {} failures", metrics.processes_failed);
75    println!("{metrics}");
76    sup.shutdown();
77    rt.shutdown();
78}
examples/throughput.rs (line 53)
24fn main() {
25    let n: u32 = match std::env::args().nth(1) {
26        Some(s) => match s.parse() {
27            Ok(v) => v,
28            Err(_) => 50_000,
29        },
30        None => 50_000,
31    };
32
33    let workers = match std::thread::available_parallelism() {
34        Ok(p) => p.get(),
35        Err(_) => 1,
36    };
37
38    let rt = match Runtime::with_config(
39        trivial_chunk(),
40        RuntimeConfig {
41            workers,
42            quantum: DEFAULT_QUANTUM,
43            mailbox: MailboxConfig::DEFAULT,
44            ..Default::default()
45        },
46    ) {
47        Ok(rt) => rt,
48        Err(e) => {
49            eprintln!("runtime: {e}");
50            std::process::exit(1);
51        }
52    };
53    let Some(worker_fn) = rt.function_index("worker") else {
54        eprintln!("missing worker");
55        std::process::exit(1);
56    };
57
58    let start = Instant::now();
59    let mut handles = Vec::with_capacity(n as usize);
60    for _ in 0..n {
61        match rt.spawn(worker_fn, &[]) {
62            Ok(h) => handles.push(h),
63            Err(e) => {
64                eprintln!("spawn: {e}");
65                std::process::exit(1);
66            }
67        }
68    }
69    let mut ok = 0u32;
70    for h in handles {
71        if matches!(h.join(), FlowOutcome::Completed(Value::Int(1))) {
72            ok += 1;
73        }
74    }
75    let elapsed = start.elapsed();
76    let metrics = rt.metrics();
77    rt.shutdown();
78
79    let secs = elapsed.as_secs_f64().max(1e-9);
80    println!("processes={ok}/{n}");
81    println!("workers={workers}");
82    println!("elapsed_ms={:.2}", elapsed.as_secs_f64() * 1000.0);
83    println!("spawns_per_sec={:.0}", ok as f64 / secs);
84    println!("{metrics}");
85}
Source

pub fn metrics(&self) -> RuntimeMetricsSnapshot

Examples found in repository?
examples/jit_loop.rs (line 42)
26fn run_once(jit: bool) -> Result<(), Box<dyn std::error::Error>> {
27    let chunk = loop_chunk(1_000_000);
28    let rt = Runtime::with_config(
29        chunk,
30        RuntimeConfig {
31            workers: 1,
32            quantum: 50_000_000,
33            jit: JitConfig {
34                enabled: jit,
35                hot_threshold: 1,
36            },
37            ..Default::default()
38        },
39    )?;
40    let start = Instant::now();
41    let outcome = rt.spawn(0, &[])?.join();
42    let snapshot = rt.metrics();
43    rt.shutdown();
44    let elapsed = start.elapsed();
45    match outcome {
46        FlowOutcome::Completed(Value::Int(n)) => {
47            println!("jit={jit} result={n} elapsed={elapsed:?} metrics={snapshot}");
48            Ok(())
49        }
50        other => Err(format!("unexpected outcome: {other:?}").into()),
51    }
52}
More examples
Hide additional examples
examples/ping_pong.rs (line 69)
40fn main() {
41    let rt = match Runtime::with_natives_and_config(
42        ping_pong_chunk(),
43        std_native_table(),
44        RuntimeConfig {
45            workers: 1,
46            quantum: DEFAULT_QUANTUM,
47            mailbox: MailboxConfig::DEFAULT,
48            ..Default::default()
49        },
50    ) {
51        Ok(rt) => rt,
52        Err(e) => {
53            eprintln!("runtime: {e}");
54            std::process::exit(1);
55        }
56    };
57    let Some(main_fn) = rt.function_index("main") else {
58        eprintln!("missing main");
59        std::process::exit(1);
60    };
61    let handle = match rt.spawn(main_fn, &[]) {
62        Ok(h) => h,
63        Err(e) => {
64            eprintln!("spawn: {e}");
65            std::process::exit(1);
66        }
67    };
68    let outcome = handle.join();
69    let metrics = rt.metrics();
70    rt.shutdown();
71
72    match outcome {
73        FlowOutcome::Completed(Value::Int(2)) => {
74            println!("pong replied 2 (Atomic Hop)");
75            println!("{metrics}");
76        }
77        other => {
78            eprintln!("unexpected {other:?}");
79            std::process::exit(1);
80        }
81    }
82}
examples/atomic_actors.rs (line 101)
72fn main() {
73    let rt = match Runtime::with_natives_and_config(
74        atomic_actors_chunk(),
75        std_native_table(),
76        RuntimeConfig {
77            workers: 2,
78            quantum: DEFAULT_QUANTUM,
79            mailbox: MailboxConfig::DEFAULT,
80            ..Default::default()
81        },
82    ) {
83        Ok(rt) => rt,
84        Err(e) => {
85            eprintln!("runtime: {e}");
86            std::process::exit(1);
87        }
88    };
89    let Some(main_fn) = rt.function_index("main") else {
90        eprintln!("missing main");
91        std::process::exit(1);
92    };
93    let handle = match rt.spawn(main_fn, &[]) {
94        Ok(h) => h,
95        Err(e) => {
96            eprintln!("spawn: {e}");
97            std::process::exit(1);
98        }
99    };
100    let outcome = handle.join();
101    let metrics = rt.metrics();
102    rt.shutdown();
103
104    match outcome {
105        FlowOutcome::Completed(Value::Int(72)) => {
106            println!("atomic actors ok: two clients × 8 Ask = 72");
107            println!("{metrics}");
108        }
109        other => {
110            eprintln!("unexpected {other:?}");
111            std::process::exit(1);
112        }
113    }
114}
examples/crash_and_restart.rs (line 73)
24fn main() {
25    let rt = match Runtime::with_config(
26        boom_chunk(),
27        RuntimeConfig {
28            workers: 1,
29            quantum: 1_000,
30            mailbox: MailboxConfig::DEFAULT,
31            ..Default::default()
32        },
33    ) {
34        Ok(rt) => rt,
35        Err(e) => {
36            eprintln!("runtime: {e}");
37            std::process::exit(1);
38        }
39    };
40    let Some(boom) = rt.function_index("boom") else {
41        eprintln!("missing boom");
42        std::process::exit(1);
43    };
44    let sup = match Supervisor::with_config(
45        rt.spawner(),
46        SupervisorConfig {
47            max_restarts: 2,
48            max_period: Duration::from_secs(5),
49            strategy: RestartStrategy::OneForOne,
50        },
51    ) {
52        Ok(s) => s,
53        Err(e) => {
54            eprintln!("supervisor: {e}");
55            std::process::exit(1);
56        }
57    };
58    if let Err(e) = sup.start_child(ChildSpec::new("boom", boom).restart(RestartPolicy::OnFailure))
59    {
60        eprintln!("start_child: {e}");
61        std::process::exit(1);
62    }
63
64    let start = std::time::Instant::now();
65    while !sup.intensity_exceeded() {
66        if start.elapsed() > Duration::from_secs(2) {
67            eprintln!("supervisor did not hit intensity in time");
68            std::process::exit(1);
69        }
70        thread::sleep(Duration::from_millis(5));
71    }
72
73    let metrics = rt.metrics();
74    println!("intensity exceeded after {} failures", metrics.processes_failed);
75    println!("{metrics}");
76    sup.shutdown();
77    rt.shutdown();
78}
examples/throughput.rs (line 76)
24fn main() {
25    let n: u32 = match std::env::args().nth(1) {
26        Some(s) => match s.parse() {
27            Ok(v) => v,
28            Err(_) => 50_000,
29        },
30        None => 50_000,
31    };
32
33    let workers = match std::thread::available_parallelism() {
34        Ok(p) => p.get(),
35        Err(_) => 1,
36    };
37
38    let rt = match Runtime::with_config(
39        trivial_chunk(),
40        RuntimeConfig {
41            workers,
42            quantum: DEFAULT_QUANTUM,
43            mailbox: MailboxConfig::DEFAULT,
44            ..Default::default()
45        },
46    ) {
47        Ok(rt) => rt,
48        Err(e) => {
49            eprintln!("runtime: {e}");
50            std::process::exit(1);
51        }
52    };
53    let Some(worker_fn) = rt.function_index("worker") else {
54        eprintln!("missing worker");
55        std::process::exit(1);
56    };
57
58    let start = Instant::now();
59    let mut handles = Vec::with_capacity(n as usize);
60    for _ in 0..n {
61        match rt.spawn(worker_fn, &[]) {
62            Ok(h) => handles.push(h),
63            Err(e) => {
64                eprintln!("spawn: {e}");
65                std::process::exit(1);
66            }
67        }
68    }
69    let mut ok = 0u32;
70    for h in handles {
71        if matches!(h.join(), FlowOutcome::Completed(Value::Int(1))) {
72            ok += 1;
73        }
74    }
75    let elapsed = start.elapsed();
76    let metrics = rt.metrics();
77    rt.shutdown();
78
79    let secs = elapsed.as_secs_f64().max(1e-9);
80    println!("processes={ok}/{n}");
81    println!("workers={workers}");
82    println!("elapsed_ms={:.2}", elapsed.as_secs_f64() * 1000.0);
83    println!("spawns_per_sec={:.0}", ok as f64 / secs);
84    println!("{metrics}");
85}
Source

pub fn live_flows(&self) -> usize

Number of flows currently registered in the directory — i.e. alive (running, ready, sleeping, or waiting), not counting ones that have already completed or failed.

Source

pub fn worker_count(&self) -> usize

Source

pub fn send(&self, target: FlowId, message: Value) -> Result<(), SendError>

Deliver an Atomic Hop (Value::Message) to target from the embedder (not from bytecode).

§Host trust boundary

This path takes a FlowId directly — no Cap required. The host is trusted; bytecode must use Value::Cap via Opcode::Send / Ask. The hop still goes through the same authentication choke-point as bytecode: sender is stamped FlowId::HOST (0), request_id is minted when unset, and payload Caps are reissued to the recipient. The host has no mailbox, so reply_cap is crate::bytecode::CapId::NONE. Bare scalars are rejected (SendError::NotAHop).

Source

pub fn mint_cap(&self, flow: FlowId) -> Result<CapId, LifecycleError>

Mint a SEND|ASK Cap for a live flow (host equivalent of SelfPid).

Source

pub fn grant_cap( &self, holder: FlowId, target: FlowId, ) -> Result<CapId, LifecycleError>

Mint a Cap held by holder targeting target (host introduction).

Source

pub fn monitor( &self, owner: FlowId, target: FlowId, ) -> Result<MonitorRef, LifecycleError>

Watch target; when it exits, owner receives a crate::TAG_SYS_DOWN hop.

Both flows must be live. owner == target is [LifecycleError::SelfRelation].

Source

pub fn demonitor( &self, owner: FlowId, monitor: MonitorRef, ) -> Result<(), LifecycleError>

Drop monitor if owner still owns it.

Bidirectional link. Abnormal exit of either side kills the peer.

Drop link if owner is one of the endpoints.

Source

pub fn register_name( &self, name: &str, cap: CapId, ) -> Result<(), LifecycleError>

Bind name to a live Cap (address). Names are swept when that flow exits.

Source

pub fn whereis(&self, name: &str) -> Result<Option<CapId>, LifecycleError>

Look up a registered Cap, or None if the name is free / was swept.

Source

pub fn kill(&self, id: FlowId) -> Result<(), LifecycleError>

Cooperative abort. Parked flows finalize immediately; a running flow dies at the next quantum with super::monitor::FlowExitReason::Killed.

Source

pub fn mint_admin_cap(&self, holder: FlowId) -> Result<CapId, LifecycleError>

Mint a scheduler ADMIN cap for a live flow (host introduction).

Source

pub fn admin_kill( &self, holder: FlowId, cap: CapId, target: FlowId, ) -> Result<(), LifecycleError>

Kill target only if holder presents a live ADMIN scheduler cap.

Source

pub fn admin_top_up_cpu( &self, holder: FlowId, cap: CapId, target: FlowId, extra: i64, ) -> Result<(), LifecycleError>

Top up target’s CPU budget. Requires a live ADMIN scheduler cap.

Source

pub fn admin_top_up_mem( &self, holder: FlowId, cap: CapId, target: FlowId, extra: usize, ) -> Result<(), LifecycleError>

Raise target’s heap limit. Requires a live ADMIN scheduler cap.

Source

pub fn admin_top_up_send( &self, holder: FlowId, cap: CapId, target: FlowId, extra: i64, ) -> Result<(), LifecycleError>

Credit target’s send bucket. Requires a live ADMIN scheduler cap.

Source

pub fn unregister_name(&self, name: &str) -> Result<bool, LifecycleError>

Remove a name without waiting for the flow to exit. false if unknown.

Source

pub fn reload_chunk(&mut self, chunk: Chunk) -> Result<(), SpawnError>

Replace the image used by new host Self::spawn calls and drop JIT traces. Live flows and bytecode Spawn keep the parent’s existing Vm chunk.

Source

pub fn shutdown(self)

Stop accepting new scheduling work and join every worker + the timer thread. Processes that are mid-quantum are allowed to reach their next natural suspension point; this does not forcibly abort running bytecode (there is no safe way to do that to an OS thread mid-instruction — see design notes §11 on why preemption here is cooperative/budgeted rather than signal-based).

Examples found in repository?
examples/jit_loop.rs (line 43)
26fn run_once(jit: bool) -> Result<(), Box<dyn std::error::Error>> {
27    let chunk = loop_chunk(1_000_000);
28    let rt = Runtime::with_config(
29        chunk,
30        RuntimeConfig {
31            workers: 1,
32            quantum: 50_000_000,
33            jit: JitConfig {
34                enabled: jit,
35                hot_threshold: 1,
36            },
37            ..Default::default()
38        },
39    )?;
40    let start = Instant::now();
41    let outcome = rt.spawn(0, &[])?.join();
42    let snapshot = rt.metrics();
43    rt.shutdown();
44    let elapsed = start.elapsed();
45    match outcome {
46        FlowOutcome::Completed(Value::Int(n)) => {
47            println!("jit={jit} result={n} elapsed={elapsed:?} metrics={snapshot}");
48            Ok(())
49        }
50        other => Err(format!("unexpected outcome: {other:?}").into()),
51    }
52}
More examples
Hide additional examples
examples/ping_pong.rs (line 70)
40fn main() {
41    let rt = match Runtime::with_natives_and_config(
42        ping_pong_chunk(),
43        std_native_table(),
44        RuntimeConfig {
45            workers: 1,
46            quantum: DEFAULT_QUANTUM,
47            mailbox: MailboxConfig::DEFAULT,
48            ..Default::default()
49        },
50    ) {
51        Ok(rt) => rt,
52        Err(e) => {
53            eprintln!("runtime: {e}");
54            std::process::exit(1);
55        }
56    };
57    let Some(main_fn) = rt.function_index("main") else {
58        eprintln!("missing main");
59        std::process::exit(1);
60    };
61    let handle = match rt.spawn(main_fn, &[]) {
62        Ok(h) => h,
63        Err(e) => {
64            eprintln!("spawn: {e}");
65            std::process::exit(1);
66        }
67    };
68    let outcome = handle.join();
69    let metrics = rt.metrics();
70    rt.shutdown();
71
72    match outcome {
73        FlowOutcome::Completed(Value::Int(2)) => {
74            println!("pong replied 2 (Atomic Hop)");
75            println!("{metrics}");
76        }
77        other => {
78            eprintln!("unexpected {other:?}");
79            std::process::exit(1);
80        }
81    }
82}
examples/atomic_actors.rs (line 102)
72fn main() {
73    let rt = match Runtime::with_natives_and_config(
74        atomic_actors_chunk(),
75        std_native_table(),
76        RuntimeConfig {
77            workers: 2,
78            quantum: DEFAULT_QUANTUM,
79            mailbox: MailboxConfig::DEFAULT,
80            ..Default::default()
81        },
82    ) {
83        Ok(rt) => rt,
84        Err(e) => {
85            eprintln!("runtime: {e}");
86            std::process::exit(1);
87        }
88    };
89    let Some(main_fn) = rt.function_index("main") else {
90        eprintln!("missing main");
91        std::process::exit(1);
92    };
93    let handle = match rt.spawn(main_fn, &[]) {
94        Ok(h) => h,
95        Err(e) => {
96            eprintln!("spawn: {e}");
97            std::process::exit(1);
98        }
99    };
100    let outcome = handle.join();
101    let metrics = rt.metrics();
102    rt.shutdown();
103
104    match outcome {
105        FlowOutcome::Completed(Value::Int(72)) => {
106            println!("atomic actors ok: two clients × 8 Ask = 72");
107            println!("{metrics}");
108        }
109        other => {
110            eprintln!("unexpected {other:?}");
111            std::process::exit(1);
112        }
113    }
114}
examples/crash_and_restart.rs (line 77)
24fn main() {
25    let rt = match Runtime::with_config(
26        boom_chunk(),
27        RuntimeConfig {
28            workers: 1,
29            quantum: 1_000,
30            mailbox: MailboxConfig::DEFAULT,
31            ..Default::default()
32        },
33    ) {
34        Ok(rt) => rt,
35        Err(e) => {
36            eprintln!("runtime: {e}");
37            std::process::exit(1);
38        }
39    };
40    let Some(boom) = rt.function_index("boom") else {
41        eprintln!("missing boom");
42        std::process::exit(1);
43    };
44    let sup = match Supervisor::with_config(
45        rt.spawner(),
46        SupervisorConfig {
47            max_restarts: 2,
48            max_period: Duration::from_secs(5),
49            strategy: RestartStrategy::OneForOne,
50        },
51    ) {
52        Ok(s) => s,
53        Err(e) => {
54            eprintln!("supervisor: {e}");
55            std::process::exit(1);
56        }
57    };
58    if let Err(e) = sup.start_child(ChildSpec::new("boom", boom).restart(RestartPolicy::OnFailure))
59    {
60        eprintln!("start_child: {e}");
61        std::process::exit(1);
62    }
63
64    let start = std::time::Instant::now();
65    while !sup.intensity_exceeded() {
66        if start.elapsed() > Duration::from_secs(2) {
67            eprintln!("supervisor did not hit intensity in time");
68            std::process::exit(1);
69        }
70        thread::sleep(Duration::from_millis(5));
71    }
72
73    let metrics = rt.metrics();
74    println!("intensity exceeded after {} failures", metrics.processes_failed);
75    println!("{metrics}");
76    sup.shutdown();
77    rt.shutdown();
78}
examples/throughput.rs (line 77)
24fn main() {
25    let n: u32 = match std::env::args().nth(1) {
26        Some(s) => match s.parse() {
27            Ok(v) => v,
28            Err(_) => 50_000,
29        },
30        None => 50_000,
31    };
32
33    let workers = match std::thread::available_parallelism() {
34        Ok(p) => p.get(),
35        Err(_) => 1,
36    };
37
38    let rt = match Runtime::with_config(
39        trivial_chunk(),
40        RuntimeConfig {
41            workers,
42            quantum: DEFAULT_QUANTUM,
43            mailbox: MailboxConfig::DEFAULT,
44            ..Default::default()
45        },
46    ) {
47        Ok(rt) => rt,
48        Err(e) => {
49            eprintln!("runtime: {e}");
50            std::process::exit(1);
51        }
52    };
53    let Some(worker_fn) = rt.function_index("worker") else {
54        eprintln!("missing worker");
55        std::process::exit(1);
56    };
57
58    let start = Instant::now();
59    let mut handles = Vec::with_capacity(n as usize);
60    for _ in 0..n {
61        match rt.spawn(worker_fn, &[]) {
62            Ok(h) => handles.push(h),
63            Err(e) => {
64                eprintln!("spawn: {e}");
65                std::process::exit(1);
66            }
67        }
68    }
69    let mut ok = 0u32;
70    for h in handles {
71        if matches!(h.join(), FlowOutcome::Completed(Value::Int(1))) {
72            ok += 1;
73        }
74    }
75    let elapsed = start.elapsed();
76    let metrics = rt.metrics();
77    rt.shutdown();
78
79    let secs = elapsed.as_secs_f64().max(1e-9);
80    println!("processes={ok}/{n}");
81    println!("workers={workers}");
82    println!("elapsed_ms={:.2}", elapsed.as_secs_f64() * 1000.0);
83    println!("spawns_per_sec={:.0}", ok as f64 / secs);
84    println!("{metrics}");
85}

Trait Implementations§

Source§

impl Drop for Runtime

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.