Skip to main content

rustsy_engine/
pipeline.rs

1use std::{
2    io,
3    sync::mpsc::sync_channel,
4    thread,
5    time::{Duration, Instant},
6};
7
8#[derive(Debug, Default)]
9pub struct Stage {
10    pub batches: usize,
11    pub work: Duration,
12    pub wait_input: Duration,
13    pub wait_output: Duration,
14}
15
16#[derive(Debug)]
17pub struct Metrics {
18    pub elapsed: Duration,
19    pub read: Stage,
20    pub compute: Stage,
21    pub write: Stage,
22}
23
24/// Choose a previously measured queue depth for this storage pair and workload.
25/// Each row is a complete wall-clock sample, with depth zero as the baseline.
26/// Require two samples per candidate and an improvement in both the median and
27/// worst observed trial. Insufficient data leaves the serial pipeline selected.
28pub fn select_depth(samples: &[(usize, Duration)]) -> usize {
29    let summarize = |depth| {
30        let mut times = samples
31            .iter()
32            .filter_map(|&(d, t)| (d == depth).then_some(t))
33            .collect::<Vec<_>>();
34        times.sort_unstable();
35        (times.len() >= 2).then(|| {
36            let midpoint = times.len() / 2;
37            let median = times[(times.len() - 1) / 2] / 2 + times[midpoint] / 2;
38            (median, times[times.len() - 1])
39        })
40    };
41    let Some((baseline, worst_baseline)) = summarize(0) else {
42        return 0;
43    };
44    [2, 3]
45        .into_iter()
46        .filter_map(|depth| {
47            let (median, worst) = summarize(depth)?;
48            (median.as_nanos() * 100 < baseline.as_nanos() * 97 && worst <= worst_baseline)
49                .then_some((median, depth))
50        })
51        .min()
52        .map_or(0, |(_, depth)| depth)
53}
54
55/// Stream jobs through a bounded pipeline. Reuse exactly N input buffers supplied by
56/// the caller. The transform runs on the calling thread, which can own a CUDA context.
57/// The sink owns each output until written. Up to N outputs can be queued or written,
58/// plus one being produced by the transform. Size each batch to fit that memory budget.
59pub fn run<Job: Send, Buffer: Send, Output: Send>(
60    mut buffers: Vec<Buffer>,
61    next: impl FnMut() -> Option<Job> + Send,
62    load: impl FnMut(&Job, &mut Buffer) -> io::Result<()> + Send,
63    process: impl FnMut(&Job, &mut Buffer) -> io::Result<Output>,
64    store: impl FnMut(Job, Output) -> io::Result<()> + Send,
65) -> io::Result<Metrics> {
66    run_with_pool(&mut buffers, next, load, process, store)
67}
68
69/// Borrow reusable input storage across runs, including after a stage error.
70/// Pool elements stay owned by the caller and remain valid when the threads join.
71pub fn run_with_pool<Job: Send, Buffer: Send, Output: Send>(
72    buffers: &mut [Buffer],
73    mut next: impl FnMut() -> Option<Job> + Send,
74    mut load: impl FnMut(&Job, &mut Buffer) -> io::Result<()> + Send,
75    mut process: impl FnMut(&Job, &mut Buffer) -> io::Result<Output>,
76    mut store: impl FnMut(Job, Output) -> io::Result<()> + Send,
77) -> io::Result<Metrics> {
78    let depth = buffers.len();
79    if depth < 2 {
80        return Err(io::Error::new(
81            io::ErrorKind::InvalidInput,
82            "at least two buffers required",
83        ));
84    }
85    let start = Instant::now();
86    thread::scope(|scope| {
87        let (recycle, free) = sync_channel(depth);
88        for buffer in buffers {
89            assert!(recycle.send(buffer).is_ok(), "empty buffer pool");
90        }
91        let (loaded, input) = sync_channel(depth - 1);
92        let (processed, output) = sync_channel(depth - 1);
93        let reader = scope.spawn(move || -> io::Result<Stage> {
94            let mut stage = Stage::default();
95            while let Some(job) = next() {
96                let time = Instant::now();
97                let Ok(buffer) = free.recv() else { break };
98                stage.wait_input += time.elapsed();
99                let time = Instant::now();
100                load(&job, buffer)?;
101                stage.work += time.elapsed();
102                stage.batches += 1;
103                let time = Instant::now();
104                if loaded.send((job, buffer)).is_err() {
105                    break;
106                }
107                stage.wait_output += time.elapsed();
108            }
109            Ok(stage)
110        });
111        let writer = scope.spawn(move || -> io::Result<Stage> {
112            let mut stage = Stage::default();
113            loop {
114                let time = Instant::now();
115                let Ok((job, value)) = output.recv() else {
116                    break;
117                };
118                stage.wait_input += time.elapsed();
119                let time = Instant::now();
120                store(job, value)?;
121                stage.work += time.elapsed();
122                stage.batches += 1;
123            }
124            Ok(stage)
125        });
126        let compute = (|| -> io::Result<Stage> {
127            let mut stage = Stage::default();
128            loop {
129                let time = Instant::now();
130                let Ok((job, buffer)) = input.recv() else {
131                    break;
132                };
133                stage.wait_input += time.elapsed();
134                let time = Instant::now();
135                let value = process(&job, buffer)?;
136                stage.work += time.elapsed();
137                stage.batches += 1;
138                // A finished reader has no further need for its buffers.
139                let _ = recycle.try_send(buffer);
140                let time = Instant::now();
141                if processed.send((job, value)).is_err() {
142                    break;
143                }
144                stage.wait_output += time.elapsed();
145            }
146            Ok(stage)
147        })();
148        drop(input);
149        drop(processed);
150        drop(recycle);
151        let read = reader
152            .join()
153            .map_err(|_| io::Error::other("pipeline reader panicked"))?;
154        let write = writer
155            .join()
156            .map_err(|_| io::Error::other("pipeline writer panicked"))?;
157        Ok(Metrics {
158            elapsed: start.elapsed(),
159            read: read?,
160            compute: compute?,
161            write: write?,
162        })
163    })
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn reuses_input_and_keeps_order() {
172        let mut written = Vec::new();
173        let mut jobs = 0..128;
174        let mut pool: [_; 3] = std::array::from_fn(|_| Vec::with_capacity(8));
175        let metrics = run_with_pool(
176            &mut pool,
177            || jobs.next(),
178            |job, buffer| {
179                buffer.clear();
180                buffer.push(*job);
181                Ok(())
182            },
183            |_, buffer| Ok(buffer[0] * 2),
184            |job, result| {
185                written.push((job, result));
186                Ok(())
187            },
188        )
189        .unwrap();
190        assert_eq!(written, (0..128).map(|n| (n, n * 2)).collect::<Vec<_>>());
191        assert_eq!(metrics.write.batches, 128);
192        assert!(pool.iter().any(|buffer| !buffer.is_empty()));
193    }
194
195    #[test]
196    fn selects_a_measured_depth_only_when_it_is_consistently_faster() {
197        let samples = [(0, 100), (0, 100), (2, 85), (2, 90), (3, 60), (3, 105)];
198        let durations = samples.map(|(depth, millis)| (depth, Duration::from_millis(millis)));
199        assert_eq!(select_depth(&durations), 2);
200        assert_eq!(select_depth(&durations[..3]), 0);
201    }
202
203    #[test]
204    fn cancels_when_any_stage_fails() {
205        for failing in 0..3 {
206            let mut jobs = 0..1000;
207            let stage = |n| {
208                if n == failing {
209                    Err(io::Error::other("stage failed"))
210                } else {
211                    Ok(())
212                }
213            };
214            let result = run(
215                vec![(); 2],
216                || jobs.next(),
217                |_, _| stage(0),
218                |_, _| stage(1),
219                |_, _| stage(2),
220            );
221            assert_eq!(result.unwrap_err().to_string(), "stage failed");
222        }
223    }
224}