rustsy-engine 0.1.0

Task graph scheduling, residency planning and bounded streaming pipelines
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
use crate::{Device, Plan, Task};
use std::{
    collections::{BTreeSet, HashMap},
    sync::mpsc,
    time::{Duration, Instant},
};

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(usize)]
pub enum Backend {
    Cpu,
    Accelerator,
    Storage,
}

impl Backend {
    /// Alias used by the CUDA adapter and historical experiments.
    #[allow(non_upper_case_globals)]
    pub const Cuda: Self = Self::Accelerator;
}
const BACKENDS: [Backend; 3] = [Backend::Cpu, Backend::Cuda, Backend::Storage];

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Memory {
    pub ram: usize,
    pub vram: usize,
}

impl Memory {
    fn fits(self, used: Self, limit: Self) -> bool {
        self.ram <= limit.ram - used.ram && self.vram <= limit.vram - used.vram
    }
}

#[derive(Clone, Copy, Debug)]
pub struct Route {
    /// Full operation time, including preparation, transfers and synchronization.
    pub estimate: Duration,
    /// Concurrent working memory. Charge externally retained allocations separately.
    pub memory: Memory,
}

#[derive(Clone, Debug)]
pub struct Operation {
    pub dependencies: Vec<usize>,
    /// Assign different classes to algorithms with different cost characteristics.
    pub class: u64,
    pub bytes: usize,
    /// Indexed by Backend. None means that implementation is unavailable.
    pub routes: [Option<Route>; 3],
}

#[derive(Clone, Copy, Debug)]
pub struct Capacity {
    /// Maximum concurrent workers per backend.
    pub workers: [usize; 3],
    pub memory: Memory,
}

#[derive(Clone, Debug)]
pub struct Hardware {
    pub logical_workers: usize,
    pub available_ram: Option<u64>,
    pub avx2: bool,
    pub sse42: bool,
    pub sha: bool,
}

pub fn discover_host() -> Hardware {
    let mut hardware = Hardware {
        logical_workers: std::thread::available_parallelism().map_or(1, usize::from),
        available_ram: available_ram(),
        avx2: false,
        sse42: false,
        sha: false,
    };
    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    {
        hardware.avx2 = std::is_x86_feature_detected!("avx2");
        hardware.sse42 = std::is_x86_feature_detected!("sse4.2");
        hardware.sha = std::is_x86_feature_detected!("sha");
    }
    hardware
}

#[cfg(windows)]
fn available_ram() -> Option<u64> {
    #[repr(C)]
    struct MemoryStatus {
        length: u32,
        load_percent: u32,
        total_physical: u64,
        available_physical: u64,
        total_page_file: u64,
        available_page_file: u64,
        total_virtual: u64,
        available_virtual: u64,
        available_extended_virtual: u64,
    }
    #[link(name = "kernel32")]
    unsafe extern "system" {
        fn GlobalMemoryStatusEx(status: *mut MemoryStatus) -> i32;
    }
    let mut status = MemoryStatus {
        length: std::mem::size_of::<MemoryStatus>() as u32,
        load_percent: 0,
        total_physical: 0,
        available_physical: 0,
        total_page_file: 0,
        available_page_file: 0,
        total_virtual: 0,
        available_virtual: 0,
        available_extended_virtual: 0,
    };
    (unsafe { GlobalMemoryStatusEx(&mut status) } != 0).then_some(status.available_physical)
}
#[cfg(not(windows))]
fn available_ram() -> Option<u64> {
    None
}

#[derive(Clone, Copy, Debug)]
pub struct Sample {
    pub task: usize,
    pub backend: Backend,
    pub ready_at: Duration,
    pub dispatched_at: Duration,
    pub started_at: Duration,
    pub setup: Option<Duration>,
    pub elapsed: Duration,
}

#[derive(Debug)]
pub struct Report {
    pub elapsed: Duration,
    pub dependency_span: Duration,
    pub samples: Vec<Sample>,
    pub peak: Memory,
    pub memory_blocked: Duration,
    pub busy: [Duration; 3],
    pub fallbacks: Vec<(usize, String)>,
    pub model_resets: usize,
    pub plan_time: Duration,
    pub dispatch_time: Duration,
    pub wait_time: Duration,
    /// Scans in which an unfinished operation provided a lower bound on service time.
    pub censored_scans: usize,
}

/// Screening signal from timing counters. Confirm causality with a controlled trial.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Pressure {
    MemoryAdmission,
    Dependencies,
    Backend(Backend),
    Unclassified,
}

