| @@ -10,14 +10,20 @@ |
| 10 | 10 | //! timeout (`receive` with a timeout, `sleep`). |
| 11 | 11 | //! - Exits follow Erlang: an abnormal exit stops linked actors (or, if |
| 12 | 12 | //! they trap exits, sends them an `ExitSignal`); monitors receive `Down`. |
| 13 | | −//! - When `main` stops, the program ends and the other actors are stopped. |
| 13 | +//! - As natively, exiting and unwinding are separate: a killed actor exits |
| 14 | +//! at once, and its fiber unwinds (running its `defer` cleanups) the next |
| 15 | +//! time it runs. It is resumed with [`RtError::Killed`] at each of its |
| 16 | +//! safe points until it finishes. A failed `proc` operation panics in the |
| 17 | +//! actor, which unwinds before it exits. |
| 18 | +//! - When `main` stops, the program ends and the other actors are stopped |
| 19 | +//! (unwound, in pid order). |
| 14 | 20 | |
| 15 | 21 | use std::collections::{HashMap, VecDeque}; |
| 16 | 22 | |
| 23 | +use corosensei::CoroutineResult; |
| 17 | 24 | use corosensei::stack::DefaultStack; |
| 18 | | −use corosensei::{CoroutineResult, Yielder}; |
| 19 | 25 | |
| 20 | | −use crate::interp::{Fiber, Interp, OpRequest, R, ROOT, RtError, Val}; |
| 26 | +use crate::interp::{Fiber, FiberYielder, Interp, OpRequest, R, ROOT, RtError, Val}; |
| 21 | 27 | use crate::ir::{EffectId, FnId}; |
| 22 | 28 | |
| 23 | 29 | /// The pseudo-effect a running actor performs to give up its slice. |
| @@ -66,7 +72,10 @@ enum Body { |
| 66 | 72 | struct Sched<'a> { |
| 67 | 73 | interp: &'a Interp, |
| 68 | 74 | actors: HashMap<u64, Actor>, |
| 69 | | − queue: VecDeque<(u64, Val)>, |
| 75 | + /// Exited actors whose fibers still have to unwind. |
| 76 | + zombies: HashMap<u64, Fiber>, |
| 77 | + /// Actors to run, with what their pending request returns. |
| 78 | + queue: VecDeque<(u64, R<Val>)>, |
| 70 | 79 | next_pid: u64, |
| 71 | 80 | next_tag: i64, |
| 72 | 81 | clock: u64, |
| @@ -87,6 +96,7 @@ pub(crate) fn run_actors(interp: &Interp, entry: FnId) -> R<()> { |
| 87 | 96 | let mut s = Sched { |
| 88 | 97 | interp, |
| 89 | 98 | actors: HashMap::new(), |
| 99 | + zombies: HashMap::new(), |
| 90 | 100 | queue: VecDeque::new(), |
| 91 | 101 | next_pid: 0, |
| 92 | 102 | next_tag: 0, |
| @@ -97,7 +107,9 @@ pub(crate) fn run_actors(interp: &Interp, entry: FnId) -> R<()> { |
| 97 | 107 | outcome: None, |
| 98 | 108 | }; |
| 99 | 109 | s.main = s.spawn(Body::Entry(entry), MAIN_STACK)?; |
| 100 | | − while s.outcome.is_none() { |
| 110 | + // Until `main`'s fiber finishes (it may have exited earlier, killed). |
| 111 | + let mut main_done = false; |
| 112 | + while !main_done { |
| 101 | 113 | let Some((pid, input)) = s.queue.pop_front() else { |
| 102 | 114 | if !s.advance_clock() { |
| 103 | 115 | return Err(RtError::Panic( |
| @@ -106,38 +118,19 @@ pub(crate) fn run_actors(interp: &Interp, entry: FnId) -> R<()> { |
| 106 | 118 | } |
| 107 | 119 | continue; |
| 108 | 120 | }; |
| 109 | | − let Some(mut fiber) = s.actors.get_mut(&pid).and_then(|a| a.fiber.take()) else { |
| 110 | | − continue; |
| 111 | | − }; |
| 112 | | − interp.state.current.set(std::ptr::null()); |
| 113 | | − interp.state.reductions.set(0); |
| 114 | | − let step = fiber.resume(input); |
| 115 | | − interp.state.current.set(std::ptr::null()); |
| 116 | | − match step { |
| 117 | | − CoroutineResult::Return(result) => { |
| 118 | | − drop(fiber); |
| 119 | | − if pid == s.main { |
| 120 | | − s.outcome = Some(result.clone().map(|_| ())); |
| 121 | | − } |
| 122 | | − let reason = match result { |
| 123 | | − Ok(_) => Reason::Normal, |
| 124 | | − Err(e) => Reason::Crashed(match e { |
| 125 | | − RtError::Panic(m) => m, |
| 126 | | − unhandled => unhandled.to_string(), |
| 127 | | − }), |
| 128 | | − }; |
| 129 | | − s.exit(pid, reason); |
| 130 | | − } |
| 131 | | − CoroutineResult::Yield(request) => { |
| 132 | | − if let Some(actor) = s.actors.get_mut(&pid) { |
| 133 | | − actor.fiber = Some(fiber); |
| 134 | | − } |
| 135 | | − s.request(pid, request); |
| 136 | | − } |
| 121 | + main_done = s.step(pid, input) && pid == s.main; |
| 122 | + } |
| 123 | + // `main` stopped: stop the others, silently, and let them unwind. |
| 124 | + let mut rest: Vec<u64> = s.actors.keys().chain(s.zombies.keys()).copied().collect(); |
| 125 | + rest.sort(); |
| 126 | + for pid in &rest { |
| 127 | + if let Some(fiber) = s.actors.remove(pid).and_then(|a| a.fiber) { |
| 128 | + s.zombies.insert(*pid, fiber); |
| 137 | 129 | } |
| 138 | 130 | } |
| 139 | | − // `main` stopped: stop the others (dropping a suspended fiber unwinds it). |
| 140 | | − s.actors.clear(); |
| 131 | + for pid in rest { |
| 132 | + while !s.step(pid, Err(RtError::Killed)) {} |
| 133 | + } |
| 141 | 134 | s.outcome.unwrap_or(Ok(())) |
| 142 | 135 | } |
| 143 | 136 | |
| @@ -208,14 +201,74 @@ fn reason_val(r: &Reason) -> Val { |
| 208 | 201 | } |
| 209 | 202 | |
| 210 | 203 | impl Sched<'_> { |
| 204 | + /// Run `pid` until it yields, answering its pending request with |
| 205 | + /// `input` (an exited actor gets `Killed` instead). Returns whether its |
| 206 | + /// fiber finished (or is gone). |
| 207 | + fn step(&mut self, pid: u64, input: R<Val>) -> bool { |
| 208 | + let (mut fiber, input) = match self.actors.get_mut(&pid) { |
| 209 | + Some(a) => match a.fiber.take() { |
| 210 | + Some(f) => (f, input), |
| 211 | + None => return true, |
| 212 | + }, |
| 213 | + None => match self.zombies.remove(&pid) { |
| 214 | + Some(f) => (f, Err(RtError::Killed)), |
| 215 | + None => return true, |
| 216 | + }, |
| 217 | + }; |
| 218 | + self.interp.state.current.set(std::ptr::null()); |
| 219 | + self.interp.state.reductions.set(0); |
| 220 | + let step = fiber.resume(input); |
| 221 | + self.interp.state.current.set(std::ptr::null()); |
| 222 | + match step { |
| 223 | + CoroutineResult::Return(result) => { |
| 224 | + drop(fiber); |
| 225 | + if !self.actors.contains_key(&pid) { |
| 226 | + return true; // a zombie: it exited when it was killed |
| 227 | + } |
| 228 | + if pid == self.main && self.outcome.is_none() { |
| 229 | + self.outcome = Some(result.clone().map(|_| ())); |
| 230 | + } |
| 231 | + let reason = match result { |
| 232 | + Ok(_) => Reason::Normal, |
| 233 | + Err(e) => Reason::Crashed(match e { |
| 234 | + RtError::Panic(m) => m, |
| 235 | + unhandled => unhandled.to_string(), |
| 236 | + }), |
| 237 | + }; |
| 238 | + self.exit(pid, reason); |
| 239 | + true |
| 240 | + } |
| 241 | + CoroutineResult::Yield(request) => { |
| 242 | + if !self.actors.contains_key(&pid) { |
| 243 | + // A zombie at a safe point: the kill is delivered again. |
| 244 | + self.zombies.insert(pid, fiber); |
| 245 | + self.queue.push_back((pid, Err(RtError::Killed))); |
| 246 | + return false; |
| 247 | + } |
| 248 | + if let Some(actor) = self.actors.get_mut(&pid) { |
| 249 | + actor.fiber = Some(fiber); |
| 250 | + } |
| 251 | + self.request(pid, request); |
| 252 | + // The request killed its own actor (`kill(self())`, a link): |
| 253 | + // it continues at once, unwinding. |
| 254 | + if self.zombies.contains_key(&pid) && !self.queue.iter().any(|(p, _)| *p == pid) { |
| 255 | + self.queue.push_front((pid, Err(RtError::Killed))); |
| 256 | + } |
| 257 | + false |
| 258 | + } |
| 259 | + } |
| 260 | + } |
| 261 | + |
| 211 | 262 | fn spawn(&mut self, body: Body, stack: usize) -> R<u64> { |
| 212 | 263 | let pid = self.next_pid; |
| 213 | 264 | self.next_pid += 1; |
| 214 | 265 | let interp = self.interp.clone(); |
| 215 | 266 | let stack = DefaultStack::new(stack) |
| 216 | 267 | .map_err(|e| RtError::Panic(format!("cannot allocate an actor stack: {e}")))?; |
| 217 | | − let fiber = Fiber::with_stack(stack, move |yielder: &Yielder<Val, OpRequest>, _: Val| { |
| 268 | + let fiber = Fiber::with_stack(stack, move |yielder: &FiberYielder, input: R<Val>| { |
| 218 | 269 | interp.state.current.set(yielder); |
| 270 | + // Killed before it ever ran. |
| 271 | + input?; |
| 219 | 272 | // Entry functions and actor bodies receive the runtime's |
| 220 | 273 | // capabilities: one per label of their row that has a handler |
| 221 | 274 | // (only `proc`; checked by `runnable`). |
| @@ -238,7 +291,7 @@ impl Sched<'_> { |
| 238 | 291 | exits_tag: None, |
| 239 | 292 | }, |
| 240 | 293 | ); |
| 241 | | − self.queue.push_back((pid, Val::Unit)); |
| 294 | + self.queue.push_back((pid, Ok(Val::Unit))); |
| 242 | 295 | Ok(pid) |
| 243 | 296 | } |
| 244 | 297 | |
| @@ -250,7 +303,17 @@ impl Sched<'_> { |
| 250 | 303 | /// Continue `pid` right away with `answer`. |
| 251 | 304 | fn reply(&mut self, pid: u64, answer: Val) { |
| 252 | 305 | if self.actors.contains_key(&pid) { |
| 253 | | − self.queue.push_front((pid, answer)); |
| 306 | + self.queue.push_front((pid, Ok(answer))); |
| 307 | + } |
| 308 | + } |
| 309 | + |
| 310 | + /// Make `pid`'s pending operation panic: it continues right away, |
| 311 | + /// unwinding, and crashes (as natively, where the runtime panics in |
| 312 | + /// the actor). |
| 313 | + fn fail(&mut self, pid: u64, message: impl Into<String>) { |
| 314 | + if self.actors.contains_key(&pid) { |
| 315 | + self.queue |
| 316 | + .push_front((pid, Err(RtError::Panic(message.into())))); |
| 254 | 317 | } |
| 255 | 318 | } |
| 256 | 319 | |
| @@ -266,7 +329,7 @@ impl Sched<'_> { |
| 266 | 329 | some(message) |
| 267 | 330 | }; |
| 268 | 331 | actor.wait = Wait::Ready; |
| 269 | | − self.queue.push_back((owner, answer)); |
| 332 | + self.queue.push_back((owner, Ok(answer))); |
| 270 | 333 | } |
| 271 | 334 | _ => actor.mailbox.push_back((tag, message)), |
| 272 | 335 | } |
| @@ -284,12 +347,19 @@ impl Sched<'_> { |
| 284 | 347 | } |
| 285 | 348 | |
| 286 | 349 | /// Stop `pid`, notify monitors, and propagate the exit through links. |
| 350 | + /// A suspended fiber is kept to unwind: it runs again with `Killed` |
| 351 | + /// (now if it was waiting; at its turn if it is queued). |
| 287 | 352 | fn exit(&mut self, pid: u64, reason: Reason) { |
| 288 | 353 | let Some(actor) = self.actors.remove(&pid) else { |
| 289 | 354 | return; |
| 290 | 355 | }; |
| 291 | 356 | let links = actor.links.clone(); |
| 292 | | − drop(actor); |
| 357 | + if let Some(fiber) = actor.fiber { |
| 358 | + if !matches!(actor.wait, Wait::Ready) { |
| 359 | + self.queue.push_back((pid, Err(RtError::Killed))); |
| 360 | + } |
| 361 | + self.zombies.insert(pid, fiber); |
| 362 | + } |
| 293 | 363 | if pid == self.main && self.outcome.is_none() { |
| 294 | 364 | self.outcome = Some(match &reason { |
| 295 | 365 | Reason::Normal => Ok(()), |
| @@ -336,23 +406,20 @@ impl Sched<'_> { |
| 336 | 406 | |
| 337 | 407 | fn request(&mut self, pid: u64, request: OpRequest) { |
| 338 | 408 | if request.effect == PREEMPT { |
| 339 | | − self.queue.push_back((pid, Val::Unit)); |
| 409 | + self.queue.push_back((pid, Ok(Val::Unit))); |
| 340 | 410 | return; |
| 341 | 411 | } |
| 342 | 412 | if request.cap != ROOT { |
| 343 | 413 | let name = self.interp.op_name(request.effect, request.op); |
| 344 | | − self.exit( |
| 414 | + self.fail( |
| 345 | 415 | pid, |
| 346 | | − Reason::Crashed(format!("`{name}` used a handler that has already finished")), |
| 416 | + format!("`{name}` used a handler that has already finished"), |
| 347 | 417 | ); |
| 348 | 418 | return; |
| 349 | 419 | } |
| 350 | 420 | if Some(request.effect) != self.proc_effect { |
| 351 | 421 | let name = self.interp.op_name(request.effect, request.op); |
| 352 | | − self.exit( |
| 353 | | − pid, |
| 354 | | − Reason::Crashed(format!("unhandled effect operation `{name}`")), |
| 355 | | − ); |
| 422 | + self.fail(pid, format!("unhandled effect operation `{name}`")); |
| 356 | 423 | return; |
| 357 | 424 | } |
| 358 | 425 | let op = self.interp.program.effects[request.effect as usize].ops[request.op as usize] |
| @@ -365,7 +432,7 @@ impl Sched<'_> { |
| 365 | 432 | "spawn" | "spawn_link" | "spawn_monitor" | "send" |
| 366 | 433 | ) && let Some(reason) = request.args.iter().find_map(unsendable) |
| 367 | 434 | { |
| 368 | | − self.exit(pid, Reason::Crashed(reason.into())); |
| 435 | + self.fail(pid, reason); |
| 369 | 436 | return; |
| 370 | 437 | } |
| 371 | 438 | let mut args = request.args.into_iter(); |
| @@ -384,8 +451,8 @@ impl Sched<'_> { |
| 384 | 451 | match op.as_str() { |
| 385 | 452 | "spawn" => match self.spawn(Body::Closure(arg()), ACTOR_STACK) { |
| 386 | 453 | Ok(child) => self.reply(pid, Val::Pid(child)), |
| 387 | | − Err(RtError::Panic(m)) => self.exit(pid, Reason::Crashed(m)), |
| 388 | | − Err(e) => self.exit(pid, Reason::Crashed(e.to_string())), |
| 454 | + Err(RtError::Panic(m)) => self.fail(pid, m), |
| 455 | + Err(e) => self.fail(pid, e.to_string()), |
| 389 | 456 | }, |
| 390 | 457 | "spawn_link" => match self.spawn(Body::Closure(arg()), ACTOR_STACK) { |
| 391 | 458 | Ok(child) => { |
| @@ -396,8 +463,8 @@ impl Sched<'_> { |
| 396 | 463 | } |
| 397 | 464 | self.reply(pid, Val::Pid(child)); |
| 398 | 465 | } |
| 399 | | − Err(RtError::Panic(m)) => self.exit(pid, Reason::Crashed(m)), |
| 400 | | − Err(e) => self.exit(pid, Reason::Crashed(e.to_string())), |
| 466 | + Err(RtError::Panic(m)) => self.fail(pid, m), |
| 467 | + Err(e) => self.fail(pid, e.to_string()), |
| 401 | 468 | }, |
| 402 | 469 | "spawn_monitor" => match self.spawn(Body::Closure(arg()), ACTOR_STACK) { |
| 403 | 470 | Ok(child) => { |
| @@ -408,8 +475,8 @@ impl Sched<'_> { |
| 408 | 475 | Val::Tuple(vec![Val::Pid(child), subject(pid, tag)].into()), |
| 409 | 476 | ); |
| 410 | 477 | } |
| 411 | | − Err(RtError::Panic(m)) => self.exit(pid, Reason::Crashed(m)), |
| 412 | | − Err(e) => self.exit(pid, Reason::Crashed(e.to_string())), |
| 478 | + Err(RtError::Panic(m)) => self.fail(pid, m), |
| 479 | + Err(e) => self.fail(pid, e.to_string()), |
| 413 | 480 | }, |
| 414 | 481 | "self" => self.reply(pid, Val::Pid(pid)), |
| 415 | 482 | "subject" => { |
| @@ -426,10 +493,7 @@ impl Sched<'_> { |
| 426 | 493 | let (owner, tag) = subject_of(&arg()); |
| 427 | 494 | let timeout = crate::int::saturate(&arg()).unwrap_or(-1); |
| 428 | 495 | if owner != pid { |
| 429 | | − self.exit( |
| 430 | | − pid, |
| 431 | | − Reason::Crashed("receive on a subject owned by another actor".into()), |
| 432 | | − ); |
| 496 | + self.fail(pid, "receive on a subject owned by another actor"); |
| 433 | 497 | return; |
| 434 | 498 | } |
| 435 | 499 | let clock = self.clock; |
| @@ -530,17 +594,14 @@ impl Sched<'_> { |
| 530 | 594 | "sleep" => { |
| 531 | 595 | let ms = crate::int::saturate(&arg()).unwrap_or(0); |
| 532 | 596 | if ms <= 0 { |
| 533 | | − self.queue.push_back((pid, Val::Unit)); |
| 597 | + self.queue.push_back((pid, Ok(Val::Unit))); |
| 534 | 598 | } else if let Some(actor) = self.actors.get_mut(&pid) { |
| 535 | 599 | actor.wait = Wait::Sleep { |
| 536 | 600 | deadline: self.clock.saturating_add(ms as u64), |
| 537 | 601 | }; |
| 538 | 602 | } |
| 539 | 603 | } |
| 540 | | − other => self.exit( |
| 541 | | − pid, |
| 542 | | − Reason::Crashed(format!("unknown process operation `{other}`")), |
| 543 | | − ), |
| 604 | + other => self.fail(pid, format!("unknown process operation `{other}`")), |
| 544 | 605 | } |
| 545 | 606 | } |
| 546 | 607 | |
| @@ -571,7 +632,7 @@ impl Sched<'_> { |
| 571 | 632 | _ => none(), |
| 572 | 633 | }; |
| 573 | 634 | actor.wait = Wait::Ready; |
| 574 | | − self.queue.push_back((pid, answer)); |
| 635 | + self.queue.push_back((pid, Ok(answer))); |
| 575 | 636 | } |
| 576 | 637 | true |
| 577 | 638 | } |