pi-async-executor 0.1.4

默认执行器的统一时钟与线程通知基础
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
//! 验证具体执行器(executor)的四种队列组合可在同一个程序中工作。

use pi_async_executor::{
    routing::LocalReadySubmit,
    timer::{DefaultTimerItem, LocalTimerSubmit},
    AdmissionRule, AdmissionState, DefaultExecutor, DefaultIdlePolicy, DefaultTimerDriver,
    ExecutorClock, ExecutorOptions, NoHooks, NoIdleQueue, NoTimerQueue, ThreadNotifier,
};
use pi_async_runtime_core::{
    block_on::block_on_root, CloseState, RuntimeControl, RuntimeId, RuntimeQuery, RuntimeStatus,
    TaskConfig,
};
use pi_async_task::{Runnable, TaskError};
use pi_async_task_queue::{
    CancelTimerKey, CancelTimerOptions, ExternalQueueManager, ExternalTaskQueue, MpscIdleTaskQueue,
    MpscQueueOptions, MpscTaskQueue, MpscTaskQueueHandle, QueueCleanupProgress, TimerQueueError,
    TimerSubmitError,
};
use pi_clock_manual::global::GlobalManualInstant;
use std::{
    alloc::{GlobalAlloc, Layout, System},
    cell::Cell,
    future::ready,
    rc::Rc,
    sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed},
    sync::Arc,
    time::Duration,
};

/// 只观察启用区间内当前线程经 system allocator 发出的实际分配请求。
struct ObservedAllocator;

#[global_allocator]
static ALLOCATOR: ObservedAllocator = ObservedAllocator;

thread_local! {
    static PI_ASYNC_EXECUTOR_TEST_ALLOCATIONS: Cell<Option<usize>> = const { Cell::new(None) };
}

// SAFETY: 分配和释放都由 System 使用原布局处理。计数只访问当前线程的固定空间。
unsafe impl GlobalAlloc for ObservedAllocator {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        let _ = PI_ASYNC_EXECUTOR_TEST_ALLOCATIONS.try_with(|current| {
            if let Some(count) = current.get() {
                current.set(Some(count.saturating_add(1)));
            }
        });
        unsafe { System.alloc(layout) }
    }

    unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
        unsafe { System.dealloc(pointer, layout) };
    }
}

/// 普通新任务(Task)全接纳,保持焦点在实际队列推进。
struct AdmitAll;
impl AdmissionRule for AdmitAll {
    fn admits_external(&self, _: &AdmissionState) -> bool {
        true
    }
}

/// 使用原归属回送(return routing)兜底,测试不设置应用的本地绑定。
struct NoLocalBinding;
impl LocalReadySubmit for NoLocalBinding {
    fn try_push_local(_: RuntimeId, task: Runnable) -> Result<(), Runnable> {
        // 这个执行器(executor)未注册本地访问,原归属回送(return routing)接续。
        Err(task)
    }
}
impl LocalTimerSubmit<DefaultTimerItem<TestClock, Self>> for NoLocalBinding {
    fn try_push_local(
        _: RuntimeId,
        _: GlobalManualInstant,
        item: DefaultTimerItem<TestClock, Self>,
    ) -> Result<CancelTimerKey, TimerSubmitError<DefaultTimerItem<TestClock, Self>>> {
        Err(TimerSubmitError {
            item,
            cause: TimerQueueError::WrongOwner,
        })
    }
}

type Timer = DefaultTimerDriver<TestClock, NoLocalBinding>;
type TimedAndIdle =
    DefaultExecutor<TestClock, MpscTaskQueue, MpscIdleTaskQueue, Timer, NoLocalBinding>;
type TimedOnly = DefaultExecutor<TestClock, MpscTaskQueue, NoIdleQueue, Timer, NoLocalBinding>;
type IdleOnly = DefaultExecutor<
    UnusedClock,
    MpscTaskQueue,
    MpscIdleTaskQueue,
    NoTimerQueue<()>,
    NoLocalBinding,