impl Report {
    pub fn pressure(&self, capacity: Capacity) -> Pressure {
        if self.elapsed.is_zero() {
            return Pressure::Unclassified;
        }
        if self.memory_blocked >= self.elapsed / 2 {
            return Pressure::MemoryAdmission;
        }
        if self.dependency_span >= self.elapsed - self.elapsed / 5 {
            return Pressure::Dependencies;
        }
        BACKENDS
            .into_iter()
            .filter_map(|backend| {
                let index = backend as usize;
                let workers = capacity.workers[index];
                (workers != 0).then(|| {
                    (
                        self.busy[index].as_secs_f64()
                            / (self.elapsed.as_secs_f64() * workers as f64),
                        backend,
                    )
                })
            })
            .max_by(|a, b| a.0.total_cmp(&b.0))
            .filter(|(utilization, _)| *utilization >= 0.8)
            .map_or(Pressure::Unclassified, |(_, backend)| {
                Pressure::Backend(backend)
            })
    }
}

/// Keep one history per workload, hardware and executor configuration.
#[derive(Default)]
pub struct History {
    service: HashMap<(u64, u32, Backend), Duration>,
    startup: [Option<Duration>; 3],
    frozen: bool,
    probe_joins: bool,
    censor: bool,
    deviations: HashMap<(u64, u32, Backend), (bool, Duration)>,
}

fn smooth(prior: Duration, sample: Duration) -> Duration {
    (prior - prior / 4).saturating_add(sample / 4)
}

impl History {
    /// Experimental policy. Probe high fan-in/fan-out joins on the accelerator
    /// and use the age of unfinished work as a temporary cost floor.
    pub fn live_probes(&mut self, probe_joins: bool, censor: bool) {
        self.probe_joins = probe_joins;
        self.censor = censor;
    }

    /// Freeze predictions for a controlled comparison. Explicit observations can be
    /// added before freezing. A frozen model supplies estimates but ignores completions.
    pub fn freeze(&mut self) {
        self.frozen = true;
    }

    fn key(class: u64, bytes: usize, backend: Backend) -> (u64, u32, Backend) {
        (class, bytes.checked_ilog2().unwrap_or(0), backend)
    }

    pub fn observe(&mut self, class: u64, bytes: usize, backend: Backend, elapsed: Duration) {
        self.update(class, bytes, backend, elapsed);
    }

    fn update(&mut self, class: u64, bytes: usize, backend: Backend, elapsed: Duration) -> bool {
        if self.frozen {
            return false;
        }
        let key = Self::key(class, bytes, backend);
        let Some(estimate) = self.service.get_mut(&key) else {
            self.service.insert(key, elapsed);
            return false;
        };
        let large_change = elapsed.abs_diff(*estimate) >= Duration::from_micros(25)
            && elapsed.max(*estimate) > elapsed.min(*estimate).saturating_mul(2);
        if large_change {
            let slower = elapsed > *estimate;
            if let Some((direction, previous)) = self.deviations.remove(&key)
                && direction == slower
            {
                *estimate = elapsed.min(previous) + elapsed.abs_diff(previous) / 2;
                return true;
            }
            self.deviations.insert(key, (slower, elapsed));
        } else {
            self.deviations.remove(&key);
            *estimate = smooth(*estimate, elapsed);
        }
        false
    }

    pub fn observe_startup(&mut self, backend: Backend, elapsed: Duration) {
        if self.frozen {
            return;
        }
        let slot = &mut self.startup[backend as usize];
        *slot = Some(slot.map_or(elapsed, |prior| smooth(prior, elapsed)));
    }

    fn predict(&self, op: &Operation, backend: Backend) -> Duration {
        self.service
            .get(&Self::key(op.class, op.bytes, backend))
            .copied()
            .unwrap_or_else(|| {
                op.routes[backend as usize]
                    .expect("supported route")
                    .estimate
            })
    }
}

pub enum Attempt {
    Done,
    /// Request a retry only before publishing an output or any visible side effects.
    RetryOnCpu(String),
}

#[derive(Clone, Copy)]
struct InFlight {
    memory: Memory,
    finish: Duration,
    task: usize,
    dispatched: Duration,
    predicted: Duration,
}

pub struct Scheduler {
    ops: Vec<Operation>,
    plan: Plan,
}

