qubit-batch 0.4.0

One-shot batch execution and processing with sequential and scoped parallel utilities
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
/*******************************************************************************
 *
 *    Copyright (c) 2025 - 2026 Haixing Hu.
 *
 *    SPDX-License-Identifier: Apache-2.0
 *
 *    Licensed under the Apache License, Version 2.0.
 *
 ******************************************************************************/
//! Tests for [`ParallelBatchExecutor`](qubit_batch::ParallelBatchExecutor).

use std::{
    fmt,
    panic::{
        AssertUnwindSafe,
        catch_unwind,
    },
    sync::Arc,
    thread,
    time::Duration,
};

use qubit_atomic::{
    ArcAtomic,
    ArcAtomicCount,
    AtomicCount,
};
use qubit_batch::{
    BatchExecutionError,
    BatchExecutor,
    ParallelBatchExecutor,
    ParallelBatchExecutorBuildError,
};
use qubit_function::Runnable;

use crate::support::{
    PanickingProgressReporter,
    ProgressEvent,
    ProgressPanicPhase,
    RecordingProgressReporter,
    TestTask,
    panic_payload_message,
};

#[test]
fn test_parallel_batch_executor_builds_default_and_custom_config() {
    let default_executor = ParallelBatchExecutor::default();
    assert_eq!(
        default_executor.thread_count(),
        ParallelBatchExecutor::default_thread_count()
    );
    assert_eq!(
        default_executor.sequential_threshold(),
        ParallelBatchExecutor::DEFAULT_SEQUENTIAL_THRESHOLD
    );
    let new_executor = ParallelBatchExecutor::new(2).expect("executor should build");
    assert_eq!(new_executor.thread_count(), 2);

    let executor = ParallelBatchExecutor::builder()
        .thread_count(3)
        .sequential_threshold(2)
        .report_interval(Duration::from_millis(25))
        .build()
        .expect("custom executor should build");

    assert_eq!(executor.thread_count(), 3);
    assert_eq!(executor.sequential_threshold(), 2);
    assert_eq!(executor.report_interval(), Duration::from_millis(25));
    assert!(Arc::strong_count(executor.reporter()) >= 1);
}

#[test]
fn test_parallel_batch_executor_rejects_invalid_builder_config() {
    assert!(matches!(
        ParallelBatchExecutor::builder().thread_count(0).build(),
        Err(ParallelBatchExecutorBuildError::ZeroThreadCount)
    ));
}

#[test]
fn test_parallel_batch_executor_executes_with_configured_parallelism() {
    let executor = ParallelBatchExecutor::builder()
        .thread_count(2)
        .sequential_threshold(1)
        .build()
        .expect("parallel executor should build");
    let active_count = ArcAtomicCount::zero();
    let max_active_count = ArcAtomic::new(0usize);
    let tasks = (0..6)
        .map(|_| {
            ActiveTrackingTask::new(
                active_count.clone(),
                max_active_count.clone(),
                Duration::from_millis(20),
            )
        })
        .collect::<Vec<_>>();

    let result = executor
        .execute(tasks, 6)
        .expect("parallel batch should succeed");

    assert_eq!(result.completed_count(), 6);
    assert_eq!(result.succeeded_count(), 6);
    assert_eq!(result.failure_count(), 0);
    assert!(max_active_count.load() > 1);
    assert!(max_active_count.load() <= 2);
}

#[test]
fn test_parallel_batch_executor_uses_sequential_threshold() {
    let executor = ParallelBatchExecutor::builder()
        .thread_count(4)
        .sequential_threshold(8)
        .build()
        .expect("parallel executor should build");
    let active_count = ArcAtomicCount::zero();
    let max_active_count = ArcAtomic::new(0usize);
    let tasks = (0..4)
        .map(|_| {
            ActiveTrackingTask::new(
                active_count.clone(),
                max_active_count.clone(),
                Duration::from_millis(1),
            )
        })
        .collect::<Vec<_>>();

    let result = executor
        .execute(tasks, 4)
        .expect("threshold fallback should succeed");

    assert_eq!(result.completed_count(), 4);
    assert_eq!(max_active_count.load(), 1);
}

