//! An actor's OTP state ([`Proc`]): its mailbox, what it waits for, its //! links and monitors. Timers, kills and the actor itself change it under //! the actor's lock (ADR 0004, Revision 2), each through one method here, //! so that loom models check the code the scheduler runs //! (`RUSTFLAGS="--cfg loom" cargo test -p louise_rt --release --lib otp inbox`). //! //! Senders do not take the lock (ADR 0028): they push onto the actor's //! [`Inbox`], and take the lock only when their push found the actor //! waiting, to wake it ([`Proc::woken_by_message`]). The actor moves what //! its inbox holds into its mailbox, under its lock, when it receives. A //! receive woken by a message on another tag finds nothing, and waits //! again, in the same wait (its timer still applies). //! //! `Proc` is generic in the values it holds and in the fiber: the runtime //! uses `Proc`, the models plain data. Taking the lock is the //! caller's job. use std::collections::VecDeque; use crate::handoff::RunState; use crate::inbox::Inbox; use crate::sched::{IdHasher, IdMap}; /// What parked operations return, made under the lock. pub(crate) trait Answer: Sized + PartialEq { /// A received message: `Some(message)`, or `Some((tag, message))` /// for `receive_any`. fn received(message: Self, tag: Option) -> Self; /// `None`: no message before the timeout. fn timed_out() -> Self; /// `()`: a sleep ended, a socket is ready, or the wait was interrupted. fn unit() -> Self; } #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) enum Wait { Ready, /// Waiting for a message on one of the actor's `waiting_tags`. Receive { deadline: Option, }, Sleep { deadline: u64, }, /// In a `blocking` extern call (never woken early, not even by a kill). Blocking, /// Waiting for a socket (`net`). Io, } /// The tags a receive waits on: one for `receive`, several for /// `receive_any`. One is kept inline: a waiting actor holds its tags, and /// most waiting actors wait on one subject. pub(crate) enum Tags { One(i64), Many(Vec), } impl Tags { #[cfg(test)] fn of(tags: &[i64]) -> Tags { match tags { [one] => Tags::One(*one), many => Tags::Many(many.to_vec()), } } fn as_slice(&self) -> &[i64] { match self { Tags::One(tag) => std::slice::from_ref(tag), Tags::Many(tags) => tags, } } } /// How long a receive waits. #[derive(Clone, Copy)] pub(crate) enum Timeout { /// Not at all: `receive(_, 0)`. Zero, /// Until this time on the scheduler's clock. At(u64), Never, } /// What a receive did. pub(crate) enum Received { /// It took a message (or timed out at once): what it returns. Now(V), /// The actor waits; the wait's number, for its timer. Parked(u64), } /// What an exit leaves to its caller (after releasing the lock). pub(crate) struct Exited { /// The linked actors, to stop or signal, in the order they were linked. pub(crate) links: Vec, /// (watcher, tag): who receives `Down`. pub(crate) monitors: Vec<(i64, i64)>, /// The nodes `dist` lists it under ([`Ties::nodes`]). pub(crate) nodes: Vec, /// Whether the actor must be scheduled, to unwind. pub(crate) wake: bool, } /// An actor's links and monitors, and how it takes exit signals. #[derive(Default)] #[cfg_attr(test, derive(Clone))] pub(crate) struct Ties { /// Its halves of its links: an exit through a link counts only while /// its receiver still has its half. pub(crate) links: Links, /// pid -> id: the remote pids this actor unlinked, until their node /// acknowledges unlink `id` (Erlang's *unlinking* state, `dist`). Not /// in `links`: an exit through the link is ignored at once. A link /// from that pid is ignored too, so the two sides end unlinked; a link /// from this actor overrides the unlink. At most one per pid (an /// unlink needs a link, which ends the one before), and a map: a peer /// that never acknowledges keeps them until its loss, and each op /// `10` or `18` to this actor looks one up. pub(crate) unlinking: IdMap, /// (watcher, tag): who receives `Down` when this actor exits. A remote /// watcher's goes out through the transport (`dist`). pub(crate) monitors: Vec<(i64, i64)>, /// (pid, tag): the remote actors this one monitors, its `Down` due on /// `tag` (`dist`). A local monitor is kept by the actor it watches. pub(crate) watching: Vec<(i64, i64)>, /// The nodes `dist` lists this actor under, as tied to them: every /// node it linked or monitored a pid of, or one of whose pids linked or /// monitored it, since, until that node is lost. Its exit unlists it /// from each, whether or not ties to it remain. pub(crate) nodes: Vec, pub(crate) trap: bool, pub(crate) exits_tag: Option, } impl Ties { /// Note a tie to a pid of `node`; whether `dist` must list this actor /// under it (the node is new to it). pub(crate) fn tie(&mut self, node: u16) -> bool { let new = !self.nodes.contains(&node); if new { self.nodes.push(node); } new } /// Forget the monitor of the remote `pid` on `tag`; whether there was /// one. pub(crate) fn unwatch(&mut self, pid: i64, tag: i64) -> bool { let found = self.watching.iter().position(|w| *w == (pid, tag)); found.map(|i| self.watching.remove(i)).is_some() } /// This actor links the remote `pid`: a new link, whatever unlink of /// it still waits for its acknowledgement. pub(crate) fn link_remote(&mut self, pid: i64) { self.unlinking.remove(&pid); self.links.insert(pid); } /// The remote `pid` links this actor: whether it is linked now. Not /// while this actor's unlink of it waits for its acknowledgement: /// that link was sent before the unlink reached `pid`'s node, which /// removes `pid`'s half, so both sides end unlinked. pub(crate) fn linked_by(&mut self, pid: i64) -> bool { if self.unlinking.contains_key(&pid) { return false; } self.links.insert(pid); true } /// This actor unlinks the remote `pid` as unlink `id`: its half waits /// for the acknowledgement. Whether it had one (then the unlink goes to /// `pid`'s node). pub(crate) fn unlink_remote(&mut self, pid: i64, id: u64) -> bool { let linked = self.links.remove(pid); if linked { self.unlinking.insert(pid, id); } linked } /// The remote `pid` acknowledged unlink `id`: forget it, unless this /// actor linked `pid` again since. Whether it did. pub(crate) fn unlink_acked(&mut self, pid: i64, id: u64) -> bool { let found = self.unlinking.get(&pid) == Some(&id); if found { self.unlinking.remove(&pid); } found } /// Take the links and monitors of the pids `lost` picks (a lost node's /// pids), each in its order, and forget the monitors they hold on this /// actor, no `Down` can reach them, and the unlinks waiting for them, /// whose acknowledgement cannot come. pub(crate) fn take(&mut self, lost: impl Fn(i64) -> bool) -> (Vec, Vec<(i64, i64)>) { let (links, kept): (Vec, Vec) = std::mem::take(&mut self.links) .into_vec() .into_iter() .partition(|p| lost(*p)); for p in kept { self.links.insert(p); } self.unlinking.retain(|p, _| !lost(*p)); let (watching, kept) = std::mem::take(&mut self.watching) .into_iter() .partition(|(p, _)| lost(*p)); self.watching = kept; self.monitors.retain(|(watcher, _)| !lost(*watcher)); (links, watching) } /// The unlinks waiting for their acknowledgement, as (pid, id), by pid. #[cfg(all(test, not(loom)))] pub(crate) fn unlinks(&self) -> Vec<(i64, u64)> { let mut unlinks: Vec<_> = self.unlinking.iter().map(|(p, id)| (*p, *id)).collect(); unlinks.sort_unstable(); unlinks } } /// The actors an actor is linked to, in the order they were linked (the /// order exits propagate in). /// /// Most linked actors have one link (to the actor that spawned them), and /// it is kept inline. More make a set, so that membership and removal take /// constant time: an actor linked to each of 100,000 short-lived children /// removed each child from a vector as it exited, quadratic time that /// dominated `tests/stress/actors.lse` (issue #61). The set alone cost /// each linked child three allocations, and 10-20% on 4-22 threads (issue /// #104). #[derive(Default)] #[cfg_attr(test, derive(Clone))] pub(crate) enum Links { #[default] None, One(i64), Many { /// Insertion order; removed links stay until compacted, and a pid /// linked again is pushed again (its first copy is its place). order: Vec, live: std::collections::HashSet>, }, } impl Links { fn is_empty(&self) -> bool { match self { Links::None => true, Links::One(_) => false, Links::Many { live, .. } => live.is_empty(), } } /// Link `pid`, unless it already is. pub(crate) fn insert(&mut self, pid: i64) { match self { Links::None => *self = Links::One(pid), Links::One(p) if *p == pid => {} Links::One(p) => { let order = vec![*p, pid]; let live = order.iter().copied().collect(); *self = Links::Many { order, live }; } Links::Many { order, live } => { if live.insert(pid) { order.push(pid); } } } } /// Unlink `pid`; whether it was linked. pub(crate) fn remove(&mut self, pid: i64) -> bool { match self { Links::None => false, Links::One(p) => { let linked = *p == pid; if linked { *self = Links::None; } linked } Links::Many { order, live } => { let linked = live.remove(&pid); if linked && order.len() > 2 * live.len() + 16 { // Keep each linked pid's first copy only, the place // `into_vec` gives it: a pid unlinked and linked again // has one copy per link, and keeping them all would // leave `order` past the bound, rescanned by every // later removal. let mut first = live.clone(); order.retain(|p| first.remove(p)); } linked } } } /// Whether `pid` is linked. #[cfg(test)] pub(crate) fn contains(&self, pid: i64) -> bool { match self { Links::None => false, Links::One(p) => *p == pid, Links::Many { live, .. } => live.contains(&pid), } } /// The linked actors, in order. pub(crate) fn into_vec(self) -> Vec { match self { Links::None => Vec::new(), Links::One(p) => vec![p], Links::Many { order, mut live } => { // `remove` on a pid seen twice (unlinked, then linked // again) keeps its first place. order.into_iter().filter(|p| live.remove(p)).collect() } } } } /// Messages by subject tag, each with its arrival number: receiving from /// one subject is O(1) however many other messages wait, and /// `receive_any` still takes the oldest of several subjects. pub(crate) struct Mailbox { by_tag: IdMap>, arrived: u64, } impl Default for Mailbox { fn default() -> Self { Mailbox { by_tag: IdMap::default(), arrived: 0, } } } impl Mailbox { fn push(&mut self, tag: i64, message: V) { self.arrived += 1; self.by_tag .entry(tag) .or_default() .push_back((self.arrived, message)); } /// The oldest message on one of `tags`, with its tag. fn take(&mut self, tags: &[i64]) -> Option<(i64, V)> { let tag = tags .iter() .filter_map(|t| Some((self.by_tag.get(t)?.front()?.0, *t))) .min()? .1; let queue = self.by_tag.get_mut(&tag)?; let (_, message) = queue.pop_front()?; if queue.is_empty() { self.by_tag.remove(&tag); } Some((tag, message)) } /// Every message left, to drop. fn is_empty(&self) -> bool { self.by_tag.is_empty() } pub(crate) fn drain(&mut self) -> impl Iterator { std::mem::take(&mut self.by_tag) .into_values() .flatten() .map(|(_, message)| message) } } /// The oldest message on one of `tags`: in the mailbox, which holds the /// older ones, else the first such in the inbox, whose other messages are /// filed in the mailbox. A message a receive is waiting for skips the /// mailbox: filing and taking it again (a queue made and freed per /// message) cost 15% of `tests/bench/messages.lse`. fn take_wanted(mailbox: &mut Mailbox, inbox: &Inbox, tags: &[i64]) -> Option<(i64, V)> { if !mailbox.is_empty() && let Some(older) = mailbox.take(tags) { return Some(older); } let mut wanted = None; inbox.take(|tag, message| { if wanted.is_none() && tags.contains(&tag) { wanted = Some((tag, message)); } else { mailbox.push(tag, message); } }); wanted } pub(crate) struct Proc { mailbox: Mailbox, pub(crate) wait: Wait, /// What a parked operation returns when woken. wake: V, /// Allocated when first used: most actors have none (ADR 0028). ties: Option>, /// While `wait` is `Receive`: the tags waited on, and whether the /// answer carries the tag (`receive_any`). waiting_tags: Tags, waiting_any: bool, /// Counts waits, so a timer set for an earlier one is ignored. wait_gen: u64, /// The current receive's timer fired. timed_out: bool, /// Exited (logically); its fiber may still have to unwind. pub(crate) dead: bool, pub(crate) run: RunState, } impl Proc { /// A new actor, queued (its caller pushes it right after). pub(crate) fn new(fiber: F, links: Links, monitors: Vec<(i64, i64)>) -> Self { let mut run = RunState::new(fiber); run.queue_new(); Proc { mailbox: Mailbox::default(), wait: Wait::Ready, wake: V::unit(), ties: (!links.is_empty() || !monitors.is_empty()).then(|| { Box::new(Ties { links, monitors, ..Ties::default() }) }), waiting_tags: Tags::Many(Vec::new()), waiting_any: false, wait_gen: 0, timed_out: false, dead: false, run, } } /// A push found the actor waiting ([`Inbox::push`]): wake it if it /// still waits for a message. Returns whether the caller must schedule /// it. (The actor finds the message itself, in its inbox.) pub(crate) fn woken_by_message(&mut self) -> bool { matches!(self.wait, Wait::Receive { .. }) && self.run.wake() } /// Whether the actor waits in a receive on `tag`. pub(crate) fn waits_for(&self, tag: i64) -> bool { matches!(self.wait, Wait::Receive { .. }) && self.waiting_tags.as_slice().contains(&tag) } /// Its links, monitors and exit-signal settings, allocated now if they /// were not. pub(crate) fn ties(&mut self) -> &mut Ties { self.ties.get_or_insert_with(Box::default) } /// Make this actor's half of a link to `pid`, unless it exited: /// whether it did. pub(crate) fn link(&mut self, pid: i64) -> bool { if self.dead { return false; } self.ties().links.insert(pid); true } /// Remove this actor's half of its link to `pid`: whether it had it /// (an exit through the link counts only then), and whether this /// actor traps exits. pub(crate) fn unlink(&mut self, pid: i64) -> (bool, bool) { self.ties .as_mut() .map_or((false, false), |t| (t.links.remove(pid), t.trap)) } /// This actor, alive, unlinks the remote `pid` as unlink `id` /// ([`Ties::unlink_remote`]): whether it had a link to it. pub(crate) fn unlink_remote(&mut self, pid: i64, id: u64) -> bool { !self.dead && self.ties.as_mut().is_some_and(|t| t.unlink_remote(pid, id)) } /// [`Ties::unlink_acked`]. pub(crate) fn unlink_acked(&mut self, pid: i64, id: u64) -> bool { self.ties.as_mut().is_some_and(|t| t.unlink_acked(pid, id)) } /// `watcher` stops monitoring this actor on `tag` (`demonitor`): /// whether it did. pub(crate) fn demonitor(&mut self, watcher: i64, tag: i64) -> bool { let Some(ties) = self.ties.as_mut() else { return false; }; let found = ties.monitors.iter().position(|m| *m == (watcher, tag)); found.map(|i| ties.monitors.remove(i)).is_some() } /// Forget this actor's monitor of the remote `pid` on `tag` /// ([`Ties::unwatch`]); whether there was one. pub(crate) fn unwatch(&mut self, pid: i64, tag: i64) -> bool { self.ties.as_mut().is_some_and(|t| t.unwatch(pid, tag)) } /// A sender that claimed the actor's wait ([`Inbox::claim_waiting`], /// after [`Proc::waits_for`]): the receive returns `message`. Returns /// whether the caller must schedule the actor. pub(crate) fn hand_over(&mut self, tag: i64, message: V) -> bool { debug_assert!(self.waits_for(tag)); let answer = V::received(message, self.waiting_any.then_some(tag)); self.wake(answer) } /// Move what the inbox holds into the mailbox. fn file(&mut self, inbox: &Inbox) { let mailbox = &mut self.mailbox; inbox.take(|tag, message| mailbox.push(tag, message)); } /// Take the oldest message on one of `tags`, or else wait for one /// (then the caller parks, after setting the timer). `any`: the answer /// carries the tag. pub(crate) fn receive( &mut self, inbox: &Inbox, tags: Tags, any: bool, timeout: Timeout, ) -> Received { if let Some((tag, message)) = take_wanted(&mut self.mailbox, inbox, tags.as_slice()) { return Received::Now(V::received(message, any.then_some(tag))); } let deadline = match timeout { Timeout::Zero => return Received::Now(V::timed_out()), Timeout::At(d) => Some(d), Timeout::Never => None, }; self.waiting_tags = tags; self.waiting_any = any; self.timed_out = false; Received::Parked(self.park_as(Wait::Receive { deadline })) } /// The actor, parked by [`Proc::receive`], runs again: what the /// receive returns, or `None` if it must wait again (woken by a message /// on another tag). pub(crate) fn receive_woken(&mut self, inbox: &Inbox) -> Option { let handed = self.take_wake(); if handed != V::unit() { // A message handed over (`hand_over`): never unit, since a // received message comes wrapped (`Answer::received`). return Some(handed); } if let Some((tag, message)) = take_wanted(&mut self.mailbox, inbox, self.waiting_tags.as_slice()) { self.wait = Wait::Ready; return Some(V::received(message, self.waiting_any.then_some(tag))); } if self.timed_out || self.wait == Wait::Ready { // Only a timer or an exit end a receive; an exit unwinds the // actor before it gets here. debug_assert!(self.timed_out, "louise: a receive ended for nothing"); self.timed_out = false; self.wait = Wait::Ready; return Some(V::timed_out()); } None } /// Make the actor ready; its parked operation returns `value`. /// Returns whether the caller must schedule it (after releasing the /// lock). pub(crate) fn wake(&mut self, value: V) -> bool { self.wait = Wait::Ready; self.wake = value; self.run.wake() } /// Wake it if it is still in `Io` wait number `wait`, not a later one /// (a sender parked on a peer's full queue, `dist::send_parking`). /// Returns whether the caller must schedule it. pub(crate) fn resume(&mut self, wait: u64) -> bool { self.wait_gen == wait && self.wait == Wait::Io && self.wake(V::unit()) } /// Wake it unless it is ready or in a blocking call. pub(crate) fn interrupt(&mut self) -> bool { if self.wait != Wait::Ready && self.wait != Wait::Blocking { return self.wake(V::unit()); } false } /// Start waiting as `wait`; returns the wait's number, for its timer. /// /// An actor that exited while it ran (killed, or a linked actor /// crashed) does not wait: its exit found it ready, so nothing would /// wake it. It stays ready, its thread queues it again when it yields, /// and it unwinds. Except in a blocking call, which runs to its end /// (it still reads the actor's values). pub(crate) fn park_as(&mut self, wait: Wait) -> u64 { self.wait_gen += 1; if !self.dead || wait == Wait::Blocking { self.wait = wait; } self.wait_gen } /// Whether the actor is still in wait number `wait`, until `deadline` /// (else that wait's timer no longer applies). pub(crate) fn waits_until(&self, wait: u64, deadline: u64) -> bool { let current = match self.wait { Wait::Receive { deadline: Some(d), .. } | Wait::Sleep { deadline: d } => Some(d), _ => None, }; self.wait_gen == wait && current == Some(deadline) } /// The timer of wait number `wait` is due: end that wait, if it is /// still on. A receive returns `None` ([`Proc::receive_woken`]), a /// sleep `()`. Returns whether the caller must schedule the actor. pub(crate) fn time_out(&mut self, wait: u64, deadline: u64) -> bool { if !self.waits_until(wait, deadline) { return false; } if matches!(self.wait, Wait::Receive { .. }) { self.timed_out = true; } self.wake(V::unit()) } /// The actor exits: from now on, messages are refused and its wait is /// interrupted. `None` if it had already exited. pub(crate) fn exit(&mut self, inbox: &Inbox) -> Option { if self.dead { return None; } self.dead = true; // A receive it waits in is interrupted below, like any other wait. inbox.close(); let ties = self.ties.take().map(|t| *t).unwrap_or_default(); Some(Exited { links: ties.links.into_vec(), monitors: ties.monitors, nodes: ties.nodes, wake: self.interrupt(), }) } /// What the woken operation returns (the actor resumed). pub(crate) fn take_wake(&mut self) -> V { std::mem::replace(&mut self.wake, V::unit()) } /// The actor's fiber yielded: whether the caller must queue it again /// (it was preempted, or woken before it stopped). A receive waits on /// its inbox from here, its fiber suspended: unless messages arrived /// meanwhile, or it exited, the next push wakes it. pub(crate) fn stop(&mut self, inbox: &Inbox, fiber: F) -> bool { let ready = match self.wait { Wait::Ready => true, Wait::Receive { .. } => !inbox.park(), _ => false, }; self.run.stop(fiber, ready) } /// What the actor still holds once it exited, to drop: its inbox is /// closed, so nothing arrives any more. pub(crate) fn release(&mut self, inbox: &Inbox) -> (Mailbox, V) { debug_assert!(self.dead); self.file(inbox); (std::mem::take(&mut self.mailbox), self.take_wake()) } } /// The models' values: messages are numbered, so that each can be found /// again wherever it ended up. #[cfg(test)] #[derive(Clone, Copy, Debug, PartialEq)] enum Val { Unit, TimedOut, Message(u32), Received(u32, Option), } #[cfg(test)] impl Answer for Val { fn received(message: Val, tag: Option) -> Val { match message { Val::Message(n) => Val::Received(n, tag), other => panic!("not a message: {other:?}"), } } fn timed_out() -> Val { Val::TimedOut } fn unit() -> Val { Val::Unit } } #[cfg(all(test, loom))] mod loom_models { //! Each model plays an actor's receive on the main thread, as //! `process::take_or_wait` and `wait_for_message` do, against senders //! (as `Shared::deliver`), timers and kills on other threads. The //! actor starts running, as the thread that took it from a run queue //! leaves it. When its fiber yields, its thread stops it (`run_slice`); //! then it runs again once someone queued it. `queued` is its run //! queue: a lost wake-up leaves the actor waiting there for good, which //! loom reports as a deadlock; a doubled one leaves an entry behind. //! //! A kill is modelled by `Proc::exit` alone: the kill flag the actor //! reads at its safe points is set under the same lock, just before. use super::*; use loom::sync::atomic::{AtomicBool, Ordering}; use loom::sync::{Arc, Condvar, Mutex}; use loom::thread; const A: i64 = 1; const B: i64 = 2; /// Every interleaving with up to 3 preemptions (loom's usual bound): /// unbounded (`LOUISE_LOOM_UNBOUNDED=1`), the three models take /// minutes, and pass. Bounded, /// they still find each of these, as a lost wake-up (checked by hand): /// a sender that does not wake a waiting receiver, whether it pushed /// or handed its message over; `stop` parking without re-checking the /// inbox; an exit that does not interrupt a receive. fn model(f: impl Fn() + Sync + Send + 'static) { let mut builder = loom::model::Builder::new(); if std::env::var_os("LOUISE_LOOM_UNBOUNDED").is_none() { builder.preemption_bound = Some(3); } builder.check(f); } /// An actor's shared half, as `sched::Cell`, with its run queue. struct Cell { inbox: Inbox, proc: Mutex>, queued: Mutex, queue: Condvar, } fn running() -> Arc { let mut p = Proc::new((), Links::default(), Vec::new()); assert!(p.run.start().is_some()); Arc::new(Cell { inbox: Inbox::new(), proc: Mutex::new(p), queued: Mutex::new(0), queue: Condvar::new(), }) } impl Cell { fn schedule(&self) { *self.queued.lock().unwrap() += 1; self.queue.notify_one(); } /// A send, as `Shared::deliver`: the message back if refused. fn send(&self, tag: i64, message: u32) -> Option { if self.inbox.waits_empty() && let Ok(mut p) = self.proc.try_lock() && p.waits_for(tag) && self.inbox.claim_waiting() { if p.hand_over(tag, Val::Message(message)) { drop(p); self.schedule(); } return None; } match self.inbox.push(tag, Val::Message(message)) { Err(refused) => Some(refused), Ok(false) => None, Ok(true) => { if self.proc.lock().unwrap().woken_by_message() { self.schedule(); } None } } } /// The actor's fiber yields; its thread stops it. fn stop(&self) { if self.proc.lock().unwrap().stop(&self.inbox, ()) { self.schedule(); } } /// A thread takes the actor from its run queue, and runs it. fn run_once_queued(&self) { let mut queued = self.queued.lock().unwrap(); while *queued == 0 { queued = self.queue.wait(queued).unwrap(); } *queued -= 1; drop(queued); let started = self.proc.lock().unwrap().run.start(); assert!(started.is_some(), "queued while not suspended"); } /// What is left in the mailbox on `tag` (checked without waiting). fn left(&self, tag: i64) -> Val { let mut p = self.proc.lock().unwrap(); match p.receive(&self.inbox, Tags::One(tag), false, Timeout::Zero) { Received::Now(v) => v, Received::Parked(_) => unreachable!("a zero timeout never waits"), } } } /// The actor receives on `tags`: what the receive returns. If the /// actor unwinds (it exited): `None`, or the message handed over /// before the exit, which it frees. A timeout sets its timer, on /// another thread, once the actor waits. fn receive( cell: &Arc, tags: &[i64], timeout: Timeout, ) -> (Option, Option>) { let received = cell.proc .lock() .unwrap() .receive(&cell.inbox, Tags::of(tags), false, timeout); let wait = match received { Received::Now(v) => return (Some(v), None), Received::Parked(wait) => wait, }; let timer = match timeout { Timeout::At(deadline) => { let cell = cell.clone(); Some(thread::spawn(move || { if cell.proc.lock().unwrap().time_out(wait, deadline) { cell.schedule(); } })) } _ => None, }; loop { cell.stop(); cell.run_once_queued(); let mut p = cell.proc.lock().unwrap(); if p.dead { // Unwinding: a message handed over is dropped (counted by // the caller, as `wait_for_message` frees it). let handed = p.take_wake(); return (Some(handed).filter(|v| *v != Val::Unit), timer); } if let Some(v) = p.receive_woken(&cell.inbox) { return (Some(v), timer); } } } fn sender(cell: &Arc, tag: i64, message: u32) -> thread::JoinHandle> { let cell = cell.clone(); thread::spawn(move || cell.send(tag, message)) } /// Two messages race with a receive on one of their tags: the receive /// gets the first, at once or woken (perhaps first by the other one, /// then again); the other stays in the mailbox. #[test] fn sends_race_a_receive() { model(|| { let cell = running(); let to_a = sender(&cell, A, 1); let to_b = sender(&cell, B, 2); let (got, _) = receive(&cell, &[A], Timeout::Never); assert_eq!(got, Some(Val::Received(1, None))); assert_eq!(to_a.join().unwrap(), None); assert_eq!(to_b.join().unwrap(), None); assert_eq!(cell.left(A), Val::TimedOut); assert_eq!(cell.left(B), Val::Received(2, None)); assert_eq!(*cell.queued.lock().unwrap(), 0, "a doubled wake-up"); }); } /// A receive's timer fires while its message arrives: the receive /// returns the message or `None`, not both, and a message it did not /// return is still in the mailbox. #[test] fn a_timeout_races_a_send() { model(|| { let cell = running(); let send = sender(&cell, A, 1); let (got, timer) = receive(&cell, &[A], Timeout::At(10)); assert_eq!(send.join().unwrap(), None); if let Some(timer) = timer { timer.join().unwrap(); } match got { Some(Val::Received(1, None)) => assert_eq!(cell.left(A), Val::TimedOut), Some(Val::TimedOut) => assert_eq!(cell.left(A), Val::Received(1, None)), other => panic!("the receive returned {other:?}"), } assert_eq!(*cell.queued.lock().unwrap(), 0, "a doubled wake-up"); }); } /// The actor is killed while a message arrives and it receives: the /// message is received, refused (back to its sender) or left for the /// actor to free as it unwinds, exactly one of them. #[test] fn a_kill_races_a_send_and_a_receive() { model(|| { let cell = running(); let send = sender(&cell, A, 1); let kill = { let cell = cell.clone(); thread::spawn(move || { let exited = cell.proc.lock().unwrap().exit(&cell.inbox); if exited.expect("exits once").wake { cell.schedule(); } }) }; let (got, _) = receive(&cell, &[A], Timeout::Never); let refused = send.join().unwrap(); kill.join().unwrap(); let mut found: Vec = got.into_iter().chain(refused).collect(); let (mut mailbox, wake) = cell.proc.lock().unwrap().release(&cell.inbox); assert_eq!(wake, Val::Unit); found.extend(mailbox.drain()); let ones = found .iter() .filter(|v| matches!(v, Val::Message(1) | Val::Received(1, _))) .count(); assert_eq!(ones, 1, "the message, once: {found:?}"); assert_eq!(*cell.queued.lock().unwrap(), 0, "a doubled wake-up"); }); } // ---- links: each step under one actor's lock, as `op_link`, `op_unlink` // and `exit_actor` (with `propagate_exit`) take them. // // These are copies of the production steps, not the production // functions (which need a scheduler): each model function names the // one it copies, step for step, and a change to that function must be // made here too. Not modelled: a receiver that does not trap exits // and dies of one under its lock (`Linked::Dies`; its own exit then // runs as `exit` here), the inbox push and wake-up, and two actors // exiting at once. /// What happened to an actor of the link models, under its lock. #[derive(Clone, Copy, Debug, PartialEq)] enum Event { /// Its half of a link was made (`link`). Linked, /// Its half was removed by its own `unlink`. Unlinked, /// The exit of this pid came through a link (an `ExitSignal`: the /// models' actors trap exits, so none dies of it). Exit(i64), } /// An actor of the link models: its lock, what happened under it, and /// the kill flag its exit sets under it (`Cell::kill`). struct Linker { pid: i64, inbox: Inbox, proc: Mutex<(Proc, Vec)>, killed: AtomicBool, } impl Linker { fn new(pid: i64, linked: &[i64]) -> Arc { let mut links = Links::default(); linked.iter().for_each(|p| links.insert(*p)); let mut p = Proc::new((), links, Vec::new()); assert!(p.run.start().is_some()); Arc::new(Linker { pid, inbox: Inbox::new(), proc: Mutex::new((p, Vec::new())), killed: AtomicBool::new(false), }) } fn has_half(&self, pid: i64) -> bool { let p = &self.proc.lock().unwrap().0; p.ties.as_ref().is_some_and(|t| t.links.contains(pid)) } fn events(&self) -> Vec { self.proc.lock().unwrap().1.clone() } } /// `me` links `other` (`process::link_local`): its own half, unless it /// exited; then `other`'s, unless `other` exited or `me`'s kill flag is /// set (its exit, which sets it under `me`'s lock, signals `other` /// under `other`'s, after); without `other`, its own half goes. /// Whether `other`'s half was made. fn link(me: &Linker, other: &Linker) -> bool { { let mut g = me.proc.lock().unwrap(); if !g.0.link(other.pid) { return false; } g.1.push(Event::Linked); } let made = { let mut g = other.proc.lock().unwrap(); (!g.0.dead).then(|| !me.killed.load(Ordering::Acquire) && g.0.link(me.pid)) }; if made.is_none() { me.proc.lock().unwrap().0.unlink(other.pid); } made == Some(true) } /// `me` unlinks `other` (`process::op_unlink`, local): its own half, /// then `other`'s. fn unlink(me: &Linker, other: &Linker) { { let mut g = me.proc.lock().unwrap(); g.0.unlink(other.pid); g.1.push(Event::Unlinked); } let mut g = other.proc.lock().unwrap(); if !g.0.dead { g.0.unlink(me.pid); } } /// `who` exits (`sched::exit_actor`, `exit_locked`): its links taken /// and its kill flag set under its lock; then each linked actor, under /// its own, counts the exit only through a half it still has /// (`propagate_exit`, `exit_through_link`). `table` says whether each /// linked pid is in the actor table yet (`Shared::cell`): one that is /// not is not told. fn exit(who: &Linker, all: &[&Linker]) { exit_in(who, all, None); } fn exit_in(who: &Linker, all: &[&Linker], table: Option<&Mutex>) { let links = { let mut g = who.proc.lock().unwrap(); let exited = g.0.exit(&who.inbox).expect("exits once"); who.killed.store(true, Ordering::Release); exited.links }; for to in links { if table.is_some_and(|t| !*t.lock().unwrap()) { continue; } let to = all.iter().find(|a| a.pid == to).expect("a linked actor"); let mut g = to.proc.lock().unwrap(); if !g.0.dead && g.0.unlink(who.pid).0 { g.1.push(Event::Exit(who.pid)); } } } /// `a` unlinks `b`, then links it again, while `b` exits: `b`'s exit /// reaches `a` at most once, never between the unlink and the new /// link; if the new link made `b`'s half, it does; and `a` keeps no /// half of a link to the pid that exited. #[test] fn an_unlink_races_an_exit_and_a_new_link() { model(|| { let a = Linker::new(A, &[B]); let b = Linker::new(B, &[A]); let exiting = { let (a, b) = (a.clone(), b.clone()); thread::spawn(move || exit(&b, &[&a, &b])) }; unlink(&a, &b); let relinked = link(&a, &b); exiting.join().unwrap(); let events = a.events(); let exits: Vec = (0..events.len()) .filter(|i| events[*i] == Event::Exit(B)) .collect(); assert!(exits.len() <= 1, "one exit at most: {events:?}"); let at = |e: Event| events.iter().position(|x| *x == e).unwrap(); let (unlinked, linked) = (at(Event::Unlinked), at(Event::Linked)); if let Some(&i) = exits.first() { assert!( i < unlinked || i > linked, "an exit while unlinked: {events:?}" ); } if relinked { assert!(exits.first().is_some_and(|i| *i > linked), "{events:?}"); } assert!(!a.has_half(B), "linked to a pid that exited: {events:?}"); }); } /// `a` links `b` while `a` is killed: `b` gets `a`'s exit if it has its /// half, and keeps no half of a link to the pid that exited. #[test] fn a_link_races_the_linkers_exit() { model(|| { let a = Linker::new(A, &[]); let b = Linker::new(B, &[]); let killing = { let (a, b) = (a.clone(), b.clone()); thread::spawn(move || exit(&a, &[&a, &b])) }; let made = link(&a, &b); killing.join().unwrap(); let events = b.events(); let told = events.iter().filter(|e| **e == Event::Exit(A)).count(); assert!(told <= 1, "{events:?}"); assert_eq!(made, told == 1, "{events:?}"); assert!(!b.has_half(A), "linked to a pid that exited: {events:?}"); }); } /// `parent` spawn_links `child` while `parent` is killed /// (`sched::spawn_actor`): the parent's half first, unless it exited; /// the child made with its half and put in the actor table; then the /// child is stopped as an orphan if the parent's half could not be /// made or the parent's kill flag is set. The parent's exit sets the /// flag before it looks the child up in the table, so whenever it /// misses the child, the child sees the flag: the child is always told /// or stopped, never left linked to a pid that exited. #[test] fn a_spawn_link_races_the_parents_exit() { model(|| { let parent = Linker::new(A, &[]); let child = Linker::new(B, &[A]); let table = Arc::new(Mutex::new(false)); let killing = { let (parent, child, table) = (parent.clone(), child.clone(), table.clone()); thread::spawn(move || exit_in(&parent, &[&parent, &child], Some(&table))) }; let linked = parent.proc.lock().unwrap().0.link(B); *table.lock().unwrap() = true; let orphan = !linked || parent.killed.load(Ordering::Acquire); killing.join().unwrap(); let told = child.events().contains(&Event::Exit(A)); assert!(told || orphan, "the child outlived its parent, linked"); }); } } // Second security review of #404 (dist/secreview2): a measurement. #[cfg(all(test, not(loom)))] mod secreview2; // Third security review of #404 (dist/secreview3): a measurement. #[cfg(all(test, not(loom)))] mod secreview3; #[cfg(all(test, not(loom)))] mod tests { use super::*; fn actor() -> (Proc, Inbox) { let mut p = Proc::new((), Links::default(), Vec::new()); assert!(p.run.start().is_some()); (p, Inbox::new()) } fn parked(r: Received) -> u64 { match r { Received::Parked(wait) => wait, Received::Now(v) => panic!("received {v:?}"), } } #[test] fn receive_any_takes_the_oldest_and_names_its_tag() { let (mut p, inbox) = actor(); for (tag, n) in [(2, 1), (1, 2), (2, 3)] { assert_eq!(inbox.push(tag, Val::Message(n)), Ok(false)); } assert!(matches!( p.receive(&inbox, Tags::of(&[1, 2]), true, Timeout::Zero), Received::Now(Val::Received(1, Some(2))) )); assert!(matches!( p.receive(&inbox, Tags::of(&[1]), false, Timeout::Zero), Received::Now(Val::Received(2, None)) )); } #[test] fn a_message_on_another_tag_wakes_a_receive_which_waits_again() { let (mut p, inbox) = actor(); parked(p.receive(&inbox, Tags::of(&[1]), false, Timeout::Never)); assert!(!p.stop(&inbox, ()), "it waits"); assert_eq!(inbox.push(2, Val::Message(1)), Ok(true)); assert!(p.woken_by_message()); assert!(p.run.start().is_some()); assert_eq!(p.receive_woken(&inbox), None, "not its tag"); assert!(!p.stop(&inbox, ()), "it waits again"); assert_eq!(inbox.push(1, Val::Message(2)), Ok(true)); assert!(p.woken_by_message()); assert!(p.run.start().is_some()); assert_eq!(p.receive_woken(&inbox), Some(Val::Received(2, None))); } #[test] fn a_timer_for_an_earlier_wait_is_ignored() { let (mut p, inbox) = actor(); let first = parked(p.receive(&inbox, Tags::of(&[1]), false, Timeout::At(10))); assert!(!p.stop(&inbox, ())); assert_eq!(inbox.push(1, Val::Message(1)), Ok(true)); assert!(p.woken_by_message()); assert!(p.run.start().is_some()); assert_eq!(p.receive_woken(&inbox), Some(Val::Received(1, None))); // Waiting again, with the same deadline. let second = parked(p.receive(&inbox, Tags::of(&[1]), false, Timeout::At(10))); assert!(!p.stop(&inbox, ())); assert!(!p.time_out(first, 10), "the first wait's timer"); assert!(p.time_out(second, 10)); assert!(p.run.start().is_some()); assert_eq!(p.receive_woken(&inbox), Some(Val::TimedOut)); } #[test] fn a_timeout_survives_a_wake_up_for_another_tag() { let (mut p, inbox) = actor(); let wait = parked(p.receive(&inbox, Tags::of(&[1]), false, Timeout::At(10))); assert!(!p.stop(&inbox, ())); assert_eq!(inbox.push(2, Val::Message(1)), Ok(true)); assert!(p.woken_by_message()); assert!(p.run.start().is_some()); assert_eq!(p.receive_woken(&inbox), None); assert!(!p.stop(&inbox, ())); assert!(p.time_out(wait, 10), "the same wait, so its timer applies"); assert!(p.run.start().is_some()); assert_eq!(p.receive_woken(&inbox), Some(Val::TimedOut)); } #[test] fn a_message_does_not_wake_a_sleep() { let (mut p, inbox) = actor(); // A wait flag left by an earlier receive that a timer ended. parked(p.receive(&inbox, Tags::of(&[1]), false, Timeout::Never)); assert!(!p.stop(&inbox, ())); assert!(p.interrupt()); assert!(p.run.start().is_some()); p.park_as(Wait::Sleep { deadline: 5 }); assert!(!p.stop(&inbox, ())); assert_eq!(inbox.push(1, Val::Message(1)), Ok(true)); assert!(!p.woken_by_message(), "it sleeps"); inbox.take(|_, _| {}); } /// A sender parked on a full queue is resumed by its own wait only: a /// late wake for an earlier one, or for an actor now receiving, is /// ignored. #[test] fn a_parked_sender_is_resumed_by_its_own_wait_only() { let (mut p, inbox) = actor(); let first = p.park_as(Wait::Io); assert!(!p.stop(&inbox, ())); assert!(p.resume(first), "woken: schedule it"); assert!(p.run.start().is_some()); assert!(!p.resume(first), "ready: nothing to wake"); let second = p.park_as(Wait::Io); assert!(!p.stop(&inbox, ())); assert!(!p.resume(first), "an earlier wait's wake"); assert!(p.resume(second)); assert!(p.run.start().is_some()); parked(p.receive(&inbox, Tags::of(&[1]), false, Timeout::Never)); assert!(!p.stop(&inbox, ())); assert!(!p.resume(second), "it receives now"); assert_eq!(inbox.push(1, Val::Message(1)), Ok(true)); assert!(p.woken_by_message()); inbox.take(|_, _| {}); } /// Killed while it ran, then it receives: it does not wait, so that it /// is queued again to unwind (found by `a_kill_races_a_send_and_a_receive`). #[test] fn an_actor_killed_while_running_does_not_wait() { for wait in [Wait::Io, Wait::Sleep { deadline: 5 }] { let (mut p, inbox) = actor(); assert!( !p.exit(&inbox).expect("alive").wake, "running: nothing to wake" ); p.park_as(wait); assert!(p.stop(&inbox, ()), "{wait:?}: queued again, to unwind"); } let (mut p, inbox) = actor(); p.exit(&inbox); parked(p.receive(&inbox, Tags::of(&[1]), false, Timeout::Never)); assert!(p.stop(&inbox, ())); } #[test] fn an_exited_actor_refuses_messages_and_a_blocking_call_is_not_interrupted() { let (mut p, inbox) = actor(); p.park_as(Wait::Blocking); assert!(!p.stop(&inbox, ())); assert!( !p.exit(&inbox).expect("alive").wake, "a blocking call runs to its end" ); assert!(p.exit(&inbox).is_none(), "exits once"); assert_eq!(inbox.push(1, Val::Message(1)), Err(Val::Message(1))); } #[test] fn links_keep_their_order_and_drop_removed_ones() { let mut links = Links::default(); for pid in [5, 3, 9, 3, 7] { links.insert(pid); } links.remove(9); links.remove(42); assert_eq!(links.into_vec(), [5, 3, 7]); // Many removals compact the order, without changing it. let mut links = Links::default(); for pid in 0..1000 { links.insert(pid); } for pid in (0..1000).filter(|p| p % 10 != 0) { links.remove(pid); } let Links::Many { order, .. } = &links else { panic!("100 links are a set"); }; assert!(order.len() < 300); assert_eq!(links.into_vec(), (0..1000).step_by(10).collect::>()); } #[test] fn links_grow_from_one_to_a_set_keeping_their_order() { let mut links = Links::default(); assert!(links.is_empty()); links.insert(1); links.insert(1); assert!(matches!(links, Links::One(1))); links.remove(1); assert!(links.is_empty()); links.insert(1); links.insert(2); assert!(matches!(links, Links::Many { .. })); links.insert(3); links.remove(1); links.insert(1); // linked again: keeps its first place assert_eq!(links.into_vec(), [1, 2, 3]); } /// Review of #422 (dist/ccreview3). Before `unlink`, a pid left an /// actor's links only when it exited, and never came back. Now a live /// pid is removed and linked again as a matter of course (`unlink` /// then `link`, here or by a peer's frames 17 and 10), and each time /// `insert` pushes it on `order` once more. Compaction keeps every /// copy of a pid that was linked at the time: a pid unlinked and linked /// again many times, then left linked, kept `order` above the bound /// `remove` compacts at, so every later removal (each linked child's /// exit) scanned all of it, and n exits took time quadratic in n. /// Compaction now keeps each pid's first copy only. #[test] fn a_pid_linked_again_many_times_leaves_removals_cheap() { let mut links = Links::default(); let children = 2000; for pid in 0..children { links.insert(pid); } let relinked = -1; links.insert(relinked); for _ in 0..5 * children { links.remove(relinked); links.insert(relinked); } for pid in 0..children { links.remove(pid); let Links::Many { order, live } = &links else { panic!("still a set"); }; // `remove` compacts once `order` is past this: when compacting // leaves it past this still, the next removal scans it again. assert!( order.len() <= 2 * live.len() + 16, "after child {pid}'s exit: {} entries in order for {} links", order.len(), live.len() ); } assert_eq!(links.into_vec(), [relinked]); } /// A remote pid's link through Erlang's unlinking state: an exit or a /// link from the pid is ignored until the acknowledgement of the /// unlink; a link from this side overrides the unlink, whose /// acknowledgement then changes nothing; a lost node forgets it. #[test] fn a_remote_unlink_waits_for_its_acknowledgement() { let mut ties = Ties::default(); let (p, q) = (-5, -6); ties.links.insert(p); ties.links.insert(q); assert!(ties.unlink_remote(p, 1)); assert!(!ties.unlink_remote(p, 2), "unlinking already"); assert!(!ties.links.remove(p), "an exit through it is ignored"); assert!(!ties.linked_by(p), "a link sent before the unlink arrived"); assert!(!ties.unlink_acked(p, 2), "no unlink 2"); assert!(!ties.unlink_acked(q, 1), "no unlink of q"); assert!(ties.unlink_acked(p, 1)); assert!(ties.linked_by(p), "a link sent after"); assert!(ties.unlink_remote(p, 3)); ties.link_remote(p); assert!(!ties.unlink_acked(p, 3), "linked again since"); assert!(ties.links.remove(p), "still linked"); assert!(ties.unlink_remote(q, 4)); let (links, _) = ties.take(|pid| pid == q); assert!(links.is_empty()); assert!( ties.unlinking.is_empty(), "the lost node's unlink forgotten" ); } /// Erlang's link protocol between actors of two nodes, with `Ties`'s /// steps as `dist` takes them (a frame is sent in the step that /// decides it, as under the actor's lock): every interleaving of each /// side's operations, in order, with the frames on the two ordered /// streams leaves both sides agreeing on whether they are linked, with /// no unlink left waiting. #[test] fn crossing_links_and_unlinks_leave_both_sides_agreeing() { #[derive(Clone, Copy, Debug)] enum Op { Link, Unlink, } #[derive(Clone, Copy, Debug)] enum Frame { Link, Unlink(u64), Ack(u64), } /// One side: its actor's ties, the pid it knows the other by, its /// operations left, its last unlink's id, and the frames the other /// side sent it, in order. #[derive(Clone)] struct Side { ties: Ties, peer: i64, ops: VecDeque, ids: u64, frames: VecDeque, } /// Side `s` performs its next operation. fn operate(sides: &mut [Side; 2], s: usize) -> String { let side = &mut sides[s]; let op = side.ops.pop_front().expect("an operation"); let frame = match op { Op::Link => { side.ties.link_remote(side.peer); Some(Frame::Link) } Op::Unlink => { side.ids += 1; let id = side.ids; side.ties .unlink_remote(side.peer, id) .then_some(Frame::Unlink(id)) } }; sides[1 - s].frames.extend(frame); format!("{s}: {op:?} -> {frame:?}") } /// Side `s` takes the next frame the other sent it. fn take(sides: &mut [Side; 2], s: usize) -> String { let side = &mut sides[s]; let frame = side.frames.pop_front().expect("a frame"); match frame { Frame::Link => { side.ties.linked_by(side.peer); } Frame::Unlink(id) => { side.ties.links.remove(side.peer); sides[1 - s].frames.push_back(Frame::Ack(id)); } Frame::Ack(id) => { side.ties.unlink_acked(side.peer, id); } } format!("{s} takes {frame:?}") } fn explore(sides: [Side; 2], trace: &mut Vec, leaves: &mut usize) { let mut moved = false; for s in 0..2 { type Step = fn(&mut [Side; 2], usize) -> String; let steps: [(bool, Step); 2] = [ (!sides[s].ops.is_empty(), operate), (!sides[s].frames.is_empty(), take), ]; for (_, step) in steps.into_iter().filter(|(can, _)| *can) { moved = true; let mut next = sides.clone(); trace.push(step(&mut next, s)); explore(next, trace, leaves); trace.pop(); } } if moved { return; } *leaves += 1; let linked = |side: &Side| side.ties.links.contains(side.peer); assert_eq!(linked(&sides[0]), linked(&sides[1]), "{trace:#?}"); let waiting = |side: &Side| side.ties.unlinks(); assert_eq!((waiting(&sides[0]), waiting(&sides[1])), (vec![], vec![])); } use Op::{Link, Unlink}; let scenarios: [(bool, &[Op], &[Op]); 7] = [ (true, &[Unlink, Link], &[Unlink]), (true, &[Unlink], &[Link]), (true, &[Link], &[Unlink, Link]), (true, &[Unlink, Link, Unlink], &[Unlink, Link]), (false, &[Link], &[Link, Unlink]), (false, &[Link, Unlink, Link], &[Link, Unlink]), (false, &[Link, Unlink], &[Link, Unlink, Link]), ]; for (linked, a, b) in scenarios { let side = |peer: i64, ops: &[Op]| { let mut ties = Ties::default(); if linked { ties.links.insert(peer); } Side { ties, peer, ops: ops.iter().copied().collect(), ids: 0, frames: VecDeque::new(), } }; let mut leaves = 0; explore([side(-2, a), side(-1, b)], &mut Vec::new(), &mut leaves); assert!(leaves > 1, "{a:?} {b:?}"); } } }