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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
use super::*;
use crate::bytecode::{builder::ChunkBuilder, Opcode, Value};
use crate::scheduler::FlowOutcome;
use std::time::Duration;

#[test]
fn bytecode_spawn_rejects_an_argc_the_callee_did_not_declare() {
    assert!(super::bytecode_spawn_arity(2, 2).is_ok());
    assert!(matches!(
        super::bytecode_spawn_arity(2, 1),
        Err(crate::vm::Fault::BadArity {
            passed: 1,
            expected: 2,
        })
    ));
}

fn add_chunk() -> Chunk {
    let mut b = ChunkBuilder::new("test");
    b.begin_function("main", 0, 2);
    b.emit_load_imm(0, 41);
    b.emit_load_imm(1, 1);
    b.emit_binop(Opcode::Add, 0, 0, 1);
    b.emit_return(0);
    b.finish()
}

/// Sleeps `millis` inside the flow, then returns 7. The sleep is what
/// makes "still running" an observable state from the host thread.
fn sleep_then_return_chunk(millis: i32) -> Chunk {
    let mut b = ChunkBuilder::new("test");
    b.begin_function("main", 0, 2);
    b.emit_load_imm(0, millis);
    b.emit_sleep(0);
    b.emit_load_imm(0, 7);
    b.emit_return(0);
    b.finish()
}

/// The host thread must be able to ask "done yet?" and to wait under a
/// bound *it* chooses, instead of surrendering itself to `join` for
/// however long the bytecode decides to take.
#[test]
fn polling_and_bounded_waits_never_commit_the_host_thread() -> Result<(), Box<dyn std::error::Error>>
{
    const FLOW_SLEEP: i32 = 150;
    let rt = Runtime::with_config(
        sleep_then_return_chunk(FLOW_SLEEP),
        RuntimeConfig {
            workers: 1,
            quantum: 1_000,
            mailbox: MailboxConfig::DEFAULT,
            ..Default::default()
        },
    )?;
    let handle = rt.spawn(0, &[])?;

    // The flow cannot possibly be finished yet: it has to be picked up
    // and then sleep. A poll must say so without waiting.
    if let Some(outcome) = handle.try_join() {
        rt.shutdown();
        return Err(format!("try_join answered too early: {outcome:?}").into());
    }

    // A bound well below the flow's sleep must expire and hand control
    // back, not block until the flow happens to finish.
    if let Some(outcome) = handle.join_timeout(Duration::from_millis(20)) {
        rt.shutdown();
        return Err(format!("join_timeout answered too early: {outcome:?}").into());
    }

    // A generous bound collects the real outcome through the same
    // (non-consuming) handle.
    let outcome = handle.join_timeout(Duration::from_secs(10));
    rt.shutdown();
    match outcome {
        Some(FlowOutcome::Completed(Value::Int(7))) => Ok(()),
        other => Err(format!("unexpected outcome: {other:?}").into()),
    }
}

#[test]
fn spawn_and_join_add() -> Result<(), Box<dyn std::error::Error>> {
    let rt = Runtime::with_config(
        add_chunk(),
        RuntimeConfig {
            workers: 1,
            quantum: 1_000,
            mailbox: MailboxConfig::DEFAULT,
            ..Default::default()
        },
    )?;
    let outcome = rt.spawn(0, &[])?.join();
    rt.shutdown();
    match outcome {
        FlowOutcome::Completed(Value::Int(42)) => Ok(()),
        other => Err(format!("unexpected outcome: {other:?}").into()),
    }
}

fn receive_forever_chunk() -> Chunk {
    let mut b = ChunkBuilder::new("recv");
    b.begin_function("main", 0, 1);
    b.emit_receive(0);
    b.emit_return(0);
    b.finish()
}

