//! Remote pids without a network (ADR 0072): `proc` operations on a //! remote pid reach a fake transport's hooks, or act as on a dead pid //! without any; what a transport delivers from its own thread reaches //! local actors and their ties. //! //! The hooks are global: each test installs them in its root actor, under //! the scheduler tests' turn, and removes them before returning. The fake //! hooks make the local halves of ties as the transport's do, listing them //! in a fake node's [`Dist`], fresh for each test. //! //! Back-pressure: a fake peer's queue of [`CAPACITY`] messages, drained by //! the root actor, parks senders through `dist::send_parking`. use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; use std::sync::{Arc, Mutex}; use crate::abi::{Block, Ctx, UNIT, Value, YIELD_NONE, YIELD_PANIC, int, int_get, is_ptr}; use crate::dist::{ Dist, Hooks, Signal, Try, Waiter, inbound, install, outbound, remote, send_parking, uninstall, unsendable, wake_sender, }; use crate::heap::{drop_value, dup_value}; use crate::process::{PROC_OPS, RootCap}; use super::super::{Exit, Shared, exit_actor, this}; use super::{THREADS, run_root, spawn, wait_forever, waits_forever, yield_until}; /// What the fake transport was asked to do. #[derive(Clone, Debug, PartialEq)] enum Call { /// (owner, tag, wire, the message, an `Int`). Send(i64, i64, i64, i64), Link(i64, i64), /// (watcher, tag, watched). Monitor(i64, i64, i64), /// (watcher, tag, watched). Demonitor(i64, i64, i64), /// (unlinker, unlinked, id). Unlink(i64, i64, u64), /// The acknowledgement of a remote pid's unlink: (local, remote, id). UnlinkAck(i64, i64, u64), Signal(i64, i64, Signal), /// (watched, watcher, tag, reason). Down(i64, i64, i64, Exit), /// A monitored spawn's answer, for this new actor. Answered(i64), } static CALLS: Mutex> = Mutex::new(Vec::new()); fn called(call: Call) { CALLS.lock().expect("calls").push(call); } fn calls() -> Vec { CALLS.lock().expect("calls").clone() } /// The fake node's ties: what a started node keeps (`node.rs`). static DIST: Mutex>> = Mutex::new(None); fn dist() -> Arc { let mut dist = DIST.lock().expect("the ties"); Arc::clone(dist.get_or_insert_with(Arc::default)) } static FAKE: Hooks = Hooks { send: |_, owner, tag, wire, message| { called(Call::Send(owner, tag, wire, int_get(message))); Ok(()) }, link: |sched, me, other| { let mut meanwhile = None; outbound::link(&dist(), me, other, || { if KILL_WHILE_LINKING.swap(false, Ordering::SeqCst) { meanwhile = Some(kill_meanwhile(sched, me.pid)); } if LOSE_NODE_WHILE_LINKING.swap(false, Ordering::SeqCst) { meanwhile = Some(lose_node_meanwhile(sched, me.pid, other)); } called(Call::Link(me.pid, other)); true }); if let Some(meanwhile) = meanwhile { meanwhile.join().expect("the meanwhile"); } }, monitor: |sched, me, watched, tag| { if outbound::monitor(sched, &dist(), me, watched, tag) { called(Call::Monitor(me.pid, tag, watched)); } true }, demonitor: |me, watched, tag| { if outbound::demonitor(me, watched, tag) { called(Call::Demonitor(me.pid, tag, watched)); } }, unlink: |me, other| { let id = dist().unlink_id(); outbound::unlink(me, other, id, || { if UNLINK_NOT_UP.swap(false, Ordering::SeqCst) { return false; } called(Call::Unlink(me.pid, other, id)); true }); }, signal: |from, to, signal| called(Call::Signal(from, to, signal.clone())), down: |watched, watcher, tag, reason| called(Call::Down(watched, watcher, tag, reason.clone())), exit: |pid, nodes| dist().untie(pid, nodes), }; /// The next link the fake transport sends, its actor is killed from /// another thread while it sends it. static KILL_WHILE_LINKING: AtomicBool = AtomicBool::new(false); /// The next link the fake transport sends, its node is lost as the frame /// is queued, under the linking actor's lock. static LOSE_NODE_WHILE_LINKING: AtomicBool = AtomicBool::new(false); /// The next unlink the fake transport sends finds its node not up. static UNLINK_NOT_UP: AtomicBool = AtomicBool::new(false); /// Kill `pid` from a thread that is no scheduler's, after a pause long /// enough for it to wait for `pid`'s lock if it is held: what the fake link /// does while it queues its frame. fn kill_meanwhile(sched: &Shared, pid: i64) -> std::thread::JoinHandle<()> { let address = std::ptr::from_ref(sched) as usize; let killer = std::thread::spawn(move || { // SAFETY: the scheduler outlives the thread, joined by the hook. exit_actor(unsafe { &*(address as *const Shared) }, pid, Exit::Killed); }); std::thread::sleep(std::time::Duration::from_millis(20)); killer } /// Lose `other`'s node from a thread that is no scheduler's, as the frame /// linking `pid` to it is queued: return once the loss's fan-out has taken /// the actors listed under the node (if `pid` is listed, it then waits for /// `pid`'s lock), or has ended. fn lose_node_meanwhile(sched: &Shared, pid: i64, other: i64) -> std::thread::JoinHandle<()> { let node = crate::dist::parts(other).0; let listed = dist().tied_to(node).contains(&pid); let address = std::ptr::from_ref(sched) as usize; let loser = std::thread::spawn(move || { // SAFETY: the scheduler outlives the thread, joined by the hook. inbound::node_down(unsafe { &*(address as *const Shared) }, &dist(), node); }); while !loser.is_finished() && !(listed && !dist().tied_to(node).contains(&pid)) { std::thread::yield_now(); } loser } /// Start the fake transport, forgetting earlier calls and ties. fn start_fake() { CALLS.lock().expect("calls").clear(); *DIST.lock().expect("the ties") = Some(Arc::default()); install(&FAKE); } fn pid(node: u16, serial: i64) -> i64 { remote(node, serial).expect("a remote pid") } /// Perform `proc` operation `op` with `args` (owned), as generated code /// does: through a clause of the actor's root capability. /// /// # Safety /// `ctx` must be the running actor's context. unsafe fn perform(ctx: *mut Ctx, op: &str, args: &[Value]) -> Value { let i = PROC_OPS .iter() .position(|o| *o == op) .expect("an operation"); // SAFETY: forwarded caller guarantee; a capability holds a clause per // operation. unsafe { let cap = crate::process::root_cap(RootCap::Proc); let clause = dup_value(*Block::fields_ptr(cap as *mut Block).add(i)); drop_value(ctx, cap); crate::prims::call_closure(ctx, clause, args) } } /// Field `i` of a constructor block (borrowed). /// /// # Safety /// `v` must be a live block with more than `i` fields. unsafe fn field(v: Value, i: usize) -> Value { // SAFETY: caller guarantee. unsafe { *Block::fields_ptr(v as *mut Block).add(i) } } /// A subject's tag. /// /// # Safety /// `s` must be a live subject. unsafe fn tag_of(s: Value) -> i64 { // SAFETY: caller guarantee. unsafe { int_get(field(s, 1)) } } /// The message on `subject` (borrowed), waiting up to `timeout` (0: none). /// /// # Safety /// `ctx` must be the running actor's context. unsafe fn receive(ctx: *mut Ctx, subject: Value, timeout: i64) -> Option { // SAFETY: forwarded caller guarantee; `receive` answers an `Option`. unsafe { let answer = perform(ctx, "receive", &[dup_value(subject), int(timeout)]); assert_eq!((*ctx).yielding, YIELD_NONE, "the receive returned"); if !is_ptr(answer) { return None; } let message = dup_value(field(answer, 0)); drop_value(ctx, answer); Some(message) } } /// An `ExitReason` value. /// /// # Safety /// `v` must be a live `ExitReason`. unsafe fn reason(v: Value) -> Exit { if !is_ptr(v) { return match int_get(v) { 0 => Exit::Normal, 1 => Exit::Killed, 3 => Exit::Shutdown, other => panic!("no reason {other}"), }; } // SAFETY: caller guarantee: `Crashed(message)`. let message = unsafe { crate::values::string_bytes(field(v, 0)) }; Exit::Crashed(String::from_utf8_lossy(message).into_owned()) } /// A `Down(pid, reason)` or `ExitSignal(pid, reason)` (owned, dropped). /// /// # Safety /// `ctx` must be the running actor's context; `v` such a value. unsafe fn signal_of(ctx: *mut Ctx, v: Value) -> (i64, Exit) { // SAFETY: caller guarantee. unsafe { let parts = (int_get(field(v, 0)), reason(field(v, 1))); drop_value(ctx, v); parts } } fn crashed(message: &str) -> Exit { Exit::Crashed(message.into()) } /// Run `f` with the scheduler on a thread that is no scheduler's, as the /// transport's. /// /// # Safety /// `ctx` must be the running actor's context; the thread must be joined /// before the actor returns. unsafe fn outside( ctx: *mut Ctx, f: impl FnOnce(&Shared) + Send + 'static, ) -> std::thread::JoinHandle<()> { // SAFETY: forwarded caller guarantee. let address = std::ptr::from_ref(unsafe { this(ctx) }.1) as usize; std::thread::spawn(move || { // SAFETY: the scheduler outlives the thread (caller guarantee). f(unsafe { &*(address as *const Shared) }); }) } /// [`outside`], waiting for it. /// /// # Safety /// `ctx` must be the running actor's context. unsafe fn from_outside(ctx: *mut Ctx, f: impl FnOnce(&Shared) + Send + 'static) { // SAFETY: forwarded caller guarantee; joined at once. unsafe { outside(ctx, f) } .join() .expect("the transport's thread"); } // ---- without hooks --------------------------------------------------------------- /// Every operation on a remote pid, with no transport. unsafe extern "C" fn treats_remote_pids_as_dead(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { uninstall(); CALLS.lock().expect("calls").clear(); let other = pid(3, 42); let to = crate::values::cell(ctx, 1, &[int(other), int(7), int(0)]); assert_eq!(perform(ctx, "send", &[to, int(5)]), UNIT, "dropped"); perform(ctx, "link", &[int(other)]); let a = this(ctx).0; assert_eq!(a.with_proc(|p| p.unlink(other)), (false, false), "no link"); let down = perform(ctx, "monitor", &[int(other)]); let message = receive(ctx, down, 0).expect("a Down at once"); assert_eq!(signal_of(ctx, message), (other, crashed("noproc"))); drop_value(ctx, down); perform(ctx, "kill", &[int(other)]); perform(ctx, "stop", &[int(other)]); assert_eq!((*ctx).yielding, YIELD_NONE, "still running"); assert!(a.with_proc(|p| p.ties().nodes.is_empty()), "no ties"); assert!(calls().is_empty()); } UNIT } #[test] fn without_a_transport_a_remote_pid_is_a_dead_one() { for threads in THREADS { assert_eq!( run_root(threads, treats_remote_pids_as_dead), Exit::Normal, "{threads} threads" ); } } /// Receives on a `Remote` subject. unsafe extern "C" fn receives_on_a_remote_subject(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { let from = crate::values::cell(ctx, 1, &[int(pid(0, 0)), int(7), int(0)]); perform(ctx, "receive", &[from, int(0)]); assert_eq!((*ctx).yielding, YIELD_PANIC); } UNIT } #[test] fn receiving_on_a_remote_subject_panics() { for threads in THREADS { assert_eq!( run_root(threads, receives_on_a_remote_subject), crashed("receive on a subject owned by another actor"), "{threads} threads" ); } } // ---- outbound ---------------------------------------------------------------------- static CRASHER_LINKS: AtomicI64 = AtomicI64::new(0); /// Links the pid in `CRASHER_LINKS`, then crashes. unsafe extern "C" fn links_then_crashes(ctx: *mut Ctx) -> Value { // SAFETY: an actor's entry. unsafe { perform(ctx, "link", &[int(CRASHER_LINKS.load(Ordering::SeqCst))]); crate::effects::tl_panic_str(ctx, c"boom".as_ptr()) } } /// Every operation on a remote pid, through the fake transport. unsafe extern "C" fn reaches_the_transport(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_fake(); let a = this(ctx).0; let me = a.pid; let other = pid(3, 42); let to = crate::values::cell(ctx, 1, &[int(other), int(7), int(2)]); perform(ctx, "send", &[to, int(5)]); perform(ctx, "link", &[int(other)]); let down = perform(ctx, "monitor", &[int(other)]); let tag = tag_of(down); assert_eq!(receive(ctx, down, 0), None, "no Down yet"); drop_value(ctx, down); perform(ctx, "kill", &[int(other)]); perform(ctx, "stop", &[int(other)]); assert_eq!( calls(), [ Call::Send(other, 7, 2, 5), Call::Link(me, other), Call::Monitor(me, tag, other), Call::Signal(me, other, Signal::Kill), Call::Signal(me, other, Signal::Stop), ] ); assert_eq!(dist().tied_to(3), [me]); // An actor linked to a remote pid crashes: the transport is told, // and the actor is no longer listed as tied to the node. let linked = pid(4, 1); CRASHER_LINKS.store(linked, Ordering::SeqCst); let crasher = spawn(ctx, links_then_crashes); yield_until(ctx, "the crasher to finish", |s| s.actors.all().len() == 1); let told = Call::Signal(crasher, linked, Signal::Linked(crashed("boom"))); assert_eq!(calls()[5..], [Call::Link(crasher, linked), told]); assert!(dist().tied_to(4).is_empty(), "untied at its exit"); uninstall(); } UNIT } #[test] fn remote_operations_reach_the_transport() { for threads in THREADS { assert_eq!( run_root(threads, reaches_the_transport), Exit::Normal, "{threads} threads" ); } } // ---- inbound ----------------------------------------------------------------------- /// Waits for a message the transport delivers once every actor waits: /// with a transport running, that is no deadlock. unsafe extern "C" fn receives_from_the_transport(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry; it joins the thread before returning. unsafe { start_fake(); spawn(ctx, waits_forever); let me = this(ctx).0.pid; let subject = perform(ctx, "subject", &[]); let tag = tag_of(subject); // The root joins it before it returns. let transport = outside(ctx, move |sched| { while !sched.idling.load(Ordering::SeqCst) { std::thread::sleep(std::time::Duration::from_micros(100)); } inbound::deliver(sched, me, tag, int(42)); }); let message = receive(ctx, subject, -1).expect("a message"); assert_eq!(int_get(message), 42); drop_value(ctx, subject); transport.join().expect("the transport's thread"); uninstall(); } UNIT } #[test] fn a_running_transport_is_no_deadlock_and_delivers_from_its_thread() { for threads in THREADS { assert_eq!( run_root(threads, receives_from_the_transport), Exit::Normal, "{threads} threads" ); } } static LINKED_TO: AtomicI64 = AtomicI64::new(0); /// Links the pid in `LINKED_TO`, then waits until stopped. unsafe extern "C" fn links_and_waits(ctx: *mut Ctx) -> Value { // SAFETY: an actor's entry. unsafe { perform(ctx, "link", &[int(LINKED_TO.load(Ordering::SeqCst))]); wait_forever(ctx); } UNIT } /// Whether [`links_when_told_and_waits`] may link. static LINK_NOW: AtomicBool = AtomicBool::new(false); /// As [`links_and_waits`], once `LINK_NOW` is set. unsafe extern "C" fn links_when_told_and_waits(ctx: *mut Ctx) -> Value { // SAFETY: an actor's entry. unsafe { yield_until(ctx, "the go to link", |_| LINK_NOW.load(Ordering::SeqCst)); links_and_waits(ctx) } } /// Spawn an actor running `entry` and monitor it: its `Down` subject. /// /// # Safety /// `ctx` must be the running actor's context. unsafe fn spawn_watched(ctx: *mut Ctx, entry: super::EntryFn) -> (i64, Value) { // SAFETY: forwarded caller guarantee. unsafe { let child = spawn(ctx, entry); (child, perform(ctx, "monitor", &[int(child)])) } } /// Exit signals from a remote pid: through links (trapped or not), and /// `stop` and `kill`. unsafe extern "C" fn takes_remote_signals(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_fake(); let me = this(ctx).0.pid; let other = pid(3, 42); LINKED_TO.store(other, Ordering::SeqCst); perform(ctx, "trap_exits", &[int(1)]); let exits = perform(ctx, "exits", &[]); perform(ctx, "link", &[int(other)]); let (child, child_down) = spawn_watched(ctx, links_and_waits); yield_until(ctx, "the child to link", |_| { calls().contains(&Call::Link(child, other)) }); let (victim, victim_down) = spawn_watched(ctx, waits_forever); from_outside(ctx, move |sched| { let boom = Signal::Linked(crashed("boom")); inbound::signal(sched, other, me, &boom); inbound::signal(sched, other, child, &boom); // The link is gone: a second exit through it changes nothing. inbound::signal(sched, other, me, &boom); inbound::signal(sched, other, me, &Signal::Stop); inbound::signal(sched, other, victim, &Signal::Kill); }); let trapped = receive(ctx, exits, -1).expect("an exit signal"); assert_eq!(signal_of(ctx, trapped), (other, crashed("boom"))); let stopped = receive(ctx, exits, -1).expect("an exit signal"); assert_eq!(signal_of(ctx, stopped), (other, Exit::Shutdown)); assert_eq!(receive(ctx, exits, 0), None, "one exit through the link"); let down = receive(ctx, child_down, -1).expect("the child's Down"); assert_eq!(signal_of(ctx, down), (child, crashed("boom"))); // The child is unlisted at its exit, although the remote exit had // already taken its only tie to the node. assert_eq!(dist().tied_to(3), [me], "the child unlisted"); let down = receive(ctx, victim_down, -1).expect("the victim's Down"); assert_eq!(signal_of(ctx, down), (victim, Exit::Killed)); for subject in [exits, child_down, victim_down] { drop_value(ctx, subject); } uninstall(); } UNIT } #[test] fn remote_exit_signals_reach_local_ties() { for threads in THREADS { assert_eq!( run_root(threads, takes_remote_signals), Exit::Normal, "{threads} threads" ); } } static TRAPPER_LINKS: Mutex> = Mutex::new(Vec::new()); static TRAPPED: Mutex> = Mutex::new(None); /// Traps exits, links the pids in `TRAPPER_LINKS`, and records the first /// exit signal it gets. unsafe extern "C" fn traps_one_exit(ctx: *mut Ctx) -> Value { // SAFETY: an actor's entry. unsafe { perform(ctx, "trap_exits", &[int(1)]); let exits = perform(ctx, "exits", &[]); for other in TRAPPER_LINKS.lock().expect("links").clone() { perform(ctx, "link", &[int(other)]); } let signal = receive(ctx, exits, -1).expect("an exit signal"); *TRAPPED.lock().expect("trapped") = Some(signal_of(ctx, signal)); drop_value(ctx, exits); } UNIT } /// Node 5 is lost: its links and monitors end with `noconnection`; node /// 6's stay. unsafe extern "C" fn loses_a_node(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_fake(); let (lost, kept) = (5, 6); let (linked, watched, elsewhere) = (pid(lost, 1), pid(lost, 2), pid(kept, 1)); LINKED_TO.store(linked, Ordering::SeqCst); *TRAPPER_LINKS.lock().expect("links") = vec![linked, elsewhere]; *TRAPPED.lock().expect("trapped") = None; let (plain, plain_down) = spawn_watched(ctx, links_and_waits); let trapper = spawn(ctx, traps_one_exit); let watched_down = perform(ctx, "monitor", &[int(watched)]); let elsewhere_down = perform(ctx, "monitor", &[int(elsewhere)]); yield_until(ctx, "the children to link", |_| { let calls = calls(); calls.contains(&Call::Link(plain, linked)) && calls.contains(&Call::Link(trapper, elsewhere)) }); let me = this(ctx).0.pid; assert_eq!(dist().tied_to(lost), [me, plain, trapper]); let watched_tag = tag_of(watched_down); let elsewhere_tag = tag_of(elsewhere_down); from_outside(ctx, move |sched| inbound::node_down(sched, &dist(), lost)); let noconnection = crashed("noconnection"); let down = receive(ctx, plain_down, -1).expect("the plain child's Down"); assert_eq!(signal_of(ctx, down), (plain, noconnection.clone())); let down = receive(ctx, watched_down, -1).expect("the remote Down"); assert_eq!(signal_of(ctx, down), (watched, noconnection.clone())); yield_until(ctx, "the trapper to finish", |s| s.actors.all().len() == 1); assert_eq!( *TRAPPED.lock().expect("trapped"), Some((linked, noconnection.clone())) ); // The trapper's exit reached its link on node 6 only. let told = Call::Signal(trapper, elsewhere, Signal::Linked(Exit::Normal)); assert!(calls().contains(&told)); assert!( !calls() .iter() .any(|c| matches!(c, Call::Signal(_, to, _) if *to == linked)) ); assert!(dist().tied_to(lost).is_empty()); assert_eq!(dist().tied_to(kept), [me]); // Node 6 is untouched; a `Down` the fan-out already sent comes once. assert_eq!(receive(ctx, elsewhere_down, 0), None); from_outside(ctx, move |sched| { inbound::down(sched, me, watched_tag, watched, &Exit::Normal); inbound::down(sched, me, elsewhere_tag, elsewhere, &Exit::Normal); }); assert_eq!(receive(ctx, watched_down, 0), None, "one Down"); let down = receive(ctx, elsewhere_down, -1).expect("node 6's Down"); assert_eq!(signal_of(ctx, down), (elsewhere, Exit::Normal)); for subject in [plain_down, watched_down, elsewhere_down] { drop_value(ctx, subject); } uninstall(); } UNIT } #[test] fn a_lost_node_ends_every_tie_to_it_with_noconnection() { for threads in THREADS { assert_eq!( run_root(threads, loses_a_node), Exit::Normal, "{threads} threads" ); } } // ---- ties a remote node makes ------------------------------------------------------ /// Remote pids link to and monitor local actors: the ties are kept and /// listed, the actor's exit goes out through the transport, and a pid that /// is gone answers `noproc`. unsafe extern "C" fn takes_remote_ties(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_fake(); let (linker, watcher) = (pid(3, 1), pid(3, 2)); let (child, child_down) = spawn_watched(ctx, waits_forever); from_outside(ctx, move |sched| { inbound::link(sched, &dist(), linker, child); inbound::monitor(sched, &dist(), watcher, 9, child); // Twice: one link, two monitors (as locally). inbound::link(sched, &dist(), linker, child); inbound::monitor(sched, &dist(), watcher, 10, child); }); assert_eq!(dist().tied_to(3), [child]); assert!(calls().is_empty(), "nothing sent yet"); perform(ctx, "kill", &[int(child)]); let down = receive(ctx, child_down, -1).expect("the child's Down"); assert_eq!(signal_of(ctx, down), (child, Exit::Killed)); assert_eq!( calls(), [ Call::Down(child, watcher, 9, Exit::Killed), Call::Down(child, watcher, 10, Exit::Killed), Call::Signal(child, linker, Signal::Linked(Exit::Killed)), ] ); assert!(dist().tied_to(3).is_empty(), "unlisted at its exit"); // Now gone, as a pid that never was: `noproc`, and no listing. let never = child + 1_000_000; CALLS.lock().expect("calls").clear(); from_outside(ctx, move |sched| { inbound::link(sched, &dist(), linker, child); inbound::monitor(sched, &dist(), watcher, 11, never); }); let noproc = crashed("noproc"); assert_eq!( calls(), [ Call::Signal(child, linker, Signal::Linked(noproc.clone())), Call::Down(never, watcher, 11, noproc), ] ); assert!(dist().tied_to(3).is_empty()); drop_value(ctx, child_down); uninstall(); } UNIT } #[test] fn remote_pids_link_to_and_monitor_local_actors() { for threads in THREADS { assert_eq!( run_root(threads, takes_remote_ties), Exit::Normal, "{threads} threads" ); } } /// A lost node ends the ties its pids made, once: a trapping actor gets /// one exit signal, whether the node's loss or the peer's own exit comes /// first, and the monitors those pids held are forgotten. unsafe extern "C" fn loses_a_node_tied_to_it(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_fake(); let (me, sched) = (this(ctx).0.pid, this(ctx).1); let (lost, kept) = (5, 6); let (linker, watcher, elsewhere) = (pid(lost, 1), pid(lost, 2), pid(kept, 1)); perform(ctx, "trap_exits", &[int(1)]); let exits = perform(ctx, "exits", &[]); from_outside(ctx, move |sched| { inbound::link(sched, &dist(), linker, me); inbound::monitor(sched, &dist(), watcher, 9, me); inbound::monitor(sched, &dist(), elsewhere, 9, me); }); assert_eq!(dist().tied_to(lost), [me]); from_outside(ctx, move |sched| { inbound::node_down(sched, &dist(), lost); // The peer's own exit, late: the link is gone. let late = Signal::Linked(crashed("boom")); inbound::signal(sched, linker, me, &late); }); let trapped = receive(ctx, exits, -1).expect("an exit signal"); assert_eq!(signal_of(ctx, trapped), (linker, crashed("noconnection"))); assert_eq!(receive(ctx, exits, 0), None, "one exit signal"); assert!(dist().tied_to(lost).is_empty()); assert_eq!(dist().tied_to(kept), [me]); // Only node 6's watcher is left to tell, when this actor exits. let monitors = sched.with_alive(me, |p| p.ties().monitors.clone()); assert_eq!(monitors, Some(vec![(elsewhere, 9)])); assert!(calls().is_empty(), "nothing sent to a lost node"); drop_value(ctx, exits); uninstall(); } UNIT } #[test] fn a_lost_node_ends_the_ties_its_pids_made_once() { for threads in THREADS { assert_eq!( run_root(threads, loses_a_node_tied_to_it), Exit::Normal, "{threads} threads" ); } } /// A remote link racing the local actor's exit: either the link is made /// and the exit goes out through it, or the actor was gone and `noproc` /// does; never both, never neither, and no actor stays listed. unsafe extern "C" fn races_remote_links_with_exits(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry; it joins each thread it starts. unsafe { start_fake(); let linker = pid(7, 1); for _ in 0..200 { let child = spawn(ctx, waits_forever); let transport = outside(ctx, move |sched| { inbound::link(sched, &dist(), linker, child) }); perform(ctx, "kill", &[int(child)]); transport.join().expect("the transport's thread"); yield_until(ctx, "the child to finish", |s| s.actors.all().len() == 1); let told: Vec = calls() .into_iter() .filter(|c| matches!(c, Call::Signal(from, ..) if *from == child)) .collect(); let killed = Call::Signal(child, linker, Signal::Linked(Exit::Killed)); let noproc = Call::Signal(child, linker, Signal::Linked(crashed("noproc"))); assert!(told == [killed] || told == [noproc], "{told:?}"); assert!(dist().tied_to(7).is_empty(), "listed after its exit"); } uninstall(); } UNIT } #[test] fn a_remote_link_racing_an_exit_is_answered_once() { for threads in THREADS { assert_eq!( run_root(threads, races_remote_links_with_exits), Exit::Normal, "{threads} threads" ); } } /// Links the pid in `LINKED_TO`, and returns (killed meanwhile). unsafe extern "C" fn links_once(ctx: *mut Ctx) -> Value { // SAFETY: an actor's entry. unsafe { perform(ctx, "link", &[int(LINKED_TO.load(Ordering::SeqCst))]); } UNIT } /// An actor killed while it links to a remote pid: its exit goes out after /// the link frame, whose queuing the kill waits for, so the other side has /// the link the exit ends. unsafe extern "C" fn killed_while_linking(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_fake(); let other = pid(5, 9); LINKED_TO.store(other, Ordering::SeqCst); KILL_WHILE_LINKING.store(true, Ordering::SeqCst); let (child, down) = spawn_watched(ctx, links_once); let message = receive(ctx, down, -1).expect("the child's Down"); assert_eq!(signal_of(ctx, message), (child, Exit::Killed)); assert_eq!( calls(), [ Call::Link(child, other), Call::Signal(child, other, Signal::Linked(Exit::Killed)), ] ); assert!(dist().tied_to(5).is_empty(), "untied at its exit"); drop_value(ctx, down); uninstall(); } UNIT } #[test] fn a_link_frame_goes_out_before_its_actors_exit() { for threads in THREADS { assert_eq!( run_root(threads, killed_while_linking), Exit::Normal, "{threads} threads" ); } } /// A node lost once the link frame is queued, under the actor's lock: its /// fan-out must find the actor and end the link with `noconnection`, as /// when the loss comes before the frame (`send` fails). Listed after the /// lock (as #415 first had it), the actor escaped the fan-out, listed /// itself under the lost node, and kept its link to a pid of it. unsafe extern "C" fn loses_the_node_while_linking(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_fake(); let other = pid(5, 9); LINKED_TO.store(other, Ordering::SeqCst); LOSE_NODE_WHILE_LINKING.store(true, Ordering::SeqCst); LINK_NOW.store(false, Ordering::SeqCst); let (child, down) = spawn_watched(ctx, links_when_told_and_waits); // Monitored first: a child that died before would be `noproc`. LINK_NOW.store(true, Ordering::SeqCst); yield_until(ctx, "the child to link", |_| { calls().contains(&Call::Link(child, other)) }); let message = receive(ctx, down, 1000); let tied = dist().tied_to(5); let outcome = message.map(|m| signal_of(ctx, m)); if outcome.is_none() { // Not to leave it waiting forever. from_outside(ctx, move |sched| exit_actor(sched, child, Exit::Killed)); let _ = receive(ctx, down, -1); } drop_value(ctx, down); uninstall(); let ended = outcome == Some((child, crashed("noconnection"))); *LOST_WHILE_LINKING.lock().expect("outcome") = Some((ended, child, outcome, tied)); } UNIT } /// What [`loses_the_node_while_linking`] saw: whether the child died of /// `noconnection`, its `Down` if any, and who was listed under the lost /// node afterwards. #[allow(clippy::type_complexity)] static LOST_WHILE_LINKING: Mutex, Vec)>> = Mutex::new(None); #[test] fn a_node_lost_while_linking_still_ends_the_link() { for threads in THREADS { assert_eq!( run_root(threads, loses_the_node_while_linking), Exit::Normal, "{threads} threads" ); let seen = LOST_WHILE_LINKING.lock().expect("outcome").take(); let (ended, child, down, tied) = seen.expect("the root ran"); assert!( ended, "{threads} threads: child {child} outlived its link's lost node (its Down: \ {down:?}); listed under the lost node afterwards: {tied:?}" ); } } /// As [`loses_the_node_while_linking`], for a new actor linked to the /// remote asker of its spawn (`spawn_link_on`, [`outbound::link_spawned`]): /// the asker's node lost once the link frame is queued. unsafe extern "C" fn loses_the_askers_node_while_linking(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_fake(); let (_, sched) = this(ctx); let asker = pid(5, 9); let (child, down) = spawn_watched(ctx, waits_forever); let mut loser = None; let sent = outbound::link_spawned(sched, &dist(), child, asker, || { loser = Some(lose_node_meanwhile(sched, child, asker)); true }); loser.expect("the frame queued").join().expect("the loss"); assert_eq!(sent, Some(true), "the child was alive"); let message = receive(ctx, down, 1000); let tied = dist().tied_to(5); let outcome = message.map(|m| signal_of(ctx, m)); if outcome.is_none() { from_outside(ctx, move |sched| exit_actor(sched, child, Exit::Killed)); let _ = receive(ctx, down, -1); } drop_value(ctx, down); uninstall(); let ended = outcome == Some((child, crashed("noconnection"))); *LOST_WHILE_SPAWNING.lock().expect("outcome") = Some((ended, child, outcome, tied)); } UNIT } /// What [`loses_the_askers_node_while_linking`] saw, as /// [`LOST_WHILE_LINKING`]. #[allow(clippy::type_complexity)] static LOST_WHILE_SPAWNING: Mutex, Vec)>> = Mutex::new(None); #[test] fn an_askers_node_lost_while_its_spawn_links_still_ends_the_link() { for threads in THREADS { assert_eq!( run_root(threads, loses_the_askers_node_while_linking), Exit::Normal, "{threads} threads" ); let seen = LOST_WHILE_SPAWNING.lock().expect("outcome").take(); let (ended, child, down, tied) = seen.expect("the root ran"); assert!( ended, "{threads} threads: child {child} outlived its asker's lost node (its Down: \ {down:?}); listed under the lost node afterwards: {tied:?}" ); } } // ---- spawn_monitor_on -------------------------------------------------------------- /// Return at once. unsafe extern "C" fn ends(_ctx: *mut Ctx) -> Value { UNIT } /// The node of a new actor monitored by a remote asker /// ([`outbound::monitor_spawned`]): its answer is queued under the actor's /// lock, so a kill from another thread meanwhile sends its `Down` after /// the answer, which the asker's node needs first. An answer that cannot /// be queued forgets the monitor; an actor already gone sends nothing. unsafe extern "C" fn killed_while_answering(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_fake(); let (me, sched) = this(ctx); let me = me.pid; let asker = pid(5, 9); let (child, down) = spawn_watched(ctx, waits_forever); let mut killer = None; let made = outbound::monitor_spawned(sched, &dist(), child, asker, 77, || { killer = Some(kill_meanwhile(sched, child)); called(Call::Answered(child)); true }); killer.expect("the answer queued").join().expect("the kill"); assert_eq!(made, Some(true)); let message = receive(ctx, down, -1).expect("the child's Down"); assert_eq!(signal_of(ctx, message), (child, Exit::Killed)); assert_eq!( calls(), [ Call::Answered(child), Call::Down(child, asker, 77, Exit::Killed), ] ); assert!(dist().tied_to(5).is_empty(), "untied at its exit"); // Gone: nothing is made or sent. let gone = outbound::monitor_spawned(sched, &dist(), child, asker, 78, || { called(Call::Answered(child)); true }); assert_eq!(gone, None); assert_eq!(calls().len(), 2); // The asker's node is not up: the monitor is forgotten at once. let (other, other_down) = spawn_watched(ctx, waits_forever); let made = outbound::monitor_spawned(sched, &dist(), other, asker, 79, || false); assert_eq!(made, Some(false)); let monitors = sched.with_alive(other, |p| p.ties().monitors.clone()); assert_eq!(monitors, Some(vec![(me, tag_of(other_down))])); perform(ctx, "kill", &[int(other)]); let message = receive(ctx, other_down, -1).expect("its Down"); assert_eq!(signal_of(ctx, message), (other, Exit::Killed)); assert_eq!(calls().len(), 2, "no Down for the forgotten monitor"); drop_value(ctx, down); drop_value(ctx, other_down); uninstall(); } UNIT } #[test] fn a_monitored_spawns_answer_goes_before_its_down() { for threads in THREADS { assert_eq!( run_root(threads, killed_while_answering), Exit::Normal, "{threads} threads" ); } } /// The asker's node, as a monitored spawn's answer arrives /// ([`inbound::watch_spawned`]): the asker's half of the monitor and the /// answer are made in one step, on the transport's thread, so the `Down` /// that follows on the stream is delivered (once), and a lost node ends /// the monitor with `noconnection`. An asker that is gone gets nothing, /// and its answer is not made. unsafe extern "C" fn watches_what_it_spawned(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_fake(); let me = this(ctx).0.pid; let answers = perform(ctx, "subject", &[]); let downs = perform(ctx, "subject", &[]); let lost = perform(ctx, "subject", &[]); let (reply_tag, down_tag, lost_tag) = (tag_of(answers), tag_of(downs), tag_of(lost)); let (watched, other) = (pid(4, 12), pid(4, 13)); from_outside(ctx, move |sched| { let watch = |pid, tag| { inbound::watch_spawned(sched, &dist(), me, pid, tag, reply_tag, || { int(remote_serial(pid)) }) }; assert!(watch(watched, down_tag)); // The stream's next frame: the new actor's `Down`, twice. inbound::down(sched, me, down_tag, watched, &Exit::Killed); inbound::down(sched, me, down_tag, watched, &Exit::Killed); assert!(watch(other, lost_tag)); }); assert_eq!(dist().tied_to(4), [me]); for serial in [12, 13] { let answer = receive(ctx, answers, 0).expect("the answer"); assert_eq!(int_get(answer), serial); } let message = receive(ctx, downs, 0).expect("the Down"); assert_eq!(signal_of(ctx, message), (watched, Exit::Killed)); assert!(receive(ctx, downs, 0).is_none(), "one Down"); from_outside(ctx, |sched| inbound::node_down(sched, &dist(), 4)); let message = receive(ctx, lost, 0).expect("the lost node's Down"); assert_eq!(signal_of(ctx, message), (other, crashed("noconnection"))); // An asker that is gone. let (gone, gone_down) = spawn_watched(ctx, ends); let message = receive(ctx, gone_down, -1).expect("its Down"); assert_eq!(signal_of(ctx, message), (gone, Exit::Normal)); from_outside(ctx, move |sched| { let watched = inbound::watch_spawned(sched, &dist(), gone, other, 1, 2, || { panic!("an answer made for an asker that is gone") }); assert!(!watched); }); assert!(dist().tied_to(4).is_empty()); for subject in [answers, downs, lost, gone_down] { drop_value(ctx, subject); } uninstall(); } UNIT } /// A remote pid's serial. fn remote_serial(pid: i64) -> i64 { crate::dist::parts(pid).1 } #[test] fn a_monitored_spawns_watch_comes_with_its_answer() { for threads in THREADS { assert_eq!( run_root(threads, watches_what_it_spawned), Exit::Normal, "{threads} threads" ); } } // ---- demonitor --------------------------------------------------------------------- /// `demonitor(pid, down)` (owned `down`). /// /// # Safety /// `ctx` must be the running actor's context. unsafe fn demonitor(ctx: *mut Ctx, pid: i64, down: Value) { // SAFETY: forwarded caller guarantee. unsafe { assert_eq!(perform(ctx, "demonitor", &[int(pid), down]), UNIT); assert_eq!((*ctx).yielding, YIELD_NONE, "the demonitor returned"); } } /// A remote monitor's own half goes first, then the frame: a `Down` that /// arrives after is not delivered, and a monitor ends once. unsafe extern "C" fn demonitors_a_remote_pid(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_fake(); let me = this(ctx).0.pid; let (watched, never) = (pid(3, 42), pid(3, 43)); let down = perform(ctx, "monitor", &[int(watched)]); let kept = perform(ctx, "monitor", &[int(watched)]); let (tag, kept_tag) = (tag_of(down), tag_of(kept)); demonitor(ctx, watched, dup_value(down)); // Gone already, or never there: nothing to tell the node. demonitor(ctx, watched, dup_value(down)); demonitor(ctx, never, dup_value(kept)); assert_eq!( calls(), [ Call::Monitor(me, tag, watched), Call::Monitor(me, kept_tag, watched), Call::Demonitor(me, tag, watched), ] ); from_outside(ctx, move |sched| { inbound::down(sched, me, tag, watched, &Exit::Normal); inbound::down(sched, me, kept_tag, watched, &Exit::Normal); }); assert_eq!(receive(ctx, down, 0), None, "no Down after demonitor"); let message = receive(ctx, kept, 0).expect("the other monitor's Down"); assert_eq!(signal_of(ctx, message), (watched, Exit::Normal)); // Still listed under the node until it exits. assert_eq!(dist().tied_to(3), [me]); drop_value(ctx, down); drop_value(ctx, kept); uninstall(); } UNIT } #[test] fn a_remote_demonitor_stops_its_down() { for threads in THREADS { assert_eq!( run_root(threads, demonitors_a_remote_pid), Exit::Normal, "{threads} threads" ); } } /// A remote watcher's demonitor removes its monitor from the local actor: /// the actor's exit sends no `Down` for it. unsafe extern "C" fn forgets_a_remote_watcher(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_fake(); let sched = this(ctx).1; let watcher = pid(3, 2); let (child, child_down) = spawn_watched(ctx, waits_forever); from_outside(ctx, move |sched| { inbound::monitor(sched, &dist(), watcher, 9, child); inbound::monitor(sched, &dist(), watcher, 10, child); inbound::demonitor(sched, watcher, 9, child); // Another tag, another watcher: nothing to forget. inbound::demonitor(sched, watcher, 11, child); inbound::demonitor(sched, pid(3, 3), 10, child); }); let monitors = sched.with_alive(child, |p| p.ties().monitors.clone()); let me = this(ctx).0.pid; assert_eq!( monitors, Some(vec![(me, tag_of(child_down)), (watcher, 10)]) ); perform(ctx, "kill", &[int(child)]); let down = receive(ctx, child_down, -1).expect("the child's Down"); assert_eq!(signal_of(ctx, down), (child, Exit::Killed)); assert_eq!(calls(), [Call::Down(child, watcher, 10, Exit::Killed)]); // Gone: a late demonitor finds nothing, and answers nothing. from_outside(ctx, move |sched| { inbound::demonitor(sched, watcher, 10, child) }); assert_eq!(calls().len(), 1); drop_value(ctx, child_down); uninstall(); } UNIT } #[test] fn a_remote_watchers_demonitor_removes_its_monitor() { for threads in THREADS { assert_eq!( run_root(threads, forgets_a_remote_watcher), Exit::Normal, "{threads} threads" ); } } /// `demonitor` racing the `Down` it stops, from a local actor's exit and /// from a remote one: once it returns, a `Down` is in the mailbox already /// or never comes. A remote one is sent, or the demonitor frame is, never /// both. unsafe extern "C" fn races_demonitors_with_downs(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry; it joins each thread it starts. unsafe { start_fake(); let me = this(ctx).0.pid; for i in 0..200 { // Local: the child's exit, on another thread. let (child, down) = spawn_watched(ctx, waits_forever); let kept = perform(ctx, "monitor", &[int(child)]); let killer = outside(ctx, move |sched| exit_actor(sched, child, Exit::Killed)); demonitor(ctx, child, dup_value(down)); let early = receive(ctx, down, 0); killer.join().expect("the killer's thread"); // Pushed under the same lock as the first monitor's `Down`. let message = receive(ctx, kept, -1).expect("the other monitor's Down"); drop_value(ctx, message); assert_eq!(receive(ctx, down, 0), None, "a local Down after demonitor"); if let Some(message) = early { drop_value(ctx, message); } for subject in [down, kept] { drop_value(ctx, subject); } // Remote: the watched pid's `Down`, from the transport's thread. let watched = pid(3, i); let down = perform(ctx, "monitor", &[int(watched)]); let tag = tag_of(down); let transport = outside(ctx, move |sched| { inbound::down(sched, me, tag, watched, &Exit::Normal) }); demonitor(ctx, watched, dup_value(down)); let early = receive(ctx, down, 0); transport.join().expect("the transport's thread"); assert_eq!(receive(ctx, down, 0), None, "a remote Down after demonitor"); let sent = calls().contains(&Call::Demonitor(me, tag, watched)); assert_ne!(sent, early.is_some(), "the Down or the demonitor frame"); if let Some(message) = early { drop_value(ctx, message); } drop_value(ctx, down); } uninstall(); } UNIT } #[test] fn a_demonitor_racing_a_down_leaves_none_to_come() { for threads in THREADS { assert_eq!( run_root(threads, races_demonitors_with_downs), Exit::Normal, "{threads} threads" ); } } /// `demonitor` on another actor's subject panics, as `receive` does. unsafe extern "C" fn demonitors_on_another_subject(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { let down = crate::values::cell(ctx, 0, &[int(this(ctx).0.pid + 1), int(7)]); perform(ctx, "demonitor", &[int(0), down]); assert_eq!((*ctx).yielding, YIELD_PANIC); } UNIT } #[test] fn demonitor_on_another_actors_subject_panics() { for threads in THREADS { assert_eq!( run_root(threads, demonitors_on_another_subject), crashed("demonitor on a subject owned by another actor"), "{threads} threads" ); } } // ---- unlink ------------------------------------------------------------------------ /// `unlink(pid)`. /// /// # Safety /// `ctx` must be the running actor's context. unsafe fn unlink(ctx: *mut Ctx, pid: i64) { // SAFETY: forwarded caller guarantee. unsafe { assert_eq!(perform(ctx, "unlink", &[int(pid)]), UNIT); assert_eq!((*ctx).yielding, YIELD_NONE, "the unlink returned"); } } /// Whether `pid` has its half of a link to `other`, and its unlinks /// waiting for their acknowledgement. fn link_state(sched: &Shared, pid: i64, other: i64) -> (bool, Vec<(i64, u64)>) { let state = sched.with_proc(pid, |p| { let ties = p.ties(); (ties.links.contains(other), ties.unlinks()) }); state.expect("an actor") } /// A remote unlink: the actor's half waits for the acknowledgement of its /// id, the frame sent once. An exit or a link from the pid meanwhile is /// ignored, and so is the acknowledgement of another id; a link from the /// actor overrides the unlink. Without the node up, or with the node /// lost, nothing is left waiting, and no `noconnection` comes through it. unsafe extern "C" fn unlinks_a_remote_pid(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_fake(); let (me, sched) = (this(ctx).0.pid, this(ctx).1); let (other, far) = (pid(3, 42), pid(5, 1)); perform(ctx, "trap_exits", &[int(1)]); let exits = perform(ctx, "exits", &[]); perform(ctx, "link", &[int(other)]); unlink(ctx, other); // Unlinking already: nothing more to send (id 2 is not sent). unlink(ctx, other); assert_eq!(link_state(sched, me, other), (false, vec![(other, 1)])); from_outside(ctx, move |sched| { inbound::signal(sched, other, me, &Signal::Linked(crashed("boom"))); inbound::link(sched, &dist(), other, me); inbound::unlink_acked(sched, other, me, 2); }); assert_eq!(receive(ctx, exits, 0), None, "an exit through the unlink"); assert_eq!(link_state(sched, me, other), (false, vec![(other, 1)])); from_outside(ctx, move |sched| inbound::unlink_acked(sched, other, me, 1)); assert_eq!(link_state(sched, me, other), (false, vec![])); // Linked again, by the remote pid: an exit through it counts. from_outside(ctx, move |sched| { inbound::link(sched, &dist(), other, me); inbound::signal(sched, other, me, &Signal::Linked(crashed("boom"))); }); let trapped = receive(ctx, exits, 0).expect("an exit signal"); assert_eq!(signal_of(ctx, trapped), (other, crashed("boom"))); // Linked again by this actor before the acknowledgement. perform(ctx, "link", &[int(other)]); unlink(ctx, other); perform(ctx, "link", &[int(other)]); from_outside(ctx, move |sched| inbound::unlink_acked(sched, other, me, 3)); assert_eq!(link_state(sched, me, other), (true, vec![])); UNLINK_NOT_UP.store(true, Ordering::SeqCst); unlink(ctx, other); assert_eq!(link_state(sched, me, other), (false, vec![]), "not up"); perform(ctx, "link", &[int(far)]); unlink(ctx, far); assert_eq!(link_state(sched, me, far), (false, vec![(far, 5)])); from_outside(ctx, move |sched| inbound::node_down(sched, &dist(), 5)); assert_eq!(receive(ctx, exits, 0), None, "noconnection through it"); assert_eq!(link_state(sched, me, far), (false, vec![]), "lost"); assert_eq!( calls(), [ Call::Link(me, other), Call::Unlink(me, other, 1), Call::Link(me, other), Call::Unlink(me, other, 3), Call::Link(me, other), Call::Link(me, far), Call::Unlink(me, far, 5), ] ); assert_eq!(dist().tied_to(3), [me], "listed until it exits"); drop_value(ctx, exits); uninstall(); } UNIT } #[test] fn a_remote_unlink_waits_for_its_acknowledgement() { for threads in THREADS { assert_eq!( run_root(threads, unlinks_a_remote_pid), Exit::Normal, "{threads} threads" ); } } /// A remote pid unlinks a local actor: the actor's half goes, so its exit /// sends nothing, and the unlink is acknowledged, for an actor that is /// gone too. An actor unlinking that pid itself keeps its own unlink /// waiting, and ignores a link the pid sent before it got that unlink. unsafe extern "C" fn takes_remote_unlinks(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_fake(); let (me, sched) = (this(ctx).0.pid, this(ctx).1); let linker = pid(3, 1); let ack = move |local: i64, id: u64| move || called(Call::UnlinkAck(local, linker, id)); let (child, child_down) = spawn_watched(ctx, waits_forever); from_outside(ctx, move |sched| { inbound::link(sched, &dist(), linker, child); inbound::unlink(sched, linker, child, ack(child, 5)); }); perform(ctx, "kill", &[int(child)]); let down = receive(ctx, child_down, -1).expect("the child's Down"); assert_eq!(signal_of(ctx, down), (child, Exit::Killed)); from_outside(ctx, move |sched| { inbound::unlink(sched, linker, child, ack(child, 6)) }); let acks = [ Call::UnlinkAck(child, linker, 5), Call::UnlinkAck(child, linker, 6), ]; assert_eq!(calls(), acks, "no exit sent"); perform(ctx, "trap_exits", &[int(1)]); let exits = perform(ctx, "exits", &[]); from_outside(ctx, move |sched| inbound::link(sched, &dist(), linker, me)); unlink(ctx, linker); from_outside(ctx, move |sched| { inbound::unlink(sched, linker, me, ack(me, 7)); inbound::link(sched, &dist(), linker, me); inbound::signal(sched, linker, me, &Signal::Linked(crashed("boom"))); }); assert_eq!(receive(ctx, exits, 0), None); assert_eq!(link_state(sched, me, linker), (false, vec![(linker, 1)])); from_outside(ctx, move |sched| { inbound::unlink_acked(sched, linker, me, 1) }); assert_eq!(link_state(sched, me, linker), (false, vec![])); assert_eq!( calls()[2..], [Call::Unlink(me, linker, 1), Call::UnlinkAck(me, linker, 7)] ); drop_value(ctx, exits); drop_value(ctx, child_down); uninstall(); } UNIT } #[test] fn a_remote_pids_unlink_is_acknowledged() { for threads in THREADS { assert_eq!( run_root(threads, takes_remote_unlinks), Exit::Normal, "{threads} threads" ); } } /// `unlink` racing an exit through the link, from a local actor's exit /// and from a remote one: once it returns, an `ExitSignal` is in the /// mailbox already, or never comes. A remote one is delivered, or the /// unlink frame is sent, never both. unsafe extern "C" fn races_unlinks_with_exits(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry; it joins each thread it starts. unsafe { start_fake(); let me = this(ctx).0.pid; perform(ctx, "trap_exits", &[int(1)]); let exits = perform(ctx, "exits", &[]); for i in 0..200 { // Local: the child's exit, on another thread, signals the // root before it returns. let child = spawn(ctx, waits_forever); perform(ctx, "link", &[int(child)]); let killer = outside(ctx, move |sched| exit_actor(sched, child, Exit::Killed)); unlink(ctx, child); let early = receive(ctx, exits, 0); killer.join().expect("the killer's thread"); assert_eq!(receive(ctx, exits, 0), None, "a local exit after unlink"); if let Some(message) = early { assert_eq!(signal_of(ctx, message), (child, Exit::Killed)); } yield_until(ctx, "the child to finish", |s| s.actors.all().len() == 1); // Remote: the linked pid's exit, from the transport's thread. let other = pid(3, i); perform(ctx, "link", &[int(other)]); let boom = Signal::Linked(crashed("boom")); let transport = outside(ctx, move |sched| inbound::signal(sched, other, me, &boom)); unlink(ctx, other); let early = receive(ctx, exits, 0); transport.join().expect("the transport's thread"); assert_eq!(receive(ctx, exits, 0), None, "a remote exit after unlink"); let sent = calls() .iter() .any(|c| matches!(c, Call::Unlink(_, to, _) if *to == other)); assert_ne!(sent, early.is_some(), "the exit or the unlink frame"); if let Some(message) = early { assert_eq!(signal_of(ctx, message), (other, crashed("boom"))); } } drop_value(ctx, exits); uninstall(); } UNIT } #[test] fn an_unlink_racing_an_exit_leaves_none_to_come() { for threads in THREADS { assert_eq!( run_root(threads, races_unlinks_with_exits), Exit::Normal, "{threads} threads" ); } } // ---- third security review of #404 (dist/secreview3) ----------------------------- /// The ids of `pid`'s unlinks of `other` waiting for their acknowledgement. fn waiting_ids(sched: &Shared, pid: i64, other: i64) -> Vec { let (_, unlinking) = link_state(sched, pid, other); unlinking .into_iter() .filter(|(p, _)| *p == other) .map(|(_, id)| id) .collect() } /// Pinned (`dist/secreview3`): only the pid an unlink names acknowledges /// it, and only with its id; an unlink frame removes only the half of the /// pid that sent it. `node.rs` makes a frame's remote pid from its sender's /// node (`State::tie`), so a peer names only its own pids: it can neither /// end another node's unlink early nor remove a half linking another /// node's pid, nor another serial's. unsafe extern "C" fn acknowledges_only_its_own_unlinks(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_fake(); let (me, sched) = (this(ctx).0.pid, this(ctx).1); // The same serial on nodes 3 and 5, and another serial of node 3. let (x, y, z) = (pid(3, 42), pid(5, 42), pid(3, 43)); for other in [x, y, z] { perform(ctx, "link", &[int(other)]); unlink(ctx, other); } let [ix, iy, iz] = [x, y, z].map(|other| { let ids = waiting_ids(sched, me, other); assert_eq!(ids.len(), 1, "{other}: one unlink waiting"); ids[0] }); from_outside(ctx, move |sched| { // Another node's pid, another serial, another id. inbound::unlink_acked(sched, y, me, ix); inbound::unlink_acked(sched, z, me, ix); inbound::unlink_acked(sched, x, me, iy); inbound::unlink_acked(sched, x, me, iz); }); for (other, id) in [(x, ix), (y, iy), (z, iz)] { assert_eq!(waiting_ids(sched, me, other), [id], "{other}: waiting"); } from_outside(ctx, move |sched| inbound::unlink_acked(sched, x, me, ix)); assert!( waiting_ids(sched, me, x).is_empty(), "x acknowledged its own" ); assert_eq!(waiting_ids(sched, me, y), [iy]); // Linked to x again: unlink frames from y and z leave its half. perform(ctx, "link", &[int(x)]); from_outside(ctx, move |sched| { inbound::unlink(sched, y, me, || {}); inbound::unlink(sched, z, me, || {}); }); assert!(link_state(sched, me, x).0, "x's half kept"); from_outside(ctx, move |sched| inbound::unlink(sched, x, me, || {})); assert!(!link_state(sched, me, x).0, "x's own unlink removes it"); uninstall(); } UNIT } #[test] fn secreview3_an_unlink_is_acknowledged_only_by_its_pid() { for threads in THREADS { assert_eq!( run_root(threads, acknowledges_only_its_own_unlinks), Exit::Normal, "{threads} threads" ); } } /// SR3-2 (minor), confirmed. A peer whose hello sets flag bit 4 but that /// never answers op `17` keeps each unlink of one of its pids waiting /// (`Ties::unlinking`) until its node is lost: one entry per pid the actor /// unlinked, with no cap and no timeout (Erlang's protocol has neither). /// Meanwhile those pids' links are ignored, as an unlink in flight /// requires. Only an acknowledgement, a new link from the actor, its exit /// or the node's loss ends one, and the loss sends no exit through them. /// Bounded by the actor's own unlinks of links that existed: a peer adds /// none by itself. The entries are scanned by every op `10` and `18` to /// the actor and every link it makes (`otp/secreview3.rs` measures it). unsafe extern "C" fn keeps_unlinks_a_peer_never_answers(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_fake(); let (me, sched) = (this(ctx).0.pid, this(ctx).1); perform(ctx, "trap_exits", &[int(1)]); let exits = perform(ctx, "exits", &[]); let n = 1_000; for serial in 0..n { let other = pid(3, serial); perform(ctx, "link", &[int(other)]); unlink(ctx, other); } let waiting = |sched: &Shared| { sched .with_proc(me, |p| p.ties().unlinking.len()) .expect("the root") }; assert_eq!(waiting(sched), n as usize, "one per unlinked pid"); // A link from one of them meanwhile is ignored; a link from this // actor ends its unlink. from_outside(ctx, move |sched| { inbound::link(sched, &dist(), pid(3, 0), me) }); assert!(!link_state(sched, me, pid(3, 0)).0, "a link in flight"); perform(ctx, "link", &[int(pid(3, 1))]); assert_eq!(waiting(sched), n as usize - 1); // The node's loss forgets them, and ends the one link left. from_outside(ctx, |sched| inbound::node_down(sched, &dist(), 3)); assert_eq!(waiting(sched), 0, "forgotten with the node"); let message = receive(ctx, exits, 0).expect("the link's exit"); assert_eq!( signal_of(ctx, message), (pid(3, 1), crashed("noconnection")) ); assert_eq!(receive(ctx, exits, 0), None, "none through an unlink"); drop_value(ctx, exits); uninstall(); } UNIT } #[test] fn secreview3_unlinks_a_peer_never_answers_wait_until_its_loss() { for threads in THREADS { assert_eq!( run_root(threads, keeps_unlinks_a_peer_never_answers), Exit::Normal, "{threads} threads" ); } } /// Pinned (`dist/secreview3`): the relay makes the asker's half of a /// monitored spawn's monitor for the pid spawned and the down tag only /// (`inbound::watch_spawned`; `node.rs` takes the tag from the pending /// spawn, never from the answer). So a peer's `Down` naming the reply tag /// (a subject of `std/dist.Answer`s) or another of its pids is dropped: a /// `Down` reaches only the `Subject` the asker made. unsafe extern "C" fn delivers_downs_only_on_the_down_subject(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_fake(); let me = this(ctx).0.pid; let answers = perform(ctx, "subject", &[]); let downs = perform(ctx, "subject", &[]); let (reply_tag, down_tag) = (tag_of(answers), tag_of(downs)); let (spawned, other) = (pid(4, 12), pid(4, 13)); from_outside(ctx, move |sched| { let watched = inbound::watch_spawned(sched, &dist(), me, spawned, down_tag, reply_tag, || { int(12) }); assert!(watched); inbound::down(sched, me, reply_tag, spawned, &crashed("on the reply tag")); inbound::down(sched, me, down_tag, other, &crashed("another pid")); }); let answer = receive(ctx, answers, 0).expect("the answer"); assert_eq!(int_get(answer), 12); assert!( receive(ctx, answers, 0).is_none(), "a Down on the reply tag" ); assert!(receive(ctx, downs, 0).is_none(), "a Down of another pid"); from_outside(ctx, move |sched| { inbound::down(sched, me, down_tag, spawned, &Exit::Killed) }); let message = receive(ctx, downs, 0).expect("its Down"); assert_eq!(signal_of(ctx, message), (spawned, Exit::Killed)); drop_value(ctx, answers); drop_value(ctx, downs); uninstall(); } UNIT } #[test] fn secreview3_a_monitored_spawns_down_reaches_only_its_down_subject() { for threads in THREADS { assert_eq!( run_root(threads, delivers_downs_only_on_the_down_subject), Exit::Normal, "{threads} threads" ); } } /// Starting distribution switches the clock to real time, unless /// `LOUISE_VIRTUAL_TIME` keeps it virtual. unsafe extern "C" fn switches_to_real_time(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. let sched = unsafe { this(ctx) }.1; assert!(!sched.real_time()); sched.switch_to_real_time(); assert_eq!(sched.real_time(), !sched.virtual_time); UNIT } #[test] fn starting_distribution_switches_to_real_time() { for virtual_time in [false, true] { assert_eq!( super::run_root_clock(1, virtual_time, switches_to_real_time), Exit::Normal, "virtual time: {virtual_time}" ); } } // ---- back-pressure --------------------------------------------------------------- /// The fake peer's queue holds this many messages. const CAPACITY: usize = 2; /// The fake peer: its queue, the senders parked on it, and what it gave /// up (senders that exited while parked). struct Peer { queue: Vec, parked: Vec, abandoned: Vec, } static PEER: Mutex = Mutex::new(Peer { queue: Vec::new(), parked: Vec::new(), abandoned: Vec::new(), }); fn peer() -> std::sync::MutexGuard<'static, Peer> { PEER.lock().expect("the peer") } /// Hooks whose sends queue an `Int` message on [`PEER`], parking while it /// is full, as the transport's do. static PARKING: Hooks = Hooks { send: |ctx, _, _, _, message| { let n = int_get(message); let attempt = |n: i64, waiter: Option| { let mut p = peer(); if p.queue.len() < CAPACITY { p.queue.push(n); return Try::Done(Ok(())); } p.parked.extend(waiter); Try::Full(n) }; let unwait = |w: Waiter| peer().parked.retain(|p| *p != w); // SAFETY: the hook runs on the running actor of `ctx`. let sent = unsafe { send_parking(ctx, n, attempt, unwait) }; let sent = sent.unwrap_or_else(|| { peer().abandoned.push(n); Ok(()) }); sent.map_err(|why| unsendable(&why)) }, link: |_, _, _| {}, monitor: |_, _, _, _| false, demonitor: |_, _, _| {}, unlink: |_, _| {}, signal: |_, _, _| {}, down: |_, _, _, _| {}, exit: |_, _| {}, }; /// Messages the peer took off its queue, in order; how many waiters it /// woke. static TAKEN: Mutex<(Vec, usize)> = Mutex::new((Vec::new(), 0)); /// The peer writes its queue out, then wakes its parked senders, as the /// transport's thread does. fn drain(sched: &Shared) { let (queue, parked) = { let mut p = peer(); (std::mem::take(&mut p.queue), std::mem::take(&mut p.parked)) }; let mut taken = TAKEN.lock().expect("taken"); taken.0.extend(queue); taken.1 += parked.len(); drop(taken); for w in parked { wake_sender(sched, w); } } fn start_parking() { *peer() = Peer { queue: Vec::new(), parked: Vec::new(), abandoned: Vec::new(), }; *TAKEN.lock().expect("taken") = (Vec::new(), 0); install(&PARKING); } /// How many messages [`sends_ten`] sends. const SENT: i64 = 10; /// Sends 1 to [`SENT`] to a remote subject, unless it is killed. unsafe extern "C" fn sends_ten(ctx: *mut Ctx) -> Value { // SAFETY: an actor's entry. unsafe { for n in 1..=SENT { let to = crate::values::cell(ctx, 1, &[int(pid(3, 42)), int(7), int(0)]); perform(ctx, "send", &[to, int(n)]); if (*ctx).yielding != YIELD_NONE { break; } } } UNIT } /// The root drains the peer's queue only between its own turns: a sender /// that blocked its thread instead of parking would hang one thread. unsafe extern "C" fn parks_senders(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_parking(); let sender = spawn(ctx, sends_ten); yield_until(ctx, "the sender parked", |_| { peer().parked.iter().any(|w| w.pid == sender) }); assert_eq!(peer().queue, [1, 2], "the rest waits in its sender"); yield_until(ctx, "every message", |s| { drain(s); TAKEN.lock().expect("taken").0.len() == SENT as usize }); let (taken, woken) = TAKEN.lock().expect("taken").clone(); assert_eq!(taken, (1..=SENT).collect::>(), "in send order"); // On one thread, after every second message; on several, the // root may drain as fast as the sender sends. assert!(woken >= 1, "woken where it parked"); yield_until(ctx, "the sender to finish", |s| s.actors.all().len() == 1); assert!(peer().abandoned.is_empty()); uninstall(); } UNIT } #[test] fn a_sender_parks_while_the_queue_is_full() { for threads in THREADS { assert_eq!( run_root(threads, parks_senders), Exit::Normal, "{threads} threads" ); } } /// A sender killed while parked: its message is dropped, its waiter /// forgotten, and a late wake for it does nothing. unsafe extern "C" fn kills_a_parked_sender(ctx: *mut Ctx) -> Value { // SAFETY: the root actor's entry. unsafe { start_parking(); let sender = spawn(ctx, sends_ten); yield_until(ctx, "the sender parked", |_| !peer().parked.is_empty()); let stale = peer().parked[0]; let down = perform(ctx, "monitor", &[int(sender)]); perform(ctx, "kill", &[int(sender)]); let message = receive(ctx, down, -1).expect("its Down"); assert_eq!(signal_of(ctx, message), (sender, Exit::Killed)); drop_value(ctx, down); // Its `Down` comes at the kill; it unwinds when it runs next. yield_until(ctx, "the sender to unwind", |s| s.actors.all().len() == 1); { let p = peer(); assert_eq!(p.queue, [1, 2]); assert!(p.parked.is_empty(), "unregistered: {:?}", p.parked); assert_eq!(p.abandoned, [3], "dropped, at most once"); } from_outside(ctx, move |sched| wake_sender(sched, stale)); uninstall(); } UNIT } #[test] fn a_sender_killed_while_parked_drops_its_message() { for threads in THREADS { assert_eq!( run_root(threads, kills_a_parked_sender), Exit::Normal, "{threads} threads" ); } }