Files
obipipeline/tests/scheduling.rs
T
Eric Coissac 8fbd73a657
Release / release (push) Successful in 1m11s
refactor: redesign scheduler with shared worker pool and fallible iterators
The pipeline scheduler is refactored to use a shared worker pool instead of
dedicated threads per stage, and `PipeIter` now yields `Result` items to
propagate errors as the last element. The change introduces a new state
machine for scheduling, updates error handling types, and reorganizes tests
to cover scheduling and shutdown behaviors separately.

- Update package version to 0.2.0, Rust MSRV to 1.100, and add
  `crossbeam-channel` dependency in `Cargo.toml` and `Cargo.lock`.
- Refactor `src/scheduler/pipe.rs` to yield `Result<Out, PipelineError>`
  from `PipeIter`, adding cancellation support and moving `finish` to
  `pool.rs` as `wait`.
- Introduce `src/scheduler/state.rs` with `State`, `Job`, and `Outcome`
  types, moving `dispatch` from `runner.rs` to `pick` in the new module.
- Rewrite `src/scheduler/runner.rs` to use shared state and signals,
  removing `dispatch` and `transform_runner` while adding worker and
  source/sink runners with lock-based synchronization.
- Add `src/scheduler/pool.rs` methods `start` and `wait` to manage thread
  lifecycle, replacing the previous handle-based approach in `WorkerPool`.
- Replace `WorkerPanic` with `Panicked` and add `NeverFails` error types
  in `src/scheduler/error.rs` for clearer error reporting.
- Update `src/scheduler/macros.rs` to use fallible variants for source,
  transform, flat, and sink macros, ensuring proper error propagation.
- Remove `WorkerTask` from `src/scheduler/types.rs` and add `SharedFlatFn`
  alias for 1->N transform functions returning lazy sequences.
- Update `src/lib.rs` documentation to reflect the new scheduler behavior
  and expose `NeverFails` and `Stage` publicly.
- Enhance `src/throttle.rs` documentation to clarify slot acquisition
  rules and guard behavior in flat stages to prevent deadlocks.
- Add `tests/scheduling.rs` with tests for deadlock prevention and
  scheduling priority, moving `fallible_flat_stage_error_is_returned_and_does_not_hang`
  from `tests/errors.rs`.
- Add `tests/shutdown.rs` with tests for early drop and panic message
  preservation, moving `worker_panic_is_returned_and_does_not_hang`
  from `tests/errors.rs`.
- Refactor `tests/errors.rs` to focus on error propagation as the last
  iterator item, adding comprehensive tests for panics and type mismatches.
- Update `tests/pipe.rs` to use `.collect::<Result<_, _>>()` for handling
  fallible iterators in existing tests.
- Add `figures/pipeline.svg` visualizing the parallel scheduler logic.
- Add API documentation snapshots for version 0.2.0 in `api/`.
- Update `.crate-kit/` scripts to support MSRV checking and improved
  dependency update logic, adding `msrv-check.sh` and refining
  `publish-guard.sh`.
2026-12-02 15:48:59 +01:00

129 lines
4.2 KiB
Rust

//! Scheduling: downstream stages first, lazy 1→N stages, no deadlock with small queues.
use obipipeline::{Throttled, make_pipe, throttle};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, mpsc};
use std::thread;
use std::time::Duration;
enum D {
Num(u64),
Held(Throttled<u64>),
}
/// Runs `f` on a thread and fails the test if it does not finish in time.
fn within<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let _ = tx.send(f());
});
rx.recv_timeout(Duration::from_secs(20))
.expect("the pipeline hung")
}
fn hundred(x: u64) -> impl Iterator<Item = u64> + Send {
// Slow to start, so that the other inputs are queued meanwhile.
thread::sleep(Duration::from_millis(5));
(0..100).map(move |i| x * 100 + i)
}
fn identity(x: u64) -> u64 {
x
}
#[test]
fn flat_stage_followed_by_a_stage_never_deadlocks() {
for (workers, capacity) in [(1, 1), (4, 4), (4, 16), (8, 1)] {
let n = within(move || {
let pipe =
make_pipe! { D : u64 => u64, || hundred : Num => Num, | identity : Num => Num, };
pipe.apply(0..20u64, workers, capacity)
.filter(Result::is_ok)
.count()
});
assert_eq!(n, 2000, "workers={workers} capacity={capacity}");
}
}
#[test]
fn chained_flat_stages_with_one_worker_and_one_slot() {
fn three(x: u64) -> Vec<u64> {
vec![x; 3]
}
let n = within(|| {
let pipe = make_pipe! {
D : u64 => u64,
|| three : Num => Num,
|| three : Num => Num,
| identity : Num => Num,
};
pipe.apply(0..50u64, 1, 1).filter(Result::is_ok).count()
});
assert_eq!(n, 450);
}
#[test]
fn throttle_larger_than_the_pool_does_not_deadlock() {
fn expand(t: Throttled<u64>) -> impl Iterator<Item = u64> + Send {
(0..100).map(move |i| {
let _held = &t.guard; // the slot lives as long as the expansion
t.item + i
})
}
let n = within(|| {
let pipe = make_pipe! { D : Throttled<u64> => u64, || expand : Held => Num, | identity : Num => Num, };
pipe.apply(throttle(0..50u64, 8), 4, 2)
.filter(Result::is_ok)
.count()
});
assert_eq!(n, 5000);
}
#[test]
fn the_most_advanced_stage_is_served_first() {
let log: Arc<Mutex<Vec<(char, u64)>>> = Arc::default();
let (first, second) = (Arc::clone(&log), Arc::clone(&log));
let produce = move |x: u64| {
let log = Arc::clone(&first);
(0..3).map(move |i| {
log.lock().unwrap().push(('p', x * 10 + i));
x * 10 + i
})
};
let consume = move |x: u64| {
second.lock().unwrap().push(('c', x));
x
};
within(move || {
let pipe = make_pipe! { D : u64 => u64, || produce : Num => Num, | consume : Num => Num, };
// One worker and an output queue that never fills: the order is fully determined.
pipe.apply(0..10u64, 1, 1000).count()
});
let log = log.lock().unwrap();
assert_eq!(log.len(), 60);
for pair in log.chunks(2) {
assert_eq!((pair[0].0, pair[1].0), ('p', 'c'), "{log:?}");
assert_eq!(pair[0].1, pair[1].1);
}
}
#[test]
fn a_flat_stage_is_pulled_only_as_downstream_makes_room() {
let produced = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&produced);
let endless = move |_: u64| {
let counter = Arc::clone(&counter);
std::iter::from_fn(move || Some(counter.fetch_add(1, Ordering::SeqCst) as u64))
};
let (workers, capacity) = (3, 4);
within(move || {
let pipe = make_pipe! { D : u64 => u64, || endless : Num => Num, | identity : Num => Num, };
let mut out = pipe.apply(0..1u64, workers, capacity);
assert!(out.next().is_some());
thread::sleep(Duration::from_millis(200)); // nobody consumes: production must stop
drop(out); // and dropping an endless expansion must not hang
});
// Two stage output queues, the output channel, the sink's item and the consumed one.
assert!(produced.load(Ordering::SeqCst) <= 3 * capacity + 2);
}