rustsy-engine 0.1.0

Task graph scheduling, residency planning and bounded streaming pipelines
Documentation
use std::{
    io,
    sync::mpsc::sync_channel,
    thread,
    time::{Duration, Instant},
};

#[derive(Debug, Default)]
pub struct Stage {
    pub batches: usize,
    pub work: Duration,
    pub wait_input: Duration,
    pub wait_output: Duration,
}

#[derive(Debug)]
pub struct Metrics {
    pub elapsed: Duration,
    pub read: Stage,
    pub compute: Stage,
    pub write: Stage,
}

/// Choose a previously measured queue depth for this storage pair and workload.
/// Each row is a complete wall-clock sample, with depth zero as the baseline.
/// Require two samples per candidate and an improvement in both the median and
/// worst observed trial. Insufficient data leaves the serial pipeline selected.
pub fn select_depth(samples: &[(usize, Duration)]) -> usize {
    let summarize = |depth| {
        let mut times = samples
            .iter()
            .filter_map(|&(d, t)| (d == depth).then_some(t))
            .collect::<Vec<_>>();
        times.sort_unstable();
        (times.len() >= 2).then(|| {
            let midpoint = times.len() / 2;
            let median = times[(times.len() - 1) / 2] / 2 + times[midpoint] / 2;
            (median, times[times.len() - 1])
        })
    };
    let Some((baseline, worst_baseline)) = summarize(0) else {
        return 0;
    };
    [2, 3]
        .into_iter()
        .filter_map(|depth| {
            let (median, worst) = summarize(depth)?;
            (median.as_nanos() * 100 < baseline.as_nanos() * 97 && worst <= worst_baseline)
                .then_some((median, depth))
        })
        .min()
        .map_or(0, |(_, depth)| depth)
}

/// Stream jobs through a bounded pipeline. Reuse exactly N input buffers supplied by
/// the caller. The transform runs on the calling thread, which can own a CUDA context.
/// The sink owns each output until written. Up to N outputs can be queued or written,
/// plus one being produced by the transform. Size each batch to fit that memory budget.
pub fn run<Job: Send, Buffer: Send, Output: Send>(
    mut buffers: Vec<Buffer>,
    next: impl FnMut() -> Option<Job> + Send,
    load: impl FnMut(&Job, &mut Buffer) -> io::Result<()> + Send,
    process: impl FnMut(&Job, &mut Buffer) -> io::Result<Output>,
    store: impl FnMut(Job, Output) -> io::Result<()> + Send,
) -> io::Result<Metrics> {
    run_with_pool(&mut buffers, next, load, process, store)
}

/// Borrow reusable input storage across runs, including after a stage error.
/// Pool elements stay owned by the caller and remain valid when the threads join.
pub fn run_with_pool<Job: Send, Buffer: Send, Output: Send>(
    buffers: &mut [Buffer],
    mut next: impl FnMut() -> Option<Job> + Send,
    mut load: impl FnMut(&Job, &mut Buffer) -> io::Result<()> + Send,
    mut process: impl FnMut(&Job, &mut Buffer) -> io::Result<Output>,
    mut store: impl FnMut(Job, Output) -> io::Result<()> + Send,
) -> io::Result<Metrics> {
    let depth = buffers.len();
    if depth < 2 {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "at least two buffers required",
        ));
    }
    let start = Instant::now();
    thread::scope(|scope| {
        let (recycle, free) = sync_channel(depth);
        for buffer in buffers {
            assert!(recycle.send(buffer).is_ok(), "empty buffer pool");
        }
        let (loaded, input) = sync_channel(depth - 1);
        let (processed, output) = sync_channel(depth - 1);
        let reader = scope.spawn(move || -> io::Result<Stage> {
            let mut stage = Stage::default();
            while let Some(job) = next() {
                let time = Instant::now();
                let Ok(buffer) = free.recv() else { break };
                stage.wait_input += time.elapsed();
                let time = Instant::now();
                load(&job, buffer)?;
                stage.work += time.elapsed();
                stage.batches += 1;
                let time = Instant::now();
                if loaded.send((job, buffer)).is_err() {
                    break;
                }
                stage.wait_output += time.elapsed();
            }
            Ok(stage)
        });
        let writer = scope.spawn(move || -> io::Result<Stage> {
            let mut stage = Stage::default();
            loop {
                let time = Instant::now();
                let Ok((job, value)) = output.recv() else {
                    break;
                };
                stage.wait_input += time.elapsed();
                let time = Instant::now();
                store(job, value)?;
                stage.work += time.elapsed();
                stage.batches += 1;
            }
            Ok(stage)
        });
        let compute = (|| -> io::Result<Stage> {
            let mut stage = Stage::default();
            loop {
                let time = Instant::now();
                let Ok((job, buffer)) = input.recv() else {
                    break;
                };
                stage.wait_input += time.elapsed();
                let time = Instant::now();
                let value = process(&job, buffer)?;
                stage.work += time.elapsed();
                stage.batches += 1;
                // A finished reader has no further need for its buffers.
                let _ = recycle.try_send(buffer);
                let time = Instant::now();
                if processed.send((job, value)).is_err() {
                    break;
                }
                stage.wait_output += time.elapsed();
            }
            Ok(stage)
        })();
        drop(input);
        drop(processed);
        drop(recycle);
        let read = reader
            .join()
            .map_err(|_| io::Error::other("pipeline reader panicked"))?;
        let write = writer
            .join()
            .map_err(|_| io::Error::other("pipeline writer panicked"))?;
        Ok(Metrics {
            elapsed: start.elapsed(),
            read: read?,
            compute: compute?,
            write: write?,
        })
    })
}

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

    #[test]
    fn reuses_input_and_keeps_order() {
        let mut written = Vec::new();
        let mut jobs = 0..128;
        let mut pool: [_; 3] = std::array::from_fn(|_| Vec::with_capacity(8));
        let metrics = run_with_pool(
            &mut pool,
            || jobs.next(),
            |job, buffer| {
                buffer.clear();
                buffer.push(*job);
                Ok(())
            },
            |_, buffer| Ok(buffer[0] * 2),
            |job, result| {
                written.push((job, result));
                Ok(())
            },
        )
        .unwrap();
        assert_eq!(written, (0..128).map(|n| (n, n * 2)).collect::<Vec<_>>());
        assert_eq!(metrics.write.batches, 128);
        assert!(pool.iter().any(|buffer| !buffer.is_empty()));
    }

    #[test]
    fn selects_a_measured_depth_only_when_it_is_consistently_faster() {
        let samples = [(0, 100), (0, 100), (2, 85), (2, 90), (3, 60), (3, 105)];
        let durations = samples.map(|(depth, millis)| (depth, Duration::from_millis(millis)));
        assert_eq!(select_depth(&durations), 2);
        assert_eq!(select_depth(&durations[..3]), 0);
    }

    #[test]
    fn cancels_when_any_stage_fails() {
        for failing in 0..3 {
            let mut jobs = 0..1000;
            let stage = |n| {
                if n == failing {
                    Err(io::Error::other("stage failed"))
                } else {
                    Ok(())
                }
            };
            let result = run(
                vec![(); 2],
                || jobs.next(),
                |_, _| stage(0),
                |_, _| stage(1),
                |_, _| stage(2),
            );
            assert_eq!(result.unwrap_err().to_string(), "stage failed");
        }
    }
}