| @@ -0,0 +1,454 @@ |
| 1 | +//! The interpreter's actor scheduler: OTP semantics (ADR 0004), made |
| 2 | +//! deterministic so test output is reproducible. |
| 3 | +//! |
| 4 | +//! - Every actor, including `main`, runs on its own fiber. Operations of |
| 5 | +//! the `std/process.proc` effect that no handler in the actor catches |
| 6 | +//! reach the actor's root as requests, and this scheduler answers them. |
| 7 | +//! - Round-robin run queue; an actor is preempted after [`REDUCTIONS`] |
| 8 | +//! calls. Spawned actors run after their parent's current slice. |
| 9 | +//! - Time is virtual: when no actor can run, the clock jumps to the next |
| 10 | +//! timeout (`receive` with a timeout, `sleep`). |
| 11 | +//! - Exits follow Erlang: an abnormal exit stops linked actors (or, if |
| 12 | +//! they trap exits, sends them an `ExitSignal`); monitors receive `Down`. |
| 13 | +//! - When `main` stops, the program ends and the other actors are stopped. |
| 14 | + |
| 15 | +use std::collections::{HashMap, VecDeque}; |
| 16 | + |
| 17 | +use corosensei::stack::DefaultStack; |
| 18 | +use corosensei::{CoroutineResult, Yielder}; |
| 19 | + |
| 20 | +use crate::interp::{Fiber, Interp, OpRequest, R, RtError, Val}; |
| 21 | +use crate::ir::{EffectId, FnId}; |
| 22 | + |
| 23 | +/// The pseudo-effect a running actor performs to give up its slice. |
| 24 | +pub(crate) const PREEMPT: EffectId = EffectId::MAX; |
| 25 | +/// Calls an actor may make before it is preempted. |
| 26 | +pub(crate) const REDUCTIONS: u32 = 2000; |
| 27 | +/// Virtual stack sizes (committed lazily). |
| 28 | +const MAIN_STACK: usize = 1 << 30; |
| 29 | +const ACTOR_STACK: usize = 16 << 20; |
| 30 | + |
| 31 | +#[derive(Clone, Debug)] |
| 32 | +enum Reason { |
| 33 | + Normal, |
| 34 | + Killed, |
| 35 | + Crashed(String), |
| 36 | +} |
| 37 | + |
| 38 | +enum Wait { |
| 39 | + Ready, |
| 40 | + Receive { tag: i64, deadline: Option<u64> }, |
| 41 | + Sleep { deadline: u64 }, |
| 42 | +} |
| 43 | + |
| 44 | +struct Actor { |
| 45 | + fiber: Option<Fiber>, |
| 46 | + mailbox: VecDeque<(i64, Val)>, |
| 47 | + wait: Wait, |
| 48 | + links: Vec<u64>, |
| 49 | + trap: bool, |
| 50 | + exits_tag: Option<i64>, |
| 51 | +} |
| 52 | + |
| 53 | +enum Body { |
| 54 | + Entry(FnId), |
| 55 | + Closure(Val), |
| 56 | +} |
| 57 | + |
| 58 | +struct Sched<'a> { |
| 59 | + interp: &'a Interp, |
| 60 | + actors: HashMap<u64, Actor>, |
| 61 | + queue: VecDeque<(u64, Val)>, |
| 62 | + next_pid: u64, |
| 63 | + next_tag: i64, |
| 64 | + clock: u64, |
| 65 | + /// (watched, watcher, tag) |
| 66 | + monitors: Vec<(u64, u64, i64)>, |
| 67 | + proc_effect: Option<EffectId>, |
| 68 | + main: u64, |
| 69 | + outcome: Option<R<()>>, |
| 70 | +} |
| 71 | + |
| 72 | +pub(crate) fn run_actors(interp: &Interp, entry: FnId) -> R<()> { |
| 73 | + let proc_effect = interp |
| 74 | + .program |
| 75 | + .effects |
| 76 | + .iter() |
| 77 | + .position(|e| e.name == "std/process.proc") |
| 78 | + .map(|i| i as EffectId); |
| 79 | + let mut s = Sched { |
| 80 | + interp, |
| 81 | + actors: HashMap::new(), |
| 82 | + queue: VecDeque::new(), |
| 83 | + next_pid: 0, |
| 84 | + next_tag: 0, |
| 85 | + clock: 0, |
| 86 | + monitors: Vec::new(), |
| 87 | + proc_effect, |
| 88 | + main: 0, |
| 89 | + outcome: None, |
| 90 | + }; |
| 91 | + s.main = s.spawn(Body::Entry(entry), MAIN_STACK)?; |
| 92 | + while s.outcome.is_none() { |
| 93 | + let Some((pid, input)) = s.queue.pop_front() else { |
| 94 | + if !s.advance_clock() { |
| 95 | + return Err(RtError::Panic( |
| 96 | + "deadlock: every actor is waiting for a message".into(), |
| 97 | + )); |
| 98 | + } |
| 99 | + continue; |
| 100 | + }; |
| 101 | + let Some(mut fiber) = s.actors.get_mut(&pid).and_then(|a| a.fiber.take()) else { |
| 102 | + continue; |
| 103 | + }; |
| 104 | + interp.state.current.set(std::ptr::null()); |
| 105 | + interp.state.reductions.set(0); |
| 106 | + let step = fiber.resume(input); |
| 107 | + interp.state.current.set(std::ptr::null()); |
| 108 | + match step { |
| 109 | + CoroutineResult::Return(result) => { |
| 110 | + drop(fiber); |
| 111 | + if pid == s.main { |
| 112 | + s.outcome = Some(result.clone().map(|_| ())); |
| 113 | + } |
| 114 | + let reason = match result { |
| 115 | + Ok(_) => Reason::Normal, |
| 116 | + Err(e) => Reason::Crashed(match e { |
| 117 | + RtError::Panic(m) => m, |
| 118 | + unhandled => unhandled.to_string(), |
| 119 | + }), |
| 120 | + }; |
| 121 | + s.exit(pid, reason); |
| 122 | + } |
| 123 | + CoroutineResult::Yield(request) => { |
| 124 | + if let Some(actor) = s.actors.get_mut(&pid) { |
| 125 | + actor.fiber = Some(fiber); |
| 126 | + } |
| 127 | + s.request(pid, request); |
| 128 | + } |
| 129 | + } |
| 130 | + } |
| 131 | + // `main` stopped: stop the others (dropping a suspended fiber unwinds it). |
| 132 | + s.actors.clear(); |
| 133 | + s.outcome.unwrap_or(Ok(())) |
| 134 | +} |
| 135 | + |
| 136 | +fn data(tag: u32, name: &str, fields: Vec<Val>) -> Val { |
| 137 | + Val::Data { |
| 138 | + tag, |
| 139 | + name: name.into(), |
| 140 | + fields: fields.into(), |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +// Constructor tags follow declaration order in std/process.til and the |
| 145 | +// prelude (checked by the `process` run test). |
| 146 | +fn some(v: Val) -> Val { |
| 147 | + data(1, "Some", vec![v]) |
| 148 | +} |
| 149 | + |
| 150 | +fn none() -> Val { |
| 151 | + data(0, "None", Vec::new()) |
| 152 | +} |
| 153 | + |
| 154 | +fn subject(owner: u64, tag: i64) -> Val { |
| 155 | + data(0, "Subject", vec![Val::Pid(owner), Val::Int(tag)]) |
| 156 | +} |
| 157 | + |
| 158 | +fn reason_val(r: &Reason) -> Val { |
| 159 | + match r { |
| 160 | + Reason::Normal => data(0, "Normal", Vec::new()), |
| 161 | + Reason::Killed => data(1, "Killed", Vec::new()), |
| 162 | + Reason::Crashed(m) => data(2, "Crashed", vec![Val::Str(m.as_str().into())]), |
| 163 | + } |
| 164 | +} |
| 165 | + |
| 166 | +impl Sched<'_> { |
| 167 | + fn spawn(&mut self, body: Body, stack: usize) -> R<u64> { |
| 168 | + let pid = self.next_pid; |
| 169 | + self.next_pid += 1; |
| 170 | + let interp = self.interp.clone(); |
| 171 | + let stack = DefaultStack::new(stack) |
| 172 | + .map_err(|e| RtError::Panic(format!("cannot allocate an actor stack: {e}")))?; |
| 173 | + let fiber = Fiber::with_stack(stack, move |yielder: &Yielder<Val, OpRequest>, _: Val| { |
| 174 | + interp.state.current.set(yielder); |
| 175 | + match body { |
| 176 | + Body::Entry(f) => interp.call_fn(f, Vec::new()), |
| 177 | + Body::Closure(c) => interp.call_val(&c, Vec::new()), |
| 178 | + } |
| 179 | + }); |
| 180 | + self.actors.insert( |
| 181 | + pid, |
| 182 | + Actor { |
| 183 | + fiber: Some(fiber), |
| 184 | + mailbox: VecDeque::new(), |
| 185 | + wait: Wait::Ready, |
| 186 | + links: Vec::new(), |
| 187 | + trap: false, |
| 188 | + exits_tag: None, |
| 189 | + }, |
| 190 | + ); |
| 191 | + self.queue.push_back((pid, Val::Unit)); |
| 192 | + Ok(pid) |
| 193 | + } |
| 194 | + |
| 195 | + fn tag(&mut self) -> i64 { |
| 196 | + self.next_tag += 1; |
| 197 | + self.next_tag |
| 198 | + } |
| 199 | + |
| 200 | + /// Continue `pid` right away with `answer`. |
| 201 | + fn reply(&mut self, pid: u64, answer: Val) { |
| 202 | + if self.actors.contains_key(&pid) { |
| 203 | + self.queue.push_front((pid, answer)); |
| 204 | + } |
| 205 | + } |
| 206 | + |
| 207 | + fn deliver(&mut self, owner: u64, tag: i64, message: Val) { |
| 208 | + let Some(actor) = self.actors.get_mut(&owner) else { |
| 209 | + return; |
| 210 | + }; |
| 211 | + match actor.wait { |
| 212 | + Wait::Receive { tag: t, .. } if t == tag => { |
| 213 | + actor.wait = Wait::Ready; |
| 214 | + self.queue.push_back((owner, some(message))); |
| 215 | + } |
| 216 | + _ => actor.mailbox.push_back((tag, message)), |
| 217 | + } |
| 218 | + } |
| 219 | + |
| 220 | + fn exits_tag(&mut self, pid: u64) -> i64 { |
| 221 | + if let Some(t) = self.actors.get(&pid).and_then(|a| a.exits_tag) { |
| 222 | + return t; |
| 223 | + } |
| 224 | + let t = self.tag(); |
| 225 | + if let Some(a) = self.actors.get_mut(&pid) { |
| 226 | + a.exits_tag = Some(t); |
| 227 | + } |
| 228 | + t |
| 229 | + } |
| 230 | + |
| 231 | + /// Stop `pid`, notify monitors, and propagate the exit through links. |
| 232 | + fn exit(&mut self, pid: u64, reason: Reason) { |
| 233 | + let Some(actor) = self.actors.remove(&pid) else { |
| 234 | + return; |
| 235 | + }; |
| 236 | + let links = actor.links.clone(); |
| 237 | + drop(actor); |
| 238 | + if pid == self.main && self.outcome.is_none() { |
| 239 | + self.outcome = Some(match &reason { |
| 240 | + Reason::Normal => Ok(()), |
| 241 | + Reason::Killed => Err(RtError::Panic("the main actor was killed".into())), |
| 242 | + Reason::Crashed(m) => Err(RtError::Panic(m.clone())), |
| 243 | + }); |
| 244 | + } |
| 245 | + if let Reason::Crashed(m) = &reason |
| 246 | + && pid != self.main |
| 247 | + { |
| 248 | + eprintln!("actor {pid} crashed: {m}"); |
| 249 | + } |
| 250 | + let (fired, kept): (Vec<_>, Vec<_>) = self |
| 251 | + .monitors |
| 252 | + .drain(..) |
| 253 | + .partition(|(watched, _, _)| *watched == pid); |
| 254 | + self.monitors = kept; |
| 255 | + for (_, watcher, tag) in fired { |
| 256 | + self.deliver( |
| 257 | + watcher, |
| 258 | + tag, |
| 259 | + data(0, "Down", vec![Val::Pid(pid), reason_val(&reason)]), |
| 260 | + ); |
| 261 | + } |
| 262 | + for linked in links { |
| 263 | + let Some(other) = self.actors.get_mut(&linked) else { |
| 264 | + continue; |
| 265 | + }; |
| 266 | + other.links.retain(|l| *l != pid); |
| 267 | + // As in Erlang: actors that trap exits are told about every |
| 268 | + // exit, normal ones included; others only die of abnormal ones. |
| 269 | + if other.trap { |
| 270 | + let tag = self.exits_tag(linked); |
| 271 | + self.deliver( |
| 272 | + linked, |
| 273 | + tag, |
| 274 | + data(0, "ExitSignal", vec![Val::Pid(pid), reason_val(&reason)]), |
| 275 | + ); |
| 276 | + } else if !matches!(reason, Reason::Normal) { |
| 277 | + self.exit(linked, reason.clone()); |
| 278 | + } |
| 279 | + } |
| 280 | + } |
| 281 | + |
| 282 | + fn request(&mut self, pid: u64, request: OpRequest) { |
| 283 | + if request.effect == PREEMPT { |
| 284 | + self.queue.push_back((pid, Val::Unit)); |
| 285 | + return; |
| 286 | + } |
| 287 | + if Some(request.effect) != self.proc_effect { |
| 288 | + let name = self.interp.op_name(request.effect, request.op); |
| 289 | + self.exit( |
| 290 | + pid, |
| 291 | + Reason::Crashed(format!("unhandled effect operation `{name}`")), |
| 292 | + ); |
| 293 | + return; |
| 294 | + } |
| 295 | + let op = self.interp.program.effects[request.effect as usize].ops[request.op as usize] |
| 296 | + .0 |
| 297 | + .clone(); |
| 298 | + let mut args = request.args.into_iter(); |
| 299 | + let mut arg = || args.next().unwrap_or(Val::Unit); |
| 300 | + let pid_of = |v: &Val| match v { |
| 301 | + Val::Pid(p) => *p, |
| 302 | + _ => u64::MAX, |
| 303 | + }; |
| 304 | + let subject_of = |v: &Val| match v { |
| 305 | + Val::Data { fields, .. } => match (&fields[0], &fields[1]) { |
| 306 | + (Val::Pid(p), Val::Int(t)) => (*p, *t), |
| 307 | + _ => (u64::MAX, 0), |
| 308 | + }, |
| 309 | + _ => (u64::MAX, 0), |
| 310 | + }; |
| 311 | + match op.as_str() { |
| 312 | + "spawn" => match self.spawn(Body::Closure(arg()), ACTOR_STACK) { |
| 313 | + Ok(child) => self.reply(pid, Val::Pid(child)), |
| 314 | + Err(RtError::Panic(m)) => self.exit(pid, Reason::Crashed(m)), |
| 315 | + Err(e) => self.exit(pid, Reason::Crashed(e.to_string())), |
| 316 | + }, |
| 317 | + "self" => self.reply(pid, Val::Pid(pid)), |
| 318 | + "subject" => { |
| 319 | + let tag = self.tag(); |
| 320 | + self.reply(pid, subject(pid, tag)); |
| 321 | + } |
| 322 | + "send" => { |
| 323 | + let (owner, tag) = subject_of(&arg()); |
| 324 | + let message = arg(); |
| 325 | + self.deliver(owner, tag, message); |
| 326 | + self.reply(pid, Val::Unit); |
| 327 | + } |
| 328 | + "receive" => { |
| 329 | + let (owner, tag) = subject_of(&arg()); |
| 330 | + let timeout = match arg() { |
| 331 | + Val::Int(t) => t, |
| 332 | + _ => -1, |
| 333 | + }; |
| 334 | + if owner != pid { |
| 335 | + self.exit( |
| 336 | + pid, |
| 337 | + Reason::Crashed("receive on a subject owned by another actor".into()), |
| 338 | + ); |
| 339 | + return; |
| 340 | + } |
| 341 | + let clock = self.clock; |
| 342 | + let Some(actor) = self.actors.get_mut(&pid) else { |
| 343 | + return; |
| 344 | + }; |
| 345 | + if let Some(i) = actor.mailbox.iter().position(|(t, _)| *t == tag) { |
| 346 | + let (_, message) = actor.mailbox.remove(i).expect("found"); |
| 347 | + self.reply(pid, some(message)); |
| 348 | + } else if timeout == 0 { |
| 349 | + self.reply(pid, none()); |
| 350 | + } else { |
| 351 | + let deadline = (timeout > 0).then(|| clock + timeout as u64); |
| 352 | + actor.wait = Wait::Receive { tag, deadline }; |
| 353 | + } |
| 354 | + } |
| 355 | + "link" => { |
| 356 | + let other = pid_of(&arg()); |
| 357 | + if other != pid && self.actors.contains_key(&other) { |
| 358 | + for (a, b) in [(pid, other), (other, pid)] { |
| 359 | + if let Some(actor) = self.actors.get_mut(&a) |
| 360 | + && !actor.links.contains(&b) |
| 361 | + { |
| 362 | + actor.links.push(b); |
| 363 | + } |
| 364 | + } |
| 365 | + } |
| 366 | + self.reply(pid, Val::Unit); |
| 367 | + } |
| 368 | + "monitor" => { |
| 369 | + let watched = pid_of(&arg()); |
| 370 | + let tag = self.tag(); |
| 371 | + if self.actors.contains_key(&watched) { |
| 372 | + self.monitors.push((watched, pid, tag)); |
| 373 | + } else { |
| 374 | + // Like Erlang's `noproc`: the actor is already gone. |
| 375 | + let down = data( |
| 376 | + 0, |
| 377 | + "Down", |
| 378 | + vec![ |
| 379 | + Val::Pid(watched), |
| 380 | + reason_val(&Reason::Crashed("noproc".into())), |
| 381 | + ], |
| 382 | + ); |
| 383 | + self.deliver(pid, tag, down); |
| 384 | + } |
| 385 | + self.reply(pid, subject(pid, tag)); |
| 386 | + } |
| 387 | + "kill" => { |
| 388 | + let target = pid_of(&arg()); |
| 389 | + self.exit(target, Reason::Killed); |
| 390 | + self.reply(pid, Val::Unit); |
| 391 | + } |
| 392 | + "trap_exits" => { |
| 393 | + let on = matches!(arg(), Val::Data { tag: 1, .. }); |
| 394 | + if let Some(actor) = self.actors.get_mut(&pid) { |
| 395 | + actor.trap = on; |
| 396 | + } |
| 397 | + self.reply(pid, Val::Unit); |
| 398 | + } |
| 399 | + "exits" => { |
| 400 | + let tag = self.exits_tag(pid); |
| 401 | + self.reply(pid, subject(pid, tag)); |
| 402 | + } |
| 403 | + "sleep" => { |
| 404 | + let ms = match arg() { |
| 405 | + Val::Int(ms) => ms, |
| 406 | + _ => 0, |
| 407 | + }; |
| 408 | + if ms <= 0 { |
| 409 | + self.queue.push_back((pid, Val::Unit)); |
| 410 | + } else if let Some(actor) = self.actors.get_mut(&pid) { |
| 411 | + actor.wait = Wait::Sleep { |
| 412 | + deadline: self.clock + ms as u64, |
| 413 | + }; |
| 414 | + } |
| 415 | + } |
| 416 | + other => self.exit( |
| 417 | + pid, |
| 418 | + Reason::Crashed(format!("unknown process operation `{other}`")), |
| 419 | + ), |
| 420 | + } |
| 421 | + } |
| 422 | + |
| 423 | + /// Jump the virtual clock to the next deadline and wake those actors. |
| 424 | + fn advance_clock(&mut self) -> bool { |
| 425 | + let deadline = |a: &Actor| match a.wait { |
| 426 | + Wait::Receive { |
| 427 | + deadline: Some(d), .. |
| 428 | + } |
| 429 | + | Wait::Sleep { deadline: d } => Some(d), |
| 430 | + _ => None, |
| 431 | + }; |
| 432 | + let Some(next) = self.actors.values().filter_map(deadline).min() else { |
| 433 | + return false; |
| 434 | + }; |
| 435 | + self.clock = next; |
| 436 | + let mut due: Vec<u64> = self |
| 437 | + .actors |
| 438 | + .iter() |
| 439 | + .filter(|(_, a)| deadline(a) == Some(next)) |
| 440 | + .map(|(p, _)| *p) |
| 441 | + .collect(); |
| 442 | + due.sort(); |
| 443 | + for pid in due { |
| 444 | + let actor = self.actors.get_mut(&pid).expect("listed"); |
| 445 | + let answer = match actor.wait { |
| 446 | + Wait::Sleep { .. } => Val::Unit, |
| 447 | + _ => none(), |
| 448 | + }; |
| 449 | + actor.wait = Wait::Ready; |
| 450 | + self.queue.push_back((pid, answer)); |
| 451 | + } |
| 452 | + true |
| 453 | + } |
| 454 | +} |