>;
type Neither =
    DefaultExecutor<UnusedClock, MpscTaskQueue, NoIdleQueue, NoTimerQueue<()>, NoLocalBinding>;

/// 为每次构造准备独占的实际外部任务队列(external task queue)。
fn external() -> MpscTaskQueue {
    MpscTaskQueue::new(MpscQueueOptions::default()).unwrap()
}
/// 实际空闲任务队列(idle task queue)提供与默认相同的接收和清理。
fn idle() -> MpscIdleTaskQueue {
    MpscIdleTaskQueue::new(MpscQueueOptions::default()).unwrap()
}
/// 以本次构造给出的身份、时钟和通知句柄建立生产定时驱动。
fn make_timer(
    id: RuntimeId,
    clock: &TestClock,
    notifier: ThreadNotifier,
) -> pi_result::Result<Timer> {
    Timer::new(id, clock.clone(), notifier, CancelTimerOptions::default())
}

/// 用实际定时驱动(default timer driver),通过公开时钟移动同一条时间轴。
#[derive(Clone)]
struct TestClock(Arc<AtomicUsize>);
impl ExecutorClock for TestClock {
    type Instant = GlobalManualInstant;

    fn now(&self) -> pi_result::Result<GlobalManualInstant> {
        GlobalManualInstant::ZERO.try_add(Duration::from_millis(self.0.load(Relaxed) as u64))
    }

    fn checked_add(
        &self,
        now: &Self::Instant,
        duration: Duration,
    ) -> pi_result::Result<Self::Instant> {
        now.try_add(duration)
    }

    fn remaining(
        &self,
        now: &Self::Instant,
        deadline: &Self::Instant,
    ) -> pi_result::Result<Duration> {
        if deadline <= now {
            Ok(Duration::ZERO)
        } else {
            deadline.try_duration_since(*now)
        }
    }
}

/// 没有定时任务队列(timer task queue)的执行器在推进、休眠和关闭时均不得访问时钟。
#[derive(Clone, Copy)]
struct UnusedClock;
impl ExecutorClock for UnusedClock {
    type Instant = ();
    fn now(&self) -> pi_result::Result<()> {
        panic!("省略定时任务队列后不得取时");
    }
    fn checked_add(&self, _: &(), _: Duration) -> pi_result::Result<()> {
        panic!("省略定时任务队列后不得计算截止时间");
    }
    fn remaining(&self, _: &(), _: &()) -> pi_result::Result<Duration> {
        panic!("省略定时任务队列后不得重查截止时间");
    }
}