impl Scheduler {
    pub fn new(ops: Vec<Operation>) -> Result<Self, &'static str> {
        let plan = Plan::new(
            ops.iter()
                .map(|op| Task {
                    dependencies: op.dependencies.clone(),
                    device: Device::Cpu,
                    memory_bytes: 0,
                })
                .collect(),
        )?;
        Ok(Self { ops, plan })
    }

    /// Workers own backend state for the duration of a run, including !Send CUDA sessions.
    /// The callback publishes results before returning. Dependencies are released at completion.
    /// Independent operations already dispatched may finish after an error. Callers own
    /// the lifetime and memory accounting of results retained beyond an operation.
    pub fn execute<S>(
        &self,
        capacity: Capacity,
        history: &mut History,
        initialize: impl Fn(Backend) -> Result<S, String> + Sync,
        work: impl Fn(&mut S, usize, Backend) -> Result<(), String> + Sync,
    ) -> Result<Report, String> {
        self.execute_retry(capacity, history, initialize, |session, task, backend| {
            work(session, task, backend).map(|()| Attempt::Done)
        })
    }

    pub fn execute_retry<S>(
        &self,
        capacity: Capacity,
        history: &mut History,
        initialize: impl Fn(Backend) -> Result<S, String> + Sync,
        work: impl Fn(&mut S, usize, Backend) -> Result<Attempt, String> + Sync,
    ) -> Result<Report, String> {
        self.execute_interruptible(capacity, history, initialize, work, None)
    }

    /// Stop admitting nodes once cancellation is observed. Running callbacks finish
    /// before returning; callers can use the same flag for cooperative interruption.
    pub fn execute_interruptible<S>(
        &self,
        capacity: Capacity,
        history: &mut History,
        initialize: impl Fn(Backend) -> Result<S, String> + Sync,
        work: impl Fn(&mut S, usize, Backend) -> Result<Attempt, String> + Sync,
        cancelled: Option<&std::sync::atomic::AtomicBool>,
    ) -> Result<Report, String> {
        let is_cancelled =
            || cancelled.is_some_and(|flag| flag.load(std::sync::atomic::Ordering::Acquire));
        let start = Instant::now();
        let eligible = |op: &Operation, backend: Backend| {
            capacity.workers[backend as usize] != 0
                && op.routes[backend as usize]
                    .is_some_and(|route| route.memory.fits(Memory::default(), capacity.memory))
        };
        let mut choices: Vec<Vec<Backend>> = self
            .ops
            .iter()
            .map(|op| BACKENDS.into_iter().filter(|&b| eligible(op, b)).collect())
            .collect();
        if let Some(id) = choices.iter().position(Vec::is_empty) {
            return Err(format!("operation {id} has no feasible route"));
        }
        let mut pending = self.plan.incoming.clone();
        let mut order: Vec<_> = (0..self.ops.len()).filter(|&id| pending[id] == 0).collect();
        let mut cursor = 0;
        while cursor < order.len() {
            for &next in &self.plan.successors[order[cursor]] {
                pending[next] -= 1;
                if pending[next] == 0 {
                    order.push(next);
                }
            }
            cursor += 1;
        }
        let mut ranks = vec![Duration::ZERO; self.ops.len()];
        let rank = |ranks: &mut [Duration], choices: &[Vec<Backend>], history: &History| {
            for &id in order.iter().rev() {
                let cost = choices[id]
                    .iter()
                    .map(|&b| history.predict(&self.ops[id], b))
                    .min()
                    .unwrap();
                let tail = self.plan.successors[id]
                    .iter()
                    .map(|&next| ranks[next])
                    .max()
                    .unwrap_or_default();
                ranks[id] = cost.saturating_add(tail);
            }
        };
        rank(&mut ranks, &choices, history);
        pending.clone_from(&self.plan.incoming);
        let mut ready: BTreeSet<_> = order
            .iter()
            .copied()
            .filter(|&id| pending[id] == 0)
            .map(|id| (std::cmp::Reverse(ranks[id]), id))
            .collect();
        let mut ready_at = vec![Duration::ZERO; self.ops.len()];
        let mut finish = vec![Duration::ZERO; self.ops.len()];
        let mut peak = Memory::default();
        let mut used = Memory::default();
        let mut busy = [Duration::ZERO; 3];
        let mut memory_blocked = Duration::ZERO;
        let mut fallbacks = Vec::new();
        let mut model_resets = 0;
        let mut censored_scans = 0;
        let mut dispatch_time = Duration::ZERO;
        let mut wait_time = Duration::ZERO;
        let plan_time = start.elapsed();
        let mut samples = Vec::with_capacity(self.ops.len());
        std::thread::scope(|scope| {
            let (completed, events) = mpsc::channel();
            let mut workers = Vec::new();
            for backend in BACKENDS {
                let demand = choices
                    .iter()
                    .filter(|routes| routes.contains(&backend))
                    .count();
                for _ in 0..capacity.workers[backend as usize].min(demand) {
                    let worker_id = workers.len();
                    let (dispatch, queue) = mpsc::sync_channel::<(usize, Duration)>(1);
                    workers.push((backend, dispatch, None::<InFlight>, false));
                    let completed = completed.clone();
                    let initialize = &initialize;
                    let work = &work;
                    scope.spawn(move || {
                        // Open sessions only on workers that actually receive work.
                        let mut state = None;
                        while let Ok((task, dispatched_at)) = queue.recv() {
                            let started = start.elapsed();
                            let mut setup = None;
                            let result =
                                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                                    let state = state.get_or_insert_with(|| {
                                        let init = initialize(backend);
                                        setup = Some(start.elapsed() - started);
                                        init
                                    });
                                    work(state.as_mut().map_err(|e| e.clone())?, task, backend)
                                }))
                                .unwrap_or_else(|_| Err("worker panicked".into()));
                            if completed
                                .send((
                                    worker_id,
                                    task,
                                    dispatched_at,
                                    started,
                                    setup,
                                    start.elapsed() - started,
                                    result,
                                ))
                                .is_err()
                            {
                                break;
                            }
                        }
                    });
                }
            }
            drop(completed);
            while samples.len() < self.ops.len() {
                if is_cancelled() {
                    return Err("execution cancelled".into());
                }
                let tick = Instant::now();
                let mut floor = HashMap::new();
                if history.censor {
                    let now = start.elapsed();
                    for (backend, _, active, _) in &workers {
                        if let Some(active) = active {
                            let age = now.saturating_sub(active.dispatched);
                            if age
                                > active
                                    .predicted
                                    .saturating_mul(3)
                                    .saturating_add(Duration::from_micros(100))
                            {
                                let op = &self.ops[active.task];
                                let floor = floor
                                    .entry(History::key(op.class, op.bytes, *backend))
                                    .or_insert(Duration::ZERO);
                                *floor = (*floor).max(age.saturating_mul(2));
                            }
                        }
                    }
                }
                censored_scans += usize::from(!floor.is_empty());
                let mut waiting_for_memory = false;
                for &(_, id) in &ready {
                    if is_cancelled() {
                        return Err("execution cancelled".into());
                    }
                    let op = &self.ops[id];
                    let now = start.elapsed();
                    let candidate = workers
                        .iter()
                        .enumerate()
                        .filter_map(|(index, (backend, _, active, opened))| {
                            if !choices[id].contains(backend) {
                                return None;
                            }
                            let memory = op.routes[*backend as usize]?.memory;
                            if active.is_none() && !memory.fits(used, capacity.memory) {
                                return None;
                            }
                            let availability = active.map_or(now, |work| work.finish.max(now));
                            let cost = history.predict(op, *backend).max(
                                floor
                                    .get(&History::key(op.class, op.bytes, *backend))
                                    .copied()
                                    .unwrap_or_default(),
                            );
                            Some((
                                availability
                                    .saturating_add(cost)
                                    .saturating_add(if *opened {
                                        Duration::ZERO
                                    } else {
                                        history.startup[*backend as usize].unwrap_or_default()
                                    }),
                                index,
                                memory,
                            ))
                        })
                        .min_by_key(|&(eta, index, _)| {
                            let probe = history.probe_joins
                                && self.plan.incoming[id] >= 4
                                && self.plan.successors[id].len() >= 4
                                && choices[id].contains(&Backend::Accelerator);
                            (
                                probe && workers[index].0 != Backend::Accelerator,
                                eta,
                                workers[index].2.is_some(),
                                index,
                            )
                        });
                    waiting_for_memory |= workers.iter().any(|(backend, _, active, _)| {
                        active.is_none()
                            && choices[id].contains(backend)
                            && !op.routes[*backend as usize]
                                .unwrap()
                                .memory
                                .fits(used, capacity.memory)
                    });
                    if let Some((eta, index, memory)) = candidate
                        && workers[index].2.is_none()
                    {
                        workers[index]
                            .1
                            .send((id, now))
                            .map_err(|_| "worker disconnected")?;
                        workers[index].2 = Some(InFlight {
                            memory,
                            finish: eta,
                            task: id,
                            dispatched: now,
                            predicted: eta.saturating_sub(now),
                        });
                        workers[index].3 = true;
                        used.ram += memory.ram;
                        used.vram += memory.vram;
                        peak.ram = peak.ram.max(used.ram);
                        peak.vram = peak.vram.max(used.vram);
                        // Defer mutation of the ready set until after this scan.
                        pending[id] = usize::MAX;
                    }
                }
                ready.retain(|&(_, id)| pending[id] != usize::MAX);
                dispatch_time += tick.elapsed();
                let wait = Instant::now();
                let message = if history.censor && !ready.is_empty() || cancelled.is_some() {
                    match events.recv_timeout(Duration::from_micros(300)) {
                        Ok(event) => Some(event),
                        Err(mpsc::RecvTimeoutError::Timeout) => None,
                        Err(mpsc::RecvTimeoutError::Disconnected) => {
                            return Err("workers disconnected".into());
                        }
                    }
                } else {
                    Some(events.recv().map_err(|_| "workers disconnected")?)
                };
                wait_time += wait.elapsed();
                if waiting_for_memory {
                    memory_blocked += wait.elapsed();
                }
                let Some((index, id, dispatched_at, started_at, setup, elapsed, result)) = message
                else {
                    continue;
                };
                let tick = Instant::now();
                let outcome = result.map_err(|e| format!("operation {id}: {e}"))?;
                let (backend, _, active, _) = &mut workers[index];
                let memory = active.take().unwrap().memory;
                used.ram -= memory.ram;
                used.vram -= memory.vram;
                busy[*backend as usize] += elapsed;
                if let Attempt::RetryOnCpu(reason) = outcome {
                    if *backend != Backend::Accelerator || !choices[id].contains(&Backend::Cpu) {
                        return Err(format!("operation {id}: {reason}"));
                    }
                    choices[id].retain(|backend| *backend == Backend::Cpu);
                    fallbacks.push((id, reason));
                    pending[id] = 0;
                    ready.insert((std::cmp::Reverse(ranks[id]), id));
                    dispatch_time += tick.elapsed();
                    continue;
                }
                let op = &self.ops[id];
                if let Some(setup) = setup {
                    history.observe_startup(*backend, setup);
                }
                if history.update(
                    op.class,
                    op.bytes,
                    *backend,
                    elapsed - setup.unwrap_or_default(),
                ) {
                    model_resets += 1;
                    rank(&mut ranks, &choices, history);
                    ready = ready
                        .iter()
                        .map(|&(_, id)| (std::cmp::Reverse(ranks[id]), id))
                        .collect();
                }
                finish[id] = elapsed.saturating_add(
                    op.dependencies
                        .iter()
                        .map(|&dep| finish[dep])
                        .max()
                        .unwrap_or_default(),
                );
                samples.push(Sample {
                    task: id,
                    backend: *backend,
                    ready_at: ready_at[id],
                    dispatched_at,
                    started_at,
                    setup,
                    elapsed,
                });
                for &next in &self.plan.successors[id] {
                    pending[next] -= 1;
                    if pending[next] == 0 {
                        ready_at[next] = start.elapsed();
                        ready.insert((std::cmp::Reverse(ranks[next]), next));
                    }
                }
                dispatch_time += tick.elapsed();
            }
            Ok(Report {
                elapsed: start.elapsed(),
                dependency_span: finish.into_iter().max().unwrap_or_default(),
                samples,
                peak,
                memory_blocked,
                busy,
                fallbacks,
                model_resets,
                plan_time,
                dispatch_time,
                wait_time,
                censored_scans,
            })
        })
    }
}
/// Measurements of one policy with a stable workload and fixed correctness criteria.
#[derive(Debug)]
pub struct Calibration<T> {
    pub policy: T,
    samples: Vec<Duration>,
}