#[test]
fn test_parallel_batch_executor_supports_non_static_tasks() {
    let executor = ParallelBatchExecutor::builder()
        .thread_count(2)
        .sequential_threshold(1)
        .build()
        .expect("parallel executor should build");
    let first = AtomicCount::zero();
    let second = AtomicCount::zero();
    let tasks = vec![
        BorrowingTask { counter: &first },
        BorrowingTask { counter: &second },
    ];

    let result = executor
        .execute(tasks, 2)
        .expect("borrowed tasks should execute");

    assert_eq!(result.succeeded_count(), 2);
    assert_eq!(first.get(), 1);
    assert_eq!(second.get(), 1);
}

#[test]
fn test_parallel_batch_executor_collects_failures_and_panics() {
    let executor = ParallelBatchExecutor::builder()
        .thread_count(2)
        .sequential_threshold(1)
        .build()
        .expect("parallel executor should build");
    let tasks = vec![
        TestTask::succeed(),
        TestTask::fail("failed"),
        TestTask::panic("panic in parallel batch"),
    ];

    let result = executor
        .execute(tasks, 3)
        .expect("task failures should stay in the batch result");

    assert_eq!(result.completed_count(), 3);
    assert_eq!(result.succeeded_count(), 1);
    assert_eq!(result.failed_count(), 1);
    assert_eq!(result.panicked_count(), 1);
    assert_eq!(result.failures().len(), 2);
    assert_eq!(result.failures()[0].index(), 1);
    assert_eq!(result.failures()[1].index(), 2);
    assert_eq!(
        result.failures()[1].error().panic_message(),
        Some("panic in parallel batch")
    );
}

#[test]
fn test_parallel_batch_executor_reports_count_shortfall() {
    let executor = ParallelBatchExecutor::builder()
        .thread_count(2)
        .sequential_threshold(1)
        .build()
        .expect("parallel executor should build");
    let tasks = vec![TestTask::succeed(), TestTask::succeed()];

    let error = executor
        .execute(tasks, 3)
        .expect_err("shortfall should be reported");

    match error {
        BatchExecutionError::CountShortfall {
            expected,
            actual,
            outcome,
        } => {
            assert_eq!(expected, 3);
            assert_eq!(actual, 2);
            assert_eq!(outcome.completed_count(), 2);
        }
        other => panic!("unexpected error: {other:?}"),
    }
}

#[test]
fn test_parallel_batch_executor_reports_count_exceeded() {
    let executor = ParallelBatchExecutor::builder()
        .thread_count(2)
        .sequential_threshold(1)
        .build()
        .expect("parallel executor should build");
    let tasks = vec![
        TestTask::succeed(),
        TestTask::succeed(),
        TestTask::succeed(),
    ];

    let error = executor
        .execute(tasks, 2)
        .expect_err("overflow should be reported");

    match error {
        BatchExecutionError::CountExceeded {
            expected,
            observed_at_least,
            outcome,
        } => {
            assert_eq!(expected, 2);
            assert_eq!(observed_at_least, 3);
            assert_eq!(outcome.completed_count(), 2);
        }
        other => panic!("unexpected error: {other:?}"),
    }
}

#[test]
fn test_parallel_batch_executor_reports_progress() {
    let reporter = Arc::new(RecordingProgressReporter::new());
    let executor = ParallelBatchExecutor::builder()
        .thread_count(2)
        .sequential_threshold(1)
        .reporter_arc(reporter.clone())
        .report_interval(Duration::from_millis(10))
        .build()
        .expect("parallel executor should build");
    let tasks = vec![
        TestTask::sleep_success(Duration::from_millis(20)),
        TestTask::sleep_success(Duration::from_millis(20)),
        TestTask::sleep_success(Duration::from_millis(20)),
    ];

    let result = executor
        .execute(tasks, 3)
        .expect("parallel batch should succeed");
    let events = reporter.events();

    assert_eq!(result.completed_count(), 3);
    assert!(matches!(
        events.first(),
        Some(ProgressEvent::Start { total_count: 3 })
    ));
    assert!(events.iter().any(|event| matches!(
        event,
        ProgressEvent::Process {
            total_count: 3,
            active_count,
            completed_count,
        } if *active_count > 0 || *completed_count > 0
    )));
    assert!(matches!(
        events.last(),
        Some(ProgressEvent::Finish { total_count: 3, .. })
    ));
}

