Skip to main content

logicaffeine_runtime/
scheduler.rs

1//! The scheduler core + cooperative driver.
2//!
3//! A single, deterministic, seed-driven scheduler that multiplexes [`Task`]s over
4//! channels, `Select`, and timers. The cooperative driver ([`Scheduler::run`])
5//! runs everything on one thread, resolving every nondeterministic decision
6//! through the embedded [`Chooser`] (so a fixed seed ⇒ a fixed run, and a trace
7//! ⇒ an exact replay). The ready-selection discipline is the configured
8//! [`SchedulePolicy`]; determinism holds under all of them.
9
10use std::collections::{HashMap, HashSet};
11
12use crate::channel::{Chan, ChanId};
13use crate::config::{SchedulePolicy, SchedulerConfig};
14use crate::payload::RtPayload;
15use crate::seed::{ChoiceKind, Chooser, SchedSeed, SchedTrace};
16use crate::task::{SelectArm, Task, TaskCtx, TaskId, TaskStep};
17
18/// The result of running a scheduler to quiescence.
19#[derive(Debug, Clone, PartialEq)]
20pub enum RunOutcome {
21    /// Every task finished. Carries the main task's result (or `Nothing`).
22    Done(RtPayload),
23    /// Tasks remain but all are blocked with no timer to fire — a deadlock.
24    Deadlock,
25    /// Tasks remain, none ready and no timer to fire, but at least one is parked on
26    /// external async I/O (`TaskState::BlockedIo`) — not a deadlock. The scheduler has no
27    /// reactor; the async drive loop must yield to the host reactor, then [`Scheduler::wake_io`]
28    /// to re-poll the parked tasks. The synchronous `run()` cannot make progress here.
29    WaitingForIo,
30}
31
32enum TaskState {
33    Ready,
34    BlockedRecv,
35    BlockedSend,
36    BlockedSelect,
37    BlockedTimer,
38    BlockedAwait,
39    BlockedIo,
40    Done,
41}
42
43/// A public, read-only projection of a task's scheduling state — what the Studio's
44/// Tasks/Channels strip renders. Mirrors the private `TaskState` without exposing the
45/// task body or any mutable handle.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum TaskStateKind {
48    Ready,
49    BlockedRecv,
50    BlockedSend,
51    BlockedSelect,
52    BlockedTimer,
53    BlockedAwait,
54    BlockedIo,
55    Done,
56}
57
58impl TaskState {
59    fn kind(&self) -> TaskStateKind {
60        match self {
61            TaskState::Ready => TaskStateKind::Ready,
62            TaskState::BlockedRecv => TaskStateKind::BlockedRecv,
63            TaskState::BlockedSend => TaskStateKind::BlockedSend,
64            TaskState::BlockedSelect => TaskStateKind::BlockedSelect,
65            TaskState::BlockedTimer => TaskStateKind::BlockedTimer,
66            TaskState::BlockedAwait => TaskStateKind::BlockedAwait,
67            TaskState::BlockedIo => TaskStateKind::BlockedIo,
68            TaskState::Done => TaskStateKind::Done,
69        }
70    }
71}
72
73/// A read-only view of one task for [`Scheduler::snapshot`].
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub struct TaskView {
76    pub id: TaskId,
77    pub kind: TaskStateKind,
78    pub is_main: bool,
79}
80
81/// A read-only view of one channel for [`Scheduler::snapshot`].
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub struct ChanView {
84    pub id: ChanId,
85    /// Buffered values waiting to be received.
86    pub depth: usize,
87    /// `None` for an unbounded channel, `Some(0)` for a rendezvous channel.
88    pub capacity: Option<usize>,
89    pub blocked_senders: usize,
90    pub blocked_receivers: usize,
91    pub closed: bool,
92}
93
94/// A deterministic, read-only snapshot of the scheduler between steps — the observability
95/// seam the browser drive loop emits to the Studio so a running concurrent program shows
96/// its live task and channel state instead of freezing the UI.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct SchedSnapshot {
99    /// The logical clock (the timer wheel's current tick).
100    pub clock: u64,
101    /// How many tasks are ready to run right now.
102    pub ready_len: usize,
103    /// Every task, sorted by id (deterministic order for a stable UI).
104    pub tasks: Vec<TaskView>,
105    /// Every channel, sorted by id.
106    pub channels: Vec<ChanView>,
107}
108
109/// Narrate a deadlock as English prose: the cooperative deterministic runtime has PERFECT information, so the
110/// explanation is a proof, not a heuristic — who waits, on what, and how full
111/// each channel is. Fed the snapshot taken when the scheduler proved the
112/// deadlock.
113pub fn narrate_deadlock(snap: &SchedSnapshot) -> String {
114    let mut lines = vec![format!(
115        "Deadlock at tick {} — every remaining task is blocked, and no timer can fire.",
116        snap.clock
117    )];
118    lines.push("  The blocked tasks:".to_string());
119    for t in &snap.tasks {
120        let why = match t.kind {
121            TaskStateKind::BlockedRecv => "waiting to RECEIVE from a channel",
122            TaskStateKind::BlockedSend => "waiting to SEND into a full channel",
123            TaskStateKind::BlockedSelect => "waiting in a select with no ready arm",
124            TaskStateKind::BlockedAwait => "waiting on a peer that never answers",
125            TaskStateKind::BlockedTimer => "waiting on a timer that never fires",
126            TaskStateKind::BlockedIo => "waiting on I/O that never completes",
127            // Ready and Done tasks are not part of the blocked cycle.
128            TaskStateKind::Ready | TaskStateKind::Done => continue,
129        };
130        lines.push(format!(
131            "    task {} ({}) is {}",
132            t.id.0,
133            if t.is_main { "main" } else { "spawned" },
134            why
135        ));
136    }
137    if !snap.channels.is_empty() {
138        lines.push("  The channels:".to_string());
139        for c in &snap.channels {
140            let cap = c
141                .capacity
142                .map(|c| c.to_string())
143                .unwrap_or_else(|| "∞".to_string());
144            lines.push(format!(
145                "    channel {} — {}/{} full, {} blocked sender(s), {} blocked receiver(s){}",
146                c.id.0,
147                c.depth,
148                cap,
149                c.blocked_senders,
150                c.blocked_receivers,
151                if c.closed { " (closed)" } else { "" }
152            ));
153        }
154    }
155    lines.join("\n")
156}
157
158/// How a finished task finished — delivered to anyone awaiting it.
159#[derive(Debug, Clone)]
160enum AwaitResult {
161    Completed(RtPayload),
162    Aborted,
163}
164
165impl AwaitResult {
166    fn payload(&self) -> RtPayload {
167        match self {
168            AwaitResult::Completed(p) => p.clone(),
169            AwaitResult::Aborted => RtPayload::Nothing,
170        }
171    }
172}
173
174struct TaskSlot<'t> {
175    task: Option<Box<dyn Task<'t> + 't>>,
176    priority: u8,
177    resume: RtPayload,
178    selected_arm: Option<usize>,
179    select_arms: Option<Vec<SelectArm>>,
180    /// Channel id to deliver on the next poll (after a `NewChan`).
181    resume_chan: Option<ChanId>,
182    /// Task id to deliver on the next poll (after a `Spawn`).
183    resume_task: Option<TaskId>,
184    state: TaskState,
185    is_main: bool,
186}
187
188struct TimerEntry {
189    fire_at: u64,
190    tid: TaskId,
191    /// `Some(i)` if this is the timeout arm `i` of a `Select`; `None` for a plain `Sleep`.
192    arm: Option<usize>,
193}
194
195/// The resume state of a ready task, taken by the work-stealing coordinator
196/// ([`crate::executor`]) to deliver to a worker thread. Mirrors the `TaskCtx` the
197/// cooperative `run` builds inline. (Native-only.)
198#[cfg(not(target_arch = "wasm32"))]
199pub(crate) struct WsDispatch {
200    pub tid: TaskId,
201    pub priority: u8,
202    pub selected_arm: Option<usize>,
203    pub resume: RtPayload,
204    pub new_chan: Option<ChanId>,
205    pub spawned: Option<TaskId>,
206}
207
208/// The deterministic task scheduler.
209pub struct Scheduler<'t> {
210    config: SchedulerConfig,
211    chooser: Chooser,
212    tasks: HashMap<TaskId, TaskSlot<'t>>,
213    ready: Vec<TaskId>,
214    chans: HashMap<ChanId, Chan>,
215    timers: Vec<TimerEntry>,
216    clock: u64,
217    next_id: u64,
218    main_result: Option<RtPayload>,
219    results: HashMap<TaskId, AwaitResult>,
220    awaiters: HashMap<TaskId, Vec<TaskId>>,
221}
222
223impl<'t> Scheduler<'t> {
224    /// A fresh scheduler with the given config and decision source.
225    pub fn new(config: SchedulerConfig, chooser: Chooser) -> Self {
226        Scheduler {
227            config,
228            chooser,
229            tasks: HashMap::new(),
230            ready: Vec::new(),
231            chans: HashMap::new(),
232            timers: Vec::new(),
233            clock: 0,
234            next_id: 0,
235            main_result: None,
236            results: HashMap::new(),
237            awaiters: HashMap::new(),
238        }
239    }
240
241    fn bump(&mut self) -> u64 {
242        let v = self.next_id;
243        self.next_id += 1;
244        v
245    }
246
247    /// Create a channel with an explicit capacity (`None` = unbounded, `Some(0)` = rendezvous).
248    pub fn new_chan(&mut self, capacity: Option<usize>) -> ChanId {
249        let id = ChanId(self.bump());
250        self.chans.insert(id, Chan::new(capacity));
251        id
252    }
253
254    /// Create a channel with the config's default capacity.
255    pub fn new_default_chan(&mut self) -> ChanId {
256        let cap = self.config.default_channel_capacity;
257        self.new_chan(Some(cap))
258    }
259
260    /// Spawn a task. Returns its id; it is enqueued ready.
261    pub fn spawn(&mut self, task: Box<dyn Task<'t> + 't>) -> TaskId {
262        let priority = task.priority();
263        self.spawn_inner(Some(task), priority, false)
264    }
265
266    /// Spawn the *main* task — its `Exit` value becomes the run's [`RunOutcome::Done`] payload.
267    pub fn spawn_main(&mut self, task: Box<dyn Task<'t> + 't>) -> TaskId {
268        let priority = task.priority();
269        self.spawn_inner(Some(task), priority, true)
270    }
271
272    fn spawn_inner(
273        &mut self,
274        task: Option<Box<dyn Task<'t> + 't>>,
275        priority: u8,
276        is_main: bool,
277    ) -> TaskId {
278        let id = TaskId(self.bump());
279        self.tasks.insert(
280            id,
281            TaskSlot {
282                task,
283                priority,
284                resume: RtPayload::Nothing,
285                selected_arm: None,
286                select_arms: None,
287                resume_chan: None,
288                resume_task: None,
289                state: TaskState::Ready,
290                is_main,
291            },
292        );
293        self.ready.push(id);
294        id
295    }
296
297    /// Spawn a *metadata-only* slot (no task body) for the work-stealing driver:
298    /// the body lives worker-side, built from a `Send` descriptor. Otherwise
299    /// identical to [`Self::spawn`] — enqueued ready, same id allocation. Returns
300    /// its id. (Native-only: the coordinator that uses it is `cfg(not(wasm32))`.)
301    #[cfg(not(target_arch = "wasm32"))]
302    pub(crate) fn spawn_meta(&mut self, priority: u8, is_main: bool) -> TaskId {
303        self.spawn_inner(None, priority, is_main)
304    }
305
306    /// Consume the scheduler and return the recorded scheduling trace.
307    pub fn into_trace(self) -> SchedTrace {
308        self.chooser.into_trace()
309    }
310
311    /// Run cooperatively to quiescence.
312    pub fn run(&mut self) -> RunOutcome {
313        loop {
314            if let Some(outcome) = self.poll_once() {
315                return outcome;
316            }
317        }
318    }
319
320    /// Advance the scheduler by a single step: dispatch one ready task, or (if none is
321    /// ready) advance the timer wheel. Returns `Some(outcome)` only at quiescence — when no
322    /// task is ready and no timer can fire — and `None` while there is still work to do.
323    /// `run` is `poll_once` to a fixpoint; the browser drive loop calls it in slices,
324    /// yielding a macrotask between them so the UI repaints. Both produce identical
325    /// behavior and identical traces by construction.
326    pub fn poll_once(&mut self) -> Option<RunOutcome> {
327        if let Some(tid) = self.pick_ready() {
328            let step = {
329                let slot = self.tasks.get_mut(&tid).expect("ready task exists");
330                let mut boxed = slot.task.take().expect("task body present");
331                let mut ctx = TaskCtx {
332                    resumed_with: std::mem::replace(&mut slot.resume, RtPayload::Nothing),
333                    selected_arm: slot.selected_arm.take(),
334                    new_chan: slot.resume_chan.take(),
335                    spawned: slot.resume_task.take(),
336                };
337                let step = boxed.poll(&mut ctx);
338                slot.task = Some(boxed);
339                step
340            };
341            self.process_step(tid, step);
342            None
343        } else if !self.timers.is_empty() {
344            self.advance_timers();
345            None
346        } else {
347            let all_done = self
348                .tasks
349                .values()
350                .all(|s| matches!(s.state, TaskState::Done));
351            let any_io = self
352                .tasks
353                .values()
354                .any(|s| matches!(s.state, TaskState::BlockedIo));
355            Some(if all_done {
356                RunOutcome::Done(self.main_result.clone().unwrap_or(RtPayload::Nothing))
357            } else if any_io {
358                // Not a deadlock: a task awaits external I/O the async drive loop will service.
359                RunOutcome::WaitingForIo
360            } else {
361                RunOutcome::Deadlock
362            })
363        }
364    }
365
366    /// Run at most `max_steps` steps. Returns `Some(outcome)` if quiescence was reached
367    /// within the budget, or `None` if work remains (the caller should yield and call
368    /// again). A `max_steps` of 0 makes no progress and returns `None`.
369    pub fn run_slice(&mut self, max_steps: usize) -> Option<RunOutcome> {
370        for _ in 0..max_steps {
371            if let Some(outcome) = self.poll_once() {
372                return Some(outcome);
373            }
374        }
375        None
376    }
377
378    /// Re-ready every task parked on external I/O (`TaskState::BlockedIo`), in ascending
379    /// id order (deterministic). The async drive loop calls this after yielding to the host
380    /// reactor so the parked tasks re-poll their network futures. Returns whether any task was
381    /// woken. Channel/timer tasks are untouched, so a non-networking program never sees this.
382    pub fn wake_io(&mut self) -> bool {
383        let mut io_tasks: Vec<TaskId> = self
384            .tasks
385            .iter()
386            .filter(|(_, s)| matches!(s.state, TaskState::BlockedIo))
387            .map(|(id, _)| *id)
388            .collect();
389        io_tasks.sort_by_key(|t| t.0);
390        for tid in &io_tasks {
391            let slot = self.tasks.get_mut(tid).unwrap();
392            slot.state = TaskState::Ready;
393            self.ready.push(*tid);
394        }
395        !io_tasks.is_empty()
396    }
397
398    /// A deterministic, read-only snapshot of the current task and channel state — emitted
399    /// between slices to drive the Studio's Tasks/Channels strip. Tasks and channels are
400    /// sorted by id so the UI order is stable across snapshots.
401    pub fn snapshot(&self) -> SchedSnapshot {
402        let mut tasks: Vec<TaskView> = self
403            .tasks
404            .iter()
405            .map(|(id, slot)| TaskView {
406                id: *id,
407                kind: slot.state.kind(),
408                is_main: slot.is_main,
409            })
410            .collect();
411        tasks.sort_by_key(|t| t.id.0);
412        let mut channels: Vec<ChanView> = self
413            .chans
414            .iter()
415            .map(|(id, ch)| ChanView {
416                id: *id,
417                depth: ch.queue.len(),
418                capacity: ch.capacity,
419                blocked_senders: ch.blocked_senders.len(),
420                blocked_receivers: ch.blocked_receivers.len(),
421                closed: ch.closed,
422            })
423            .collect();
424        channels.sort_by_key(|c| c.id.0);
425        SchedSnapshot {
426            clock: self.clock,
427            ready_len: self.ready.len(),
428            tasks,
429            channels,
430        }
431    }
432
433    // ─── Work-stealing coordinator hooks (native-only) ──────────────────────
434    // The work-stealing driver (`executor.rs`) owns a `Scheduler` with
435    // metadata-only slots and drives it externally: it dispatches ready tasks to
436    // worker threads (each builds + polls the `!Send` body locally) and applies
437    // the workers' `Send` `StepReport`s through the SAME `process_step`/`do_*`
438    // methods — so channel and decision semantics, and the seeded trace, are
439    // identical to the cooperative run.
440
441    /// Spawn a metadata child + ready the parent with the child's handle, exactly
442    /// as the cooperative `Spawn` step does. Returns the child's id (the
443    /// coordinator records its build descriptor under that id).
444    #[cfg(not(target_arch = "wasm32"))]
445    pub(crate) fn ws_spawn_child(&mut self, parent: TaskId, priority: u8) -> TaskId {
446        let child = self.spawn_meta(priority, false);
447        self.tasks.get_mut(&parent).unwrap().resume_task = Some(child);
448        self.mark_ready(parent, RtPayload::Nothing);
449        child
450    }
451
452    /// Pick the next ready task (the same `pick_ready` discipline as cooperative)
453    /// and take its resume state, for the coordinator to deliver to a worker.
454    #[cfg(not(target_arch = "wasm32"))]
455    pub(crate) fn ws_next_dispatch(&mut self) -> Option<WsDispatch> {
456        let tid = self.pick_ready()?;
457        let slot = self.tasks.get_mut(&tid).expect("ready task exists");
458        Some(WsDispatch {
459            tid,
460            priority: slot.priority,
461            selected_arm: slot.selected_arm.take(),
462            resume: std::mem::replace(&mut slot.resume, RtPayload::Nothing),
463            new_chan: slot.resume_chan.take(),
464            spawned: slot.resume_task.take(),
465        })
466    }
467
468    /// Every task finished?
469    #[cfg(not(target_arch = "wasm32"))]
470    pub(crate) fn ws_all_done(&self) -> bool {
471        self.tasks
472            .values()
473            .all(|s| matches!(s.state, TaskState::Done))
474    }
475
476    /// Are there pending timers (advance the logical clock when no task is ready)?
477    #[cfg(not(target_arch = "wasm32"))]
478    pub(crate) fn ws_has_timers(&self) -> bool {
479        !self.timers.is_empty()
480    }
481
482    /// Advance the timer wheel (marks timer / select-timeout tasks ready).
483    #[cfg(not(target_arch = "wasm32"))]
484    pub(crate) fn ws_advance_timers(&mut self) {
485        self.advance_timers();
486    }
487
488    /// The main task's result (or `Nothing`).
489    #[cfg(not(target_arch = "wasm32"))]
490    pub(crate) fn ws_main_result(&self) -> RtPayload {
491        self.main_result.clone().unwrap_or(RtPayload::Nothing)
492    }
493
494    fn pick_ready(&mut self) -> Option<TaskId> {
495        if self.ready.is_empty() {
496            return None;
497        }
498        let idx = match self.config.policy {
499            SchedulePolicy::Fifo | SchedulePolicy::RoundRobin => 0,
500            SchedulePolicy::Lifo => self.ready.len() - 1,
501            SchedulePolicy::Random => self.chooser.decide(ChoiceKind::TaskPick, self.ready.len()),
502            SchedulePolicy::Priority => {
503                let mut best = 0usize;
504                let mut best_pri = self.tasks[&self.ready[0]].priority;
505                for i in 1..self.ready.len() {
506                    let p = self.tasks[&self.ready[i]].priority;
507                    if p > best_pri {
508                        best_pri = p;
509                        best = i;
510                    }
511                }
512                best
513            }
514        };
515        Some(self.ready.remove(idx))
516    }
517
518    pub(crate) fn process_step(&mut self, tid: TaskId, step: TaskStep<'t>) {
519        match step {
520            TaskStep::Yield => self.mark_ready(tid, RtPayload::Nothing),
521            TaskStep::Await(target) => self.do_await(tid, target),
522            TaskStep::Abort(target) => {
523                self.do_abort(target);
524                self.mark_ready(tid, RtPayload::Nothing);
525            }
526            TaskStep::Close(ch) => {
527                self.do_close(ch);
528                self.mark_ready(tid, RtPayload::Nothing);
529            }
530            TaskStep::Exit(v) => {
531                if self.tasks[&tid].is_main {
532                    self.main_result = Some(v.clone());
533                }
534                self.tasks.get_mut(&tid).unwrap().state = TaskState::Done;
535                self.complete_task(tid, AwaitResult::Completed(v));
536            }
537            TaskStep::Spawn(child) => {
538                let child_id = self.spawn(child);
539                self.tasks.get_mut(&tid).unwrap().resume_task = Some(child_id);
540                self.mark_ready(tid, RtPayload::Nothing);
541            }
542            // The descriptor form is produced only by work-stealing tasks and is
543            // serviced by the coordinator (which builds the child worker-side),
544            // never the inline `process_step`.
545            TaskStep::SpawnDesc { .. } => {
546                unreachable!(
547                    "SpawnDesc is serviced by the work-stealing coordinator, not process_step"
548                )
549            }
550            TaskStep::NewChan(cap) => {
551                let capacity = Some(cap.unwrap_or(self.config.default_channel_capacity));
552                let id = self.new_chan(capacity);
553                self.tasks.get_mut(&tid).unwrap().resume_chan = Some(id);
554                self.mark_ready(tid, RtPayload::Nothing);
555            }
556            TaskStep::Send(ch, payload) => self.do_send(tid, ch, payload),
557            TaskStep::TrySend(ch, payload) => self.do_try_send(tid, ch, payload),
558            TaskStep::Recv(ch) => self.do_recv(tid, ch),
559            TaskStep::TryRecv(ch) => self.do_try_recv(tid, ch),
560            TaskStep::Sleep(d) => {
561                self.timers.push(TimerEntry {
562                    fire_at: self.clock + d,
563                    tid,
564                    arm: None,
565                });
566                self.tasks.get_mut(&tid).unwrap().state = TaskState::BlockedTimer;
567            }
568            TaskStep::Select(arms) => self.do_select(tid, arms),
569            TaskStep::IoPending => {
570                // Parked on external async I/O. The scheduler has no reactor; the async drive
571                // loop re-readies this task via `wake_io` after yielding to the host reactor.
572                self.tasks.get_mut(&tid).unwrap().state = TaskState::BlockedIo;
573            }
574        }
575    }
576
577    fn mark_ready(&mut self, tid: TaskId, value: RtPayload) {
578        let slot = self.tasks.get_mut(&tid).unwrap();
579        slot.resume = value;
580        slot.state = TaskState::Ready;
581        self.ready.push(tid);
582    }
583
584    fn do_send(&mut self, tid: TaskId, ch: ChanId, payload: RtPayload) {
585        let waiting_receiver = self
586            .chans
587            .get_mut(&ch)
588            .unwrap()
589            .blocked_receivers
590            .pop_front();
591        if let Some(rid) = waiting_receiver {
592            self.deliver_to_receiver(rid, ch, payload);
593            self.mark_ready(tid, RtPayload::Nothing);
594            return;
595        }
596        if self.chans[&ch].has_room() {
597            self.chans.get_mut(&ch).unwrap().queue.push_back(payload);
598            self.mark_ready(tid, RtPayload::Nothing);
599        } else {
600            self.chans
601                .get_mut(&ch)
602                .unwrap()
603                .blocked_senders
604                .push_back((tid, payload));
605            self.tasks.get_mut(&tid).unwrap().state = TaskState::BlockedSend;
606        }
607    }
608
609    fn do_recv(&mut self, tid: TaskId, ch: ChanId) {
610        let from_queue = self.chans.get_mut(&ch).unwrap().queue.pop_front();
611        if let Some(v) = from_queue {
612            self.mark_ready(tid, v);
613            self.refill_from_blocked_sender(ch);
614            return;
615        }
616        let from_sender = self.chans.get_mut(&ch).unwrap().blocked_senders.pop_front();
617        if let Some((sid, payload)) = from_sender {
618            self.mark_ready(tid, payload);
619            self.mark_ready(sid, RtPayload::Nothing);
620            return;
621        }
622        if self.chans[&ch].closed {
623            self.mark_ready(tid, RtPayload::Nothing);
624            return;
625        }
626        self.chans
627            .get_mut(&ch)
628            .unwrap()
629            .blocked_receivers
630            .push_back(tid);
631        self.tasks.get_mut(&tid).unwrap().state = TaskState::BlockedRecv;
632    }
633
634    fn do_try_send(&mut self, tid: TaskId, ch: ChanId, payload: RtPayload) {
635        let waiting_receiver = self
636            .chans
637            .get_mut(&ch)
638            .unwrap()
639            .blocked_receivers
640            .pop_front();
641        if let Some(rid) = waiting_receiver {
642            self.deliver_to_receiver(rid, ch, payload);
643            self.mark_ready(tid, RtPayload::Bool(true));
644            return;
645        }
646        if self.chans[&ch].has_room() {
647            self.chans.get_mut(&ch).unwrap().queue.push_back(payload);
648            self.mark_ready(tid, RtPayload::Bool(true));
649        } else {
650            // Would block — report failure and drop the payload (never park).
651            self.mark_ready(tid, RtPayload::Bool(false));
652        }
653    }
654
655    fn do_try_recv(&mut self, tid: TaskId, ch: ChanId) {
656        let from_queue = self.chans.get_mut(&ch).unwrap().queue.pop_front();
657        if let Some(v) = from_queue {
658            self.mark_ready(tid, v);
659            self.refill_from_blocked_sender(ch);
660            return;
661        }
662        let from_sender = self.chans.get_mut(&ch).unwrap().blocked_senders.pop_front();
663        if let Some((sid, payload)) = from_sender {
664            self.mark_ready(tid, payload);
665            self.mark_ready(sid, RtPayload::Nothing);
666            return;
667        }
668        // Empty (or closed-and-empty) — never park; resume with Nothing.
669        self.mark_ready(tid, RtPayload::Nothing);
670    }
671
672    fn refill_from_blocked_sender(&mut self, ch: ChanId) {
673        let take = {
674            let chan = self.chans.get_mut(&ch).unwrap();
675            if chan.has_room() {
676                chan.blocked_senders.pop_front()
677            } else {
678                None
679            }
680        };
681        if let Some((sid, payload)) = take {
682            self.chans.get_mut(&ch).unwrap().queue.push_back(payload);
683            self.mark_ready(sid, RtPayload::Nothing);
684        }
685    }
686
687    fn deliver_to_receiver(&mut self, rid: TaskId, ch: ChanId, value: RtPayload) {
688        let select_arms = self.tasks.get_mut(&rid).unwrap().select_arms.take();
689        if let Some(arms) = select_arms {
690            let arm_idx = arms
691                .iter()
692                .position(|a| matches!(a, SelectArm::Recv(c) if *c == ch))
693                .expect("delivering channel must be one of the select arms");
694            {
695                let slot = self.tasks.get_mut(&rid).unwrap();
696                slot.resume = value;
697                slot.selected_arm = Some(arm_idx);
698                slot.state = TaskState::Ready;
699            }
700            self.ready.push(rid);
701            self.cancel_select_registrations(rid);
702        } else {
703            self.mark_ready(rid, value);
704        }
705    }
706
707    /// Withdraw every registration a woken select made — on every pipe, the one that woke it too,
708    /// since a select naming one pipe in two arms waits on it twice — and its timeouts.
709    fn cancel_select_registrations(&mut self, rid: TaskId) {
710        for chan in self.chans.values_mut() {
711            chan.blocked_receivers.retain(|t| *t != rid);
712        }
713        self.timers.retain(|t| t.tid != rid);
714    }
715
716    fn do_select(&mut self, tid: TaskId, arms: Vec<SelectArm>) {
717        let ready_arms: Vec<usize> = arms
718            .iter()
719            .enumerate()
720            .filter_map(|(i, a)| match a {
721                SelectArm::Recv(ch) if self.chans[ch].can_recv() => Some(i),
722                _ => None,
723            })
724            .collect();
725
726        if !ready_arms.is_empty() {
727            let w = if ready_arms.len() == 1 {
728                0
729            } else {
730                self.chooser
731                    .decide(ChoiceKind::SelectWinner, ready_arms.len())
732            };
733            let arm_idx = ready_arms[w];
734            let ch = match &arms[arm_idx] {
735                SelectArm::Recv(ch) => *ch,
736                SelectArm::Timeout(_) => unreachable!("ready arms are recv arms"),
737            };
738            let v = self.take_one(ch);
739            {
740                let slot = self.tasks.get_mut(&tid).unwrap();
741                slot.resume = v;
742                slot.selected_arm = Some(arm_idx);
743                slot.state = TaskState::Ready;
744            }
745            self.ready.push(tid);
746        } else {
747            for (i, a) in arms.iter().enumerate() {
748                match a {
749                    SelectArm::Recv(ch) => {
750                        self.chans
751                            .get_mut(ch)
752                            .unwrap()
753                            .blocked_receivers
754                            .push_back(tid);
755                    }
756                    SelectArm::Timeout(d) => {
757                        self.timers.push(TimerEntry {
758                            fire_at: self.clock + *d,
759                            tid,
760                            arm: Some(i),
761                        });
762                    }
763                }
764            }
765            let slot = self.tasks.get_mut(&tid).unwrap();
766            slot.select_arms = Some(arms);
767            slot.state = TaskState::BlockedSelect;
768        }
769    }
770
771    fn take_one(&mut self, ch: ChanId) -> RtPayload {
772        if let Some(v) = self.chans.get_mut(&ch).unwrap().queue.pop_front() {
773            self.refill_from_blocked_sender(ch);
774            return v;
775        }
776        if let Some((sid, payload)) = self.chans.get_mut(&ch).unwrap().blocked_senders.pop_front() {
777            self.mark_ready(sid, RtPayload::Nothing);
778            return payload;
779        }
780        RtPayload::Nothing
781    }
782
783    fn advance_timers(&mut self) {
784        let earliest = match self.timers.iter().map(|t| t.fire_at).min() {
785            Some(e) => e,
786            None => return,
787        };
788        self.clock = earliest;
789
790        let mut due = Vec::new();
791        let mut rest = Vec::new();
792        for t in self.timers.drain(..) {
793            if t.fire_at == earliest {
794                due.push(t);
795            } else {
796                rest.push(t);
797            }
798        }
799        self.timers = rest;
800
801        // Seeded tie-break order among timers firing on the same tick.
802        let order: Vec<usize> = if due.len() > 1 {
803            let mut pool: Vec<usize> = (0..due.len()).collect();
804            let mut shuffled = Vec::with_capacity(pool.len());
805            while !pool.is_empty() {
806                let k = self.chooser.decide(ChoiceKind::TimerTieBreak, pool.len());
807                shuffled.push(pool.remove(k));
808            }
809            shuffled
810        } else {
811            vec![0]
812        };
813
814        for idx in order {
815            let tid = due[idx].tid;
816            let arm = due[idx].arm;
817            self.fire_timer(tid, arm);
818        }
819    }
820
821    fn fire_timer(&mut self, tid: TaskId, arm: Option<usize>) {
822        let still_blocked = matches!(
823            self.tasks.get(&tid).map(|s| &s.state),
824            Some(TaskState::BlockedTimer) | Some(TaskState::BlockedSelect)
825        );
826        if !still_blocked {
827            return;
828        }
829        match arm {
830            Some(arm_idx) => {
831                let had = self.tasks.get_mut(&tid).unwrap().select_arms.take();
832                {
833                    let slot = self.tasks.get_mut(&tid).unwrap();
834                    slot.selected_arm = Some(arm_idx);
835                    slot.resume = RtPayload::Nothing;
836                    slot.state = TaskState::Ready;
837                }
838                self.ready.push(tid);
839                if had.is_some() {
840                    self.cancel_select_registrations(tid);
841                }
842            }
843            None => self.mark_ready(tid, RtPayload::Nothing),
844        }
845    }
846
847    fn complete_task(&mut self, tid: TaskId, result: AwaitResult) {
848        let waiters = self.awaiters.remove(&tid).unwrap_or_default();
849        let payload = result.payload();
850        self.results.insert(tid, result);
851        for w in waiters {
852            self.mark_ready(w, payload.clone());
853        }
854    }
855
856    fn do_await(&mut self, tid: TaskId, target: TaskId) {
857        if let Some(res) = self.results.get(&target) {
858            let payload = res.payload();
859            self.mark_ready(tid, payload);
860        } else if !self.tasks.contains_key(&target) {
861            // Unknown target — treat as already gone.
862            self.mark_ready(tid, RtPayload::Nothing);
863        } else {
864            self.awaiters.entry(target).or_default().push(tid);
865            self.tasks.get_mut(&tid).unwrap().state = TaskState::BlockedAwait;
866        }
867    }
868
869    fn do_abort(&mut self, target: TaskId) {
870        if self.results.contains_key(&target) {
871            return; // already finished
872        }
873        match self.tasks.get(&target) {
874            None => return,
875            Some(s) if matches!(s.state, TaskState::Done) => return,
876            _ => {}
877        }
878        self.ready.retain(|t| *t != target);
879        for chan in self.chans.values_mut() {
880            chan.blocked_receivers.retain(|t| *t != target);
881            chan.blocked_senders.retain(|(t, _)| *t != target);
882        }
883        self.timers.retain(|t| t.tid != target);
884        // Don't let a future completion try to re-wake an aborted task.
885        for list in self.awaiters.values_mut() {
886            list.retain(|t| *t != target);
887        }
888        self.tasks.get_mut(&target).unwrap().state = TaskState::Done;
889        self.complete_task(target, AwaitResult::Aborted);
890    }
891
892    fn do_close(&mut self, ch: ChanId) {
893        let waiters: Vec<TaskId> = {
894            let chan = self.chans.get_mut(&ch).unwrap();
895            chan.closed = true;
896            chan.blocked_receivers.drain(..).collect()
897        };
898        // A select naming this pipe in two arms is registered twice, and wakes once.
899        let mut woken = HashSet::new();
900        for rid in waiters {
901            if woken.insert(rid) {
902                self.wake_closed_receiver(rid, ch);
903            }
904        }
905    }
906
907    fn wake_closed_receiver(&mut self, rid: TaskId, ch: ChanId) {
908        let select_arms = self.tasks.get_mut(&rid).unwrap().select_arms.take();
909        if let Some(arms) = select_arms {
910            let arm_idx = arms
911                .iter()
912                .position(|a| matches!(a, SelectArm::Recv(c) if *c == ch))
913                .unwrap_or(0);
914            {
915                let slot = self.tasks.get_mut(&rid).unwrap();
916                slot.resume = RtPayload::Nothing;
917                slot.selected_arm = Some(arm_idx);
918                slot.state = TaskState::Ready;
919            }
920            self.ready.push(rid);
921            self.cancel_select_registrations(rid);
922        } else {
923            self.mark_ready(rid, RtPayload::Nothing);
924        }
925    }
926}
927
928/// Run `setup` (which spawns tasks and creates channels) under a fresh recording
929/// scheduler seeded by `seed`, returning the outcome and the scheduling trace.
930pub fn run_with_seed<'t, F>(
931    config: SchedulerConfig,
932    seed: SchedSeed,
933    setup: F,
934) -> (RunOutcome, SchedTrace)
935where
936    F: FnOnce(&mut Scheduler<'t>),
937{
938    let mut sched = Scheduler::new(config, Chooser::record(seed));
939    setup(&mut sched);
940    let outcome = sched.run();
941    (outcome, sched.into_trace())
942}
943
944/// Re-run `setup` under a replaying scheduler driven by `trace`, returning the outcome.
945pub fn run_with_trace<'t, F>(config: SchedulerConfig, trace: SchedTrace, setup: F) -> RunOutcome
946where
947    F: FnOnce(&mut Scheduler<'t>),
948{
949    let mut sched = Scheduler::new(config, Chooser::replay(trace));
950    setup(&mut sched);
951    sched.run()
952}
953
954#[cfg(test)]
955#[path = "../../logicaffeine_tests/unit/logicaffeine_runtime/scheduler/deadlock_narration_tests.rs"]
956mod deadlock_narration_tests;