diff --git a/Cargo.lock b/Cargo.lock index 60f4e86..efcff0d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -29,6 +29,12 @@ version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" +[[package]] +name = "anyhow" +version = "1.0.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f0e0fee31ef5ed1ba1316088939cea399010ed7731dba877ed44aeb407a75ea" + [[package]] name = "ascii" version = "1.1.0" @@ -47,6 +53,21 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + [[package]] name = "bitflags" version = "2.10.0" @@ -277,7 +298,7 @@ dependencies = [ "crossterm_winapi", "mio", "parking_lot", - "rustix", + "rustix 0.38.44", "signal-hook", "signal-hook-mio", "winapi", @@ -417,7 +438,7 @@ name = "distribution" version = "0.1.0" dependencies = [ "ed25519-dalek", - "rand_core", + "rand_core 0.6.4", "serde", "serde_json", "swactor", @@ -441,7 +462,7 @@ checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" dependencies = [ "curve25519-dalek", "ed25519", - "rand_core", + "rand_core 0.6.4", "serde", "sha2", "subtle", @@ -470,12 +491,24 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "fastrand" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" + [[package]] name = "fiat-crypto" version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "foldhash" version = "0.1.5" @@ -503,6 +536,31 @@ dependencies = [ "wasi", ] +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", + "wasip3", +] + [[package]] name = "half" version = "2.7.1" @@ -549,6 +607,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + [[package]] name = "ident_case" version = "1.0.1" @@ -563,6 +627,8 @@ checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" dependencies = [ "equivalent", "hashbrown 0.16.1", + "serde", + "serde_core", ] [[package]] @@ -638,6 +704,12 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + [[package]] name = "libc" version = "0.2.181" @@ -650,6 +722,12 @@ version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" +[[package]] +name = "linux-raw-sys" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" + [[package]] name = "lock_api" version = "0.4.14" @@ -837,6 +915,25 @@ version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn", +] + [[package]] name = "proc-macro2" version = "1.0.106" @@ -846,6 +943,34 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "proptest" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37566cb3fdacef14c0737f9546df7cfeadbfbc9fef10991038bf5015d0c80532" +dependencies = [ + "bit-set", + "bit-vec", + "bitflags", + "num-traits", + "rand", + "rand_chacha", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + +[[package]] +name = "proptest-state-machine" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e943d140e09d07740fb496487c51fb8eb31c70389ac4a2e9dcd8a0d9fdf228d4" +dependencies = [ + "proptest", +] + [[package]] name = "pyo3" version = "0.23.5" @@ -917,6 +1042,12 @@ dependencies = [ "swactor", ] +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + [[package]] name = "quote" version = "1.0.44" @@ -926,13 +1057,57 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + [[package]] name = "rand_core" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ - "getrandom", + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_xorshift" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" +dependencies = [ + "rand_core 0.9.5", ] [[package]] @@ -1049,16 +1224,41 @@ dependencies = [ "bitflags", "errno", "libc", - "linux-raw-sys", + "linux-raw-sys 0.4.15", "windows-sys 0.59.0", ] +[[package]] +name = "rustix" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.11.0", + "windows-sys 0.61.2", +] + [[package]] name = "rustversion" version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error", + "tempfile", + "wait-timeout", +] + [[package]] name = "ryu" version = "1.0.23" @@ -1195,7 +1395,7 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -1203,7 +1403,7 @@ name = "simulation" version = "0.1.0" dependencies = [ "distribution", - "getrandom", + "getrandom 0.2.17", "log", "serde", "serde_json", @@ -1285,11 +1485,22 @@ dependencies = [ "criterion", "crossbeam-queue", "crossbeam-utils", - "getrandom", + "getrandom 0.2.17", + "proptest", + "proptest-state-machine", "serde", + "swactor-std", "tracing", ] +[[package]] +name = "swactor-std" +version = "0.1.0" +dependencies = [ + "getrandom 0.2.17", + "swactor", +] + [[package]] name = "syn" version = "2.0.114" @@ -1307,6 +1518,19 @@ version = "0.12.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" +[[package]] +name = "tempfile" +version = "3.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0136791f7c95b1f6dd99f9cc786b91bb81c3800b639b3478e561ddb7be95e5f1" +dependencies = [ + "fastrand", + "getrandom 0.4.1", + "once_cell", + "rustix 1.1.3", + "windows-sys 0.61.2", +] + [[package]] name = "thread_local" version = "1.1.9" @@ -1442,6 +1666,12 @@ version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + [[package]] name = "unicode-ident" version = "1.0.23" @@ -1477,6 +1707,12 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + [[package]] name = "unindent" version = "0.2.4" @@ -1495,6 +1731,15 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + [[package]] name = "walkdir" version = "2.5.0" @@ -1511,6 +1756,24 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasip2" +version = "1.0.2+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "wasm" version = "0.1.0" @@ -1564,6 +1827,40 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap", + "semver", +] + [[package]] name = "web-sys" version = "0.3.85" @@ -1702,6 +1999,94 @@ dependencies = [ "memchr", ] +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + [[package]] name = "zerocopy" version = "0.8.39" diff --git a/Cargo.toml b/Cargo.toml index ee80c46..2dcb021 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = [".", "crates/python", "crates/wasm", "crates/simulation", "crates/runtime-dashboard", "crates/distribution", "crates/simulation-dashboard"] +members = [".", "crates/python", "crates/wasm", "crates/simulation", "crates/runtime-dashboard", "crates/distribution", "crates/simulation-dashboard", "crates/std"] exclude = ["tools/depgraph"] [package] @@ -32,6 +32,9 @@ crossbeam-utils = "0.8.21" [dev-dependencies] criterion = { version = "0.5", features = ["html_reports"] } +proptest = "1" +proptest-state-machine = "0.3" +swactor-std = { path = "crates/std" } [[bench]] name = "runtime_benchmarks" @@ -41,6 +44,10 @@ harness = false name = "mt_benchmarks" harness = false +[[bench]] +name = "hasher_benchmarks" +harness = false + [[example]] name = "tcp_ping_pong" required-features = ["transport"] diff --git a/benches/hasher_benchmarks.rs b/benches/hasher_benchmarks.rs new file mode 100644 index 0000000..271104a --- /dev/null +++ b/benches/hasher_benchmarks.rs @@ -0,0 +1,164 @@ +use criterion::{criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion}; +use std::collections::HashMap; +use std::hash::{BuildHasher, Hash, Hasher}; +use swactor::actor::ActorAddress; + +// ─── Reproduce the identity hasher for benchmarking ───────────────────────── +// (The real one is pub(crate) in delivery.rs — recreate here for bench access) + +struct AddrHasher(u64); + +impl Hasher for AddrHasher { + #[inline] + fn finish(&self) -> u64 { + self.0 + } + + #[inline] + fn write(&mut self, _bytes: &[u8]) {} + + #[inline] + fn write_u64(&mut self, i: u64) { + self.0 = i; + } +} + +#[derive(Default, Clone)] +struct AddrBuildHasher; + +impl BuildHasher for AddrBuildHasher { + type Hasher = AddrHasher; + #[inline] + fn build_hasher(&self) -> AddrHasher { + AddrHasher(0) + } +} + +// ─── Helpers ──────────────────────────────────────────────────────────────── + +fn random_addresses(n: usize) -> Vec { + (0..n).map(|_| ActorAddress::new_random()).collect() +} + +// ─── Hash benchmarks ──────────────────────────────────────────────────────── + +fn bench_hash(c: &mut Criterion) { + let mut group = c.benchmark_group("hash"); + + let addr = ActorAddress::new_random(); + + // Default hasher (SipHash) — hashes all 32 bytes via derived Hash, + // but our custom Hash impl only writes 8 bytes + group.bench_function("siphash_custom_hash", |b| { + b.iter(|| { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + addr.hash(&mut hasher); + std::hint::black_box(hasher.finish()) + }) + }); + + // Identity hasher — reads the u64 from our custom Hash impl directly + group.bench_function("identity", |b| { + b.iter(|| { + let mut hasher = AddrHasher(0); + addr.hash(&mut hasher); + std::hint::black_box(hasher.finish()) + }) + }); + + group.finish(); +} + +// ─── Lookup benchmarks ───────────────────────────────────────────────────── + +fn bench_lookup(c: &mut Criterion) { + let mut group = c.benchmark_group("lookup"); + + for &size in &[100, 1000] { + let addrs = random_addresses(size); + let lookup_targets: Vec = addrs.iter().cloned().collect(); + + // SipHash HashMap (but with our custom 8-byte Hash impl) + let sip_map: HashMap = + addrs.iter().enumerate().map(|(i, a)| (*a, i)).collect(); + + group.bench_with_input( + BenchmarkId::new("siphash", size), + &size, + |b, _| { + let mut idx = 0; + b.iter(|| { + let addr = &lookup_targets[idx % lookup_targets.len()]; + idx += 1; + std::hint::black_box(sip_map.get(addr)) + }) + }, + ); + + // Identity HashMap + let identity_map: HashMap = { + let mut m = HashMap::with_capacity_and_hasher(size, AddrBuildHasher); + for (i, a) in addrs.iter().enumerate() { + m.insert(*a, i); + } + m + }; + + group.bench_with_input( + BenchmarkId::new("identity", size), + &size, + |b, _| { + let mut idx = 0; + b.iter(|| { + let addr = &lookup_targets[idx % lookup_targets.len()]; + idx += 1; + std::hint::black_box(identity_map.get(addr)) + }) + }, + ); + } + + group.finish(); +} + +// ─── Insert benchmarks ───────────────────────────────────────────────────── + +fn bench_insert(c: &mut Criterion) { + let mut group = c.benchmark_group("insert"); + + let addrs = random_addresses(1000); + + group.bench_function("siphash", |b| { + b.iter_batched( + || addrs.clone(), + |addrs| { + let mut m: HashMap = HashMap::with_capacity(addrs.len()); + for (i, a) in addrs.iter().enumerate() { + m.insert(*a, i); + } + std::hint::black_box(m.len()) + }, + BatchSize::SmallInput, + ) + }); + + group.bench_function("identity", |b| { + b.iter_batched( + || addrs.clone(), + |addrs| { + let mut m: HashMap = + HashMap::with_capacity_and_hasher(addrs.len(), AddrBuildHasher); + for (i, a) in addrs.iter().enumerate() { + m.insert(*a, i); + } + std::hint::black_box(m.len()) + }, + BatchSize::SmallInput, + ) + }); + + group.finish(); +} + +criterion_group!(benches, bench_hash, bench_lookup, bench_insert); +criterion_main!(benches); diff --git a/benches/mt_benchmarks.rs b/benches/mt_benchmarks.rs index 2d7979a..12c0a1c 100644 --- a/benches/mt_benchmarks.rs +++ b/benches/mt_benchmarks.rs @@ -22,6 +22,7 @@ fn mt_config(threads: usize, max_actors: usize, max_messages: usize) -> RuntimeC sleep_increment_us: 10, sleep_max_us: 100, }, + ..Default::default() } } diff --git a/benches/runtime_benchmarks.rs b/benches/runtime_benchmarks.rs index 06ad48b..57fa122 100644 --- a/benches/runtime_benchmarks.rs +++ b/benches/runtime_benchmarks.rs @@ -1,11 +1,13 @@ use criterion::{ criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion, Throughput, }; +use std::sync::Arc; use swactor::{ actor::{ActorAddress, ActorInterface}, config::RuntimeConfig, runtime::{Ctx, Runtime}, }; +use swactor_std::{RuntimeGroups, RuntimeNaming, StdExtension}; // --------------------------------------------------------------------------- // Helper @@ -272,5 +274,462 @@ fn throughput_benchmarks(c: &mut Criterion) { group.finish(); } -criterion_group!(benches, latency_benchmarks, throughput_benchmarks); +// --------------------------------------------------------------------------- +// Fairness benchmarks +// --------------------------------------------------------------------------- + +fn fairness_benchmarks(c: &mut Criterion) { + let mut group = c.benchmark_group("fairness"); + + // F1 — Cold-actor latency under hot-actor pressure + // Measures how quickly a cold actor responds when a hot actor has a full mailbox + for hot_msgs in [100, 1_000, 10_000] { + group.bench_with_input( + BenchmarkId::new("cold_latency_under_pressure", hot_msgs), + &hot_msgs, + |b, &hot_msgs| { + b.iter_batched( + || { + let rt = Runtime::new(RuntimeConfig { + max_actors: 100, + channel_buffer_size: hot_msgs + 100, + num_threads: 1, + ..Default::default() + }); + let hot_addr = rt.spawn(SinkActor).unwrap(); + let cold_addr = rt.spawn(EchoActor).unwrap(); + rt.tick(); // register actors + + // Load hot actor + for i in 0..hot_msgs { + rt.send_to(hot_addr, CountMessage(i as u64)).unwrap(); + } + + let inbox = rt.new_inbox::().unwrap(); + let inbox_addr = *inbox.addr(); + (rt, cold_addr, inbox, inbox_addr) + }, + |(rt, cold_addr, inbox, inbox_addr)| { + // Send to cold actor and measure ticks until reply + rt.send_to(cold_addr, PingMessage { reply_to: inbox_addr }).unwrap(); + for _ in 0..200 { + rt.tick(); + if inbox.try_recv().is_some() { + return; + } + } + panic!("Cold actor did not respond"); + }, + BatchSize::SmallInput, + ); + }, + ); + } + + // F2 — Total throughput with budget vs without (ensures budget doesn't kill throughput) + for budget in [0usize, 32, 64, 128] { + let label = if budget == 0 { "unlimited".to_string() } else { format!("{budget}") }; + group.throughput(Throughput::Elements(10_000)); + group.bench_with_input( + BenchmarkId::new("throughput_by_budget", &label), + &budget, + |b, &budget| { + b.iter_batched( + || { + let rt = Runtime::new(RuntimeConfig { + max_actors: 200, + channel_buffer_size: 11_000, + num_threads: 1, + actor_message_budget: budget, + ..Default::default() + }); + let mut addrs = Vec::new(); + for _ in 0..10 { + addrs.push(rt.spawn(SinkActor).unwrap()); + } + rt.tick(); + for &addr in &addrs { + for i in 0..1_000 { + rt.send_to(addr, CountMessage(i as u64)).unwrap(); + } + } + rt + }, + |rt| { + for _ in 0..500 { + rt.tick(); + } + }, + BatchSize::LargeInput, + ); + }, + ); + } + + group.finish(); +} + +// --------------------------------------------------------------------------- +// Message size sensitivity benchmarks +// --------------------------------------------------------------------------- + +/// Payload message of configurable size +#[derive(Clone)] +struct SizedMessage { + _payload: Vec, +} + +struct SizedSinkActor; + +impl ActorInterface for SizedSinkActor { + type Incoming = SizedMessage; + type Response = (); + fn handle(&mut self, _ctx: &Ctx, _msg: SizedMessage) {} +} + +fn message_size_benchmarks(c: &mut Criterion) { + let mut group = c.benchmark_group("msg_size"); + + // Throughput sensitivity to message size (8B, 64B, 256B, 1KB, 4KB) + for size in [8usize, 64, 256, 1024, 4096] { + let n = 10_000usize; + group.throughput(Throughput::Bytes((n * size) as u64)); + group.bench_with_input( + BenchmarkId::new("throughput", format!("{size}B")), + &size, + |b, &size| { + b.iter_batched( + || { + let rt = Runtime::new(make_config(100, n + 100)); + let addr = rt.spawn(SizedSinkActor).unwrap(); + rt.tick(); + let msg = SizedMessage { _payload: vec![0u8; size] }; + for _ in 0..n { + rt.send_to(addr, msg.clone()).unwrap(); + } + rt + }, + |rt| { + for _ in 0..500 { + rt.tick(); + } + }, + BatchSize::LargeInput, + ); + }, + ); + } + + // Send latency sensitivity to message size + for size in [8usize, 64, 256, 1024, 4096] { + group.bench_with_input( + BenchmarkId::new("send_latency", format!("{size}B")), + &size, + |b, &size| { + b.iter_batched( + || { + let rt = Runtime::new(make_config(100, 100_000)); + let addr = rt.spawn(SizedSinkActor).unwrap(); + rt.tick(); + let msg = SizedMessage { _payload: vec![0u8; size] }; + (rt, addr, msg) + }, + |(rt, addr, msg)| { + rt.send_to(addr, msg).unwrap(); + }, + BatchSize::SmallInput, + ); + }, + ); + } + + group.finish(); +} + +// --------------------------------------------------------------------------- +// Contention benchmarks (many-to-one fanin) +// --------------------------------------------------------------------------- + +fn contention_benchmarks(c: &mut Criterion) { + let mut group = c.benchmark_group("contention"); + + // Many actors sending to one sink (fanin pattern) + for num_senders in [1usize, 10, 50, 100] { + let msgs_per_sender = 100usize; + let total = num_senders * msgs_per_sender; + group.throughput(Throughput::Elements(total as u64)); + group.bench_with_input( + BenchmarkId::new("fanin", format!("{num_senders}_senders")), + &num_senders, + |b, &num_senders| { + b.iter_batched( + || { + let rt = Runtime::new(RuntimeConfig { + max_actors: num_senders + 100, + channel_buffer_size: total + 100, + num_threads: 1, + ..Default::default() + }); + let sink = rt.spawn(SinkActor).unwrap(); + // Create sender actors that forward to the sink + let senders: Vec<_> = (0..num_senders) + .map(|_| rt.spawn(NoopActor).unwrap()) + .collect(); + rt.tick(); // register all actors + + // Each "sender" just contributes messages aimed at the sink + for _ in &senders { + for i in 0..msgs_per_sender { + rt.send_to(sink, CountMessage(i as u64)).unwrap(); + } + } + rt + }, + |rt| { + for _ in 0..200 { + rt.tick(); + } + }, + BatchSize::LargeInput, + ); + }, + ); + } + + // Cross-worker vs same-worker delivery comparison + for num_threads in [1usize, 2, 4] { + let n = 10_000usize; + group.throughput(Throughput::Elements(n as u64)); + group.bench_with_input( + BenchmarkId::new("cross_worker", format!("{num_threads}t")), + &num_threads, + |b, &num_threads| { + b.iter_custom(|iters| { + let total = iters as usize * n; + let rt = Runtime::new(RuntimeConfig { + num_threads, + max_actors: 100, + channel_buffer_size: total + 1024, + ..Default::default() + }); + let inbox = rt.new_inbox::().unwrap(); + let addr = rt.spawn(EchoActor).unwrap(); + for _ in 0..total { + rt.send_to(addr, PingMessage { reply_to: *inbox.addr() }).unwrap(); + } + if num_threads < 2 { + let start = std::time::Instant::now(); + for _ in 0..(total * 2) { + rt.tick(); + } + start.elapsed() + } else { + let start = std::time::Instant::now(); + let handle = rt.run().unwrap(); + let mut received = 0u64; + let deadline = std::time::Instant::now() + + std::time::Duration::from_secs(30); + while received < iters { + if inbox.try_recv().is_some() { + received += 1; + } else if std::time::Instant::now() > deadline { + panic!("Timed out"); + } else { + std::hint::spin_loop(); + } + } + let elapsed = start.elapsed(); + handle.shutdown(); + handle.join(); + elapsed + } + }); + }, + ); + } + + group.finish(); +} + +// --------------------------------------------------------------------------- +// Placement benchmarks — measure spawn distribution quality under load +// --------------------------------------------------------------------------- + +fn placement_benchmarks(c: &mut Criterion) { + let mut group = c.benchmark_group("placement"); + group.sample_size(20); + + // Measure spawn+process throughput under imbalanced load across workers + for &num_threads in &[2, 4] { + group.bench_with_input( + BenchmarkId::new("spawn_under_load", num_threads), + &num_threads, + |b, &threads| { + b.iter_custom(|iters| { + let rt = Runtime::new(RuntimeConfig { + num_threads: threads, + ..Default::default() + }); + + // Pre-spawn some actors and send them messages to create load + let mut addrs = Vec::new(); + for _ in 0..20 { + addrs.push(rt.spawn(NoopActor).unwrap()); + } + let handle = rt.run().unwrap(); + + // Create imbalanced load: flood first few actors + for addr in &addrs[..5] { + for _ in 0..200 { + let _ = handle.runtime.send_to(*addr, NoopMessage); + } + } + std::thread::sleep(std::time::Duration::from_millis(5)); + + // Now measure spawning new actors under this load + let start = std::time::Instant::now(); + for _ in 0..iters { + let _ = handle.runtime.spawn(NoopActor); + } + let elapsed = start.elapsed(); + + handle.shutdown(); + handle.join(); + elapsed + }); + }, + ); + } + + group.finish(); +} + +// --------------------------------------------------------------------------- +// Registry benchmarks — named actors, groups, monitors, ask +// --------------------------------------------------------------------------- + +fn registry_benchmarks(c: &mut Criterion) { + let mut group = c.benchmark_group("registry"); + + // R1 — Named spawn + lookup roundtrip + group.bench_function("named_spawn_lookup", |b| { + let mut counter = 0u64; + b.iter_batched( + || { + counter += 1; + let rt = Runtime::new(make_config(1_000, 1_000)) + .with_extension(Arc::new(StdExtension::new())); + (rt, counter) + }, + |(rt, i)| { + let name = format!("actor-{i}"); + let addr = rt.spawn_named(&name, NoopActor).unwrap(); + let found = rt.where_is(&name); + assert_eq!(found, Some(addr)); + }, + BatchSize::SmallInput, + ); + }); + + // R2 — where_is lookup latency (populated registry) + group.bench_function("where_is_100_names", |b| { + b.iter_batched( + || { + let rt = Runtime::new(make_config(1_000, 1_000)) + .with_extension(Arc::new(StdExtension::new())); + for i in 0..100 { + rt.spawn_named(format!("actor-{i}"), NoopActor).unwrap(); + } + rt + }, + |rt| { + // Lookup a name in the middle + rt.where_is("actor-50"); + }, + BatchSize::SmallInput, + ); + }); + + // R3 — Group join + publish broadcast + for members in [10, 50, 100] { + group.throughput(Throughput::Elements(members as u64)); + group.bench_with_input( + BenchmarkId::new("group_publish", members), + &members, + |b, &members| { + b.iter_batched( + || { + let rt = Runtime::new(make_config(members + 100, members * 10)) + .with_extension(Arc::new(StdExtension::new())); + for _ in 0..members { + let addr = rt.spawn(SinkActor).unwrap(); + rt.join_group(addr, "bench-group"); + } + rt.tick(); + rt + }, + |rt| { + rt.publish_to("bench-group", CountMessage(42)); + }, + BatchSize::SmallInput, + ); + }, + ); + } + + // R4 — Monitor setup + teardown + group.bench_function("monitor_setup", |b| { + b.iter_batched( + || { + let rt = Runtime::new(make_config(1_000, 1_000)); + let target = rt.spawn(NoopActor).unwrap(); + rt.tick(); + (rt, target) + }, + |(rt, target)| { + use swactor::actor::Down; + let inbox = rt.new_inbox::().unwrap(); + // We can't call ctx.monitor from outside, but we can benchmark + // the registry operations indirectly via spawn+stop+tick + let _ = inbox.addr(); + let _ = rt.stop_actor(target); + }, + BatchSize::SmallInput, + ); + }); + + // R5 — Ask pattern roundtrip + group.bench_function("ask_roundtrip", |b| { + b.iter_batched( + || { + let rt = Runtime::new(make_config(1_000, 1_000)); + let addr = rt.spawn(EchoActor).unwrap(); + rt.tick(); + (rt, addr) + }, + |(rt, addr)| { + let resp = rt + .ask::(addr, |reply_to| PingMessage { reply_to }) + .unwrap() + .recv_ticking(&rt, 10) + .unwrap(); + std::hint::black_box(resp); + }, + BatchSize::SmallInput, + ); + }); + + group.finish(); +} + +criterion_group!( + benches, + latency_benchmarks, + throughput_benchmarks, + fairness_benchmarks, + message_size_benchmarks, + contention_benchmarks, + placement_benchmarks, + registry_benchmarks, +); criterion_main!(benches); diff --git a/crates/python/src/lib.rs b/crates/python/src/lib.rs index ce41d43..25a95d5 100644 --- a/crates/python/src/lib.rs +++ b/crates/python/src/lib.rs @@ -282,6 +282,7 @@ impl From for RuntimeConfig { sleep_increment_us: py.sleep_increment_us, sleep_max_us: py.sleep_max_us, }, + ..Default::default() } } } diff --git a/crates/runtime-dashboard/examples/bench_dashboard.rs b/crates/runtime-dashboard/examples/bench_dashboard.rs index a227b9b..aef4283 100644 --- a/crates/runtime-dashboard/examples/bench_dashboard.rs +++ b/crates/runtime-dashboard/examples/bench_dashboard.rs @@ -87,6 +87,7 @@ fn bench_config(threads: usize, max_actors: usize, max_messages: usize) -> Runti sleep_increment_us: 10, sleep_max_us: 100, }, + ..Default::default() } } diff --git a/crates/std/Cargo.toml b/crates/std/Cargo.toml new file mode 100644 index 0000000..99e4b2a --- /dev/null +++ b/crates/std/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "swactor-std" +version = "0.1.0" +edition = "2024" + +[features] +default = ["getrandom"] +getrandom = ["dep:getrandom"] + +[dependencies] +swactor = { path = "../.." } +getrandom = { version = "0.2", optional = true } diff --git a/crates/std/src/ctx_ext.rs b/crates/std/src/ctx_ext.rs new file mode 100644 index 0000000..4db2b15 --- /dev/null +++ b/crates/std/src/ctx_ext.rs @@ -0,0 +1,113 @@ +use swactor::actor::{ActorAddress, ActorInterface, Ctx, Message, MonitorRef}; +use swactor::Error; + +use crate::StdExtension; + +fn get_ext<'a>(ctx: &'a Ctx) -> &'a StdExtension { + ctx.extension() + .expect("StdExtension not installed — use Runtime::with_extension()") + .as_any() + .downcast_ref::() + .expect("Extension is not StdExtension") +} + +/// Monitoring extension for [`Ctx`]. +/// +/// Provides `monitor` / `demonitor` via the [`StdExtension`] monitor registry. +pub trait CtxMonitoring { + /// Subscribe to death notifications from `target`. Returns a [`MonitorRef`] + /// that can be used to cancel the subscription. + fn monitor(&self, target: ActorAddress) -> MonitorRef; + + /// Cancel a monitor subscription. + fn demonitor(&self, mref: MonitorRef); +} + +impl CtxMonitoring for Ctx<'_> { + fn monitor(&self, target: ActorAddress) -> MonitorRef { + get_ext(self).monitor_registry.register(self.self_addr(), target) + } + + fn demonitor(&self, mref: MonitorRef) { + get_ext(self).monitor_registry.deregister(mref); + } +} + +/// Naming extension for [`Ctx`]. +/// +/// Provides `where_is`, `register_name`, and `spawn_named` via the [`StdExtension`] +/// name registry. +pub trait CtxNaming { + /// Look up an actor address by its registered name. + fn where_is(&self, name: &str) -> Option; + + /// Register a name for the given address. + fn register_name(&self, name: impl Into, addr: ActorAddress) -> Result<(), Error>; + + /// Spawn an actor with a registered name, returning its address. + fn spawn_named(&self, name: impl Into, actor: A) -> Result; +} + +impl CtxNaming for Ctx<'_> { + fn where_is(&self, name: &str) -> Option { + get_ext(self).name_registry.lookup(name) + } + + fn register_name(&self, name: impl Into, addr: ActorAddress) -> Result<(), Error> { + get_ext(self).name_registry.register(name.into(), addr) + } + + fn spawn_named(&self, name: impl Into, actor: A) -> Result { + let name = name.into(); + let addr = self.spawn(actor)?; + if let Err(e) = get_ext(self).name_registry.register(name, addr) { + let _ = self.stop_actor(addr); + return Err(e); + } + Ok(addr) + } +} + +/// Group extension for [`Ctx`]. +/// +/// Provides `join_group`, `leave_group`, `publish`, and `group_members` via +/// the [`StdExtension`] group registry. +pub trait CtxGroups { + /// Add this actor to a named group. + fn join_group(&self, group: impl Into); + + /// Remove this actor from a named group. + fn leave_group(&self, group: &str); + + /// Broadcast a message to all members of a named group. + /// Returns the number of messages successfully enqueued. + fn publish(&self, group: &str, msg: M) -> usize; + + /// Return all members of a named group. + fn group_members(&self, group: &str) -> Vec; +} + +impl CtxGroups for Ctx<'_> { + fn join_group(&self, group: impl Into) { + get_ext(self).group_registry.join(group.into(), self.self_addr()); + } + + fn leave_group(&self, group: &str) { + get_ext(self).group_registry.leave(group, &self.self_addr()); + } + + fn publish(&self, group: &str, msg: M) -> usize { + let members = get_ext(self).group_registry.members(group); + let mut count = 0; + for member in &members { + if self.send(*member, msg.clone()).is_ok() { + count += 1; + } + } + count + } + + fn group_members(&self, group: &str) -> Vec { + get_ext(self).group_registry.members(group) + } +} diff --git a/crates/std/src/extension.rs b/crates/std/src/extension.rs new file mode 100644 index 0000000..fa7d20c --- /dev/null +++ b/crates/std/src/extension.rs @@ -0,0 +1,62 @@ +use std::any::Any; + +use swactor::actor::{ActorAddress, Down, StopReason}; +use swactor::extension::RuntimeExtension; + +use crate::group_registry::GroupRegistry; +use crate::monitor_registry::MonitorRegistry; +use crate::name_registry::NameRegistry; + +/// Standard library extension — provides naming, monitoring, and group registries. +/// +/// Install on a `Runtime` via `runtime.with_extension(Arc::new(StdExtension::new()))`. +pub struct StdExtension { + pub(crate) name_registry: NameRegistry, + pub(crate) monitor_registry: MonitorRegistry, + pub(crate) group_registry: GroupRegistry, +} + +impl StdExtension { + pub fn new() -> Self { + Self { + name_registry: NameRegistry::new(), + monitor_registry: MonitorRegistry::new(), + group_registry: GroupRegistry::new(), + } + } +} + +impl Default for StdExtension { + fn default() -> Self { + Self::new() + } +} + +impl RuntimeExtension for StdExtension { + fn on_actor_death( + &self, + dead: &[(ActorAddress, StopReason)], + ) -> Vec<(ActorAddress, Box)> { + let mut notifications = Vec::new(); + for &(addr, reason) in dead { + let watchers = self.monitor_registry.take_monitors(&addr); + for (_mref, watcher) in watchers { + let down = Down { addr, reason }; + notifications.push((watcher, Box::new(down) as Box)); + } + } + notifications + } + + fn cleanup_dead(&self, dead: &[ActorAddress]) { + for addr in dead { + self.name_registry.unregister_by_addr(addr); + self.group_registry.cleanup(addr); + self.monitor_registry.remove_watcher(addr); + } + } + + fn as_any(&self) -> &dyn Any { + self + } +} diff --git a/crates/std/src/group_registry.rs b/crates/std/src/group_registry.rs new file mode 100644 index 0000000..5b2ee9b --- /dev/null +++ b/crates/std/src/group_registry.rs @@ -0,0 +1,81 @@ +use std::collections::{HashMap, HashSet}; +use std::sync::RwLock; + +use swactor::actor::ActorAddress; +use swactor::{AddrBuildHasher, AddrMap, AddrSet}; + +/// Actor groups (pub-sub). Actors join/leave named groups; messages can be +/// broadcast to all members of a group. +/// +/// Groups are created lazily on first join and removed when empty. +pub struct GroupRegistry { + /// group_name → set of member addresses + groups: RwLock>, + /// actor_addr → set of group names (reverse map for O(G) cleanup on death) + memberships: RwLock>>, +} + +impl GroupRegistry { + pub fn new() -> Self { + Self { + groups: RwLock::new(HashMap::new()), + memberships: RwLock::new(HashMap::with_hasher(AddrBuildHasher)), + } + } + + /// Add an actor to a named group. Group is created if it doesn't exist. + pub fn join(&self, group: String, addr: ActorAddress) { + self.groups.write().unwrap() + .entry(group.clone()) + .or_insert_with(|| HashSet::with_hasher(AddrBuildHasher)) + .insert(addr); + self.memberships.write().unwrap() + .entry(addr) + .or_default() + .insert(group); + } + + /// Remove an actor from a named group. Empty groups are auto-deleted. + pub fn leave(&self, group: &str, addr: &ActorAddress) { + let mut groups = self.groups.write().unwrap(); + if let Some(members) = groups.get_mut(group) { + members.remove(addr); + if members.is_empty() { + groups.remove(group); + } + } + drop(groups); + if let Some(membership) = self.memberships.write().unwrap().get_mut(addr) { + membership.remove(group); + } + } + + /// Return all members of a group. + pub fn members(&self, group: &str) -> Vec { + self.groups.read().unwrap() + .get(group) + .map(|s| s.iter().copied().collect()) + .unwrap_or_default() + } + + /// Remove a dead actor from all its groups. + pub fn cleanup(&self, addr: &ActorAddress) { + let group_names = self.memberships.write().unwrap().remove(addr); + if let Some(names) = group_names { + let mut groups = self.groups.write().unwrap(); + for name in names { + if let Some(members) = groups.get_mut(&name) { + members.remove(addr); + if members.is_empty() { + groups.remove(&name); + } + } + } + } + } + + /// Return all active group names. + pub fn group_names(&self) -> Vec { + self.groups.read().unwrap().keys().cloned().collect() + } +} diff --git a/crates/std/src/lib.rs b/crates/std/src/lib.rs new file mode 100644 index 0000000..3481957 --- /dev/null +++ b/crates/std/src/lib.rs @@ -0,0 +1,14 @@ +mod supervisor; +mod router; +pub mod name_registry; +pub mod monitor_registry; +pub mod group_registry; +mod extension; +mod ctx_ext; +mod runtime_ext; + +pub use supervisor::{ChildSpec, RestartPolicy, Supervisor, SupervisorStrategy}; +pub use router::{Router, RoutingStrategy}; +pub use extension::StdExtension; +pub use ctx_ext::{CtxMonitoring, CtxNaming, CtxGroups}; +pub use runtime_ext::{RuntimeNaming, RuntimeGroups}; diff --git a/crates/std/src/monitor_registry.rs b/crates/std/src/monitor_registry.rs new file mode 100644 index 0000000..9a0b848 --- /dev/null +++ b/crates/std/src/monitor_registry.rs @@ -0,0 +1,79 @@ +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::RwLock; + +use swactor::actor::{ActorAddress, MonitorRef}; +use swactor::{AddrBuildHasher, AddrMap}; + +/// Tracks monitor subscriptions: watched actor → list of (MonitorRef, watcher address). +/// +/// Write-rare (monitor/demonitor/death), read at cleanup time. +pub struct MonitorRegistry { + /// watched_addr → [(mref, watcher_addr)] + monitors: RwLock>>, + /// mref → watched_addr (for O(1) demonitor) + ref_to_target: RwLock>, + next_ref: AtomicU64, +} + +impl MonitorRegistry { + pub fn new() -> Self { + Self { + monitors: RwLock::new(HashMap::with_hasher(AddrBuildHasher)), + ref_to_target: RwLock::new(HashMap::new()), + next_ref: AtomicU64::new(1), + } + } + + /// Register a monitor: `watcher` wants to know when `target` dies. + pub fn register(&self, watcher: ActorAddress, target: ActorAddress) -> MonitorRef { + let id = self.next_ref.fetch_add(1, Ordering::Relaxed); + let mref = MonitorRef::from_raw(id); + self.monitors.write().unwrap() + .entry(target) + .or_default() + .push((mref, watcher)); + self.ref_to_target.write().unwrap().insert(mref, target); + mref + } + + /// Cancel a monitor by its ref. + pub fn deregister(&self, mref: MonitorRef) { + if let Some(target) = self.ref_to_target.write().unwrap().remove(&mref) { + let mut monitors = self.monitors.write().unwrap(); + if let Some(watchers) = monitors.get_mut(&target) { + watchers.retain(|(r, _)| *r != mref); + if watchers.is_empty() { + monitors.remove(&target); + } + } + } + } + + /// Remove and return all monitors for a dead actor. + pub fn take_monitors(&self, target: &ActorAddress) -> Vec<(MonitorRef, ActorAddress)> { + let watchers = self.monitors.write().unwrap().remove(target).unwrap_or_default(); + let mut ref_map = self.ref_to_target.write().unwrap(); + for (mref, _) in &watchers { + ref_map.remove(mref); + } + watchers + } + + /// Remove all monitor subscriptions where `addr` is the watcher (dead watcher cleanup). + pub fn remove_watcher(&self, addr: &ActorAddress) { + let mut monitors = self.monitors.write().unwrap(); + let mut ref_map = self.ref_to_target.write().unwrap(); + monitors.retain(|_target, watchers| { + watchers.retain(|(mref, watcher)| { + if watcher == addr { + ref_map.remove(mref); + false + } else { + true + } + }); + !watchers.is_empty() + }); + } +} diff --git a/crates/std/src/name_registry.rs b/crates/std/src/name_registry.rs new file mode 100644 index 0000000..3b1cc0f --- /dev/null +++ b/crates/std/src/name_registry.rs @@ -0,0 +1,59 @@ +use std::collections::HashMap; +use std::sync::RwLock; + +use swactor::actor::ActorAddress; +use swactor::{AddrBuildHasher, AddrMap}; + +/// Named actor registry — maps human-readable names to actor addresses. +/// +/// `RwLock` — same pattern as `AddressMap`. Write-rare (spawn/death), +/// read-often (lookup). A reverse map enables O(1) cleanup on actor death. +pub struct NameRegistry { + names: RwLock>, + reverse: RwLock>, +} + +impl NameRegistry { + pub fn new() -> Self { + Self { + names: RwLock::new(HashMap::new()), + reverse: RwLock::new(HashMap::with_hasher(AddrBuildHasher)), + } + } + + /// Register a name → address mapping. Returns `Err` if the name is already taken. + pub fn register(&self, name: String, addr: ActorAddress) -> Result<(), swactor::Error> { + let mut names = self.names.write().unwrap(); + if names.contains_key(&name) { + return Err(swactor::Error::from("Name already registered")); + } + names.insert(name.clone(), addr); + drop(names); + self.reverse.write().unwrap().insert(addr, name); + Ok(()) + } + + /// Look up an actor address by name. + pub fn lookup(&self, name: &str) -> Option { + self.names.read().unwrap().get(name).copied() + } + + /// Unregister a name, returning the address it was bound to. + pub fn unregister(&self, name: &str) -> Option { + let addr = self.names.write().unwrap().remove(name)?; + self.reverse.write().unwrap().remove(&addr); + Some(addr) + } + + /// Remove a name by address (called on actor death for auto-cleanup). + pub fn unregister_by_addr(&self, addr: &ActorAddress) { + if let Some(name) = self.reverse.write().unwrap().remove(addr) { + self.names.write().unwrap().remove(&name); + } + } + + /// Return all registered names. + pub fn registered_names(&self) -> Vec { + self.names.read().unwrap().keys().cloned().collect() + } +} diff --git a/crates/std/src/router.rs b/crates/std/src/router.rs new file mode 100644 index 0000000..c0d2f89 --- /dev/null +++ b/crates/std/src/router.rs @@ -0,0 +1,169 @@ +use std::marker::PhantomData; +use std::sync::Arc; + +use swactor::actor::{ActorAddress, ActorInterface, Ctx, Down, Message}; +use swactor::Error; + +use crate::supervisor::ActiveChild; +use crate::CtxMonitoring; + +/// Strategy for distributing messages across pool workers. +#[derive(Debug, Clone)] +pub enum RoutingStrategy { + /// Sequential round-robin distribution. + RoundRobin, + /// Random worker selection. + Random, + /// Send to all workers (message is cloned to each). + Broadcast, +} + +/// A router actor that manages a pool of identical workers and distributes +/// incoming messages across them according to a [`RoutingStrategy`]. +/// +/// Workers are spawned during `on_start`, monitored for failures, and +/// automatically replaced to maintain the target pool size. Meltdown +/// protection stops the router when total restarts exceed `max_restarts`. +/// +/// # Example +/// +/// ```ignore +/// let router = Router::new( +/// RoutingStrategy::RoundRobin, +/// 5, +/// |ctx| ctx.spawn(MyWorker::new()), +/// 10, +/// ); +/// let router_addr = rt.spawn(router)?; +/// rt.send_to(router_addr, WorkerMessage::DoWork(42))?; +/// ``` +pub struct Router { + strategy: RoutingStrategy, + pool_size: usize, + factory: Arc Result + Send + Sync>, + workers: Vec>, + rr_index: usize, + total_restarts: u32, + max_restarts: u32, + _marker: PhantomData, +} + +impl Router { + pub fn new( + strategy: RoutingStrategy, + pool_size: usize, + factory: impl Fn(&Ctx) -> Result + Send + Sync + 'static, + max_restarts: u32, + ) -> Self { + Self { + strategy, + pool_size, + factory: Arc::new(factory), + workers: (0..pool_size).map(|_| None).collect(), + rr_index: 0, + total_restarts: 0, + max_restarts, + _marker: PhantomData, + } + } + + fn start_worker(&mut self, ctx: &Ctx, idx: usize) -> Result<(), Error> { + let addr = (self.factory)(ctx)?; + let mref = ctx.monitor(addr); + self.workers[idx] = Some(ActiveChild { + addr, + _monitor_ref: mref, + }); + Ok(()) + } + + fn find_worker_idx(&self, addr: ActorAddress) -> Option { + self.workers + .iter() + .position(|w| w.as_ref().map_or(false, |ac| ac.addr == addr)) + } + + fn live_workers(&self) -> Vec { + self.workers + .iter() + .filter_map(|w| w.as_ref().map(|ac| ac.addr)) + .collect() + } + + fn select_one(&mut self) -> Option { + let live = self.live_workers(); + if live.is_empty() { + return None; + } + match self.strategy { + RoutingStrategy::RoundRobin => { + let idx = self.rr_index % live.len(); + self.rr_index = self.rr_index.wrapping_add(1); + Some(live[idx]) + } + RoutingStrategy::Random => { + let mut buf = [0u8; 8]; + getrandom::getrandom(&mut buf).expect("getrandom failed"); + let r = u64::from_ne_bytes(buf) as usize; + Some(live[r % live.len()]) + } + RoutingStrategy::Broadcast => None, // handled separately + } + } +} + +impl ActorInterface for Router { + type Incoming = M; + type Response = (); + + fn handle(&mut self, ctx: &Ctx, msg: M) { + match self.strategy { + RoutingStrategy::Broadcast => { + let live = self.live_workers(); + for addr in live { + let _ = ctx.send(addr, msg.clone()); + } + } + _ => { + if let Some(addr) = self.select_one() { + let _ = ctx.send(addr, msg); + } + } + } + } + + fn on_start(&mut self, ctx: &Ctx) { + for idx in 0..self.pool_size { + if let Err(e) = self.start_worker(ctx, idx) { + eprintln!("swactor: router failed to start worker {idx}: {e}"); + } + } + } + + fn on_stop(&mut self, ctx: &Ctx) { + for child in self.workers.iter().flatten() { + let _ = ctx.stop_actor(child.addr); + } + } + + fn handle_down(&mut self, ctx: &Ctx, down: Down) { + let Some(idx) = self.find_worker_idx(down.addr) else { + return; + }; + self.workers[idx] = None; + + self.total_restarts += 1; + if self.total_restarts > self.max_restarts { + eprintln!( + "swactor: router reached max restarts ({}), shutting down", + self.max_restarts + ); + ctx.stop_self(); + return; + } + + if let Err(e) = self.start_worker(ctx, idx) { + eprintln!("swactor: router failed to restart worker {idx}: {e}"); + } + } +} diff --git a/crates/std/src/runtime_ext.rs b/crates/std/src/runtime_ext.rs new file mode 100644 index 0000000..1f7ab67 --- /dev/null +++ b/crates/std/src/runtime_ext.rs @@ -0,0 +1,106 @@ +use swactor::actor::{ActorAddress, ActorInterface, Message}; +use swactor::runtime::Runtime; +use swactor::Error; + +use crate::StdExtension; + +fn get_ext(rt: &Runtime) -> &StdExtension { + rt.extension() + .expect("StdExtension not installed — use Runtime::with_extension()") + .as_any() + .downcast_ref::() + .expect("Extension is not StdExtension") +} + +/// Naming extension for [`Runtime`]. +/// +/// Provides `spawn_named`, `where_is`, `unregister`, and `registered_names` +/// via the [`StdExtension`] name registry. +pub trait RuntimeNaming { + /// Spawn an actor with a registered name, returning its address. + fn spawn_named(&self, name: impl Into, actor: A) -> Result; + + /// Look up an actor address by its registered name. + fn where_is(&self, name: &str) -> Option; + + /// Unregister a name. Returns the address it was bound to, or `None`. + fn unregister(&self, name: &str) -> Option; + + /// Return all currently registered actor names. + fn registered_names(&self) -> Vec; +} + +impl RuntimeNaming for Runtime { + fn spawn_named(&self, name: impl Into, actor: A) -> Result { + let name = name.into(); + let addr = self.spawn(actor)?; + if let Err(e) = get_ext(self).name_registry.register(name, addr) { + let _ = self.stop_actor(addr); + return Err(e); + } + Ok(addr) + } + + fn where_is(&self, name: &str) -> Option { + get_ext(self).name_registry.lookup(name) + } + + fn unregister(&self, name: &str) -> Option { + get_ext(self).name_registry.unregister(name) + } + + fn registered_names(&self) -> Vec { + get_ext(self).name_registry.registered_names() + } +} + +/// Group extension for [`Runtime`]. +/// +/// Provides `join_group`, `leave_group`, `publish_to`, `group_members`, +/// and `groups` via the [`StdExtension`] group registry. +pub trait RuntimeGroups { + /// Add an actor to a named group. The group is created if it doesn't exist. + fn join_group(&self, addr: ActorAddress, group: impl Into); + + /// Remove an actor from a named group. Empty groups are auto-deleted. + fn leave_group(&self, addr: ActorAddress, group: &str); + + /// Broadcast a message to all members of a named group. + /// Returns the number of messages successfully enqueued. + fn publish_to(&self, group: &str, msg: M) -> usize; + + /// Return all current members of a named group. + fn group_members(&self, group: &str) -> Vec; + + /// Return all active group names. + fn groups(&self) -> Vec; +} + +impl RuntimeGroups for Runtime { + fn join_group(&self, addr: ActorAddress, group: impl Into) { + get_ext(self).group_registry.join(group.into(), addr); + } + + fn leave_group(&self, addr: ActorAddress, group: &str) { + get_ext(self).group_registry.leave(group, &addr); + } + + fn publish_to(&self, group: &str, msg: M) -> usize { + let members = get_ext(self).group_registry.members(group); + let mut count = 0; + for member in &members { + if self.send_to(*member, msg.clone()).is_ok() { + count += 1; + } + } + count + } + + fn group_members(&self, group: &str) -> Vec { + get_ext(self).group_registry.members(group) + } + + fn groups(&self) -> Vec { + get_ext(self).group_registry.group_names() + } +} diff --git a/crates/std/src/supervisor.rs b/crates/std/src/supervisor.rs new file mode 100644 index 0000000..1d809ed --- /dev/null +++ b/crates/std/src/supervisor.rs @@ -0,0 +1,301 @@ +use std::sync::Arc; + +use swactor::actor::{ActorAddress, ActorInterface, Ctx, Down, MonitorRef, StopReason}; +use swactor::Error; + +use crate::CtxMonitoring; + +/// How a child should be restarted when it dies. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RestartPolicy { + /// Always restart, regardless of stop reason. + Permanent, + /// Restart only on abnormal exit (Panicked). Normal stops are final. + Transient, + /// Never restart. The child is removed on any exit. + Temporary, +} + +/// Strategy for handling child failures. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SupervisorStrategy { + /// Only restart the failed child. Other children are unaffected. + OneForOne, + /// Terminate all children and restart them all in spec order. + OneForAll, + /// Terminate children started after the failed child, then restart + /// the failed child and all terminated children in spec order. + RestForOne, +} + +/// Specification for a supervised child actor. +/// +/// The `start` closure is called with `&Ctx` and should spawn the child actor +/// (typically via `ctx.spawn()`). The supervisor monitors the returned address +/// and applies the restart policy when the child dies. +pub struct ChildSpec { + /// Unique identifier for this child. + pub id: String, + /// How to restart this child. + pub restart: RestartPolicy, + /// Factory to spawn the child. Called with `&Ctx`, returns the child's address. + pub start: Arc Result + Send + Sync>, +} + +impl ChildSpec { + pub fn new( + id: impl Into, + restart: RestartPolicy, + start: impl Fn(&Ctx) -> Result + Send + Sync + 'static, + ) -> Self { + Self { + id: id.into(), + restart, + start: Arc::new(start), + } + } +} + +/// Tracked state for an active child within a supervisor or router. +pub(crate) struct ActiveChild { + pub(crate) addr: ActorAddress, + pub(crate) _monitor_ref: MonitorRef, +} + +/// Internal phase for coordinating multi-child restart (OneForAll, RestForOne). +/// +/// In `Normal` phase, the supervisor processes Down messages and applies the strategy. +/// When a coordinated restart is needed, it transitions to `Stopping` (sends stop +/// signals, waits for Down confirmations) then restarts all affected children. +enum SupervisorPhase { + /// Normal operation — process Down messages and apply strategy. + Normal, + /// Waiting for children to confirm death before restarting. + Stopping { + /// Children we're still waiting for Down confirmation. + awaiting: Vec, + /// Spec indices to restart once all confirmations received. + restart_set: Vec, + }, +} + +/// A supervisor actor that manages child actors according to a restart strategy. +/// +/// Children are spawned during `on_start`. When a child dies, the supervisor +/// receives a [`Down`] notification via [`ActorInterface::handle_down`] and +/// applies the configured strategy and restart policy. +/// +/// # Strategies +/// +/// - **OneForOne**: Only the failed child is restarted. +/// - **OneForAll**: All children are stopped, then all restarted in spec order. +/// - **RestForOne**: The failed child and all children started after it are +/// stopped, then restarted in spec order. +/// +/// # Restart Intensity +/// +/// The supervisor tracks total restarts. When `total_restarts > max_restarts`, +/// the supervisor stops itself (meltdown protection), escalating the failure +/// to its own supervisor if one exists. +/// +/// # Example +/// +/// ```ignore +/// let sup = Supervisor::new( +/// SupervisorStrategy::OneForOne, +/// 5, // max 5 restarts before meltdown +/// vec![ +/// ChildSpec::new("worker", RestartPolicy::Permanent, |ctx| { +/// ctx.spawn(MyWorker::new()) +/// }), +/// ], +/// ); +/// let sup_addr = rt.spawn(sup)?; +/// ``` +pub struct Supervisor { + strategy: SupervisorStrategy, + max_restarts: u32, + specs: Vec, + children: Vec>, + total_restarts: u32, + phase: SupervisorPhase, +} + +impl Supervisor { + pub fn new( + strategy: SupervisorStrategy, + max_restarts: u32, + specs: Vec, + ) -> Self { + let children = (0..specs.len()).map(|_| None).collect(); + Self { + strategy, + max_restarts, + specs, + children, + total_restarts: 0, + phase: SupervisorPhase::Normal, + } + } + + fn start_child(&mut self, ctx: &Ctx, idx: usize) -> Result<(), Error> { + let addr = (self.specs[idx].start)(ctx)?; + let mref = ctx.monitor(addr); + self.children[idx] = Some(ActiveChild { + addr, + _monitor_ref: mref, + }); + Ok(()) + } + + fn find_child_idx(&self, addr: ActorAddress) -> Option { + self.children + .iter() + .position(|c| c.as_ref().map_or(false, |ac| ac.addr == addr)) + } + + /// Check meltdown intensity — returns true if we should stop. + fn check_intensity(&mut self) -> bool { + self.total_restarts += 1; + self.total_restarts > self.max_restarts + } + + /// Try to finish the coordinated restart: restart all children in `restart_set`. + fn finish_restart(&mut self, ctx: &Ctx) { + let restart_set = match &mut self.phase { + SupervisorPhase::Stopping { restart_set, .. } => { + std::mem::take(restart_set) + } + _ => return, + }; + self.phase = SupervisorPhase::Normal; + + for idx in restart_set { + if let Err(e) = self.start_child(ctx, idx) { + eprintln!( + "swactor: supervisor failed to restart child '{}': {}", + self.specs[idx].id, e + ); + } + } + } + + /// Begin a coordinated restart for the given spec indices. + /// Stops any living children in the set, then waits for their Down messages. + fn begin_coordinated_restart(&mut self, ctx: &Ctx, restart_indices: Vec) { + let mut awaiting = Vec::new(); + for &idx in &restart_indices { + if let Some(child) = self.children[idx].take() { + let _ = ctx.stop_actor(child.addr); + awaiting.push(child.addr); + } + } + + if awaiting.is_empty() { + // All children already dead — restart immediately. + for idx in &restart_indices { + if let Err(e) = self.start_child(ctx, *idx) { + eprintln!( + "swactor: supervisor failed to restart child '{}': {}", + self.specs[*idx].id, e + ); + } + } + } else { + self.phase = SupervisorPhase::Stopping { + awaiting, + restart_set: restart_indices, + }; + } + } +} + +impl ActorInterface for Supervisor { + type Incoming = (); + type Response = (); + + fn handle(&mut self, _ctx: &Ctx, _msg: ()) {} + + fn on_start(&mut self, ctx: &Ctx) { + for idx in 0..self.specs.len() { + if let Err(e) = self.start_child(ctx, idx) { + eprintln!( + "swactor: supervisor failed to start child '{}': {}", + self.specs[idx].id, e + ); + } + } + } + + fn on_stop(&mut self, ctx: &Ctx) { + for child in self.children.iter().flatten() { + let _ = ctx.stop_actor(child.addr); + } + } + + fn handle_down(&mut self, ctx: &Ctx, down: Down) { + // During coordinated restart: track Down confirmations. + if matches!(self.phase, SupervisorPhase::Stopping { .. }) { + // Clear from children tracking + if let Some(idx) = self.find_child_idx(down.addr) { + self.children[idx] = None; + } + // Remove from awaiting list + if let SupervisorPhase::Stopping { awaiting, .. } = &mut self.phase { + awaiting.retain(|a| *a != down.addr); + } + let done = matches!(&self.phase, + SupervisorPhase::Stopping { awaiting, .. } if awaiting.is_empty()); + if done { + self.finish_restart(ctx); + } + return; + } + + // Normal phase: handle child death. + let Some(idx) = self.find_child_idx(down.addr) else { + return; + }; + self.children[idx] = None; + + let should_restart = match self.specs[idx].restart { + RestartPolicy::Permanent => true, + RestartPolicy::Transient => down.reason == StopReason::Panicked, + RestartPolicy::Temporary => false, + }; + + if !should_restart { + return; + } + + if self.check_intensity() { + eprintln!( + "swactor: supervisor reached max restarts ({}), shutting down", + self.max_restarts + ); + ctx.stop_self(); + return; + } + + match self.strategy { + SupervisorStrategy::OneForOne => { + if let Err(e) = self.start_child(ctx, idx) { + eprintln!( + "swactor: supervisor failed to restart child '{}': {}", + self.specs[idx].id, e + ); + } + } + SupervisorStrategy::OneForAll => { + // Stop all other living children, then restart all in order. + let restart_indices: Vec = (0..self.specs.len()).collect(); + self.begin_coordinated_restart(ctx, restart_indices); + } + SupervisorStrategy::RestForOne => { + // Stop children after the failed one, then restart failed + rest. + let restart_indices: Vec = (idx..self.specs.len()).collect(); + self.begin_coordinated_restart(ctx, restart_indices); + } + } + } +} diff --git a/docs/development_history/cfuzz/CFUZZ_OVERVIEW.md b/docs/development_history/cfuzz/CFUZZ_OVERVIEW.md new file mode 100644 index 0000000..5139a2e --- /dev/null +++ b/docs/development_history/cfuzz/CFUZZ_OVERVIEW.md @@ -0,0 +1,95 @@ +# cfuzz Branch — Development History Overview + +> 19 improvement cycles on the `cfuzz` branch. +> Research-driven methodology: study competitors → identify gap → implement → test → benchmark. +> Grew test suite from 42 → 148 passing tests. + +--- + +## Methodology + +Each cycle followed a consistent pattern: + +1. **Research** — Study how competitors (Erlang/OTP, Tokio, Akka, Ractor, Actix, Kameo) handle the problem +2. **Identify gap** — Find a specific deficiency in swactor +3. **Implement** — Fix the gap with minimal, targeted changes +4. **Test** — Write behavioral tests (Given/When/Then) from the consumer's perspective +5. **Benchmark** — Measure impact where applicable + +### Constraints + +- `src/` structure is frozen — no new files or modules, only modify existing files in-place +- No new dependencies on the root crate +- Behavioral tests only — no white-box/structural tests +- All `cargo test` must pass before each commit +- Never delete tests for active code + +--- + +## Baseline Benchmarks (Pre-Improvement) + +| Benchmark | Time | Throughput | +|-----------|------|-----------| +| spawn | 1.28 µs | — | +| message_roundtrip | 2.24 µs | — | +| send_fire_and_forget | 1.50 µs | — | +| single_actor/1000 | 57.5 µs | 17.4 Melem/s | +| multi_actor/100x100 | 610.6 µs | 16.4 Melem/s | +| ring/100 | 99.9 µs | 1.01 Melem/s | + +--- + +## Cycle Summary + +| Cycle | Commit | Topic | Tests Added | Cumulative Tests | +|-------|--------|-------|-------------|-----------------| +| 1 | `ef87f7e` | [Fairness (message budget)](CYCLE_01_FAIRNESS.md) | 3 | 45 | +| 2 | `10cb078` | [Stress tests + benchmarks](CYCLE_02_STRESS_TESTS.md) | 6 | 51 | +| 3 | `acacc1b` | [Thread parking](CYCLE_03_THREAD_PARKING.md) | 1 | 52 | +| 4 | `cf61619` | [Shutdown fix + bug-inspired tests](CYCLE_04_SHUTDOWN_FIX.md) | 5 | 57 | +| 5 | `7d00e65` | [Load-aware placement](CYCLE_05_LOAD_AWARE_PLACEMENT.md) | 3 | 60 | +| 6 | `265992c` | [Mailbox backpressure](CYCLE_06_BACKPRESSURE.md) | 4 | 64 | +| 7 | `1779ad6` | [Actor recovery](CYCLE_07_ACTOR_RECOVERY.md) | 4 | 68 | +| 8 | `0213938` | [Dead actor cleanup](CYCLE_08_DEAD_ACTOR_CLEANUP.md) | 2 (+2 updated) | 70 | +| 9 | `e28aca0` | [Lifecycle hooks + graceful stop](CYCLE_09_LIFECYCLE_HOOKS.md) | 12 | 82 | +| 10 | `d58a999` | [Actor timers](CYCLE_10_TIMERS.md) | 6 | 88 | +| 11 | `9b1518b` | [Property-based testing](CYCLE_11_PROPERTY_TESTING.md) | 7 | 95 | +| 12 | `66a8523` | [Named actor registry](CYCLE_12_NAMED_REGISTRY.md) | 11 | 106 | +| 13 | `8782638` | [Actor monitoring](CYCLE_13_MONITORING.md) | 7 | 113 | +| 14 | `4d18874` | [Actor groups](CYCLE_14_GROUPS.md) | 9 | 122 | +| 15 | `902471b` | [Ask pattern](CYCLE_15_ASK_PATTERN.md) | 5 | 127 | +| 16 | `0ef6df9` | [Registry benchmarks](CYCLE_16_REGISTRY_BENCHMARKS.md) | 0 | 127 | +| 17 | `a70bd86` | [Supervision trees](CYCLE_17_SUPERVISION.md) | 10 | 138 | +| 18 | `771c38c` | [OneForAll + RestForOne](CYCLE_18_SUPERVISOR_STRATEGIES.md) | 3 | 141 | +| 19 | `c688f0a` | [Router](CYCLE_19_ROUTER.md) | 7 | 148 | + +--- + +## Thematic Groupings + +### Scheduling & Performance (Cycles 1–5) +Foundation work: fairness guarantees, stress testing, thread parking, shutdown reliability, and load-aware actor placement. Research thread: BEAM reductions → tokio coop budget → Kameo/Actix mailboxes → tokio parker → work stealing survey. + +### Resilience & Lifecycle (Cycles 6–10) +Production hardening: backpressure, crash recovery, memory leak fix, lifecycle hooks, and deterministic timers. Narrative arc: from "actors crash permanently" to "actors have a fully managed lifecycle." + +### Testing & Service Discovery (Cycles 11–16) +Property-based testing for invariant verification, plus four registry features (names, monitoring, groups, ask pattern) and benchmarks to validate them. Research shifted from scheduling to service discovery patterns. + +### Supervision (Cycles 17–19) +Capstone features built on everything preceding: supervision trees with configurable restart strategies, and routers for actor pool management. Directly modeled on Erlang/OTP supervision trees. + +--- + +## Frameworks Studied + +| Framework | Language | Key Lessons | +|-----------|----------|-------------| +| Erlang/OTP BEAM | Erlang | 4000-reduction budget, supervision trees, pg groups, gen_server:call | +| Tokio | Rust | 128-op coop budget, work-stealing, parker state machine | +| Akka | Scala/Java | SupervisorStrategy, Router actors, PoisonPill | +| Ractor | Rust | String-based registry, SupervisionEvent, bug history | +| Actix | Rust | Vyukov MPSC queue, 256-message guard, ctx.stop() | +| Kameo | Rust | Dual mailbox (bounded/unbounded), on_panic hook, ActorPool | +| Linux CFS/EEVDF | C | vruntime fairness, NO_HZ adaptive ticks | +| libuv/Node.js | C | Phase-based event loop, round-robin handlers | diff --git a/docs/development_history/cfuzz/CYCLE_01_FAIRNESS.md b/docs/development_history/cfuzz/CYCLE_01_FAIRNESS.md new file mode 100644 index 0000000..e71e88b --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_01_FAIRNESS.md @@ -0,0 +1,61 @@ +# Cycle 1: Per-Actor Message Budget for Tick Fairness — Development History + +> Commit: `ef87f7e` · 8 files · Priority: P0 (critical bug fix) + +--- + +## Motivation + +The `tick_all` function in `worker.rs` drained the **entire mailbox** for each actor before moving to the next: + +```rust +while let Some(msg) = slot.mailbox.pop_front() { + // processes ALL messages for actor A before moving to actor B +} +``` + +If actor A had 10,000 queued messages, all other actors on the same worker were completely starved until A finished. This is a critical fairness bug — every other runtime studied prevents this. + +## Competitor Analysis + +| Runtime | Fairness Mechanism | Budget | +|---------|-------------------|--------| +| Erlang/OTP BEAM | Reduction counting, preemptive | 4,000 reductions | +| Tokio | Cooperative budgeting | 128–256 operations | +| libuv/Node.js | Round-robin across handlers | No single handler drains completely | +| Linux CFS | vruntime-based fairness | Time slices enforced | +| Ractor | N/A (1 task = 1 actor via tokio) | Inherited from tokio | +| **Swactor (before)** | **None** | **Unlimited drain** | + +The BEAM's reduction budget (4,000 per process before preemption) is the gold standard for actor fairness. Tokio's cooperative budget (128 ops) serves a similar purpose for async tasks. Actix has a 256-message assertion guard that validates the approach. + +## Implementation + +- Added `actor_message_budget: usize` to `RuntimeConfig` (default: 64) +- Modified `tick_all` in `worker.rs` to break after `budget` messages per actor per tick +- `budget=0` means unlimited (100% backward compatible) +- Updated `RuntimeConfig` struct literals across all crates (python, runtime-dashboard, mt_benchmarks) + +**Key files modified:** `src/worker.rs`, `src/config.rs`, `benches/runtime_benchmarks.rs`, `tests/runtime_api.rs` + +## Design Decisions + +- **Budget of 64 chosen** as default — between BEAM's 4,000 (too generous for swactor's coarser granularity) and tokio's 128 (per-op vs per-message). Benchmarks showed budget=32 was slightly faster for throughput, but 64 provides more fairness headroom. +- **Per-runtime, not per-actor** — simpler configuration, matching the BEAM model where the reduction budget is global. Per-actor budgets could be added later as an extension. +- **budget=0 means unlimited** — backward compatibility for users who want the old behavior. + +## Tests Added + +3 new behavioral tests (42 → 45 total): + +- `hot_actor_does_not_starve_cold_actor` — hot actor with many messages doesn't prevent cold actor from processing +- `unlimited_budget_drains_all` — budget=0 preserves old behavior +- `budget_messages_drain_across_multiple_ticks` — excess messages carry over to next tick + +**Benchmarks added:** `fairness/cold_latency_under_pressure`, `fairness/throughput_by_budget` + +## Result + +- 45 tests pass (42 original + 3 new) +- All workspace crates compile +- Baseline benchmarks established for future comparison diff --git a/docs/development_history/cfuzz/CYCLE_02_STRESS_TESTS.md b/docs/development_history/cfuzz/CYCLE_02_STRESS_TESTS.md new file mode 100644 index 0000000..b9444ad --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_02_STRESS_TESTS.md @@ -0,0 +1,74 @@ +# Cycle 2: Stress Tests, Expanded Benchmarks, and Research Extension — Development History + +> Commit: `10cb078` · 4 files · 517 insertions + +--- + +## Motivation + +After fixing the fairness bug in Cycle 1, the runtime needed stress testing under adversarial conditions to find edge cases. Additionally, the competitor survey was extended to cover Kameo and Actix — two frameworks with distinct approaches to mailbox management and message dispatch. + +## Competitor Analysis + +### Kameo (v0.19) +- Fully async on tokio, one task per actor +- Dual mailbox: bounded (default 64) or unbounded tokio mpsc channels +- Typed signals via vtable dispatch (no `Box` downcast) +- Erlang-style links for supervision (`on_link_died`) +- `on_panic` hook can restart actor (vs swactor's then-permanent poisoning) +- Known bugs: deadlocks in link establishment, leaked ActorRef preventing stop + +### Actix (v0.13) +- Context-as-Future model — each actor is a single pollable Future on an Arbiter +- **Custom Vyukov lock-free MPSC queue** (not tokio channels) — push is single atomic_swap +- Default mailbox capacity: 16 (tiny) +- `do_send()` bypasses capacity for internal notifications +- **256-message assertion guard** — validates swactor's budget approach +- vtable dispatch via `Box>` — no Any downcast +- WHY FAST: custom MPSC queue, no async overhead, same-thread actors avoid cross-thread coordination + +### Key Insight +Both frameworks use vtable dispatch instead of `Box` downcast. Actix's 256-message assertion guard independently validates the per-actor budget concept from Cycle 1. + +## Implementation + +### Stress Tests (6 new) +- `message_ordering_preserved_under_budget` — FIFO order with budget=8 +- `mt_stress_many_senders_one_receiver` — 50 senders × 100 msgs on 4 threads +- `mt_stress_concurrent_spawn_and_send` — 200 concurrent spawn+send on 4 threads +- `mt_chain_spawning_under_load` — 50-level chain across 2 workers +- `mt_panic_isolation_under_load` — 10 panicking + 10 healthy actors on 4 threads +- `sustained_throughput_does_not_drop_messages` — 10 batches × 100 msgs + +### Benchmarks (2 new groups) +- `msg_size` group: throughput and send_latency by message size (8B, 64B, 256B, 1KB, 4KB) +- `contention` group: fanin (1–100 senders to 1 sink), cross_worker (1–4 threads) + +**Key files modified:** `tests/runtime_api.rs`, `benches/runtime_benchmarks.rs`, `CLAUDE/notes/research_synthesis.md` + +## Design Decisions + +- **Multi-threaded stress tests** included because single-threaded testing can't catch cross-worker races +- **Panic isolation test** inspired by Actix's SyncArbiter model — ensures one panicking actor doesn't take down healthy actors on other workers +- **Message ordering test** validates that the budget mechanism (Cycle 1) doesn't break FIFO guarantees +- **Chain spawning** tests the spawn+send-in-same-handler pattern across worker boundaries + +## Tests Added + +6 new stress tests (45 → 51 total): + +| Test | Pattern | Purpose | +|------|---------|---------| +| `message_ordering_preserved_under_budget` | FIFO verification | Budget doesn't break ordering | +| `mt_stress_many_senders_one_receiver` | Fan-in | 50:1 contention on 4 threads | +| `mt_stress_concurrent_spawn_and_send` | Concurrent spawn | Race condition hunting | +| `mt_chain_spawning_under_load` | Cascading spawn | Cross-worker chain delivery | +| `mt_panic_isolation_under_load` | Fault isolation | Panics don't spread | +| `sustained_throughput_does_not_drop_messages` | Sustained load | No message loss over time | + +## Result + +- 51 tests pass (42 original + 3 fairness + 6 stress) +- All workspace crates compile +- No bugs found — the runtime handles adversarial conditions correctly +- Benchmark data provides baselines for message size sensitivity and contention scaling diff --git a/docs/development_history/cfuzz/CYCLE_03_THREAD_PARKING.md b/docs/development_history/cfuzz/CYCLE_03_THREAD_PARKING.md new file mode 100644 index 0000000..e8d96f4 --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_03_THREAD_PARKING.md @@ -0,0 +1,51 @@ +# Cycle 3: Thread Parking for Instant Worker Wakeup — Development History + +> Commit: `acacc1b` · 4 files · 59 insertions, 10 deletions + +--- + +## Motivation + +Before this change, idle workers used `thread::sleep` with a fixed timeout to wait for new work. This meant an idle worker wouldn't notice new messages until its sleep timer expired — up to 1ms of unnecessary latency on the idle-to-active transition. Under bursty workloads, this sleep-based backoff wastes both time and power. + +## Competitor Analysis + +| Runtime | Idle Strategy | Wakeup Mechanism | +|---------|--------------|-----------------| +| Tokio | Parker state machine (notified/sleeping/empty) | `unpark()` via atomic CAS | +| Linux | NO_HZ adaptive ticks (stop tick when idle) | Interrupt on new work | +| Go | `notewakeup` / futex | OS-level wake | +| BEAM | Scheduler sleep + signal | Thread signal | +| **Swactor (before)** | **`thread::sleep(1ms)`** | **Timer expiry only** | + +Tokio's parker uses a 3-state machine (notified → sleeping → empty) with atomic transitions. The key insight: `unpark()` is a **no-op** if the thread isn't parked, so callers pay zero cost on the hot path. + +## Implementation + +- Replaced `thread::sleep` with `thread::park_timeout` in worker run loop +- Workers register `thread::current()` via `OnceLock` on startup +- `send_to` and `spawn` call `Thread::unpark()` on target worker after enqueuing work +- Cross-worker sends from `WorkerContext` also unpark the target +- Zero new dependencies — uses only `std::sync::OnceLock` + `std::thread::park_timeout` + +**Key files modified:** `src/worker.rs`, `src/runtime.rs`, `src/delivery.rs` + +## Design Decisions + +- **`OnceLock` for thread handle storage** — set-once semantics match the worker lifecycle (one thread per worker, never changes). Simpler than `Mutex>`. +- **`park_timeout` instead of `park`** — timeout ensures workers periodically wake even without explicit unpark, preventing permanent sleep if an unpark is missed. +- **Unpark on `send_to` and `spawn`** — these are the two operations that create work for a worker. The cost is a single atomic store (no-op if thread is already running). +- **No condvar** — `thread::park/unpark` is simpler and avoids the spurious wakeup complexity of condition variables. Tokio's parker validates this approach. + +## Tests Added + +1 new test (51 → 52 total): + +- `mt_parked_worker_wakes_on_send` — verifies that a parked worker processes a message immediately after send (not after timeout) + +## Result + +- 52 tests pass +- All workspace crates compile +- Idle-to-active latency reduced from up to 1ms to near-zero +- No overhead on hot path — `unpark()` is a no-op when thread isn't parked diff --git a/docs/development_history/cfuzz/CYCLE_04_SHUTDOWN_FIX.md b/docs/development_history/cfuzz/CYCLE_04_SHUTDOWN_FIX.md new file mode 100644 index 0000000..fc25d5c --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_04_SHUTDOWN_FIX.md @@ -0,0 +1,54 @@ +# Cycle 4: Shutdown Fix + Bug-Inspired Tests — Development History + +> Commit: `cf61619` · 3 files · 161 insertions, 12 deletions + +--- + +## Motivation + +Cycle 3 introduced thread parking, but created a new problem: `shutdown()` didn't unpark workers. Parked workers wouldn't notice the shutdown signal until their `park_timeout` expired, causing delayed shutdown. Additionally, studying bug reports from competitor projects (Ractor, Kameo, Actix) revealed specific failure modes worth testing in swactor. + +## Competitor Bug Analysis + +The 5 new tests were directly inspired by real bug reports from other actor frameworks: + +| Test | Inspired By | Bug | +|------|-------------|-----| +| `stats_snapshot_is_read_only` | Ractor #310 | `get_children()` was destructive — moved children out of supervisor | +| `stats_under_load_do_not_interfere_with_processing` | General | Stats collection shouldn't slow down message processing | +| `shutdown_wakes_parked_workers_immediately` | Cycle 3 regression | Parked workers must notice shutdown promptly | +| `mt_send_after_run_delivers_to_running_actors` | Kameo #185 | Messages sent after `run()` weren't delivered during startup race | +| `budget_respected_even_with_self_sends` | Actix #515 | Self-sends bypassed mailbox capacity, defeating backpressure | + +## Implementation + +### Shutdown Fix +- `shutdown()` now iterates all workers and calls `unpark()` on each thread handle +- Parked workers wake immediately and check the shutdown flag +- Workers that aren't parked are unaffected (unpark is a no-op) + +### Bug-Inspired Tests +Each test encodes a real bug class discovered in competitor frameworks, ensuring swactor doesn't have the same vulnerability. + +**Key files modified:** `src/runtime.rs`, `tests/runtime_api.rs` + +## Design Decisions + +- **Unpark-all on shutdown** rather than a dedicated shutdown condvar — simpler, reuses existing parking infrastructure from Cycle 3 +- **Bug-inspired testing methodology** — studying competitor bug trackers yields high-value test cases that target real failure modes, not theoretical ones + +## Tests Added + +5 new tests (52 → 57 total): + +- `stats_snapshot_is_read_only` — reading stats doesn't mutate runtime state (from Ractor #310) +- `stats_under_load_do_not_interfere_with_processing` — stats don't affect message processing throughput +- `shutdown_wakes_parked_workers_immediately` — validates fast shutdown with thread parking +- `mt_send_after_run_delivers_to_running_actors` — messages sent after run() are delivered (from Kameo #185) +- `budget_respected_even_with_self_sends` — self-sends don't bypass budget (from Actix #515) + +## Result + +- 57 tests pass +- All workspace crates compile +- Shutdown latency with parked workers reduced from up to 1ms to near-zero diff --git a/docs/development_history/cfuzz/CYCLE_05_LOAD_AWARE_PLACEMENT.md b/docs/development_history/cfuzz/CYCLE_05_LOAD_AWARE_PLACEMENT.md new file mode 100644 index 0000000..c3eef1b --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_05_LOAD_AWARE_PLACEMENT.md @@ -0,0 +1,66 @@ +# Cycle 5: Load-Aware Actor Placement + Work Stealing Research — Development History + +> Commit: `7d00e65` · 6 files · 184 insertions, 13 deletions + +--- + +## Motivation + +With fairness (Cycle 1), thread parking (Cycle 3), and shutdown (Cycle 4) resolved, the next bottleneck was actor placement. Swactor used blind round-robin to assign actors to workers — ignoring current load. If actors have unequal workloads, round-robin produces persistent imbalance. This cycle also included deep research into work stealing to decide whether full actor migration was worthwhile. + +## Competitor Analysis: Work Stealing Deep Dive + +| Aspect | Tokio | Go | BEAM | ForkJoinPool | +|--------|-------|-----|------|-------------| +| Queue | Fixed 256-slot ring | 256-slot ring + runnext | Per-priority linked | Growable array deque | +| Steal granularity | Half victim's queue | Half victim's runq | Individual processes | One task at a time | +| LIFO fast-path | Dedicated slot (3-use cap) | runnext (stealable 4th try) | None | Owner pops from top | +| Global queue | Mutex intrusive list | Checked 1/61 ticks | Per-priority migration | Even-indexed queues | +| Searcher limit | N/2 workers | GOMAXPROCS/2 | N/A (proactive migration) | Idle stack in ctl | +| Balance strategy | Reactive steal | Reactive steal | **Proactive migration** + reactive | Reactive scan | + +### Key Patterns Discovered + +1. **LIFO slot** — every runtime has one; improves cache locality by running the recipient immediately after the sender. Tokio caps at 3 consecutive uses to prevent starvation. +2. **Steal-half** — Tokio and Go both steal half the victim's queue, amortizing cross-thread coordination overhead. +3. **N/2 searcher limit** — both Tokio and Go cap concurrent searchers to prevent thundering herd (O(N²) cache-line bouncing). +4. **BEAM's migration** — unique dual approach: reactive stealing when idle + proactive migration via periodic `check_balance()`. + +### Feasibility for Swactor + +- **Full actor migration**: Mechanically possible (ActorSlot is `Send`), but has a 1-tick message loss window during migration and requires push-based donation (`ActorPool` is not `Sync` → no pull stealing) +- **Message stealing without actors**: Impossible — the actor IS the state; messages without the actor are meaningless +- **Decision: Load-aware placement over work stealing** — zero correctness risk, handles the primary imbalance source (uneven spawn distribution), full work stealing deferred + +## Implementation + +- `Placement::next_worker()` now reads per-worker stats (`num_actors` + `mailbox_depth`) +- Selects the worker with lowest combined load +- Scan starts from a rotating position → round-robin fallback when all stats are equal (initial burst, before first tick publishes stats) +- O(N) relaxed atomic loads per spawn — trivial for N ≤ 8 workers + +**Key files modified:** `src/delivery.rs`, `tests/runtime_api.rs`, `benches/runtime_benchmarks.rs` + +## Design Decisions + +- **Load-aware placement instead of work stealing** — zero message loss risk, no ordering changes, trivial implementation cost. Handles the #1 source of imbalance: uneven spawn distribution. +- **Combined metric (actors + depth)** — neither actor count alone nor mailbox depth alone captures load accurately. Combined metric approximates total pending work per worker. +- **Relaxed atomics for stat reads** — stats are advisory (best-effort), so relaxed ordering is sufficient. No need for acquire/release which would add synchronization cost. +- **Round-robin fallback** — before the first tick, all workers report zero stats. Falling back to round-robin ensures even initial distribution rather than always picking worker 0. +- **Full work stealing deferred** — would require migration channels, address map coordination, forwarding tombstones, and a message loss window. Benefit uncertain for N ≤ 8 workers. + +## Tests Added + +3 new tests (57 → 60 total): + +- `load_aware_placement_prefers_lighter_worker` — imbalanced load biases spawn toward the lighter worker +- `load_aware_placement_single_worker_degrades_gracefully` — single-thread mode works correctly +- `load_aware_placement_falls_back_to_round_robin_on_fresh_runtime` — even distribution before ticks produce stats + +**Benchmark added:** `placement/spawn_under_load` (2-thread and 4-thread variants) + +## Result + +- 60 tests pass +- All workspace crates compile +- Comprehensive work-stealing research documented for future reference diff --git a/docs/development_history/cfuzz/CYCLE_06_BACKPRESSURE.md b/docs/development_history/cfuzz/CYCLE_06_BACKPRESSURE.md new file mode 100644 index 0000000..67f6444 --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_06_BACKPRESSURE.md @@ -0,0 +1,56 @@ +# Cycle 6: Per-Actor Mailbox Backpressure — Development History + +> Commit: `265992c` · 6 files · 163 insertions, 8 deletions + +--- + +## Motivation + +Before this change, swactor mailboxes were unbounded — a fast producer could flood a slow consumer's mailbox without limit, eventually exhausting memory. Every production actor framework provides some form of backpressure. This was identified as a key weakness in the competitor analysis. + +## Competitor Analysis + +| Framework | Default Capacity | Overflow Policy | Backpressure Model | +|-----------|-----------------|----------------|-------------------| +| Erlang/OTP | Unbounded | N/A (pobox for opt-in bounding) | Process isolation limits blast radius | +| Actix | 16 | `do_send()` bypasses for internal msgs | Tiny default, force callers to handle | +| Kameo | 64 | Bounded tokio mpsc (sender blocks) | Blocking backpressure | +| Tokio mpsc | User-specified | Bounded (sender blocks or permit pattern) | Blocking or try_send | +| Go channels | User-specified | Blocking send / non-blocking select | Blocking backpressure | +| **Swactor (before)** | **Unbounded** | **None** | **None** | + +Key observation: Actix's default capacity of 16 is aggressive — it forces callers to think about message flow. Kameo's 64 matches swactor's message budget. The consensus across frameworks: bounded by default, with configurable overflow policy. + +## Implementation + +- Added `MailboxOverflow` enum: `DropNewest` (discard incoming when full) and `DropOldest` (evict oldest to make room) +- Added `default_mailbox_capacity` and `mailbox_overflow` to `RuntimeConfig` +- Default: `capacity=0` (unbounded) — 100% backward compatible +- `ActorSlot` stores per-actor capacity and policy (initialized from runtime defaults at spawn time) +- `deliver()` in worker enforces bounds; dropped messages tracked via `drops_this_tick` counter +- `messages_dropped: AtomicU64` added to `WorkerStats` and `WorkerInfo` + +**Key files modified:** `src/config.rs`, `src/worker.rs`, `src/runtime.rs`, `src/stats.rs`, `tests/runtime_api.rs` + +## Design Decisions + +- **DropNewest vs DropOldest (not blocking)** — swactor's synchronous tick model can't block the sender (it would deadlock the entire worker). Drop policies are the only viable option for a sync runtime. +- **Default unbounded** — backward compatibility. Users opt into backpressure by setting capacity > 0. +- **Per-runtime defaults, not per-actor** — simpler configuration. Per-actor overrides could be added later via a builder pattern on spawn. +- **Drop counting** — critical for observability. Without it, users can't tell if their system is losing messages. +- **No DropRandom** — the two policies cover the common cases. DropNewest protects against producer floods (newest messages are redundant). DropOldest keeps the freshest state (useful for sensor/status actors). + +## Tests Added + +4 new tests (60 → 64 total): + +- `bounded_mailbox_drop_newest_caps_at_capacity` — 50 msgs sent, capacity 10 → only 10 delivered (oldest 10) +- `bounded_mailbox_drop_oldest_keeps_newest` — 10 msgs sent, capacity 5 → newest 5 kept +- `unbounded_mailbox_delivers_all_messages` — backward compatibility: capacity=0 delivers everything +- `bounded_mailbox_refills_after_processing` — capacity 5, process batch, refill works correctly + +## Result + +- 64 tests pass +- All workspace crates compile +- Swactor weakness "no backpressure" resolved diff --git a/docs/development_history/cfuzz/CYCLE_07_ACTOR_RECOVERY.md b/docs/development_history/cfuzz/CYCLE_07_ACTOR_RECOVERY.md new file mode 100644 index 0000000..1dd04d9 --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_07_ACTOR_RECOVERY.md @@ -0,0 +1,59 @@ +# Cycle 7: Actor Recovery via Factory-Based Restart — Development History + +> Commit: `1779ad6` · 6 files · 167 insertions, 10 deletions + +--- + +## Motivation + +Before this change, a panicking actor was permanently poisoned — it could never process messages again. Its address remained in the address map but silently discarded all messages. In production, this means a single panic permanently degrades the system. Every mature actor framework provides some form of crash recovery. + +## Competitor Analysis + +| Framework | Recovery Model | State After Restart | Mailbox After Restart | +|-----------|---------------|--------------------|-----------------------| +| Erlang/OTP | Factory (MFA tuple), fresh process | Fresh (new init/1) | Lost (new PID) | +| Akka | Replace internals, keep ActorRef | Fresh (preRestart hook) | Preserved (docs say "usually wrong") | +| Kameo | `on_panic(&mut self)` hook | Potentially corrupt | Preserved | +| Actix | `Supervised` trait, re-create context | Fresh | Lost | +| Ractor | `SupervisionEvent` callback | Up to supervisor | Up to supervisor | +| **Swactor (before)** | **None — permanent poison** | **N/A** | **Silently discarded** | + +### Key Insight +Akka's approach of preserving state by replacing internals is documented as "usually wrong" — the state that caused the panic is likely corrupt. Kameo's `on_panic(&mut self)` is risky for the same reason. Erlang's factory-based restart (fresh process from MFA tuple) is the safest approach: guaranteed clean state. + +## Implementation + +- `Actor` expanded from tuple struct to named fields: `inner`, `restart_factory`, `max_restarts`, `restart_count` +- `AnyActor::try_restart(&self) -> Option>` trait method (default `None`, backward compatible) +- Factory stored as `Arc A + Send + Sync>` — called to produce fresh actor instance on restart +- `spawn_restartable(actor, factory, max_restarts)` added to both `Runtime` and `Ctx` +- `tick_all` panic handler: `try_restart()` before poisoning; on success, replace actor, clear mailbox, reset state +- `restarts` counter added to `WorkerStats` and `WorkerInfo` + +**Key files modified:** `src/actor.rs`, `src/runtime.rs`, `src/worker.rs`, `src/stats.rs`, `tests/runtime_api.rs` + +## Design Decisions + +- **Factory-based restart (Erlang model)** — safest approach, guaranteed clean state. Factory closure is `Arc A>`, cloned into fresh `Actor` on each restart. +- **max_restarts limit** — prevents infinite restart loops. When exceeded, actor is permanently poisoned. Mirrors Erlang's restart intensity. +- **Mailbox cleared on restart** — messages that triggered the panic are discarded. Fresh actor starts with empty mailbox. (Erlang does this too — new PID means new mailbox.) +- **Same address preserved** — unlike Erlang (new PID), the restarted actor keeps its `ActorAddress`. This is simpler for callers and matches Akka's model. +- **Factory fields are "cold"** — `restart_factory` and `max_restarts` are never touched by `handle_any` (the hot path). After `catch_unwind`, these fields are guaranteed safe to read. +- **Non-restartable actors unchanged** — `try_restart()` returns `None` by default, preserving the existing poison-on-panic behavior. + +## Tests Added + +4 new tests (64 → 68 total): + +- `restartable_actor_recovers_after_panic` — basic restart works: panic, recover, process new messages +- `restartable_actor_resets_state_on_restart` — fresh state confirmed post-restart (counter resets to zero) +- `restartable_actor_respects_max_restarts` — 2 restarts allowed, 3rd panic → permanent poison +- `non_restartable_actor_still_poisons_on_panic` — backward compatibility: default actors still poison + +## Result + +- 68 tests pass +- All workspace crates compile +- Swactor weakness "panicked actors permanently poisoned" resolved +- Foundation laid for supervision trees (Cycle 17) diff --git a/docs/development_history/cfuzz/CYCLE_08_DEAD_ACTOR_CLEANUP.md b/docs/development_history/cfuzz/CYCLE_08_DEAD_ACTOR_CLEANUP.md new file mode 100644 index 0000000..e697429 --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_08_DEAD_ACTOR_CLEANUP.md @@ -0,0 +1,54 @@ +# Cycle 8: Dead Actor Cleanup (Memory Leak Fix) — Development History + +> Commit: `0213938` · 4 files · 120 insertions, 14 deletions + +--- + +## Motivation + +After Cycles 7 (recovery) and the pre-existing poison-on-panic behavior, dead actors accumulated in both `ActorPool` and `AddressMap` forever. Their slots were never reclaimed, their addresses remained registered, and the system gradually leaked memory. This is a known bug class in actor frameworks. + +## Competitor Analysis + +| Framework | Dead Actor Handling | Known Bugs | +|-----------|-------------------|------------| +| Akka | Automatic cleanup via DeathWatch | #22990 — ActorRef leak in certain paths | +| CAF | Manual cleanup expected | #420 — actor leak in specific failure modes | +| Erlang/OTP | Automatic — process exits free all resources | N/A (VM handles cleanup) | +| Ractor | Supervisor-driven cleanup | Memory bloat per actor at scale | +| **Swactor (before)** | **None — permanent leak** | **Both ActorPool and AddressMap leak** | + +## Implementation + +- Added `AddressMap::remove(addr)` to `delivery.rs` — O(1) removal from address map +- Added `ActorPool::cleanup_dead()` to `worker.rs` — collects and removes poisoned actors, returns their addresses +- Added Phase 7 to `tick_once`: `cleanup_dead` → remove from address_map → re-publish `num_actors` stat +- Stats immediately reflect removal (no stale counts) + +**Key files modified:** `src/delivery.rs`, `src/worker.rs`, `tests/runtime_api.rs` + +## Design Decisions + +- **Automatic cleanup in tick_once** — no manual API needed. Dead actors are cleaned up every tick, preventing accumulation. +- **Phase 7 (after all message processing)** — cleanup happens after `tick_all` and `pending_local`, so any final messages to dead actors correctly fail. No risk of cleaning up an actor that's about to receive a message. +- **Re-publish `num_actors` after cleanup** — ensures stats are immediately consistent. Without this, stats would show stale actor counts until the next tick. + +### Behavior Change +- **Before**: Sending to a poisoned actor silently discarded the message (address still in map, delivery succeeded, but processing was skipped) +- **After**: Sending to a cleaned-up actor returns `Err` (address removed from map, send fails) +- This is **better** — callers learn the actor is gone instead of silently losing messages. + +## Tests Added + +2 new tests + 2 existing tests updated (68 → 70 total): + +- `dead_actor_cleaned_up_from_stats_and_address_map` — good actor persists, bad actor's address is removed +- `bulk_dead_actor_cleanup` — 20 panicked actors all cleaned up in one tick +- Updated `send_to_poisoned_actor_is_a_silent_black_hole` → now asserts send returns `Err` (behavior change) +- Updated `poisoned_actor_messages_not_counted_as_processed` → sends fail to cleaned-up actor + +## Result + +- 70 tests pass +- All workspace crates compile +- Memory leak closed: dead actors no longer accumulate in ActorPool or AddressMap diff --git a/docs/development_history/cfuzz/CYCLE_09_LIFECYCLE_HOOKS.md b/docs/development_history/cfuzz/CYCLE_09_LIFECYCLE_HOOKS.md new file mode 100644 index 0000000..ab06da4 --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_09_LIFECYCLE_HOOKS.md @@ -0,0 +1,79 @@ +# Cycle 9: Lifecycle Hooks and Graceful Actor Stop — Development History + +> Commit: `e28aca0` · 8 files · 427 insertions, 27 deletions + +--- + +## Motivation + +Before this change, actors had no initialization or teardown callbacks and no way to stop gracefully. An actor started processing messages immediately (no setup phase) and could only die by panicking. Every mature actor framework provides lifecycle hooks for resource management and graceful shutdown. + +## Competitor Analysis + +| Framework | on_start | on_stop | on_panic | Self-stop | External stop | +|-----------|----------|---------|----------|-----------|---------------| +| Erlang | `init/1` | `terminate/2` (NOT on crash) | N/A | `{stop,Reason,State}` | `gen_server:stop` | +| Akka | `preStart` | `postStop` (always) | `preRestart` | `context.stop(self)` | PoisonPill / stop | +| Actix | `started` | `stopped` | N/A | `ctx.stop()` | `addr.do_send(Stop)` | +| Kameo | `on_start` | `on_stop` | `on_panic` | `Context::stop()` | `stop_gracefully/kill` | +| Ractor | `pre_start` | `post_stop` (NOT on kill/panic) | N/A | `stop()` | `Signal::Kill` | +| **Swactor** | **`on_start`** | **`on_stop` (NOT on panic)** | N/A | **`ctx.stop_self()`** | **`runtime.stop_actor()`** | + +### Key Findings +- Most frameworks do NOT call `on_stop` on panic — state may be corrupt, running teardown on corrupt state is unsafe. Erlang and Ractor agree. Akka is the outlier (always calls `postStop`). +- Self-stop should be immediate (after current message). External stop should be queued (PoisonPill semantics — process pending messages first). +- Restarted actors should get `on_start` called again on the fresh instance. + +## Implementation + +### Lifecycle Hooks +- `ActorInterface::on_start(&mut self, ctx: &Ctx)` — default no-op, called on first tick before any messages +- `ActorInterface::on_stop(&mut self, ctx: &Ctx)` — default no-op, called during cleanup for gracefully-stopped actors +- `AnyActor::on_start()`/`on_stop()` — forwarded from `Actor` implementation +- `ActorSlot` gains `started: bool` flag — tracks whether `on_start` has been called +- `on_start` called in `tick_all` before first message; panic in `on_start` → immediate poison +- `on_stop` called in `cleanup_dead` for stopping (not poisoned) actors, wrapped in `catch_unwind` +- Restarted actors get `started=false` so `on_start` fires again on fresh instance + +### Graceful Stop (Dual Mode) +- `ctx.stop_self()` — **immediate** stop after current message via `request_stop` buffer +- `runtime.stop_actor(addr)` — **external** stop via `StopSignal` message (PoisonPill semantics: queued after existing messages) +- `ActorSlot` gains `stopping: bool` flag +- Phase 7 `cleanup_dead` now handles both poisoned AND stopping actors + +### Stats +- `stops: AtomicU64` added to `WorkerStats` and `WorkerInfo` — tracks graceful stops separately from panics + +**Key files modified:** `src/actor.rs`, `src/worker.rs`, `src/runtime.rs`, `src/delivery.rs`, `src/stats.rs`, `tests/runtime_api.rs` + +## Design Decisions + +- **`on_stop` NOT called on panic** — matches Erlang and Ractor. Corrupt state after panic makes teardown unsafe. If you need cleanup, use `spawn_restartable` (Cycle 7) to get a fresh instance. +- **Dual stop modes** — `ctx.stop_self()` is immediate (actor decides "I'm done after this message"). `runtime.stop_actor()` is queued (external signal processed after pending messages). This matches Erlang's `{stop, Reason, State}` vs `gen_server:stop`. +- **StopSignal as a message** — external stop uses the same delivery pipeline as regular messages. No special-case routing needed. The PoisonPill pattern (Akka) is well-proven. +- **`on_start` panic → immediate poison** — initialization failure is fatal. No restart attempted because the factory might produce the same broken actor. Matches Erlang's `{stop, Reason}` from `init/1`. +- **Default no-ops** — both hooks are optional. Existing actors don't need to change. 100% backward compatible. + +## Tests Added + +12 new tests (70 → 82 total): + +- `on_start_called_before_first_message` — on_start fires on first tick, before messages +- `on_start_called_per_actor` — 5 actors each get exactly one on_start call +- `on_start_panic_poisons_actor` — panic in on_start → poisoned, no messages processed +- `actor_can_stop_self` — 5 msgs sent, stops after 3, only 3 processed, on_stop called +- `runtime_can_stop_actor` — external stop via runtime, on_stop called, actor removed +- `send_to_stopped_actor_returns_error` — stopped actor gone from address map +- `stop_vs_panic_tracked_separately_in_stats` — stops and panics counted independently +- `on_stop_can_send_messages` — farewell message sent during on_stop is delivered +- `on_start_called_again_after_restart` — restartable actor gets on_start on fresh instance +- `external_stop_is_queued_after_pending_messages` — PoisonPill semantics verified +- `external_stop_before_new_messages_prevents_processing` — stop before send blocks new msgs +- `stop_nonexistent_actor_returns_error` — stop on bad address returns Err + +## Result + +- 82 tests pass +- All workspace crates compile +- Swactor weaknesses "no lifecycle hooks" and "no graceful stop" both resolved +- Foundation for supervision (Cycle 17) — `on_stop` enables resource cleanup, `stop_actor` enables supervisor-controlled shutdown diff --git a/docs/development_history/cfuzz/CYCLE_10_TIMERS.md b/docs/development_history/cfuzz/CYCLE_10_TIMERS.md new file mode 100644 index 0000000..98e1d2d --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_10_TIMERS.md @@ -0,0 +1,76 @@ +# Cycle 10: Per-Worker Tick-Counting Timers — Development History + +> Commit: `d58a999` · 5 files · 247 insertions, 5 deletions + +--- + +## Motivation + +Actors often need to schedule delayed or periodic work (timeouts, heartbeats, polling intervals). Before this change, swactor had no timer mechanism — actors had to manually count ticks or rely on external scheduling. The synchronous tick model makes wall-clock timers inappropriate, but tick-counting timers are a natural fit and provide deterministic behavior. + +## Competitor Analysis + +| Framework | Timer Model | Deterministic? | +|-----------|------------|---------------| +| Erlang | `timer:send_after`, `erlang:start_timer` (wall-clock ms) | No | +| Akka | `scheduleOnce`, `scheduler` (wall-clock duration) | No | +| Actix | `ctx.run_later`, `ctx.run_interval` (wall-clock) | No | +| Kameo | `tokio::time::sleep` (wall-clock) | No | +| Tokio | `tokio::time` (wall-clock, pausable for testing) | With `time::pause()` | +| Go | `time.After`, `time.NewTicker` (wall-clock) | No | +| **Swactor** | **Tick-counting** | **Yes — fully deterministic** | + +### Key Insight +Swactor's synchronous tick model makes tick-counting timers uniquely valuable: a timer scheduled for "5 ticks from now" fires at exactly tick N+5, regardless of wall-clock speed. This makes timer behavior reproducible in tests and simulations — something no other framework provides natively. + +Also researched but **rejected**: priority messages (lifecycle hooks from Cycle 9 cover 95% of use cases) and SmallBox optimization (deferred: measure allocation cost first before adding unsafe code). + +## Implementation + +### Timer Types +- `OnceTimer` — fire once at `fire_at` tick, consumed after firing +- `IntervalTimer` — fire every `period` ticks, message cloned via `CloneMsg` trait + +### Timer Infrastructure +- `CloneMsg` trait — type-erased clone for interval timer messages (blanket impl for `Message + Clone`) +- `TimerRequest` enum: `Once { dest, msg, ticks }` | `Interval { dest, msg, period }` +- Per-worker `TimerWheel` — stores pending timers, checked each tick + +### Integration into tick_once +- **Phase 2.5**: Fire due timers, route through full delivery system (pool.deliver for local actors, transfer_txs for cross-worker, inbox_registry for inboxes) +- **Phase 5.5**: Drain timer requests from handler buffer into TimerWheel +- **After cleanup_dead**: GC interval timers for dead actors + +### API +- `ctx.send_after_ticks(addr, msg, ticks)` — one-shot timer +- `ctx.send_interval_ticks(addr, msg, period)` — interval timer +- `Runtime::schedule_timer()` — no-op with warning (timers are per-worker only, must be scheduled from within a handler) + +**Key files modified:** `src/actor.rs`, `src/worker.rs`, `src/runtime.rs`, `src/delivery.rs`, `tests/runtime_api.rs` + +## Design Decisions + +- **Tick-counting, not wall-clock** — deterministic behavior is a core swactor advantage. Wall-clock timers would break test reproducibility and simulation fidelity. +- **Per-worker timer wheel** — timers are local to the worker that owns the actor. No cross-worker synchronization needed. Timer routing uses the same delivery system as regular messages. +- **CloneMsg trait** — interval timers need to clone the message for each firing. A blanket impl covers all `Message + Clone` types, so users don't need to implement anything extra. +- **Timer GC for dead actors** — interval timers must be cleaned up when their target actor dies, otherwise they fire forever into the void. + +### Bug Fixed +`gc_dead_intervals` was initially over-aggressive — it removed timers for ANY address not in the local pool, including inboxes and cross-worker actors. Fixed to only GC timers for addresses in the `dead` set from `cleanup_dead`. + +## Tests Added + +6 new tests (82 → 88 total): + +- `one_shot_timer_fires_after_n_ticks` — timer with delay=3 fires on tick 4 +- `handler_can_schedule_one_shot_timer` — timer scheduled from within a handler fires correctly +- `one_shot_timer_fires_only_once` — consumed after firing, doesn't repeat +- `interval_timer_fires_repeatedly` — period=2, fires every 2 ticks (3 firings verified) +- `interval_timer_cleaned_up_when_actor_dies` — GC removes orphaned interval timers +- `timer_with_zero_delay_fires_next_tick` — delay=0 fires on next tick (not same tick) + +## Result + +- 88 tests pass +- All workspace crates compile +- Bug found and fixed: over-aggressive timer GC for cross-worker addresses diff --git a/docs/development_history/cfuzz/CYCLE_11_PROPERTY_TESTING.md b/docs/development_history/cfuzz/CYCLE_11_PROPERTY_TESTING.md new file mode 100644 index 0000000..544628f --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_11_PROPERTY_TESTING.md @@ -0,0 +1,84 @@ +# Cycle 11: Property-Based Testing and Extended Fuzz Targets — Development History + +> Commit: `9b1518b` · 5 files · 534 insertions, 3 deletions + +--- + +## Motivation + +After 10 cycles of behavioral tests, the test suite relied entirely on manually-written scenarios. Property-based testing can explore state spaces that humans wouldn't think to test, automatically finding minimal failing cases. With swactor's deterministic tick model, property-based testing is an especially good fit — no concurrency noise to mask bugs. + +## Competitor Analysis + +| Framework/Tool | Testing Approach | Fit for Swactor | +|----------------|-----------------|-----------------| +| Tokio + Loom | Model-checking for lock-free code | Poor fit — swactor isn't lock-free | +| Erlang + PropEr/QuickCheck | Property-based with shrinking | Good model for swactor | +| Shuttle | Concurrency permutation testing | Moderate — useful for MT tests | +| proptest-state-machine | Stateful property testing for Rust | **Perfect fit** — deterministic ticks | +| cargo-fuzz | Coverage-guided fuzzing | Already in use, extended here | + +### Ranked Approaches +1. **proptest-state-machine** — perfect fit for deterministic ticks, generates random operation sequences, automatic shrinking +2. Extend cargo-fuzz with new action types +3. Simple proptest (stateless properties) +4. Shuttle (concurrency permutations) +5. Loom (lock-free verification) + +### Key Finding: Feature Gap Analysis +While researching testing approaches, also surveyed remaining feature gaps: named actors/registry, actor monitoring/death watch, actor groups/pub-sub, and ask pattern. These became Cycles 12–15. + +## Implementation + +### Property-Based Tests (proptest) +Added `proptest` and `proptest-state-machine` to dev-dependencies. New test file: `tests/proptest_runtime.rs` with 7 tests: + +| Test | Property Verified | +|------|-------------------| +| `fifo_ordering_for_any_message_sequence` | FIFO preserved for 1–100 random messages | +| `budget_limits_per_actor_processing` | Budget caps per-tick processing for 2–10 actors | +| `one_shot_timer_fires_at_correct_tick` | Timer with delay 1–20 fires at exact right tick | +| `interval_timer_fires_at_correct_period` | Period 1–10, verifies 3 consecutive firings | +| `bounded_mailbox_never_exceeds_capacity` | Capacity 1–20, 1–200 messages, never exceeds | +| `spawn_n_actors_all_tracked` | 1–50 actors, all unique, all in stats | +| `swactor_state_machine` | Random Spawn/Send/Tick/Stop/CheckStats sequences | + +### State Machine Test +The `swactor_state_machine` test is the most sophisticated: +- **Reference model**: `HashMap` tracking expected actor lifecycle +- **Operations**: random Spawn, Send, Tick, Stop, CheckStats transitions (up to 40 per test, 128 cases) +- **Invariants checked after every transition**: worker count, actor placement, mailbox safety +- **Automatic shrinking**: finds minimal failing sequences when invariants break + +### Extended Fuzz Targets +Added 4 new `RawAction` variants to `fuzz/fuzz_targets/fuzz_runtime.rs`: +- `StopActor` — graceful stop via `runtime.stop_actor` +- `SpawnRestartable` — `spawn_restartable` with configurable `max_restarts` +- `ScheduleTimer` — one-shot timer via TimerSchedulerActor +- `ScheduleInterval` — interval timer via IntervalSchedulerActor + +3 new actor types added to fuzz: `TimerSchedulerActor`, `IntervalSchedulerActor`, `RestartableEchoActor` + +**Key files modified:** `Cargo.toml`, `tests/proptest_runtime.rs` (new), `fuzz/fuzz_targets/fuzz_runtime.rs` + +## Design Decisions + +- **proptest-state-machine over Loom** — Loom is designed for lock-free concurrent data structures. Swactor's primary correctness properties are sequential (within a tick). The state machine approach tests the actor lifecycle model, which is where bugs are most likely. +- **Reference model pattern** — the state machine test maintains a separate `HashMap` as the "expected" state and compares it against the runtime's actual state after each operation. This catches any divergence between the mental model and reality. +- **Extending existing fuzz targets** — rather than creating new fuzz targets, extended the existing `fuzz_runtime.rs` with new action variants. This means the fuzzer explores interactions between the new features (timers, restart, stop) and existing operations (spawn, send, tick). + +### Bug Found +The state machine test immediately caught an invariant mismatch: `address_map` tracks spawned actors immediately (on spawn), but per-worker `num_actors` lags until the first tick (when the spawn is drained). Fixed the invariant to use `<=` check instead of exact equality. + +## Tests Added + +7 new property tests (88 → 95 total): + +- 6 stateless property tests covering FIFO, budget, timers, mailbox bounds, and spawn tracking +- 1 stateful state machine test covering random operation sequences + +## Result + +- 95 tests pass (88 behavioral + 7 proptest) +- Fuzz targets compile with new action variants +- Bug found: stats lag vs address_map on spawn (invariant relaxed) diff --git a/docs/development_history/cfuzz/CYCLE_12_NAMED_REGISTRY.md b/docs/development_history/cfuzz/CYCLE_12_NAMED_REGISTRY.md new file mode 100644 index 0000000..2127187 --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_12_NAMED_REGISTRY.md @@ -0,0 +1,83 @@ +# Cycle 12: Named Actor Registry with Auto-Cleanup — Development History + +> Commit: `66a8523` · 6 files · 267 insertions, 7 deletions + +--- + +## Motivation + +Actors in swactor were only addressable by opaque `ActorAddress` values returned from spawn. There was no way to look up an actor by name — callers needed to pass addresses around manually. Named registration is one of the most fundamental actor runtime features, enabling service discovery within a runtime. + +## Competitor Analysis + +| Framework | Key Type | Storage | Scope | Auto-Cleanup | +|-----------|----------|---------|-------|-------------| +| Erlang | Atom | ETS table | Per-node or global | Yes (on process exit) | +| Actix | TypeId | SystemRegistry | Per-Arbiter | Yes (on actor stop) | +| Bastion | Path | Hierarchy | Global | Yes (structural) | +| Ractor | String | DashMap (global static) | Global | Yes (on actor death) | +| xactor | TypeId | Singleton registry | Global | N/A (singletons) | +| Akka | ServiceKey[T] | Receptionist | Cluster-wide | Yes (via DeathWatch) | +| **Swactor** | **String** | **RwLock\** | **Per-runtime** | **Yes (on death)** | + +### Key Findings +- **TypeId keys** (Actix, xactor) don't fit swactor's type-erased model — multiple actors of the same type can't share a TypeId key +- **Global static** (Ractor) breaks multi-runtime scenarios (tests, embedding) +- **Erlang's `register/whereis`** is the gold standard: atom keys, per-node scope, automatic cleanup on process exit + +## Implementation + +### NameRegistry +- `NameRegistry` in `delivery.rs` with forward + reverse maps: + - `names: RwLock>` — name → address lookup + - `addrs: RwLock>` — address → name (for O(1) cleanup) +- Added to `Runtime` as `Arc`, threaded through `TickContext` + +### Runtime API +- `spawn_named(name, actor)` — spawn and register atomically +- `where_is(name)` — look up address by name +- `unregister(name)` — manual unregistration (actor keeps running) +- `registered_names()` — list all registered names + +### Context API +- `ctx.spawn_named(name, actor)` — register from within a handler +- `ctx.where_is(name)` — look up from within a handler + +### Auto-Cleanup +- `cleanup_dead` phase calls `name_registry.unregister_by_addr()` for each dead actor +- Name is freed immediately — can be reused for a replacement actor + +### TOCTOU Prevention +- Name reservation is immediate (before spawn queue push) — prevents race between checking name availability and registering it + +**Key files modified:** `src/delivery.rs`, `src/runtime.rs`, `src/actor.rs`, `src/worker.rs`, `tests/runtime_api.rs` + +## Design Decisions + +- **String keys** — most flexible. Atoms (Erlang) aren't idiomatic in Rust. TypeId (Actix) is too restrictive. Strings allow any naming convention. +- **Per-runtime scope** — matches swactor's architecture (one runtime per application). Global registries (Ractor) cause problems in tests and embedded scenarios. +- **RwLock\** — matches the existing `AddressMap` and `InboxRegistry` pattern. RwLock allows concurrent reads (lookups) with exclusive writes (registration). +- **Collision returns error** — `spawn_named` returns `Err` if the name is already taken. The original binding is preserved. This is explicit and predictable, matching Erlang's behavior. +- **Reverse map for O(1) cleanup** — without the reverse map, cleanup would require scanning all entries. The reverse map adds memory proportional to registered actors but makes cleanup constant-time. +- **Immediate reservation** — name is reserved before the spawn is queued, preventing TOCTOU races where two `spawn_named` calls for the same name could both succeed. + +## Tests Added + +11 new tests (95 → 106 total): + +- `named_actor_lookup_returns_spawn_address` — spawn_named → where_is roundtrip +- `named_actor_receives_messages_via_lookup` — send to looked-up address works +- `duplicate_name_returns_error` — collision error, original binding preserved +- `where_is_returns_none_for_unknown_name` — nonexistent name → None +- `name_auto_unregistered_on_actor_death` — stop_actor → name freed +- `name_can_be_reused_after_actor_death` — death → respawn with same name succeeds +- `name_auto_unregistered_on_panic` — panic → name freed +- `registered_names_lists_all` — all registered names returned +- `manual_unregister_frees_name_but_actor_lives` — unregister doesn't kill the actor +- `ctx_where_is_resolves_inside_handler` — where_is works from handler context +- `ctx_spawn_named_registers_from_handler` — spawn_named works from handler context + +## Result + +- 106 tests pass (99 behavioral + 7 proptest) +- All workspace crates compile, zero warnings diff --git a/docs/development_history/cfuzz/CYCLE_13_MONITORING.md b/docs/development_history/cfuzz/CYCLE_13_MONITORING.md new file mode 100644 index 0000000..59cc323 --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_13_MONITORING.md @@ -0,0 +1,74 @@ +# Cycle 13: Actor Monitoring with Down Message Notifications — Development History + +> Commit: `8782638` · 6 files · 268 insertions, 10 deletions + +--- + +## Motivation + +Actors had no way to know when other actors died. If actor A depended on actor B, and B panicked or was stopped, A would continue sending messages into the void with no notification. Monitoring (also called "death watch") is essential for building fault-tolerant systems — it's the foundation that supervision trees are built on. + +## Competitor Analysis + +| Framework | Mechanism | Direction | Notification | +|-----------|-----------|-----------|-------------| +| Erlang | `monitor/2` | Unidirectional | `DOWN` message | +| Akka | `watch` | Unidirectional | `Terminated` message | +| Ractor | `link` | Bidirectional | `SupervisionEvent` | +| Actix | None built-in | N/A | N/A | +| Kameo | `link` | Bidirectional | `on_link_died` callback | +| **Swactor** | **`ctx.monitor()`** | **Unidirectional** | **`Down` message** | + +### Key Findings +- **Erlang's unidirectional monitor + message delivery** is the best fit for swactor — it reuses the existing type-erased message handler, requires zero trait changes, and is composable +- **Callbacks** (Ractor/Kameo style) rejected — would require adding a new method to `AnyActor`/`ActorInterface` traits, forcing all actors to implement it +- **Bidirectional links** deferred — can be layered on top of monitors later +- **Stacking** (Erlang) — multiple monitors of the same target produce independent notifications + +## Implementation + +### Types (in `actor.rs`) +- `MonitorRef(u64)` — unique token from `AtomicU64` counter, used for demonitor +- `Down { addr: ActorAddress, reason: StopReason }` — delivered as normal mailbox message +- `StopReason` enum: `Normal` (graceful stop) | `Panicked` (panic, not restartable) + +### MonitorRegistry (in `delivery.rs`) +- `watchers: RwLock>>` — watched → list of (ref, watcher) +- `refs: RwLock>` — ref → watched (for O(1) demonitor) + +### API +- `ctx.monitor(target) → MonitorRef` — subscribe to death notifications +- `ctx.demonitor(mref)` — cancel a subscription + +### Integration with cleanup_dead +- `cleanup_dead` now returns `Vec<(ActorAddress, StopReason)>` instead of `Vec` +- After cleanup: iterate dead actors, take monitors from registry, route `Down` through normal delivery (pool.deliver for same-worker, transfer_txs for cross-worker, inbox_registry for inboxes) +- Dead watcher cleanup: `remove_watcher()` strips monitor subscriptions for dead watchers (prevents ghost subscriptions) + +**Key files modified:** `src/actor.rs`, `src/delivery.rs`, `src/runtime.rs`, `src/worker.rs`, `tests/runtime_api.rs` + +## Design Decisions + +- **Unidirectional monitors (Erlang model)** — simpler than bidirectional links, no cascading death. The watcher is notified but doesn't automatically die. This gives the watcher full control over how to react. +- **Down as a regular message** — delivered through the same mailbox as other messages. Actors with `Incoming = Down` receive it via `handle()`. This reuses the entire existing delivery pipeline with zero special-case code. +- **MonitorRef for demonitor** — each monitor subscription gets a unique ref. This supports stacking (multiple monitors of the same target) and precise cancellation. +- **StopReason distinguishes Normal vs Panicked** — watchers can decide how to react based on whether the death was graceful or a crash. Matches Erlang's `DOWN` message which includes the exit reason. +- **Dead watcher cleanup** — if the watcher dies before the watched actor, its monitor subscriptions are cleaned up. Without this, dead watchers would accumulate as ghost entries in the registry. + +## Tests Added + +7 new tests (106 → 113 total): + +- `monitor_notifies_on_graceful_stop` — Down{reason: Normal} on graceful stop +- `monitor_notifies_on_panic` — Down{reason: Panicked} on panic +- `multiple_watchers_all_notified` — two watchers both receive Down +- `demonitor_cancels_notification` — demonitor → no Down delivered +- `dead_watcher_does_not_receive_down` — dead watcher's monitors cleaned up +- `down_delivered_to_external_inbox` — Down forwarded through inbox +- `stacked_monitors_produce_multiple_notifications` — two monitors on same target → two Downs + +## Result + +- 113 tests pass (106 behavioral + 7 proptest) +- All workspace crates compile, zero warnings +- Foundation for supervision trees (Cycle 17) — monitors provide the death detection mechanism diff --git a/docs/development_history/cfuzz/CYCLE_14_GROUPS.md b/docs/development_history/cfuzz/CYCLE_14_GROUPS.md new file mode 100644 index 0000000..d8be6d4 --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_14_GROUPS.md @@ -0,0 +1,83 @@ +# Cycle 14: Actor Groups with Pub-Sub Broadcast — Development History + +> Commit: `4d18874` · 5 files · 307 insertions, 8 deletions + +--- + +## Motivation + +Named registry (Cycle 12) provides one-to-one name→actor mapping. Many patterns require one-to-many: broadcasting events to subscribers, load distribution across a pool, or topic-based message routing. Actor groups provide this — a named collection of actors that can receive messages as a group. + +## Competitor Analysis + +| Framework | Mechanism | Key Design | Auto-Cleanup | +|-----------|-----------|------------|-------------| +| Erlang `pg` | Scopes, join/leave/get_members | Flat groups, atom keys | Yes (on process exit) | +| Akka | DistributedPubSub (mediator, topics) | Cluster-wide pub-sub | Yes (via DeathWatch) | +| Ractor | `pg` module (join/leave/broadcast) | Erlang-style, global | Yes | +| Bastion | Dispatcher | Hierarchy-based routing | Structural | +| Redis pub/sub | Channels, patterns | External service | N/A | +| **Swactor** | **GroupRegistry** | **Erlang pg-style, per-runtime** | **Yes (on death)** | + +### Common Patterns Across Frameworks +- Auto-cleanup on death (universal) +- At-most-once delivery (no re-delivery guarantees) +- String-based naming (flat, not hierarchical) +- Lazy group creation/deletion (groups created on first join, deleted when empty) + +## Implementation + +### GroupRegistry (in `delivery.rs`) +- Forward map: `groups: RwLock>>` — group → members +- Reverse map: `memberships: RwLock>>` — actor → groups (for cleanup) +- Groups auto-create on first join, auto-delete when empty + +### Runtime API +- `join_group(addr, name)` — add actor to group +- `leave_group(addr, name)` — remove actor from group +- `publish_to(group, msg)` — broadcast to all group members +- `group_members(group)` — list members +- `groups()` — list all groups + +### Context API (from handler) +- `ctx.join_group(name)` — join from inside handler +- `ctx.leave_group(name)` — leave from inside handler +- `ctx.publish(group, msg)` — broadcast from inside handler +- `ctx.group_members(group)` — query from inside handler + +### Message Delivery +- `publish` clones message at the typed level (`Message: Clone`), sends to each member via normal routing +- Uses the same delivery pipeline as regular messages (pool.deliver, transfer_txs, inbox_registry) + +### Auto-Cleanup +- `group_registry.cleanup(&addr)` called in `cleanup_dead` phase +- Uses reverse map to find all groups the dead actor belonged to, removes from each + +**Key files modified:** `src/delivery.rs`, `src/runtime.rs`, `src/actor.rs`, `src/worker.rs`, `tests/runtime_api.rs` + +## Design Decisions + +- **Erlang `pg` model** — flat groups with string keys. Simpler than Akka's mediator/topic model, and sufficient for the common use cases (event broadcasting, worker pools). +- **Clone-based broadcast** — message is cloned for each recipient. This is O(N) but straightforward and type-safe. Alternative (shared Arc) would complicate the message pipeline. +- **Reverse map for cleanup** — without it, cleaning up a dead actor would require scanning all groups. O(1) per group membership vs O(groups) scan. +- **Lazy lifecycle** — groups are created implicitly on first join and deleted when the last member leaves. No explicit create/delete API needed. Matches Erlang `pg`. +- **publish requires `Message: Clone`** — enforced at the type level. If a message type isn't Clone, it can't be broadcast. This is a compile-time safety guarantee. + +## Tests Added + +9 new tests (113 → 122 total): + +- `group_members_returns_joined_actors` — join + query returns members +- `empty_group_returns_no_members` — nonexistent group → empty set +- `publish_broadcasts_to_all_members` — 2 members, both receive the message +- `leave_group_stops_receiving_publishes` — leave → excluded from future broadcasts +- `dead_actor_auto_removed_from_group` — stop → removed from group +- `actor_removed_from_all_groups_on_death` — multi-group membership cleanup +- `empty_group_auto_deleted` — last member leaves → group removed from `groups()` +- `ctx_join_group_from_handler` — join via on_start +- `ctx_publish_broadcasts_from_handler` — publish via handler + +## Result + +- 122 tests pass (115 behavioral + 7 proptest) +- All workspace crates compile, zero warnings diff --git a/docs/development_history/cfuzz/CYCLE_15_ASK_PATTERN.md b/docs/development_history/cfuzz/CYCLE_15_ASK_PATTERN.md new file mode 100644 index 0000000..d40c8f0 --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_15_ASK_PATTERN.md @@ -0,0 +1,67 @@ +# Cycle 15: Ask Pattern for Typed Request-Response — Development History + +> Commit: `902471b` · 3 files · 166 insertions, 1 deletion + +--- + +## Motivation + +Request-response is one of the most common actor communication patterns: "send a question, wait for the answer." Before this change, implementing request-response in swactor required manual inbox creation, message construction with a reply-to address, sending, ticking, and polling — a verbose 5-step process. Every mature actor framework provides a convenience wrapper for this pattern. + +## Competitor Analysis + +| Framework | Pattern | Mechanism | Synchronous? | +|-----------|---------|-----------|-------------| +| Erlang | `gen_server:call` | `From` + `gen_server:reply` | Blocks caller (with timeout) | +| Akka | `ask` | Temporary actor + `Future` | Returns Future | +| Ractor | `call` | `RpcReplyPort` (oneshot channel) | Returns JoinHandle | +| Kameo | `ask` | Async + `Reply` trait | Returns Future | +| xactor | `Handler::handle` | Return value auto-routed | Implicit | +| **Swactor** | **`rt.ask()`** | **Inbox + closure** | **`recv_ticking` (tick-driven)** | + +### Key Findings +- Swactor's synchronous tick model requires explicit `reply_to` — there's no async runtime to suspend the caller +- **Implicit auto-reply rejected** — would add magic to the message pipeline and complicate the actor interface +- **Decision**: convenience wrapper over existing inbox pattern (not a new mechanism) + +## Implementation + +### Ask\ Struct +- Wraps an `Inbox` with convenience methods +- `try_recv()` — poll without ticking (works in both single and multi-threaded modes) +- `recv_ticking(rt, max_ticks)` — tick the runtime until a response arrives or timeout (single-threaded only) +- `reply_addr()` — access the inbox address for manual use + +### Runtime::ask() +- `rt.ask(addr, |reply_to| Msg { reply_to })` — one-line request-response +- Creates inbox, builds message via closure (user provides the reply_to field), sends, returns `Ask` +- Purely sugar over the existing `new_inbox → send_to → tick → try_recv` pattern + +### No Internal Changes +- Zero changes to `ContextInner` or `ActorInterface` +- No implicit auto-reply magic +- Actors reply by explicitly sending to the `reply_to` address (same as before) + +**Key files modified:** `src/runtime.rs`, `tests/runtime_api.rs` + +## Design Decisions + +- **Closure-based message construction** — `rt.ask(addr, |reply_to| Msg { reply_to })` lets the user embed the reply address in any message shape. No trait requirements on the message type (beyond `Message`). +- **`recv_ticking` for single-threaded** — in single-threaded mode, the runtime must be ticked for the target actor to process the request and reply. `recv_ticking` does this automatically. In multi-threaded mode, use `try_recv` with your own tick loop. +- **No implicit reply** — frameworks like xactor auto-route the handler's return value as a reply. This is magical and doesn't fit swactor's explicit model. The ask pattern wraps existing mechanics without adding new ones. +- **max_ticks timeout** — instead of wall-clock timeout, uses tick count for deterministic behavior (consistent with Cycle 10 timers). + +## Tests Added + +5 new tests (122 → 127 total): + +- `ask_recv_ticking_returns_response` — basic PingPong ask roundtrip +- `ask_multiple_times_tracks_state` — 3 sequential asks to CounterActor, state increments +- `ask_timeout_when_no_response` — ask dead actor → timeout error +- `ask_try_recv_returns_none_before_tick` — poll before tick → None, after tick → Some +- `ask_reply_addr_is_accessible` — reply address is valid for manual use + +## Result + +- 127 tests pass (120 behavioral + 7 proptest) +- All workspace crates compile, zero warnings diff --git a/docs/development_history/cfuzz/CYCLE_16_REGISTRY_BENCHMARKS.md b/docs/development_history/cfuzz/CYCLE_16_REGISTRY_BENCHMARKS.md new file mode 100644 index 0000000..5f0d639 --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_16_REGISTRY_BENCHMARKS.md @@ -0,0 +1,59 @@ +# Cycle 16: Registry Benchmarks for Named Actors, Groups, Monitors, and Ask — Development History + +> Commit: `0ef6df9` · 2 files · 130 insertions, 1 deletion + +--- + +## Motivation + +Cycles 12–15 added four new features (named registry, monitoring, groups, ask pattern) without performance measurement. Before building more features on top of these primitives, it was important to quantify their overhead and ensure they're efficient enough for production use. + +## Benchmark Results + +| Benchmark | Time | Analysis | +|-----------|------|----------| +| `named_spawn_lookup` | ~2.4 µs | vs bare spawn 1.9 µs → **+0.5 µs** overhead for name registration | +| `where_is_100_names` | ~9.0 µs | Includes setup overhead; per-lookup cost is negligible | +| `group_publish/10` | ~4.8 µs | O(N) message cloning | +| `group_publish/50` | ~15.5 µs | Linear scaling confirmed | +| `group_publish/100` | ~60 µs | Linear with O(N) clones | +| `monitor_setup` | ~13.4 µs | monitor + stop + cleanup full cycle | +| `ask_roundtrip` | ~4.5 µs | vs manual roundtrip 3.0 µs → **+1.5 µs** for inbox creation | + +### Analysis + +- **Named lookup**: +0.5 µs over bare spawn — the `RwLock` insert is fast. Acceptable for a feature used at spawn time, not on the hot path. +- **Group publish**: scales linearly with group size, as expected for O(N) message cloning. No optimization needed — the bottleneck is inherent (must clone and deliver N messages). +- **Monitor setup**: 13.4 µs covers the full lifecycle (monitor → stop → cleanup → Down delivery). The monitoring machinery adds minimal per-message overhead. +- **Ask roundtrip**: +1.5 µs over manual inbox pattern (4.5 µs vs 3.0 µs). The overhead is inbox creation. Acceptable for a convenience pattern — users who need maximum throughput can use the manual pattern. + +## Implementation + +5 new criterion benchmark functions added to `benches/runtime_benchmarks.rs` in a `registry` group: + +- `named_spawn_lookup` — spawn_named + where_is roundtrip +- `where_is_100_names` — lookup in 100-name registry +- `group_publish/{10,50,100}` — broadcast to N group members +- `monitor_setup` — monitor + stop + Down delivery cycle +- `ask_roundtrip` — ask + recv_ticking response + +**Key files modified:** `benches/runtime_benchmarks.rs` + +## Design Decisions + +- **Full-cycle benchmarks** — each benchmark measures the complete operation (not just the fast path). For example, `monitor_setup` includes stop and cleanup, not just the monitor call, because that's the real-world cost. +- **Parameterized group publish** — three group sizes (10, 50, 100) to verify linear scaling and catch any unexpected superlinear behavior. +- **No optimization undertaken** — all operations are efficient enough. The benchmark results serve as baselines for future changes. + +## Tests Added + +No new tests (benchmarks only). Test count remains at 127. + +## Result + +- All benchmarks run cleanly +- 127 tests pass, zero warnings +- All registry operations confirmed efficient for production use +- Named lookup: <1 µs overhead over bare spawn +- Ask: ~50% overhead over manual inbox pattern (acceptable for convenience) +- Group publish: linear O(N) as expected diff --git a/docs/development_history/cfuzz/CYCLE_17_SUPERVISION.md b/docs/development_history/cfuzz/CYCLE_17_SUPERVISION.md new file mode 100644 index 0000000..f7076b6 --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_17_SUPERVISION.md @@ -0,0 +1,89 @@ +# Cycle 17: Supervision Trees with handle_down and Supervisor Actor — Development History + +> Commit: `a70bd86` · 4 files · 754 insertions, 7 deletions + +--- + +## Motivation + +With monitoring (Cycle 13), lifecycle hooks (Cycle 9), and factory-based restart (Cycle 7) in place, swactor had all the building blocks for supervision trees — the signature feature of Erlang/OTP. Supervision trees provide structured fault tolerance: a parent actor (supervisor) monitors children and restarts them according to configurable policies when they fail. + +## Competitor Analysis + +| Framework | Supervisor Model | Strategies | Child Spec | Meltdown Protection | +|-----------|-----------------|------------|------------|---------------------| +| Erlang/OTP | Built-in `supervisor` behaviour | one_for_one, one_for_all, rest_for_one, simple_one_for_one | `{Id, MFA, Restart, Shutdown, Type}` | Intensity/period limits | +| Akka | SupervisorStrategy | Resume, Restart, Stop, Escalate + BackoffSupervisor | N/A (inline) | MaxNrOfRetries/withinTimeRange | +| Ractor | `ractor-supervisor` crate | External crate, event-based | SupervisionEvent callback | N/A | +| Bastion | Built-in hierarchy | Redundancy groups | Structural (parent-child) | N/A | +| CAF | No built-in supervisor | Monitor-based (manual) | N/A | N/A | +| **Swactor** | **User-space `Supervisor` actor** | **OneForOne** (Cycle 17), **OneForAll/RestForOne** (Cycle 18) | **`ChildSpec`** | **max_restarts budget** | + +### Key Findings +- Swactor has all the building blocks: monitor (Cycle 13), `spawn_restartable` (Cycle 7), lifecycle hooks (Cycle 9), `Down` messages (Cycle 13) +- **Decision**: Supervisor as a user-space actor built on existing primitives (like Ractor's `ractor-supervisor` crate), not a special runtime construct +- **`handle_down` callback** enables any actor to react to monitored deaths without requiring `Incoming = Down` — this is the key API gap that needed filling + +## Implementation + +### 1. `handle_down` Callback on ActorInterface + +The core API addition enabling supervision: + +- `fn handle_down(&mut self, ctx: &Ctx, down: Down)` — default no-op, called when a monitored actor dies and the actor's `Incoming` type is NOT `Down` +- Implemented via second downcast attempt in `handle_any`: if the message is `Down` and the actor's `Incoming` type doesn't match, call `handle_down` instead of `handle` +- Fully backward-compatible: actors with `Incoming = Down` still receive via `handle()` as before +- This decouples supervision logic from the actor's primary message type + +### 2. `ctx.stop_actor(addr)` — Stop Another Actor + +- Sends graceful stop to another actor from handler context +- Uses `StopSignal` through normal message routing (PoisonPill semantics) +- Enables supervisor-controlled shutdown of children + +### 3. `Supervisor` Actor + +A user-space actor managing child actors: + +- **`SupervisorStrategy::OneForOne`** — only the failed child is restarted (Cycle 17) +- **`RestartPolicy`**: `Permanent` (always restart), `Transient` (restart only on panic, not normal stop), `Temporary` (never restart) +- **`ChildSpec`** — `{ id: String, restart: RestartPolicy, factory: Fn(&Ctx) -> Result }` +- Children spawned in `on_start`, monitored via `ctx.monitor()` +- Death detected via `handle_down`, restart policy consulted, factory invoked for replacement +- **Meltdown detection**: stops itself when `total_restarts > max_restarts` +- **Cascading shutdown**: `on_stop` sends stop signals to all living children + +### ActiveChild Struct +- Tracks `addr: ActorAddress` and `monitor_ref: MonitorRef` per child +- Reused by Router (Cycle 19) + +**Key files modified:** `src/actor.rs`, `tests/runtime_api.rs`, `docs/runtime.md` + +## Design Decisions + +- **User-space actor (not runtime primitive)** — the Supervisor is just an actor that uses existing APIs (monitor, spawn, stop). No special runtime support needed. This validates the composability of the monitoring and lifecycle systems. +- **`handle_down` as opt-in callback** — adding `handle_down` to `ActorInterface` with a default no-op means existing actors don't need to change. Actors that want to react to deaths override it. The alternative (requiring `Incoming = Down`) would force actors to handle `Down` as their primary message type. +- **Factory takes `&Ctx`** — the factory closure receives the context so it can use `ctx.spawn`, `ctx.monitor`, etc. during child creation. This enables the supervisor to monitor new children immediately. +- **Meltdown protection** — if children keep crashing faster than they can be restarted, the supervisor stops itself rather than looping forever. Matches Erlang's intensity/period limits. +- **Cascading shutdown** — when the supervisor stops, all living children receive stop signals. This prevents orphaned actors. + +## Tests Added + +10 new tests (127 → 138 total, counting 130 behavioral + 7 proptest + 1 doctest): + +- `handle_down_receives_death_notification` — handle_down callback fires on monitored death +- `handle_down_skipped_when_incoming_is_down` — backward compat: Incoming=Down uses handle() +- `ctx_stop_actor_stops_target` — one actor stops another via ctx.stop_actor() +- `supervisor_restarts_permanent_child_on_panic` — panic → restart (OneForOne + Permanent) +- `supervisor_does_not_restart_transient_child_on_normal_stop` — Normal stop → no restart +- `supervisor_restarts_transient_child_on_panic` — Panicked → restart (Transient) +- `supervisor_never_restarts_temporary_child` — Temporary → never restart +- `supervisor_meltdown_after_max_restarts` — exceeding max_restarts stops supervisor +- `supervisor_one_for_one_only_restarts_failed_child` — multi-child, only crashed child restarted +- `supervisor_on_stop_kills_children` — supervisor shutdown cascades to children + +## Result + +- 138 tests pass (130 behavioral + 7 proptest + 1 doctest) +- Zero warnings, full workspace compiles +- Supervisor validates the composability of Cycles 7 (recovery), 9 (lifecycle), and 13 (monitoring) diff --git a/docs/development_history/cfuzz/CYCLE_18_SUPERVISOR_STRATEGIES.md b/docs/development_history/cfuzz/CYCLE_18_SUPERVISOR_STRATEGIES.md new file mode 100644 index 0000000..e96a888 --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_18_SUPERVISOR_STRATEGIES.md @@ -0,0 +1,86 @@ +# Cycle 18: OneForAll and RestForOne Supervisor Strategies — Development History + +> Commit: `771c38c` · 4 files · 277 insertions, 2 deletions + +--- + +## Motivation + +Cycle 17 introduced supervision with the `OneForOne` strategy (only the failed child is restarted). Erlang/OTP defines two additional coordinated restart strategies that handle interdependent children: + +- **`one_for_all`** — when one child fails, ALL children are restarted (for tightly coupled children that share state assumptions) +- **`rest_for_one`** — when one child fails, it and all children started AFTER it are restarted (for chains where later children depend on earlier ones) + +These strategies require coordinated shutdown: the supervisor must stop living siblings, wait for all of them to die, then restart the affected set in the original spec order. + +### Research Detour: SmallBox/InlineAny Optimization +Before choosing this cycle's topic, investigated SmallBox optimization for message dispatch — a 44% queue throughput improvement was measured. However, it was deferred because: +- Requires `unsafe` code in a core path +- Would touch 32+ call sites across the codebase +- Violates the "src/ structure frozen" constraint + +Extended the Supervisor with coordinated strategies instead — higher value, zero risk. + +## Competitor Analysis + +| Framework | OneForAll | RestForOne | Coordinated Shutdown | +|-----------|-----------|------------|---------------------| +| Erlang/OTP | Yes | Yes | Built into supervisor behaviour | +| Akka | No (different model: Resume/Restart/Stop/Escalate) | No | N/A | +| Ractor | No | No | N/A | +| Bastion | Implicit (redundancy groups) | No | Implicit | +| **Swactor** | **Yes** | **Yes** | **Phase-based state machine** | + +### Erlang's Coordinated Restart +In Erlang, `one_for_all` and `rest_for_one` stop affected children in reverse start order, wait for all to terminate, then restart in start order. This guarantees initialization dependencies are respected. + +## Implementation + +### SupervisorPhase State Machine +- `Normal` — steady state, processing handle_down events normally +- `Stopping { awaiting: HashSet, restart_set: Vec }` — coordinated shutdown in progress + +### SupervisorStrategy Extensions +- `SupervisorStrategy::OneForAll` — all children restarted when one fails +- `SupervisorStrategy::RestForOne` — failed child + all children after it (in spec order) restarted + +### Coordinated Restart Flow +1. Child dies → `handle_down` called +2. Strategy determines affected indices (OneForAll: all, RestForOne: failed + later) +3. `begin_coordinated_restart(ctx, indices)`: + - Sends stop signals to living siblings in the restart set + - Transitions to `Stopping` phase with `awaiting` set + - Already-dead children handled: if all targets are already dead, skip to immediate restart +4. Subsequent `handle_down` calls during `Stopping` phase: + - Remove from `awaiting` set + - When `awaiting` is empty → all stopped +5. `finish_restart(ctx)`: + - Restart all children in the restart set, in spec order + - Transition back to `Normal` phase + +### Refactoring +- `check_intensity()` factored out of `handle_down` for restart budget checking — shared by all strategies + +**Key files modified:** `src/actor.rs`, `tests/runtime_api.rs`, `docs/runtime.md` + +## Design Decisions + +- **Phase-based state machine** — the `Stopping` phase cleanly separates "waiting for siblings to die" from "normal operation." This prevents races where a new death arrives while a coordinated restart is in progress. +- **Stop signals (not kill)** — affected siblings are stopped gracefully (PoisonPill semantics), giving them a chance to run `on_stop` for cleanup. This matches Erlang's `terminate/2` being called during supervised shutdown. +- **Restart in spec order** — children are restarted in the order they appear in the ChildSpec list, regardless of which child triggered the restart. This preserves initialization dependencies. +- **Already-dead optimization** — if all children in the restart set are already dead (e.g., cascading failures), skip the `Stopping` phase entirely and restart immediately. Without this, the supervisor would wait forever for Down messages that already arrived. +- **Meltdown protection shared** — the same `max_restarts` budget applies across all strategies. OneForAll restarts count as one restart event (not N), matching Erlang's behavior. + +## Tests Added + +3 new tests (138 → 141 total): + +- `supervisor_one_for_all_restarts_all_on_single_failure` — one child panics, all 3 get new addresses +- `supervisor_rest_for_one_restarts_rest_after_failed` — child_b panics, child_a unchanged, child_b + child_c restarted +- `supervisor_one_for_all_waits_for_all_downs_before_restart` — verifies coordinated shutdown completes before restart begins + +## Result + +- 141 tests pass (133 behavioral + 7 proptest + 1 doctest) +- Zero warnings, full workspace compiles +- All three Erlang-standard supervision strategies now available: OneForOne, OneForAll, RestForOne diff --git a/docs/development_history/cfuzz/CYCLE_19_ROUTER.md b/docs/development_history/cfuzz/CYCLE_19_ROUTER.md new file mode 100644 index 0000000..7897eaa --- /dev/null +++ b/docs/development_history/cfuzz/CYCLE_19_ROUTER.md @@ -0,0 +1,78 @@ +# Cycle 19: Router Actor for Pooled Message Distribution — Development History + +> Commit: `c688f0a` · 4 files · 528 insertions, 3 deletions + +--- + +## Motivation + +Many workloads benefit from distributing messages across a pool of identical worker actors. Before this change, users had to manually manage actor pools: spawn N workers, track their addresses, implement distribution logic, and handle worker replacement on failure. A Router actor encapsulates this pattern — it receives messages and transparently forwards them to pool members using a configurable strategy. + +## Competitor Analysis + +| Framework | Pool/Router Model | Strategies | Auto-Replace | +|-----------|------------------|------------|-------------| +| Erlang | `poolboy` (checkout/checkin), `wpool` (transparent forwarding, 6 strategies + custom) | RoundRobin, Random, BestWorker, Hash, Available, custom | Manual | +| Akka | Router actors (Pool vs Group), Resizer for dynamic sizing | RoundRobin, Random, SmallestMailbox, Balancing, Broadcast, ScatterGather, TailChopping, ConsistentHashing | Pool auto-creates, Group manual | +| Actix | SyncArbiter (shared queue, implicit work-stealing) | N/A (shared queue) | N/A | +| Kameo | ActorPool (least-connections, auto-replace dead workers) | Least-connections | Yes | +| Ractor | No built-in router (process groups only) | N/A | N/A | +| **Swactor** | **`Router` actor** | **RoundRobin, Random, Broadcast** | **Yes (via monitor + handle_down)** | + +### Key Findings +- **Router-as-actor** with transparent forwarding (wpool/Akka style) is the best fit — the router looks like a regular actor to callers +- **User-space actor** like Supervisor (Cycle 17), reusing monitor + handle_down for worker replacement +- **SmallestMailbox deferred** — requires runtime stats access not available in user-space +- **ConsistentHashing deferred** — requires a hash function parameter, can be added later as a builder method + +## Implementation + +### Router\ Actor +- Generic over `M: Message` — same `Incoming` type as workers, enabling transparent forwarding +- Workers spawned in `on_start`, monitored via `ctx.monitor()`, auto-replaced via `handle_down` +- Reuses `ActiveChild` struct from Supervisor (addr + monitor_ref) + +### Routing Strategies +- `RoutingStrategy::RoundRobin` — sequential circular distribution via counter +- `RoutingStrategy::Random` — random worker selection via `get_random()` helper +- `RoutingStrategy::Broadcast` — clone message to all live workers (`M: Clone` required) + +### Fault Tolerance +- Dead worker detected via `handle_down` → factory invoked → new worker spawned and monitored +- **Meltdown protection**: `total_restarts > max_restarts` → `ctx.stop_self()` +- **Cascading shutdown**: `on_stop` sends stop signals to all workers + +### Configuration +- `Router::new(pool_size, strategy, factory, max_restarts)` — all-in-one constructor +- Factory: `Arc Result + Send + Sync>` + +**Key files modified:** `src/actor.rs`, `tests/runtime_api.rs`, `docs/runtime.md` + +## Design Decisions + +- **Router-as-actor (transparent forwarding)** — callers send messages to the router's address as if it were a regular actor. The router forwards to pool members. This is the cleanest API: no special send function, no pool handle, just an address. +- **User-space actor (not runtime primitive)** — like Supervisor, Router is built entirely on existing APIs (spawn, monitor, handle_down, stop). This validates the actor system's composability. +- **Generic over M** — `Router` has `Incoming = M`, same as the workers. Messages are forwarded with zero transformation. Type safety is enforced at compile time. +- **Broadcast requires Clone** — broadcasting clones the message for each worker. The Clone bound is only required when using the Broadcast strategy, enforced at the type level. +- **SmallestMailbox deferred** — would require reading per-actor mailbox depth from runtime stats, which isn't available from within a handler. Could be added with a stats query API. +- **ConsistentHashing deferred** — requires a hash function parameter (user must define which part of the message determines the routing key). Better to add as a builder method with a closure parameter. +- **Reuses ActiveChild from Supervisor** — the pattern of "track address + monitor ref, replace on death" is identical. Code sharing confirms the design consistency between Supervisor and Router. + +## Tests Added + +7 new tests (141 → 148 total): + +- `router_round_robin_distributes_across_workers` — 6 msgs to 3 workers, each gets 2 +- `router_broadcast_sends_to_all_workers` — 1 msg, all 3 workers receive +- `router_random_delivers_to_some_worker` — 30 msgs across 3 workers, at least 2 workers used +- `router_replaces_dead_worker` — panicked worker auto-replaced, pool size maintained +- `router_meltdown_after_max_restarts` — 3 deaths with max_restarts=2 → router stops +- `router_on_stop_kills_workers` — stopping router cascades to all workers +- `router_broadcast_multiple_messages_all_received` — 5 msgs × 3 workers = 15 received + +## Result + +- 148 tests pass (140 behavioral + 7 proptest + 1 doctest) +- Zero warnings, full workspace compiles +- Router validates the composability of the entire cfuzz feature set: monitoring (Cycle 13), lifecycle hooks (Cycle 9), handle_down (Cycle 17), and the ActiveChild pattern (Cycle 17) +- The cfuzz branch concludes with a comprehensive actor runtime featuring: fairness, backpressure, recovery, lifecycle management, timers, named registry, monitoring, groups, ask pattern, supervision trees, and routers diff --git a/docs/runtime.md b/docs/runtime.md index 9ca1c13..05655fe 100644 --- a/docs/runtime.md +++ b/docs/runtime.md @@ -14,10 +14,13 @@ messages. │ │ │ ┌─ Shared State (lives on Arc) ──────────────────────────────┐ │ │ │ │ │ -│ │ address_map: Arc -- actor -> worker lookup │ │ -│ │ inbox_registry: Arc -- external inbox delivery │ │ -│ │ placement: Placement -- round-robin worker picker │ │ -│ │ worker_stats: Vec> -- atomic stat counters │ │ +│ │ address_map: Arc -- actor -> worker lookup │ │ +│ │ inbox_registry: Arc -- external inbox delivery │ │ +│ │ name_registry: Arc -- name -> address lookup │ │ +│ │ monitor_registry: Arc -- death watch subscripts │ │ +│ │ group_registry: Arc -- pub-sub actor groups │ │ +│ │ placement: Placement -- load-aware worker picker │ │ +│ │ worker_stats: Vec> -- atomic stat counters │ │ │ │ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ @@ -28,14 +31,8 @@ messages. │ │ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ -│ ┌─ Mode ──────────────────────────────────────────────────────────────┐ │ -│ │ │ │ -│ │ SINGLE-THREADED: single_worker: Some(RefCell) │ │ -│ │ MULTI-THREADED: pending_workers: Some(Vec) │ │ -│ │ │ │ -│ │ After run() is called, both are None — workers move to threads. │ │ -│ │ │ │ -│ └─────────────────────────────────────────────────────────────────────┘ │ +│ tick_workers: RefCell> -- for tick(); run() drains these │ +│ worker_threads: Vec> -- for waking parked workers │ │ │ └───────────────────────────────────────────────────────────────────────────┘ ``` @@ -80,9 +77,22 @@ only way for actors to interact with the outside world. │ │ │ ┌─ Public API ────────────────────────────────────────────────────────┐ │ │ │ │ │ -│ │ ctx.self_addr() -> ActorAddress │ │ -│ │ ctx.send(addr, msg) -> Result<(), Error> │ │ -│ │ ctx.spawn(actor) -> Result │ │ +│ │ ctx.self_addr() -> ActorAddress │ │ +│ │ ctx.send(addr, msg) -> Result<(), Error> │ │ +│ │ ctx.spawn(actor) -> Result │ │ +│ │ ctx.spawn_named(name, actor) -> Result │ │ +│ │ ctx.spawn_restartable(a, f, max) -> Result │ │ +│ │ ctx.stop_self() │ │ +│ │ ctx.stop_actor(addr) -> Result<(), Error> │ │ +│ │ ctx.where_is(name) -> Option │ │ +│ │ ctx.monitor(target) -> MonitorRef │ │ +│ │ ctx.demonitor(mref) │ │ +│ │ ctx.join_group(group) │ │ +│ │ ctx.leave_group(group) │ │ +│ │ ctx.publish(group, msg) -> usize │ │ +│ │ ctx.group_members(group) -> Vec │ │ +│ │ ctx.send_after_ticks(addr, msg, n) │ │ +│ │ ctx.send_interval_ticks(addr, msg, period) │ │ │ │ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ @@ -130,21 +140,160 @@ handler, etc.) receive typed messages from actors. │ if let Some(msg) = inbox.try_recv() { ... } │ │ │ └────────────────────────────────────────────────────────────────────────┘ +``` - ┌─ Delivery Path ────────────────────────────────────────────────────────┐ - │ │ - │ actor calls ctx.send(inbox_addr, response) │ - │ │ │ - │ v │ - │ address_map.lookup(inbox_addr) → None (inboxes aren't actors) │ - │ │ │ - │ v │ - │ inbox_registry.try_deliver(addr, msg) │ - │ │ │ - │ v │ - │ downcast Box → M, push into Receiver │ - │ │ - └────────────────────────────────────────────────────────────────────────┘ +## Ask — Typed Request-Response + +`Ask` wraps an `Inbox` for convenient request-response: + +``` + let response: Pong = rt.ask(actor, |reply_to| Ping { reply_to })? + .recv_ticking(&rt, 10)?; // tick until response or timeout +``` + +## Named Actors + +Actors can be spawned with a registered name for discovery: + +``` + let addr = rt.spawn_named("coordinator", my_actor)?; + let found = rt.where_is("coordinator"); // -> Some(addr) + // Names are auto-unregistered when the actor dies. +``` + +## Actor Monitoring (Death Watch) + +Subscribe to death notifications via `ctx.monitor()`: + +``` + let mref = ctx.monitor(target_addr); + // When target dies, a Down { addr, reason } message arrives in + // the watcher's normal handle() method. No special callback needed. +``` + +`StopReason`: `Normal` (graceful stop) | `Panicked` (panic, not restartable) + +## Actor Groups (Pub-Sub) + +Named groups for broadcast messaging: + +``` + ctx.join_group("workers"); + ctx.publish("workers", StatusUpdate { ... }); // all members receive it + // Members auto-removed on death. Groups auto-deleted when empty. +``` + +## Lifecycle Hooks + +``` + fn on_start(&mut self, ctx: &Ctx) {} -- called once before first message + fn on_stop(&mut self, ctx: &Ctx) {} -- called on graceful stop (not panic) +``` + +## Actor Recovery + +Factory-based restart after panic: + +``` + rt.spawn_restartable(actor, || MyActor::new(), 3)?; + // On panic: mailbox cleared, factory creates fresh instance, up to 3 times. + // After max_restarts: permanently poisoned. +``` + +## Supervision Trees + +The `Supervisor` actor manages child actors with configurable restart policies: + +``` + let sup = Supervisor::new( + SupervisorStrategy::OneForOne, // only the failed child is restarted + // Also: OneForAll — all children restarted when one fails + // RestForOne — failed child + all children after it restarted + 5, // max 5 restarts before meltdown + vec![ + ChildSpec::new("worker_a", RestartPolicy::Permanent, |ctx| { + ctx.spawn(MyWorker::new()) + }), + ChildSpec::new("worker_b", RestartPolicy::Transient, |ctx| { + ctx.spawn(MyOtherWorker::new()) + }), + ], + ); + let sup_addr = rt.spawn(sup)?; +``` + +Restart policies: +- `Permanent`: always restart +- `Transient`: restart only on panic, not normal stop +- `Temporary`: never restart + +Strategies: +- `OneForOne`: only the failed child is restarted (default) +- `OneForAll`: all children are stopped and restarted when one fails +- `RestForOne`: the failed child and all children after it (in spec order) are restarted + +Coordinated restart (OneForAll/RestForOne): the supervisor enters a `Stopping` phase, +sends stop signals to affected siblings, waits for all `Down` confirmations, then +restarts the full set in spec order. Already-dead children are handled immediately. + +Meltdown: supervisor stops itself when total restarts exceed `max_restarts`. +Cascading: supervisor stops all children in `on_stop`. + +## Router — Actor Pool with Message Routing + +The `Router` actor manages a pool of identical workers and distributes +incoming messages across them. Callers send messages to the router's address, +and the router forwards them according to the configured strategy. + +``` + let router = Router::new( + RoutingStrategy::RoundRobin, + 5, // pool size + |ctx| ctx.spawn(MyWorker::new()), // worker factory + 10, // max restarts before meltdown + ); + let router_addr = rt.spawn(router)?; + rt.send_to(router_addr, WorkerMsg::DoWork(42))?; +``` + +Routing strategies: +- `RoundRobin`: sequential circular distribution +- `Random`: random worker selection +- `Broadcast`: clone message to all workers + +Workers are monitored and automatically replaced on failure. Meltdown +protection stops the router when total restarts exceed `max_restarts`. + +### handle_down Callback + +Any actor can override `handle_down` to react to monitored actor deaths +without making `Down` its `Incoming` type: + +``` + impl ActorInterface for MyActor { + type Incoming = MyMsg; + // ... + fn handle_down(&mut self, ctx: &Ctx, down: Down) { + // React to monitored actor death + } + } +``` + +### ctx.stop_actor + +Actors can stop other actors from handlers: + +``` + ctx.stop_actor(other_addr)?; // PoisonPill semantics — queued after existing msgs +``` + +## Per-Worker Timers + +Deterministic tick-counting timers (not wall-clock): + +``` + ctx.send_after_ticks(addr, msg, 5); // one-shot: fires after 5 ticks + ctx.send_interval_ticks(addr, msg, 10); // repeating: every 10 ticks ``` ## RuntimeHandle @@ -171,12 +320,18 @@ Returned by `run()`. Holds `Arc` and the thread `JoinHandle`s. ┌─ RuntimeStats ────────────────────────────────────────────────────────────┐ │ │ │ num_workers: usize │ +│ uptime_ms: u64 │ │ actors: Vec<(ActorAddress, worker_id)> -- from AddressMap snapshot │ │ workers: Vec │ │ ├─ id: usize │ │ ├─ num_actors: usize -- from atomic counter │ │ ├─ mailbox_depth: usize -- total queued messages │ -│ └─ messages_processed: u64 -- cumulative count │ +│ ├─ messages_processed: u64 -- cumulative count │ +│ ├─ messages_dropped: u64 -- overflow drops │ +│ ├─ panics: u64 │ +│ ├─ restarts: u64 │ +│ └─ stops: u64 │ +│ tick_timings: Vec> -- per-phase timing data │ │ │ └───────────────────────────────────────────────────────────────────────────┘ ``` diff --git a/docs/worker-thread.md b/docs/worker-thread.md index bb909da..3916f9e 100644 --- a/docs/worker-thread.md +++ b/docs/worker-thread.md @@ -48,6 +48,12 @@ │ │ │ │ │ └──────────────────────────────────────────────────────────────────┘ │ │ │ +│ ┌─ TimerWheel ────────────────────────────────────────────────────┐ │ +│ │ current_tick: u64 │ │ +│ │ once_timers: Vec -- fire_at, dest, msg │ │ +│ │ interval_timers: Vec -- period, dest, clone_msg │ │ +│ └──────────────────────────────────────────────────────────────────┘ │ +│ │ └────────────────────────────────────────────────────────────────────────┘ ``` @@ -58,12 +64,17 @@ Lives on `Arc`, shared read-only across all worker threads. ``` ┌─ TickContext<'a> ──────────────────────────────────────────────────────┐ │ │ -│ address_map: &AddressMap -- ActorAddress -> WorkerId lookup │ -│ transfer_txs: &[Sender] -- one Sender per worker (cross-send) │ -│ spawn_txs: &[Sender] -- one Sender per worker (spawn reqs) │ -│ placement: &Placement -- round-robin next-worker picker │ -│ inbox_registry: &InboxRegistry -- external Inbox receivers │ -│ config: &RuntimeConfig -- waterlevel, backoff params, etc. │ +│ address_map: &AddressMap -- ActorAddress -> WorkerId │ +│ transfer_txs: &[Sender] -- one Sender per worker │ +│ spawn_txs: &[Sender] -- one Sender per worker │ +│ placement: &Placement -- load-aware worker picker │ +│ inbox_registry: &InboxRegistry -- external Inbox receivers │ +│ name_registry: &NameRegistry -- String -> ActorAddress │ +│ monitor_registry: &MonitorRegistry -- death watch subscriptions │ +│ group_registry: &GroupRegistry -- pub-sub actor groups │ +│ config: &RuntimeConfig -- budget, backoff, etc. │ +│ stats_hook: Option<&dyn Hook> -- per-tick stats callback │ +│ worker_threads: &[OnceLock] -- for unpark on send/spawn │ │ │ └────────────────────────────────────────────────────────────────────────┘ ``` @@ -89,11 +100,13 @@ Lives on `Arc`, shared read-only across all worker threads. │ v v │ │ │ idle = 0 idle++ │ │ │ │ │ │ │ -│ │ ┌────┴────────────────────────┐ │ │ -│ │ │ idle < spin_thr: spin │ │ │ -│ │ │ idle < yield_thr: yield │ │ │ -│ │ │ else: sleep(incr, capped) │ │ │ -│ │ └─────────────────────────┬───┘ │ │ +│ │ ┌────┴──────────────────────────────┐ │ │ +│ │ │ idle < spin_thr: spin │ │ │ +│ │ │ idle < yield_thr: yield_now │ │ │ +│ │ │ else: park_timeout(incr, capped) │ │ │ +│ │ │ (instant wake via Thread::unpark │ │ │ +│ │ │ when send/spawn targets worker) │ │ │ +│ │ └──────────────────────────────┬─────┘ │ │ │ │ │ │ │ │ └──────────┬───────────────────┘ │ │ │ │ │ │ @@ -102,7 +115,7 @@ Lives on `Arc`, shared read-only across all worker threads. └────────────────────────────────────────────────────────────────────────┘ ``` -## Tick Once (four phases) +## Tick Once (eight phases) ``` ┌─ tick_once ────────────────────────────────────────────────────────────┐ @@ -114,12 +127,9 @@ Lives on `Arc`, shared read-only across all worker threads. │ │ │ ││ │ │ v ││ │ │ pool.insert(addr, actor) ││ -│ │ │ ││ -│ │ v ││ -│ │ ActorSlot { ││ -│ │ mailbox: VecDeque::new() ││ -│ │ actor: ││ -│ │ } ││ +│ │ started: false ││ +│ │ stopping: false ││ +│ │ mailbox_capacity: from config ││ │ │ ││ │ └────────────────────────────────────────────────────────────────────┘│ │ │ │ @@ -131,10 +141,25 @@ Lives on `Arc`, shared read-only across all worker threads. │ │ │ ││ │ │ v ││ │ │ pool.deliver(&dest, payload) ││ -│ │ │ ││ -│ │ v ││ -│ │ slot.mailbox.push_back(msg) ││ -│ │ (untyped; type check at handle time) ││ +│ │ (enforces mailbox_capacity; ││ +│ │ drop newest/oldest on overflow) ││ +│ │ ││ +│ └────────────────────────────────────────────────────────────────────┘│ +│ │ │ +│ v │ +│ PHASE 2.5 --- Fire Due Timers │ +│ ┌────────────────────────────────────────────────────────────────────┐│ +│ │ ││ +│ │ timers.fire() (advances tick counter, collects due messages) ││ +│ │ │ ││ +│ │ v ││ +│ │ for (dest, msg) in timer_msgs: ││ +│ │ ┌──────────────┬──────────────┬─────────────────┐ ││ +│ │ │ local actor │ other worker │ inbox/unknown │ ││ +│ │ │ │ │ │ ││ +│ │ │ pool.deliver │ transfer_tx │ inbox_registry │ ││ +│ │ │ │ + unpark │ .try_deliver() │ ││ +│ │ └──────────────┴──────────────┴─────────────────┘ ││ │ │ ││ │ └────────────────────────────────────────────────────────────────────┘│ │ │ │ @@ -144,25 +169,35 @@ Lives on `Arc`, shared read-only across all worker threads. │ │ ││ │ │ ┌─ WorkerContext (on stack) ─────────────────────────────────┐ ││ │ │ │ implements ContextInner │ ││ -│ │ │ owns pending_local: RefCell)>> │ ││ +│ │ │ pending_local: RefCell)>> │ ││ +│ │ │ stop_requests: RefCell> │ ││ +│ │ │ timer_requests: RefCell> │ ││ │ │ └────────────────────────────────────────────────────────────┘ ││ │ │ ││ │ │ for each (addr, slot) in pool: ││ +│ │ if poisoned or stopping → clear mailbox, skip ││ │ │ ││ -│ │ ┌─ drain_count ──────────────────────────────────────────┐ ││ -│ │ │ len = slot.mailbox.len() │ ││ -│ │ │ len < waterlevel --> n = len (drain all) │ ││ -│ │ │ len >= waterlevel --> n = len / 2 (backpressure) │ ││ -│ │ └────────────────────────────────────────────────────────┘ ││ +│ │ ┌─ on_start (once per actor) ──────────────────────────────┐ ││ +│ │ │ if !slot.started: │ ││ +│ │ │ catch_unwind(actor.on_start(&ctx)) │ ││ +│ │ │ panic → poisoned (immediate, no messages) │ ││ +│ │ │ ok → started = true │ ││ +│ │ └──────────────────────────────────────────────────────────┘ ││ │ │ ││ -│ │ ctx = Ctx { inner: &worker_ctx, self_addr: addr } ││ -│ │ ││ -│ │ repeat n times: ││ -│ │ msg = slot.mailbox.pop_front() ││ -│ │ slot.actor.handle_any(&ctx, msg) ││ -│ │ │ ││ -│ │ │ actor calls ctx.send() or ctx.spawn() ││ -│ │ v ││ +│ │ ┌─ message loop (budget-limited) ──────────────────────────┐ ││ +│ │ │ repeat up to `budget` times (budget=0 → unlimited): │ ││ +│ │ │ msg = slot.mailbox.pop_front() │ ││ +│ │ │ │ ││ +│ │ │ if msg is StopSignal: │ ││ +│ │ │ slot.stopping = true; clear mailbox; break │ ││ +│ │ │ │ ││ +│ │ │ catch_unwind(actor.handle_any(&ctx, msg)) │ ││ +│ │ │ panic → try_restart (factory) or poison │ ││ +│ │ │ ok → count += 1 │ ││ +│ │ │ │ ││ +│ │ │ if stop_requests contains addr: │ ││ +│ │ │ slot.stopping = true; clear mailbox; break │ ││ +│ │ └──────────────────────────────────────────────────────────┘ ││ │ │ ││ │ │ ┌─ WorkerContext routes ─────────────────────────────────────┐ ││ │ │ │ │ ││ @@ -171,29 +206,91 @@ Lives on `Arc`, shared read-only across all worker threads. │ │ │ │ same worker │ other worker │ unknown addr │ │ ││ │ │ │ │ │ │ │ │ ││ │ │ │ │ pending_ │ transfer_tx │ inbox_registry │ │ ││ -│ │ │ │ local.push()│ [wid].send()│ .try_deliver() │ │ ││ +│ │ │ │ local.push()│ + unpark │ .try_deliver() │ │ ││ │ │ │ └──────────────┴──────────────┴─────────────────┘ │ ││ │ │ │ │ ││ │ │ │ spawn_any(addr, actor): │ ││ -│ │ │ wid = placement.next_worker() │ ││ +│ │ │ wid = placement.next_worker() (load-aware) │ ││ │ │ │ address_map.insert(addr, wid) │ ││ -│ │ │ spawn_txs[wid].send((addr, actor)) │ ││ +│ │ │ spawn_txs[wid].send((addr, actor)) + unpark │ ││ +│ │ │ │ ││ +│ │ │ request_stop(addr): → stop_requests.push(addr) │ ││ +│ │ │ schedule_timer(req): → timer_requests.push(req) │ ││ +│ │ │ where_is(name): → name_registry.lookup(name) │ ││ +│ │ │ monitor(w, t): → monitor_registry.register(w, t) │ ││ +│ │ │ join_group(a, g): → group_registry.join(g, a) │ ││ │ │ │ │ ││ │ │ └────────────────────────────────────────────────────────────┘ ││ │ │ ││ │ └────────────────────────────────────────────────────────────────────┘│ │ │ │ │ v │ -│ PHASE 4 --- Drain Pending Local │ +│ PHASE 4 --- Drain Spawn Queue (again) │ +│ ┌────────────────────────────────────────────────────────────────────┐│ +│ │ Actors spawned during phase 3 must be in the pool before ││ +│ │ pending_local delivery (phase 5). ││ +│ └────────────────────────────────────────────────────────────────────┘│ +│ │ │ +│ v │ +│ PHASE 5 --- Drain Pending Local │ │ ┌────────────────────────────────────────────────────────────────────┐│ │ │ ││ │ │ for (addr, msg) in pending_local.into_inner(): ││ │ │ pool.deliver(&addr, msg) ││ -│ │ --> slot.mailbox.push_back(msg) ││ -│ │ ││ │ │ these sit in the mailbox until NEXT tick ││ │ │ ││ │ └────────────────────────────────────────────────────────────────────┘│ +│ │ │ +│ v │ +│ PHASE 5.5 --- Drain Timer Requests │ +│ ┌────────────────────────────────────────────────────────────────────┐│ +│ │ ││ +│ │ for request in timer_requests: ││ +│ │ Once { dest, msg, ticks } → timers.add_once(dest, msg, ticks) ││ +│ │ Interval { dest, msg, p } → timers.add_interval(dest, msg, p) ││ +│ │ ││ +│ └────────────────────────────────────────────────────────────────────┘│ +│ │ │ +│ v │ +│ PHASE 6 --- Publish Stats │ +│ ┌────────────────────────────────────────────────────────────────────┐│ +│ │ ││ +│ │ if did_work: ││ +│ │ stats.num_actors, total_mailbox_depth, messages_processed ││ +│ │ stats.messages_dropped (if any overflow drops) ││ +│ │ stats_hook.on_tick(worker_id, snapshots) if configured ││ +│ │ ││ +│ │ record TickTiming (6-element phase_us array + processed + flag) ││ +│ │ ││ +│ └────────────────────────────────────────────────────────────────────┘│ +│ │ │ +│ v │ +│ PHASE 7 --- Cleanup Dead Actors │ +│ ┌────────────────────────────────────────────────────────────────────┐│ +│ │ ││ +│ │ pool.cleanup_dead() → Vec<(ActorAddress, StopReason)> ││ +│ │ stopping actors: call on_stop(&ctx) before removal ││ +│ │ poisoned actors: skip on_stop (state may be corrupt) ││ +│ │ ││ +│ │ for each dead (addr, reason): ││ +│ │ address_map.remove(&addr) ││ +│ │ name_registry.unregister_by_addr(&addr) ││ +│ │ group_registry.cleanup(&addr) ││ +│ │ ││ +│ │ deliver any messages sent during on_stop callbacks ││ +│ │ ││ +│ │ emit Down notifications for monitored dead actors: ││ +│ │ for (addr, reason) in dead: ││ +│ │ watchers = monitor_registry.take_monitors(&addr) ││ +│ │ for each watcher: route Down { addr, reason } ││ +│ │ same-worker → pool.deliver ││ +│ │ cross-worker → transfer_tx + unpark ││ +│ │ inbox → inbox_registry.try_deliver ││ +│ │ monitor_registry.remove_watcher(&addr) ││ +│ │ ││ +│ │ timers.gc_dead_intervals(dead_addrs) ││ +│ │ ││ +│ └────────────────────────────────────────────────────────────────────┘│ │ │ └────────────────────────────────────────────────────────────────────────┘ ``` @@ -400,7 +497,9 @@ Who holds what: ``` ┌─ User Code ────────────────────────────────────────────────────────────┐ -│ rt.spawn() rt.send_to() inbox.try_recv() rt.shutdown() │ +│ rt.spawn() rt.send_to() inbox.try_recv() rt.shutdown() │ +│ rt.spawn_named() rt.ask() rt.where_is() rt.stop_actor()│ +│ rt.join_group() rt.publish_to() rt.group_members() │ └────┬──────────────────┬──────────────────┬──────────────────┬──────────┘ │ │ ^ │ v v │ v @@ -408,10 +507,16 @@ Who holds what: │ │ │ ┌───────────┐ ┌────────────┐ ┌─────────────┐ ┌────────────┐ │ │ │AddressMap │ │ Placement │ │InboxRegistry│ │ is_running │ │ -│ │ addr->wid │ │ round-robin│ │ addr->Sender│ │ AtomicBool │ │ +│ │ addr->wid │ │ load-aware │ │ addr->Sender│ │ AtomicBool │ │ │ └─────┬─────┘ └──────┬─────┘ └──────┬──────┘ └──────┬─────┘ │ │ │ │ │ │ │ -│ ┌─────┴───────────────┴──────────────┴───────────────┴────────────────┐ │ +│ ┌─────────────┐ ┌──────────────┐ ┌─────────────┐ │ +│ │NameRegistry │ │MonitorRegist.│ │GroupRegistry │ │ +│ │ name->addr │ │ watched-> │ │ group->addrs │ │ +│ │ addr->name │ │ watchers │ │ addr->groups │ │ +│ └─────┬───────┘ └──────┬───────┘ └──────┬───────┘ │ +│ │ │ │ │ +│ ┌─────┴───────────────┴──────────────┴───────────────────────────────┐ │ │ │ TickContext (borrows all above) │ │ │ └──────────────────────────┬──────────────────────────────────────────┘ │ │ │ │ diff --git a/fuzz/fuzz_targets/fuzz_runtime.rs b/fuzz/fuzz_targets/fuzz_runtime.rs index aea7a0a..54349ee 100644 --- a/fuzz/fuzz_targets/fuzz_runtime.rs +++ b/fuzz/fuzz_targets/fuzz_runtime.rs @@ -144,6 +144,51 @@ impl ActorInterface for WrongTypeActor { fn handle(&mut self, _ctx: &Ctx, _msg: WrongTypeMsg) {} } +/// Timer actor: on message, schedules a one-shot timer to deliver the message +/// to the given target after `delay` ticks. +struct TimerSchedulerActor { + target: ActorAddress, + delay: u64, +} +impl ActorInterface for TimerSchedulerActor { + type Incoming = FuzzMsg; + type Response = (); + fn handle(&mut self, ctx: &Ctx, msg: FuzzMsg) { + ctx.send_after_ticks(self.target, msg, self.delay); + } +} + +/// Interval timer actor: on start, schedules an interval timer to fire +/// to the target every `period` ticks. +struct IntervalSchedulerActor { + target: ActorAddress, + period: u64, +} +impl ActorInterface for IntervalSchedulerActor { + type Incoming = FuzzMsg; + type Response = (); + fn on_start(&mut self, ctx: &Ctx) { + ctx.send_interval_ticks(self.target, FuzzMsg { value: 0, reply_to_idx: None }, self.period); + } + fn handle(&mut self, _ctx: &Ctx, _msg: FuzzMsg) {} +} + +/// Panicking echo: panics on value=0, otherwise echoes. +struct PanickingEchoActor; +impl ActorInterface for PanickingEchoActor { + type Incoming = FuzzMsg; + type Response = (); + fn handle(&mut self, ctx: &Ctx, msg: FuzzMsg) { + if msg.value == 0 { + panic!("fuzz: intentional panic"); + } + if let Some(idx) = msg.reply_to_idx { + let reply = FuzzMsg { value: msg.value, reply_to_idx: None }; + let _ = ctx.send(INBOX_ADDRS.lock_or_default().get(idx as usize), reply); + } + } +} + // ─── Shared Inbox Address Table ───────────────────────────────────────────── struct InboxAddrs(Vec); @@ -205,6 +250,14 @@ enum RawAction { DrainAll, Tick, TickN { n: u8 }, + /// Graceful stop an actor + StopActor { actor_idx: u8 }, + /// Spawn a panicking echo actor (panics on value=0) + SpawnPanicking, + /// Schedule a one-shot timer from an actor to an inbox + ScheduleTimer { delay: u8 }, + /// Schedule an interval timer from an actor to an inbox + ScheduleInterval { actor_idx: u8, period: u8 }, } #[derive(Debug, Arbitrary)] @@ -753,6 +806,50 @@ impl FuzzState { RawAction::DrainAll => { self.drain_all_inboxes(); } RawAction::Tick => { self.tick(); } RawAction::TickN { n } => { self.tick_n((*n).max(1).min(64) as usize); } + RawAction::StopActor { actor_idx } => { + if let Some(addr) = self.resolve_actor(*actor_idx) { + let label = self.actor_label(addr); + let _ = self.runtime.stop_actor(addr); + self.log(format_args!("[STOP] {label}")); + } + } + RawAction::SpawnPanicking => { + if let Ok(addr) = self.runtime.spawn(PanickingEchoActor) { + let id = self.actors.len(); + self.actors.push((addr, ActorKind::Echo)); + self.total_spawned += 1; + self.log(format_args!("[SPAWN] PanickingEcho -> actor#{id}")); + } + } + RawAction::ScheduleTimer { delay } => { + // Create a timer scheduler actor, send it a message to trigger scheduling + let delay = (*delay).max(1).min(10) as u64; + if self.inboxes.is_empty() { self.new_inbox(); } + if let Some(idx) = self.resolve_inbox_idx(0) { + let target = *self.inboxes[idx].addr(); + if let Ok(addr) = self.runtime.spawn(TimerSchedulerActor { target, delay }) { + let id = self.actors.len(); + self.actors.push((addr, ActorKind::Echo)); + self.total_spawned += 1; + self.tick(); // bring actor alive + self.send_msg(addr, FuzzMsg { value: 42, reply_to_idx: None }); + self.log(format_args!("[TIMER] actor#{id} -> inbox#{idx} delay={delay}")); + } + } + } + RawAction::ScheduleInterval { actor_idx, period } => { + let period = (*period).max(1).min(5) as u64; + if self.inboxes.is_empty() { self.new_inbox(); } + if let Some(idx) = self.resolve_inbox_idx(*actor_idx) { + let target = *self.inboxes[idx].addr(); + if let Ok(addr) = self.runtime.spawn(IntervalSchedulerActor { target, period }) { + let id = self.actors.len(); + self.actors.push((addr, ActorKind::Echo)); + self.total_spawned += 1; + self.log(format_args!("[INTVL] actor#{id} -> inbox#{idx} period={period}")); + } + } + } } } } diff --git a/src/actor.rs b/src/actor.rs index 95ad87b..17b9504 100644 --- a/src/actor.rs +++ b/src/actor.rs @@ -10,15 +10,50 @@ pub trait ActorInterface: 'static + Send { type Incoming: Message; type Response: Message; fn handle(&mut self, ctx: &Ctx, msg: Self::Incoming); + + /// Called once after the actor is added to a worker, before the first message. + /// Receives `&Ctx` so the actor can send messages or spawn children during init. + /// + /// If `on_start` panics, the actor is immediately poisoned (no restart attempted). + fn on_start(&mut self, _ctx: &Ctx) {} + + /// Called when the actor is being gracefully stopped (via `ctx.stop_self()` or + /// `Runtime::stop_actor()`), before removal from the worker pool. + /// + /// NOT called when an actor is poisoned by panic — panicked actors may have + /// corrupt state and calling methods on them is unsafe. + fn on_stop(&mut self, _ctx: &Ctx) {} + + /// Called when a monitored actor dies (via [`Ctx::monitor`]). + /// + /// Override this to react to death notifications without making [`Down`] + /// your `Incoming` type. Default: no-op (the `Down` message is silently consumed). + /// + /// If your `Incoming` type IS `Down`, this method is never called — the + /// normal `handle()` receives the message instead. + fn handle_down(&mut self, _ctx: &Ctx, _down: Down) {} } /// A unique address for this actor. 32 bytes is overkill for a small application, /// but most systems are powerful, and this allows us to create a global map of /// actor processes in the future, without worrying about collision. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct ActorAddress(pub [u8; 32]); +/// Custom Hash: only hash the first 8 bytes since all 32 are random. +/// SipHash on 8 bytes is ~3x faster than on 32 bytes, with identical +/// collision properties (2^64 possible values from cryptographic randomness). +impl std::hash::Hash for ActorAddress { + #[inline] + fn hash(&self, state: &mut H) { + // SAFETY: ActorAddress is always 32 bytes, so [..8] is valid. + state.write_u64(u64::from_ne_bytes( + self.0[..8].try_into().unwrap(), + )); + } +} + impl std::fmt::Display for ActorAddress { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for b in &self.0[..8] { @@ -36,11 +71,13 @@ impl ActorAddress { } /// The actor process as represented in the Runtime — thin wrapper around user state. -pub struct Actor(A); +pub struct Actor { + inner: A, +} impl Actor { pub fn new(inner: A) -> Self { - Self(inner) + Self { inner } } } @@ -49,6 +86,12 @@ impl Actor { /// Returns `Some(type_name)` if handled, `None` on type mismatch. pub trait AnyActor: Send { fn handle_any(&mut self, ctx: &Ctx, msg: Box) -> Option<&'static str>; + + /// Called once after spawn, before first message. See [`ActorInterface::on_start`]. + fn on_start(&mut self, _ctx: &Ctx) {} + + /// Called on graceful stop, before removal. See [`ActorInterface::on_stop`]. + fn on_stop(&mut self, _ctx: &Ctx) {} } impl AnyActor for Actor @@ -56,25 +99,119 @@ where A: ActorInterface, { fn handle_any(&mut self, ctx: &Ctx, msg: Box) -> Option<&'static str> { - if let Ok(typed) = msg.downcast::() { - self.0.handle(ctx, *typed); - Some(std::any::type_name::()) - } else { - None + let msg = match msg.downcast::() { + Ok(typed) => { + self.inner.handle(ctx, *typed); + return Some(std::any::type_name::()); + } + Err(msg) => msg, + }; + match msg.downcast::() { + Ok(down) => { + self.inner.handle_down(ctx, *down); + Some("swactor::actor::Down") + } + Err(_) => None, } } + + fn on_start(&mut self, ctx: &Ctx) { + self.inner.on_start(ctx); + } + + fn on_stop(&mut self, ctx: &Ctx) { + self.inner.on_stop(ctx); + } +} + +/// Unique token identifying a monitor subscription. +/// +/// Returned by [`Ctx::monitor`] and used with [`Ctx::demonitor`] to cancel. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct MonitorRef(pub(crate) u64); + +impl MonitorRef { + /// Construct a MonitorRef from a raw id. Used by extension crates. + pub fn from_raw(id: u64) -> Self { + Self(id) + } +} + +/// Reason an actor was removed from the runtime. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum StopReason { + /// Graceful stop (via `ctx.stop_self()` or `Runtime::stop_actor()`). + Normal, + /// Actor panicked and could not be restarted. + Panicked, +} + +/// Death notification delivered as a normal message when a monitored actor dies. +/// +/// Subscribe via [`Ctx::monitor`]. The `Down` message arrives in the watcher's +/// regular `handle()` method — no special callback needed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Down { + /// Address of the dead actor. + pub addr: ActorAddress, + /// Why it died. + pub reason: StopReason, +} + +/// Internal sentinel message for graceful actor stop. +/// Not a `Message` — intercepted in `tick_all` before reaching `handle_any`. +pub(crate) struct StopSignal; + +/// Type-erased cloneable message for interval timers. +/// Since `Message: Clone`, all actor messages can implement this. +pub(crate) trait CloneMsg: Send { + fn clone_boxed(&self) -> Box; +} + +impl CloneMsg for M { + fn clone_boxed(&self) -> Box { + Box::new(self.clone()) + } +} + +/// Timer request from a handler, queued for processing after tick_all. +pub(crate) enum TimerRequest { + /// One-shot: deliver `msg` to `dest` after `ticks` worker ticks. + Once { + dest: ActorAddress, + msg: Box, + ticks: u64, + }, + /// Repeating: deliver a clone of `msg` to `dest` every `period` ticks. + Interval { + dest: ActorAddress, + msg: Box, + period: u64, + }, } /// Object-safe inner trait for sending type-erased messages. +/// +/// Minimal core interface: send, spawn, stop, timers, and extension access. +/// Registry methods (naming, monitoring, groups) are provided by extension +/// traits in `swactor-std`. +#[allow(private_interfaces)] pub trait ContextInner { fn send_any(&self, addr: ActorAddress, msg: Box) -> Result<(), Error>; fn spawn_any(&self, addr: ActorAddress, actor: Box); + /// Request graceful stop for an actor. Takes effect after the current message. + fn request_stop(&self, addr: ActorAddress); + /// Schedule a timer (one-shot or interval). + fn schedule_timer(&self, request: TimerRequest); + /// Access the runtime extension (if installed). + fn extension(&self) -> Option<&dyn crate::extension::RuntimeExtension>; } /// Actor syscall interface — passed to `ActorInterface::handle()`. /// /// Wraps a `&dyn ContextInner` to solve the object-safety problem while -/// providing a typed public API. +/// providing a typed public API. Registry methods (naming, monitoring, groups) +/// are provided by extension traits in `swactor-std`. pub struct Ctx<'a> { inner: &'a dyn ContextInner, self_addr: ActorAddress, @@ -94,6 +231,11 @@ impl<'a> Ctx<'a> { self.self_addr } + /// Access the runtime extension (if installed). + pub fn extension(&self) -> Option<&dyn crate::extension::RuntimeExtension> { + self.inner.extension() + } + /// Send a typed message to an actor address. pub fn send(&self, addr: ActorAddress, msg: M) -> Result<(), Error> { self.inner.send_any(addr, Box::new(msg)) @@ -106,4 +248,46 @@ impl<'a> Ctx<'a> { self.inner.spawn_any(addr, boxed); Ok(addr) } + + /// Request graceful stop for this actor after the current message completes. + /// + /// The actor's `on_stop()` hook is called and the actor is removed from the + /// worker pool. Pending messages in the mailbox are discarded. + pub fn stop_self(&self) { + self.inner.request_stop(self.self_addr); + } + + /// Send a graceful stop request to another actor. + /// + /// The target actor will process any messages already in its mailbox before + /// the stop signal, then its `on_stop()` hook is called and it is removed. + /// Uses PoisonPill semantics — queued after existing messages. + pub fn stop_actor(&self, addr: ActorAddress) -> Result<(), Error> { + self.inner.send_any(addr, Box::new(StopSignal)) + } + + /// Schedule a one-shot timer: deliver `msg` to `addr` after `ticks` worker ticks. + /// + /// The message is delivered as a normal mailbox message during the fire tick, + /// before `tick_all` processes messages. The timer is tick-counted (deterministic), + /// not wall-clock based. + pub fn send_after_ticks(&self, addr: ActorAddress, msg: M, ticks: u64) { + self.inner.schedule_timer(TimerRequest::Once { + dest: addr, + msg: Box::new(msg), + ticks, + }); + } + + /// Schedule a repeating timer: deliver a clone of `msg` to `addr` every `period` ticks. + /// + /// The first delivery happens after `period` ticks. The message is cloned for each + /// delivery. The timer continues until the target actor is stopped/poisoned. + pub fn send_interval_ticks(&self, addr: ActorAddress, msg: M, period: u64) { + self.inner.schedule_timer(TimerRequest::Interval { + dest: addr, + msg: Box::new(msg), + period, + }); + } } diff --git a/src/channel.rs b/src/channel.rs index 4860704..38f6c3d 100644 --- a/src/channel.rs +++ b/src/channel.rs @@ -1,4 +1,3 @@ - use std::sync::Arc; use crossbeam_queue::{ArrayQueue, SegQueue}; diff --git a/src/config.rs b/src/config.rs index ef8c9b7..4772bd4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -23,12 +23,30 @@ impl Default for BackoffPolicy { } } +/// What to do when a bounded mailbox is full. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MailboxOverflow { + /// Drop the incoming message (newest). The message is silently discarded. + DropNewest, + /// Drop the oldest message in the queue to make room for the new one. + DropOldest, +} + /// The tunable settings for the runtime. pub struct RuntimeConfig { pub max_actors: usize, pub channel_buffer_size: usize, pub num_threads: usize, pub backoff_policy: BackoffPolicy, + /// Maximum messages processed per actor per tick. + /// Prevents a single actor with a large mailbox from starving others. + /// `0` means unlimited (drain entire mailbox). + pub actor_message_budget: usize, + /// Default per-actor mailbox capacity. `0` means unbounded (no limit). + /// When non-zero, `mailbox_overflow` controls what happens when the mailbox is full. + pub default_mailbox_capacity: usize, + /// Overflow policy for bounded mailboxes. Ignored when `default_mailbox_capacity` is 0. + pub mailbox_overflow: MailboxOverflow, } /// 8kB for the `Box<..>` before counting the rest of the memory @@ -38,6 +56,11 @@ const DEFAULT_MAX_ACTORS: usize = 1_000; /// When the ring is full, messages overflow into an unbounded backup queue. const DEFAULT_CHANNEL_BUFFER_SIZE: usize = 1_000; +/// Default per-actor message budget per tick. +/// Inspired by BEAM's reduction budget (4000) and tokio's cooperative budget (128). +/// 64 is a good default: high enough for throughput, low enough for fairness. +const DEFAULT_ACTOR_MESSAGE_BUDGET: usize = 64; + impl Default for RuntimeConfig { fn default() -> Self { Self { @@ -45,6 +68,9 @@ impl Default for RuntimeConfig { channel_buffer_size: DEFAULT_CHANNEL_BUFFER_SIZE, num_threads: 1, backoff_policy: BackoffPolicy::default(), + actor_message_budget: DEFAULT_ACTOR_MESSAGE_BUDGET, + default_mailbox_capacity: 0, + mailbox_overflow: MailboxOverflow::DropNewest, } } } diff --git a/src/delivery.rs b/src/delivery.rs index 9841059..b1f3aeb 100644 --- a/src/delivery.rs +++ b/src/delivery.rs @@ -1,13 +1,65 @@ use std::any::Any; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; +use std::hash::{BuildHasher, Hasher}; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Arc, RwLock}; +use std::sync::{Arc, OnceLock, RwLock}; +use std::thread::Thread; use crate::actor::{ActorAddress, AnyActor, Message}; use crate::channel::Sender; use crate::config::RuntimeConfig; +use crate::stats::WorkerStats; use crate::Error; +// ─── Identity Hasher for ActorAddress ─────────────────────────────────────── + +/// Identity hasher for ActorAddress keys. +/// +/// ActorAddress contains 32 cryptographically random bytes. The custom `Hash` +/// impl on ActorAddress writes only the first 8 bytes as a `u64`. This hasher +/// passes that u64 through as the hash value directly — no mixing, no SipHash. +/// +/// This is safe because the input is already random (uniform distribution), +/// so additional mixing would be redundant. +pub struct AddrHasher(u64); + +impl Hasher for AddrHasher { + #[inline] + fn finish(&self) -> u64 { + self.0 + } + + #[inline] + fn write(&mut self, _bytes: &[u8]) { + // Unused — ActorAddress::hash calls write_u64 directly. + } + + #[inline] + fn write_u64(&mut self, i: u64) { + self.0 = i; + } +} + +/// BuildHasher for creating AddrHasher instances. +#[derive(Default, Clone)] +pub struct AddrBuildHasher; + +impl BuildHasher for AddrBuildHasher { + type Hasher = AddrHasher; + + #[inline] + fn build_hasher(&self) -> AddrHasher { + AddrHasher(0) + } +} + +/// HashMap optimized for ActorAddress keys. +/// Uses identity hashing since ActorAddress bytes are already random. +pub type AddrMap = HashMap; + +/// HashSet optimized for ActorAddress keys. +pub type AddrSet = HashSet; + // ─── Address Map Types ─────────────────────────────────────────────────────── /// Identifies a worker thread. @@ -24,13 +76,13 @@ impl WorkerId { /// /// `RwLock` — zero contention for parallel reads, write-rare (only on spawn). pub(crate) struct AddressMap { - inner: RwLock>, + inner: RwLock>, } impl AddressMap { pub fn with_capacity(cap: usize) -> Self { Self { - inner: RwLock::new(HashMap::with_capacity(cap)), + inner: RwLock::new(HashMap::with_capacity_and_hasher(cap, AddrBuildHasher)), } } @@ -42,6 +94,11 @@ impl AddressMap { self.inner.read().unwrap().get(addr).copied() } + /// Remove an actor address from the map (e.g., after permanent poisoning). + pub fn remove(&self, addr: &ActorAddress) { + self.inner.write().unwrap().remove(addr); + } + /// Returns a snapshot of all (address, worker) pairs. pub fn snapshot(&self) -> Vec<(ActorAddress, WorkerId)> { self.inner @@ -53,23 +110,50 @@ impl AddressMap { } } -/// Round-robin actor placement strategy. +/// Load-aware actor placement strategy. +/// +/// Picks the worker with the lowest load score (actor count + mailbox depth). +/// When all workers have equal load (e.g., before any ticks), falls back to +/// round-robin via a rotating start position for the scan. pub(crate) struct Placement { next: AtomicUsize, num_workers: usize, + worker_stats: Vec>, } impl Placement { - pub fn new(num_workers: usize) -> Self { + pub fn new(num_workers: usize, worker_stats: Vec>) -> Self { Self { next: AtomicUsize::new(0), num_workers, + worker_stats, } } pub fn next_worker(&self) -> WorkerId { - let id = self.next.fetch_add(1, Ordering::Relaxed) % self.num_workers; - WorkerId(id) + let n = self.num_workers; + if n == 1 { + return WorkerId(0); + } + + // Rotate the scan start for round-robin tie-breaking + let rr = self.next.fetch_add(1, Ordering::Relaxed); + + let mut best_id = rr % n; + let mut best_score = usize::MAX; + + for offset in 0..n { + let i = (rr + offset) % n; + let actors = self.worker_stats[i].num_actors.load(Ordering::Relaxed); + let depth = self.worker_stats[i].total_mailbox_depth.load(Ordering::Relaxed); + let score = actors + depth; + if score < best_score { + best_score = score; + best_id = i; + } + } + + WorkerId(best_id) } } @@ -112,13 +196,13 @@ impl SenderT for Sender { /// Registry of external inboxes — replaces the Router's role for non-actor receivers. pub(crate) struct InboxRegistry { - senders: RwLock>>, + senders: RwLock>>, } impl InboxRegistry { pub fn new() -> Self { Self { - senders: RwLock::new(HashMap::new()), + senders: RwLock::new(HashMap::with_hasher(AddrBuildHasher)), } } @@ -127,6 +211,7 @@ impl InboxRegistry { } /// Check if an address is registered without consuming a message. + #[cfg(feature = "transport")] pub fn contains(&self, addr: &ActorAddress) -> bool { self.senders.read().unwrap().contains_key(addr) } @@ -154,7 +239,10 @@ pub(crate) struct TickContext<'a> { pub(crate) placement: &'a Placement, pub(crate) inbox_registry: &'a InboxRegistry, pub(crate) config: &'a RuntimeConfig, + pub(crate) extension: Option<&'a dyn crate::extension::RuntimeExtension>, pub(crate) stats_hook: Option<&'a dyn crate::stats::StatsHook>, + /// Thread handles for waking parked workers on cross-worker sends. + pub(crate) worker_threads: &'a [OnceLock], #[cfg(feature = "transport")] pub(crate) codec_registry: Option<&'a crate::transport::CodecRegistry>, #[cfg(feature = "transport")] diff --git a/src/extension.rs b/src/extension.rs new file mode 100644 index 0000000..7028bd2 --- /dev/null +++ b/src/extension.rs @@ -0,0 +1,28 @@ +use std::any::Any; + +use crate::actor::{ActorAddress, StopReason}; + +/// Extension hook for runtime lifecycle events. +/// +/// Stored as `Arc` in the Runtime. Workers access it +/// via TickContext. Ctx methods that need registry access downcast to the +/// concrete type via `as_any()`. +/// +/// Core calls these methods at appropriate tick phases: +/// - `on_actor_death`: called during phase 7 (cleanup_dead) with newly dead actors +/// - `cleanup_dead`: called during phase 7 to clean up extension state +pub trait RuntimeExtension: Send + Sync { + /// Called during phase 7 (cleanup_dead) for each dead actor. + /// Returns (destination, message) pairs for death notifications. + /// The core delivers these through normal routing (pending_local or transfer queue). + fn on_actor_death( + &self, + dead: &[(ActorAddress, StopReason)], + ) -> Vec<(ActorAddress, Box)>; + + /// Clean up extension state for dead actors (names, groups, monitors). + fn cleanup_dead(&self, dead: &[ActorAddress]); + + /// Downcast support for Ctx extension traits. + fn as_any(&self) -> &dyn Any; +} diff --git a/src/lib.rs b/src/lib.rs index 06642fc..146ff90 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,10 +1,13 @@ pub mod actor; +pub mod extension; pub mod worker; pub(crate) mod channel; pub(crate) mod error; pub use error::Error; +// Re-export identity hashing types for ActorAddress-keyed collections. +pub use delivery::{AddrBuildHasher, AddrMap, AddrSet}; pub mod config; pub(crate) mod delivery; diff --git a/src/runtime.rs b/src/runtime.rs index 314fcf6..815e051 100644 --- a/src/runtime.rs +++ b/src/runtime.rs @@ -1,15 +1,16 @@ use std::any::Any; use std::cell::RefCell; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; -use std::thread::{self, JoinHandle}; +use std::sync::{Arc, OnceLock}; +use std::thread::{self, JoinHandle, Thread}; use std::time::Instant; -use crate::actor::{Actor, ActorAddress, ActorInterface, AnyActor, Message}; +use crate::actor::{Actor, ActorAddress, ActorInterface, AnyActor, Message, StopSignal, TimerRequest}; use crate::channel::{Receiver, Sender}; // Re-export config types so existing code using `runtime::RuntimeConfig` still works -pub use crate::config::{BackoffPolicy, RuntimeConfig}; +pub use crate::config::{BackoffPolicy, MailboxOverflow, RuntimeConfig}; use crate::delivery::{AddressMap, Envelope, InboxRegistry, Placement, TickContext, WorkerId}; +use crate::extension::RuntimeExtension; use crate::stats::{StatsHook, WorkerStats}; // Re-export stats types so existing code using `runtime::*` still works pub use crate::stats::{RuntimeStats, WorkerInfo}; @@ -32,6 +33,39 @@ impl Inbox { } } +/// Pending ask response — wraps an inbox with convenience recv methods. +/// +/// Created by [`Runtime::ask`]. Provides `try_recv()` for polling and +/// `recv_ticking()` for automatic tick-until-response. +pub struct Ask { + inbox: Inbox, +} + +impl Ask { + /// Try to receive the response without ticking. + pub fn try_recv(&self) -> Option { + self.inbox.try_recv() + } + + /// Tick the runtime until a response arrives or `max_ticks` is exhausted. + /// + /// Only valid for single-threaded runtimes (panics if `num_threads >= 2`). + pub fn recv_ticking(&self, rt: &Runtime, max_ticks: usize) -> Result { + for _ in 0..max_ticks { + rt.tick(); + if let Some(resp) = self.inbox.try_recv() { + return Ok(resp); + } + } + Err(Error::from("ask timeout: no response within max_ticks")) + } + + /// Get the reply address (for manual message construction). + pub fn reply_addr(&self) -> &ActorAddress { + self.inbox.addr() + } +} + /// Handle for dealing with a runtime that has started via the `Runtime::run()` method. pub struct RuntimeHandle { pub runtime: Arc, @@ -62,6 +96,7 @@ pub struct Runtime { config: RuntimeConfig, address_map: Arc, inbox_registry: Arc, + extension: Option>, transfer_txs: Vec>, spawn_txs: Vec)>>, placement: Placement, @@ -70,6 +105,8 @@ pub struct Runtime { stats_hook: Option>, /// Workers available for tick(). run() drains this and moves workers to threads. tick_workers: RefCell>, + /// Thread handles for waking parked workers. Set by workers on startup via OnceLock. + worker_threads: Vec>, created_at: Instant, #[cfg(feature = "transport")] codec_registry: Option>, @@ -117,7 +154,6 @@ impl Runtime { let address_map = Arc::new(AddressMap::with_capacity(config.max_actors)); let inbox_registry = Arc::new(InboxRegistry::new()); - let placement = Placement::new(num_workers); let mut transfer_txs = Vec::with_capacity(num_workers); let mut spawn_txs = Vec::with_capacity(num_workers); @@ -136,13 +172,26 @@ impl Runtime { let stats = Arc::new(WorkerStats::new()); worker_stats.push(stats.clone()); - workers.push(Worker::new(WorkerId(i), transfer_rx, spawn_rx, stats)); + workers.push(Worker::new( + WorkerId(i), + transfer_rx, + spawn_rx, + stats, + config.default_mailbox_capacity, + config.mailbox_overflow, + )); } + let placement = Placement::new(num_workers, worker_stats.clone()); + + let worker_threads: Vec> = + (0..num_workers).map(|_| OnceLock::new()).collect(); + let rt = Self { config, address_map, inbox_registry, + extension: None, transfer_txs, spawn_txs, placement, @@ -150,6 +199,7 @@ impl Runtime { worker_stats, stats_hook: None, tick_workers: RefCell::new(workers), + worker_threads, created_at: Instant::now(), #[cfg(feature = "transport")] codec_registry: None, @@ -186,6 +236,41 @@ impl Runtime { Ok(addr) } + /// Install a runtime extension. Extensions provide higher-level features + /// (naming, monitoring, groups) via lifecycle hooks. + /// + /// Must be called before `run()` or `tick()`. + pub fn with_extension(mut self, ext: Arc) -> Self { + self.extension = Some(ext); + self + } + + /// Access the installed runtime extension (if any). + pub fn extension(&self) -> Option<&dyn RuntimeExtension> { + self.extension.as_deref() + } + + /// Send a request and get a handle for the response. + /// + /// Creates a temporary inbox, calls `msg_builder` with the inbox's address + /// (so you can embed it as `reply_to`), sends the message, and returns an + /// [`Ask`] handle for receiving the response. + /// + /// ```ignore + /// let ask = rt.ask(actor, |reply_to| GetValue { reply_to })?; + /// let value = ask.recv_ticking(&rt, 10)?; + /// ``` + pub fn ask( + &self, + addr: ActorAddress, + msg_builder: impl FnOnce(ActorAddress) -> Req, + ) -> Result, Error> { + let inbox = self.new_inbox::()?; + let msg = msg_builder(*inbox.addr()); + self.send_to(addr, msg)?; + Ok(Ask { inbox }) + } + /// Send a message to an actor address pub fn send_to(&self, addr: ActorAddress, msg: M) -> Result<(), Error> { let result = self.send_any(addr, Box::new(msg)); @@ -216,7 +301,9 @@ impl Runtime { placement: &self.placement, inbox_registry: &self.inbox_registry, config: &self.config, + extension: self.extension.as_deref(), stats_hook: self.stats_hook.as_deref(), + worker_threads: &self.worker_threads, #[cfg(feature = "transport")] codec_registry: self.codec_registry.as_deref(), #[cfg(feature = "transport")] @@ -256,10 +343,13 @@ impl Runtime { for mut worker in workers { let rt_clone = rt.clone(); - let name = format!("swactor-worker-{}", worker.id.0); + let worker_id = worker.id.0; + let name = format!("swactor-worker-{}", worker_id); let handle = thread::Builder::new() .name(name) .spawn(move || { + // Register this thread so send_to/spawn can unpark us + let _ = rt_clone.worker_threads[worker_id].set(thread::current()); let tc = rt_clone.make_tick_context(); worker.run(&tc, &rt_clone.is_running); }) @@ -294,12 +384,36 @@ impl Runtime { RuntimeStats { num_workers, uptime_ms, actors, workers, actor_details: Vec::new(), tick_timings } } - /// Signal all workers to stop + /// Request an actor to stop gracefully. + /// + /// The actor's `on_stop()` hook is called before removal. Pending messages + /// in the mailbox are discarded. The stop takes effect on the next tick. + /// + /// Returns `Err` if the actor address is not found in the runtime. + pub fn stop_actor(&self, addr: ActorAddress) -> Result<(), Error> { + match self.address_map.lookup(&addr) { + Some(wid) => { + self.transfer_txs[wid.as_usize()] + .send(Envelope::new(addr, Box::new(StopSignal))); + notify_worker(&self.worker_threads, wid.as_usize()); + Ok(()) + } + None => Err(Error::from("Actor not found")), + } + } + + /// Signal all workers to stop and wake any that are parked. pub fn shutdown(&self) { #[cfg(feature = "tracing")] tracing::info!("runtime.shutdown"); self.is_running.store(false, Ordering::Release); + // Wake all parked workers so they see the shutdown flag immediately + for thread in &self.worker_threads { + if let Some(t) = thread.get() { + t.unpark(); + } + } } /// Set a stats hook to receive per-actor snapshots from workers. @@ -342,12 +456,23 @@ impl Runtime { } } +/// Wake a parked worker thread so it can process new work. +/// No-op if the thread handle hasn't been registered yet (single-threaded tick mode). +#[inline] +pub(crate) fn notify_worker(threads: &[OnceLock], wid: usize) { + if let Some(t) = threads.get(wid).and_then(|o| o.get()) { + t.unpark(); + } +} + +#[allow(private_interfaces)] impl ContextInner for Runtime { fn send_any(&self, addr: ActorAddress, msg: Box) -> Result<(), Error> { match self.address_map.lookup(&addr) { Some(wid) => { self.transfer_txs[wid.as_usize()] .send(Envelope::new(addr, msg)); + notify_worker(&self.worker_threads, wid.as_usize()); Ok(()) } None => self.make_tick_context().route_nonlocal(addr, msg), @@ -359,5 +484,26 @@ impl ContextInner for Runtime { self.address_map.insert(addr, worker_id); self.spawn_txs[worker_id.as_usize()] .send((addr, actor)); + notify_worker(&self.worker_threads, worker_id.as_usize()); + } + + fn request_stop(&self, addr: ActorAddress) { + // From spawn context (outside worker), send StopSignal through transfer queue + if let Some(wid) = self.address_map.lookup(&addr) { + self.transfer_txs[wid.as_usize()] + .send(Envelope::new(addr, Box::new(StopSignal))); + notify_worker(&self.worker_threads, wid.as_usize()); + } + } + + fn schedule_timer(&self, _request: TimerRequest) { + // Timers are per-worker and tick-counted; scheduling from outside + // a worker context (e.g., rt.spawn() callback) is not supported. + // Use rt.send_to() with a delay loop instead. + eprintln!("swactor: schedule_timer called outside worker context — ignored"); + } + + fn extension(&self) -> Option<&dyn RuntimeExtension> { + self.extension.as_deref() } } diff --git a/src/stats.rs b/src/stats.rs index 2b49db5..5cabf5b 100644 --- a/src/stats.rs +++ b/src/stats.rs @@ -30,6 +30,12 @@ pub struct WorkerStats { // Error counters pub type_mismatches: AtomicU64, pub panics: AtomicU64, + /// Messages dropped due to mailbox overflow (bounded mailbox policy). + pub messages_dropped: AtomicU64, + /// Number of actor restarts after panic (restartable actors only). + pub restarts: AtomicU64, + /// Number of actors gracefully stopped via `ctx.stop_self()` or `Runtime::stop_actor()`. + pub stops: AtomicU64, // Tick timing ring buffer (last N ticks, lock-free) tick_timings: ArrayQueue, } @@ -45,6 +51,9 @@ impl WorkerStats { inbox_sends: AtomicU64::new(0), type_mismatches: AtomicU64::new(0), panics: AtomicU64::new(0), + messages_dropped: AtomicU64::new(0), + restarts: AtomicU64::new(0), + stops: AtomicU64::new(0), tick_timings: ArrayQueue::new(TICK_BUFFER_CAP), } } @@ -79,6 +88,9 @@ impl WorkerStats { inbox_sends: self.inbox_sends.load(Relaxed), type_mismatches: self.type_mismatches.load(Relaxed), panics: self.panics.load(Relaxed), + messages_dropped: self.messages_dropped.load(Relaxed), + restarts: self.restarts.load(Relaxed), + stops: self.stops.load(Relaxed), } } } @@ -96,6 +108,9 @@ pub struct WorkerInfo { pub inbox_sends: u64, pub type_mismatches: u64, pub panics: u64, + pub messages_dropped: u64, + pub restarts: u64, + pub stops: u64, } /// Per-actor snapshot transferred from worker to runtime (not serialized). diff --git a/src/transport.rs b/src/transport.rs index 439c5a6..0955276 100644 --- a/src/transport.rs +++ b/src/transport.rs @@ -13,6 +13,7 @@ use std::collections::HashMap; use std::sync::{Arc, RwLock}; use crate::actor::{ActorAddress, Message}; +use crate::delivery::{AddrBuildHasher, AddrMap}; use crate::Error; // ─── Codec ────────────────────────────────────────────────────────────────── @@ -150,13 +151,13 @@ impl CodecRegistry { /// Maps remote actor addresses to their [`Transport`]. pub struct TransportRouter { - routes: RwLock>>, + routes: RwLock>>, } impl TransportRouter { pub fn new() -> Self { Self { - routes: RwLock::new(HashMap::new()), + routes: RwLock::new(HashMap::with_hasher(AddrBuildHasher)), } } diff --git a/src/worker.rs b/src/worker.rs index a257a30..35f0f52 100644 --- a/src/worker.rs +++ b/src/worker.rs @@ -6,12 +6,110 @@ use std::sync::Arc; use std::thread; use std::time::Instant; -use crate::actor::{ActorAddress, AnyActor, ContextInner, Ctx}; +use crate::actor::{ActorAddress, AnyActor, CloneMsg, ContextInner, Ctx, StopReason, StopSignal, TimerRequest}; use crate::channel::Receiver; -use crate::delivery::{Envelope, TickContext, WorkerId}; +use crate::config::MailboxOverflow; +use crate::delivery::{AddrBuildHasher, AddrMap, Envelope, TickContext, WorkerId}; use crate::stats::{ActorSnapshot, TickTiming, WorkerStats}; use crate::Error; +// ─── Per-Worker Timer Wheel ───────────────────────────────────────────────── + +struct OnceTimer { + fire_at: u64, + dest: ActorAddress, + msg: Box, +} + +struct IntervalTimer { + next_fire: u64, + period: u64, + dest: ActorAddress, + msg: Box, +} + +/// Per-worker tick-counting timer wheel. +/// +/// Timers are deterministic (tick-counted, not wall-clock). One-shot timers +/// fire once and are consumed; interval timers fire repeatedly every N ticks. +struct TimerWheel { + current_tick: u64, + once_timers: Vec, + interval_timers: Vec, +} + +impl TimerWheel { + fn new() -> Self { + Self { + current_tick: 0, + once_timers: Vec::new(), + interval_timers: Vec::new(), + } + } + + /// Advance the tick counter and collect all due timer messages. + /// Returns the messages to be routed by the caller (may target local or remote actors/inboxes). + fn fire(&mut self) -> Vec<(ActorAddress, Box)> { + self.current_tick += 1; + let tick = self.current_tick; + let mut result = Vec::new(); + + // Fire one-shot timers (swap-remove for O(1) removal) + let mut i = 0; + while i < self.once_timers.len() { + if self.once_timers[i].fire_at <= tick { + let timer = self.once_timers.swap_remove(i); + result.push((timer.dest, timer.msg)); + } else { + i += 1; + } + } + + // Fire interval timers + for timer in &mut self.interval_timers { + if timer.next_fire <= tick { + let msg = timer.msg.clone_boxed(); + result.push((timer.dest, msg)); + timer.next_fire = tick + timer.period; + } + } + + result + } + + /// Remove interval timers whose target was just removed from the worker. + /// Only GCs timers for addresses in `dead` — inboxes and cross-worker actors + /// are not in the local pool but are still valid targets. + fn gc_dead_intervals(&mut self, dead: &[ActorAddress]) { + if dead.is_empty() { + return; + } + self.interval_timers.retain(|t| !dead.iter().any(|d| *d == t.dest)); + } + + /// Add a one-shot timer. + fn add_once(&mut self, dest: ActorAddress, msg: Box, ticks: u64) { + self.once_timers.push(OnceTimer { + fire_at: self.current_tick + ticks, + dest, + msg, + }); + } + + /// Add an interval timer. First fire is after `period` ticks. + fn add_interval(&mut self, dest: ActorAddress, msg: Box, period: u64) { + let period = period.max(1); // prevent zero-period infinite loop + self.interval_timers.push(IntervalTimer { + next_fire: self.current_tick + period, + period, + dest, + msg, + }); + } +} + +// ─── Worker ───────────────────────────────────────────────────────────────── + /// A worker owns a set of actors and runs them in a loop. pub(crate) struct Worker { pub(crate) id: WorkerId, @@ -21,6 +119,8 @@ pub(crate) struct Worker { stats: Arc, /// Reusable scratch buffer for building per-actor snapshots. snapshot_buf: Vec, + /// Per-worker tick-counting timer wheel. + timers: TimerWheel, } impl Worker { @@ -29,14 +129,17 @@ impl Worker { transfer_rx: Receiver, spawn_rx: Receiver<(ActorAddress, Box)>, stats: Arc, + default_mailbox_capacity: usize, + default_overflow_policy: MailboxOverflow, ) -> Self { Self { id, - pool: ActorPool::new(), + pool: ActorPool::new(default_mailbox_capacity, default_overflow_policy), transfer_rx, spawn_rx, stats, snapshot_buf: Vec::new(), + timers: TimerWheel::new(), } } @@ -72,9 +175,32 @@ impl Worker { } let t2 = Instant::now(); + // 2.5. Fire due timers → deliver to mailboxes before tick_all + let timer_msgs = self.timers.fire(); + for (dest, msg) in timer_msgs { + if self.pool.contains(&dest) { + // Same-worker: deliver directly to actor's mailbox + self.pool.deliver(&dest, msg); + } else { + // Inbox or cross-worker: route through address map / inbox registry + match tc.address_map.lookup(&dest) { + Some(wid) => { + tc.transfer_txs[wid.as_usize()].send(Envelope::new(dest, msg)); + crate::runtime::notify_worker(tc.worker_threads, wid.as_usize()); + } + None => { + let _ = tc.inbox_registry.try_deliver(dest, msg); + } + } + } + did_work = true; + } + // 3. Tick all actors with WorkerContext let pending_local: RefCell)>> = RefCell::new(Vec::new()); + let stop_requests: RefCell> = RefCell::new(Vec::new()); + let timer_requests: RefCell> = RefCell::new(Vec::new()); let processed; { @@ -82,9 +208,11 @@ impl Worker { worker_id: self.id, tc, pending_local: &pending_local, + stop_requests: &stop_requests, + timer_requests: &timer_requests, stats: &self.stats, }; - processed = self.pool.tick_all(&worker_ctx, &self.stats); + processed = self.pool.tick_all(&worker_ctx, &self.stats, tc.config.actor_message_budget, &stop_requests); if processed > 0 { did_work = true; } @@ -116,13 +244,29 @@ impl Worker { for (addr, msg) in pending { self.pool.deliver(&addr, msg); } + + // 5.5. Process timer requests from handlers + for request in timer_requests.into_inner() { + match request { + TimerRequest::Once { dest, msg, ticks } => { + self.timers.add_once(dest, msg, ticks); + } + TimerRequest::Interval { dest, msg, period } => { + self.timers.add_interval(dest, msg, period); + } + } + } let t5 = Instant::now(); // 6. Publish stats (skip entirely when idle to avoid allocation + mutex) + let drops = self.pool.take_drops(); if did_work { self.stats.num_actors.store(self.pool.len(), Ordering::Relaxed); self.stats.total_mailbox_depth.store(self.pool.total_mailbox_depth(), Ordering::Relaxed); self.stats.messages_processed.fetch_add(processed as u64, Ordering::Relaxed); + if drops > 0 { + self.stats.messages_dropped.fetch_add(drops as u64, Ordering::Relaxed); + } if let Some(hook) = tc.stats_hook { self.pool.mailbox_depths_into(&mut self.snapshot_buf); @@ -158,6 +302,69 @@ impl Worker { ); } + // 7. Clean up poisoned and stopping actors + // on_stop() may send messages, so provide a fresh pending_local buffer. + let cleanup_pending: RefCell)>> = + RefCell::new(Vec::new()); + let cleanup_stops: RefCell> = RefCell::new(Vec::new()); + let cleanup_timers: RefCell> = RefCell::new(Vec::new()); + let dead = { + let cleanup_ctx = WorkerContext { + worker_id: self.id, + tc, + pending_local: &cleanup_pending, + stop_requests: &cleanup_stops, + timer_requests: &cleanup_timers, + stats: &self.stats, + }; + let dead = self.pool.cleanup_dead(&cleanup_ctx); + if !dead.is_empty() { + for &(addr, _) in &dead { + tc.address_map.remove(&addr); + } + + if let Some(ext) = tc.extension { + // Get death notifications (monitors) before cleaning up state + let notifications = ext.on_actor_death(&dead); + + // Clean up extension state (names, groups, dead watcher monitors) + let dead_addrs: Vec<_> = dead.iter().map(|(a, _)| *a).collect(); + ext.cleanup_dead(&dead_addrs); + + // Deliver Down notifications through normal routing + for (dest, msg) in notifications { + if self.pool.contains(&dest) { + self.pool.deliver(&dest, msg); + } else { + match tc.address_map.lookup(&dest) { + Some(wid) => { + tc.transfer_txs[wid.as_usize()] + .send(Envelope::new(dest, msg)); + crate::runtime::notify_worker(tc.worker_threads, wid.as_usize()); + } + None => { + let _ = tc.inbox_registry.try_deliver(dest, msg); + } + } + } + } + } + + // Re-publish num_actors after cleanup so stats reflect removal + self.stats.num_actors.store(self.pool.len(), Ordering::Relaxed); + did_work = true; + } + dead + }; + // Deliver any messages sent during on_stop callbacks + for (addr, msg) in cleanup_pending.into_inner() { + self.pool.deliver(&addr, msg); + } + + // GC orphaned interval timers for actors that were just removed + let dead_addrs: Vec = dead.iter().map(|(a, _)| *a).collect(); + self.timers.gc_dead_intervals(&dead_addrs); + did_work } @@ -182,7 +389,9 @@ impl Worker { (idle_count - backoff.yield_threshold) as u64 * backoff.sleep_increment_us, backoff.sleep_max_us, ); - thread::sleep(std::time::Duration::from_micros(micros)); + // park_timeout allows instant wakeup via Thread::unpark() + // when new work arrives (send_to/spawn notify the target worker) + thread::park_timeout(std::time::Duration::from_micros(micros)); } } } @@ -197,6 +406,8 @@ struct WorkerContext<'a> { worker_id: WorkerId, tc: &'a TickContext<'a>, pending_local: &'a RefCell)>>, + stop_requests: &'a RefCell>, + timer_requests: &'a RefCell>, stats: &'a WorkerStats, } @@ -211,6 +422,7 @@ impl ContextInner for WorkerContext<'_> { Some(wid) => { self.stats.cross_sends.fetch_add(1, Ordering::Relaxed); self.tc.transfer_txs[wid.as_usize()].send(Envelope::new(addr, msg)); + crate::runtime::notify_worker(self.tc.worker_threads, wid.as_usize()); Ok(()) } None => { @@ -224,7 +436,20 @@ impl ContextInner for WorkerContext<'_> { let worker_id = self.tc.placement.next_worker(); self.tc.address_map.insert(addr, worker_id); self.tc.spawn_txs[worker_id.as_usize()] - .send((addr, actor)) + .send((addr, actor)); + crate::runtime::notify_worker(self.tc.worker_threads, worker_id.as_usize()); + } + + fn request_stop(&self, addr: ActorAddress) { + self.stop_requests.borrow_mut().push(addr); + } + + fn schedule_timer(&self, request: TimerRequest) { + self.timer_requests.borrow_mut().push(request); + } + + fn extension(&self) -> Option<&dyn crate::extension::RuntimeExtension> { + self.tc.extension } } @@ -232,36 +457,68 @@ struct ActorSlot { mailbox: VecDeque>, actor: Box, poisoned: bool, + /// Graceful stop requested (via StopSignal). + stopping: bool, + /// Whether on_start has been called for this actor. + started: bool, last_msg_type: Option<&'static str>, messages_processed: u64, + /// Per-actor mailbox capacity. 0 = unbounded. + mailbox_capacity: usize, + overflow_policy: MailboxOverflow, } /// Per-worker actor storage. Owns per-actor mailboxes. pub(crate) struct ActorPool { - actors: HashMap, + actors: AddrMap, + default_mailbox_capacity: usize, + default_overflow_policy: MailboxOverflow, + /// Messages dropped this tick due to mailbox overflow. Reset after publishing to stats. + drops_this_tick: usize, } impl ActorPool { - pub fn new() -> Self { + pub fn new(default_mailbox_capacity: usize, default_overflow_policy: MailboxOverflow) -> Self { Self { - actors: HashMap::new(), + actors: HashMap::with_hasher(AddrBuildHasher), + default_mailbox_capacity, + default_overflow_policy, + drops_this_tick: 0, } } pub fn insert(&mut self, addr: ActorAddress, actor: Box) { + let cap = self.default_mailbox_capacity; + let prealloc = if cap > 0 { cap.min(64) } else { 16 }; self.actors.insert(addr, ActorSlot { - mailbox: VecDeque::with_capacity(16), + mailbox: VecDeque::with_capacity(prealloc), actor, poisoned: false, + stopping: false, + started: false, last_msg_type: None, messages_processed: 0, + mailbox_capacity: self.default_mailbox_capacity, + overflow_policy: self.default_overflow_policy, }); } /// Deliver a type-erased message to the actor at `addr`. - /// Returns `true` if the actor exists (message is queued; type check deferred to tick). + /// Returns `true` if the actor exists (message handled or dropped; type check deferred to tick). pub fn deliver(&mut self, addr: &ActorAddress, msg: Box) -> bool { if let Some(slot) = self.actors.get_mut(addr) { + if slot.mailbox_capacity > 0 && slot.mailbox.len() >= slot.mailbox_capacity { + match slot.overflow_policy { + MailboxOverflow::DropNewest => { + self.drops_this_tick += 1; + return true; + } + MailboxOverflow::DropOldest => { + slot.mailbox.pop_front(); + self.drops_this_tick += 1; + } + } + } slot.mailbox.push_back(msg); true } else { @@ -269,17 +526,72 @@ impl ActorPool { } } + /// Take and reset the drop counter for this tick. + pub fn take_drops(&mut self) -> usize { + std::mem::replace(&mut self.drops_this_tick, 0) + } + /// Tick all actors in the pool. Returns the number of messages processed. - pub fn tick_all(&mut self, inner: &dyn ContextInner, stats: &WorkerStats) -> usize { + /// + /// Each actor processes up to `budget` messages per tick (0 = unlimited). + /// This prevents a single hot actor from starving others on the same worker. + pub fn tick_all( + &mut self, + inner: &dyn ContextInner, + stats: &WorkerStats, + budget: usize, + stop_requests: &RefCell>, + ) -> usize { let mut count = 0; for (&addr, slot) in self.actors.iter_mut() { - if slot.poisoned { - // Discard all messages for poisoned actors + if slot.poisoned || slot.stopping { + // Discard all messages for poisoned/stopping actors slot.mailbox.clear(); continue; } + let ctx = Ctx::new(inner, addr); + + // Call on_start once, before first message + if !slot.started { + let start_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + slot.actor.on_start(&ctx); + })); + slot.started = true; + if start_result.is_err() { + stats.panics.fetch_add(1, Ordering::Relaxed); + eprintln!("swactor: actor {addr} panicked in on_start — poisoned"); + #[cfg(feature = "tracing")] + tracing::error!(actor_addr = %addr, "actor.on_start_panicked"); + slot.poisoned = true; + slot.mailbox.clear(); + continue; + } + // Check if on_start requested stop + { + let stops = stop_requests.borrow(); + if !stops.is_empty() && stops.contains(&addr) { + drop(stops); + slot.stopping = true; + stats.stops.fetch_add(1, Ordering::Relaxed); + slot.mailbox.clear(); + continue; + } + } + } + + let mut actor_count = 0usize; while let Some(msg) = slot.mailbox.pop_front() { + // Intercept StopSignal (from external runtime.stop_actor) + if msg.is::() { + slot.stopping = true; + stats.stops.fetch_add(1, Ordering::Relaxed); + slot.mailbox.clear(); + #[cfg(feature = "tracing")] + tracing::info!(actor_addr = %addr, "actor.stop_requested"); + break; + } + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { slot.actor.handle_any(&ctx, msg) })); @@ -289,11 +601,11 @@ impl ActorPool { } Err(_) => { stats.panics.fetch_add(1, Ordering::Relaxed); + slot.mailbox.clear(); eprintln!("swactor: actor {addr} panicked — poisoned, future messages will be discarded"); #[cfg(feature = "tracing")] tracing::error!(actor_addr = %addr, "actor.panicked"); slot.poisoned = true; - slot.mailbox.clear(); break; } Ok(Some(type_name)) => { @@ -302,6 +614,23 @@ impl ActorPool { } } count += 1; + actor_count += 1; + + // Check if handler requested self-stop (via ctx.stop_self()) + { + let stops = stop_requests.borrow(); + if !stops.is_empty() && stops.contains(&addr) { + drop(stops); + slot.stopping = true; + stats.stops.fetch_add(1, Ordering::Relaxed); + slot.mailbox.clear(); + break; + } + } + + if budget > 0 && actor_count >= budget { + break; + } } } count @@ -311,10 +640,44 @@ impl ActorPool { self.actors.len() } + pub fn contains(&self, addr: &ActorAddress) -> bool { + self.actors.contains_key(addr) + } + pub fn total_mailbox_depth(&self) -> usize { self.actors.values().map(|slot| slot.mailbox.len()).sum() } + /// Remove poisoned and stopping actors, returning their addresses and stop reasons. + /// Called after tick_all so the caller can clean up the address map. + /// + /// For stopping actors: calls `on_stop()` before removal (wrapped in catch_unwind). + /// For poisoned actors: `on_stop()` is NOT called (state may be corrupt). + pub fn cleanup_dead(&mut self, inner: &dyn ContextInner) -> Vec<(ActorAddress, StopReason)> { + let dead: Vec<(ActorAddress, StopReason)> = self + .actors + .iter() + .filter(|(_, slot)| slot.poisoned || slot.stopping) + .map(|(&addr, slot)| { + let reason = if slot.poisoned { StopReason::Panicked } else { StopReason::Normal }; + (addr, reason) + }) + .collect(); + for &(addr, _) in &dead { + if let Some(mut slot) = self.actors.remove(&addr) { + // Call on_stop for gracefully stopping actors only + if slot.stopping && !slot.poisoned { + let ctx = Ctx::new(inner, addr); + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + slot.actor.on_stop(&ctx); + })); + } + // slot is dropped here — actor resources freed + } + } + dead + } + /// Fill `out` with per-actor snapshots, reusing the existing allocation. pub fn mailbox_depths_into(&self, out: &mut Vec) { out.clear(); diff --git a/tests/proptest_runtime.rs b/tests/proptest_runtime.rs new file mode 100644 index 0000000..832f9b0 --- /dev/null +++ b/tests/proptest_runtime.rs @@ -0,0 +1,576 @@ +//! Property-based tests for the swactor runtime. +//! +//! Uses proptest for randomized testing and proptest-state-machine for +//! stateful property testing with automatic shrinking of failing sequences. + +use std::collections::HashMap; + +use proptest::prelude::*; +use proptest_state_machine::{prop_state_machine, ReferenceStateMachine, StateMachineTest}; + +use swactor::actor::{ActorAddress, ActorInterface}; +use swactor::config::{MailboxOverflow, RuntimeConfig}; +use swactor::runtime::{Ctx, Inbox, Runtime}; + +// ─── Shared Actor Types ──────────────────────────────────────────────────── + +#[derive(Clone, Debug)] +struct Ping(u64); + +/// Echo: receives Ping, sends Ping back to reply_to address. +struct EchoActor { + reply_to: ActorAddress, +} +impl ActorInterface for EchoActor { + type Incoming = Ping; + type Response = (); + fn handle(&mut self, ctx: &Ctx, msg: Ping) { + let _ = ctx.send(self.reply_to, msg); + } +} + +/// Counter: tracks message count, replies with count. +struct CounterActor { + count: u64, + reply_to: ActorAddress, +} +impl ActorInterface for CounterActor { + type Incoming = Ping; + type Response = (); + fn handle(&mut self, ctx: &Ctx, _msg: Ping) { + self.count += 1; + let _ = ctx.send(self.reply_to, Ping(self.count)); + } +} + +/// PanicActor: panics on first message. +struct PanicActor; +impl ActorInterface for PanicActor { + type Incoming = Ping; + type Response = (); + fn handle(&mut self, _ctx: &Ctx, _msg: Ping) { + panic!("intentional panic"); + } +} + +/// Noop: discards all messages silently. +struct NoopActor; +impl ActorInterface for NoopActor { + type Incoming = Ping; + type Response = (); + fn handle(&mut self, _ctx: &Ctx, _msg: Ping) {} +} + +// ─── Simple Property Tests ───────────────────────────────────────────────── + +proptest! { + /// FIFO ordering is preserved for any sequence of numbered messages + /// sent from a single sender to a single actor. + #[test] + fn fifo_ordering_for_any_message_sequence( + values in proptest::collection::vec(0u64..10_000, 1..100) + ) { + let rt = Runtime::new(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + let addr = rt.spawn(EchoActor { reply_to: *inbox.addr() }).unwrap(); + + // Send all messages + for &v in &values { + rt.send_to(addr, Ping(v)).unwrap(); + } + + // Tick enough to process all + let ticks_needed = (values.len() / 64) + 3; // budget=64 default + for _ in 0..ticks_needed { rt.tick(); } + + // Verify FIFO ordering + let mut received = Vec::new(); + while let Some(msg) = inbox.try_recv() { + received.push(msg.0); + } + prop_assert_eq!(&received, &values, "FIFO ordering violated"); + } + + /// Budget fairness: no actor processes more than budget messages per tick + /// when multiple actors have pending messages. + #[test] + fn budget_limits_per_actor_processing( + n_actors in 2usize..10, + msgs_per in 10usize..100, + budget in 1usize..32, + ) { + let config = RuntimeConfig { + actor_message_budget: budget, + ..Default::default() + }; + let rt = Runtime::new(config); + let inbox = rt.new_inbox::().unwrap(); + + let mut addrs = Vec::new(); + for _ in 0..n_actors { + addrs.push(rt.spawn(CounterActor { count: 0, reply_to: *inbox.addr() }).unwrap()); + } + + rt.tick(); // on_start + + // Send msgs_per messages to each actor + for addr in &addrs { + for v in 0..msgs_per as u64 { + rt.send_to(*addr, Ping(v)).unwrap(); + } + } + + // Single tick — each actor should process at most `budget` messages + rt.tick(); + + // Drain inbox to count replies per actor + // CounterActor replies with incrementing count, so max reply value = messages processed + let mut replies = Vec::new(); + while let Some(msg) = inbox.try_recv() { + replies.push(msg.0); + } + + // Total replies should be at most n_actors * budget + prop_assert!( + replies.len() <= n_actors * budget, + "Too many messages processed: {} > {} (n_actors={}, budget={})", + replies.len(), n_actors * budget, n_actors, budget, + ); + } + + /// One-shot timer fires at exactly the right tick for any delay. + #[test] + fn one_shot_timer_fires_at_correct_tick(delay in 1u64..20) { + let rt = Runtime::new(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + struct TimerActor { target: ActorAddress, delay: u64 } + impl ActorInterface for TimerActor { + type Incoming = Ping; + type Response = (); + fn handle(&mut self, _ctx: &Ctx, _msg: Ping) {} + fn on_start(&mut self, ctx: &Ctx) { + ctx.send_after_ticks(self.target, Ping(42), self.delay); + } + } + + let _addr = rt.spawn(TimerActor { target: *inbox.addr(), delay }).unwrap(); + + // Tick up to the expected fire tick + for tick in 1..=(delay + 1) { + rt.tick(); + let msg = inbox.try_recv(); + if tick <= delay { + prop_assert!(msg.is_none(), "Timer fired too early at tick {}", tick); + } else { + prop_assert!(msg.is_some(), "Timer should have fired at tick {}", tick); + } + } + + // No second fire (one-shot) + rt.tick(); + prop_assert!(inbox.try_recv().is_none(), "One-shot timer fired twice"); + } + + /// Interval timer fires at correct periodic ticks for any period. + #[test] + fn interval_timer_fires_at_correct_period(period in 1u64..10) { + let rt = Runtime::new(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + struct IntervalActor { target: ActorAddress, period: u64 } + impl ActorInterface for IntervalActor { + type Incoming = Ping; + type Response = (); + fn handle(&mut self, _ctx: &Ctx, _msg: Ping) {} + fn on_start(&mut self, ctx: &Ctx) { + ctx.send_interval_ticks(self.target, Ping(1), self.period); + } + } + + let _addr = rt.spawn(IntervalActor { target: *inbox.addr(), period }).unwrap(); + + // Verify 3 consecutive fires + let mut fire_count = 0; + // Timer scheduled on tick 1 (on_start). First fire at tick 1+period. + for tick in 1..=(period * 3 + 2) { + rt.tick(); + if let Some(_) = inbox.try_recv() { + fire_count += 1; + // First fire should be at tick (period + 1) + // Subsequent fires every `period` ticks after that + let expected_tick = period + 1 + (fire_count - 1) * period; + prop_assert_eq!(tick, expected_tick, + "Fire #{} at wrong tick (period={})", fire_count, period); + } + } + prop_assert!(fire_count >= 3, "Expected 3+ fires, got {} (period={})", fire_count, period); + } + + /// Bounded mailbox with DropNewest never exceeds capacity. + #[test] + fn bounded_mailbox_never_exceeds_capacity( + capacity in 1usize..20, + msg_count in 1usize..200, + ) { + let config = RuntimeConfig { + default_mailbox_capacity: capacity, + mailbox_overflow: MailboxOverflow::DropNewest, + ..Default::default() + }; + let rt = Runtime::new(config); + let addr = rt.spawn(NoopActor).unwrap(); + rt.tick(); // on_start + + for v in 0..msg_count as u64 { + rt.send_to(addr, Ping(v)).unwrap(); + } + + let stats = rt.stats(); + let worker = &stats.workers[0]; + // Mailbox depth should never exceed capacity + prop_assert!( + worker.mailbox_depth <= capacity, + "Mailbox depth {} exceeds capacity {}", + worker.mailbox_depth, capacity, + ); + } + + /// Spawn N actors and verify all get unique addresses and appear in stats. + #[test] + fn spawn_n_actors_all_tracked(n in 1usize..50) { + let rt = Runtime::new(RuntimeConfig::default()); + let mut addrs = Vec::new(); + for _ in 0..n { + addrs.push(rt.spawn(NoopActor).unwrap()); + } + rt.tick(); // process spawns + + let stats = rt.stats(); + prop_assert_eq!(stats.actors.len(), n, "Expected {} actors in stats", n); + + // All addresses should be unique + let unique: std::collections::HashSet<_> = addrs.iter().collect(); + prop_assert_eq!(unique.len(), n, "Duplicate addresses detected"); + } +} + +// ─── State Machine Test ──────────────────────────────────────────────────── +// +// Reference model tracks expected runtime state. Transitions are random +// operations (spawn, send, tick, stop). After each transition, invariants +// are checked against the actual runtime. + +#[derive(Clone, Debug)] +struct RefState { + /// actor_id -> is_alive (not stopped/poisoned) + actors: HashMap, + /// actor_id -> messages sent (values, in order) + sent_messages: HashMap>, + /// Number of ticks executed + tick_count: u64, + /// Next actor ID to assign + next_id: usize, + /// IDs of actors that will panic on first message + panic_actors: Vec, +} + +#[derive(Clone, Debug)] +enum Transition { + /// Spawn a new echo actor + SpawnEcho, + /// Spawn a panic-on-first-message actor + SpawnPanic, + /// Send a numbered message to actor at index + Send { actor_idx: usize, value: u64 }, + /// Run one tick + Tick, + /// Run N ticks + TickN(u8), + /// Stop actor at index gracefully + StopActor(usize), + /// Check runtime stats match reference + CheckStats, +} + +struct SwactorModel; + +impl ReferenceStateMachine for SwactorModel { + type State = RefState; + type Transition = Transition; + + fn init_state() -> BoxedStrategy { + Just(RefState { + actors: HashMap::new(), + sent_messages: HashMap::new(), + tick_count: 0, + next_id: 0, + panic_actors: Vec::new(), + }) + .boxed() + } + + fn transitions(state: &Self::State) -> BoxedStrategy { + let has_actors = !state.actors.is_empty(); + let has_alive = state.actors.values().any(|&alive| alive); + + if !has_actors { + // Must spawn first + prop_oneof![ + 3 => Just(Transition::SpawnEcho), + 1 => Just(Transition::SpawnPanic), + ] + .boxed() + } else if !has_alive { + // All actors dead, spawn new ones or tick to clean up + prop_oneof![ + 3 => Just(Transition::SpawnEcho), + 1 => Just(Transition::SpawnPanic), + 1 => Just(Transition::Tick), + ] + .boxed() + } else { + let n = state.actors.len(); + prop_oneof![ + 3 => Just(Transition::SpawnEcho), + 1 => Just(Transition::SpawnPanic), + 10 => (0..n, 0u64..1000).prop_map(|(idx, val)| Transition::Send { + actor_idx: idx, + value: val, + }), + 5 => Just(Transition::Tick), + 2 => (1u8..5).prop_map(Transition::TickN), + 2 => (0..n).prop_map(Transition::StopActor), + 1 => Just(Transition::CheckStats), + ] + .boxed() + } + } + + fn apply(mut state: Self::State, transition: &Self::Transition) -> Self::State { + match transition { + Transition::SpawnEcho => { + let id = state.next_id; + state.next_id += 1; + state.actors.insert(id, true); + state.sent_messages.insert(id, Vec::new()); + } + Transition::SpawnPanic => { + let id = state.next_id; + state.next_id += 1; + state.actors.insert(id, true); + state.sent_messages.insert(id, Vec::new()); + state.panic_actors.push(id); + } + Transition::Send { actor_idx, value } => { + let alive_ids: Vec = state + .actors + .iter() + .filter(|(_, alive)| **alive) + .map(|(&id, _)| id) + .collect(); + if !alive_ids.is_empty() { + let id = alive_ids[*actor_idx % alive_ids.len()]; + state + .sent_messages + .entry(id) + .or_default() + .push(*value); + } + } + Transition::Tick => { + state.tick_count += 1; + } + Transition::TickN(n) => { + state.tick_count += *n as u64; + } + Transition::StopActor(idx) => { + let alive_ids: Vec = state + .actors + .iter() + .filter(|(_, alive)| **alive) + .map(|(&id, _)| id) + .collect(); + if !alive_ids.is_empty() { + let id = alive_ids[*idx % alive_ids.len()]; + state.actors.insert(id, false); + } + } + Transition::CheckStats => {} + } + state + } + + fn preconditions(state: &Self::State, transition: &Self::Transition) -> bool { + match transition { + Transition::Send { .. } | Transition::StopActor(_) => { + state.actors.values().any(|&alive| alive) + } + _ => true, + } + } +} + +// ─── Concrete System Under Test ──────────────────────────────────────────── + +struct SutState { + runtime: Runtime, + inbox: Inbox, + /// Maps reference actor_id to actual ActorAddress + actor_map: HashMap, + /// Reference IDs that are panic actors + panic_ids: Vec, + /// Tracks which actor IDs are alive (mirrors ref model) + alive: HashMap, + /// Next ID for spawn + next_id: usize, +} + +struct SwactorTest; + +impl StateMachineTest for SwactorTest { + type SystemUnderTest = SutState; + type Reference = SwactorModel; + + fn init_test(_ref_state: &RefState) -> Self::SystemUnderTest { + let rt = Runtime::new(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + SutState { + runtime: rt, + inbox, + actor_map: HashMap::new(), + panic_ids: Vec::new(), + alive: HashMap::new(), + next_id: 0, + } + } + + fn apply( + mut sut: Self::SystemUnderTest, + _ref_state: &RefState, + transition: Transition, + ) -> Self::SystemUnderTest { + match transition { + Transition::SpawnEcho => { + let id = sut.next_id; + sut.next_id += 1; + let addr = sut + .runtime + .spawn(EchoActor { + reply_to: *sut.inbox.addr(), + }) + .unwrap(); + sut.actor_map.insert(id, addr); + sut.alive.insert(id, true); + } + Transition::SpawnPanic => { + let id = sut.next_id; + sut.next_id += 1; + let addr = sut.runtime.spawn(PanicActor).unwrap(); + sut.actor_map.insert(id, addr); + sut.alive.insert(id, true); + sut.panic_ids.push(id); + } + Transition::Send { actor_idx, value } => { + let alive_ids: Vec = sut + .alive + .iter() + .filter(|(_, alive)| **alive) + .map(|(&id, _)| id) + .collect(); + if !alive_ids.is_empty() { + let id = alive_ids[actor_idx % alive_ids.len()]; + if let Some(&addr) = sut.actor_map.get(&id) { + let _ = sut.runtime.send_to(addr, Ping(value)); + } + } + } + Transition::Tick => { + sut.runtime.tick(); + } + Transition::TickN(n) => { + for _ in 0..n { + sut.runtime.tick(); + } + } + Transition::StopActor(idx) => { + let alive_ids: Vec = sut + .alive + .iter() + .filter(|(_, alive)| **alive) + .map(|(&id, _)| id) + .collect(); + if !alive_ids.is_empty() { + let id = alive_ids[idx % alive_ids.len()]; + sut.alive.insert(id, false); + if let Some(&addr) = sut.actor_map.get(&id) { + let _ = sut.runtime.stop_actor(addr); + } + } + } + Transition::CheckStats => { + let stats = sut.runtime.stats(); + assert!(stats.num_workers >= 1); + for info in &stats.workers { + assert!(info.id < stats.num_workers); + } + } + } + sut + } + + fn check_invariants(sut: &Self::SystemUnderTest, _ref_state: &RefState) { + let stats = sut.runtime.stats(); + + // Invariant 1: worker count is consistent + assert_eq!(stats.workers.len(), stats.num_workers); + + // Invariant 2: all actors in stats are on valid workers + for (_, wid) in &stats.actors { + assert!( + *wid < stats.num_workers, + "Actor on worker {} but only {} workers", + wid, + stats.num_workers + ); + } + + // Invariant 3: per-worker actor count <= address map count + // (workers lag behind address map because they drain spawn queue on tick) + let worker_actor_count: usize = stats.workers.iter().map(|w| w.num_actors).sum(); + assert!( + worker_actor_count <= stats.actors.len(), + "Worker actor count {} > address map count {}", + worker_actor_count, + stats.actors.len(), + ); + + // Invariant 4: inbox can be drained without panic + // (type-safety of inbox messages) + while let Some(_msg) = sut.inbox.try_recv() { + // Just verify no panic on try_recv + } + + // Invariant 5: stats queries don't panic + let _total_processed: u64 = stats.workers.iter().map(|w| w.messages_processed).sum(); + let _total_depth: usize = stats.workers.iter().map(|w| w.mailbox_depth).sum(); + } + + fn teardown(_sut: Self::SystemUnderTest) { + // Runtime drops normally + } +} + +prop_state_machine! { + #![proptest_config(proptest::test_runner::Config { + cases: 128, + max_shrink_iters: 10_000, + .. proptest::test_runner::Config::default() + })] + + /// Given a random sequence of spawn/send/tick/stop operations, + /// when applied to a swactor runtime, + /// then all invariants (worker consistency, mailbox safety, stats accuracy) hold. + #[test] + fn swactor_state_machine(sequential 1..40 => SwactorTest); +} diff --git a/tests/runtime_api.rs b/tests/runtime_api.rs index 33273f7..0a85827 100644 --- a/tests/runtime_api.rs +++ b/tests/runtime_api.rs @@ -1,8 +1,17 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; -use swactor::actor::{ActorAddress, ActorInterface}; -use swactor::runtime::{Ctx, Inbox, Runtime, RuntimeConfig}; +use swactor::actor::{ActorAddress, ActorInterface, Down, MonitorRef, StopReason}; +use swactor_std::{ + ChildSpec, CtxGroups, CtxMonitoring, CtxNaming, RestartPolicy, Router, RoutingStrategy, + RuntimeGroups, RuntimeNaming, StdExtension, Supervisor, SupervisorStrategy, +}; +use swactor::runtime::{Ctx, Inbox, MailboxOverflow, Runtime, RuntimeConfig}; + +/// Helper: construct a Runtime with StdExtension installed. +fn std_runtime(config: RuntimeConfig) -> Runtime { + Runtime::new(config).with_extension(Arc::new(StdExtension::new())) +} // ── Messages ──────────────────────────────────────────────────────────────── @@ -218,7 +227,7 @@ fn tick_and_drain( #[test] fn actor_receives_message_and_replies() { // Given a spawned PingPongActor - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(PingPongActor).unwrap(); let inbox = rt.new_inbox::().unwrap(); @@ -233,7 +242,7 @@ fn actor_receives_message_and_replies() { #[test] fn actor_maintains_state_across_messages() { // Given a CounterActor starting at 0 - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(CounterActor { count: 0 }).unwrap(); let inbox = rt.new_inbox::().unwrap(); @@ -250,7 +259,7 @@ fn actor_maintains_state_across_messages() { #[test] fn actor_spawns_child_and_child_replies() { // Given a DelegatorActor - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(DelegatorActor).unwrap(); let inbox = rt.new_inbox::().unwrap(); @@ -265,7 +274,7 @@ fn actor_spawns_child_and_child_replies() { #[test] fn three_level_chain_reaches_leaf() { // Given a ChainActor that will spawn 2 more levels - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(ChainActor).unwrap(); let inbox = rt.new_inbox::().unwrap(); @@ -280,7 +289,7 @@ fn three_level_chain_reaches_leaf() { #[test] fn fan_out_distributes_work_to_children() { // Given a FanOutActor told to spawn 5 children - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(FanOutActor).unwrap(); let inbox = rt.new_inbox::().unwrap(); @@ -297,7 +306,7 @@ fn fan_out_distributes_work_to_children() { #[test] fn actor_knows_its_own_address() { // Given a SelfAddrActor - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(SelfAddrActor).unwrap(); let inbox = rt.new_inbox::().unwrap(); @@ -316,7 +325,7 @@ fn actor_knows_its_own_address() { #[test] fn messages_arrive_in_fifo_order() { // Given a CounterActor - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(CounterActor { count: 0 }).unwrap(); let inbox = rt.new_inbox::().unwrap(); @@ -337,7 +346,7 @@ fn messages_arrive_in_fifo_order() { #[test] fn multiple_actors_have_independent_mailboxes() { // Given 3 PingPongActors, each with its own inbox - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let mut addrs = Vec::new(); let mut inboxes = Vec::new(); for _ in 0..3 { @@ -363,7 +372,7 @@ fn multiple_actors_have_independent_mailboxes() { #[test] fn multiple_senders_reach_same_actor() { // Given 1 CounterActor - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(CounterActor { count: 0 }).unwrap(); let inbox_a = rt.new_inbox::().unwrap(); let inbox_b = rt.new_inbox::().unwrap(); @@ -387,7 +396,7 @@ fn multiple_senders_reach_same_actor() { #[test] fn send_to_nonexistent_address_returns_error() { // Given a runtime with no actors at a random address - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let bogus = ActorAddress::new_random(); // When I try to send to that address @@ -400,7 +409,7 @@ fn send_to_nonexistent_address_returns_error() { #[test] fn messages_sent_within_handler_are_delivered() { // Given a DelegatorActor (spawns child + sends in same handler call) - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(DelegatorActor).unwrap(); let inbox = rt.new_inbox::().unwrap(); @@ -420,7 +429,7 @@ fn messages_sent_within_handler_are_delivered() { #[test] fn tick_drives_single_threaded_processing() { // Given a single-threaded runtime - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(PingPongActor).unwrap(); let inbox = rt.new_inbox::().unwrap(); @@ -439,7 +448,7 @@ fn tick_drives_single_threaded_processing() { #[test] fn run_processes_messages_in_background() { // Given a multi-threaded runtime - let rt = Runtime::new(RuntimeConfig { num_threads: 4, ..Default::default() }); + let rt = std_runtime(RuntimeConfig { num_threads: 4, ..Default::default() }); let addr = rt.spawn(PingPongActor).unwrap(); let inbox = rt.new_inbox::().unwrap(); rt.send_to(addr, Ping { reply_to: *inbox.addr() }).unwrap(); @@ -464,7 +473,7 @@ fn run_processes_messages_in_background() { #[test] fn shutdown_stops_background_workers() { // Given a running multi-threaded runtime - let rt = Runtime::new(RuntimeConfig { num_threads: 2, ..Default::default() }); + let rt = std_runtime(RuntimeConfig { num_threads: 2, ..Default::default() }); let handle = rt.run().unwrap(); // When I call shutdown + join @@ -477,7 +486,7 @@ fn shutdown_stops_background_workers() { #[test] fn cross_worker_delegation_delivers_reply() { // Given a 2-thread runtime with a DelegatorActor - let rt = Runtime::new(RuntimeConfig { num_threads: 2, ..Default::default() }); + let rt = std_runtime(RuntimeConfig { num_threads: 2, ..Default::default() }); let addr = rt.spawn(DelegatorActor).unwrap(); let inbox = rt.new_inbox::().unwrap(); rt.send_to(addr, Forward { value: 3, reply_to: *inbox.addr() }).unwrap(); @@ -506,7 +515,7 @@ fn cross_worker_delegation_delivers_reply() { #[test] fn inbox_handles_burst_of_messages() { // Given a CounterActor and a small runtime - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(CounterActor { count: 0 }).unwrap(); let inbox = rt.new_inbox::().unwrap(); @@ -525,7 +534,7 @@ fn inbox_handles_burst_of_messages() { #[test] fn hundred_actors_all_receive_messages() { // Given 100 PingPongActors - let rt = Runtime::new(RuntimeConfig { + let rt = std_runtime(RuntimeConfig { max_actors: 2000, ..Default::default() }); @@ -554,7 +563,7 @@ fn hundred_actors_all_receive_messages() { #[test] fn panic_in_handler_does_not_kill_other_actors() { // Given a PanicActor and a PingPongActor on the same runtime - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let panic_addr = rt.spawn(PanicActor).unwrap(); let good_addr = rt.spawn(PingPongActor).unwrap(); let inbox = rt.new_inbox::().unwrap(); @@ -574,7 +583,7 @@ fn panic_in_handler_does_not_kill_other_actors() { #[test] fn panic_does_not_corrupt_subsequent_messages() { // Given a PanicActor and a CounterActor - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let panic_addr = rt.spawn(PanicActor).unwrap(); let counter_addr = rt.spawn(CounterActor { count: 0 }).unwrap(); let inbox = rt.new_inbox::().unwrap(); @@ -598,7 +607,7 @@ fn panicked_actor_is_poisoned_and_discards_future_messages() { // // Specifically: a PanicActor receives one PanicMsg, panics, then future // PanicMsgs should be silently discarded (actor is poisoned). - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let panic_addr = rt.spawn(PanicActor).unwrap(); let good_addr = rt.spawn(CounterActor { count: 0 }).unwrap(); let inbox = rt.new_inbox::().unwrap(); @@ -632,7 +641,7 @@ fn panicked_actor_is_poisoned_and_discards_future_messages() { #[test] fn stats_report_spawned_actors() { // Given 3 spawned actors - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); for _ in 0..3 { rt.spawn(PingPongActor).unwrap(); } @@ -652,7 +661,7 @@ fn stats_report_spawned_actors() { #[test] fn stats_report_message_throughput() { // Given 3 actors that each process 10 messages - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let counter = Arc::new(AtomicUsize::new(0)); let inbox = rt.new_inbox::().unwrap(); let inbox_addr = *inbox.addr(); @@ -686,7 +695,7 @@ fn stats_report_message_throughput() { #[test] fn stats_record_panics() { // Given a PanicActor that panics twice - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(PanicActor).unwrap(); rt.send_to(addr, PanicMsg).unwrap(); @@ -790,7 +799,7 @@ impl ActorInterface for SendThenPanicActor { #[test] fn wrong_type_to_actor_increments_type_mismatch_counter() { // Given a PingPongActor that expects Ping - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(PingPongActor).unwrap(); // When I send it a Count message (wrong type) @@ -809,7 +818,7 @@ fn wrong_type_to_actor_increments_type_mismatch_counter() { #[test] fn type_mismatch_still_counted_as_processed() { // Given a PingPongActor - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(PingPongActor).unwrap(); // When I send it 3 wrong-type messages @@ -836,7 +845,7 @@ fn type_mismatch_still_counted_as_processed() { #[test] fn self_send_chain_completes() { // Given a SelfSendActor that will bounce a message to itself 10 times - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(SelfSendActor).unwrap(); let inbox = rt.new_inbox::().unwrap(); @@ -854,7 +863,7 @@ fn self_send_chain_completes() { fn panic_mid_batch_discards_remaining_messages() { // Given an actor that processes 2 messages then panics on the 3rd let counter = Arc::new(AtomicUsize::new(0)); - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let dummy = rt.new_inbox::().unwrap(); let addr = rt.spawn(PanicAfterNActor { remaining_good: 2, @@ -883,7 +892,7 @@ fn panic_mid_batch_discards_remaining_messages() { #[test] fn spawn_then_panic_child_survives() { // Given a SpawnThenPanicActor - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(SpawnThenPanicActor).unwrap(); let inbox = rt.new_inbox::().unwrap(); @@ -902,7 +911,7 @@ fn spawn_then_panic_child_survives() { #[test] fn panic_after_send_still_delivers_sent_messages() { // Given a SendThenPanicActor (sends Pong, then panics) - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(SendThenPanicActor).unwrap(); let inbox = rt.new_inbox::().unwrap(); @@ -923,35 +932,32 @@ fn panic_after_send_still_delivers_sent_messages() { #[test] fn send_to_poisoned_actor_is_a_silent_black_hole() { // Given a poisoned actor (panicked on first message) - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let panic_addr = rt.spawn(PanicActor).unwrap(); rt.send_to(panic_addr, PanicMsg).unwrap(); for _ in 0..5 { rt.tick(); } - // When I send more messages to it + // When I send more messages to it (after cleanup, address is removed) let result = rt.send_to(panic_addr, PanicMsg); - // Then send_to succeeds (address is still in address_map) + // Then send_to returns an error (actor has been cleaned up and removed) assert!( - result.is_ok(), - "send_to poisoned actor should succeed from sender's POV" + result.is_err(), + "send_to cleaned-up actor should return error" ); - // And ticking doesn't produce new panics — messages are discarded in tick_all - for _ in 0..10 { - rt.tick(); - } + // And the original panic was recorded let s = rt.stats(); let panics: u64 = s.workers.iter().map(|w| w.panics).sum(); - assert_eq!(panics, 1, "poisoned actor should not produce new panics"); + assert_eq!(panics, 1, "poisoned actor should have recorded one panic"); } #[test] fn tiny_buffer_delivers_all_messages_in_order() { // Given a runtime with channel_buffer_size=1 (overflow on every 2nd message) - let rt = Runtime::new(RuntimeConfig { + let rt = std_runtime(RuntimeConfig { channel_buffer_size: 1, ..Default::default() }); @@ -976,7 +982,7 @@ fn tiny_buffer_delivers_all_messages_in_order() { #[test] fn empty_runtime_tick_and_stats_are_safe() { // Given a runtime with no actors at all - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); // When I tick and check stats for _ in 0..10 { @@ -994,7 +1000,7 @@ fn empty_runtime_tick_and_stats_are_safe() { #[test] fn stats_stable_after_idle_ticks() { // Given an actor that processes a message - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(CounterActor { count: 0 }).unwrap(); let inbox = rt.new_inbox::().unwrap(); rt.send_to(addr, Increment { reply_to: *inbox.addr() }).unwrap(); @@ -1022,7 +1028,7 @@ fn stats_stable_after_idle_ticks() { #[test] fn deep_spawn_chain_completes() { // Given a 100-level chain (tests no stack overflow from recursive tick_all) - let rt = Runtime::new(RuntimeConfig { + let rt = std_runtime(RuntimeConfig { max_actors: 2000, ..Default::default() }); @@ -1046,7 +1052,7 @@ fn deep_spawn_chain_completes() { #[test] fn all_spawned_addresses_are_unique() { - let rt = Runtime::new(RuntimeConfig { + let rt = std_runtime(RuntimeConfig { max_actors: 10_000, ..Default::default() }); @@ -1063,7 +1069,7 @@ fn all_spawned_addresses_are_unique() { #[test] fn inbox_empty_before_any_tick() { // Given a sent message that hasn't been ticked - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(PingPongActor).unwrap(); let inbox = rt.new_inbox::().unwrap(); rt.send_to(addr, Ping { reply_to: *inbox.addr() }).unwrap(); @@ -1075,7 +1081,7 @@ fn inbox_empty_before_any_tick() { #[test] fn interleaved_spawn_and_send_in_handler_all_complete() { // Given a FanOutActor that spawns 20 children with interleaved spawn+send - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(FanOutActor).unwrap(); let inbox = rt.new_inbox::().unwrap(); @@ -1092,7 +1098,7 @@ fn interleaved_spawn_and_send_in_handler_all_complete() { #[test] fn multiple_inbox_types_coexist() { // Given two inboxes of different types on the same runtime - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let counter = rt.spawn(CounterActor { count: 0 }).unwrap(); let pinger = rt.spawn(PingPongActor).unwrap(); let count_inbox = rt.new_inbox::().unwrap(); @@ -1112,8 +1118,8 @@ fn multiple_inbox_types_coexist() { #[test] fn poisoned_actor_messages_not_counted_as_processed() { - // Given a poisoned actor that then receives 10 more messages - let rt = Runtime::new(RuntimeConfig::default()); + // Given a poisoned actor that has been cleaned up + let rt = std_runtime(RuntimeConfig::default()); let panic_addr = rt.spawn(PanicActor).unwrap(); rt.send_to(panic_addr, PanicMsg).unwrap(); for _ in 0..5 { @@ -1122,9 +1128,13 @@ fn poisoned_actor_messages_not_counted_as_processed() { let s1 = rt.stats(); let processed_before: u64 = s1.workers.iter().map(|w| w.messages_processed).sum(); - // When I send 10 messages to the poisoned actor and tick + // When I try to send 10 messages to the cleaned-up actor + // (sends will fail because actor is removed from address map) + let mut send_failures = 0; for _ in 0..10 { - rt.send_to(panic_addr, PanicMsg).unwrap(); + if rt.send_to(panic_addr, PanicMsg).is_err() { + send_failures += 1; + } } for _ in 0..20 { rt.tick(); @@ -1132,17 +1142,18 @@ fn poisoned_actor_messages_not_counted_as_processed() { let s2 = rt.stats(); let processed_after: u64 = s2.workers.iter().map(|w| w.messages_processed).sum(); - // Then the 10 discarded messages should NOT increase the processed count + // Then sends fail (actor cleaned up) and processed count unchanged + assert_eq!(send_failures, 10, "all sends should fail to cleaned-up actor"); assert_eq!( processed_before, processed_after, - "messages discarded by poisoned actors should not be counted as processed" + "no additional messages should be processed after cleanup" ); } #[test] fn rapid_spawn_and_immediate_send() { // Given a runtime, spawn an actor and immediately send before any tick - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let inbox = rt.new_inbox::().unwrap(); // When I spawn + send in rapid succession, 50 times @@ -1165,7 +1176,7 @@ fn rapid_spawn_and_immediate_send() { #[test] fn default_config_works_out_of_the_box() { // Given the default config — no tuning needed - let rt = Runtime::new(RuntimeConfig::default()); + let rt = std_runtime(RuntimeConfig::default()); let addr = rt.spawn(PingPongActor).unwrap(); let inbox = rt.new_inbox::().unwrap(); @@ -1180,7 +1191,7 @@ fn default_config_works_out_of_the_box() { #[test] fn custom_thread_count_respected() { // Given a config requesting 4 threads - let rt = Runtime::new(RuntimeConfig { num_threads: 4, ..Default::default() }); + let rt = std_runtime(RuntimeConfig { num_threads: 4, ..Default::default() }); // Spawn an actor so the runtime has something to report rt.spawn(PingPongActor).unwrap(); let handle = rt.run().unwrap(); @@ -1194,3 +1205,3418 @@ fn custom_thread_count_respected() { // Then the runtime created the requested number of workers assert_eq!(s.num_workers, 4, "runtime should respect the requested thread count"); } + +// ═══════════════════════════════════════════════════════════════════════════ +// Fairness (message budget) +// ═══════════════════════════════════════════════════════════════════════════ + +#[test] +fn hot_actor_does_not_starve_cold_actor() { + // Given: one "hot" actor with 1000 queued messages and one "cold" actor with 1 message + let rt = std_runtime(RuntimeConfig::default()); + let hot_counter = Arc::new(AtomicUsize::new(0)); + let cold_inbox = rt.new_inbox::().unwrap(); + + let hot_addr = rt.spawn(CountingPingActor { counter: hot_counter.clone() }).unwrap(); + let cold_addr = rt.spawn(PingPongActor).unwrap(); + + // Load the hot actor with 1000 messages (needs a dummy inbox for replies) + let dummy = rt.new_inbox::().unwrap(); + for _ in 0..1000 { + rt.send_to(hot_addr, Ping { reply_to: *dummy.addr() }).unwrap(); + } + // Send one message to the cold actor + rt.send_to(cold_addr, Ping { reply_to: *cold_inbox.addr() }).unwrap(); + + // When: we tick a limited number of times (default budget = 64 msgs/actor/tick) + // After 1 tick: hot actor processes 64, cold actor processes 1 + rt.tick(); + + // Then: the cold actor replied even though the hot actor had 1000 queued messages + let cold_reply = cold_inbox.try_recv(); + assert!( + cold_reply.is_some(), + "cold actor must not be starved by hot actor; message budget should enforce fairness" + ); + // And the hot actor only processed its budget, not all 1000 + let hot_processed = hot_counter.load(Ordering::SeqCst); + assert!( + hot_processed <= 64, + "hot actor should process at most the budget (64) per tick, got {hot_processed}" + ); +} + +#[test] +fn unlimited_budget_drains_all_messages() { + // Given: a runtime with unlimited budget (0) + let rt = std_runtime(RuntimeConfig { + actor_message_budget: 0, + ..Default::default() + }); + let counter = Arc::new(AtomicUsize::new(0)); + let dummy = rt.new_inbox::().unwrap(); + let addr = rt.spawn(CountingPingActor { counter: counter.clone() }).unwrap(); + + // When: 500 messages are queued and we tick once + for _ in 0..500 { + rt.send_to(addr, Ping { reply_to: *dummy.addr() }).unwrap(); + } + rt.tick(); + rt.tick(); + + // Then: all 500 are processed in a single pass (no budget limit) + let processed = counter.load(Ordering::SeqCst); + assert_eq!(processed, 500, "unlimited budget should drain all messages"); +} + +#[test] +fn budget_messages_drain_across_multiple_ticks() { + // Given: an actor with more messages than the budget + let rt = std_runtime(RuntimeConfig::default()); // budget=64 + let counter = Arc::new(AtomicUsize::new(0)); + let dummy = rt.new_inbox::().unwrap(); + let addr = rt.spawn(CountingPingActor { counter: counter.clone() }).unwrap(); + + // When: 200 messages are queued + for _ in 0..200 { + rt.send_to(addr, Ping { reply_to: *dummy.addr() }).unwrap(); + } + + // Then: it takes multiple ticks to drain them all + for _ in 0..10 { + rt.tick(); + } + let processed = counter.load(Ordering::SeqCst); + assert_eq!(processed, 200, "all messages should eventually be processed across ticks"); +} + +// ═══════════════════════════════════════════════════════════════════════════ +// Stress Tests +// ═══════════════════════════════════════════════════════════════════════════ + +#[test] +fn message_ordering_preserved_under_budget() { + // Given: a CounterActor processing messages with a small budget + let rt = std_runtime(RuntimeConfig { + actor_message_budget: 8, + ..Default::default() + }); + let addr = rt.spawn(CounterActor { count: 0 }).unwrap(); + let inbox = rt.new_inbox::().unwrap(); + + // When: 100 messages are sent and processed across many ticks + for _ in 0..100 { + rt.send_to(addr, Increment { reply_to: *inbox.addr() }).unwrap(); + } + for _ in 0..50 { + rt.tick(); + } + + // Then: replies arrive in FIFO order (Count(1), Count(2), ..., Count(100)) + let replies: Vec<_> = std::iter::from_fn(|| inbox.try_recv()).collect(); + assert_eq!(replies.len(), 100, "all 100 messages should be delivered"); + for (i, reply) in replies.iter().enumerate() { + assert_eq!( + *reply, + Count(i + 1), + "message ordering must be preserved under budget; expected Count({}) at position {i}", + i + 1 + ); + } +} + +#[test] +fn mt_stress_many_senders_one_receiver() { + // Given: 4 threads, 50 senders each sending 100 messages to one receiver + let rt = std_runtime(RuntimeConfig { + num_threads: 4, + max_actors: 5_000, + channel_buffer_size: 10_000, + ..Default::default() + }); + let total_senders = 50; + let msgs_per_sender = 100; + let total_expected = total_senders * msgs_per_sender; + + let counter = Arc::new(AtomicUsize::new(0)); + let inbox = rt.new_inbox::().unwrap(); + let receiver = rt.spawn(CountingPingActor { counter: counter.clone() }).unwrap(); + + // Spawn senders and send messages + for _ in 0..total_senders { + for _ in 0..msgs_per_sender { + rt.send_to(receiver, Ping { reply_to: *inbox.addr() }).unwrap(); + } + } + + // When: runtime runs in background + let handle = rt.run().unwrap(); + + // Then: all messages are eventually processed + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + loop { + let processed = counter.load(Ordering::SeqCst); + if processed >= total_expected { + break; + } + if std::time::Instant::now() > deadline { + let processed = counter.load(Ordering::SeqCst); + handle.shutdown(); + handle.join(); + panic!( + "Timed out: only {processed}/{total_expected} messages processed in 5s" + ); + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + + handle.shutdown(); + handle.join(); + let final_count = counter.load(Ordering::SeqCst); + assert_eq!( + final_count, total_expected, + "all {total_expected} messages should be processed" + ); +} + +#[test] +fn mt_stress_concurrent_spawn_and_send() { + // Given: a multi-threaded runtime + let rt = std_runtime(RuntimeConfig { + num_threads: 4, + max_actors: 5_000, + channel_buffer_size: 10_000, + ..Default::default() + }); + let inbox = rt.new_inbox::().unwrap(); + let inbox_addr = *inbox.addr(); + + // Spawn 200 actors and immediately send them messages before any ticks + let mut addrs = Vec::new(); + for _ in 0..200 { + let addr = rt.spawn(PingPongActor).unwrap(); + rt.send_to(addr, Ping { reply_to: inbox_addr }).unwrap(); + addrs.push(addr); + } + + // When: runtime processes in background + let handle = rt.run().unwrap(); + + // Then: all 200 replies arrive + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + let mut received = 0; + while received < 200 { + if inbox.try_recv().is_some() { + received += 1; + } else if std::time::Instant::now() > deadline { + handle.shutdown(); + handle.join(); + panic!("Timed out: only {received}/200 replies received in 5s"); + } else { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + } + + handle.shutdown(); + handle.join(); + assert_eq!(received, 200, "all 200 concurrent spawn+send pairs should complete"); +} + +#[test] +fn mt_chain_spawning_under_load() { + // Given: a multi-threaded runtime with a chain actor + let rt = std_runtime(RuntimeConfig { + num_threads: 2, + max_actors: 5_000, + ..Default::default() + }); + let addr = rt.spawn(ChainActor).unwrap(); + let inbox = rt.new_inbox::().unwrap(); + + // When: we trigger a 50-level chain that will spawn actors across workers + rt.send_to( + addr, + ChainMsg { remaining: 50, depth: 0, reply_to: *inbox.addr() }, + ) + .unwrap(); + let handle = rt.run().unwrap(); + + // Then: the chain completes despite actors being on different workers + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + let mut reply = None; + while reply.is_none() { + if let Some(msg) = inbox.try_recv() { + reply = Some(msg); + } else if std::time::Instant::now() > deadline { + handle.shutdown(); + handle.join(); + panic!("Timed out waiting for chain completion"); + } else { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + } + + handle.shutdown(); + handle.join(); + assert_eq!( + reply, + Some(Done(50)), + "50-level chain should complete across multiple workers" + ); +} + +#[test] +fn mt_panic_isolation_under_load() { + // Given: a 4-thread runtime with panicking and healthy actors + let rt = std_runtime(RuntimeConfig { + num_threads: 4, + max_actors: 5_000, + channel_buffer_size: 10_000, + ..Default::default() + }); + let counter = Arc::new(AtomicUsize::new(0)); + let dummy = rt.new_inbox::().unwrap(); + + // Spawn 10 panicking actors and 10 healthy counting actors + let mut panic_addrs = Vec::new(); + let mut healthy_addrs = Vec::new(); + for _ in 0..10 { + panic_addrs.push(rt.spawn(PanicActor).unwrap()); + healthy_addrs.push(rt.spawn(CountingPingActor { counter: counter.clone() }).unwrap()); + } + + // Trigger panics and send 100 messages to each healthy actor + for &addr in &panic_addrs { + rt.send_to(addr, PanicMsg).unwrap(); + } + for &addr in &healthy_addrs { + for _ in 0..100 { + rt.send_to(addr, Ping { reply_to: *dummy.addr() }).unwrap(); + } + } + + // When: runtime runs + let handle = rt.run().unwrap(); + + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + let expected = 10 * 100; + loop { + let processed = counter.load(Ordering::SeqCst); + if processed >= expected { + break; + } + if std::time::Instant::now() > deadline { + let processed = counter.load(Ordering::SeqCst); + handle.shutdown(); + handle.join(); + panic!("Timed out: only {processed}/{expected} healthy messages processed"); + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + + handle.shutdown(); + handle.join(); + + // Then: all healthy actors processed all their messages despite panicking peers + let final_count = counter.load(Ordering::SeqCst); + assert_eq!( + final_count, expected, + "panicking actors should not affect healthy actors on other workers" + ); +} + +#[test] +fn sustained_throughput_does_not_drop_messages() { + // Given: a runtime processing messages in batches, simulating sustained load + let rt = std_runtime(RuntimeConfig::default()); + let counter = Arc::new(AtomicUsize::new(0)); + let dummy = rt.new_inbox::().unwrap(); + let addr = rt.spawn(CountingPingActor { counter: counter.clone() }).unwrap(); + + // When: we send 10 batches of 100 messages, ticking between batches + for batch in 0..10 { + for _ in 0..100 { + rt.send_to(addr, Ping { reply_to: *dummy.addr() }).unwrap(); + } + // Tick enough to process one budget worth per batch + for _ in 0..5 { + rt.tick(); + } + // Verify progress is being made (not stuck) + let processed = counter.load(Ordering::SeqCst); + assert!( + processed > batch * 50, + "batch {batch}: should have made progress, only {processed} processed" + ); + } + + // Drain remaining + for _ in 0..100 { + rt.tick(); + } + + // Then: all 1000 messages are eventually processed + let total = counter.load(Ordering::SeqCst); + assert_eq!(total, 1000, "sustained load should not drop any messages"); +} + +#[test] +fn mt_parked_worker_wakes_on_send() { + // Given: a 2-thread runtime that has been idle (workers are parked) + let rt = std_runtime(RuntimeConfig { + num_threads: 2, + ..Default::default() + }); + let addr = rt.spawn(PingPongActor).unwrap(); + let inbox = rt.new_inbox::().unwrap(); + + let handle = rt.run().unwrap(); + + // Let workers park (idle for a while) + std::thread::sleep(std::time::Duration::from_millis(50)); + + // When: we send a message to a parked worker + let before = std::time::Instant::now(); + handle.runtime.send_to(addr, Ping { reply_to: *inbox.addr() }).unwrap(); + + // Then: the worker wakes up and processes the message quickly + let mut received = false; + for _ in 0..1000 { + if inbox.try_recv().is_some() { + received = true; + break; + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let latency = before.elapsed(); + + handle.shutdown(); + handle.join(); + + assert!(received, "parked worker should wake up and process the message"); + // With park_timeout + unpark, the latency should be well under 100ms + // (old sleep-based approach could have up to 1ms delay per the default max) + assert!( + latency.as_millis() < 100, + "wake-from-park latency should be low, was {:?}", + latency + ); +} + +// ═══════════════════════════════════════════════════════════════════════════ +// Competitor Bug-Inspired Tests +// (from analyzing ractor, actix, kameo bug histories) +// ═══════════════════════════════════════════════════════════════════════════ + +#[test] +fn stats_snapshot_is_read_only() { + // Inspired by ractor #310: get_children() was destructive (cleared on read). + // Verify that calling stats() multiple times returns consistent data. + let rt = std_runtime(RuntimeConfig::default()); + let _addr = rt.spawn(PingPongActor).unwrap(); + rt.tick(); + + let s1 = rt.stats(); + let s2 = rt.stats(); + let s3 = rt.stats(); + + // All three snapshots should report the same actor count + assert_eq!(s1.actors.len(), s2.actors.len(), "stats() should not mutate state"); + assert_eq!(s2.actors.len(), s3.actors.len(), "repeated stats() calls must be idempotent"); + assert!(s1.actors.len() >= 1, "should report at least 1 actor"); +} + +#[test] +fn stats_under_load_do_not_interfere_with_processing() { + // Verify that taking stats snapshots doesn't slow down or break message processing. + let rt = std_runtime(RuntimeConfig::default()); + let counter = Arc::new(AtomicUsize::new(0)); + let dummy = rt.new_inbox::().unwrap(); + let addr = rt.spawn(CountingPingActor { counter: counter.clone() }).unwrap(); + + for _ in 0..100 { + rt.send_to(addr, Ping { reply_to: *dummy.addr() }).unwrap(); + } + + // Interleave stats calls with ticks + for _ in 0..20 { + rt.tick(); + let _s = rt.stats(); // should not affect processing + } + + let processed = counter.load(Ordering::SeqCst); + assert_eq!(processed, 100, "stats() calls must not interfere with message processing"); +} + +#[test] +fn shutdown_wakes_parked_workers_immediately() { + // Verify that shutdown unparks all workers so they exit promptly. + let rt = std_runtime(RuntimeConfig { + num_threads: 4, + ..Default::default() + }); + let handle = rt.run().unwrap(); + + // Let workers park + std::thread::sleep(std::time::Duration::from_millis(50)); + + // Shutdown should wake all parked workers + let before = std::time::Instant::now(); + handle.shutdown(); + handle.join(); + let shutdown_time = before.elapsed(); + + // Workers should exit quickly (well under 1 second) + assert!( + shutdown_time.as_millis() < 500, + "shutdown should complete quickly with parked workers, took {:?}", + shutdown_time + ); +} + +#[test] +fn mt_send_after_run_delivers_to_running_actors() { + // Inspired by kameo #185: messages not delivered during startup. + // Verify that send_to works correctly after run() is called. + let rt = std_runtime(RuntimeConfig { + num_threads: 2, + ..Default::default() + }); + let addr = rt.spawn(PingPongActor).unwrap(); + let inbox = rt.new_inbox::().unwrap(); + + // Start the runtime FIRST, then send + let handle = rt.run().unwrap(); + + // Give workers a moment to start + std::thread::sleep(std::time::Duration::from_millis(10)); + + // Send after run() + handle.runtime.send_to(addr, Ping { reply_to: *inbox.addr() }).unwrap(); + + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + let mut received = false; + while !received { + if inbox.try_recv().is_some() { + received = true; + } else if std::time::Instant::now() > deadline { + handle.shutdown(); + handle.join(); + panic!("Message sent after run() was not delivered"); + } else { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + } + + handle.shutdown(); + handle.join(); + assert!(received, "messages sent after run() must be delivered"); +} + +#[test] +fn budget_respected_even_with_self_sends() { + // Inspired by actix #515: send bypassing mailbox size. + // Verify that self-sends (pending_local) don't bypass the message budget. + // The SelfSendActor sends to itself; each self-send goes through pending_local + // and appears in the mailbox on the next tick. The budget should still apply. + let rt = std_runtime(RuntimeConfig { + actor_message_budget: 4, + ..Default::default() + }); + let addr = rt.spawn(SelfSendActor).unwrap(); + let inbox = rt.new_inbox::().unwrap(); + + // remaining=20 means 20 self-sends before replying Done(0) + rt.send_to(addr, Countdown { remaining: 20, reply_to: *inbox.addr() }).unwrap(); + + // With budget=4, each tick processes at most 4 messages per actor. + // The self-send chain should take several ticks to complete. + for _ in 0..30 { + rt.tick(); + } + + let reply = inbox.try_recv(); + assert_eq!( + reply, + Some(Done(0)), + "self-send chain should complete despite message budget" + ); +} + +// ── Load-Aware Placement Tests ───────────────────────────────────────────── + +/// Given a multi-threaded runtime where one worker has many more actors, +/// when new actors are spawned after a few ticks (so stats propagate), +/// then they should be placed on the lighter worker. +#[test] +fn load_aware_placement_prefers_lighter_worker() { + // 2 threads: intentionally imbalance by spawning many actors first + let rt = std_runtime(RuntimeConfig { + num_threads: 2, + ..Default::default() + }); + + // Phase 1: Spawn 20 actors. With round-robin, they split ~10/10. + let mut addrs = Vec::new(); + for _ in 0..20 { + addrs.push(rt.spawn(CounterActor { count: 0 }).unwrap()); + } + + // Run so stats propagate, then bombard worker 0's actors with messages + // to create mailbox depth imbalance. + let handle = rt.run().unwrap(); + std::thread::sleep(std::time::Duration::from_millis(10)); + + // Send 500 messages to the first 10 actors (likely on worker 0). + for addr in &addrs[..10] { + for _ in 0..50 { + let _ = handle.runtime.send_to(*addr, Increment { + reply_to: *addr, // self-reply to keep mailbox depth up + }); + } + } + + std::thread::sleep(std::time::Duration::from_millis(20)); + + // Phase 2: Spawn 10 more actors. With load-aware placement, + // they should bias toward the lighter worker. + let mut late_addrs = Vec::new(); + for _ in 0..10 { + late_addrs.push(handle.runtime.spawn(CounterActor { count: 0 }).unwrap()); + } + + std::thread::sleep(std::time::Duration::from_millis(20)); + + let stats = handle.runtime.stats(); + handle.shutdown(); + handle.join(); + + // Verify the system is operational — both workers should have actors + let total_actors: usize = stats.workers.iter().map(|w| w.num_actors).sum(); + assert!(total_actors >= 20, "expected at least 20 actors, got {}", total_actors); + + // The lighter worker should have gotten more of the late actors. + // We can't assert exact distribution due to timing, but verify + // actors are distributed across workers (not all on one). + assert!( + stats.workers.iter().all(|w| w.num_actors > 0), + "both workers should have actors, got {:?}", + stats.workers.iter().map(|w| w.num_actors).collect::>() + ); +} + +/// Given a single-threaded runtime (1 worker), +/// when many actors are spawned, +/// then all go to worker 0 regardless of load (no panic, no error). +#[test] +fn load_aware_placement_single_worker_degrades_gracefully() { + let rt = std_runtime(RuntimeConfig::default()); + + for _ in 0..50 { + rt.spawn(CounterActor { count: 0 }).unwrap(); + } + + // Tick several times to let stats update + for _ in 0..10 { + rt.tick(); + } + + let stats = rt.stats(); + assert_eq!(stats.workers.len(), 1); + assert_eq!(stats.workers[0].num_actors, 50); +} + +/// Given a fresh runtime with no prior ticks, +/// when actors are spawned in a burst, +/// then they distribute evenly (round-robin fallback when stats are all zero). +#[test] +fn load_aware_placement_falls_back_to_round_robin_on_fresh_runtime() { + let rt = std_runtime(RuntimeConfig { + num_threads: 4, + ..Default::default() + }); + + // Spawn 100 actors before any ticks (all stats are zero) + for _ in 0..100 { + rt.spawn(CounterActor { count: 0 }).unwrap(); + } + + let handle = rt.run().unwrap(); + std::thread::sleep(std::time::Duration::from_millis(20)); + + let stats = handle.runtime.stats(); + handle.shutdown(); + handle.join(); + + // With 4 workers and 100 actors, each should have ~25 (±5). + // Round-robin gives exactly 25 each. + for w in &stats.workers { + assert!( + w.num_actors >= 20 && w.num_actors <= 30, + "worker {} has {} actors, expected ~25 (round-robin)", + w.id, w.num_actors + ); + } +} + +// ── Mailbox Backpressure Tests ───────────────────────────────────────────── + +/// Given a runtime with bounded mailboxes (capacity=10, DropNewest), +/// when 50 messages are sent to an actor before any ticks, +/// then only the first 10 are delivered and the rest are dropped. +#[test] +fn bounded_mailbox_drop_newest_caps_at_capacity() { + let rt = std_runtime(RuntimeConfig { + default_mailbox_capacity: 10, + mailbox_overflow: MailboxOverflow::DropNewest, + ..Default::default() + }); + + let inbox = rt.new_inbox::().unwrap(); + let addr = rt.spawn(CounterActor { count: 0 }).unwrap(); + + // Send 50 messages — only first 10 should be queued + for _ in 0..50 { + let _ = rt.send_to(addr, Increment { reply_to: *inbox.addr() }); + } + + // Tick enough times to process all queued messages + for _ in 0..20 { + rt.tick(); + } + + // Count replies — should be exactly 10 (the mailbox capacity) + let mut replies = 0; + while inbox.try_recv().is_some() { + replies += 1; + } + assert_eq!(replies, 10, "should deliver exactly mailbox_capacity messages"); + + // Stats should show drops + let stats = rt.stats(); + let total_drops: u64 = stats.workers.iter().map(|w| w.messages_dropped).sum(); + assert_eq!(total_drops, 40, "40 messages should have been dropped"); +} + +/// Given a runtime with bounded mailboxes (capacity=5, DropOldest), +/// when 10 messages are sent before any tick, +/// then only the 5 most recent messages are delivered. +#[test] +fn bounded_mailbox_drop_oldest_keeps_newest() { + let rt = std_runtime(RuntimeConfig { + default_mailbox_capacity: 5, + mailbox_overflow: MailboxOverflow::DropOldest, + ..Default::default() + }); + + let inbox = rt.new_inbox::().unwrap(); + let addr = rt.spawn(DoubleActor).unwrap(); + + // Send messages with values 0..10. DoubleActor replies Done(value * 2). + // With DropOldest and capacity 5, messages 0-4 should be dropped as 5-9 arrive. + for i in 0..10 { + let _ = rt.send_to(addr, Forward { + value: i, + reply_to: *inbox.addr(), + }); + } + + for _ in 0..10 { + rt.tick(); + } + + // Collect all replies + let mut replies = Vec::new(); + while let Some(Done(v)) = inbox.try_recv() { + replies.push(v); + } + + assert_eq!(replies.len(), 5, "should deliver exactly 5 messages"); + // The 5 most recent: values 5,6,7,8,9 → doubled: 10,12,14,16,18 + assert_eq!(replies, vec![10, 12, 14, 16, 18], "should keep the newest messages"); +} + +/// Given a runtime with unbounded mailboxes (capacity=0, the default), +/// when many messages are sent, +/// then all are delivered (backward compatibility). +#[test] +fn unbounded_mailbox_delivers_all_messages() { + let rt = std_runtime(RuntimeConfig::default()); + + let inbox = rt.new_inbox::().unwrap(); + let addr = rt.spawn(CounterActor { count: 0 }).unwrap(); + + for _ in 0..200 { + let _ = rt.send_to(addr, Increment { reply_to: *inbox.addr() }); + } + + for _ in 0..50 { + rt.tick(); + } + + let mut replies = 0; + while inbox.try_recv().is_some() { + replies += 1; + } + assert_eq!(replies, 200, "all 200 messages should be delivered with unbounded mailbox"); + + let stats = rt.stats(); + let total_drops: u64 = stats.workers.iter().map(|w| w.messages_dropped).sum(); + assert_eq!(total_drops, 0, "no drops with unbounded mailbox"); +} + +/// Given bounded mailboxes with budget, when an actor processes messages +/// and frees mailbox space, then new messages should be accepted on subsequent ticks. +#[test] +fn bounded_mailbox_refills_after_processing() { + let rt = std_runtime(RuntimeConfig { + default_mailbox_capacity: 5, + actor_message_budget: 5, + mailbox_overflow: MailboxOverflow::DropNewest, + ..Default::default() + }); + + let inbox = rt.new_inbox::().unwrap(); + let addr = rt.spawn(CounterActor { count: 0 }).unwrap(); + + // Send first batch of 5 — fills mailbox exactly + for _ in 0..5 { + let _ = rt.send_to(addr, Increment { reply_to: *inbox.addr() }); + } + + // Tick to process all 5 (budget=5, capacity=5) + rt.tick(); + + // Send second batch of 5 — mailbox is empty, so all 5 should be accepted + for _ in 0..5 { + let _ = rt.send_to(addr, Increment { reply_to: *inbox.addr() }); + } + + rt.tick(); + + let mut replies = 0; + while inbox.try_recv().is_some() { + replies += 1; + } + assert_eq!(replies, 10, "all 10 messages across 2 batches should be processed"); + + let stats = rt.stats(); + let total_drops: u64 = stats.workers.iter().map(|w| w.messages_dropped).sum(); + assert_eq!(total_drops, 0, "no drops when mailbox drains between batches"); +} + +// ── Dead Actor Cleanup Tests ─────────────────────────────────────────────── + +/// Given an actor that panics and is poisoned, +/// when ticks continue, +/// then the actor is removed from stats and sends to its address fail. +#[test] +fn dead_actor_cleaned_up_from_stats_and_address_map() { + let rt = std_runtime(RuntimeConfig::default()); + + let good = rt.spawn(PingPongActor).unwrap(); + let bad = rt.spawn(PanicActor).unwrap(); + + // Trigger panic + let _ = rt.send_to(bad, PanicMsg); + for _ in 0..5 { rt.tick(); } + + let stats = rt.stats(); + // Good actor still present, bad actor cleaned up + assert_eq!(stats.workers[0].num_actors, 1, "only the healthy actor should remain"); + assert!( + stats.actors.iter().any(|(a, _)| *a == good), + "good actor should be in address map" + ); + assert!( + !stats.actors.iter().any(|(a, _)| *a == bad), + "poisoned actor should be removed from address map" + ); + + // Sends to cleaned-up actor fail + let result = rt.send_to(bad, PanicMsg); + assert!(result.is_err(), "send to cleaned-up actor should fail"); +} + +/// Given many actors that all panic, +/// when ticks proceed, +/// then all are cleaned up and stats reflect zero actors. +#[test] +fn bulk_dead_actor_cleanup() { + let rt = std_runtime(RuntimeConfig::default()); + + let mut addrs = Vec::new(); + for _ in 0..20 { + addrs.push(rt.spawn(PanicActor).unwrap()); + } + + // Trigger all panics + for &addr in &addrs { + let _ = rt.send_to(addr, PanicMsg); + } + for _ in 0..10 { rt.tick(); } + + let stats = rt.stats(); + assert_eq!(stats.workers[0].num_actors, 0, "all poisoned actors should be cleaned up"); + assert_eq!( + stats.actors.len(), 0, + "address map should be empty after all actors poisoned" + ); +} + +// ── Actor Recovery Helpers ────────────────────────────────────────────────── + +/// Handles Forward messages, replies Done(value * 2), panics on the panic_at-th message. +/// count resets to 0 on fresh construction, so restarts reset the counter. +struct RestartTestActor { + count: usize, + panic_at: usize, +} + +impl ActorInterface for RestartTestActor { + type Incoming = Forward; + type Response = Done; + fn handle(&mut self, ctx: &Ctx, msg: Forward) { + self.count += 1; + if self.count >= self.panic_at { + panic!("intentional panic at message {}", self.count); + } + let _ = ctx.send(msg.reply_to, Done(msg.value * 2)); + } +} + +// ── Actor Recovery Tests ─────────────────────────────────────────────────── + +/// Given an actor that panics, +/// when it panics, +/// then it is poisoned and future messages are discarded. +#[test] +fn non_restartable_actor_still_poisons_on_panic() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + // Normal spawn — not restartable + let addr = rt.spawn(RestartTestActor { count: 0, panic_at: 1 }).unwrap(); + + let _ = rt.send_to(addr, Forward { value: 42, reply_to: *inbox.addr() }); + for _ in 0..5 { rt.tick(); } + + let stats = rt.stats(); + let total_panics: u64 = stats.workers.iter().map(|w| w.panics).sum(); + let total_restarts: u64 = stats.workers.iter().map(|w| w.restarts).sum(); + assert_eq!(total_panics, 1, "should panic"); + assert_eq!(total_restarts, 0, "should not restart (not restartable)"); +} + +// ── Lifecycle Hook Helpers ──────────────────────────────────────────────── + +/// An actor that records lifecycle events to shared counters. +struct LifecycleActor { + started: Arc, + stopped: Arc, + handled: Arc, +} + +impl ActorInterface for LifecycleActor { + type Incoming = Ping; + type Response = Pong; + + fn on_start(&mut self, _ctx: &Ctx) { + self.started.fetch_add(1, Ordering::Relaxed); + } + + fn on_stop(&mut self, _ctx: &Ctx) { + self.stopped.fetch_add(1, Ordering::Relaxed); + } + + fn handle(&mut self, ctx: &Ctx, msg: Ping) { + self.handled.fetch_add(1, Ordering::Relaxed); + let _ = ctx.send(msg.reply_to, Pong); + } +} + +/// An actor that stops itself after processing N messages. +struct SelfStopActor { + count: usize, + stop_after: usize, + stopped: Arc, +} + +impl ActorInterface for SelfStopActor { + type Incoming = Forward; + type Response = Done; + + fn on_stop(&mut self, _ctx: &Ctx) { + self.stopped.fetch_add(1, Ordering::Relaxed); + } + + fn handle(&mut self, ctx: &Ctx, msg: Forward) { + self.count += 1; + let _ = ctx.send(msg.reply_to, Done(msg.value)); + if self.count >= self.stop_after { + ctx.stop_self(); + } + } +} + +/// An actor that sends a farewell message in on_stop. +struct FarewellActor { + farewell_to: ActorAddress, +} + +impl ActorInterface for FarewellActor { + type Incoming = Ping; + type Response = Pong; + + fn on_stop(&mut self, ctx: &Ctx) { + let _ = ctx.send(self.farewell_to, Pong); + } + + fn handle(&mut self, ctx: &Ctx, msg: Ping) { + let _ = ctx.send(msg.reply_to, Pong); + } +} + +/// An actor whose on_start panics. +struct PanicOnStartActor { + handled: Arc, +} + +impl ActorInterface for PanicOnStartActor { + type Incoming = Ping; + type Response = Pong; + + fn on_start(&mut self, _ctx: &Ctx) { + panic!("on_start panic"); + } + + fn handle(&mut self, _ctx: &Ctx, _msg: Ping) { + self.handled.fetch_add(1, Ordering::Relaxed); + } +} + +// ── Lifecycle Hook Tests ────────────────────────────────────────────────── + +/// Given an actor with on_start implemented, +/// when it is spawned and the runtime ticks, +/// then on_start is called exactly once before the first message. +#[test] +fn on_start_called_before_first_message() { + let started = Arc::new(AtomicUsize::new(0)); + let stopped = Arc::new(AtomicUsize::new(0)); + let handled = Arc::new(AtomicUsize::new(0)); + + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let addr = rt.spawn(LifecycleActor { + started: started.clone(), + stopped: stopped.clone(), + handled: handled.clone(), + }).unwrap(); + + // First tick — should call on_start + rt.tick(); + assert_eq!(started.load(Ordering::Relaxed), 1, "on_start called on first tick"); + assert_eq!(handled.load(Ordering::Relaxed), 0, "no messages processed yet"); + + // Send messages and tick more + let _ = rt.send_to(addr, Ping { reply_to: *inbox.addr() }); + rt.tick(); + assert_eq!(started.load(Ordering::Relaxed), 1, "on_start not called again"); + assert_eq!(handled.load(Ordering::Relaxed), 1, "message processed after on_start"); +} + +/// Given an actor with on_start, +/// when multiple actors are spawned, +/// then each gets its own on_start call exactly once. +#[test] +fn on_start_called_per_actor() { + let started = Arc::new(AtomicUsize::new(0)); + let stopped = Arc::new(AtomicUsize::new(0)); + let handled = Arc::new(AtomicUsize::new(0)); + + let rt = std_runtime(RuntimeConfig::default()); + + for _ in 0..5 { + let _ = rt.spawn(LifecycleActor { + started: started.clone(), + stopped: stopped.clone(), + handled: handled.clone(), + }).unwrap(); + } + + rt.tick(); + assert_eq!(started.load(Ordering::Relaxed), 5, "on_start called for each of 5 actors"); + + // Subsequent ticks don't repeat on_start + rt.tick(); + rt.tick(); + assert_eq!(started.load(Ordering::Relaxed), 5, "on_start still 5 after more ticks"); +} + +/// Given an actor whose on_start panics, +/// when it is spawned and the runtime ticks, +/// then it is immediately poisoned and never processes messages. +#[test] +fn on_start_panic_poisons_actor() { + let handled = Arc::new(AtomicUsize::new(0)); + + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let addr = rt.spawn(PanicOnStartActor { handled: handled.clone() }).unwrap(); + + let _ = rt.send_to(addr, Ping { reply_to: *inbox.addr() }); + for _ in 0..5 { rt.tick(); } + + assert_eq!(handled.load(Ordering::Relaxed), 0, "actor never processed messages"); + + let stats = rt.stats(); + let total_panics: u64 = stats.workers.iter().map(|w| w.panics).sum(); + assert_eq!(total_panics, 1, "on_start panic counted"); +} + +// ── Graceful Stop Tests ─────────────────────────────────────────────────── + +/// Given an actor that calls ctx.stop_self() after 3 messages, +/// when 5 messages are sent, +/// then only 3 are processed, the actor is removed, and on_stop is called. +#[test] +fn actor_can_stop_self() { + let stopped = Arc::new(AtomicUsize::new(0)); + + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let addr = rt.spawn(SelfStopActor { + count: 0, + stop_after: 3, + stopped: stopped.clone(), + }).unwrap(); + + for i in 0..5 { + let _ = rt.send_to(addr, Forward { value: i, reply_to: *inbox.addr() }); + } + for _ in 0..10 { rt.tick(); } + + // Only 3 messages should be processed (stop_self after 3rd) + let mut replies = Vec::new(); + while let Some(Done(v)) = inbox.try_recv() { + replies.push(v); + } + assert_eq!(replies.len(), 3, "only 3 messages processed before stop"); + assert!(replies.contains(&0)); + assert!(replies.contains(&1)); + assert!(replies.contains(&2)); + + assert_eq!(stopped.load(Ordering::Relaxed), 1, "on_stop called exactly once"); + + // Actor should be removed from address map + let stats = rt.stats(); + assert_eq!(stats.actors.len(), 0, "stopped actor removed from address map"); +} + +/// Given a running actor, +/// when runtime.stop_actor(addr) is called, +/// then the actor stops, on_stop is called, and it's removed from the pool. +#[test] +fn runtime_can_stop_actor() { + let started = Arc::new(AtomicUsize::new(0)); + let stopped = Arc::new(AtomicUsize::new(0)); + let handled = Arc::new(AtomicUsize::new(0)); + + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let addr = rt.spawn(LifecycleActor { + started: started.clone(), + stopped: stopped.clone(), + handled: handled.clone(), + }).unwrap(); + + // Let it start and process a message + let _ = rt.send_to(addr, Ping { reply_to: *inbox.addr() }); + for _ in 0..3 { rt.tick(); } + assert_eq!(handled.load(Ordering::Relaxed), 1); + + // Stop it externally + rt.stop_actor(addr).unwrap(); + for _ in 0..3 { rt.tick(); } + + assert_eq!(stopped.load(Ordering::Relaxed), 1, "on_stop called"); + + // Actor should be gone + let stats = rt.stats(); + assert_eq!(stats.actors.len(), 0, "stopped actor removed"); + assert_eq!(stats.workers[0].num_actors, 0); +} + +/// Given a stopped actor, +/// when new messages are sent to it, +/// then sends return Err (address not found). +#[test] +fn send_to_stopped_actor_returns_error() { + let stopped = Arc::new(AtomicUsize::new(0)); + + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let addr = rt.spawn(SelfStopActor { + count: 0, + stop_after: 1, + stopped: stopped.clone(), + }).unwrap(); + + // One message triggers stop + let _ = rt.send_to(addr, Forward { value: 1, reply_to: *inbox.addr() }); + for _ in 0..10 { rt.tick(); } + + // Actor is now removed — send should fail + let result = rt.send_to(addr, Forward { value: 2, reply_to: *inbox.addr() }); + assert!(result.is_err(), "send to stopped actor should return Err"); +} + +/// Given a gracefully stopped actor and a panicked actor, +/// then stats.stops and stats.panics track them separately. +#[test] +fn stop_vs_panic_tracked_separately_in_stats() { + let stopped = Arc::new(AtomicUsize::new(0)); + + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + // Actor that stops itself after 1 message + let _stop_addr = rt.spawn(SelfStopActor { + count: 0, + stop_after: 1, + stopped: stopped.clone(), + }).unwrap(); + + // Actor that panics on first message + let panic_addr = rt.spawn(RestartTestActor { count: 0, panic_at: 1 }).unwrap(); + + let _ = rt.send_to(_stop_addr, Forward { value: 1, reply_to: *inbox.addr() }); + let _ = rt.send_to(panic_addr, Forward { value: 1, reply_to: *inbox.addr() }); + for _ in 0..10 { rt.tick(); } + + let stats = rt.stats(); + let total_stops: u64 = stats.workers.iter().map(|w| w.stops).sum(); + let total_panics: u64 = stats.workers.iter().map(|w| w.panics).sum(); + + assert_eq!(total_stops, 1, "one graceful stop"); + assert_eq!(total_panics, 1, "one panic"); +} + +/// Given an actor with on_stop that sends a farewell message, +/// when the actor is stopped, +/// then the farewell message is delivered. +#[test] +fn on_stop_can_send_messages() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let addr = rt.spawn(FarewellActor { + farewell_to: *inbox.addr(), + }).unwrap(); + + // Let it start + rt.tick(); + + // Stop it + rt.stop_actor(addr).unwrap(); + for _ in 0..5 { rt.tick(); } + + // Should receive farewell Pong from on_stop + let farewell = inbox.try_recv(); + assert_eq!(farewell, Some(Pong), "farewell message delivered from on_stop"); +} + +/// Given a supervisor with a child that panics and is restarted, +/// when the child is respawned by the supervisor, +/// then on_start is called again on the fresh instance. +#[test] +fn on_start_called_again_after_restart() { + let started = Arc::new(AtomicUsize::new(0)); + + let rt = std_runtime(RuntimeConfig::default()); + + let started_c = started.clone(); + let _sup_addr = rt.spawn(Supervisor::new( + SupervisorStrategy::OneForOne, + 5, + vec![ChildSpec::new("child", RestartPolicy::Permanent, move |ctx| { + ctx.spawn(LifecycleActor { + started: started_c.clone(), + stopped: Arc::new(AtomicUsize::new(0)), + handled: Arc::new(AtomicUsize::new(0)), + }) + })], + )).unwrap(); + + // First tick: supervisor starts, spawns child, on_start called + for _ in 0..3 { rt.tick(); } + assert_eq!(started.load(Ordering::Relaxed), 1, "on_start called once"); +} + +/// Given an actor stopped via stop_actor() with messages already queued, +/// when the stop signal arrives after the queued messages (PoisonPill semantics), +/// then messages ahead of the signal are processed, then the actor stops. +#[test] +fn external_stop_is_queued_after_pending_messages() { + let stopped = Arc::new(AtomicUsize::new(0)); + let handled = Arc::new(AtomicUsize::new(0)); + + let rt = std_runtime(RuntimeConfig::default()); + + let started = Arc::new(AtomicUsize::new(0)); + let addr = rt.spawn(LifecycleActor { + started: started.clone(), + stopped: stopped.clone(), + handled: handled.clone(), + }).unwrap(); + + let inbox = rt.new_inbox::().unwrap(); + + // Queue 10 messages, then stop — StopSignal is queued AFTER the 10 + for _ in 0..10 { + let _ = rt.send_to(addr, Ping { reply_to: *inbox.addr() }); + } + rt.stop_actor(addr).unwrap(); + for _ in 0..10 { rt.tick(); } + + // All 10 messages processed (they were ahead of StopSignal in the queue) + let total_handled = handled.load(Ordering::Relaxed); + assert_eq!(total_handled, 10, "all messages processed before stop signal"); + assert_eq!(stopped.load(Ordering::Relaxed), 1, "on_stop called"); + + // Actor is removed + let stats = rt.stats(); + assert_eq!(stats.actors.len(), 0, "stopped actor removed"); +} + +/// Given a running actor with no pending messages, +/// when stop_actor() is called and then new messages are sent, +/// then the stop takes priority and new messages are not processed. +#[test] +fn external_stop_before_new_messages_prevents_processing() { + let stopped = Arc::new(AtomicUsize::new(0)); + let handled = Arc::new(AtomicUsize::new(0)); + let started = Arc::new(AtomicUsize::new(0)); + + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let addr = rt.spawn(LifecycleActor { + started: started.clone(), + stopped: stopped.clone(), + handled: handled.clone(), + }).unwrap(); + + // Let actor start + rt.tick(); + + // Stop first, then send messages + rt.stop_actor(addr).unwrap(); + for _ in 0..5 { + let _ = rt.send_to(addr, Ping { reply_to: *inbox.addr() }); + } + for _ in 0..10 { rt.tick(); } + + // Stop signal was first in queue, so no messages processed + assert_eq!(handled.load(Ordering::Relaxed), 0, "no messages processed after stop"); + assert_eq!(stopped.load(Ordering::Relaxed), 1, "on_stop called"); +} + +/// Given stop_actor is called on a nonexistent address, +/// then it returns Err. +#[test] +fn stop_nonexistent_actor_returns_error() { + let rt = std_runtime(RuntimeConfig::default()); + let fake_addr = swactor::actor::ActorAddress::default(); + let result = rt.stop_actor(fake_addr); + assert!(result.is_err(), "stop_actor on nonexistent address should return Err"); +} + +// ── Timer Helpers ───────────────────────────────────────────────────────── + +/// Actor that schedules a one-shot timer in on_start: sends a Ping to target after N ticks. +struct TimerStartActor { + target: ActorAddress, + delay_ticks: u64, +} + +impl ActorInterface for TimerStartActor { + type Incoming = Ping; + type Response = Pong; + + fn on_start(&mut self, ctx: &Ctx) { + ctx.send_after_ticks(self.target, Ping { reply_to: ctx.self_addr() }, self.delay_ticks); + } + + fn handle(&mut self, _ctx: &Ctx, _msg: Ping) {} +} + +/// Actor that schedules a one-shot timer when it receives a Forward message. +struct DelayPingPongActor; + +impl ActorInterface for DelayPingPongActor { + type Incoming = Forward; + type Response = Done; + + fn handle(&mut self, ctx: &Ctx, msg: Forward) { + ctx.send_after_ticks(msg.reply_to, Done(msg.value), 3); + } +} + +/// Actor that schedules an interval timer on start: sends Ping every N ticks. +struct HeartbeatActor { + target: ActorAddress, + period: u64, +} + +impl ActorInterface for HeartbeatActor { + type Incoming = Ping; + type Response = Pong; + + fn on_start(&mut self, ctx: &Ctx) { + ctx.send_interval_ticks(self.target, Ping { reply_to: ctx.self_addr() }, self.period); + } + + fn handle(&mut self, _ctx: &Ctx, _msg: Ping) {} +} + +// ── Timer Tests ─────────────────────────────────────────────────────────── + +/// Given an actor that schedules a one-shot timer in on_start, +/// when enough ticks pass, +/// then the timer message is delivered to the target. +#[test] +fn one_shot_timer_fires_after_n_ticks() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let _timer_actor = rt.spawn(TimerStartActor { + target: *inbox.addr(), + delay_ticks: 3, + }).unwrap(); + + // Tick 1: on_start schedules timer (fire_at = current_tick + 3 = 4) + // Timer fires when current_tick >= fire_at, so after tick 4 completes + rt.tick(); // tick 1: on_start, timer scheduled + assert!(inbox.try_recv().is_none(), "no delivery before delay"); + + rt.tick(); // tick 2 + assert!(inbox.try_recv().is_none(), "no delivery on tick 2"); + + rt.tick(); // tick 3 + assert!(inbox.try_recv().is_none(), "no delivery on tick 3"); + + rt.tick(); // tick 4: timer fires + let msg = inbox.try_recv(); + assert!(msg.is_some(), "timer message delivered after 3-tick delay"); +} + +/// Given an actor that schedules a one-shot timer from a message handler, +/// when enough ticks pass after the triggering message, +/// then the delayed response arrives. +#[test] +fn handler_can_schedule_one_shot_timer() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let addr = rt.spawn(DelayPingPongActor).unwrap(); + + let _ = rt.send_to(addr, Forward { value: 42, reply_to: *inbox.addr() }); + rt.tick(); // process Forward, schedule timer (delay=3) + + assert!(inbox.try_recv().is_none(), "no immediate reply"); + + rt.tick(); // tick 2 + rt.tick(); // tick 3 + assert!(inbox.try_recv().is_none(), "not yet"); + + rt.tick(); // tick 4: timer fires + let reply = inbox.try_recv(); + assert_eq!(reply, Some(Done(42)), "delayed reply arrives after 3 ticks"); +} + +/// Given a one-shot timer, +/// when it fires, +/// then it does NOT fire again on subsequent ticks (consumed). +#[test] +fn one_shot_timer_fires_only_once() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let _timer_actor = rt.spawn(TimerStartActor { + target: *inbox.addr(), + delay_ticks: 1, + }).unwrap(); + + rt.tick(); // on_start schedules timer + rt.tick(); // timer fires + assert!(inbox.try_recv().is_some(), "first fire"); + + // Subsequent ticks should NOT fire again + for _ in 0..5 { rt.tick(); } + assert!(inbox.try_recv().is_none(), "one-shot does not repeat"); +} + +/// Given an interval timer with period 2, +/// when multiple ticks pass, +/// then the timer fires repeatedly every 2 ticks. +#[test] +fn interval_timer_fires_repeatedly() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let _heartbeat = rt.spawn(HeartbeatActor { + target: *inbox.addr(), + period: 2, + }).unwrap(); + + rt.tick(); // tick 1: on_start, interval scheduled (next_fire = current + 2 = 3) + assert!(inbox.try_recv().is_none(), "no fire on tick 1"); + + rt.tick(); // tick 2 + assert!(inbox.try_recv().is_none(), "no fire on tick 2"); + + rt.tick(); // tick 3: first fire + assert!(inbox.try_recv().is_some(), "fire on tick 3"); + + rt.tick(); // tick 4 + assert!(inbox.try_recv().is_none(), "no fire on tick 4"); + + rt.tick(); // tick 5: second fire + assert!(inbox.try_recv().is_some(), "fire on tick 5"); + + rt.tick(); // tick 6 + assert!(inbox.try_recv().is_none(), "no fire on tick 6"); + + rt.tick(); // tick 7: third fire + assert!(inbox.try_recv().is_some(), "fire on tick 7"); +} + +/// Given an interval timer targeting an actor that gets stopped, +/// when the actor is removed, +/// then the interval timer is cleaned up (no orphan timers). +#[test] +fn interval_timer_cleaned_up_when_actor_dies() { + let rt = std_runtime(RuntimeConfig::default()); + let _inbox = rt.new_inbox::().unwrap(); + + // Heartbeat sends to a counter that we'll kill + let counter_addr = rt.spawn(CounterActor { count: 0 }).unwrap(); + + // HeartbeatActor sends Ping to counter every tick + let _hb = rt.spawn(HeartbeatActor { + target: counter_addr, + period: 1, + }).unwrap(); + + // Let it run a few ticks + for _ in 0..3 { rt.tick(); } + + // Stop the counter + rt.stop_actor(counter_addr).unwrap(); + for _ in 0..5 { rt.tick(); } + + // Counter is gone, interval timer should be GC'd. + // No crash, no leak — just verifying it doesn't panic. + let stats = rt.stats(); + // Only the heartbeat actor should remain + assert_eq!(stats.workers[0].num_actors, 1); +} + +/// Given a timer with delay 0, +/// when the next tick fires, +/// then the message is delivered immediately on the next tick. +#[test] +fn timer_with_zero_delay_fires_next_tick() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let _timer_actor = rt.spawn(TimerStartActor { + target: *inbox.addr(), + delay_ticks: 0, + }).unwrap(); + + rt.tick(); // on_start schedules timer with delay=0 + // Timer requests are processed after tick_all (phase 5.5) + // Timer fires on the NEXT tick (phase 2.5) + assert!(inbox.try_recv().is_none(), "not yet — timer fires next tick"); + + rt.tick(); // timer fires + assert!(inbox.try_recv().is_some(), "zero-delay timer fires on next tick"); +} + +// ── Named Actor Registry ──────────────────────────────────────────────────── + +/// Given a named actor is spawned, +/// when I look it up by name, +/// then I get the same address that spawn returned. +#[test] +fn named_actor_lookup_returns_spawn_address() { + let rt = std_runtime(RuntimeConfig::default()); + let addr = rt.spawn_named("greeter", PingPongActor).unwrap(); + assert_eq!(rt.where_is("greeter"), Some(addr)); +} + +/// Given a named actor exists, +/// when I send a message to the looked-up address, +/// then the actor receives and processes it. +#[test] +fn named_actor_receives_messages_via_lookup() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + let addr = rt.spawn_named("ponger", PingPongActor).unwrap(); + assert_eq!(rt.where_is("ponger"), Some(addr)); + + rt.send_to(addr, Ping { reply_to: *inbox.addr() }).unwrap(); + rt.tick(); + assert!(inbox.try_recv().is_some(), "named actor should process message"); +} + +/// Given a name is already registered, +/// when I try to spawn another actor with the same name, +/// then I get an error and the original binding is preserved. +#[test] +fn duplicate_name_returns_error() { + let rt = std_runtime(RuntimeConfig::default()); + let first_addr = rt.spawn_named("singleton", PingPongActor).unwrap(); + let result = rt.spawn_named("singleton", PingPongActor); + assert!(result.is_err(), "duplicate name should fail"); + assert_eq!(rt.where_is("singleton"), Some(first_addr), "original binding preserved"); +} + +/// Given no actors are registered, +/// when I look up a nonexistent name, +/// then I get None. +#[test] +fn where_is_returns_none_for_unknown_name() { + let rt = std_runtime(RuntimeConfig::default()); + assert_eq!(rt.where_is("ghost"), None); +} + +/// Given a named actor is stopped, +/// when the next tick runs cleanup, +/// then the name is automatically unregistered. +#[test] +fn name_auto_unregistered_on_actor_death() { + let rt = std_runtime(RuntimeConfig::default()); + let addr = rt.spawn_named("ephemeral", PingPongActor).unwrap(); + rt.tick(); // on_start + + rt.stop_actor(addr).unwrap(); + rt.tick(); // process StopSignal + cleanup + + assert_eq!(rt.where_is("ephemeral"), None, "name should be freed after stop"); +} + +/// Given a named actor died and its name was freed, +/// when I spawn a new actor with the same name, +/// then registration succeeds with a new address. +#[test] +fn name_can_be_reused_after_actor_death() { + let rt = std_runtime(RuntimeConfig::default()); + let first = rt.spawn_named("worker", PingPongActor).unwrap(); + rt.tick(); + rt.stop_actor(first).unwrap(); + rt.tick(); // cleanup frees the name + + let second = rt.spawn_named("worker", PingPongActor).unwrap(); + assert_ne!(first, second, "new actor should have a different address"); + assert_eq!(rt.where_is("worker"), Some(second)); +} + +/// Given a named actor panics (and is not restartable), +/// when the next tick runs cleanup, +/// then the name is freed. +#[test] +fn name_auto_unregistered_on_panic() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + let _addr = rt.spawn_named("fragile", PanicActor).unwrap(); + rt.tick(); // on_start + + rt.send_to(_addr, PanicMsg).unwrap(); + rt.tick(); // panic → poison → cleanup + + assert_eq!(rt.where_is("fragile"), None, "name freed after panic"); + // Can reuse the name + let _new = rt.spawn_named("fragile", PingPongActor).unwrap(); + assert!(rt.where_is("fragile").is_some()); + drop(inbox); +} + +/// Given multiple named actors are registered, +/// when I call registered_names(), +/// then all names are returned. +#[test] +fn registered_names_lists_all() { + let rt = std_runtime(RuntimeConfig::default()); + rt.spawn_named("alpha", PingPongActor).unwrap(); + rt.spawn_named("beta", PingPongActor).unwrap(); + rt.spawn_named("gamma", PingPongActor).unwrap(); + + let mut names = rt.registered_names(); + names.sort(); + assert_eq!(names, vec!["alpha", "beta", "gamma"]); +} + +/// Given a named actor exists, +/// when I manually unregister the name, +/// then the name is freed but the actor continues running. +#[test] +fn manual_unregister_frees_name_but_actor_lives() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + let addr = rt.spawn_named("temp-name", PingPongActor).unwrap(); + rt.tick(); // on_start + + let removed = rt.unregister("temp-name"); + assert_eq!(removed, Some(addr)); + assert_eq!(rt.where_is("temp-name"), None, "name freed"); + + // Actor still alive and can receive messages + rt.send_to(addr, Ping { reply_to: *inbox.addr() }).unwrap(); + rt.tick(); + assert!(inbox.try_recv().is_some(), "actor still processes messages"); +} + +/// An actor that looks up a peer by name using ctx.where_is(). +struct NameLookupActor { + target_name: &'static str, + reply_to: ActorAddress, +} + +impl ActorInterface for NameLookupActor { + type Incoming = Ping; + type Response = (); + fn handle(&mut self, ctx: &Ctx, _msg: Ping) { + if let Some(peer) = ctx.where_is(self.target_name) { + ctx.send(self.reply_to, MyAddr(peer)).unwrap(); + } + } +} + +/// Given a named actor exists, +/// when another actor calls ctx.where_is() from inside a handler, +/// then it resolves the correct address. +#[test] +fn ctx_where_is_resolves_inside_handler() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + let target = rt.spawn_named("target", PingPongActor).unwrap(); + + let looker = rt.spawn(NameLookupActor { + target_name: "target", + reply_to: *inbox.addr(), + }).unwrap(); + + rt.tick(); // on_start + rt.send_to(looker, Ping { reply_to: ActorAddress::default() }).unwrap(); + rt.tick(); // handle → where_is → send + rt.tick(); // deliver reply + + let result = inbox.try_recv(); + assert_eq!(result, Some(MyAddr(target)), "ctx.where_is found the named actor"); +} + +/// An actor that spawns a named child using ctx.spawn_named(). +struct NamedSpawnerActor { + reply_to: ActorAddress, +} + +impl ActorInterface for NamedSpawnerActor { + type Incoming = Ping; + type Response = (); + fn handle(&mut self, ctx: &Ctx, _msg: Ping) { + match ctx.spawn_named("child", PingPongActor) { + Ok(addr) => { ctx.send(self.reply_to, MyAddr(addr)).unwrap(); } + Err(_) => {} + } + } +} + +/// Given an actor calls ctx.spawn_named("child", ...), +/// when the child is spawned, +/// then where_is("child") returns the correct address. +#[test] +fn ctx_spawn_named_registers_from_handler() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let spawner = rt.spawn(NamedSpawnerActor { + reply_to: *inbox.addr(), + }).unwrap(); + + rt.tick(); // on_start + rt.send_to(spawner, Ping { reply_to: ActorAddress::default() }).unwrap(); + rt.tick(); // handle → spawn_named + rt.tick(); // deliver reply + + let child_addr = inbox.try_recv().expect("should receive child address"); + assert_eq!(rt.where_is("child"), Some(child_addr.0), "name registered from handler"); +} + +// ── Actor Monitoring / Death Watch ────────────────────────────────────────── + +/// An actor that monitors a target and forwards Down notifications to a reply address. +struct WatcherActor { + watch_target: ActorAddress, + reply_to: ActorAddress, + mref: Option, +} + +impl ActorInterface for WatcherActor { + type Incoming = Down; + type Response = (); + fn on_start(&mut self, ctx: &Ctx) { + self.mref = Some(ctx.monitor(self.watch_target)); + } + fn handle(&mut self, ctx: &Ctx, msg: Down) { + // Forward the Down notification to the test inbox + ctx.send(self.reply_to, msg).unwrap(); + } +} + +/// Given actor A monitors actor B, +/// when B is gracefully stopped, +/// then A receives a Down { reason: Normal } message. +#[test] +fn monitor_notifies_on_graceful_stop() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let target = rt.spawn(PingPongActor).unwrap(); + let _watcher = rt.spawn(WatcherActor { + watch_target: target, + reply_to: *inbox.addr(), + mref: None, + }).unwrap(); + + rt.tick(); // on_start → watcher sets up monitor + rt.stop_actor(target).unwrap(); + rt.tick(); // target receives StopSignal → cleanup_dead emits Down + rt.tick(); // watcher receives Down → forwards to inbox + + let down = inbox.try_recv().expect("should receive Down notification"); + assert_eq!(down.addr, target); + assert_eq!(down.reason, StopReason::Normal); +} + +/// Given actor A monitors actor B, +/// when B panics, +/// then A receives a Down { reason: Panicked } message. +#[test] +fn monitor_notifies_on_panic() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let target = rt.spawn(PanicActor).unwrap(); + let _watcher = rt.spawn(WatcherActor { + watch_target: target, + reply_to: *inbox.addr(), + mref: None, + }).unwrap(); + + rt.tick(); // on_start + rt.send_to(target, PanicMsg).unwrap(); + rt.tick(); // target panics → cleanup_dead emits Down + rt.tick(); // watcher receives Down → forwards to inbox + + let down = inbox.try_recv().expect("should receive Down on panic"); + assert_eq!(down.addr, target); + assert_eq!(down.reason, StopReason::Panicked); +} + +/// Given two actors both monitor the same target, +/// when the target dies, +/// then both watchers receive independent Down notifications. +#[test] +fn multiple_watchers_all_notified() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox1 = rt.new_inbox::().unwrap(); + let inbox2 = rt.new_inbox::().unwrap(); + + let target = rt.spawn(PingPongActor).unwrap(); + rt.spawn(WatcherActor { + watch_target: target, + reply_to: *inbox1.addr(), + mref: None, + }).unwrap(); + rt.spawn(WatcherActor { + watch_target: target, + reply_to: *inbox2.addr(), + mref: None, + }).unwrap(); + + rt.tick(); // on_start for all + rt.stop_actor(target).unwrap(); + rt.tick(); // cleanup → Down emitted to both watchers + rt.tick(); // watchers forward Down to inboxes + + assert!(inbox1.try_recv().is_some(), "watcher 1 should receive Down"); + assert!(inbox2.try_recv().is_some(), "watcher 2 should receive Down"); +} + +/// An actor that demonitors in response to a Ping message. +struct DemonitorActor { + watch_target: ActorAddress, + mref: Option, +} + +impl ActorInterface for DemonitorActor { + type Incoming = Ping; + type Response = (); + fn on_start(&mut self, ctx: &Ctx) { + self.mref = Some(ctx.monitor(self.watch_target)); + } + fn handle(&mut self, ctx: &Ctx, _msg: Ping) { + // Cancel the monitor + if let Some(mref) = self.mref.take() { + ctx.demonitor(mref); + } + } +} + +/// Given actor A monitors actor B then demonitors, +/// when B dies, +/// then A does NOT receive a Down notification. +#[test] +fn demonitor_cancels_notification() { + let rt = std_runtime(RuntimeConfig::default()); + let down_inbox = rt.new_inbox::().unwrap(); + + let target = rt.spawn(PingPongActor).unwrap(); + let watcher = rt.spawn(DemonitorActor { + watch_target: target, + mref: None, + }).unwrap(); + + rt.tick(); // on_start → monitor set up + + // Trigger demonitor + rt.send_to(watcher, Ping { reply_to: ActorAddress::default() }).unwrap(); + rt.tick(); // handle → demonitor + + // Now kill the target + rt.stop_actor(target).unwrap(); + rt.tick(); // cleanup — no Down should be emitted + rt.tick(); // extra tick to be sure + + assert!(down_inbox.try_recv().is_none(), "demonitored — should NOT receive Down"); +} + +/// Given actor A monitors B, and A dies before B, +/// when B dies, +/// then no Down is delivered (dead watcher cleaned up). +#[test] +fn dead_watcher_does_not_receive_down() { + let rt = std_runtime(RuntimeConfig::default()); + + let target = rt.spawn(PingPongActor).unwrap(); + let watcher = rt.spawn(WatcherActor { + watch_target: target, + reply_to: ActorAddress::default(), // won't matter, watcher dies first + mref: None, + }).unwrap(); + + rt.tick(); // on_start → monitor set up + rt.stop_actor(watcher).unwrap(); + rt.tick(); // watcher dies → its monitors are cleaned up + + // Now kill the target — the dead watcher's subscription should be gone + rt.stop_actor(target).unwrap(); + rt.tick(); // cleanup — should not panic or try to deliver to dead watcher + // If we get here without panic, the test passes +} + +/// Given an external inbox monitors via the runtime, +/// when the target dies, +/// then the inbox receives a Down message. +#[test] +fn down_delivered_to_external_inbox() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let target = rt.spawn(PingPongActor).unwrap(); + + // Set up a monitor from an actor that forwards Down to the inbox. + // The watcher is an actor, but the final recipient is the inbox. + let _watcher = rt.spawn(WatcherActor { + watch_target: target, + reply_to: *inbox.addr(), + mref: None, + }).unwrap(); + + rt.tick(); // on_start + rt.stop_actor(target).unwrap(); + rt.tick(); // cleanup → Down to watcher + rt.tick(); // watcher forwards to inbox + + let down = inbox.try_recv().expect("inbox should receive forwarded Down"); + assert_eq!(down.addr, target); + assert_eq!(down.reason, StopReason::Normal); +} + +/// Given actor A monitors B with two independent monitors, +/// when B dies, +/// then A receives two Down messages (one per monitor). +#[test] +fn stacked_monitors_produce_multiple_notifications() { + /// An actor that creates two monitors on the same target. + struct DoubleWatcherActor { + target: ActorAddress, + reply_to: ActorAddress, + } + + impl ActorInterface for DoubleWatcherActor { + type Incoming = Down; + type Response = (); + fn on_start(&mut self, ctx: &Ctx) { + ctx.monitor(self.target); + ctx.monitor(self.target); + } + fn handle(&mut self, ctx: &Ctx, msg: Down) { + ctx.send(self.reply_to, msg).unwrap(); + } + } + + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let target = rt.spawn(PingPongActor).unwrap(); + rt.spawn(DoubleWatcherActor { + target, + reply_to: *inbox.addr(), + }).unwrap(); + + rt.tick(); // on_start → 2 monitors + rt.stop_actor(target).unwrap(); + rt.tick(); // cleanup → 2 Down messages to watcher + rt.tick(); // watcher forwards both to inbox + + assert!(inbox.try_recv().is_some(), "first Down"); + assert!(inbox.try_recv().is_some(), "second Down"); + assert!(inbox.try_recv().is_none(), "no more"); +} + +// ── Actor Groups / Pub-Sub ────────────────────────────────────────────────── + +/// Given actors join a group, +/// when I query group_members, +/// then all joined actors are listed. +#[test] +fn group_members_returns_joined_actors() { + let rt = std_runtime(RuntimeConfig::default()); + let a = rt.spawn(PingPongActor).unwrap(); + let b = rt.spawn(PingPongActor).unwrap(); + + rt.join_group(a, "workers"); + rt.join_group(b, "workers"); + + let mut members = rt.group_members("workers"); + members.sort_by_key(|addr| addr.0); + let mut expected = vec![a, b]; + expected.sort_by_key(|addr| addr.0); + assert_eq!(members, expected); +} + +/// Given no actors have joined a group, +/// when I query group_members, +/// then the result is empty. +#[test] +fn empty_group_returns_no_members() { + let rt = std_runtime(RuntimeConfig::default()); + assert!(rt.group_members("nonexistent").is_empty()); +} + +/// Given actors in a group, +/// when a message is published to the group, +/// then all members receive the message. +#[test] +fn publish_broadcasts_to_all_members() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox1 = rt.new_inbox::().unwrap(); + let inbox2 = rt.new_inbox::().unwrap(); + + let a = rt.spawn(PingPongActor).unwrap(); + let b = rt.spawn(PingPongActor).unwrap(); + rt.join_group(a, "pongers"); + rt.join_group(b, "pongers"); + + rt.tick(); // on_start + + // Publish a Ping with different reply_to for each — but since it's cloned, + // all members get the same message. Use inbox1's addr as reply_to. + let count = rt.publish_to("pongers", Ping { reply_to: *inbox1.addr() }); + assert_eq!(count, 2, "two members, two messages sent"); + + rt.tick(); // actors handle Ping → send Pong to inbox1 + + // Both actors send to inbox1 (because the published Ping had inbox1 as reply_to) + assert!(inbox1.try_recv().is_some(), "first Pong"); + assert!(inbox1.try_recv().is_some(), "second Pong"); + assert!(inbox1.try_recv().is_none(), "no more"); + drop(inbox2); +} + +/// Given an actor leaves a group, +/// when a message is published, +/// then the leaver does not receive it. +#[test] +fn leave_group_stops_receiving_publishes() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let a = rt.spawn(PingPongActor).unwrap(); + let b = rt.spawn(PingPongActor).unwrap(); + rt.join_group(a, "pool"); + rt.join_group(b, "pool"); + rt.leave_group(b, "pool"); + + rt.tick(); // on_start + let count = rt.publish_to("pool", Ping { reply_to: *inbox.addr() }); + assert_eq!(count, 1, "only one member after leave"); + + rt.tick(); + assert!(inbox.try_recv().is_some(), "one Pong from remaining member"); + assert!(inbox.try_recv().is_none(), "no second Pong"); +} + +/// Given a group member dies, +/// when a message is published, +/// then the dead member is not included. +#[test] +fn dead_actor_auto_removed_from_group() { + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + let a = rt.spawn(PingPongActor).unwrap(); + let b = rt.spawn(PingPongActor).unwrap(); + rt.join_group(a, "team"); + rt.join_group(b, "team"); + + rt.tick(); // on_start + rt.stop_actor(b).unwrap(); + rt.tick(); // b dies, cleaned up from group + + let count = rt.publish_to("team", Ping { reply_to: *inbox.addr() }); + assert_eq!(count, 1, "dead actor removed from group"); + + rt.tick(); + assert!(inbox.try_recv().is_some()); + assert!(inbox.try_recv().is_none()); +} + +/// Given an actor is in multiple groups, +/// when the actor dies, +/// then it is removed from all groups. +#[test] +fn actor_removed_from_all_groups_on_death() { + let rt = std_runtime(RuntimeConfig::default()); + let actor = rt.spawn(PingPongActor).unwrap(); + rt.join_group(actor, "alpha"); + rt.join_group(actor, "beta"); + rt.join_group(actor, "gamma"); + + rt.tick(); + rt.stop_actor(actor).unwrap(); + rt.tick(); // cleanup removes from all groups + + assert!(rt.group_members("alpha").is_empty()); + assert!(rt.group_members("beta").is_empty()); + assert!(rt.group_members("gamma").is_empty()); +} + +/// Given a group becomes empty after its last member leaves, +/// then the group name disappears from the active groups list. +#[test] +fn empty_group_auto_deleted() { + let rt = std_runtime(RuntimeConfig::default()); + let actor = rt.spawn(PingPongActor).unwrap(); + rt.join_group(actor, "temp"); + assert!(rt.groups().contains(&"temp".to_string())); + + rt.leave_group(actor, "temp"); + assert!(!rt.groups().contains(&"temp".to_string()), "empty group should be removed"); +} + +/// Given actors join groups from handlers using ctx.join_group(), +/// when group_members is queried, +/// then the joining actors are listed. +#[test] +fn ctx_join_group_from_handler() { + struct GroupJoinerActor; + + impl ActorInterface for GroupJoinerActor { + type Incoming = Ping; + type Response = (); + fn on_start(&mut self, ctx: &Ctx) { + ctx.join_group("auto-joined"); + } + fn handle(&mut self, _ctx: &Ctx, _msg: Ping) {} + } + + let rt = std_runtime(RuntimeConfig::default()); + let a = rt.spawn(GroupJoinerActor).unwrap(); + let b = rt.spawn(GroupJoinerActor).unwrap(); + + rt.tick(); // on_start → both join "auto-joined" + + let members = rt.group_members("auto-joined"); + assert_eq!(members.len(), 2); + assert!(members.contains(&a)); + assert!(members.contains(&b)); +} + +/// Given an actor uses ctx.publish() from inside a handler, +/// when the published message is processed, +/// then all group members receive it. +#[test] +fn ctx_publish_broadcasts_from_handler() { + #[derive(Clone)] + struct BroadcastCmd { + reply_to: ActorAddress, + } + + struct BroadcasterActor; + + impl ActorInterface for BroadcasterActor { + type Incoming = BroadcastCmd; + type Response = (); + fn on_start(&mut self, ctx: &Ctx) { + ctx.join_group("broadcast-test"); + } + fn handle(&mut self, ctx: &Ctx, msg: BroadcastCmd) { + ctx.publish("broadcast-test", Ping { reply_to: msg.reply_to }); + } + } + + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + + // Spawn 3 PingPongActors and one Broadcaster, all in the same group + let _p1 = rt.spawn(PingPongActor).unwrap(); + let _p2 = rt.spawn(PingPongActor).unwrap(); + rt.join_group(_p1, "broadcast-test"); + rt.join_group(_p2, "broadcast-test"); + + let broadcaster = rt.spawn(BroadcasterActor).unwrap(); + + rt.tick(); // on_start (broadcaster joins group too) + + // Send BroadcastCmd to broadcaster + rt.send_to(broadcaster, BroadcastCmd { reply_to: *inbox.addr() }).unwrap(); + rt.tick(); // broadcaster handles → publish Ping to all 3 members (including self) + rt.tick(); // PingPong actors handle Ping → send Pong to inbox + // Broadcaster also gets the Ping but it expects BroadcastCmd, so type mismatch (silent) + + // At least 2 Pongs from the PingPongActors + let mut pong_count = 0; + while inbox.try_recv().is_some() { + pong_count += 1; + } + assert!(pong_count >= 2, "at least 2 PingPong members should reply, got {pong_count}"); +} + +// ── Ask Pattern ───────────────────────────────────────────────────────────── + +/// Given a PingPong actor, +/// when I ask with recv_ticking, +/// then I get the Pong response. +#[test] +fn ask_recv_ticking_returns_response() { + let rt = std_runtime(RuntimeConfig::default()); + let actor = rt.spawn(PingPongActor).unwrap(); + rt.tick(); // on_start + + let pong: Pong = rt.ask(actor, |reply_to| Ping { reply_to }) + .unwrap() + .recv_ticking(&rt, 10) + .unwrap(); + assert_eq!(pong, Pong); +} + +/// Given a CounterActor, +/// when I ask multiple times, +/// then each response reflects the updated state. +#[test] +fn ask_multiple_times_tracks_state() { + let rt = std_runtime(RuntimeConfig::default()); + let actor = rt.spawn(CounterActor { count: 0 }).unwrap(); + rt.tick(); // on_start + + let c1: Count = rt.ask(actor, |reply_to| Increment { reply_to }) + .unwrap().recv_ticking(&rt, 10).unwrap(); + let c2: Count = rt.ask(actor, |reply_to| Increment { reply_to }) + .unwrap().recv_ticking(&rt, 10).unwrap(); + let c3: Count = rt.ask(actor, |reply_to| Increment { reply_to }) + .unwrap().recv_ticking(&rt, 10).unwrap(); + + assert_eq!(c1, Count(1)); + assert_eq!(c2, Count(2)); + assert_eq!(c3, Count(3)); +} + +/// Given a dead actor, +/// when I ask and tick, +/// then recv_ticking returns a timeout error. +#[test] +fn ask_timeout_when_no_response() { + let rt = std_runtime(RuntimeConfig::default()); + let actor = rt.spawn(PingPongActor).unwrap(); + rt.tick(); + rt.stop_actor(actor).unwrap(); + rt.tick(); // actor dies + + // Ask the dead actor — message is undeliverable, no response + let result = rt.ask::(actor, |reply_to| Ping { reply_to }); + // send_to may succeed (message goes to transfer queue) or fail (addr removed) + // Either way, no response will come + if let Ok(ask) = result { + let err = ask.recv_ticking(&rt, 5); + assert!(err.is_err(), "should timeout with no response"); + } +} + +/// Given an ask handle, +/// when I use try_recv before ticking, +/// then it returns None (response hasn't arrived yet). +#[test] +fn ask_try_recv_returns_none_before_tick() { + let rt = std_runtime(RuntimeConfig::default()); + let actor = rt.spawn(PingPongActor).unwrap(); + rt.tick(); // on_start + + let ask = rt.ask::(actor, |reply_to| Ping { reply_to }).unwrap(); + assert!(ask.try_recv().is_none(), "no response before ticking"); + + rt.tick(); // process message + assert_eq!(ask.try_recv(), Some(Pong)); +} + +/// Given an ask, the reply_addr() returns the inbox address for manual use. +#[test] +fn ask_reply_addr_is_accessible() { + let rt = std_runtime(RuntimeConfig::default()); + let actor = rt.spawn(PingPongActor).unwrap(); + rt.tick(); + + let ask = rt.ask::(actor, |reply_to| Ping { reply_to }).unwrap(); + let addr = *ask.reply_addr(); + // The address should be valid (non-zero) + assert_ne!(addr, ActorAddress::default()); +} + +// ─── Supervisor Tests ────────────────────────────────────────────────────── + +/// Actor that panics after receiving a configurable number of messages. +struct PanicAfterN { + trigger: usize, + count: usize, + counter: Arc, +} + +impl ActorInterface for PanicAfterN { + type Incoming = Ping; + type Response = (); + fn handle(&mut self, ctx: &Ctx, msg: Ping) { + self.count += 1; + self.counter.fetch_add(1, Ordering::SeqCst); + let _ = ctx.send(msg.reply_to, Pong); + if self.count >= self.trigger { + panic!("intentional panic at message {}", self.count); + } + } +} + +// --- handle_down tests --- + +/// Given an actor with handle_down and a monitored target, +/// when the target dies, the watcher receives a Down via handle_down. +#[test] +fn handle_down_receives_death_notification() { + struct MonitoringTracker { + target: ActorAddress, + downs: Vec, + inbox: ActorAddress, + } + impl ActorInterface for MonitoringTracker { + type Incoming = Ping; + type Response = (); + fn on_start(&mut self, ctx: &Ctx) { + ctx.monitor(self.target); + } + fn handle(&mut self, ctx: &Ctx, _msg: Ping) { + let _ = ctx.send(self.inbox, Count(self.downs.len())); + } + fn handle_down(&mut self, _ctx: &Ctx, down: Down) { + self.downs.push(down); + } + } + + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + let inbox_addr = *inbox.addr(); + let target = rt.spawn(PanicActor).unwrap(); + let tracker = rt.spawn(MonitoringTracker { + target, + downs: vec![], + inbox: inbox_addr, + }).unwrap(); + rt.tick(); // on_start for both + + // Kill the target + rt.send_to(target, PanicMsg).unwrap(); + rt.tick(); // target panics + rt.tick(); // Down delivered to tracker via handle_down + + // Ask tracker how many downs it saw + rt.send_to(tracker, Ping { reply_to: inbox_addr }).unwrap(); + rt.tick(); + assert_eq!(inbox.try_recv(), Some(Count(1))); +} + +/// Given an actor whose Incoming type IS Down, handle_down is NOT called — +/// the Down goes through the normal handle() method (backward compatibility). +#[test] +fn handle_down_skipped_when_incoming_is_down() { + struct DownAsIncoming { + target: ActorAddress, + inbox: ActorAddress, + } + impl ActorInterface for DownAsIncoming { + type Incoming = Down; + type Response = (); + fn on_start(&mut self, ctx: &Ctx) { + ctx.monitor(self.target); + } + fn handle(&mut self, ctx: &Ctx, msg: Down) { + let _ = ctx.send(self.inbox, msg); + } + fn handle_down(&mut self, _ctx: &Ctx, _down: Down) { + panic!("handle_down must not be called when Incoming=Down"); + } + } + + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + let inbox_addr = *inbox.addr(); + let target = rt.spawn(PanicActor).unwrap(); + let _watcher = rt.spawn(DownAsIncoming { target, inbox: inbox_addr }).unwrap(); + rt.tick(); // on_start + + rt.send_to(target, PanicMsg).unwrap(); + rt.tick(); // panic + rt.tick(); // Down delivered through handle(), not handle_down + + let received = inbox.try_recv().expect("Down should be delivered via handle()"); + assert_eq!(received.reason, StopReason::Panicked); +} + +// --- ctx.stop_actor tests --- + +/// Given two actors, one can stop the other via ctx.stop_actor(). +#[test] +fn ctx_stop_actor_stops_target() { + #[derive(Clone)] + struct StopCmd { + target: ActorAddress, + } + struct Stopper; + impl ActorInterface for Stopper { + type Incoming = StopCmd; + type Response = (); + fn handle(&mut self, ctx: &Ctx, msg: StopCmd) { + let _ = ctx.stop_actor(msg.target); + } + } + + let rt = std_runtime(RuntimeConfig::default()); + let target = rt.spawn(PingPongActor).unwrap(); + let stopper = rt.spawn(Stopper).unwrap(); + rt.tick(); // on_start + + rt.send_to(stopper, StopCmd { target }).unwrap(); + rt.tick(); // stopper handles StopCmd → stop_actor(target) + rt.tick(); // StopSignal delivered to target, target stops + rt.tick(); // cleanup + + assert!(rt.send_to(target, Ping { reply_to: ActorAddress::default() }).is_err()); + // Stopper should still be alive + assert!(rt.send_to(stopper, StopCmd { target }).is_ok()); +} + +// --- Supervisor tests --- + +/// Given a supervisor with one permanent child, +/// when the child panics, the supervisor restarts it. +#[test] +fn supervisor_restarts_permanent_child_on_panic() { + let counter = Arc::new(AtomicUsize::new(0)); + let counter_c = counter.clone(); + let inbox_holder: Arc>> = + Arc::new(std::sync::Mutex::new(None)); + + let rt = std_runtime(RuntimeConfig::default()); + let inbox = rt.new_inbox::().unwrap(); + let inbox_addr = *inbox.addr(); + *inbox_holder.lock().unwrap() = Some(inbox_addr); + + let sup = Supervisor::new( + SupervisorStrategy::OneForOne, + 5, + vec![ChildSpec::new("worker", RestartPolicy::Permanent, move |ctx| { + ctx.spawn(PanicAfterN { + trigger: 2, // panics on 2nd message + count: 0, + counter: counter_c.clone(), + }) + })], + ); + let _sup_addr = rt.spawn(sup).unwrap(); + rt.tick(); // supervisor on_start → spawns child + rt.tick(); // child on_start + + // Find the child by checking stats + let stats = rt.stats(); + assert_eq!(stats.workers[0].num_actors, 2); // supervisor + child + + // Send message to child — need to discover child address. + // We'll use the address map from stats. + let child_addr = stats.actors.iter() + .find(|(addr, _)| *addr != _sup_addr) + .map(|(addr, _)| *addr) + .unwrap(); + + // First message: child processes, increments counter + rt.send_to(child_addr, Ping { reply_to: inbox_addr }).unwrap(); + rt.tick(); + assert_eq!(counter.load(Ordering::SeqCst), 1); + + // Second message: child panics (trigger=2) + rt.send_to(child_addr, Ping { reply_to: inbox_addr }).unwrap(); + rt.tick(); // child panics and is poisoned + rt.tick(); // cleanup: Down delivered to supervisor via handle_down + rt.tick(); // supervisor restarts child (spawns new one) + rt.tick(); // new child on_start + + // Supervisor is still alive, and a new child exists + let stats = rt.stats(); + assert_eq!(stats.workers[0].num_actors, 2); // supervisor + new child +} + +/// Given a supervisor with a transient child, +/// when the child stops normally, it is NOT restarted. +#[test] +fn supervisor_does_not_restart_transient_child_on_normal_stop() { + let rt = std_runtime(RuntimeConfig::default()); + + struct StopsAfterFirst; + impl ActorInterface for StopsAfterFirst { + type Incoming = Ping; + type Response = (); + fn handle(&mut self, ctx: &Ctx, _msg: Ping) { + ctx.stop_self(); + } + } + + let sup = Supervisor::new( + SupervisorStrategy::OneForOne, + 5, + vec![ChildSpec::new("worker", RestartPolicy::Transient, |ctx| { + ctx.spawn(StopsAfterFirst) + })], + ); + let sup_addr = rt.spawn(sup).unwrap(); + rt.tick(); // supervisor on_start → child spawned + rt.tick(); // child on_start + + let stats = rt.stats(); + assert_eq!(stats.workers[0].num_actors, 2); // sup + child + + // Find child address + let child_addr = stats.actors.iter() + .find(|(addr, _)| *addr != sup_addr) + .map(|(addr, _)| *addr) + .unwrap(); + + // Send message — child stops itself + rt.send_to(child_addr, Ping { reply_to: ActorAddress::default() }).unwrap(); + rt.tick(); // child handles, stops self + rt.tick(); // cleanup: Down(Normal) delivered to supervisor + rt.tick(); // supervisor sees Transient + Normal → no restart + + let stats = rt.stats(); + assert_eq!(stats.workers[0].num_actors, 1); // only supervisor remains +} + +/// Given a supervisor with a transient child, +/// when the child panics, it IS restarted. +#[test] +fn supervisor_restarts_transient_child_on_panic() { + let rt = std_runtime(RuntimeConfig::default()); + let counter = Arc::new(AtomicUsize::new(0)); + let counter_c = counter.clone(); + + let sup = Supervisor::new( + SupervisorStrategy::OneForOne, + 5, + vec![ChildSpec::new("worker", RestartPolicy::Transient, move |ctx| { + ctx.spawn(PanicAfterN { + trigger: 1, // panics on first message + count: 0, + counter: counter_c.clone(), + }) + })], + ); + let sup_addr = rt.spawn(sup).unwrap(); + rt.tick(); // supervisor starts, spawns child + rt.tick(); // child on_start + + let child_addr = rt.stats().actors.iter() + .find(|(addr, _)| *addr != sup_addr) + .map(|(addr, _)| *addr) + .unwrap(); + + // Send message — child panics + let inbox = rt.new_inbox::().unwrap(); + rt.send_to(child_addr, Ping { reply_to: *inbox.addr() }).unwrap(); + rt.tick(); // child panics + rt.tick(); // Down(Panicked) → supervisor restarts + rt.tick(); // new child spawned + rt.tick(); // new child on_start + + // Supervisor + new child alive + let stats = rt.stats(); + assert_eq!(stats.workers[0].num_actors, 2); +} + +/// Given a supervisor with a temporary child, +/// when the child dies (any reason), it is never restarted. +#[test] +fn supervisor_never_restarts_temporary_child() { + let rt = std_runtime(RuntimeConfig::default()); + + let sup = Supervisor::new( + SupervisorStrategy::OneForOne, + 5, + vec![ChildSpec::new("worker", RestartPolicy::Temporary, |ctx| { + ctx.spawn(PanicActor) + })], + ); + let sup_addr = rt.spawn(sup).unwrap(); + rt.tick(); // supervisor starts, spawns child + rt.tick(); // child on_start + + let child_addr = rt.stats().actors.iter() + .find(|(addr, _)| *addr != sup_addr) + .map(|(addr, _)| *addr) + .unwrap(); + + // Kill the child + rt.send_to(child_addr, PanicMsg).unwrap(); + rt.tick(); // panic + rt.tick(); // Down → supervisor sees Temporary → no restart + rt.tick(); // settle + + let stats = rt.stats(); + assert_eq!(stats.workers[0].num_actors, 1); // only supervisor +} + +/// Given a supervisor with max_restarts=2, +/// when more than 2 restarts occur, the supervisor stops itself (meltdown). +#[test] +fn supervisor_meltdown_after_max_restarts() { + let rt = std_runtime(RuntimeConfig::default()); + let counter = Arc::new(AtomicUsize::new(0)); + + let sup = Supervisor::new( + SupervisorStrategy::OneForOne, + 2, // only 2 restarts allowed + vec![ChildSpec::new("crasher", RestartPolicy::Permanent, { + let counter = counter.clone(); + move |ctx| { + ctx.spawn(PanicAfterN { + trigger: 1, + count: 0, + counter: counter.clone(), + }) + } + })], + ); + let sup_addr = rt.spawn(sup).unwrap(); + rt.tick(); rt.tick(); // supervisor + child started + + // Crash the child 3 times (1 initial + 2 restarts = max, 3rd restart triggers meltdown) + for _ in 0..3 { + // Find current child + if let Some((child_addr, _)) = rt.stats().actors.iter() + .find(|(addr, _)| *addr != sup_addr) + { + let inbox = rt.new_inbox::().unwrap(); + let _ = rt.send_to(*child_addr, Ping { reply_to: *inbox.addr() }); + rt.tick(); // child panics + rt.tick(); // Down delivered → restart or meltdown + rt.tick(); // new child spawned (or supervisor stopped) + rt.tick(); // settle + } + } + + // After 3 crashes with max_restarts=2, supervisor should have stopped itself + let stats = rt.stats(); + let sup_alive = stats.actors.iter().any(|(addr, _)| *addr == sup_addr); + assert!(!sup_alive, "supervisor should have stopped after exceeding max_restarts"); +} + +/// Given a supervisor with multiple children, +/// when one child panics, only that child is restarted (OneForOne). +#[test] +fn supervisor_one_for_one_only_restarts_failed_child() { + let rt = std_runtime(RuntimeConfig::default()); + let counter_a = Arc::new(AtomicUsize::new(0)); + let counter_b = Arc::new(AtomicUsize::new(0)); + + let sup = Supervisor::new( + SupervisorStrategy::OneForOne, + 5, + vec![ + ChildSpec::new("crasher", RestartPolicy::Permanent, { + let c = counter_a.clone(); + move |ctx| ctx.spawn_named("child_a", PanicAfterN { + trigger: 1, count: 0, counter: c.clone(), + }) + }), + ChildSpec::new("stable", RestartPolicy::Permanent, { + let c = counter_b.clone(); + move |ctx| ctx.spawn_named("child_b", CountingPingActor { counter: c.clone() }) + }), + ], + ); + let _sup_addr = rt.spawn(sup).unwrap(); + rt.tick(); rt.tick(); // start up + + let child_a = rt.where_is("child_a").expect("child_a should be named"); + let child_b = rt.where_is("child_b").expect("child_b should be named"); + + // Send to child_b to prove it's alive + let inbox = rt.new_inbox::().unwrap(); + rt.send_to(child_b, Ping { reply_to: *inbox.addr() }).unwrap(); + rt.tick(); + let b_processed_before = counter_b.load(Ordering::SeqCst); + assert!(b_processed_before >= 1); + + // Crash child_a + rt.send_to(child_a, Ping { reply_to: *inbox.addr() }).unwrap(); + rt.tick(); // child_a panics + rt.tick(); // Down → supervisor restarts child_a + rt.tick(); rt.tick(); // new child spawned + on_start + + // child_b should still be alive (same address, same name) + let child_b_after = rt.where_is("child_b").expect("child_b should still exist"); + assert_eq!(child_b, child_b_after, "child_b address should be unchanged"); + + rt.send_to(child_b, Ping { reply_to: *inbox.addr() }).unwrap(); + rt.tick(); + assert!(counter_b.load(Ordering::SeqCst) > b_processed_before, + "child_b should still be processing messages"); + + // Supervisor + 2 children should be alive + assert_eq!(rt.stats().workers[0].num_actors, 3); +} + +/// Given a OneForAll supervisor with 3 children, +/// when one child panics, ALL children are stopped and restarted in spec order. +#[test] +fn supervisor_one_for_all_restarts_all_on_single_failure() { + let rt = std_runtime(RuntimeConfig::default()); + let counter_a = Arc::new(AtomicUsize::new(0)); + let counter_b = Arc::new(AtomicUsize::new(0)); + let counter_c = Arc::new(AtomicUsize::new(0)); + + let sup = Supervisor::new( + SupervisorStrategy::OneForAll, + 5, + vec![ + ChildSpec::new("a", RestartPolicy::Permanent, { + let c = counter_a.clone(); + move |ctx| ctx.spawn_named("ofa_a", PanicAfterN { + trigger: 1, count: 0, counter: c.clone(), + }) + }), + ChildSpec::new("b", RestartPolicy::Permanent, { + let c = counter_b.clone(); + move |ctx| ctx.spawn_named("ofa_b", CountingPingActor { counter: c.clone() }) + }), + ChildSpec::new("c", RestartPolicy::Permanent, { + let c = counter_c.clone(); + move |ctx| ctx.spawn_named("ofa_c", CountingPingActor { counter: c.clone() }) + }), + ], + ); + let _sup_addr = rt.spawn(sup).unwrap(); + rt.tick(); rt.tick(); // startup + + let old_b = rt.where_is("ofa_b").expect("ofa_b exists"); + let old_c = rt.where_is("ofa_c").expect("ofa_c exists"); + let child_a = rt.where_is("ofa_a").expect("ofa_a exists"); + + // Crash child_a + let inbox = rt.new_inbox::().unwrap(); + rt.send_to(child_a, Ping { reply_to: *inbox.addr() }).unwrap(); + rt.tick(); // child_a panics + // supervisor receives Down(a) → OneForAll → stops b and c + for _ in 0..8 { rt.tick(); } // wait for stops, Downs, restarts, on_starts + + // All 3 children should be alive with NEW addresses (old ones are dead) + let stats = rt.stats(); + assert_eq!(stats.workers[0].num_actors, 4); // sup + 3 new children + + // The old addresses for b and c should be gone (they were stopped and re-created) + // New names should be re-registered + let new_b = rt.where_is("ofa_b").expect("ofa_b re-registered after restart"); + let new_c = rt.where_is("ofa_c").expect("ofa_c re-registered after restart"); + assert_ne!(old_b, new_b, "child_b should have a new address after restart"); + assert_ne!(old_c, new_c, "child_c should have a new address after restart"); +} + +/// Given a RestForOne supervisor with children [a, b, c], +/// when child b panics, children b and c are restarted (children after b in spec order). +/// Child a is unaffected. +#[test] +fn supervisor_rest_for_one_restarts_rest_after_failed() { + let rt = std_runtime(RuntimeConfig::default()); + let counter_a = Arc::new(AtomicUsize::new(0)); + let counter_b = Arc::new(AtomicUsize::new(0)); + let counter_c = Arc::new(AtomicUsize::new(0)); + + let sup = Supervisor::new( + SupervisorStrategy::RestForOne, + 5, + vec![ + ChildSpec::new("a", RestartPolicy::Permanent, { + let c = counter_a.clone(); + move |ctx| ctx.spawn_named("rfo_a", CountingPingActor { counter: c.clone() }) + }), + ChildSpec::new("b", RestartPolicy::Permanent, { + let c = counter_b.clone(); + move |ctx| ctx.spawn_named("rfo_b", PanicAfterN { + trigger: 1, count: 0, counter: c.clone(), + }) + }), + ChildSpec::new("c", RestartPolicy::Permanent, { + let c = counter_c.clone(); + move |ctx| ctx.spawn_named("rfo_c", CountingPingActor { counter: c.clone() }) + }), + ], + ); + let _sup_addr = rt.spawn(sup).unwrap(); + rt.tick(); rt.tick(); // startup + + let old_a = rt.where_is("rfo_a").expect("rfo_a exists"); + let old_c = rt.where_is("rfo_c").expect("rfo_c exists"); + let child_b = rt.where_is("rfo_b").expect("rfo_b exists"); + + // Crash child_b + let inbox = rt.new_inbox::().unwrap(); + rt.send_to(child_b, Ping { reply_to: *inbox.addr() }).unwrap(); + rt.tick(); // child_b panics + // supervisor: Down(b) → RestForOne → stops c (rest after b), then restarts b+c + for _ in 0..8 { rt.tick(); } + + // All 3 children should be alive + let stats = rt.stats(); + assert_eq!(stats.workers[0].num_actors, 4); // sup + 3 children + + // child_a should be UNCHANGED (not affected by RestForOne) + let new_a = rt.where_is("rfo_a").expect("rfo_a still exists"); + assert_eq!(old_a, new_a, "child_a should not be restarted in RestForOne when b fails"); + + // child_c should have a NEW address (it was stopped and re-created) + let new_c = rt.where_is("rfo_c").expect("rfo_c re-registered"); + assert_ne!(old_c, new_c, "child_c should have a new address after RestForOne restart"); +} + +/// Given a OneForAll supervisor, when the last child of the failed set confirms death, +/// all children are restarted in spec order (not reverse). +#[test] +fn supervisor_one_for_all_waits_for_all_downs_before_restart() { + let rt = std_runtime(RuntimeConfig::default()); + + let sup = Supervisor::new( + SupervisorStrategy::OneForAll, + 5, + vec![ + ChildSpec::new("x", RestartPolicy::Permanent, |ctx| ctx.spawn(PingPongActor)), + ChildSpec::new("y", RestartPolicy::Permanent, |ctx| ctx.spawn(PingPongActor)), + ], + ); + let sup_addr = rt.spawn(sup).unwrap(); + rt.tick(); rt.tick(); // startup + + assert_eq!(rt.stats().workers[0].num_actors, 3); // sup + 2 children + + // Stop one child (graceful stop triggers OneForAll) + let actors: Vec<_> = rt.stats().actors.iter() + .filter(|(addr, _)| *addr != sup_addr) + .map(|(addr, _)| *addr) + .collect(); + rt.stop_actor(actors[0]).unwrap(); + + // Tick enough times for full cycle: stop → Down → supervisor stops other → Down → restart all + for _ in 0..10 { rt.tick(); } + + // Should have supervisor + 2 new children + assert_eq!(rt.stats().workers[0].num_actors, 3); +} + +/// Given a supervisor that stops, its children also stop. +#[test] +fn supervisor_on_stop_kills_children() { + let rt = std_runtime(RuntimeConfig::default()); + + let sup = Supervisor::new( + SupervisorStrategy::OneForOne, + 5, + vec![ + ChildSpec::new("a", RestartPolicy::Permanent, |ctx| ctx.spawn(PingPongActor)), + ChildSpec::new("b", RestartPolicy::Permanent, |ctx| ctx.spawn(PingPongActor)), + ], + ); + let sup_addr = rt.spawn(sup).unwrap(); + rt.tick(); rt.tick(); // start up + + assert_eq!(rt.stats().workers[0].num_actors, 3); // sup + 2 children + + // Stop the supervisor + rt.stop_actor(sup_addr).unwrap(); + rt.tick(); // StopSignal delivered to supervisor, on_stop sends stop to children + rt.tick(); // supervisor cleaned up, stop signals delivered to children + rt.tick(); // children stop + rt.tick(); // children cleaned up + + assert_eq!(rt.stats().workers[0].num_actors, 0); +} + +// ── Router tests ───────────────────────────────────────────────────────────── + +#[test] +fn router_round_robin_distributes_across_workers() { + // Given a round-robin router with 3 workers + // When we send 6 messages + // Then each worker should receive exactly 2 messages + let rt = std_runtime(RuntimeConfig::default()); + let collected = Arc::new(std::sync::Mutex::new(Vec::new())); + + struct Collector(Arc>>); + #[derive(Clone)] + struct Work(usize); + impl ActorInterface for Collector { + type Incoming = Work; + type Response = (); + fn handle(&mut self, ctx: &Ctx, msg: Work) { + self.0.lock().unwrap().push((ctx.self_addr(), msg.0)); + } + } + + let c = collected.clone(); + let router = Router::::new( + RoutingStrategy::RoundRobin, + 3, + move |ctx| ctx.spawn(Collector(c.clone())), + 10, + ); + let router_addr = rt.spawn(router).unwrap(); + rt.tick(); // on_start spawns 3 workers + + for i in 0..6 { + rt.send_to(router_addr, Work(i)).unwrap(); + } + rt.tick(); // router receives 6 Work messages, forwards to workers + rt.tick(); // workers process their messages + + let data = collected.lock().unwrap(); + assert_eq!(data.len(), 6); + + // Count how many unique workers received messages + let mut per_worker = std::collections::HashMap::new(); + for (addr, _) in data.iter() { + *per_worker.entry(*addr).or_insert(0usize) += 1; + } + // All 3 workers should have received exactly 2 messages each + assert_eq!(per_worker.len(), 3); + for count in per_worker.values() { + assert_eq!(*count, 2); + } +} + +#[test] +fn router_broadcast_sends_to_all_workers() { + // Given a broadcast router with 3 workers + // When we send 1 message + // Then all 3 workers should receive it + let rt = std_runtime(RuntimeConfig::default()); + let count = Arc::new(AtomicUsize::new(0)); + + struct Counter(Arc); + #[derive(Clone)] + struct Ping; + impl ActorInterface for Counter { + type Incoming = Ping; + type Response = (); + fn handle(&mut self, _ctx: &Ctx, _msg: Ping) { + self.0.fetch_add(1, Ordering::Relaxed); + } + } + + let c = count.clone(); + let router = Router::::new( + RoutingStrategy::Broadcast, + 3, + move |ctx| ctx.spawn(Counter(c.clone())), + 10, + ); + let router_addr = rt.spawn(router).unwrap(); + rt.tick(); // on_start spawns workers + + rt.send_to(router_addr, Ping).unwrap(); + rt.tick(); // router broadcasts + rt.tick(); // workers process + + assert_eq!(count.load(Ordering::Relaxed), 3); +} + +#[test] +fn router_random_delivers_to_some_worker() { + // Given a random router with 3 workers + // When we send 30 messages + // Then at least 2 different workers should have received messages + let rt = std_runtime(RuntimeConfig::default()); + let collected = Arc::new(std::sync::Mutex::new(Vec::new())); + + struct Collector(Arc>>); + #[derive(Clone)] + struct Work; + impl ActorInterface for Collector { + type Incoming = Work; + type Response = (); + fn handle(&mut self, ctx: &Ctx, _msg: Work) { + self.0.lock().unwrap().push(ctx.self_addr()); + } + } + + let c = collected.clone(); + let router = Router::::new( + RoutingStrategy::Random, + 3, + move |ctx| ctx.spawn(Collector(c.clone())), + 10, + ); + let router_addr = rt.spawn(router).unwrap(); + rt.tick(); + + for _ in 0..30 { + rt.send_to(router_addr, Work).unwrap(); + } + rt.tick(); + rt.tick(); + + let data = collected.lock().unwrap(); + assert_eq!(data.len(), 30); + + let unique: std::collections::HashSet<_> = data.iter().collect(); + // With 30 messages across 3 workers, probability of all going to 1 is vanishingly small + assert!(unique.len() >= 2, "expected at least 2 workers used, got {}", unique.len()); +} + +#[test] +fn router_replaces_dead_worker() { + // Given a router with 3 workers + // When one worker panics + // Then the router should spawn a replacement and messages continue to be delivered + let rt = std_runtime(RuntimeConfig::default()); + let spawn_count = Arc::new(AtomicUsize::new(0)); + + struct PanicOnFirst { + first: bool, + } + #[derive(Clone)] + struct Work; + impl ActorInterface for PanicOnFirst { + type Incoming = Work; + type Response = (); + fn handle(&mut self, _ctx: &Ctx, _msg: Work) { + if self.first { + self.first = false; + panic!("first message panic"); + } + } + } + + let sc = spawn_count.clone(); + let router = Router::::new( + RoutingStrategy::RoundRobin, + 3, + move |ctx| { + let n = sc.fetch_add(1, Ordering::Relaxed); + // Only the first worker panics on its first message + ctx.spawn(PanicOnFirst { first: n == 0 }) + }, + 10, + ); + let router_addr = rt.spawn(router).unwrap(); + rt.tick(); // spawn workers (3 spawned) + assert_eq!(spawn_count.load(Ordering::Relaxed), 3); + + // Send a message that will hit worker 0 (round-robin starts at 0) + rt.send_to(router_addr, Work).unwrap(); + rt.tick(); // router forwards to worker 0 + rt.tick(); // worker 0 panics + rt.tick(); // cleanup + Down delivered to router + rt.tick(); // router spawns replacement + rt.tick(); // replacement starts + + // Should have spawned 4 total (3 original + 1 replacement) + assert_eq!(spawn_count.load(Ordering::Relaxed), 4); + + // Verify all 3 slots are live — stats should show router + 3 workers + assert_eq!(rt.stats().workers[0].num_actors, 4); +} + +#[test] +fn router_meltdown_after_max_restarts() { + // Given a router with max_restarts=2 + // When 3 workers die in succession + // Then the router should stop itself + let rt = std_runtime(RuntimeConfig::default()); + + struct AlwaysPanics; + #[derive(Clone)] + struct Work; + impl ActorInterface for AlwaysPanics { + type Incoming = Work; + type Response = (); + fn handle(&mut self, _ctx: &Ctx, _msg: Work) { + panic!("always"); + } + } + + let router = Router::::new( + RoutingStrategy::RoundRobin, + 1, + |ctx| ctx.spawn(AlwaysPanics), + 2, // max 2 restarts + ); + let router_addr = rt.spawn(router).unwrap(); + rt.tick(); // on_start + + // Kill the worker 3 times (> max_restarts=2) + for _ in 0..3 { + rt.send_to(router_addr, Work).unwrap(); + for _ in 0..5 { + rt.tick(); + } + } + + // After 3 restarts, router should have shut down + for _ in 0..5 { + rt.tick(); + } + assert_eq!(rt.stats().workers[0].num_actors, 0); +} + +#[test] +fn router_on_stop_kills_workers() { + // Given a running router with 3 workers + // When the router is stopped + // Then all workers should also be stopped + let rt = std_runtime(RuntimeConfig::default()); + + struct Dummy; + #[derive(Clone)] + struct Work; + impl ActorInterface for Dummy { + type Incoming = Work; + type Response = (); + fn handle(&mut self, _ctx: &Ctx, _msg: Work) {} + } + + let router = Router::::new( + RoutingStrategy::RoundRobin, + 3, + |ctx| ctx.spawn(Dummy), + 10, + ); + let router_addr = rt.spawn(router).unwrap(); + rt.tick(); // on_start + assert_eq!(rt.stats().workers[0].num_actors, 4); // router + 3 workers + + rt.stop_actor(router_addr).unwrap(); + for _ in 0..5 { + rt.tick(); + } + + assert_eq!(rt.stats().workers[0].num_actors, 0); +} + +#[test] +fn router_broadcast_multiple_messages_all_received() { + // Given a broadcast router + // When we send 5 messages to 3 workers + // Then total received = 5 * 3 = 15 + let rt = std_runtime(RuntimeConfig::default()); + let total = Arc::new(AtomicUsize::new(0)); + + struct Sink(Arc); + #[derive(Clone)] + struct Tick; + impl ActorInterface for Sink { + type Incoming = Tick; + type Response = (); + fn handle(&mut self, _ctx: &Ctx, _msg: Tick) { + self.0.fetch_add(1, Ordering::Relaxed); + } + } + + let t = total.clone(); + let router = Router::::new( + RoutingStrategy::Broadcast, + 3, + move |ctx| ctx.spawn(Sink(t.clone())), + 10, + ); + let router_addr = rt.spawn(router).unwrap(); + rt.tick(); + + for _ in 0..5 { + rt.send_to(router_addr, Tick).unwrap(); + } + rt.tick(); // router broadcasts + rt.tick(); // workers process + + assert_eq!(total.load(Ordering::Relaxed), 15); +} + +// ── Identity Hasher Correctness ──────────────────────────────────────────── + +/// Given: 200 actors each expecting a unique numbered message +/// When: Each actor receives its number and replies with (self_addr, number) +/// Then: All 200 replies match — no message was misrouted by the identity hasher +#[test] +fn many_actors_all_receive_correct_messages() { + #[derive(Clone)] + struct NumberedMsg { + n: usize, + reply_to: ActorAddress, + } + + #[derive(Clone, Debug, PartialEq)] + struct NumberedReply { + from: ActorAddress, + n: usize, + } + + struct NumberedActor; + + impl ActorInterface for NumberedActor { + type Incoming = NumberedMsg; + type Response = (); + fn handle(&mut self, ctx: &Ctx, msg: NumberedMsg) { + let _ = ctx.send( + msg.reply_to, + NumberedReply { + from: ctx.self_addr(), + n: msg.n, + }, + ); + } + } + + let rt = std_runtime(RuntimeConfig { + max_actors: 300, + channel_buffer_size: 1024, + num_threads: 1, + ..Default::default() + }); + + let inbox = rt.new_inbox::().unwrap(); + let inbox_addr = *inbox.addr(); + + // Spawn 200 actors + let mut addrs = Vec::new(); + for _ in 0..200 { + addrs.push(rt.spawn(NumberedActor).unwrap()); + } + rt.tick(); // on_start + + // Send unique numbered message to each + for (i, addr) in addrs.iter().enumerate() { + rt.send_to( + *addr, + NumberedMsg { + n: i, + reply_to: inbox_addr, + }, + ) + .unwrap(); + } + rt.tick(); // process + reply + rt.tick(); // deliver replies + + // Verify all 200 replies + let mut replies: Vec = Vec::new(); + while let Some(reply) = inbox.try_recv() { + replies.push(reply); + } + + assert_eq!(replies.len(), 200, "should receive exactly 200 replies"); + + // Verify each reply came from the correct actor with the correct number + for (i, addr) in addrs.iter().enumerate() { + let reply = replies.iter().find(|r| r.n == i); + assert!( + reply.is_some(), + "missing reply for actor #{i}" + ); + assert_eq!( + reply.unwrap().from, *addr, + "reply #{i} came from wrong actor" + ); + } +} + +/// Given: A 100-actor ring where each actor forwards to the next +/// When: A message enters the ring and traverses all 100 hops +/// Then: The message completes the full circuit (address_map lookups all correct) +#[test] +fn ring_routing_unchanged_after_hasher_optimization() { + #[derive(Clone)] + struct RingHop { + hops_remaining: usize, + final_dest: ActorAddress, + } + + #[derive(Clone, Debug, PartialEq)] + struct RingDone(usize); // total hops completed + + struct RingNode { + next: ActorAddress, + } + + impl ActorInterface for RingNode { + type Incoming = RingHop; + type Response = (); + fn handle(&mut self, ctx: &Ctx, msg: RingHop) { + if msg.hops_remaining == 0 { + let _ = ctx.send(msg.final_dest, RingDone(100)); + } else { + let _ = ctx.send( + self.next, + RingHop { + hops_remaining: msg.hops_remaining - 1, + final_dest: msg.final_dest, + }, + ); + } + } + } + + let rt = std_runtime(RuntimeConfig { + max_actors: 200, + channel_buffer_size: 1024, + num_threads: 1, + ..Default::default() + }); + + let inbox = rt.new_inbox::().unwrap(); + let inbox_addr = *inbox.addr(); + + // Build chain backwards: last node sends to inbox, first node receives + let mut addrs = Vec::new(); + let mut next = inbox_addr; + for _ in (0..100).rev() { + let node = RingNode { next }; + let addr = rt.spawn(node).unwrap(); + addrs.push(addr); + next = addr; + } + addrs.reverse(); // addrs[0] is start of chain + + rt.tick(); // on_start + + // Inject message at the start + rt.send_to( + addrs[0], + RingHop { + hops_remaining: 99, + final_dest: inbox_addr, + }, + ) + .unwrap(); + + // Tick enough times for the message to traverse all 100 actors + // (each tick processes one hop via pending_local delivery) + for _ in 0..110 { + rt.tick(); + } + + let result = inbox.try_recv(); + assert!(result.is_some(), "ring message should complete all 100 hops"); + assert_eq!(result.unwrap(), RingDone(100)); +} + +/// Given: An actor that calls ctx.stop_self() upon receiving a trigger message +/// When: The trigger is sent, then 5 more messages are sent, then ticked +/// Then: The actor is removed, only messages before stop are processed +#[test] +fn stop_self_with_pending_messages_still_works() { + let processed = Arc::new(AtomicUsize::new(0)); + + #[derive(Clone)] + struct Msg(bool); // true = trigger stop + + struct StopOnTrigger(Arc); + + impl ActorInterface for StopOnTrigger { + type Incoming = Msg; + type Response = (); + fn handle(&mut self, ctx: &Ctx, msg: Msg) { + self.0.fetch_add(1, Ordering::Relaxed); + if msg.0 { + ctx.stop_self(); + } + } + } + + let rt = std_runtime(RuntimeConfig::default()); + let p = processed.clone(); + let addr = rt.spawn(StopOnTrigger(p)).unwrap(); + rt.tick(); // on_start + + // Send: 2 normal, 1 trigger, 5 more normal + rt.send_to(addr, Msg(false)).unwrap(); + rt.send_to(addr, Msg(false)).unwrap(); + rt.send_to(addr, Msg(true)).unwrap(); // stop trigger + rt.send_to(addr, Msg(false)).unwrap(); + rt.send_to(addr, Msg(false)).unwrap(); + rt.send_to(addr, Msg(false)).unwrap(); + rt.send_to(addr, Msg(false)).unwrap(); + rt.send_to(addr, Msg(false)).unwrap(); + + rt.tick(); // process messages — stops after trigger + rt.tick(); // cleanup + + // Only 3 messages should be processed (2 normal + 1 trigger) + assert_eq!( + processed.load(Ordering::Relaxed), + 3, + "should process exactly the messages up to and including the stop trigger" + ); + + // Subsequent sends should fail + assert!(rt.send_to(addr, Msg(false)).is_err()); +}