#[test]
fn kill_parked_flow_joins_failed() -> Result<(), Box<dyn std::error::Error>> {
    let rt = Runtime::with_config(
        receive_forever_chunk(),
        RuntimeConfig {
            workers: 1,
            quantum: 1_000,
            mailbox: MailboxConfig::DEFAULT,
            ..Default::default()
        },
    )?;
    let handle = rt.spawn(0, &[])?;
    rt.kill(handle.id())?;
    let outcome = handle.join();
    rt.shutdown();
    assert!(
        matches!(outcome, FlowOutcome::Failed(_)),
        "kill must fail the joiner, got {outcome:?}"
    );
    Ok(())
}

#[test]
fn shutdown_finalizes_parked_receive() -> Result<(), Box<dyn std::error::Error>> {
    let rt = Runtime::with_config(
        receive_forever_chunk(),
        RuntimeConfig {
            workers: 1,
            quantum: 1_000,
            mailbox: MailboxConfig::DEFAULT,
            ..Default::default()
        },
    )?;
    let handle = rt.spawn(0, &[])?;
    std::thread::sleep(Duration::from_millis(30));
    rt.shutdown();
    match handle.join() {
        FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
        other => Err(format!("expected shutdown finalize, got {other:?}").into()),
    }
}

#[test]
fn shutdown_finalizes_sleeper() -> Result<(), Box<dyn std::error::Error>> {
    let rt = Runtime::with_config(
        sleep_then_return_chunk(60_000),
        RuntimeConfig {
            workers: 1,
            quantum: 1_000,
            mailbox: MailboxConfig::DEFAULT,
            ..Default::default()
        },
    )?;
    let handle = rt.spawn(0, &[])?;
    std::thread::sleep(Duration::from_millis(30));
    rt.shutdown();
    match handle.join() {
        FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
        other => Err(format!("expected sleeper shutdown, got {other:?}").into()),
    }
}

#[test]
fn drop_finalizes_a_parked_sleeper() -> Result<(), Box<dyn std::error::Error>> {
    let rt = Runtime::with_config(
        sleep_then_return_chunk(60_000),
        RuntimeConfig {
            workers: 1,
            quantum: 1_000,
            mailbox: MailboxConfig::DEFAULT,
            ..Default::default()
        },
    )?;
    let handle = rt.spawn(0, &[])?;
    std::thread::sleep(Duration::from_millis(30));
    drop(rt);
    match handle.join() {
        FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
        other => Err(format!("expected drop to finalize the sleeper, got {other:?}").into()),
    }
}

#[test]
fn zero_quantum_still_runs_the_flow() -> Result<(), Box<dyn std::error::Error>> {
    let rt = Runtime::with_config(
        add_chunk(),
        RuntimeConfig {
            workers: 1,
            quantum: 0,
            mailbox: MailboxConfig::DEFAULT,
            ..Default::default()
        },
    )?;
    let outcome = rt.spawn(0, &[])?.join();
    rt.shutdown();
    assert!(
        matches!(outcome, FlowOutcome::Completed(Value::Int(42))),
        "got {outcome:?}"
    );
    Ok(())
}

#[test]
fn max_flows_rejects_extra_spawn() -> Result<(), Box<dyn std::error::Error>> {
    let rt = Runtime::with_config(
        receive_forever_chunk(),
        RuntimeConfig {
            workers: 1,
            quantum: 1_000,
            mailbox: MailboxConfig::DEFAULT,
            max_flows: 1,
            ..Default::default()
        },
    )?;
    let first = rt.spawn(0, &[])?;
    let second = rt.spawn(0, &[]);
    rt.kill(first.id())?;
    let _ = first.join();
    // After finalize, the reserved slot must be free again.
    let third = rt.spawn(0, &[])?;
    rt.kill(third.id())?;
    let _ = third.join();
    rt.shutdown();
    match second {
        Err(SpawnError::FlowLimit { current, max }) => {
            assert_eq!(current, 1);
            assert_eq!(max, 1);
            Ok(())
        }
        other => Err(format!(
            "expected FlowLimit, got {}",
            match &other {
                Ok(_) => "Ok(handle)".into(),
                Err(e) => format!("Err({e})"),
            }
        )
        .into()),
    }
}

