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()
}
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()
}
#[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, &[])?;
if let Some(outcome) = handle.try_join() {
rt.shutdown();
return Err(format!("try_join answered too early: {outcome:?}").into());
}
if let Some(outcome) = handle.join_timeout(Duration::from_millis(20)) {
rt.shutdown();
return Err(format!("join_timeout answered too early: {outcome:?}").into());
}
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();
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()),
}
}
#[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| {
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 {
workers: 2,
quantum: 1_000,
mailbox: MailboxConfig::new(cap, OverflowPolicy::DropNewest),
..Default::default()
},
)?;
let server = rt.spawn(busy, &[])?;
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| {
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)])?;
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()),
}
}
#[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()),
}
}