impl<T> Calibration<T> {
    pub fn samples(&self) -> &[Duration] {
        &self.samples
    }
    pub fn median(&self) -> Duration {
        let mut times = self.samples.clone();
        times.sort_unstable();
        let i = times.len() / 2;
        times[(times.len() - 1) / 2] + (times[i] - times[(times.len() - 1) / 2]) / 2
    }
}

/// Calibrate worker counts, batch sizes or other policies supplied by a caller.
/// The callback returns full wall time and can validate results outside that time.
pub fn calibrate<T: Copy, E>(
    policies: &[T],
    repeats: std::num::NonZeroUsize,
    mut measure: impl FnMut(T) -> Result<Duration, E>,
) -> Result<Vec<Calibration<T>>, E> {
    let mut profiles = policies
        .iter()
        .map(|&policy| Calibration {
            policy,
            samples: Vec::with_capacity(repeats.get()),
        })
        .collect::<Vec<_>>();
    for pass in 0..repeats.get() {
        for offset in 0..profiles.len() {
            let index = if pass % 2 == 0 {
                offset
            } else {
                profiles.len() - 1 - offset
            };
            let row = &mut profiles[index];
            row.samples.push(measure(row.policy)?);
        }
    }
    Ok(profiles)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cancellation_stops_before_releasing_dependents() {
        use std::sync::atomic::{AtomicBool, Ordering};
        let cancel = AtomicBool::new(false);
        let route = Some(Route {
            estimate: Duration::from_millis(1),
            memory: Memory::default(),
        });
        let node = |dependencies| Operation {
            dependencies,
            class: 0,
            bytes: 32,
            routes: [route, None, None],
        };
        let graph = Scheduler::new(vec![node(vec![]), node(vec![0])]).unwrap();
        let result = graph.execute_interruptible(
            Capacity {
                workers: [1, 0, 0],
                memory: Memory::default(),
            },
            &mut History::default(),
            |_| Ok(()),
            |_, id, _| {
                assert_eq!(id, 0);
                cancel.store(true, Ordering::Release);
                Ok(Attempt::Done)
            },
            Some(&cancel),
        );
        assert_eq!(result.unwrap_err(), "execution cancelled");
    }

    #[test]
    fn detects_consecutive_workload_changes_and_ignores_a_frozen_model() {
        let mut history = History::default();
        let sample = |ms| Duration::from_millis(ms);
        history.observe(7, 64, Backend::Cpu, sample(1));
        assert!(!history.update(7, 64, Backend::Cpu, sample(10)));
        assert!(history.update(7, 64, Backend::Cpu, sample(12)));
        assert_eq!(
            history.service[&History::key(7, 64, Backend::Cpu)],
            sample(11)
        );
        history.freeze();
        assert!(!history.update(7, 64, Backend::Cpu, sample(150)));
        assert_eq!(
            history.service[&History::key(7, 64, Backend::Cpu)],
            sample(11)
        );
    }

    #[test]
    fn critical_chain_precedes_root_and_reuses_worker() {
        let route = Some(Route {
            estimate: Duration::from_millis(1),
            memory: Memory { ram: 8, vram: 0 },
        });
        let make = |dependencies| Operation {
            dependencies,
            class: 0,
            bytes: 8,
            routes: [route, None, None],
        };
        let graph = Scheduler::new(vec![
            make(vec![]),
            make(vec![]),
            make(vec![1]),
            make(vec![2]),
        ])
        .unwrap();
        let runs = std::sync::Mutex::new(Vec::new());
        let report = graph
            .execute(
                Capacity {
                    workers: [2, 0, 0],
                    memory: Memory { ram: 8, vram: 0 },
                },
                &mut History::default(),
                |_| Ok(0),
                |state, id, _| {
                    *state += 1;
                    runs.lock().unwrap().push((id, *state));
                    Ok(())
                },
            )
            .unwrap();
        let values = runs.into_inner().unwrap();
        assert_eq!(values[0].0, 1);
        assert_eq!(values.len(), 4);
        assert!(values.iter().any(|&(_, calls)| calls > 1));
        assert_eq!(report.peak.ram, 8);
        assert!(report.elapsed >= report.dependency_span);
    }

    #[test]
    fn uses_feasible_route_when_gpu_memory_is_too_small() {
        let operation = Operation {
            dependencies: vec![],
            class: 0,
            bytes: 8,
            routes: [
                Some(Route {
                    estimate: Duration::from_millis(2),
                    memory: Memory { ram: 8, vram: 0 },
                }),
                Some(Route {
                    estimate: Duration::ZERO,
                    memory: Memory { ram: 8, vram: 16 },
                }),
                None,
            ],
        };
        let scheduler = Scheduler::new(vec![operation]).unwrap();
        let report = scheduler
            .execute(
                Capacity {
                    workers: [1, 1, 0],
                    memory: Memory { ram: 8, vram: 8 },
                },
                &mut History::default(),
                Ok,
                |backend, _, _| {
                    assert_eq!(*backend, Backend::Cpu);
                    Ok(())
                },
            )
            .unwrap();
        assert_eq!(report.samples[0].backend, Backend::Cpu);
    }
}