refactor: implement fail-fast error handling and panic recovery in pipelines

Introduce robust error propagation for multi-threaded pipelines, ensuring that
errors in sources, stages, or sinks cause immediate termination. Add support
for catching worker panics and converting them into structured errors, and
enforce strict validation of worker pool and throttle configuration.

- Add `WorkerPanic` struct and variant to `PipelineError` in `src/scheduler/error.rs`,
  along with `panic_error` helper to convert panic payloads into errors.
- Modify `WorkerPool::run` in `src/scheduler/pool.rs` to return `Result<(), PipelineError>`,
  propagate errors from sources/sinks, and detect uncaught panics in worker threads.
- Update `source_runner` and `transform_runner` in `src/scheduler/runner.rs` to send
  errors to the scheduler instead of printing to stderr, and use `catch_unwind` to
  handle panics in transformation stages, including flat transforms.
- Refactor `PipeIter` in `src/scheduler/pipe.rs` to include a `finish` method that
  joins the worker thread and returns a `Result`, replacing implicit drop-based
  error handling with explicit error reporting.
- Update `make_pipeline!` and `make_pipe!` macros in `src/scheduler/macros.rs` to
  signal errors via `-1` delta, and add documentation examples for pipeline usage.
- Add `Flat` variant to `Stage` enum in `src/scheduler/types.rs` to support flat
  transformation stages in the scheduler.
- Enhance `Throttle` in `src/throttle.rs` with a `lock` method for mutex management,
  poison error recovery, and validation that `max > 0` in the constructor.
- Add comprehensive tests in `tests/errors.rs` covering error propagation, panic
  recovery, capacity/worker validation, and pipeline execution flow.
- Update `README.md` to document "Errors and limits", detailing fail-fast behavior,
  error handling in `PipeIter` and `WorkerPool::run()`, and constraints on arguments.
- Set `rust-version = "1.85"` and update description in `Cargo.toml`.
- Update `examples/sandbox_pipeline.rs` to use `.expect("pipeline failed")` on
  `WorkerPool::run()` to demonstrate error handling.
This commit is contained in:
Eric Coissac committed 2026-12-02 15:46:18 +01:00
1 parent e14fb6a287
commit f68243cde0
12 files changed
+537 -40

No files matched your search