/// 同一进程交替推进四个执行器(executor),核对原结果、计数和关闭。
#[test]
fn four_queue_combinations_drive_and_close_in_one_process() {
    let clock = TestClock(Arc::new(AtomicUsize::new(0)));
    let options = ExecutorOptions::default();
    let mut both =
        TimedAndIdle::with_queues(clock.clone(), external(), idle(), options, make_timer).unwrap();
    let mut timed =
        TimedOnly::with_queues(clock.clone(), external(), NoIdleQueue, options, make_timer)
            .unwrap();
    let mut idle_only = IdleOnly::with_queues(
        UnusedClock,
        external(),
        idle(),
        options,
        NoTimerQueue::default(),
    )
    .unwrap();
    let mut neither = Neither::with_queue_factories(
        UnusedClock,
        external(),
        NoIdleQueue,
        |context| Ok(context.task_queue()),
        options,
        NoTimerQueue::default(),
    )
    .unwrap();

    let both_handle = both.handle();
    let timed_handle = timed.handle();
    let idle_handle = idle_only.handle();
    let neither_handle = neither.handle();
    let (both_idle_task, both_idle_result) = both_handle
        .create(ready(11), TaskConfig::<()>::default())
        .unwrap();
    both_handle.submit_idle(both_idle_task).unwrap();
    let (idle_only_task, idle_only_result) = idle_handle
        .create(ready(22), TaskConfig::<()>::default())
        .unwrap();
    idle_handle.submit_idle(idle_only_task).unwrap();
    let (ordinary, ordinary_result) = neither_handle
        .create(ready(33), TaskConfig::<()>::default())
        .unwrap();
    neither_handle.submit(ordinary).unwrap();
    let both_timed_result = both_handle
        .spawn_timing(ready(44), Duration::ZERO, TaskConfig::<()>::default())
        .unwrap();
    let timed_result = timed_handle
        .spawn_timing(ready(55), Duration::ZERO, TaskConfig::<()>::default())
        .unwrap();

    assert_eq!(both_handle.timer_registration_count(), 1);
    assert_eq!(timed_handle.timer_registration_count(), 1);
    assert_eq!(both_handle.idle_task_count(), 1);
    assert_eq!(idle_handle.idle_task_count(), 1);
    assert_eq!(timed_handle.idle_task_count(), 0);
    assert_eq!(idle_handle.timer_registration_count(), 0);
    assert_eq!(neither_handle.timer_registration_count(), 0);
    assert_eq!(neither_handle.idle_task_count(), 0);

    clock.0.store(1000, Relaxed);
    for _ in 0..8 {
        both.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
            .unwrap();
        timed
            .run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
            .unwrap();
        idle_only
            .run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
            .unwrap();
        neither
            .run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
            .unwrap();
    }
    // 再持一次真实推进权验证休眠(park_with_lease)时也无需取时。
    let mut lease = neither.begin_drive();
    let last = neither
        .turn_with_lease(&mut lease, &AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
        .unwrap();
    assert!(last.sleep_for.is_some());
    assert!(!last.immediate_work);
    neither
        .park_with_lease(&mut lease, &AdmitAll, &last, None)
        .unwrap();
    drop(lease);

    // 先核对应任务已结束,避免错误的推进导致测试无期限等结果。
    assert_eq!(both_handle.in_flight_task_count(), 0);
    assert_eq!(timed_handle.in_flight_task_count(), 0);
    assert_eq!(idle_handle.in_flight_task_count(), 0);
    assert_eq!(neither_handle.in_flight_task_count(), 0);
    assert_eq!(both_handle.timer_registration_count(), 0);
    assert_eq!(timed_handle.timer_registration_count(), 0);
    assert_eq!(both_handle.idle_task_count(), 0);
    assert_eq!(idle_handle.idle_task_count(), 0);
    assert_eq!(neither_handle.external_task_count(), 0);
    assert_eq!(block_on_root(both_idle_result).unwrap(), 11);
    assert_eq!(block_on_root(idle_only_result).unwrap(), 22);
    assert_eq!(block_on_root(ordinary_result).unwrap(), 33);
    assert_eq!(block_on_root(both_timed_result).unwrap(), 44);
    assert_eq!(block_on_root(timed_result).unwrap(), 55);

    both_handle.request_close();
    timed_handle.request_close();
    idle_handle.request_close();
    neither_handle.request_close();
    assert!(
        both.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
            .unwrap()
            .service_closed
    );
    assert!(
        timed
            .run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
            .unwrap()
            .service_closed
    );
    assert!(
        idle_only
            .run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
            .unwrap()
            .service_closed
    );
    assert!(
        neither
            .run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
            .unwrap()
            .service_closed
    );
    assert_eq!(both_handle.close_state(), CloseState::Completed);
    assert_eq!(timed_handle.close_state(), CloseState::Completed);
    assert_eq!(idle_handle.close_state(), CloseState::Completed);
    assert_eq!(neither_handle.close_state(), CloseState::Completed);
}

/// 两项都省略时保留正常析构(drop)责任,外部原任务释放一次。
#[test]
fn dropping_executor_without_optional_queues_cleans_pending_ordinary_tasks() {
    struct CountDrop(Arc<AtomicUsize>);
    impl Drop for CountDrop {
        fn drop(&mut self) {
            self.0.fetch_add(1, Relaxed);
        }
    }

    let executor = Neither::with_queues(
        UnusedClock,
        external(),
        NoIdleQueue,
        ExecutorOptions::default(),
        NoTimerQueue::default(),
    )
    .unwrap();
    let handle = executor.handle();
    let drops = Arc::new(AtomicUsize::new(0));
    let ownership = CountDrop(Arc::clone(&drops));
    let (task, _result) = handle
        .create(async move { drop(ownership) }, TaskConfig::<()>::default())
        .unwrap();
    handle.submit(task).unwrap();
    drop(executor);
    assert_eq!(drops.load(Relaxed), 1);
    assert_eq!(handle.status(), RuntimeStatus::Closed);
    assert_eq!(handle.close_state(), CloseState::Completed);
    assert_eq!(handle.external_task_count(), 0);
}

/// 通过真实推进(drive)验证默认外部任务队列单项交接的分配及多项原顺序。
#[test]
fn single_external_import_does_not_allocate_a_batch() {
    let mut executor = Neither::with_queues(
        UnusedClock,
        external(),
        NoIdleQueue,
        ExecutorOptions::default(),
        NoTimerQueue::default(),
    )
    .unwrap();
    let handle = executor.handle();
    // 先正常推进一次。下一轮验证已取消但仍在外部队列的原任务真实取出和清理。
    // 它不建立新的业务接纳登记,使分配(allocation)观察不计入另有用途的登记空间。
    let (warm, warmed) = handle.create(ready(1), TaskConfig::<()>::default()).unwrap();
    handle.submit(warm).unwrap();
    executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks).unwrap();
    assert_eq!(block_on_root(warmed).unwrap(), 1);

    let polls = Arc::new(AtomicUsize::new(0));
    let observed = Arc::clone(&polls);
    let (single, result) = handle
        .create(async move { observed.fetch_add(1, Relaxed) }, TaskConfig::<()>::default())
        .unwrap();
    handle.submit(single).unwrap();
    result.control_handle().cancel();
    assert_eq!(handle.external_task_count(), 1);
    PI_ASYNC_EXECUTOR_TEST_ALLOCATIONS.with(|count| count.set(Some(0)));
    let turn = executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks);
    let allocations = PI_ASYNC_EXECUTOR_TEST_ALLOCATIONS.with(|count| count.take().unwrap());
    turn.unwrap();
    assert_eq!(handle.external_task_count(), 0);
    assert_eq!(handle.in_flight_task_count(), 0);
    assert_eq!(polls.load(Relaxed), 0);
    assert!(matches!(block_on_root(result), Err(TaskError::Cancelled)));
    assert_eq!(allocations, 0);

    let order = Arc::new(AtomicUsize::new(0));
    let mut results = Vec::with_capacity(2);
    for _ in 0..2 {
        let order = Arc::clone(&order);
        let (task, result) = handle
            .create(async move { order.fetch_add(1, Relaxed) }, TaskConfig::<()>::default())
            .unwrap();
        handle.submit(task).unwrap();
        results.push(result);
    }
    assert_eq!(handle.external_task_count(), 2);
    executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks).unwrap();
    // 同一次普通取出移交完整批次,每轮仍只执行一个就绪任务。
    assert_eq!(handle.external_task_count(), 0);
    assert_eq!(order.load(Relaxed), 1);
    executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks).unwrap();
    assert_eq!(order.load(Relaxed), 2);
    for (expected, result) in results.into_iter().enumerate() {
        assert_eq!(block_on_root(result).unwrap(), expected);
    }
    // 下一轮维护收回最后一项已退役的任务登记。
    executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks).unwrap();
    assert_eq!(handle.in_flight_task_count(), 0);
}

