1use 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#[derive(Debug, Clone, PartialEq)]
20pub enum RunOutcome {
21 Done(RtPayload),
23 Deadlock,
25 WaitingForIo,
30}
31
32enum TaskState {
33 Ready,
34 BlockedRecv,
35 BlockedSend,
36 BlockedSelect,
37 BlockedTimer,
38 BlockedAwait,
39 BlockedIo,
40 Done,
41}
42
43#[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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub struct ChanView {
84 pub id: ChanId,
85 pub depth: usize,
87 pub capacity: Option<usize>,
89 pub blocked_senders: usize,
90 pub blocked_receivers: usize,
91 pub closed: bool,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct SchedSnapshot {
99 pub clock: u64,
101 pub ready_len: usize,
103 pub tasks: Vec<TaskView>,
105 pub channels: Vec<ChanView>,
107}
108
109pub 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 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#[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 resume_chan: Option<ChanId>,
182 resume_task: Option<TaskId>,
184 state: TaskState,
185 is_main: bool,
186}
187
188struct TimerEntry {
189 fire_at: u64,
190 tid: TaskId,
191 arm: Option<usize>,
193}
194
195#[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
208pub 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 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 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 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 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 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 #[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 pub fn into_trace(self) -> SchedTrace {
308 self.chooser.into_trace()
309 }
310
311 pub fn run(&mut self) -> RunOutcome {
313 loop {
314 if let Some(outcome) = self.poll_once() {
315 return outcome;
316 }
317 }
318 }
319
320 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 RunOutcome::WaitingForIo
360 } else {
361 RunOutcome::Deadlock
362 })
363 }
364 }
365
366 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 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 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 #[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 #[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 #[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 #[cfg(not(target_arch = "wasm32"))]
478 pub(crate) fn ws_has_timers(&self) -> bool {
479 !self.timers.is_empty()
480 }
481
482 #[cfg(not(target_arch = "wasm32"))]
484 pub(crate) fn ws_advance_timers(&mut self) {
485 self.advance_timers();
486 }
487
488 #[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 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 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 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 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 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 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 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; }
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 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 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
928pub 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
944pub 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;