
louise
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runRéussi#1201 · main · 9 min 57 s
1Étoiles
0Forks
0Issues
| 1 | //! An actor's OTP state ([`Proc`]): its mailbox, what it waits for, its |
| 2 | //! links and monitors. Timers, kills and the actor itself change it under |
| 3 | //! the actor's lock (ADR 0004, Revision 2), each through one method here, |
| 4 | //! so that loom models check the code the scheduler runs |
| 5 | //! (`RUSTFLAGS="--cfg loom" cargo test -p louise_rt --release --lib otp inbox`). |
| 6 | //! |
| 7 | //! Senders do not take the lock (ADR 0028): they push onto the actor's |
| 8 | //! [`Inbox`], and take the lock only when their push found the actor |
| 9 | //! waiting, to wake it ([`Proc::woken_by_message`]). The actor moves what |
| 10 | //! its inbox holds into its mailbox, under its lock, when it receives. A |
| 11 | //! receive woken by a message on another tag finds nothing, and waits |
| 12 | //! again, in the same wait (its timer still applies). |
| 13 | //! |
| 14 | //! `Proc` is generic in the values it holds and in the fiber: the runtime |
| 15 | //! uses `Proc<Value, Fiber>`, the models plain data. Taking the lock is the |
| 16 | //! caller's job. |
| 17 | |
| 18 | use std::collections::VecDeque; |
| 19 | |
| 20 | use crate::handoff::RunState; |
| 21 | use crate::inbox::Inbox; |
| 22 | use crate::sched::{IdHasher, IdMap}; |
| 23 | |
| 24 | /// What parked operations return, made under the lock. |
| 25 | pub(crate) trait Answer: Sized + PartialEq { |
| 26 | /// A received message: `Some(message)`, or `Some((tag, message))` |
| 27 | /// for `receive_any`. |
| 28 | fn received(message: Self, tag: Option<i64>) -> Self; |
| 29 | /// `None`: no message before the timeout. |
| 30 | fn timed_out() -> Self; |
| 31 | /// `()`: a sleep ended, a socket is ready, or the wait was interrupted. |
| 32 | fn unit() -> Self; |
| 33 | } |
| 34 | |
| 35 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 36 | pub(crate) enum Wait { |
| 37 | Ready, |
| 38 | /// Waiting for a message on one of the actor's `waiting_tags`. |
| 39 | Receive { |
| 40 | deadline: Option<u64>, |
| 41 | }, |
| 42 | Sleep { |
| 43 | deadline: u64, |
| 44 | }, |
| 45 | /// In a `blocking` extern call (never woken early, not even by a kill). |
| 46 | Blocking, |
| 47 | /// Waiting for a socket (`net`). |
| 48 | Io, |
| 49 | } |
| 50 | |
| 51 | /// The tags a receive waits on: one for `receive`, several for |
| 52 | /// `receive_any`. One is kept inline: a waiting actor holds its tags, and |
| 53 | /// most waiting actors wait on one subject. |
| 54 | pub(crate) enum Tags { |
| 55 | One(i64), |
| 56 | Many(Vec<i64>), |
| 57 | } |
| 58 | |
| 59 | impl Tags { |
| 60 | #[cfg(test)] |
| 61 | fn of(tags: &[i64]) -> Tags { |
| 62 | match tags { |
| 63 | [one] => Tags::One(*one), |
| 64 | many => Tags::Many(many.to_vec()), |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | fn as_slice(&self) -> &[i64] { |
| 69 | match self { |
| 70 | Tags::One(tag) => std::slice::from_ref(tag), |
| 71 | Tags::Many(tags) => tags, |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | /// How long a receive waits. |
| 77 | #[derive(Clone, Copy)] |
| 78 | pub(crate) enum Timeout { |
| 79 | /// Not at all: `receive(_, 0)`. |
| 80 | Zero, |
| 81 | /// Until this time on the scheduler's clock. |
| 82 | At(u64), |
| 83 | Never, |
| 84 | } |
| 85 | |
| 86 | /// What a receive did. |
| 87 | pub(crate) enum Received<V> { |
| 88 | /// It took a message (or timed out at once): what it returns. |
| 89 | Now(V), |
| 90 | /// The actor waits; the wait's number, for its timer. |
| 91 | Parked(u64), |
| 92 | } |
| 93 | |
| 94 | /// What an exit leaves to its caller (after releasing the lock). |
| 95 | pub(crate) struct Exited { |
| 96 | /// The linked actors, to stop or signal, in the order they were linked. |
| 97 | pub(crate) links: Vec<i64>, |
| 98 | /// (watcher, tag): who receives `Down`. |
| 99 | pub(crate) monitors: Vec<(i64, i64)>, |
| 100 | /// The nodes `dist` lists it under ([`Ties::nodes`]). |
| 101 | pub(crate) nodes: Vec<u16>, |
| 102 | /// Whether the actor must be scheduled, to unwind. |
| 103 | pub(crate) wake: bool, |
| 104 | } |
| 105 | |
| 106 | /// An actor's links and monitors, and how it takes exit signals. |
| 107 | #[derive(Default)] |
| 108 | #[cfg_attr(test, derive(Clone))] |
| 109 | pub(crate) struct Ties { |
| 110 | /// Its halves of its links: an exit through a link counts only while |
| 111 | /// its receiver still has its half. |
| 112 | pub(crate) links: Links, |
| 113 | /// pid -> id: the remote pids this actor unlinked, until their node |
| 114 | /// acknowledges unlink `id` (Erlang's *unlinking* state, `dist`). Not |
| 115 | /// in `links`: an exit through the link is ignored at once. A link |
| 116 | /// from that pid is ignored too, so the two sides end unlinked; a link |
| 117 | /// from this actor overrides the unlink. At most one per pid (an |
| 118 | /// unlink needs a link, which ends the one before), and a map: a peer |
| 119 | /// that never acknowledges keeps them until its loss, and each op |
| 120 | /// `10` or `18` to this actor looks one up. |
| 121 | pub(crate) unlinking: IdMap<u64>, |
| 122 | /// (watcher, tag): who receives `Down` when this actor exits. A remote |
| 123 | /// watcher's goes out through the transport (`dist`). |
| 124 | pub(crate) monitors: Vec<(i64, i64)>, |
| 125 | /// (pid, tag): the remote actors this one monitors, its `Down` due on |
| 126 | /// `tag` (`dist`). A local monitor is kept by the actor it watches. |
| 127 | pub(crate) watching: Vec<(i64, i64)>, |
| 128 | /// The nodes `dist` lists this actor under, as tied to them: every |
| 129 | /// node it linked or monitored a pid of, or one of whose pids linked or |
| 130 | /// monitored it, since, until that node is lost. Its exit unlists it |
| 131 | /// from each, whether or not ties to it remain. |
| 132 | pub(crate) nodes: Vec<u16>, |
| 133 | pub(crate) trap: bool, |
| 134 | pub(crate) exits_tag: Option<i64>, |
| 135 | } |
| 136 | |
| 137 | impl Ties { |
| 138 | /// Note a tie to a pid of `node`; whether `dist` must list this actor |
| 139 | /// under it (the node is new to it). |
| 140 | pub(crate) fn tie(&mut self, node: u16) -> bool { |
| 141 | let new = !self.nodes.contains(&node); |
| 142 | if new { |
| 143 | self.nodes.push(node); |
| 144 | } |
| 145 | new |
| 146 | } |
| 147 | |
| 148 | /// Forget the monitor of the remote `pid` on `tag`; whether there was |
| 149 | /// one. |
| 150 | pub(crate) fn unwatch(&mut self, pid: i64, tag: i64) -> bool { |
| 151 | let found = self.watching.iter().position(|w| *w == (pid, tag)); |
| 152 | found.map(|i| self.watching.remove(i)).is_some() |
| 153 | } |
| 154 | |
| 155 | /// This actor links the remote `pid`: a new link, whatever unlink of |
| 156 | /// it still waits for its acknowledgement. |
| 157 | pub(crate) fn link_remote(&mut self, pid: i64) { |
| 158 | self.unlinking.remove(&pid); |
| 159 | self.links.insert(pid); |
| 160 | } |
| 161 | |
| 162 | /// The remote `pid` links this actor: whether it is linked now. Not |
| 163 | /// while this actor's unlink of it waits for its acknowledgement: |
| 164 | /// that link was sent before the unlink reached `pid`'s node, which |
| 165 | /// removes `pid`'s half, so both sides end unlinked. |
| 166 | pub(crate) fn linked_by(&mut self, pid: i64) -> bool { |
| 167 | if self.unlinking.contains_key(&pid) { |
| 168 | return false; |
| 169 | } |
| 170 | self.links.insert(pid); |
| 171 | true |
| 172 | } |
| 173 | |
| 174 | /// This actor unlinks the remote `pid` as unlink `id`: its half waits |
| 175 | /// for the acknowledgement. Whether it had one (then the unlink goes to |
| 176 | /// `pid`'s node). |
| 177 | pub(crate) fn unlink_remote(&mut self, pid: i64, id: u64) -> bool { |
| 178 | let linked = self.links.remove(pid); |
| 179 | if linked { |
| 180 | self.unlinking.insert(pid, id); |
| 181 | } |
| 182 | linked |
| 183 | } |
| 184 | |
| 185 | /// The remote `pid` acknowledged unlink `id`: forget it, unless this |
| 186 | /// actor linked `pid` again since. Whether it did. |
| 187 | pub(crate) fn unlink_acked(&mut self, pid: i64, id: u64) -> bool { |
| 188 | let found = self.unlinking.get(&pid) == Some(&id); |
| 189 | if found { |
| 190 | self.unlinking.remove(&pid); |
| 191 | } |
| 192 | found |
| 193 | } |
| 194 | |
| 195 | /// Take the links and monitors of the pids `lost` picks (a lost node's |
| 196 | /// pids), each in its order, and forget the monitors they hold on this |
| 197 | /// actor, no `Down` can reach them, and the unlinks waiting for them, |
| 198 | /// whose acknowledgement cannot come. |
| 199 | pub(crate) fn take(&mut self, lost: impl Fn(i64) -> bool) -> (Vec<i64>, Vec<(i64, i64)>) { |
| 200 | let (links, kept): (Vec<i64>, Vec<i64>) = std::mem::take(&mut self.links) |
| 201 | .into_vec() |
| 202 | .into_iter() |
| 203 | .partition(|p| lost(*p)); |
| 204 | for p in kept { |
| 205 | self.links.insert(p); |
| 206 | } |
| 207 | self.unlinking.retain(|p, _| !lost(*p)); |
| 208 | let (watching, kept) = std::mem::take(&mut self.watching) |
| 209 | .into_iter() |
| 210 | .partition(|(p, _)| lost(*p)); |
| 211 | self.watching = kept; |
| 212 | self.monitors.retain(|(watcher, _)| !lost(*watcher)); |
| 213 | (links, watching) |
| 214 | } |
| 215 | |
| 216 | /// The unlinks waiting for their acknowledgement, as (pid, id), by pid. |
| 217 | #[cfg(all(test, not(loom)))] |
| 218 | pub(crate) fn unlinks(&self) -> Vec<(i64, u64)> { |
| 219 | let mut unlinks: Vec<_> = self.unlinking.iter().map(|(p, id)| (*p, *id)).collect(); |
| 220 | unlinks.sort_unstable(); |
| 221 | unlinks |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | /// The actors an actor is linked to, in the order they were linked (the |
| 226 | /// order exits propagate in). |
| 227 | /// |
| 228 | /// Most linked actors have one link (to the actor that spawned them), and |
| 229 | /// it is kept inline. More make a set, so that membership and removal take |
| 230 | /// constant time: an actor linked to each of 100,000 short-lived children |
| 231 | /// removed each child from a vector as it exited, quadratic time that |
| 232 | /// dominated `tests/stress/actors.lse` (issue #61). The set alone cost |
| 233 | /// each linked child three allocations, and 10-20% on 4-22 threads (issue |
| 234 | /// #104). |
| 235 | #[derive(Default)] |
| 236 | #[cfg_attr(test, derive(Clone))] |
| 237 | pub(crate) enum Links { |
| 238 | #[default] |
| 239 | None, |
| 240 | One(i64), |
| 241 | Many { |
| 242 | /// Insertion order; removed links stay until compacted, and a pid |
| 243 | /// linked again is pushed again (its first copy is its place). |
| 244 | order: Vec<i64>, |
| 245 | live: std::collections::HashSet<i64, std::hash::BuildHasherDefault<IdHasher>>, |
| 246 | }, |
| 247 | } |
| 248 | |
| 249 | impl Links { |
| 250 | fn is_empty(&self) -> bool { |
| 251 | match self { |
| 252 | Links::None => true, |
| 253 | Links::One(_) => false, |
| 254 | Links::Many { live, .. } => live.is_empty(), |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | /// Link `pid`, unless it already is. |
| 259 | pub(crate) fn insert(&mut self, pid: i64) { |
| 260 | match self { |
| 261 | Links::None => *self = Links::One(pid), |
| 262 | Links::One(p) if *p == pid => {} |
| 263 | Links::One(p) => { |
| 264 | let order = vec![*p, pid]; |
| 265 | let live = order.iter().copied().collect(); |
| 266 | *self = Links::Many { order, live }; |
| 267 | } |
| 268 | Links::Many { order, live } => { |
| 269 | if live.insert(pid) { |
| 270 | order.push(pid); |
| 271 | } |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | /// Unlink `pid`; whether it was linked. |
| 277 | pub(crate) fn remove(&mut self, pid: i64) -> bool { |
| 278 | match self { |
| 279 | Links::None => false, |
| 280 | Links::One(p) => { |
| 281 | let linked = *p == pid; |
| 282 | if linked { |
| 283 | *self = Links::None; |
| 284 | } |
| 285 | linked |
| 286 | } |
| 287 | Links::Many { order, live } => { |
| 288 | let linked = live.remove(&pid); |
| 289 | if linked && order.len() > 2 * live.len() + 16 { |
| 290 | // Keep each linked pid's first copy only, the place |
| 291 | // `into_vec` gives it: a pid unlinked and linked again |
| 292 | // has one copy per link, and keeping them all would |
| 293 | // leave `order` past the bound, rescanned by every |
| 294 | // later removal. |
| 295 | let mut first = live.clone(); |
| 296 | order.retain(|p| first.remove(p)); |
| 297 | } |
| 298 | linked |
| 299 | } |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | /// Whether `pid` is linked. |
| 304 | #[cfg(test)] |
| 305 | pub(crate) fn contains(&self, pid: i64) -> bool { |
| 306 | match self { |
| 307 | Links::None => false, |
| 308 | Links::One(p) => *p == pid, |
| 309 | Links::Many { live, .. } => live.contains(&pid), |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | /// The linked actors, in order. |
| 314 | pub(crate) fn into_vec(self) -> Vec<i64> { |
| 315 | match self { |
| 316 | Links::None => Vec::new(), |
| 317 | Links::One(p) => vec![p], |
| 318 | Links::Many { order, mut live } => { |
| 319 | // `remove` on a pid seen twice (unlinked, then linked |
| 320 | // again) keeps its first place. |
| 321 | order.into_iter().filter(|p| live.remove(p)).collect() |
| 322 | } |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | /// Messages by subject tag, each with its arrival number: receiving from |
| 328 | /// one subject is O(1) however many other messages wait, and |
| 329 | /// `receive_any` still takes the oldest of several subjects. |
| 330 | pub(crate) struct Mailbox<V> { |
| 331 | by_tag: IdMap<VecDeque<(u64, V)>>, |
| 332 | arrived: u64, |
| 333 | } |
| 334 | |
| 335 | impl<V> Default for Mailbox<V> { |
| 336 | fn default() -> Self { |
| 337 | Mailbox { |
| 338 | by_tag: IdMap::default(), |
| 339 | arrived: 0, |
| 340 | } |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | impl<V> Mailbox<V> { |
| 345 | fn push(&mut self, tag: i64, message: V) { |
| 346 | self.arrived += 1; |
| 347 | self.by_tag |
| 348 | .entry(tag) |
| 349 | .or_default() |
| 350 | .push_back((self.arrived, message)); |
| 351 | } |
| 352 | |
| 353 | /// The oldest message on one of `tags`, with its tag. |
| 354 | fn take(&mut self, tags: &[i64]) -> Option<(i64, V)> { |
| 355 | let tag = tags |
| 356 | .iter() |
| 357 | .filter_map(|t| Some((self.by_tag.get(t)?.front()?.0, *t))) |
| 358 | .min()? |
| 359 | .1; |
| 360 | let queue = self.by_tag.get_mut(&tag)?; |
| 361 | let (_, message) = queue.pop_front()?; |
| 362 | if queue.is_empty() { |
| 363 | self.by_tag.remove(&tag); |
| 364 | } |
| 365 | Some((tag, message)) |
| 366 | } |
| 367 | |
| 368 | /// Every message left, to drop. |
| 369 | fn is_empty(&self) -> bool { |
| 370 | self.by_tag.is_empty() |
| 371 | } |
| 372 | |
| 373 | pub(crate) fn drain(&mut self) -> impl Iterator<Item = V> { |
| 374 | std::mem::take(&mut self.by_tag) |
| 375 | .into_values() |
| 376 | .flatten() |
| 377 | .map(|(_, message)| message) |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | /// The oldest message on one of `tags`: in the mailbox, which holds the |
| 382 | /// older ones, else the first such in the inbox, whose other messages are |
| 383 | /// filed in the mailbox. A message a receive is waiting for skips the |
| 384 | /// mailbox: filing and taking it again (a queue made and freed per |
| 385 | /// message) cost 15% of `tests/bench/messages.lse`. |
| 386 | fn take_wanted<V>(mailbox: &mut Mailbox<V>, inbox: &Inbox<V>, tags: &[i64]) -> Option<(i64, V)> { |
| 387 | if !mailbox.is_empty() |
| 388 | && let Some(older) = mailbox.take(tags) |
| 389 | { |
| 390 | return Some(older); |
| 391 | } |
| 392 | let mut wanted = None; |
| 393 | inbox.take(|tag, message| { |
| 394 | if wanted.is_none() && tags.contains(&tag) { |
| 395 | wanted = Some((tag, message)); |
| 396 | } else { |
| 397 | mailbox.push(tag, message); |
| 398 | } |
| 399 | }); |
| 400 | wanted |
| 401 | } |
| 402 | |
| 403 | pub(crate) struct Proc<V, F> { |
| 404 | mailbox: Mailbox<V>, |
| 405 | pub(crate) wait: Wait, |
| 406 | /// What a parked operation returns when woken. |
| 407 | wake: V, |
| 408 | /// Allocated when first used: most actors have none (ADR 0028). |
| 409 | ties: Option<Box<Ties>>, |
| 410 | /// While `wait` is `Receive`: the tags waited on, and whether the |
| 411 | /// answer carries the tag (`receive_any`). |
| 412 | waiting_tags: Tags, |
| 413 | waiting_any: bool, |
| 414 | /// Counts waits, so a timer set for an earlier one is ignored. |
| 415 | wait_gen: u64, |
| 416 | /// The current receive's timer fired. |
| 417 | timed_out: bool, |
| 418 | /// Exited (logically); its fiber may still have to unwind. |
| 419 | pub(crate) dead: bool, |
| 420 | pub(crate) run: RunState<F>, |
| 421 | } |
| 422 | |
| 423 | impl<V: Answer, F> Proc<V, F> { |
| 424 | /// A new actor, queued (its caller pushes it right after). |
| 425 | pub(crate) fn new(fiber: F, links: Links, monitors: Vec<(i64, i64)>) -> Self { |
| 426 | let mut run = RunState::new(fiber); |
| 427 | run.queue_new(); |
| 428 | Proc { |
| 429 | mailbox: Mailbox::default(), |
| 430 | wait: Wait::Ready, |
| 431 | wake: V::unit(), |
| 432 | ties: (!links.is_empty() || !monitors.is_empty()).then(|| { |
| 433 | Box::new(Ties { |
| 434 | links, |
| 435 | monitors, |
| 436 | ..Ties::default() |
| 437 | }) |
| 438 | }), |
| 439 | waiting_tags: Tags::Many(Vec::new()), |
| 440 | waiting_any: false, |
| 441 | wait_gen: 0, |
| 442 | timed_out: false, |
| 443 | dead: false, |
| 444 | run, |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | /// A push found the actor waiting ([`Inbox::push`]): wake it if it |
| 449 | /// still waits for a message. Returns whether the caller must schedule |
| 450 | /// it. (The actor finds the message itself, in its inbox.) |
| 451 | pub(crate) fn woken_by_message(&mut self) -> bool { |
| 452 | matches!(self.wait, Wait::Receive { .. }) && self.run.wake() |
| 453 | } |
| 454 | |
| 455 | /// Whether the actor waits in a receive on `tag`. |
| 456 | pub(crate) fn waits_for(&self, tag: i64) -> bool { |
| 457 | matches!(self.wait, Wait::Receive { .. }) && self.waiting_tags.as_slice().contains(&tag) |
| 458 | } |
| 459 | |
| 460 | /// Its links, monitors and exit-signal settings, allocated now if they |
| 461 | /// were not. |
| 462 | pub(crate) fn ties(&mut self) -> &mut Ties { |
| 463 | self.ties.get_or_insert_with(Box::default) |
| 464 | } |
| 465 | |
| 466 | /// Make this actor's half of a link to `pid`, unless it exited: |
| 467 | /// whether it did. |
| 468 | pub(crate) fn link(&mut self, pid: i64) -> bool { |
| 469 | if self.dead { |
| 470 | return false; |
| 471 | } |
| 472 | self.ties().links.insert(pid); |
| 473 | true |
| 474 | } |
| 475 | |
| 476 | /// Remove this actor's half of its link to `pid`: whether it had it |
| 477 | /// (an exit through the link counts only then), and whether this |
| 478 | /// actor traps exits. |
| 479 | pub(crate) fn unlink(&mut self, pid: i64) -> (bool, bool) { |
| 480 | self.ties |
| 481 | .as_mut() |
| 482 | .map_or((false, false), |t| (t.links.remove(pid), t.trap)) |
| 483 | } |
| 484 | |
| 485 | /// This actor, alive, unlinks the remote `pid` as unlink `id` |
| 486 | /// ([`Ties::unlink_remote`]): whether it had a link to it. |
| 487 | pub(crate) fn unlink_remote(&mut self, pid: i64, id: u64) -> bool { |
| 488 | !self.dead && self.ties.as_mut().is_some_and(|t| t.unlink_remote(pid, id)) |
| 489 | } |
| 490 | |
| 491 | /// [`Ties::unlink_acked`]. |
| 492 | pub(crate) fn unlink_acked(&mut self, pid: i64, id: u64) -> bool { |
| 493 | self.ties.as_mut().is_some_and(|t| t.unlink_acked(pid, id)) |
| 494 | } |
| 495 | |
| 496 | /// `watcher` stops monitoring this actor on `tag` (`demonitor`): |
| 497 | /// whether it did. |
| 498 | pub(crate) fn demonitor(&mut self, watcher: i64, tag: i64) -> bool { |
| 499 | let Some(ties) = self.ties.as_mut() else { |
| 500 | return false; |
| 501 | }; |
| 502 | let found = ties.monitors.iter().position(|m| *m == (watcher, tag)); |
| 503 | found.map(|i| ties.monitors.remove(i)).is_some() |
| 504 | } |
| 505 | |
| 506 | /// Forget this actor's monitor of the remote `pid` on `tag` |
| 507 | /// ([`Ties::unwatch`]); whether there was one. |
| 508 | pub(crate) fn unwatch(&mut self, pid: i64, tag: i64) -> bool { |
| 509 | self.ties.as_mut().is_some_and(|t| t.unwatch(pid, tag)) |
| 510 | } |
| 511 | |
| 512 | /// A sender that claimed the actor's wait ([`Inbox::claim_waiting`], |
| 513 | /// after [`Proc::waits_for`]): the receive returns `message`. Returns |
| 514 | /// whether the caller must schedule the actor. |
| 515 | pub(crate) fn hand_over(&mut self, tag: i64, message: V) -> bool { |
| 516 | debug_assert!(self.waits_for(tag)); |
| 517 | let answer = V::received(message, self.waiting_any.then_some(tag)); |
| 518 | self.wake(answer) |
| 519 | } |
| 520 | |
| 521 | /// Move what the inbox holds into the mailbox. |
| 522 | fn file(&mut self, inbox: &Inbox<V>) { |
| 523 | let mailbox = &mut self.mailbox; |
| 524 | inbox.take(|tag, message| mailbox.push(tag, message)); |
| 525 | } |
| 526 | |
| 527 | /// Take the oldest message on one of `tags`, or else wait for one |
| 528 | /// (then the caller parks, after setting the timer). `any`: the answer |
| 529 | /// carries the tag. |
| 530 | pub(crate) fn receive( |
| 531 | &mut self, |
| 532 | inbox: &Inbox<V>, |
| 533 | tags: Tags, |
| 534 | any: bool, |
| 535 | timeout: Timeout, |
| 536 | ) -> Received<V> { |
| 537 | if let Some((tag, message)) = take_wanted(&mut self.mailbox, inbox, tags.as_slice()) { |
| 538 | return Received::Now(V::received(message, any.then_some(tag))); |
| 539 | } |
| 540 | let deadline = match timeout { |
| 541 | Timeout::Zero => return Received::Now(V::timed_out()), |
| 542 | Timeout::At(d) => Some(d), |
| 543 | Timeout::Never => None, |
| 544 | }; |
| 545 | self.waiting_tags = tags; |
| 546 | self.waiting_any = any; |
| 547 | self.timed_out = false; |
| 548 | Received::Parked(self.park_as(Wait::Receive { deadline })) |
| 549 | } |
| 550 | |
| 551 | /// The actor, parked by [`Proc::receive`], runs again: what the |
| 552 | /// receive returns, or `None` if it must wait again (woken by a message |
| 553 | /// on another tag). |
| 554 | pub(crate) fn receive_woken(&mut self, inbox: &Inbox<V>) -> Option<V> { |
| 555 | let handed = self.take_wake(); |
| 556 | if handed != V::unit() { |
| 557 | // A message handed over (`hand_over`): never unit, since a |
| 558 | // received message comes wrapped (`Answer::received`). |
| 559 | return Some(handed); |
| 560 | } |
| 561 | if let Some((tag, message)) = |
| 562 | take_wanted(&mut self.mailbox, inbox, self.waiting_tags.as_slice()) |
| 563 | { |
| 564 | self.wait = Wait::Ready; |
| 565 | return Some(V::received(message, self.waiting_any.then_some(tag))); |
| 566 | } |
| 567 | if self.timed_out || self.wait == Wait::Ready { |
| 568 | // Only a timer or an exit end a receive; an exit unwinds the |
| 569 | // actor before it gets here. |
| 570 | debug_assert!(self.timed_out, "louise: a receive ended for nothing"); |
| 571 | self.timed_out = false; |
| 572 | self.wait = Wait::Ready; |
| 573 | return Some(V::timed_out()); |
| 574 | } |
| 575 | None |
| 576 | } |
| 577 | |
| 578 | /// Make the actor ready; its parked operation returns `value`. |
| 579 | /// Returns whether the caller must schedule it (after releasing the |
| 580 | /// lock). |
| 581 | pub(crate) fn wake(&mut self, value: V) -> bool { |
| 582 | self.wait = Wait::Ready; |
| 583 | self.wake = value; |
| 584 | self.run.wake() |
| 585 | } |
| 586 | |
| 587 | /// Wake it if it is still in `Io` wait number `wait`, not a later one |
| 588 | /// (a sender parked on a peer's full queue, `dist::send_parking`). |
| 589 | /// Returns whether the caller must schedule it. |
| 590 | pub(crate) fn resume(&mut self, wait: u64) -> bool { |
| 591 | self.wait_gen == wait && self.wait == Wait::Io && self.wake(V::unit()) |
| 592 | } |
| 593 | |
| 594 | /// Wake it unless it is ready or in a blocking call. |
| 595 | pub(crate) fn interrupt(&mut self) -> bool { |
| 596 | if self.wait != Wait::Ready && self.wait != Wait::Blocking { |
| 597 | return self.wake(V::unit()); |
| 598 | } |
| 599 | false |
| 600 | } |
| 601 | |
| 602 | /// Start waiting as `wait`; returns the wait's number, for its timer. |
| 603 | /// |
| 604 | /// An actor that exited while it ran (killed, or a linked actor |
| 605 | /// crashed) does not wait: its exit found it ready, so nothing would |
| 606 | /// wake it. It stays ready, its thread queues it again when it yields, |
| 607 | /// and it unwinds. Except in a blocking call, which runs to its end |
| 608 | /// (it still reads the actor's values). |
| 609 | pub(crate) fn park_as(&mut self, wait: Wait) -> u64 { |
| 610 | self.wait_gen += 1; |
| 611 | if !self.dead || wait == Wait::Blocking { |
| 612 | self.wait = wait; |
| 613 | } |
| 614 | self.wait_gen |
| 615 | } |
| 616 | |
| 617 | /// Whether the actor is still in wait number `wait`, until `deadline` |
| 618 | /// (else that wait's timer no longer applies). |
| 619 | pub(crate) fn waits_until(&self, wait: u64, deadline: u64) -> bool { |
| 620 | let current = match self.wait { |
| 621 | Wait::Receive { |
| 622 | deadline: Some(d), .. |
| 623 | } |
| 624 | | Wait::Sleep { deadline: d } => Some(d), |
| 625 | _ => None, |
| 626 | }; |
| 627 | self.wait_gen == wait && current == Some(deadline) |
| 628 | } |
| 629 | |
| 630 | /// The timer of wait number `wait` is due: end that wait, if it is |
| 631 | /// still on. A receive returns `None` ([`Proc::receive_woken`]), a |
| 632 | /// sleep `()`. Returns whether the caller must schedule the actor. |
| 633 | pub(crate) fn time_out(&mut self, wait: u64, deadline: u64) -> bool { |
| 634 | if !self.waits_until(wait, deadline) { |
| 635 | return false; |
| 636 | } |
| 637 | if matches!(self.wait, Wait::Receive { .. }) { |
| 638 | self.timed_out = true; |
| 639 | } |
| 640 | self.wake(V::unit()) |
| 641 | } |
| 642 | |
| 643 | /// The actor exits: from now on, messages are refused and its wait is |
| 644 | /// interrupted. `None` if it had already exited. |
| 645 | pub(crate) fn exit(&mut self, inbox: &Inbox<V>) -> Option<Exited> { |
| 646 | if self.dead { |
| 647 | return None; |
| 648 | } |
| 649 | self.dead = true; |
| 650 | // A receive it waits in is interrupted below, like any other wait. |
| 651 | inbox.close(); |
| 652 | let ties = self.ties.take().map(|t| *t).unwrap_or_default(); |
| 653 | Some(Exited { |
| 654 | links: ties.links.into_vec(), |
| 655 | monitors: ties.monitors, |
| 656 | nodes: ties.nodes, |
| 657 | wake: self.interrupt(), |
| 658 | }) |
| 659 | } |
| 660 | |
| 661 | /// What the woken operation returns (the actor resumed). |
| 662 | pub(crate) fn take_wake(&mut self) -> V { |
| 663 | std::mem::replace(&mut self.wake, V::unit()) |
| 664 | } |
| 665 | |
| 666 | /// The actor's fiber yielded: whether the caller must queue it again |
| 667 | /// (it was preempted, or woken before it stopped). A receive waits on |
| 668 | /// its inbox from here, its fiber suspended: unless messages arrived |
| 669 | /// meanwhile, or it exited, the next push wakes it. |
| 670 | pub(crate) fn stop(&mut self, inbox: &Inbox<V>, fiber: F) -> bool { |
| 671 | let ready = match self.wait { |
| 672 | Wait::Ready => true, |
| 673 | Wait::Receive { .. } => !inbox.park(), |
| 674 | _ => false, |
| 675 | }; |
| 676 | self.run.stop(fiber, ready) |
| 677 | } |
| 678 | |
| 679 | /// What the actor still holds once it exited, to drop: its inbox is |
| 680 | /// closed, so nothing arrives any more. |
| 681 | pub(crate) fn release(&mut self, inbox: &Inbox<V>) -> (Mailbox<V>, V) { |
| 682 | debug_assert!(self.dead); |
| 683 | self.file(inbox); |
| 684 | (std::mem::take(&mut self.mailbox), self.take_wake()) |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | /// The models' values: messages are numbered, so that each can be found |
| 689 | /// again wherever it ended up. |
| 690 | #[cfg(test)] |
| 691 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 692 | enum Val { |
| 693 | Unit, |
| 694 | TimedOut, |
| 695 | Message(u32), |
| 696 | Received(u32, Option<i64>), |
| 697 | } |
| 698 | |
| 699 | #[cfg(test)] |
| 700 | impl Answer for Val { |
| 701 | fn received(message: Val, tag: Option<i64>) -> Val { |
| 702 | match message { |
| 703 | Val::Message(n) => Val::Received(n, tag), |
| 704 | other => panic!("not a message: {other:?}"), |
| 705 | } |
| 706 | } |
| 707 | |
| 708 | fn timed_out() -> Val { |
| 709 | Val::TimedOut |
| 710 | } |
| 711 | |
| 712 | fn unit() -> Val { |
| 713 | Val::Unit |
| 714 | } |
| 715 | } |
| 716 | |
| 717 | #[cfg(all(test, loom))] |
| 718 | mod loom_models { |
| 719 | //! Each model plays an actor's receive on the main thread, as |
| 720 | //! `process::take_or_wait` and `wait_for_message` do, against senders |
| 721 | //! (as `Shared::deliver`), timers and kills on other threads. The |
| 722 | //! actor starts running, as the thread that took it from a run queue |
| 723 | //! leaves it. When its fiber yields, its thread stops it (`run_slice`); |
| 724 | //! then it runs again once someone queued it. `queued` is its run |
| 725 | //! queue: a lost wake-up leaves the actor waiting there for good, which |
| 726 | //! loom reports as a deadlock; a doubled one leaves an entry behind. |
| 727 | //! |
| 728 | //! A kill is modelled by `Proc::exit` alone: the kill flag the actor |
| 729 | //! reads at its safe points is set under the same lock, just before. |
| 730 | use super::*; |
| 731 | use loom::sync::atomic::{AtomicBool, Ordering}; |
| 732 | use loom::sync::{Arc, Condvar, Mutex}; |
| 733 | use loom::thread; |
| 734 | |
| 735 | const A: i64 = 1; |
| 736 | const B: i64 = 2; |
| 737 | |
| 738 | /// Every interleaving with up to 3 preemptions (loom's usual bound): |
| 739 | /// unbounded (`LOUISE_LOOM_UNBOUNDED=1`), the three models take |
| 740 | /// minutes, and pass. Bounded, |
| 741 | /// they still find each of these, as a lost wake-up (checked by hand): |
| 742 | /// a sender that does not wake a waiting receiver, whether it pushed |
| 743 | /// or handed its message over; `stop` parking without re-checking the |
| 744 | /// inbox; an exit that does not interrupt a receive. |
| 745 | fn model(f: impl Fn() + Sync + Send + 'static) { |
| 746 | let mut builder = loom::model::Builder::new(); |
| 747 | if std::env::var_os("LOUISE_LOOM_UNBOUNDED").is_none() { |
| 748 | builder.preemption_bound = Some(3); |
| 749 | } |
| 750 | builder.check(f); |
| 751 | } |
| 752 | |
| 753 | /// An actor's shared half, as `sched::Cell`, with its run queue. |
| 754 | struct Cell { |
| 755 | inbox: Inbox<Val>, |
| 756 | proc: Mutex<Proc<Val, ()>>, |
| 757 | queued: Mutex<usize>, |
| 758 | queue: Condvar, |
| 759 | } |
| 760 | |
| 761 | fn running() -> Arc<Cell> { |
| 762 | let mut p = Proc::new((), Links::default(), Vec::new()); |
| 763 | assert!(p.run.start().is_some()); |
| 764 | Arc::new(Cell { |
| 765 | inbox: Inbox::new(), |
| 766 | proc: Mutex::new(p), |
| 767 | queued: Mutex::new(0), |
| 768 | queue: Condvar::new(), |
| 769 | }) |
| 770 | } |
| 771 | |
| 772 | impl Cell { |
| 773 | fn schedule(&self) { |
| 774 | *self.queued.lock().unwrap() += 1; |
| 775 | self.queue.notify_one(); |
| 776 | } |
| 777 | |
| 778 | /// A send, as `Shared::deliver`: the message back if refused. |
| 779 | fn send(&self, tag: i64, message: u32) -> Option<Val> { |
| 780 | if self.inbox.waits_empty() |
| 781 | && let Ok(mut p) = self.proc.try_lock() |
| 782 | && p.waits_for(tag) |
| 783 | && self.inbox.claim_waiting() |
| 784 | { |
| 785 | if p.hand_over(tag, Val::Message(message)) { |
| 786 | drop(p); |
| 787 | self.schedule(); |
| 788 | } |
| 789 | return None; |
| 790 | } |
| 791 | match self.inbox.push(tag, Val::Message(message)) { |
| 792 | Err(refused) => Some(refused), |
| 793 | Ok(false) => None, |
| 794 | Ok(true) => { |
| 795 | if self.proc.lock().unwrap().woken_by_message() { |
| 796 | self.schedule(); |
| 797 | } |
| 798 | None |
| 799 | } |
| 800 | } |
| 801 | } |
| 802 | |
| 803 | /// The actor's fiber yields; its thread stops it. |
| 804 | fn stop(&self) { |
| 805 | if self.proc.lock().unwrap().stop(&self.inbox, ()) { |
| 806 | self.schedule(); |
| 807 | } |
| 808 | } |
| 809 | |
| 810 | /// A thread takes the actor from its run queue, and runs it. |
| 811 | fn run_once_queued(&self) { |
| 812 | let mut queued = self.queued.lock().unwrap(); |
| 813 | while *queued == 0 { |
| 814 | queued = self.queue.wait(queued).unwrap(); |
| 815 | } |
| 816 | *queued -= 1; |
| 817 | drop(queued); |
| 818 | let started = self.proc.lock().unwrap().run.start(); |
| 819 | assert!(started.is_some(), "queued while not suspended"); |
| 820 | } |
| 821 | |
| 822 | /// What is left in the mailbox on `tag` (checked without waiting). |
| 823 | fn left(&self, tag: i64) -> Val { |
| 824 | let mut p = self.proc.lock().unwrap(); |
| 825 | match p.receive(&self.inbox, Tags::One(tag), false, Timeout::Zero) { |
| 826 | Received::Now(v) => v, |
| 827 | Received::Parked(_) => unreachable!("a zero timeout never waits"), |
| 828 | } |
| 829 | } |
| 830 | } |
| 831 | |
| 832 | /// The actor receives on `tags`: what the receive returns. If the |
| 833 | /// actor unwinds (it exited): `None`, or the message handed over |
| 834 | /// before the exit, which it frees. A timeout sets its timer, on |
| 835 | /// another thread, once the actor waits. |
| 836 | fn receive( |
| 837 | cell: &Arc<Cell>, |
| 838 | tags: &[i64], |
| 839 | timeout: Timeout, |
| 840 | ) -> (Option<Val>, Option<thread::JoinHandle<()>>) { |
| 841 | let received = |
| 842 | cell.proc |
| 843 | .lock() |
| 844 | .unwrap() |
| 845 | .receive(&cell.inbox, Tags::of(tags), false, timeout); |
| 846 | let wait = match received { |
| 847 | Received::Now(v) => return (Some(v), None), |
| 848 | Received::Parked(wait) => wait, |
| 849 | }; |
| 850 | let timer = match timeout { |
| 851 | Timeout::At(deadline) => { |
| 852 | let cell = cell.clone(); |
| 853 | Some(thread::spawn(move || { |
| 854 | if cell.proc.lock().unwrap().time_out(wait, deadline) { |
| 855 | cell.schedule(); |
| 856 | } |
| 857 | })) |
| 858 | } |
| 859 | _ => None, |
| 860 | }; |
| 861 | loop { |
| 862 | cell.stop(); |
| 863 | cell.run_once_queued(); |
| 864 | let mut p = cell.proc.lock().unwrap(); |
| 865 | if p.dead { |
| 866 | // Unwinding: a message handed over is dropped (counted by |
| 867 | // the caller, as `wait_for_message` frees it). |
| 868 | let handed = p.take_wake(); |
| 869 | return (Some(handed).filter(|v| *v != Val::Unit), timer); |
| 870 | } |
| 871 | if let Some(v) = p.receive_woken(&cell.inbox) { |
| 872 | return (Some(v), timer); |
| 873 | } |
| 874 | } |
| 875 | } |
| 876 | |
| 877 | fn sender(cell: &Arc<Cell>, tag: i64, message: u32) -> thread::JoinHandle<Option<Val>> { |
| 878 | let cell = cell.clone(); |
| 879 | thread::spawn(move || cell.send(tag, message)) |
| 880 | } |
| 881 | |
| 882 | /// Two messages race with a receive on one of their tags: the receive |
| 883 | /// gets the first, at once or woken (perhaps first by the other one, |
| 884 | /// then again); the other stays in the mailbox. |
| 885 | #[test] |
| 886 | fn sends_race_a_receive() { |
| 887 | model(|| { |
| 888 | let cell = running(); |
| 889 | let to_a = sender(&cell, A, 1); |
| 890 | let to_b = sender(&cell, B, 2); |
| 891 | let (got, _) = receive(&cell, &[A], Timeout::Never); |
| 892 | assert_eq!(got, Some(Val::Received(1, None))); |
| 893 | assert_eq!(to_a.join().unwrap(), None); |
| 894 | assert_eq!(to_b.join().unwrap(), None); |
| 895 | assert_eq!(cell.left(A), Val::TimedOut); |
| 896 | assert_eq!(cell.left(B), Val::Received(2, None)); |
| 897 | assert_eq!(*cell.queued.lock().unwrap(), 0, "a doubled wake-up"); |
| 898 | }); |
| 899 | } |
| 900 | |
| 901 | /// A receive's timer fires while its message arrives: the receive |
| 902 | /// returns the message or `None`, not both, and a message it did not |
| 903 | /// return is still in the mailbox. |
| 904 | #[test] |
| 905 | fn a_timeout_races_a_send() { |
| 906 | model(|| { |
| 907 | let cell = running(); |
| 908 | let send = sender(&cell, A, 1); |
| 909 | let (got, timer) = receive(&cell, &[A], Timeout::At(10)); |
| 910 | assert_eq!(send.join().unwrap(), None); |
| 911 | if let Some(timer) = timer { |
| 912 | timer.join().unwrap(); |
| 913 | } |
| 914 | match got { |
| 915 | Some(Val::Received(1, None)) => assert_eq!(cell.left(A), Val::TimedOut), |
| 916 | Some(Val::TimedOut) => assert_eq!(cell.left(A), Val::Received(1, None)), |
| 917 | other => panic!("the receive returned {other:?}"), |
| 918 | } |
| 919 | assert_eq!(*cell.queued.lock().unwrap(), 0, "a doubled wake-up"); |
| 920 | }); |
| 921 | } |
| 922 | |
| 923 | /// The actor is killed while a message arrives and it receives: the |
| 924 | /// message is received, refused (back to its sender) or left for the |
| 925 | /// actor to free as it unwinds, exactly one of them. |
| 926 | #[test] |
| 927 | fn a_kill_races_a_send_and_a_receive() { |
| 928 | model(|| { |
| 929 | let cell = running(); |
| 930 | let send = sender(&cell, A, 1); |
| 931 | let kill = { |
| 932 | let cell = cell.clone(); |
| 933 | thread::spawn(move || { |
| 934 | let exited = cell.proc.lock().unwrap().exit(&cell.inbox); |
| 935 | if exited.expect("exits once").wake { |
| 936 | cell.schedule(); |
| 937 | } |
| 938 | }) |
| 939 | }; |
| 940 | let (got, _) = receive(&cell, &[A], Timeout::Never); |
| 941 | let refused = send.join().unwrap(); |
| 942 | kill.join().unwrap(); |
| 943 | let mut found: Vec<Val> = got.into_iter().chain(refused).collect(); |
| 944 | let (mut mailbox, wake) = cell.proc.lock().unwrap().release(&cell.inbox); |
| 945 | assert_eq!(wake, Val::Unit); |
| 946 | found.extend(mailbox.drain()); |
| 947 | let ones = found |
| 948 | .iter() |
| 949 | .filter(|v| matches!(v, Val::Message(1) | Val::Received(1, _))) |
| 950 | .count(); |
| 951 | assert_eq!(ones, 1, "the message, once: {found:?}"); |
| 952 | assert_eq!(*cell.queued.lock().unwrap(), 0, "a doubled wake-up"); |
| 953 | }); |
| 954 | } |
| 955 | |
| 956 | // ---- links: each step under one actor's lock, as `op_link`, `op_unlink` |
| 957 | // and `exit_actor` (with `propagate_exit`) take them. |
| 958 | // |
| 959 | // These are copies of the production steps, not the production |
| 960 | // functions (which need a scheduler): each model function names the |
| 961 | // one it copies, step for step, and a change to that function must be |
| 962 | // made here too. Not modelled: a receiver that does not trap exits |
| 963 | // and dies of one under its lock (`Linked::Dies`; its own exit then |
| 964 | // runs as `exit` here), the inbox push and wake-up, and two actors |
| 965 | // exiting at once. |
| 966 | |
| 967 | /// What happened to an actor of the link models, under its lock. |
| 968 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 969 | enum Event { |
| 970 | /// Its half of a link was made (`link`). |
| 971 | Linked, |
| 972 | /// Its half was removed by its own `unlink`. |
| 973 | Unlinked, |
| 974 | /// The exit of this pid came through a link (an `ExitSignal`: the |
| 975 | /// models' actors trap exits, so none dies of it). |
| 976 | Exit(i64), |
| 977 | } |
| 978 | |
| 979 | /// An actor of the link models: its lock, what happened under it, and |
| 980 | /// the kill flag its exit sets under it (`Cell::kill`). |
| 981 | struct Linker { |
| 982 | pid: i64, |
| 983 | inbox: Inbox<Val>, |
| 984 | proc: Mutex<(Proc<Val, ()>, Vec<Event>)>, |
| 985 | killed: AtomicBool, |
| 986 | } |
| 987 | |
| 988 | impl Linker { |
| 989 | fn new(pid: i64, linked: &[i64]) -> Arc<Linker> { |
| 990 | let mut links = Links::default(); |
| 991 | linked.iter().for_each(|p| links.insert(*p)); |
| 992 | let mut p = Proc::new((), links, Vec::new()); |
| 993 | assert!(p.run.start().is_some()); |
| 994 | Arc::new(Linker { |
| 995 | pid, |
| 996 | inbox: Inbox::new(), |
| 997 | proc: Mutex::new((p, Vec::new())), |
| 998 | killed: AtomicBool::new(false), |
| 999 | }) |
| 1000 | } |
| 1001 | |
| 1002 | fn has_half(&self, pid: i64) -> bool { |
| 1003 | let p = &self.proc.lock().unwrap().0; |
| 1004 | p.ties.as_ref().is_some_and(|t| t.links.contains(pid)) |
| 1005 | } |
| 1006 | |
| 1007 | fn events(&self) -> Vec<Event> { |
| 1008 | self.proc.lock().unwrap().1.clone() |
| 1009 | } |
| 1010 | } |
| 1011 | |
| 1012 | /// `me` links `other` (`process::link_local`): its own half, unless it |
| 1013 | /// exited; then `other`'s, unless `other` exited or `me`'s kill flag is |
| 1014 | /// set (its exit, which sets it under `me`'s lock, signals `other` |
| 1015 | /// under `other`'s, after); without `other`, its own half goes. |
| 1016 | /// Whether `other`'s half was made. |
| 1017 | fn link(me: &Linker, other: &Linker) -> bool { |
| 1018 | { |
| 1019 | let mut g = me.proc.lock().unwrap(); |
| 1020 | if !g.0.link(other.pid) { |
| 1021 | return false; |
| 1022 | } |
| 1023 | g.1.push(Event::Linked); |
| 1024 | } |
| 1025 | let made = { |
| 1026 | let mut g = other.proc.lock().unwrap(); |
| 1027 | (!g.0.dead).then(|| !me.killed.load(Ordering::Acquire) && g.0.link(me.pid)) |
| 1028 | }; |
| 1029 | if made.is_none() { |
| 1030 | me.proc.lock().unwrap().0.unlink(other.pid); |
| 1031 | } |
| 1032 | made == Some(true) |
| 1033 | } |
| 1034 | |
| 1035 | /// `me` unlinks `other` (`process::op_unlink`, local): its own half, |
| 1036 | /// then `other`'s. |
| 1037 | fn unlink(me: &Linker, other: &Linker) { |
| 1038 | { |
| 1039 | let mut g = me.proc.lock().unwrap(); |
| 1040 | g.0.unlink(other.pid); |
| 1041 | g.1.push(Event::Unlinked); |
| 1042 | } |
| 1043 | let mut g = other.proc.lock().unwrap(); |
| 1044 | if !g.0.dead { |
| 1045 | g.0.unlink(me.pid); |
| 1046 | } |
| 1047 | } |
| 1048 | |
| 1049 | /// `who` exits (`sched::exit_actor`, `exit_locked`): its links taken |
| 1050 | /// and its kill flag set under its lock; then each linked actor, under |
| 1051 | /// its own, counts the exit only through a half it still has |
| 1052 | /// (`propagate_exit`, `exit_through_link`). `table` says whether each |
| 1053 | /// linked pid is in the actor table yet (`Shared::cell`): one that is |
| 1054 | /// not is not told. |
| 1055 | fn exit(who: &Linker, all: &[&Linker]) { |
| 1056 | exit_in(who, all, None); |
| 1057 | } |
| 1058 | |
| 1059 | fn exit_in(who: &Linker, all: &[&Linker], table: Option<&Mutex<bool>>) { |
| 1060 | let links = { |
| 1061 | let mut g = who.proc.lock().unwrap(); |
| 1062 | let exited = g.0.exit(&who.inbox).expect("exits once"); |
| 1063 | who.killed.store(true, Ordering::Release); |
| 1064 | exited.links |
| 1065 | }; |
| 1066 | for to in links { |
| 1067 | if table.is_some_and(|t| !*t.lock().unwrap()) { |
| 1068 | continue; |
| 1069 | } |
| 1070 | let to = all.iter().find(|a| a.pid == to).expect("a linked actor"); |
| 1071 | let mut g = to.proc.lock().unwrap(); |
| 1072 | if !g.0.dead && g.0.unlink(who.pid).0 { |
| 1073 | g.1.push(Event::Exit(who.pid)); |
| 1074 | } |
| 1075 | } |
| 1076 | } |
| 1077 | |
| 1078 | /// `a` unlinks `b`, then links it again, while `b` exits: `b`'s exit |
| 1079 | /// reaches `a` at most once, never between the unlink and the new |
| 1080 | /// link; if the new link made `b`'s half, it does; and `a` keeps no |
| 1081 | /// half of a link to the pid that exited. |
| 1082 | #[test] |
| 1083 | fn an_unlink_races_an_exit_and_a_new_link() { |
| 1084 | model(|| { |
| 1085 | let a = Linker::new(A, &[B]); |
| 1086 | let b = Linker::new(B, &[A]); |
| 1087 | let exiting = { |
| 1088 | let (a, b) = (a.clone(), b.clone()); |
| 1089 | thread::spawn(move || exit(&b, &[&a, &b])) |
| 1090 | }; |
| 1091 | unlink(&a, &b); |
| 1092 | let relinked = link(&a, &b); |
| 1093 | exiting.join().unwrap(); |
| 1094 | let events = a.events(); |
| 1095 | let exits: Vec<usize> = (0..events.len()) |
| 1096 | .filter(|i| events[*i] == Event::Exit(B)) |
| 1097 | .collect(); |
| 1098 | assert!(exits.len() <= 1, "one exit at most: {events:?}"); |
| 1099 | let at = |e: Event| events.iter().position(|x| *x == e).unwrap(); |
| 1100 | let (unlinked, linked) = (at(Event::Unlinked), at(Event::Linked)); |
| 1101 | if let Some(&i) = exits.first() { |
| 1102 | assert!( |
| 1103 | i < unlinked || i > linked, |
| 1104 | "an exit while unlinked: {events:?}" |
| 1105 | ); |
| 1106 | } |
| 1107 | if relinked { |
| 1108 | assert!(exits.first().is_some_and(|i| *i > linked), "{events:?}"); |
| 1109 | } |
| 1110 | assert!(!a.has_half(B), "linked to a pid that exited: {events:?}"); |
| 1111 | }); |
| 1112 | } |
| 1113 | |
| 1114 | /// `a` links `b` while `a` is killed: `b` gets `a`'s exit if it has its |
| 1115 | /// half, and keeps no half of a link to the pid that exited. |
| 1116 | #[test] |
| 1117 | fn a_link_races_the_linkers_exit() { |
| 1118 | model(|| { |
| 1119 | let a = Linker::new(A, &[]); |
| 1120 | let b = Linker::new(B, &[]); |
| 1121 | let killing = { |
| 1122 | let (a, b) = (a.clone(), b.clone()); |
| 1123 | thread::spawn(move || exit(&a, &[&a, &b])) |
| 1124 | }; |
| 1125 | let made = link(&a, &b); |
| 1126 | killing.join().unwrap(); |
| 1127 | let events = b.events(); |
| 1128 | let told = events.iter().filter(|e| **e == Event::Exit(A)).count(); |
| 1129 | assert!(told <= 1, "{events:?}"); |
| 1130 | assert_eq!(made, told == 1, "{events:?}"); |
| 1131 | assert!(!b.has_half(A), "linked to a pid that exited: {events:?}"); |
| 1132 | }); |
| 1133 | } |
| 1134 | |
| 1135 | /// `parent` spawn_links `child` while `parent` is killed |
| 1136 | /// (`sched::spawn_actor`): the parent's half first, unless it exited; |
| 1137 | /// the child made with its half and put in the actor table; then the |
| 1138 | /// child is stopped as an orphan if the parent's half could not be |
| 1139 | /// made or the parent's kill flag is set. The parent's exit sets the |
| 1140 | /// flag before it looks the child up in the table, so whenever it |
| 1141 | /// misses the child, the child sees the flag: the child is always told |
| 1142 | /// or stopped, never left linked to a pid that exited. |
| 1143 | #[test] |
| 1144 | fn a_spawn_link_races_the_parents_exit() { |
| 1145 | model(|| { |
| 1146 | let parent = Linker::new(A, &[]); |
| 1147 | let child = Linker::new(B, &[A]); |
| 1148 | let table = Arc::new(Mutex::new(false)); |
| 1149 | let killing = { |
| 1150 | let (parent, child, table) = (parent.clone(), child.clone(), table.clone()); |
| 1151 | thread::spawn(move || exit_in(&parent, &[&parent, &child], Some(&table))) |
| 1152 | }; |
| 1153 | let linked = parent.proc.lock().unwrap().0.link(B); |
| 1154 | *table.lock().unwrap() = true; |
| 1155 | let orphan = !linked || parent.killed.load(Ordering::Acquire); |
| 1156 | killing.join().unwrap(); |
| 1157 | let told = child.events().contains(&Event::Exit(A)); |
| 1158 | assert!(told || orphan, "the child outlived its parent, linked"); |
| 1159 | }); |
| 1160 | } |
| 1161 | } |
| 1162 | |
| 1163 | // Second security review of #404 (dist/secreview2): a measurement. |
| 1164 | #[cfg(all(test, not(loom)))] |
| 1165 | mod secreview2; |
| 1166 | |
| 1167 | // Third security review of #404 (dist/secreview3): a measurement. |
| 1168 | #[cfg(all(test, not(loom)))] |
| 1169 | mod secreview3; |
| 1170 | |
| 1171 | #[cfg(all(test, not(loom)))] |
| 1172 | mod tests { |
| 1173 | use super::*; |
| 1174 | |
| 1175 | fn actor() -> (Proc<Val, ()>, Inbox<Val>) { |
| 1176 | let mut p = Proc::new((), Links::default(), Vec::new()); |
| 1177 | assert!(p.run.start().is_some()); |
| 1178 | (p, Inbox::new()) |
| 1179 | } |
| 1180 | |
| 1181 | fn parked(r: Received<Val>) -> u64 { |
| 1182 | match r { |
| 1183 | Received::Parked(wait) => wait, |
| 1184 | Received::Now(v) => panic!("received {v:?}"), |
| 1185 | } |
| 1186 | } |
| 1187 | |
| 1188 | #[test] |
| 1189 | fn receive_any_takes_the_oldest_and_names_its_tag() { |
| 1190 | let (mut p, inbox) = actor(); |
| 1191 | for (tag, n) in [(2, 1), (1, 2), (2, 3)] { |
| 1192 | assert_eq!(inbox.push(tag, Val::Message(n)), Ok(false)); |
| 1193 | } |
| 1194 | assert!(matches!( |
| 1195 | p.receive(&inbox, Tags::of(&[1, 2]), true, Timeout::Zero), |
| 1196 | Received::Now(Val::Received(1, Some(2))) |
| 1197 | )); |
| 1198 | assert!(matches!( |
| 1199 | p.receive(&inbox, Tags::of(&[1]), false, Timeout::Zero), |
| 1200 | Received::Now(Val::Received(2, None)) |
| 1201 | )); |
| 1202 | } |
| 1203 | |
| 1204 | #[test] |
| 1205 | fn a_message_on_another_tag_wakes_a_receive_which_waits_again() { |
| 1206 | let (mut p, inbox) = actor(); |
| 1207 | parked(p.receive(&inbox, Tags::of(&[1]), false, Timeout::Never)); |
| 1208 | assert!(!p.stop(&inbox, ()), "it waits"); |
| 1209 | assert_eq!(inbox.push(2, Val::Message(1)), Ok(true)); |
| 1210 | assert!(p.woken_by_message()); |
| 1211 | assert!(p.run.start().is_some()); |
| 1212 | assert_eq!(p.receive_woken(&inbox), None, "not its tag"); |
| 1213 | assert!(!p.stop(&inbox, ()), "it waits again"); |
| 1214 | assert_eq!(inbox.push(1, Val::Message(2)), Ok(true)); |
| 1215 | assert!(p.woken_by_message()); |
| 1216 | assert!(p.run.start().is_some()); |
| 1217 | assert_eq!(p.receive_woken(&inbox), Some(Val::Received(2, None))); |
| 1218 | } |
| 1219 | |
| 1220 | #[test] |
| 1221 | fn a_timer_for_an_earlier_wait_is_ignored() { |
| 1222 | let (mut p, inbox) = actor(); |
| 1223 | let first = parked(p.receive(&inbox, Tags::of(&[1]), false, Timeout::At(10))); |
| 1224 | assert!(!p.stop(&inbox, ())); |
| 1225 | assert_eq!(inbox.push(1, Val::Message(1)), Ok(true)); |
| 1226 | assert!(p.woken_by_message()); |
| 1227 | assert!(p.run.start().is_some()); |
| 1228 | assert_eq!(p.receive_woken(&inbox), Some(Val::Received(1, None))); |
| 1229 | // Waiting again, with the same deadline. |
| 1230 | let second = parked(p.receive(&inbox, Tags::of(&[1]), false, Timeout::At(10))); |
| 1231 | assert!(!p.stop(&inbox, ())); |
| 1232 | assert!(!p.time_out(first, 10), "the first wait's timer"); |
| 1233 | assert!(p.time_out(second, 10)); |
| 1234 | assert!(p.run.start().is_some()); |
| 1235 | assert_eq!(p.receive_woken(&inbox), Some(Val::TimedOut)); |
| 1236 | } |
| 1237 | |
| 1238 | #[test] |
| 1239 | fn a_timeout_survives_a_wake_up_for_another_tag() { |
| 1240 | let (mut p, inbox) = actor(); |
| 1241 | let wait = parked(p.receive(&inbox, Tags::of(&[1]), false, Timeout::At(10))); |
| 1242 | assert!(!p.stop(&inbox, ())); |
| 1243 | assert_eq!(inbox.push(2, Val::Message(1)), Ok(true)); |
| 1244 | assert!(p.woken_by_message()); |
| 1245 | assert!(p.run.start().is_some()); |
| 1246 | assert_eq!(p.receive_woken(&inbox), None); |
| 1247 | assert!(!p.stop(&inbox, ())); |
| 1248 | assert!(p.time_out(wait, 10), "the same wait, so its timer applies"); |
| 1249 | assert!(p.run.start().is_some()); |
| 1250 | assert_eq!(p.receive_woken(&inbox), Some(Val::TimedOut)); |
| 1251 | } |
| 1252 | |
| 1253 | #[test] |
| 1254 | fn a_message_does_not_wake_a_sleep() { |
| 1255 | let (mut p, inbox) = actor(); |
| 1256 | // A wait flag left by an earlier receive that a timer ended. |
| 1257 | parked(p.receive(&inbox, Tags::of(&[1]), false, Timeout::Never)); |
| 1258 | assert!(!p.stop(&inbox, ())); |
| 1259 | assert!(p.interrupt()); |
| 1260 | assert!(p.run.start().is_some()); |
| 1261 | p.park_as(Wait::Sleep { deadline: 5 }); |
| 1262 | assert!(!p.stop(&inbox, ())); |
| 1263 | assert_eq!(inbox.push(1, Val::Message(1)), Ok(true)); |
| 1264 | assert!(!p.woken_by_message(), "it sleeps"); |
| 1265 | inbox.take(|_, _| {}); |
| 1266 | } |
| 1267 | |
| 1268 | /// A sender parked on a full queue is resumed by its own wait only: a |
| 1269 | /// late wake for an earlier one, or for an actor now receiving, is |
| 1270 | /// ignored. |
| 1271 | #[test] |
| 1272 | fn a_parked_sender_is_resumed_by_its_own_wait_only() { |
| 1273 | let (mut p, inbox) = actor(); |
| 1274 | let first = p.park_as(Wait::Io); |
| 1275 | assert!(!p.stop(&inbox, ())); |
| 1276 | assert!(p.resume(first), "woken: schedule it"); |
| 1277 | assert!(p.run.start().is_some()); |
| 1278 | assert!(!p.resume(first), "ready: nothing to wake"); |
| 1279 | let second = p.park_as(Wait::Io); |
| 1280 | assert!(!p.stop(&inbox, ())); |
| 1281 | assert!(!p.resume(first), "an earlier wait's wake"); |
| 1282 | assert!(p.resume(second)); |
| 1283 | assert!(p.run.start().is_some()); |
| 1284 | parked(p.receive(&inbox, Tags::of(&[1]), false, Timeout::Never)); |
| 1285 | assert!(!p.stop(&inbox, ())); |
| 1286 | assert!(!p.resume(second), "it receives now"); |
| 1287 | assert_eq!(inbox.push(1, Val::Message(1)), Ok(true)); |
| 1288 | assert!(p.woken_by_message()); |
| 1289 | inbox.take(|_, _| {}); |
| 1290 | } |
| 1291 | |
| 1292 | /// Killed while it ran, then it receives: it does not wait, so that it |
| 1293 | /// is queued again to unwind (found by `a_kill_races_a_send_and_a_receive`). |
| 1294 | #[test] |
| 1295 | fn an_actor_killed_while_running_does_not_wait() { |
| 1296 | for wait in [Wait::Io, Wait::Sleep { deadline: 5 }] { |
| 1297 | let (mut p, inbox) = actor(); |
| 1298 | assert!( |
| 1299 | !p.exit(&inbox).expect("alive").wake, |
| 1300 | "running: nothing to wake" |
| 1301 | ); |
| 1302 | p.park_as(wait); |
| 1303 | assert!(p.stop(&inbox, ()), "{wait:?}: queued again, to unwind"); |
| 1304 | } |
| 1305 | let (mut p, inbox) = actor(); |
| 1306 | p.exit(&inbox); |
| 1307 | parked(p.receive(&inbox, Tags::of(&[1]), false, Timeout::Never)); |
| 1308 | assert!(p.stop(&inbox, ())); |
| 1309 | } |
| 1310 | |
| 1311 | #[test] |
| 1312 | fn an_exited_actor_refuses_messages_and_a_blocking_call_is_not_interrupted() { |
| 1313 | let (mut p, inbox) = actor(); |
| 1314 | p.park_as(Wait::Blocking); |
| 1315 | assert!(!p.stop(&inbox, ())); |
| 1316 | assert!( |
| 1317 | !p.exit(&inbox).expect("alive").wake, |
| 1318 | "a blocking call runs to its end" |
| 1319 | ); |
| 1320 | assert!(p.exit(&inbox).is_none(), "exits once"); |
| 1321 | assert_eq!(inbox.push(1, Val::Message(1)), Err(Val::Message(1))); |
| 1322 | } |
| 1323 | |
| 1324 | #[test] |
| 1325 | fn links_keep_their_order_and_drop_removed_ones() { |
| 1326 | let mut links = Links::default(); |
| 1327 | for pid in [5, 3, 9, 3, 7] { |
| 1328 | links.insert(pid); |
| 1329 | } |
| 1330 | links.remove(9); |
| 1331 | links.remove(42); |
| 1332 | assert_eq!(links.into_vec(), [5, 3, 7]); |
| 1333 | // Many removals compact the order, without changing it. |
| 1334 | let mut links = Links::default(); |
| 1335 | for pid in 0..1000 { |
| 1336 | links.insert(pid); |
| 1337 | } |
| 1338 | for pid in (0..1000).filter(|p| p % 10 != 0) { |
| 1339 | links.remove(pid); |
| 1340 | } |
| 1341 | let Links::Many { order, .. } = &links else { |
| 1342 | panic!("100 links are a set"); |
| 1343 | }; |
| 1344 | assert!(order.len() < 300); |
| 1345 | assert_eq!(links.into_vec(), (0..1000).step_by(10).collect::<Vec<_>>()); |
| 1346 | } |
| 1347 | |
| 1348 | #[test] |
| 1349 | fn links_grow_from_one_to_a_set_keeping_their_order() { |
| 1350 | let mut links = Links::default(); |
| 1351 | assert!(links.is_empty()); |
| 1352 | links.insert(1); |
| 1353 | links.insert(1); |
| 1354 | assert!(matches!(links, Links::One(1))); |
| 1355 | links.remove(1); |
| 1356 | assert!(links.is_empty()); |
| 1357 | links.insert(1); |
| 1358 | links.insert(2); |
| 1359 | assert!(matches!(links, Links::Many { .. })); |
| 1360 | links.insert(3); |
| 1361 | links.remove(1); |
| 1362 | links.insert(1); // linked again: keeps its first place |
| 1363 | assert_eq!(links.into_vec(), [1, 2, 3]); |
| 1364 | } |
| 1365 | |
| 1366 | /// Review of #422 (dist/ccreview3). Before `unlink`, a pid left an |
| 1367 | /// actor's links only when it exited, and never came back. Now a live |
| 1368 | /// pid is removed and linked again as a matter of course (`unlink` |
| 1369 | /// then `link`, here or by a peer's frames 17 and 10), and each time |
| 1370 | /// `insert` pushes it on `order` once more. Compaction keeps every |
| 1371 | /// copy of a pid that was linked at the time: a pid unlinked and linked |
| 1372 | /// again many times, then left linked, kept `order` above the bound |
| 1373 | /// `remove` compacts at, so every later removal (each linked child's |
| 1374 | /// exit) scanned all of it, and n exits took time quadratic in n. |
| 1375 | /// Compaction now keeps each pid's first copy only. |
| 1376 | #[test] |
| 1377 | fn a_pid_linked_again_many_times_leaves_removals_cheap() { |
| 1378 | let mut links = Links::default(); |
| 1379 | let children = 2000; |
| 1380 | for pid in 0..children { |
| 1381 | links.insert(pid); |
| 1382 | } |
| 1383 | let relinked = -1; |
| 1384 | links.insert(relinked); |
| 1385 | for _ in 0..5 * children { |
| 1386 | links.remove(relinked); |
| 1387 | links.insert(relinked); |
| 1388 | } |
| 1389 | for pid in 0..children { |
| 1390 | links.remove(pid); |
| 1391 | let Links::Many { order, live } = &links else { |
| 1392 | panic!("still a set"); |
| 1393 | }; |
| 1394 | // `remove` compacts once `order` is past this: when compacting |
| 1395 | // leaves it past this still, the next removal scans it again. |
| 1396 | assert!( |
| 1397 | order.len() <= 2 * live.len() + 16, |
| 1398 | "after child {pid}'s exit: {} entries in order for {} links", |
| 1399 | order.len(), |
| 1400 | live.len() |
| 1401 | ); |
| 1402 | } |
| 1403 | assert_eq!(links.into_vec(), [relinked]); |
| 1404 | } |
| 1405 | |
| 1406 | /// A remote pid's link through Erlang's unlinking state: an exit or a |
| 1407 | /// link from the pid is ignored until the acknowledgement of the |
| 1408 | /// unlink; a link from this side overrides the unlink, whose |
| 1409 | /// acknowledgement then changes nothing; a lost node forgets it. |
| 1410 | #[test] |
| 1411 | fn a_remote_unlink_waits_for_its_acknowledgement() { |
| 1412 | let mut ties = Ties::default(); |
| 1413 | let (p, q) = (-5, -6); |
| 1414 | ties.links.insert(p); |
| 1415 | ties.links.insert(q); |
| 1416 | assert!(ties.unlink_remote(p, 1)); |
| 1417 | assert!(!ties.unlink_remote(p, 2), "unlinking already"); |
| 1418 | assert!(!ties.links.remove(p), "an exit through it is ignored"); |
| 1419 | assert!(!ties.linked_by(p), "a link sent before the unlink arrived"); |
| 1420 | assert!(!ties.unlink_acked(p, 2), "no unlink 2"); |
| 1421 | assert!(!ties.unlink_acked(q, 1), "no unlink of q"); |
| 1422 | assert!(ties.unlink_acked(p, 1)); |
| 1423 | assert!(ties.linked_by(p), "a link sent after"); |
| 1424 | assert!(ties.unlink_remote(p, 3)); |
| 1425 | ties.link_remote(p); |
| 1426 | assert!(!ties.unlink_acked(p, 3), "linked again since"); |
| 1427 | assert!(ties.links.remove(p), "still linked"); |
| 1428 | assert!(ties.unlink_remote(q, 4)); |
| 1429 | let (links, _) = ties.take(|pid| pid == q); |
| 1430 | assert!(links.is_empty()); |
| 1431 | assert!( |
| 1432 | ties.unlinking.is_empty(), |
| 1433 | "the lost node's unlink forgotten" |
| 1434 | ); |
| 1435 | } |
| 1436 | |
| 1437 | /// Erlang's link protocol between actors of two nodes, with `Ties`'s |
| 1438 | /// steps as `dist` takes them (a frame is sent in the step that |
| 1439 | /// decides it, as under the actor's lock): every interleaving of each |
| 1440 | /// side's operations, in order, with the frames on the two ordered |
| 1441 | /// streams leaves both sides agreeing on whether they are linked, with |
| 1442 | /// no unlink left waiting. |
| 1443 | #[test] |
| 1444 | fn crossing_links_and_unlinks_leave_both_sides_agreeing() { |
| 1445 | #[derive(Clone, Copy, Debug)] |
| 1446 | enum Op { |
| 1447 | Link, |
| 1448 | Unlink, |
| 1449 | } |
| 1450 | #[derive(Clone, Copy, Debug)] |
| 1451 | enum Frame { |
| 1452 | Link, |
| 1453 | Unlink(u64), |
| 1454 | Ack(u64), |
| 1455 | } |
| 1456 | /// One side: its actor's ties, the pid it knows the other by, its |
| 1457 | /// operations left, its last unlink's id, and the frames the other |
| 1458 | /// side sent it, in order. |
| 1459 | #[derive(Clone)] |
| 1460 | struct Side { |
| 1461 | ties: Ties, |
| 1462 | peer: i64, |
| 1463 | ops: VecDeque<Op>, |
| 1464 | ids: u64, |
| 1465 | frames: VecDeque<Frame>, |
| 1466 | } |
| 1467 | |
| 1468 | /// Side `s` performs its next operation. |
| 1469 | fn operate(sides: &mut [Side; 2], s: usize) -> String { |
| 1470 | let side = &mut sides[s]; |
| 1471 | let op = side.ops.pop_front().expect("an operation"); |
| 1472 | let frame = match op { |
| 1473 | Op::Link => { |
| 1474 | side.ties.link_remote(side.peer); |
| 1475 | Some(Frame::Link) |
| 1476 | } |
| 1477 | Op::Unlink => { |
| 1478 | side.ids += 1; |
| 1479 | let id = side.ids; |
| 1480 | side.ties |
| 1481 | .unlink_remote(side.peer, id) |
| 1482 | .then_some(Frame::Unlink(id)) |
| 1483 | } |
| 1484 | }; |
| 1485 | sides[1 - s].frames.extend(frame); |
| 1486 | format!("{s}: {op:?} -> {frame:?}") |
| 1487 | } |
| 1488 | |
| 1489 | /// Side `s` takes the next frame the other sent it. |
| 1490 | fn take(sides: &mut [Side; 2], s: usize) -> String { |
| 1491 | let side = &mut sides[s]; |
| 1492 | let frame = side.frames.pop_front().expect("a frame"); |
| 1493 | match frame { |
| 1494 | Frame::Link => { |
| 1495 | side.ties.linked_by(side.peer); |
| 1496 | } |
| 1497 | Frame::Unlink(id) => { |
| 1498 | side.ties.links.remove(side.peer); |
| 1499 | sides[1 - s].frames.push_back(Frame::Ack(id)); |
| 1500 | } |
| 1501 | Frame::Ack(id) => { |
| 1502 | side.ties.unlink_acked(side.peer, id); |
| 1503 | } |
| 1504 | } |
| 1505 | format!("{s} takes {frame:?}") |
| 1506 | } |
| 1507 | |
| 1508 | fn explore(sides: [Side; 2], trace: &mut Vec<String>, leaves: &mut usize) { |
| 1509 | let mut moved = false; |
| 1510 | for s in 0..2 { |
| 1511 | type Step = fn(&mut [Side; 2], usize) -> String; |
| 1512 | let steps: [(bool, Step); 2] = [ |
| 1513 | (!sides[s].ops.is_empty(), operate), |
| 1514 | (!sides[s].frames.is_empty(), take), |
| 1515 | ]; |
| 1516 | for (_, step) in steps.into_iter().filter(|(can, _)| *can) { |
| 1517 | moved = true; |
| 1518 | let mut next = sides.clone(); |
| 1519 | trace.push(step(&mut next, s)); |
| 1520 | explore(next, trace, leaves); |
| 1521 | trace.pop(); |
| 1522 | } |
| 1523 | } |
| 1524 | if moved { |
| 1525 | return; |
| 1526 | } |
| 1527 | *leaves += 1; |
| 1528 | let linked = |side: &Side| side.ties.links.contains(side.peer); |
| 1529 | assert_eq!(linked(&sides[0]), linked(&sides[1]), "{trace:#?}"); |
| 1530 | let waiting = |side: &Side| side.ties.unlinks(); |
| 1531 | assert_eq!((waiting(&sides[0]), waiting(&sides[1])), (vec![], vec![])); |
| 1532 | } |
| 1533 | |
| 1534 | use Op::{Link, Unlink}; |
| 1535 | let scenarios: [(bool, &[Op], &[Op]); 7] = [ |
| 1536 | (true, &[Unlink, Link], &[Unlink]), |
| 1537 | (true, &[Unlink], &[Link]), |
| 1538 | (true, &[Link], &[Unlink, Link]), |
| 1539 | (true, &[Unlink, Link, Unlink], &[Unlink, Link]), |
| 1540 | (false, &[Link], &[Link, Unlink]), |
| 1541 | (false, &[Link, Unlink, Link], &[Link, Unlink]), |
| 1542 | (false, &[Link, Unlink], &[Link, Unlink, Link]), |
| 1543 | ]; |
| 1544 | for (linked, a, b) in scenarios { |
| 1545 | let side = |peer: i64, ops: &[Op]| { |
| 1546 | let mut ties = Ties::default(); |
| 1547 | if linked { |
| 1548 | ties.links.insert(peer); |
| 1549 | } |
| 1550 | Side { |
| 1551 | ties, |
| 1552 | peer, |
| 1553 | ops: ops.iter().copied().collect(), |
| 1554 | ids: 0, |
| 1555 | frames: VecDeque::new(), |
| 1556 | } |
| 1557 | }; |
| 1558 | let mut leaves = 0; |
| 1559 | explore([side(-2, a), side(-1, b)], &mut Vec::new(), &mut leaves); |
| 1560 | assert!(leaves > 1, "{a:?} {b:?}"); |
| 1561 | } |
| 1562 | } |
| 1563 | } |