/// Ask must not park waiting for a reply when DropNewest discarded the request.
#[test]
fn ask_drop_newest_fails_closed() -> Result<(), Box<dyn std::error::Error>> {
    use crate::bytecode::{Message, Program};
    use crate::scheduler::mailbox::{MailboxCapacity, OverflowPolicy};

    let mut program = Program::new("ask-drop-newest");
    let busy = program.function("busy", 0, |f| {
        // Stay alive without spinning the worker: sleep loop.
        let loop_lbl = f.label();
        f.bind(loop_lbl);
        let ms = f.load_i32(50);
        f.sleep(ms);
        f.jump(loop_lbl);
    });
    let asker = program.function("asker", 1, |f| {
        let server = f.reg(0);
        let z = f.load_i32(0);
        let req = f.hop_fresh(1, z);
        let reply = f.ask(server, req);
        f.return_(reply);
    });
    let chunk = program.build();

    let cap = MailboxCapacity::new(1).ok_or("cap")?;
    let rt = Runtime::with_natives_and_config(
        chunk,
        crate::std_native_table(),
        RuntimeConfig {
            // Busy target must not monopolize scheduling or Ask never runs.
            workers: 2,
            quantum: 1_000,
            mailbox: MailboxConfig::new(cap, OverflowPolicy::DropNewest),
            ..Default::default()
        },
    )?;

    let server = rt.spawn(busy, &[])?;
    // Fill the only slot so the subsequent Ask is DropNewest'd.
    rt.send(
        server.id(),
        Value::Message(Message::request(1, 9, Value::Int(1))),
    )?;
    let server_cap = rt.mint_cap(server.id())?;
    let ask = rt.spawn(asker, &[Value::Cap(server_cap)])?;
    let outcome = ask.join_timeout(Duration::from_secs(3));
    rt.kill(server.id())?;
    let _ = server.join_timeout(Duration::from_millis(500));
    rt.shutdown();

    match outcome {
        Some(FlowOutcome::Failed(msg)) if msg.contains("DropNewest") => Ok(()),
        other => Err(format!("expected Ask DropNewest failure, got {other:?}").into()),
    }
}

#[test]
fn max_ask_waits_rejects_extra_park() -> Result<(), Box<dyn std::error::Error>> {
    use crate::bytecode::Program;

    let mut program = Program::new("ask-limit");
    let silent = program.function("silent", 0, |f| {
        // Accept the request hop but never reply.
        let _req = f.receive();
        let loop_lbl = f.label();
        f.bind(loop_lbl);
        let ms = f.load_i32(50);
        f.sleep(ms);
        f.jump(loop_lbl);
    });
    let asker = program.function("asker", 1, |f| {
        let server = f.reg(0);
        let z = f.load_i32(0);
        let req = f.hop_fresh(1, z);
        let reply = f.ask(server, req);
        f.return_(reply);
    });
    let chunk = program.build();

    let rt = Runtime::with_natives_and_config(
        chunk,
        crate::std_native_table(),
        RuntimeConfig {
            workers: 2,
            quantum: 1_000,
            mailbox: MailboxConfig::DEFAULT,
            max_ask_waits: 1,
            ..Default::default()
        },
    )?;

    let server = rt.spawn(silent, &[])?;
    let server_cap = rt.mint_cap(server.id())?;
    let first = rt.spawn(asker, &[Value::Cap(server_cap)])?;
    // Give the first Ask time to park before the second tries.
    std::thread::sleep(Duration::from_millis(30));
    let second = rt.spawn(asker, &[Value::Cap(server_cap)])?;
    let second_out = second.join_timeout(Duration::from_secs(2));
    rt.kill(server.id())?;
    let _ = first.join_timeout(Duration::from_millis(500));
    let _ = server.join_timeout(Duration::from_millis(500));
    rt.shutdown();

    match second_out {
        Some(FlowOutcome::Failed(msg)) if msg.contains("Ask wait limit") => Ok(()),
        other => Err(format!("expected Ask wait limit failure, got {other:?}").into()),
    }
}