+274
View File
@@ -0,0 +1,274 @@
//! Error semantics: the first error stops the pipeline and is returned by `finish()` / `run()`;
//! no failure may hang. Every test runs under a timeout guard.
use obipipeline::{
Pipeline, PipelineError, Throttle, WorkerPool, make_pipe, make_pipeline, throttle,
};
use std::io::{Error, ErrorKind};
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
// The `Text` payload is only built, never read back: it exists to trigger a runtime mismatch.
#[allow(dead_code)]
enum D {
Num(u64),
Text(String),
}
/// Runs `f` on a thread and fails the test if it does not finish in time (a hang is the bug to catch).
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(10))
.expect("the pipeline hung")
}
fn fails_on_5(x: u64) -> Result<u64, Error> {
if x == 5 {
Err(Error::new(ErrorKind::InvalidData, "boom on 5"))
} else {
Ok(x)
}
}
fn flat_fails_on_5(x: u64) -> Result<Vec<u64>, Error> {
fails_on_5(x).map(|v| vec![v, v])
}
fn panics_on_3(x: u64) -> u64 {
assert!(x != 3, "boom on 3");
x
}
fn to_text(x: u64) -> String {
x.to_string()
}
fn plus_one(x: u64) -> u64 {
x + 1
}
fn identity(x: u64) -> u64 {
x
}
fn triple(x: u64) -> Vec<u64> {
vec![x, x, x]
}
fn ignore(_x: u64) {}
fn message(e: &PipelineError) -> String {
e.to_string()
}
#[test]
fn fallible_stage_error_is_returned_and_does_not_hang() {
let (items, result) = within(|| {
let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, };
let mut it = pipe.apply(1..=10u64, 2, 4);
let items: Vec<u64> = it.by_ref().collect();
(items, it.finish())
});
assert!(items.len() < 10, "the pipeline must stop early");
let err = result.expect_err("the stage error must be returned");
assert!(message(&err).contains("boom on 5"), "{err}");
}
#[test]
fn fallible_flat_stage_error_is_returned_and_does_not_hang() {
let result = within(|| {
let pipe = make_pipe! { D : u64 => u64, ||? flat_fails_on_5 : Num => Num, };
pipe.apply(1..=10u64, 2, 4).finish()
});
assert!(message(&result.unwrap_err()).contains("boom on 5"));
}
#[test]
fn runtime_type_mismatch_is_returned_and_does_not_hang() {
let result = within(|| {
// The first stage produces a Text, the second one reads a Num.
let pipe = make_pipe! {
D : u64 => u64,
| to_text : Num => Text,
| panics_on_3 : Num => Num,
};
pipe.apply(1..=10u64, 2, 4).finish()
});
assert!(matches!(result, Err(PipelineError::TypeMismatch)));
}
#[test]
fn worker_panic_is_returned_and_does_not_hang() {
let result = within(|| {
let pipe = make_pipe! { D : u64 => u64, | panics_on_3 : Num => Num, };
pipe.apply(1..=10u64, 2, 4).finish()
});
assert!(message(&result.unwrap_err()).contains("boom on 3"));
}
#[test]
fn finish_is_ok_when_everything_went_through() {
let (n, result) = within(|| {
let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, };
let mut it = pipe.apply(6..=20u64, 3, 4);
let n = it.by_ref().count();
(n, it.finish())
});
assert_eq!(n, 15);
assert!(result.is_ok());
}
#[test]
fn capacity_one_works() {
let n = within(|| {
let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, };
pipe.apply(6..=205u64, 2, 1).count()
});
assert_eq!(n, 200);
}
#[test]
#[should_panic(expected = "capacity of at least 1")]
fn zero_capacity_is_rejected() {
let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, };
let _ = pipe.apply(0..3u64, 2, 0);
}
#[test]
#[should_panic(expected = "at least one worker")]
fn zero_workers_is_rejected() {
let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, };
let _ = pipe.apply(0..3u64, 0, 4);
}
#[test]
#[should_panic(expected = "at least one slot")]
fn throttle_new_zero_is_rejected() {
let _ = Throttle::new(0);
}
#[test]
#[should_panic(expected = "at least one slot")]
fn throttle_zero_is_rejected() {
let _ = throttle(0..3u32, 0).count();
}
// ── Pipeline / WorkerPool (the lower-level runtime) ─────────────────────────────
fn pool_run(pipeline: Pipeline<D>) -> Result<(), PipelineError> {
WorkerPool::new(pipeline, 3, 4).run()
}
#[test]
fn pipeline_runs_and_reaches_the_sink() {
let (tx, rx) = mpsc::channel::<u64>();
let result = within(move || {
let collect = move |x: u64| tx.send(x).unwrap();
let pipeline = make_pipeline! {
D,
source 1..=50u64 => Num,
| plus_one : Num => Num,
sink collect @ Num,
};
pool_run(pipeline)
});
assert!(result.is_ok());
let mut got: Vec<u64> = rx.try_iter().collect();
got.sort_unstable();
assert_eq!(got, (2..=51).collect::<Vec<_>>());
}
#[test]
fn pipeline_returns_a_stage_error() {
let result = within(|| {
pool_run(make_pipeline! {
D,
source 1..=20u64 => Num,
|? fails_on_5 : Num => Num,
sink ignore @ Num,
})
});
assert!(message(&result.unwrap_err()).contains("boom on 5"));
}
fn fallible_source() -> Vec<Result<u64, Error>> {
vec![
Ok(1),
Ok(2),
Err(Error::new(ErrorKind::UnexpectedEof, "source broke")),
Ok(4),
]
}
#[test]
fn pipeline_returns_a_source_error() {
let result = within(|| {
pool_run(make_pipeline! {
D,
source? fallible_source() => Num,
| identity : Num => Num,
sink ignore @ Num,
})
});
assert!(message(&result.unwrap_err()).contains("source broke"));
}
fn failing_sink(x: u64) -> Result<(), Error> {
if x == 7 {
Err(Error::new(ErrorKind::BrokenPipe, "sink broke"))
} else {
Ok(())
}
}
#[test]
fn pipeline_returns_a_sink_error() {
let result = within(|| {
pool_run(make_pipeline! {
D,
source 1..=20u64 => Num,
| identity : Num => Num,
sink? failing_sink @ Num,
})
});
assert!(message(&result.unwrap_err()).contains("sink broke"));
}
#[test]
fn pipeline_with_a_flat_stage_counts_every_item() {
let (tx, rx) = mpsc::channel::<u64>();
let result = within(move || {
let collect = move |x: u64| tx.send(x).unwrap();
pool_run(make_pipeline! {
D,
source 1..=10u64 => Num,
|| triple : Num => Num,
sink collect @ Num,
})
});
assert!(result.is_ok());
assert_eq!(rx.try_iter().count(), 30);
}
// ── PipelineError ───────────────────────────────────────────────────────────────
#[test]
fn pipeline_error_display_and_source() {
use std::error::Error as _;
assert_eq!(
PipelineError::TypeMismatch.to_string(),
"data type mismatch in pipeline stage"
);
assert_eq!(
PipelineError::EndOfStream.to_string(),
"end of input stream"
);
assert!(PipelineError::TypeMismatch.source().is_none());
let inner = PipelineError::StepError(Box::new(Error::other("inner")));
assert!(inner.to_string().contains("inner"));
assert!(inner.source().is_some());
}