Skip to main content

rustsy_engine/
adaptive.rs

1use crate::{Device, Plan, Task};
2use std::{
3    collections::{BTreeSet, HashMap},
4    sync::mpsc,
5    time::{Duration, Instant},
6};
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
9#[repr(usize)]
10pub enum Backend {
11    Cpu,
12    Accelerator,
13    Storage,
14}
15
16impl Backend {
17    /// Alias used by the CUDA adapter and historical experiments.
18    #[allow(non_upper_case_globals)]
19    pub const Cuda: Self = Self::Accelerator;
20}
21const BACKENDS: [Backend; 3] = [Backend::Cpu, Backend::Cuda, Backend::Storage];
22
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
24pub struct Memory {
25    pub ram: usize,
26    pub vram: usize,
27}
28
29impl Memory {
30    fn fits(self, used: Self, limit: Self) -> bool {
31        self.ram <= limit.ram - used.ram && self.vram <= limit.vram - used.vram
32    }
33}
34
35#[derive(Clone, Copy, Debug)]
36pub struct Route {
37    /// Full operation time, including preparation, transfers and synchronization.
38    pub estimate: Duration,
39    /// Concurrent working memory. Charge externally retained allocations separately.
40    pub memory: Memory,
41}
42
43#[derive(Clone, Debug)]
44pub struct Operation {
45    pub dependencies: Vec<usize>,
46    /// Assign different classes to algorithms with different cost characteristics.
47    pub class: u64,
48    pub bytes: usize,
49    /// Indexed by Backend. None means that implementation is unavailable.
50    pub routes: [Option<Route>; 3],
51}
52
53#[derive(Clone, Copy, Debug)]
54pub struct Capacity {
55    /// Maximum concurrent workers per backend.
56    pub workers: [usize; 3],
57    pub memory: Memory,
58}
59
60#[derive(Clone, Debug)]
61pub struct Hardware {
62    pub logical_workers: usize,
63    pub available_ram: Option<u64>,
64    pub avx2: bool,
65    pub sse42: bool,
66    pub sha: bool,
67}
68
69pub fn discover_host() -> Hardware {
70    let mut hardware = Hardware {
71        logical_workers: std::thread::available_parallelism().map_or(1, usize::from),
72        available_ram: available_ram(),
73        avx2: false,
74        sse42: false,
75        sha: false,
76    };
77    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
78    {
79        hardware.avx2 = std::is_x86_feature_detected!("avx2");
80        hardware.sse42 = std::is_x86_feature_detected!("sse4.2");
81        hardware.sha = std::is_x86_feature_detected!("sha");
82    }
83    hardware
84}
85
86#[cfg(windows)]
87fn available_ram() -> Option<u64> {
88    #[repr(C)]
89    struct MemoryStatus {
90        length: u32,
91        load_percent: u32,
92        total_physical: u64,
93        available_physical: u64,
94        total_page_file: u64,
95        available_page_file: u64,
96        total_virtual: u64,
97        available_virtual: u64,
98        available_extended_virtual: u64,
99    }
100    #[link(name = "kernel32")]
101    unsafe extern "system" {
102        fn GlobalMemoryStatusEx(status: *mut MemoryStatus) -> i32;
103    }
104    let mut status = MemoryStatus {
105        length: std::mem::size_of::<MemoryStatus>() as u32,
106        load_percent: 0,
107        total_physical: 0,
108        available_physical: 0,
109        total_page_file: 0,
110        available_page_file: 0,
111        total_virtual: 0,
112        available_virtual: 0,
113        available_extended_virtual: 0,
114    };
115    (unsafe { GlobalMemoryStatusEx(&mut status) } != 0).then_some(status.available_physical)
116}
117#[cfg(not(windows))]
118fn available_ram() -> Option<u64> {
119    None
120}
121
122#[derive(Clone, Copy, Debug)]
123pub struct Sample {
124    pub task: usize,
125    pub backend: Backend,
126    pub ready_at: Duration,
127    pub dispatched_at: Duration,
128    pub started_at: Duration,
129    pub setup: Option<Duration>,
130    pub elapsed: Duration,
131}
132
133#[derive(Debug)]
134pub struct Report {
135    pub elapsed: Duration,
136    pub dependency_span: Duration,
137    pub samples: Vec<Sample>,
138    pub peak: Memory,
139    pub memory_blocked: Duration,
140    pub busy: [Duration; 3],
141    pub fallbacks: Vec<(usize, String)>,
142    pub model_resets: usize,
143    pub plan_time: Duration,
144    pub dispatch_time: Duration,
145    pub wait_time: Duration,
146    /// Scans in which an unfinished operation provided a lower bound on service time.
147    pub censored_scans: usize,
148}
149
150/// Screening signal from timing counters. Confirm causality with a controlled trial.
151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
152pub enum Pressure {
153    MemoryAdmission,
154    Dependencies,
155    Backend(Backend),
156    Unclassified,
157}
158
159impl Report {
160    pub fn pressure(&self, capacity: Capacity) -> Pressure {
161        if self.elapsed.is_zero() {
162            return Pressure::Unclassified;
163        }
164        if self.memory_blocked >= self.elapsed / 2 {
165            return Pressure::MemoryAdmission;
166        }
167        if self.dependency_span >= self.elapsed - self.elapsed / 5 {
168            return Pressure::Dependencies;
169        }
170        BACKENDS
171            .into_iter()
172            .filter_map(|backend| {
173                let index = backend as usize;
174                let workers = capacity.workers[index];
175                (workers != 0).then(|| {
176                    (
177                        self.busy[index].as_secs_f64()
178                            / (self.elapsed.as_secs_f64() * workers as f64),
179                        backend,
180                    )
181                })
182            })
183            .max_by(|a, b| a.0.total_cmp(&b.0))
184            .filter(|(utilization, _)| *utilization >= 0.8)
185            .map_or(Pressure::Unclassified, |(_, backend)| {
186                Pressure::Backend(backend)
187            })
188    }
189}
190
191/// Keep one history per workload, hardware and executor configuration.
192#[derive(Default)]
193pub struct History {
194    service: HashMap<(u64, u32, Backend), Duration>,
195    startup: [Option<Duration>; 3],
196    frozen: bool,
197    probe_joins: bool,
198    censor: bool,
199    deviations: HashMap<(u64, u32, Backend), (bool, Duration)>,
200}
201
202fn smooth(prior: Duration, sample: Duration) -> Duration {
203    (prior - prior / 4).saturating_add(sample / 4)
204}
205
206impl History {
207    /// Experimental policy. Probe high fan-in/fan-out joins on the accelerator
208    /// and use the age of unfinished work as a temporary cost floor.
209    pub fn live_probes(&mut self, probe_joins: bool, censor: bool) {
210        self.probe_joins = probe_joins;
211        self.censor = censor;
212    }
213
214    /// Freeze predictions for a controlled comparison. Explicit observations can be
215    /// added before freezing. A frozen model supplies estimates but ignores completions.
216    pub fn freeze(&mut self) {
217        self.frozen = true;
218    }
219
220    fn key(class: u64, bytes: usize, backend: Backend) -> (u64, u32, Backend) {
221        (class, bytes.checked_ilog2().unwrap_or(0), backend)
222    }
223
224    pub fn observe(&mut self, class: u64, bytes: usize, backend: Backend, elapsed: Duration) {
225        self.update(class, bytes, backend, elapsed);
226    }
227
228    fn update(&mut self, class: u64, bytes: usize, backend: Backend, elapsed: Duration) -> bool {
229        if self.frozen {
230            return false;
231        }
232        let key = Self::key(class, bytes, backend);
233        let Some(estimate) = self.service.get_mut(&key) else {
234            self.service.insert(key, elapsed);
235            return false;
236        };
237        let large_change = elapsed.abs_diff(*estimate) >= Duration::from_micros(25)
238            && elapsed.max(*estimate) > elapsed.min(*estimate).saturating_mul(2);
239        if large_change {
240            let slower = elapsed > *estimate;
241            if let Some((direction, previous)) = self.deviations.remove(&key)
242                && direction == slower
243            {
244                *estimate = elapsed.min(previous) + elapsed.abs_diff(previous) / 2;
245                return true;
246            }
247            self.deviations.insert(key, (slower, elapsed));
248        } else {
249            self.deviations.remove(&key);
250            *estimate = smooth(*estimate, elapsed);
251        }
252        false
253    }
254
255    pub fn observe_startup(&mut self, backend: Backend, elapsed: Duration) {
256        if self.frozen {
257            return;
258        }
259        let slot = &mut self.startup[backend as usize];
260        *slot = Some(slot.map_or(elapsed, |prior| smooth(prior, elapsed)));
261    }
262
263    fn predict(&self, op: &Operation, backend: Backend) -> Duration {
264        self.service
265            .get(&Self::key(op.class, op.bytes, backend))
266            .copied()
267            .unwrap_or_else(|| {
268                op.routes[backend as usize]
269                    .expect("supported route")
270                    .estimate
271            })
272    }
273}
274
275pub enum Attempt {
276    Done,
277    /// Request a retry only before publishing an output or any visible side effects.
278    RetryOnCpu(String),
279}
280
281#[derive(Clone, Copy)]
282struct InFlight {
283    memory: Memory,
284    finish: Duration,
285    task: usize,
286    dispatched: Duration,
287    predicted: Duration,
288}
289
290pub struct Scheduler {
291    ops: Vec<Operation>,
292    plan: Plan,
293}
294
295impl Scheduler {
296    pub fn new(ops: Vec<Operation>) -> Result<Self, &'static str> {
297        let plan = Plan::new(
298            ops.iter()
299                .map(|op| Task {
300                    dependencies: op.dependencies.clone(),
301                    device: Device::Cpu,
302                    memory_bytes: 0,
303                })
304                .collect(),
305        )?;
306        Ok(Self { ops, plan })
307    }
308
309    /// Workers own backend state for the duration of a run, including !Send CUDA sessions.
310    /// The callback publishes results before returning. Dependencies are released at completion.
311    /// Independent operations already dispatched may finish after an error. Callers own
312    /// the lifetime and memory accounting of results retained beyond an operation.
313    pub fn execute<S>(
314        &self,
315        capacity: Capacity,
316        history: &mut History,
317        initialize: impl Fn(Backend) -> Result<S, String> + Sync,
318        work: impl Fn(&mut S, usize, Backend) -> Result<(), String> + Sync,
319    ) -> Result<Report, String> {
320        self.execute_retry(capacity, history, initialize, |session, task, backend| {
321            work(session, task, backend).map(|()| Attempt::Done)
322        })
323    }
324
325    pub fn execute_retry<S>(
326        &self,
327        capacity: Capacity,
328        history: &mut History,
329        initialize: impl Fn(Backend) -> Result<S, String> + Sync,
330        work: impl Fn(&mut S, usize, Backend) -> Result<Attempt, String> + Sync,
331    ) -> Result<Report, String> {
332        self.execute_interruptible(capacity, history, initialize, work, None)
333    }
334
335    /// Stop admitting nodes once cancellation is observed. Running callbacks finish
336    /// before returning; callers can use the same flag for cooperative interruption.
337    pub fn execute_interruptible<S>(
338        &self,
339        capacity: Capacity,
340        history: &mut History,
341        initialize: impl Fn(Backend) -> Result<S, String> + Sync,
342        work: impl Fn(&mut S, usize, Backend) -> Result<Attempt, String> + Sync,
343        cancelled: Option<&std::sync::atomic::AtomicBool>,
344    ) -> Result<Report, String> {
345        let is_cancelled =
346            || cancelled.is_some_and(|flag| flag.load(std::sync::atomic::Ordering::Acquire));
347        let start = Instant::now();
348        let eligible = |op: &Operation, backend: Backend| {
349            capacity.workers[backend as usize] != 0
350                && op.routes[backend as usize]
351                    .is_some_and(|route| route.memory.fits(Memory::default(), capacity.memory))
352        };
353        let mut choices: Vec<Vec<Backend>> = self
354            .ops
355            .iter()
356            .map(|op| BACKENDS.into_iter().filter(|&b| eligible(op, b)).collect())
357            .collect();
358        if let Some(id) = choices.iter().position(Vec::is_empty) {
359            return Err(format!("operation {id} has no feasible route"));
360        }
361        let mut pending = self.plan.incoming.clone();
362        let mut order: Vec<_> = (0..self.ops.len()).filter(|&id| pending[id] == 0).collect();
363        let mut cursor = 0;
364        while cursor < order.len() {
365            for &next in &self.plan.successors[order[cursor]] {
366                pending[next] -= 1;
367                if pending[next] == 0 {
368                    order.push(next);
369                }
370            }
371            cursor += 1;
372        }
373        let mut ranks = vec![Duration::ZERO; self.ops.len()];
374        let rank = |ranks: &mut [Duration], choices: &[Vec<Backend>], history: &History| {
375            for &id in order.iter().rev() {
376                let cost = choices[id]
377                    .iter()
378                    .map(|&b| history.predict(&self.ops[id], b))
379                    .min()
380                    .unwrap();
381                let tail = self.plan.successors[id]
382                    .iter()
383                    .map(|&next| ranks[next])
384                    .max()
385                    .unwrap_or_default();
386                ranks[id] = cost.saturating_add(tail);
387            }
388        };
389        rank(&mut ranks, &choices, history);
390        pending.clone_from(&self.plan.incoming);
391        let mut ready: BTreeSet<_> = order
392            .iter()
393            .copied()
394            .filter(|&id| pending[id] == 0)
395            .map(|id| (std::cmp::Reverse(ranks[id]), id))
396            .collect();
397        let mut ready_at = vec![Duration::ZERO; self.ops.len()];
398        let mut finish = vec![Duration::ZERO; self.ops.len()];
399        let mut peak = Memory::default();
400        let mut used = Memory::default();
401        let mut busy = [Duration::ZERO; 3];
402        let mut memory_blocked = Duration::ZERO;
403        let mut fallbacks = Vec::new();
404        let mut model_resets = 0;
405        let mut censored_scans = 0;
406        let mut dispatch_time = Duration::ZERO;
407        let mut wait_time = Duration::ZERO;
408        let plan_time = start.elapsed();
409        let mut samples = Vec::with_capacity(self.ops.len());
410        std::thread::scope(|scope| {
411            let (completed, events) = mpsc::channel();
412            let mut workers = Vec::new();
413            for backend in BACKENDS {
414                let demand = choices
415                    .iter()
416                    .filter(|routes| routes.contains(&backend))
417                    .count();
418                for _ in 0..capacity.workers[backend as usize].min(demand) {
419                    let worker_id = workers.len();
420                    let (dispatch, queue) = mpsc::sync_channel::<(usize, Duration)>(1);
421                    workers.push((backend, dispatch, None::<InFlight>, false));
422                    let completed = completed.clone();
423                    let initialize = &initialize;
424                    let work = &work;
425                    scope.spawn(move || {
426                        // Open sessions only on workers that actually receive work.
427                        let mut state = None;
428                        while let Ok((task, dispatched_at)) = queue.recv() {
429                            let started = start.elapsed();
430                            let mut setup = None;
431                            let result =
432                                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
433                                    let state = state.get_or_insert_with(|| {
434                                        let init = initialize(backend);
435                                        setup = Some(start.elapsed() - started);
436                                        init
437                                    });
438                                    work(state.as_mut().map_err(|e| e.clone())?, task, backend)
439                                }))
440                                .unwrap_or_else(|_| Err("worker panicked".into()));
441                            if completed
442                                .send((
443                                    worker_id,
444                                    task,
445                                    dispatched_at,
446                                    started,
447                                    setup,
448                                    start.elapsed() - started,
449                                    result,
450                                ))
451                                .is_err()
452                            {
453                                break;
454                            }
455                        }
456                    });
457                }
458            }
459            drop(completed);
460            while samples.len() < self.ops.len() {
461                if is_cancelled() {
462                    return Err("execution cancelled".into());
463                }
464                let tick = Instant::now();
465                let mut floor = HashMap::new();
466                if history.censor {
467                    let now = start.elapsed();
468                    for (backend, _, active, _) in &workers {
469                        if let Some(active) = active {
470                            let age = now.saturating_sub(active.dispatched);
471                            if age
472                                > active
473                                    .predicted
474                                    .saturating_mul(3)
475                                    .saturating_add(Duration::from_micros(100))
476                            {
477                                let op = &self.ops[active.task];
478                                let floor = floor
479                                    .entry(History::key(op.class, op.bytes, *backend))
480                                    .or_insert(Duration::ZERO);
481                                *floor = (*floor).max(age.saturating_mul(2));
482                            }
483                        }
484                    }
485                }
486                censored_scans += usize::from(!floor.is_empty());
487                let mut waiting_for_memory = false;
488                for &(_, id) in &ready {
489                    if is_cancelled() {
490                        return Err("execution cancelled".into());
491                    }
492                    let op = &self.ops[id];
493                    let now = start.elapsed();
494                    let candidate = workers
495                        .iter()
496                        .enumerate()
497                        .filter_map(|(index, (backend, _, active, opened))| {
498                            if !choices[id].contains(backend) {
499                                return None;
500                            }
501                            let memory = op.routes[*backend as usize]?.memory;
502                            if active.is_none() && !memory.fits(used, capacity.memory) {
503                                return None;
504                            }
505                            let availability = active.map_or(now, |work| work.finish.max(now));
506                            let cost = history.predict(op, *backend).max(
507                                floor
508                                    .get(&History::key(op.class, op.bytes, *backend))
509                                    .copied()
510                                    .unwrap_or_default(),
511                            );
512                            Some((
513                                availability
514                                    .saturating_add(cost)
515                                    .saturating_add(if *opened {
516                                        Duration::ZERO
517                                    } else {
518                                        history.startup[*backend as usize].unwrap_or_default()
519                                    }),
520                                index,
521                                memory,
522                            ))
523                        })
524                        .min_by_key(|&(eta, index, _)| {
525                            let probe = history.probe_joins
526                                && self.plan.incoming[id] >= 4
527                                && self.plan.successors[id].len() >= 4
528                                && choices[id].contains(&Backend::Accelerator);
529                            (
530                                probe && workers[index].0 != Backend::Accelerator,
531                                eta,
532                                workers[index].2.is_some(),
533                                index,
534                            )
535                        });
536                    waiting_for_memory |= workers.iter().any(|(backend, _, active, _)| {
537                        active.is_none()
538                            && choices[id].contains(backend)
539                            && !op.routes[*backend as usize]
540                                .unwrap()
541                                .memory
542                                .fits(used, capacity.memory)
543                    });
544                    if let Some((eta, index, memory)) = candidate
545                        && workers[index].2.is_none()
546                    {
547                        workers[index]
548                            .1
549                            .send((id, now))
550                            .map_err(|_| "worker disconnected")?;
551                        workers[index].2 = Some(InFlight {
552                            memory,
553                            finish: eta,
554                            task: id,
555                            dispatched: now,
556                            predicted: eta.saturating_sub(now),
557                        });
558                        workers[index].3 = true;
559                        used.ram += memory.ram;
560                        used.vram += memory.vram;
561                        peak.ram = peak.ram.max(used.ram);
562                        peak.vram = peak.vram.max(used.vram);
563                        // Defer mutation of the ready set until after this scan.
564                        pending[id] = usize::MAX;
565                    }
566                }
567                ready.retain(|&(_, id)| pending[id] != usize::MAX);
568                dispatch_time += tick.elapsed();
569                let wait = Instant::now();
570                let message = if history.censor && !ready.is_empty() || cancelled.is_some() {
571                    match events.recv_timeout(Duration::from_micros(300)) {
572                        Ok(event) => Some(event),
573                        Err(mpsc::RecvTimeoutError::Timeout) => None,
574                        Err(mpsc::RecvTimeoutError::Disconnected) => {
575                            return Err("workers disconnected".into());
576                        }
577                    }
578                } else {
579                    Some(events.recv().map_err(|_| "workers disconnected")?)
580                };
581                wait_time += wait.elapsed();
582                if waiting_for_memory {
583                    memory_blocked += wait.elapsed();
584                }
585                let Some((index, id, dispatched_at, started_at, setup, elapsed, result)) = message
586                else {
587                    continue;
588                };
589                let tick = Instant::now();
590                let outcome = result.map_err(|e| format!("operation {id}: {e}"))?;
591                let (backend, _, active, _) = &mut workers[index];
592                let memory = active.take().unwrap().memory;
593                used.ram -= memory.ram;
594                used.vram -= memory.vram;
595                busy[*backend as usize] += elapsed;
596                if let Attempt::RetryOnCpu(reason) = outcome {
597                    if *backend != Backend::Accelerator || !choices[id].contains(&Backend::Cpu) {
598                        return Err(format!("operation {id}: {reason}"));
599                    }
600                    choices[id].retain(|backend| *backend == Backend::Cpu);
601                    fallbacks.push((id, reason));
602                    pending[id] = 0;
603                    ready.insert((std::cmp::Reverse(ranks[id]), id));
604                    dispatch_time += tick.elapsed();
605                    continue;
606                }
607                let op = &self.ops[id];
608                if let Some(setup) = setup {
609                    history.observe_startup(*backend, setup);
610                }
611                if history.update(
612                    op.class,
613                    op.bytes,
614                    *backend,
615                    elapsed - setup.unwrap_or_default(),
616                ) {
617                    model_resets += 1;
618                    rank(&mut ranks, &choices, history);
619                    ready = ready
620                        .iter()
621                        .map(|&(_, id)| (std::cmp::Reverse(ranks[id]), id))
622                        .collect();
623                }
624                finish[id] = elapsed.saturating_add(
625                    op.dependencies
626                        .iter()
627                        .map(|&dep| finish[dep])
628                        .max()
629                        .unwrap_or_default(),
630                );
631                samples.push(Sample {
632                    task: id,
633                    backend: *backend,
634                    ready_at: ready_at[id],
635                    dispatched_at,
636                    started_at,
637                    setup,
638                    elapsed,
639                });
640                for &next in &self.plan.successors[id] {
641                    pending[next] -= 1;
642                    if pending[next] == 0 {
643                        ready_at[next] = start.elapsed();
644                        ready.insert((std::cmp::Reverse(ranks[next]), next));
645                    }
646                }
647                dispatch_time += tick.elapsed();
648            }
649            Ok(Report {
650                elapsed: start.elapsed(),
651                dependency_span: finish.into_iter().max().unwrap_or_default(),
652                samples,
653                peak,
654                memory_blocked,
655                busy,
656                fallbacks,
657                model_resets,
658                plan_time,
659                dispatch_time,
660                wait_time,
661                censored_scans,
662            })
663        })
664    }
665}
666/// Measurements of one policy with a stable workload and fixed correctness criteria.
667#[derive(Debug)]
668pub struct Calibration<T> {
669    pub policy: T,
670    samples: Vec<Duration>,
671}
672
673impl<T> Calibration<T> {
674    pub fn samples(&self) -> &[Duration] {
675        &self.samples
676    }
677    pub fn median(&self) -> Duration {
678        let mut times = self.samples.clone();
679        times.sort_unstable();
680        let i = times.len() / 2;
681        times[(times.len() - 1) / 2] + (times[i] - times[(times.len() - 1) / 2]) / 2
682    }
683}
684
685/// Calibrate worker counts, batch sizes or other policies supplied by a caller.
686/// The callback returns full wall time and can validate results outside that time.
687pub fn calibrate<T: Copy, E>(
688    policies: &[T],
689    repeats: std::num::NonZeroUsize,
690    mut measure: impl FnMut(T) -> Result<Duration, E>,
691) -> Result<Vec<Calibration<T>>, E> {
692    let mut profiles = policies
693        .iter()
694        .map(|&policy| Calibration {
695            policy,
696            samples: Vec::with_capacity(repeats.get()),
697        })
698        .collect::<Vec<_>>();
699    for pass in 0..repeats.get() {
700        for offset in 0..profiles.len() {
701            let index = if pass % 2 == 0 {
702                offset
703            } else {
704                profiles.len() - 1 - offset
705            };
706            let row = &mut profiles[index];
707            row.samples.push(measure(row.policy)?);
708        }
709    }
710    Ok(profiles)
711}
712
713#[cfg(test)]
714mod tests {
715    use super::*;
716
717    #[test]
718    fn cancellation_stops_before_releasing_dependents() {
719        use std::sync::atomic::{AtomicBool, Ordering};
720        let cancel = AtomicBool::new(false);
721        let route = Some(Route {
722            estimate: Duration::from_millis(1),
723            memory: Memory::default(),
724        });
725        let node = |dependencies| Operation {
726            dependencies,
727            class: 0,
728            bytes: 32,
729            routes: [route, None, None],
730        };
731        let graph = Scheduler::new(vec![node(vec![]), node(vec![0])]).unwrap();
732        let result = graph.execute_interruptible(
733            Capacity {
734                workers: [1, 0, 0],
735                memory: Memory::default(),
736            },
737            &mut History::default(),
738            |_| Ok(()),
739            |_, id, _| {
740                assert_eq!(id, 0);
741                cancel.store(true, Ordering::Release);
742                Ok(Attempt::Done)
743            },
744            Some(&cancel),
745        );
746        assert_eq!(result.unwrap_err(), "execution cancelled");
747    }
748
749    #[test]
750    fn detects_consecutive_workload_changes_and_ignores_a_frozen_model() {
751        let mut history = History::default();
752        let sample = |ms| Duration::from_millis(ms);
753        history.observe(7, 64, Backend::Cpu, sample(1));
754        assert!(!history.update(7, 64, Backend::Cpu, sample(10)));
755        assert!(history.update(7, 64, Backend::Cpu, sample(12)));
756        assert_eq!(
757            history.service[&History::key(7, 64, Backend::Cpu)],
758            sample(11)
759        );
760        history.freeze();
761        assert!(!history.update(7, 64, Backend::Cpu, sample(150)));
762        assert_eq!(
763            history.service[&History::key(7, 64, Backend::Cpu)],
764            sample(11)
765        );
766    }
767
768    #[test]
769    fn critical_chain_precedes_root_and_reuses_worker() {
770        let route = Some(Route {
771            estimate: Duration::from_millis(1),
772            memory: Memory { ram: 8, vram: 0 },
773        });
774        let make = |dependencies| Operation {
775            dependencies,
776            class: 0,
777            bytes: 8,
778            routes: [route, None, None],
779        };
780        let graph = Scheduler::new(vec![
781            make(vec![]),
782            make(vec![]),
783            make(vec![1]),
784            make(vec![2]),
785        ])
786        .unwrap();
787        let runs = std::sync::Mutex::new(Vec::new());
788        let report = graph
789            .execute(
790                Capacity {
791                    workers: [2, 0, 0],
792                    memory: Memory { ram: 8, vram: 0 },
793                },
794                &mut History::default(),
795                |_| Ok(0),
796                |state, id, _| {
797                    *state += 1;
798                    runs.lock().unwrap().push((id, *state));
799                    Ok(())
800                },
801            )
802            .unwrap();
803        let values = runs.into_inner().unwrap();
804        assert_eq!(values[0].0, 1);
805        assert_eq!(values.len(), 4);
806        assert!(values.iter().any(|&(_, calls)| calls > 1));
807        assert_eq!(report.peak.ram, 8);
808        assert!(report.elapsed >= report.dependency_span);
809    }
810
811    #[test]
812    fn uses_feasible_route_when_gpu_memory_is_too_small() {
813        let operation = Operation {
814            dependencies: vec![],
815            class: 0,
816            bytes: 8,
817            routes: [
818                Some(Route {
819                    estimate: Duration::from_millis(2),
820                    memory: Memory { ram: 8, vram: 0 },
821                }),
822                Some(Route {
823                    estimate: Duration::ZERO,
824                    memory: Memory { ram: 8, vram: 16 },
825                }),
826                None,
827            ],
828        };
829        let scheduler = Scheduler::new(vec![operation]).unwrap();
830        let report = scheduler
831            .execute(
832                Capacity {
833                    workers: [1, 1, 0],
834                    memory: Memory { ram: 8, vram: 8 },
835                },
836                &mut History::default(),
837                Ok,
838                |backend, _, _| {
839                    assert_eq!(*backend, Backend::Cpu);
840                    Ok(())
841                },
842            )
843            .unwrap();
844        assert_eq!(report.samples[0].backend, Backend::Cpu);
845    }
846}