// HostAwait E2E coverage lives in `host_await::runtime_tests`.

#[cfg(feature = "jit")]
#[test]
fn runtime_with_jit_enabled_completes_add() -> Result<(), Box<dyn std::error::Error>> {
    use crate::JitConfig;

    let rt = Runtime::with_config(
        add_chunk(),
        RuntimeConfig {
            workers: 1,
            quantum: 1_000,
            mailbox: MailboxConfig::DEFAULT,
            jit: JitConfig {
                enabled: true,
                hot_threshold: 1,
            },
            ..Default::default()
        },
    )?;
    let outcome = rt.spawn(0, &[])?.join();
    rt.shutdown();
    match outcome {
        FlowOutcome::Completed(Value::Int(42)) => Ok(()),
        other => Err(format!("unexpected outcome: {other:?}").into()),
    }
}

#[test]
fn sandbox_enables_process_wide_relation_caps() {
    let config = RuntimeConfig::sandbox();
    assert_eq!(config.max_flows, 128);
    assert_eq!(config.max_ask_waits, 64);
    assert_eq!(config.max_host_awaits, 128);
    assert_eq!(config.trust, crate::bytecode::TrustLevel::Untrusted);
    assert_ne!(
        config.policy_fingerprint(),
        RuntimeConfig::default().policy_fingerprint()
    );
    assert_eq!(config.max_links, 1024);
    assert_eq!(config.max_monitors, 1024);
    assert_eq!(config.max_registry_names, 256);
    assert_eq!(config.max_runtime_bytes, 64 * 1024 * 1024);
}

#[test]
fn default_remains_unlimited_for_relation_caps() {
    let config = RuntimeConfig::default();
    assert_eq!(config.max_links, 0);
    assert_eq!(config.max_monitors, 0);
    assert_eq!(config.max_registry_names, 0);
}

#[test]
fn with_attested_mismatch_is_attestation_error() -> Result<(), Box<dyn std::error::Error>> {
    use crate::bytecode::encode;
    use crate::{fingerprint_bf, AttestError};

    let bytes = encode(&add_chunk());
    let mut bad = fingerprint_bf(&bytes);
    bad[0] ^= 0xff;
    match Runtime::with_attested(&bytes, bad, NativeTable::empty(), RuntimeConfig::default()) {
        Err(SpawnError::Attestation(AttestError::DigestMismatch { .. })) => Ok(()),
        Ok(_) => Err("expected Attestation error, got Ok(Runtime)".into()),
        Err(e) => Err(format!("expected Attestation(DigestMismatch), got Err({e})").into()),
    }
}

#[test]
fn with_attested_match_runs() -> Result<(), Box<dyn std::error::Error>> {
    use crate::bytecode::encode;
    use crate::fingerprint_bf;

    let chunk = add_chunk();
    let bytes = encode(&chunk);
    let digest = fingerprint_bf(&bytes);
    let rt = Runtime::with_attested(
        &bytes,
        digest,
        NativeTable::empty(),
        RuntimeConfig {
            workers: 1,
            quantum: 1_000,
            mailbox: MailboxConfig::DEFAULT,
            ..Default::default()
        },
    )?;
    let outcome = rt.spawn(0, &[])?.join();
    rt.shutdown();
    match outcome {
        FlowOutcome::Completed(Value::Int(42)) => Ok(()),
        other => Err(format!("expected 42, got {other:?}").into()),
    }
}

#[test]
fn poisoned_injector_still_runs_the_flow() -> Result<(), Box<dyn std::error::Error>> {
    let rt = Runtime::new(add_chunk())?;
    rt.shared.injector.poison_for_test();
    let outcome = rt.spawn(0, &[])?.join_timeout(Duration::from_secs(2));
    rt.shutdown();
    match outcome {
        Some(FlowOutcome::Completed(Value::Int(42))) => Ok(()),
        other => Err(format!("expected 42 after a poisoned injector, got {other:?}").into()),
    }
}