// 原外部管理者先停收。结清依赖同一执行器(executor)已接纳任务的析构(drop)。
struct ExternalCloseAfterTaskExit {
    queue: MpscTaskQueue,
    task_exited: Arc<AtomicBool>,
    close_attempts: Arc<AtomicUsize>,
    final_error: Option<pi_result::Error>,
}

impl ExternalQueueManager for ExternalCloseAfterTaskExit {
    type Handle = MpscTaskQueueHandle;

    fn handle(&self) -> Self::Handle {
        self.queue.handle()
    }

    fn clear(&mut self) -> pi_result::Result<QueueCleanupProgress> {
        self.queue.clear()
    }

    fn close(&mut self) -> pi_result::Result<QueueCleanupProgress> {
        self.close_attempts.fetch_add(1, Relaxed);
        let progress = self.queue.close()?;
        if !self.task_exited.load(Relaxed) || matches!(progress, QueueCleanupProgress::MoreWork) {
            return Ok(QueueCleanupProgress::MoreWork);
        }
        match self.final_error.take() {
            Some(error) => Err(error),
            None => Ok(QueueCleanupProgress::Complete),
        }
    }
}

/// 实际关闭需接续原外部管理者,并把它最终给出的错误报告交回调用方。
#[test]
fn close_revisits_external_source_after_local_task_exits() {
    assert_external_close_after_task_exit(ExternalCloseCall::Direct);
}

