Skip to main content

logicaffeine_runtime/
executor.rs

1//! The work-stealing M:N native driver.
2//!
3//! Genuine multicore for the VM/tree-walker tiers, native-only (`std::thread` +
4//! `std::sync`; never tokio, never `crossbeam` — this crate is dependency-free by
5//! charter). The design turns on one fact: a task body (`Vm`/`Interpreter`) holds
6//! `Rc` heaps and is irreducibly `!Send`, so **tasks never cross threads**. What
7//! crosses is only a `Send` *descriptor*; each worker *builds* its `!Send` task
8//! locally from its own clone of the program.
9//!
10//! ## Architecture — a central coordinator owns every decision
11//!
12//! ```text
13//!        ┌───────────────────────────────────────────┐
14//!        │ Coordinator (the authoritative Scheduler + │
15//!        │   the SINGLE Chooser seed choke point):    │
16//!        │   channels, timers, the work deque         │
17//!        └───────────────┬───────────────────────────┘
18//!          Send descriptors ↓   ↑ Send StepReport
19//!        ┌─────────────────┴──┐ ┌┴────────────────────┐
20//!        │ Worker 0 (thread)  │ │ Worker N-1          │
21//!        │  own program clone │ │  own program clone  │
22//!        │  builds !Send task │ │  builds !Send task  │
23//!        │  polls body → block│ │  polls body → block │
24//!        └────────────────────┘ └─────────────────────┘
25//! ```
26//!
27//! Workers never touch channels, timers, or the `Chooser` directly: they poll a
28//! task body (the expensive part — arithmetic, loops, JIT regions) and report the
29//! resulting `StepReport` back. The coordinator applies every report through the
30//! *same* [`crate::scheduler::Scheduler`] state machine and the *same* `Chooser`,
31//! in a deterministic order, so for a fixed seed the trace is **identical to the
32//! cooperative run** — parallelism only reorders the wall-clock arrival of reports,
33//! which a logical clock + a `TaskId`-sorted apply order erase.
34//!
35//! Determinism is therefore preserved *by construction*: there is one choice
36//! point. "Spawns are stealable; resumptions are pinned" — a freshly spawned task
37//! (just `(func, args)`) can be built by any idle worker, but an already-built
38//! `!Send` continuation stays on the worker that last ran it.
39
40use crate::channel::ChanId;
41use crate::payload::RtPayload;
42use crate::task::{SelectArm, TaskId};
43
44/// An opaque function index, from the runtime's view — the compile crate's
45/// `FuncIdx` (a `u16`), kept local so this crate stays dependency-free.
46pub type FuncIdx = u16;
47
48/// A `Send` task descriptor: which function to run, its already-materialised
49/// arguments, its scheduling priority, and whether it is the run's main task.
50/// This is what a worker turns into a `!Send` task body locally.
51pub struct SpawnDesc {
52    pub func: FuncIdx,
53    pub args: Vec<RtPayload>,
54    pub priority: u8,
55    pub is_main: bool,
56}
57
58/// How a worker should (re)enter a task body on its next poll. Every variant is
59/// `Send` (`FuncIdx` is `u16`, `RtPayload` is `Send`, ids are `Copy`).
60pub enum ResumeKind {
61    /// First entry / a block that yields no value (`Send`/`Close`/`Yield`/`Sleep`).
62    Nothing,
63    /// Fresh spawn: build the body from this function + materialised args.
64    /// `is_main` distinguishes the program's root task (whose body is the
65    /// top-level program, not a spawned function) so the builder positions it
66    /// correctly.
67    Spawn {
68        func: FuncIdx,
69        args: Vec<RtPayload>,
70        priority: u8,
71        is_main: bool,
72    },
73    /// Resume a pinned continuation with a delivered value (`Recv`/`TryRecv`/`Await`).
74    Payload(RtPayload),
75    /// Resume a `Select` winner: the winning arm index + its (recv) payload.
76    Select { arm: usize, payload: RtPayload },
77    /// Resume after `NewChan` with the freshly-created channel id.
78    NewChan(ChanId),
79    /// Resume after a handle-bearing spawn with the child's task id.
80    SpawnedHandle(TaskId),
81}
82
83/// The `Send` projection of a [`crate::task::TaskStep`] a worker reports after
84/// polling one task slice (the `tid` lives on [`WorkerReport`]). The crucial
85/// difference from `TaskStep`: the spawn variant carries a *descriptor*, not a
86/// `Box<dyn Task>` — so the `!Send` body is built and consumed on one worker.
87enum ReportStep {
88    Yield,
89    Recv(ChanId),
90    Send(ChanId, RtPayload),
91    TrySend(ChanId, RtPayload),
92    TryRecv(ChanId),
93    Select(Vec<SelectArm>),
94    Sleep(u64),
95    NewChan(Option<usize>),
96    Spawn { func: FuncIdx, args: Vec<RtPayload> },
97    Await(TaskId),
98    Abort(TaskId),
99    Close(ChanId),
100    Exit(RtPayload),
101}
102
103/// What one worker sends back after a poll slice: which task, the output that
104/// slice produced (flushed by the coordinator in pick order), and the projected
105/// step.
106struct WorkerReport {
107    tid: TaskId,
108    output: Vec<String>,
109    step: ReportStep,
110}
111
112/// A unit of work the coordinator sends to a worker.
113enum WorkMsg {
114    Run { tid: TaskId, resume: ResumeKind },
115    Shutdown,
116}
117
118/// The result of a work-stealing run.
119pub struct WsOutcome {
120    pub outcome: crate::scheduler::RunOutcome,
121    pub output: Vec<String>,
122    pub trace: crate::seed::SchedTrace,
123}
124
125/// Compile-time proof that the entire cross-thread boundary is `Send`. The task
126/// bodies (`Vm`/`Interpreter`, `Box<dyn Task>`, any `Rc`) never cross.
127#[allow(dead_code)]
128fn _assert_boundary_send() {
129    fn s<T: Send>() {}
130    s::<SpawnDesc>();
131    s::<ResumeKind>();
132    s::<WorkerReport>();
133    s::<WorkMsg>();
134    s::<RtPayload>();
135}
136
137use std::collections::HashMap;
138use std::sync::mpsc;
139
140use crate::config::SchedulerConfig;
141use crate::scheduler::{RunOutcome, Scheduler};
142use crate::seed::{Chooser, SchedSeed};
143use crate::task::{TaskCtx, TaskStep};
144
145/// Run a concurrent program on the **work-stealing M:N driver** under `seed`.
146///
147/// `build` turns a `Send` [`SpawnDesc`] into a worker-local `!Send` task body; it
148/// is cloned once per worker, so each worker constructs its tasks over its own
149/// resources (e.g. its own program clone) and no body ever crosses a thread. The
150/// coordinator owns the single [`Scheduler`] + `Chooser`, so the seeded trace is
151/// identical to the cooperative run; workers only poll task *bodies* in parallel.
152pub fn run_workstealing_seeded<'env, B>(
153    config: SchedulerConfig,
154    seed: SchedSeed,
155    main: SpawnDesc,
156    build: B,
157) -> WsOutcome
158where
159    B: Fn(SpawnDesc) -> Box<dyn crate::task::Task<'env> + 'env> + Sync,
160{
161    let n = config.workers.max(1);
162    // The coordinator's `Scheduler` only ever holds *metadata* slots (task bodies
163    // live worker-side), so its task lifetime is vacuous — `'static`.
164    let mut sched: Scheduler<'static> = Scheduler::new(config, Chooser::record(seed));
165    let (report_tx, report_rx) = mpsc::channel::<WorkerReport>();
166
167    // The main task is a metadata slot; its body is built worker-side from `main`.
168    let main_tid = sched.spawn_meta(main.priority, true);
169    let mut fresh: HashMap<TaskId, SpawnDesc> = HashMap::new();
170    fresh.insert(main_tid, main);
171
172    // Scoped threads let workers BORROW `&build` (and through it the program), so
173    // the bodies need not be `'static` — no leak, no unsafe.
174    let build_ref = &build;
175    let (outcome, output, trace) = std::thread::scope(|scope| {
176        // coordinator→worker work (one channel each, so a pinned resume routes to
177        // its owning worker).
178        let mut work_txs = Vec::with_capacity(n);
179        for _ in 0..n {
180            let (work_tx, work_rx) = mpsc::channel::<WorkMsg>();
181            work_txs.push(work_tx);
182            let rtx = report_tx.clone();
183            scope.spawn(move || worker_main(work_rx, rtx, build_ref));
184        }
185        drop(report_tx); // so `report_rx` closes once every worker's clone drops
186
187        let mut owner: HashMap<TaskId, usize> = HashMap::new();
188        let mut next_w = 0usize;
189        let mut output: Vec<String> = Vec::new();
190
191        let outcome = loop {
192            // The ready batch, in the SAME pick order the cooperative scheduler uses.
193            let mut batch: Vec<crate::scheduler::WsDispatch> = Vec::new();
194            while let Some(d) = sched.ws_next_dispatch() {
195                batch.push(d);
196            }
197            if batch.is_empty() {
198                if sched.ws_all_done() {
199                    break RunOutcome::Done(sched.ws_main_result());
200                }
201                if sched.ws_has_timers() {
202                    sched.ws_advance_timers();
203                    continue;
204                }
205                break RunOutcome::Deadlock;
206            }
207
208            // Dispatch all ready tasks (workers poll their bodies in parallel). A
209            // fresh task is assigned round-robin (deterministic); a resume goes to
210            // its owning worker (the body is pinned there).
211            let order: Vec<TaskId> = batch.iter().map(|d| d.tid).collect();
212            for d in batch {
213                let w = if fresh.contains_key(&d.tid) {
214                    let w = next_w;
215                    next_w = (next_w + 1) % n;
216                    owner.insert(d.tid, w);
217                    w
218                } else {
219                    owner[&d.tid]
220                };
221                let resume = if let Some(desc) = fresh.remove(&d.tid) {
222                    ResumeKind::Spawn {
223                        func: desc.func,
224                        args: desc.args,
225                        priority: desc.priority,
226                        is_main: desc.is_main,
227                    }
228                } else if let Some(arm) = d.selected_arm {
229                    ResumeKind::Select {
230                        arm,
231                        payload: d.resume,
232                    }
233                } else if let Some(ch) = d.new_chan {
234                    ResumeKind::NewChan(ch)
235                } else if let Some(t) = d.spawned {
236                    ResumeKind::SpawnedHandle(t)
237                } else {
238                    match d.resume {
239                        RtPayload::Nothing => ResumeKind::Nothing,
240                        p => ResumeKind::Payload(p),
241                    }
242                };
243                work_txs[w]
244                    .send(WorkMsg::Run { tid: d.tid, resume })
245                    .expect("worker alive");
246            }
247
248            // Barrier: collect this batch's reports (arrival order is irrelevant).
249            let mut reports: HashMap<TaskId, WorkerReport> = HashMap::new();
250            for _ in 0..order.len() {
251                let r = report_rx.recv().expect("worker report");
252                reports.insert(r.tid, r);
253            }
254
255            // Apply in PICK ORDER: flush each slice's output, then apply its step
256            // through the SAME Scheduler methods the cooperative driver uses — this
257            // is what makes output + channel resolution identical to cooperative.
258            for tid in &order {
259                let WorkerReport {
260                    tid: rt,
261                    output: slice_out,
262                    step,
263                } = reports.remove(tid).expect("report for dispatched task");
264                output.extend(slice_out);
265                apply_step(&mut sched, &mut fresh, rt, step);
266            }
267        };
268
269        for tx in &work_txs {
270            let _ = tx.send(WorkMsg::Shutdown);
271        }
272        drop(work_txs);
273        (outcome, output, sched.into_trace())
274    });
275
276    WsOutcome {
277        outcome,
278        output,
279        trace,
280    }
281}
282
283/// Apply one worker's report through the authoritative `Scheduler` (reusing its
284/// channel/decision methods), turning a spawn report into a metadata child +
285/// recorded descriptor.
286fn apply_step(
287    sched: &mut Scheduler<'static>,
288    fresh: &mut HashMap<TaskId, SpawnDesc>,
289    tid: TaskId,
290    step: ReportStep,
291) {
292    match step {
293        ReportStep::Yield => sched.process_step(tid, TaskStep::Yield),
294        ReportStep::Recv(ch) => sched.process_step(tid, TaskStep::Recv(ch)),
295        ReportStep::Send(ch, p) => sched.process_step(tid, TaskStep::Send(ch, p)),
296        ReportStep::TrySend(ch, p) => sched.process_step(tid, TaskStep::TrySend(ch, p)),
297        ReportStep::TryRecv(ch) => sched.process_step(tid, TaskStep::TryRecv(ch)),
298        ReportStep::Select(arms) => sched.process_step(tid, TaskStep::Select(arms)),
299        ReportStep::Sleep(t) => sched.process_step(tid, TaskStep::Sleep(t)),
300        ReportStep::NewChan(cap) => sched.process_step(tid, TaskStep::NewChan(cap)),
301        ReportStep::Await(t) => sched.process_step(tid, TaskStep::Await(t)),
302        ReportStep::Abort(t) => sched.process_step(tid, TaskStep::Abort(t)),
303        ReportStep::Close(ch) => sched.process_step(tid, TaskStep::Close(ch)),
304        ReportStep::Exit(v) => sched.process_step(tid, TaskStep::Exit(v)),
305        ReportStep::Spawn { func, args } => {
306            // Mirror the cooperative `Spawn` step: create the child + hand the
307            // parent the child id; record the child's build descriptor.
308            let child = sched.ws_spawn_child(tid, 0);
309            fresh.insert(
310                child,
311                SpawnDesc {
312                    func,
313                    args,
314                    priority: 0,
315                    is_main: false,
316                },
317            );
318        }
319    }
320}
321
322/// One worker thread: builds (fresh) or looks up (resume) the `!Send` task body,
323/// polls one slice, and reports the projected step + the slice's output.
324fn worker_main<'env, B>(
325    work_rx: mpsc::Receiver<WorkMsg>,
326    report_tx: mpsc::Sender<WorkerReport>,
327    build: &B,
328) where
329    B: Fn(SpawnDesc) -> Box<dyn crate::task::Task<'env> + 'env>,
330{
331    let mut local: HashMap<TaskId, Box<dyn crate::task::Task<'env> + 'env>> = HashMap::new();
332    while let Ok(msg) = work_rx.recv() {
333        let (tid, resume) = match msg {
334            WorkMsg::Shutdown => break,
335            WorkMsg::Run { tid, resume } => (tid, resume),
336        };
337        let mut ctx = TaskCtx {
338            resumed_with: RtPayload::Nothing,
339            selected_arm: None,
340            new_chan: None,
341            spawned: None,
342        };
343        match resume {
344            ResumeKind::Nothing => {}
345            ResumeKind::Spawn {
346                func,
347                args,
348                priority,
349                is_main,
350            } => {
351                local.insert(
352                    tid,
353                    build(SpawnDesc {
354                        func,
355                        args,
356                        priority,
357                        is_main,
358                    }),
359                );
360            }
361            ResumeKind::Payload(p) => ctx.resumed_with = p,
362            ResumeKind::Select { arm, payload } => {
363                ctx.selected_arm = Some(arm);
364                ctx.resumed_with = payload;
365            }
366            ResumeKind::NewChan(ch) => ctx.new_chan = Some(ch),
367            ResumeKind::SpawnedHandle(t) => ctx.spawned = Some(t),
368        }
369        let task = local
370            .get_mut(&tid)
371            .expect("task body present on its owning worker");
372        let step = task.poll(&mut ctx);
373        let out = task.take_output();
374        let (rstep, done) = project_step(step);
375        if done {
376            local.remove(&tid);
377        }
378        if report_tx
379            .send(WorkerReport {
380                tid,
381                output: out,
382                step: rstep,
383            })
384            .is_err()
385        {
386            break;
387        }
388    }
389}
390
391/// Project a worker's `TaskStep` into the `Send` [`ReportStep`]; the `bool` is
392/// whether the task finished (so the worker drops its body).
393fn project_step<'env>(step: TaskStep<'env>) -> (ReportStep, bool) {
394    match step {
395        TaskStep::Yield => (ReportStep::Yield, false),
396        TaskStep::Recv(ch) => (ReportStep::Recv(ch), false),
397        TaskStep::Send(ch, p) => (ReportStep::Send(ch, p), false),
398        TaskStep::TrySend(ch, p) => (ReportStep::TrySend(ch, p), false),
399        TaskStep::TryRecv(ch) => (ReportStep::TryRecv(ch), false),
400        TaskStep::Select(arms) => (ReportStep::Select(arms), false),
401        TaskStep::Sleep(t) => (ReportStep::Sleep(t), false),
402        TaskStep::NewChan(cap) => (ReportStep::NewChan(cap), false),
403        TaskStep::SpawnDesc { func, args, .. } => (ReportStep::Spawn { func, args }, false),
404        TaskStep::Spawn(_) => {
405            panic!("work-stealing tasks must spawn via SpawnDesc, not a boxed Spawn")
406        }
407        TaskStep::Await(t) => (ReportStep::Await(t), false),
408        TaskStep::Abort(t) => (ReportStep::Abort(t), false),
409        TaskStep::Close(ch) => (ReportStep::Close(ch), false),
410        TaskStep::IoPending => {
411            // Networking runs on the tree-walker (async) tier, never the work-stealing
412            // compute tier, so a worker never parks on external I/O.
413            panic!("work-stealing tasks do not perform external I/O (IoPending)")
414        }
415        TaskStep::Exit(v) => (ReportStep::Exit(v), true),
416    }
417}