#[test]
fn test_parallel_batch_executor_reports_progress_with_zero_interval() {
    let reporter = Arc::new(RecordingProgressReporter::new());
    let executor = ParallelBatchExecutor::builder()
        .thread_count(2)
        .sequential_threshold(0)
        .reporter_arc(reporter.clone())
        .report_interval(Duration::ZERO)
        .build()
        .expect("zero report interval should build");
    let tasks = vec![
        TestTask::succeed(),
        TestTask::succeed(),
        TestTask::succeed(),
    ];

    let result = executor
        .execute(tasks, 3)
        .expect("parallel batch should succeed");
    let events = reporter.events();

    assert_eq!(result.completed_count(), 3);
    assert!(events.iter().any(|event| matches!(
        event,
        ProgressEvent::Process {
            total_count: 3,
            completed_count,
            ..
        } if *completed_count >= 1
    )));
}

#[test]
fn test_parallel_batch_executor_propagates_progress_reporter_finish_panic() {
    const PANIC_MESSAGE: &str = "parallel progress finish panic";
    let executor = ParallelBatchExecutor::builder()
        .thread_count(2)
        .sequential_threshold(0)
        .reporter(PanickingProgressReporter::new(
            ProgressPanicPhase::Finish,
            PANIC_MESSAGE,
        ))
        .build()
        .expect("parallel executor should build");
    let tasks = vec![TestTask::succeed()];

    let payload = catch_unwind(AssertUnwindSafe(|| executor.execute(tasks, 1)))
        .expect_err("progress reporter finish panic should be propagated");

    assert_eq!(panic_payload_message(payload.as_ref()), Some(PANIC_MESSAGE));
}

#[test]
fn test_parallel_batch_executor_propagates_progress_reporter_process_panic() {
    const PANIC_MESSAGE: &str = "parallel progress process panic";
    let executor = ParallelBatchExecutor::builder()
        .thread_count(2)
        .sequential_threshold(1)
        .report_interval(Duration::from_millis(1))
        .reporter(PanickingProgressReporter::new(
            ProgressPanicPhase::Process,
            PANIC_MESSAGE,
        ))
        .build()
        .expect("parallel executor should build");
    let tasks = vec![
        TestTask::sleep_success(Duration::from_millis(50)),
        TestTask::sleep_success(Duration::from_millis(50)),
    ];

    let payload = catch_unwind(AssertUnwindSafe(|| executor.execute(tasks, 2)))
        .expect_err("progress reporter process panic should be propagated");

    assert_eq!(panic_payload_message(payload.as_ref()), Some(PANIC_MESSAGE));
}

/// Task that records the maximum number of concurrently active tasks.
#[derive(Debug)]
struct ActiveTrackingTask {
    /// Shared count of currently running tasks.
    active_count: ArcAtomicCount,
    /// Shared maximum active count observed by any task.
    max_active_count: ArcAtomic<usize>,
    /// Time to keep the task active.
    duration: Duration,
}

impl ActiveTrackingTask {
    /// Creates an active-tracking task.
    ///
    /// # Parameters
    ///
    /// * `active_count` - Shared active counter.
    /// * `max_active_count` - Shared maximum active counter.
    /// * `duration` - Time to keep the task active.
    ///
    /// # Returns
    ///
    /// A task configured with the supplied counters.
    fn new(
        active_count: ArcAtomicCount,
        max_active_count: ArcAtomic<usize>,
        duration: Duration,
    ) -> Self {
        Self {
            active_count,
            max_active_count,
            duration,
        }
    }
}

impl Runnable<&'static str> for ActiveTrackingTask {
    /// Runs this task while updating active counters.
    ///
    /// # Returns
    ///
    /// Always returns `Ok(())`.
    fn run(&mut self) -> Result<(), &'static str> {
        let active = self.active_count.inc();
        self.max_active_count.fetch_max(active);
        thread::sleep(self.duration);
        self.active_count.dec();
        Ok(())
    }
}

/// Task that borrows a counter from the caller's stack.
struct BorrowingTask<'a> {
    /// Borrowed counter incremented by this task.
    counter: &'a AtomicCount,
}

impl fmt::Debug for BorrowingTask<'_> {
    /// Formats this task for failed test output.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.debug_struct("BorrowingTask").finish()
    }
}

impl Runnable<&'static str> for BorrowingTask<'_> {
    /// Increments the borrowed counter.
    ///
    /// # Returns
    ///
    /// Always returns `Ok(())`.
    fn run(&mut self) -> Result<(), &'static str> {
        self.counter.inc();
        Ok(())
    }
}