/// 尚有所属域(owner domain)借用时,下一次推进继续调用原外部管理者。
#[test]
fn close_keeps_pending_external_source_across_owner_borrow() {
    assert_external_close_after_task_exit(ExternalCloseCall::AfterBorrow);
}

/// 后续确实清理完成,已报告的未确认状态保持原规则。
#[test]
fn close_can_finish_source_after_reporting_unconfirmed() {
    assert_external_close_after_task_exit(ExternalCloseCall::SuccessAfterBorrow);
}

/// 归还所属域借用后直接释放执行器,仍由同一外部管理者接续关闭。
#[test]
fn drop_finishes_the_pending_external_source_after_owner_borrow() {
    assert_external_close_after_task_exit(ExternalCloseCall::DropAfterBorrow);
}

enum ExternalCloseCall {
    Direct,
    AfterBorrow,
    DropAfterBorrow,
    SuccessAfterBorrow,
}

fn assert_external_close_after_task_exit(call: ExternalCloseCall) {
    struct SetOnExit(Arc<AtomicBool>);
    impl Drop for SetOnExit {
        fn drop(&mut self) {
            self.0.store(true, Relaxed);
        }
    }

    let task_exited = Arc::new(AtomicBool::new(false));
    let close_attempts = Arc::new(AtomicUsize::new(0));
    let reports_error = !matches!(call, ExternalCloseCall::SuccessAfterBorrow);
    let queue = ExternalCloseAfterTaskExit {
        queue: external(),
        task_exited: Arc::clone(&task_exited),
        close_attempts: Arc::clone(&close_attempts),
        final_error: reports_error.then(|| pi_result::Error::new(pi_result::ErrorKind::Unsupported)
            .attach("外部任务退出后的原关闭错误")),
    };
    let mut executor = DefaultExecutor::<_, _, _, _, NoLocalBinding>::with_queues(
        UnusedClock,
        queue,
        NoIdleQueue,
        ExecutorOptions::default(),
        NoTimerQueue::default(),
    )
    .unwrap();
    let handle = executor.handle();
    let exit = SetOnExit(Arc::clone(&task_exited));
    let (task, result) = handle
        .create(
            async move {
                let _exit = exit;
                std::future::pending::<()>().await
            },
            TaskConfig::<()>::default(),
        )
        .unwrap();
    handle.submit(task).unwrap();
    assert_eq!(executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks).unwrap().runs, 1);
    assert_eq!(handle.in_flight_task_count(), 1);
    assert!(!task_exited.load(Relaxed));

    handle.request_close();
    if !matches!(call, ExternalCloseCall::Direct) {
        let local = Rc::clone(executor.local());
        local
            .with_owner(|_| {
                for _ in 0..2 {
                    let error = executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
                        .expect_err("借用归还前无法确认关闭");
                    assert_eq!(error.current_context(), &pi_result::ErrorKind::InvalidState);
                    assert_eq!(handle.status(), RuntimeStatus::Closing);
                    assert_eq!(close_attempts.load(Relaxed), 1);
                    assert!(!task_exited.load(Relaxed));
                }
            })
            .unwrap();
        assert!(task_exited.load(Relaxed));
        assert_eq!(close_attempts.load(Relaxed), 1);
    }
    if matches!(call, ExternalCloseCall::DropAfterBorrow) {
        drop(executor);
    } else {
        let turn = executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks);
        if reports_error {
            let error = turn.expect_err("必须取得来源实际关闭错误");
            assert_eq!(error.current_context(), &pi_result::ErrorKind::Unsupported);
            assert_eq!(error.downcast_ref::<&'static str>(), Some(&"外部任务退出后的原关闭错误"));
        } else {
            assert!(turn.expect("来源后来确实完成清理").service_closed);
        }
    }
    assert!(task_exited.load(Relaxed));
    assert!(matches!(block_on_root(result), Err(TaskError::Cancelled)));
    assert_eq!(close_attempts.load(Relaxed), 2);
    assert_eq!(handle.status(), RuntimeStatus::Closed);
    assert_eq!(handle.close_state(), CloseState::Requested);
}

/// 原 MPSC 清理额度为一时,关闭继续到真实结束才公布 Completed。
#[test]
fn close_drains_a_bounded_external_source_before_reporting_complete() {
    let queue = MpscTaskQueue::new(MpscQueueOptions {
        cleanup_batch_size: std::num::NonZeroUsize::MIN,
        ..MpscQueueOptions::default()
    })
    .unwrap();
    let mut executor = Neither::with_queues(
        UnusedClock,
        queue,
        NoIdleQueue,
        ExecutorOptions::default(),
        NoTimerQueue::default(),
    )
    .unwrap();
    let handle = executor.handle();
    let mut results = Vec::new();
    for value in 0..3 {
        let (task, result) = handle.create(ready(value), TaskConfig::<()>::default()).unwrap();
        handle.submit(task).unwrap();
        results.push(result);
    }
    assert_eq!(handle.external_task_count(), 3);
    handle.request_close();
    let closed = executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks).unwrap();
    assert!(closed.service_closed);
    assert_eq!(closed.runs, 0);
    assert_eq!(handle.external_task_count(), 0);
    assert_eq!(handle.status(), RuntimeStatus::Closed);
    assert_eq!(handle.close_state(), CloseState::Completed);
    for result in results {
        assert!(matches!(block_on_root(result), Err(TaskError::Abandoned)));
    }
}

/// 关闭越过先前开放清理的终点(endpoint)时,后到的原值仍须由相同管理者清理。
#[test]
fn close_drains_tasks_after_a_pending_external_clear_endpoint() {
    struct NeverSchedule;
    impl pi_async_task::Schedule for NeverSchedule {
        fn schedule(&self, _: Runnable) {
            panic!("关闭只能清理原任务");
        }
    }

    let mut queue = MpscTaskQueue::new(MpscQueueOptions {
        cleanup_batch_size: std::num::NonZeroUsize::MIN,
        ..MpscQueueOptions::default()
    }).unwrap();
    let queue_handle = queue.handle();
    let mut results = Vec::new();
    for value in 0..3 {
        if value == 2 {
            assert!(matches!(queue.clear().unwrap(), QueueCleanupProgress::MoreWork));
            assert_eq!(queue_handle.len(), 1);
        }
        let task = pi_async_task::create(
            ready(value), NeverSchedule, (), pi_async_task::TaskOptions::intrusive_mpsc(),
        ).unwrap_or_else(|_| panic!("原任务应可创建"));
        queue_handle.try_push(task.runnable).unwrap_or_else(|_| panic!("原任务应可入队"));
        results.push(task.join);
    }
    let mut executor = Neither::with_queues(
        UnusedClock, queue, NoIdleQueue, ExecutorOptions::default(), NoTimerQueue::default(),
    ).unwrap();
    let handle = executor.handle();
    assert_eq!(handle.external_task_count(), 2);
    handle.request_close();
    let report = executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks).unwrap();
    assert!(report.service_closed);
    assert_eq!(handle.close_state(), CloseState::Completed);
    assert_eq!(queue_handle.len(), 0);
    for result in results {
        assert!(matches!(block_on_root(result), Err(TaskError::Abandoned)));
    }
}