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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
//! 用公开构造、提交和推进入口验证内部任务队列(internal task queue)的接管和关闭(close)。
//! 测试在所属线程(owner thread)同步推进,使用真实任务、时钟(clock)及普通、定时和空闲来源。

use pi_async_executor::{
    routing::LocalReadySubmit,
    timer::{DefaultTimerItem, LocalTimerSubmit},
    AdmissionRule, AdmissionState, DefaultExecutor, DefaultIdlePolicy, DefaultTimerDriver,
    ExecutorLocal, ExecutorOptions, ManualClock, NoHooks, ThreadNotifier, TurnResult,
};
use pi_async_runtime_core::{
    context::record::{bind_current, try_with_local_for},
    CloseRequestStatus, CloseState, RuntimeControl, RuntimeId, RuntimeQuery, RuntimeStatus,
    TaskConfig, TaskError,
};
use pi_async_task::{
    create, definitions::TaskOwnerId, Runnable, Schedule, TaskOptions, TaskThread,
};
use pi_async_task_queue::{
    CancelTimerKey, CancelTimerOptions, IdleQueueManager, InternalTaskQueue, MpscIdleTaskQueue,
    MpscIdleTaskQueueHandle, MpscQueueOptions, MpscTaskQueue, QueueCleanupProgress, QueuePushError,
    QueuePushErrorKind, TaskQueue, TimerQueueError, TimerSubmitError,
};
use pi_clock_manual::global::{self, GlobalManualInstant};
use pi_result::{Error, ErrorKind};
use std::{
    cell::{Cell, RefCell},
    collections::VecDeque,
    future::{pending, poll_fn, ready, Future},
    ops::Deref,
    panic::{catch_unwind, panic_any, AssertUnwindSafe},
    rc::Rc,
    sync::Arc,
    task::{Context, Poll, Waker},
};

type Timer = DefaultTimerDriver<ManualClock, SharedOnly>;
type Executor<Q, I = MpscIdleTaskQueue, L = SharedOnly> =
    DefaultExecutor<ManualClock, MpscTaskQueue, I, Timer, L, Q>;

/// 夹具不注册运行时(runtime)本地权限;原唤醒和定时值仍可经既有共享来源接续。
struct SharedOnly;

impl LocalReadySubmit for SharedOnly {
    fn try_push_local(_: RuntimeId, task: Runnable) -> Result<(), Runnable> {
        Err(task)
    }
}

impl LocalTimerSubmit<DefaultTimerItem<ManualClock, Self>> for SharedOnly {
    fn try_push_local(
        _: RuntimeId,
        _: GlobalManualInstant,
        item: DefaultTimerItem<ManualClock, Self>,
    ) -> Result<CancelTimerKey, TimerSubmitError<DefaultTimerItem<ManualClock, Self>>> {
        Err(TimerSubmitError {
            item,
            cause: TimerQueueError::WrongOwner,
        })
    }
}

/// 通过实际本地权限尾插原任务(Task);无本地权限时由生产归属回送(return routing)接手。
struct LocalWake;

impl LocalReadySubmit for LocalWake {
    fn try_push_local(runtime: RuntimeId, task: Runnable) -> Result<(), Runnable> {
        let mut pending = Some(task);
        let result = try_with_local_for::<
            ExecutorLocal<Timer, TestInternalQueue<Rc<Observations>>>,
            _,
        >(runtime, |local| {
            local
                .try_push(pending.take().unwrap(), false)
                .map_err(|error| error.task)
        });
        match result {
            Ok(outcome) => outcome,
            Err(_) => Err(pending.take().unwrap()),
        }
    }
}

/// 使用普通并发接纳(admission),让原提交和关闭都通过单轮推进。
struct Admit;

impl AdmissionRule for Admit {
    fn admits_external(&self, _: &AdmissionState) -> bool {
        true
    }
}

/// 构造失败测试中的未入队任务从未被轮询(poll),若被调度仍按原责任释放。
struct ReleaseOnWake;

impl Schedule for ReleaseOnWake {
    fn schedule(&self, task: Runnable) {
        drop(task);
    }
}

/// 准备真实的默认来源;定时驱动(default timer driver)只用本次构造提供的时钟和通知句柄。
fn sources() -> (ManualClock, MpscTaskQueue, MpscIdleTaskQueue) {
    let _ = global::try_init();
    (
        ManualClock::new().unwrap(),
        MpscTaskQueue::new(MpscQueueOptions::default()).unwrap(),
        MpscIdleTaskQueue::new(MpscQueueOptions::default()).unwrap(),
    )
}

/// 使用生产定时驱动(default timer driver),保持构造入口给出的身份和时间轴。
fn make_timer(
    id: RuntimeId,
    clock: &ManualClock,
    notifier: ThreadNotifier,
) -> pi_result::Result<Timer> {
    Timer::new(id, *clock, notifier, CancelTimerOptions::default())
}

/// 记录普通入队和关闭(close)。析构(drop)释放原值后读取计数,核对该计数仍由执行器(executor)保管。
#[derive(Default)]
struct Observations {
    pushes: Cell<usize>,
    close_calls: Cell<usize>,
    drops: Cell<usize>,
    remaining_on_drop: Cell<usize>,
    count_on_drop: Cell<Option<usize>>,
    read_count: RefCell<Option<Box<dyn FnOnce() -> usize>>>,
}

/// 自定义队列实际执行结束、留余项、返回原报告或展开(unwinding)。
enum CloseOutcome {
    Complete,
    MoreWork,
    Error(Error),
    Panic,
}

const CLOSE_PANIC: &str = "内部任务队列(internal task queue)关闭的原载荷";
const DROP_PANIC: &str = "内部任务队列(internal task queue)析构的原载荷";

/// 保管真实可执行句柄(Runnable),以观察记录核对原任务和值的释放。
struct TestInternalQueue<P: Deref<Target = Observations>> {
    tasks: VecDeque<Runnable>,
    owner: Option<TaskOwnerId>,
    closed: bool,
    outcome: CloseOutcome,
    panic_on_drop: bool,
    observations: P,
}

impl<P: Deref<Target = Observations>> TestInternalQueue<P> {
    /// 初始为空且开放,按各测试给出的真实进度处理首次关闭。
    fn new(observations: P, outcome: CloseOutcome) -> Self {
        Self {
            tasks: VecDeque::new(),
            owner: None,
            closed: false,
            outcome,
            panic_on_drop: false,
            observations,
        }
    }

    /// 查询原状态,拒绝时返还同一个可执行句柄(Runnable)。
    fn check_push(&self, task: Runnable) -> Result<Runnable, QueuePushError> {
        if self.closed {
            return Err(QueuePushError {
                task,
                cause: QueuePushErrorKind::Closed,
            });
        }
        if self
            .owner
            .is_some_and(|owner| task.snapshot().owner != Some(owner))
        {
            return Err(QueuePushError {
                task,
                cause: QueuePushErrorKind::WrongOwner,
            });
        }
        Ok(task)
    }
}

impl<P: Deref<Target = Observations>> InternalTaskQueue for TestInternalQueue<P> {
    fn try_push_internal_front(&mut self, task: Runnable) -> Result<(), QueuePushError> {
        let task = self.check_push(task)?;
        self.tasks.push_front(task);
        self.observations
            .pushes
            .set(self.observations.pushes.get() + 1);
        Ok(())
    }

    fn try_push_internal_back(&mut self, task: Runnable) -> Result<(), QueuePushError> {
        let task = self.check_push(task)?;
        self.tasks.push_back(task);
        self.observations
            .pushes
            .set(self.observations.pushes.get() + 1);
        Ok(())
    }

    fn pop_internal_front(&mut self) -> Option<Runnable> {
        self.tasks.pop_front()
    }

    fn internal_len(&self) -> usize {
        self.tasks.len()
    }

    fn internal_owner_id(&self) -> Option<TaskOwnerId> {
        self.owner
    }

    fn is_internal_closed(&self) -> bool {
        self.closed
    }

    fn clear_internal(&mut self) -> pi_result::Result<QueueCleanupProgress> {
        self.tasks.clear();
        Ok(QueueCleanupProgress::Complete)
    }

    fn close_internal(&mut self) -> pi_result::Result<QueueCleanupProgress> {
        self.observations
            .close_calls
            .set(self.observations.close_calls.get() + 1);
        self.closed = true;
        match std::mem::replace(&mut self.outcome, CloseOutcome::Complete) {
            CloseOutcome::Complete => self.clear_internal(),
            CloseOutcome::MoreWork => Ok(QueueCleanupProgress::MoreWork),
            CloseOutcome::Error(report) => Err(report),
            CloseOutcome::Panic => panic_any(CLOSE_PANIC),
        }
    }
}

impl<P: Deref<Target = Observations>> Drop for TestInternalQueue<P> {
    fn drop(&mut self) {
        let observations = &*self.observations;
        observations.drops.set(observations.drops.get() + 1);
        observations.remaining_on_drop.set(self.tasks.len());
        self.tasks.clear();
        if let Some(read_count) = observations.read_count.borrow_mut().take() {
            observations.count_on_drop.set(Some(read_count()));
        }
        if self.panic_on_drop {
            panic_any(DROP_PANIC);
        }
    }
}

/// 通过按值入口绑定没有预绑定的自定义队列,调用者可在原线程提交和推进任务。
fn build<P: Deref<Target = Observations>>(
    queue: TestInternalQueue<P>,
) -> Executor<TestInternalQueue<P>> {
    let (clock, external, idle) = sources();
    Executor::with_internal_queue(
        clock,
        external,
        idle,
        queue,
        ExecutorOptions::default(),
        make_timer,
    )
    .expect("绑定开放且为空的内部任务队列")
}

/// 用公开推进(drive)入口取得同一次关闭报告或轮转结果。
fn turn<Q: InternalTaskQueue, I: IdleQueueManager, L: LocalReadySubmit>(
    executor: &mut Executor<Q, I, L>,
) -> pi_result::Result<TurnResult> {
    executor.run_once(&Admit, &mut DefaultIdlePolicy, &mut NoHooks)
}

/// 真实提交一个尚未轮询(poll)的本地任务,验证关闭清理会结清该份持有。
fn submit_pending<Q: InternalTaskQueue, I: IdleQueueManager>(executor: &Executor<Q, I>) {
    let handle = executor.handle();
    let (task, _result) = handle
        .create_local(executor.local(), pending::<()>(), TaskConfig::new(()))
        .unwrap();
    handle.submit_local(executor.local(), task).unwrap();
    assert_eq!(handle.internal_task_count(), 1);
}

/// @api DefaultExecutor::with_internal_queue
/// 接管借入自定义队列记录的原实例,真实运行本地任务并只关闭该队列一次。
#[test]
fn test_supplied_queue_runs_local_task_and_closes_once() {
    let observations = Observations::default();
    let mut executor = build(TestInternalQueue::new(
        &observations,
        CloseOutcome::Complete,
    ));
    let handle = executor.handle();
    let (task, answer) = handle
        .create_local(executor.local(), ready(42_u32), TaskConfig::new(()))
        .unwrap();
    handle.submit_local(executor.local(), task).unwrap();
    assert_eq!(handle.internal_task_count(), 1);
    assert_eq!(turn(&mut executor).unwrap().runs, 1);
    let mut answer = std::pin::pin!(answer);
    assert!(matches!(
        answer
            .as_mut()
            .poll(&mut Context::from_waker(Waker::noop())),
        Poll::Ready(Ok(42))
    ));

    submit_pending(&executor);
    assert_eq!(handle.request_close(), CloseRequestStatus::Requested);
    assert_eq!(handle.request_close(), CloseRequestStatus::AlreadyRequested);
    assert!(turn(&mut executor).unwrap().service_closed);
    assert_eq!(handle.request_close(), CloseRequestStatus::AlreadyClosed);
    assert!(turn(&mut executor).unwrap().service_closed);
    assert_eq!(handle.status(), RuntimeStatus::Closed);
    assert_eq!(handle.close_state(), CloseState::Completed);
    assert_eq!(handle.internal_task_count(), 0);
    assert_eq!(observations.close_calls.get(), 1);
    assert_eq!(observations.drops.get(), 1);
    assert_eq!(observations.remaining_on_drop.get(), 0);
}

/// @api ExecutorHandle::submit_local、DefaultExecutor::run_once 与 TaskControl::cancel
/// 用同一份选配队列验证轮询(poll)期间提交、同线程尾插、跨线程归属回送(return routing)和取消(cancellation)。
#[test]
fn test_configured_queue_preserves_wakeups_nested_submission_and_cancellation() {
    let observations = Rc::new(Observations::default());
    let queue = TestInternalQueue::new(Rc::clone(&observations), CloseOutcome::Complete);
    let (clock, external, idle) = sources();
    let mut executor = Executor::<_, MpscIdleTaskQueue, LocalWake>::with_internal_queue(
        clock,
        external,
        idle,
        queue,
        ExecutorOptions::default(),
        make_timer,
    )
    .unwrap();
    let handle = executor.handle();
    let _binding = executor
        .local()
        .with_owner(|owner| bind_current(handle.clone(), owner, executor.local()))
        .unwrap()
        .unwrap();

    let wake = Rc::new(RefCell::new(None::<Waker>));
    let polls = Rc::new(Cell::new(0));
    let child_ran = Rc::new(Cell::new(false));
    let future = {
        let wake = Rc::clone(&wake);
        let polls = Rc::clone(&polls);
        let child_ran = Rc::clone(&child_ran);
        let local = Rc::downgrade(executor.local());
        let handle = handle.clone();
        poll_fn(move |cx| {
            let count = polls.get();
            polls.set(count + 1);
            if count == 0 {
                let local = local.upgrade().unwrap();
                let ran = Rc::clone(&child_ran);
                let (child, _result) = handle
                    .create_local(&local, async move { ran.set(true) }, TaskConfig::new(()))
                    .unwrap();
                handle.submit_local(&local, child).unwrap();
            }
            if count < 2 {
                wake.replace(Some(cx.waker().clone()));
                Poll::Pending
            } else {
                Poll::Ready(42_u32)
            }
        })
    };
    let (task, answer) = handle
        .create_local(executor.local(), future, TaskConfig::new(()))
        .unwrap();
    let task_id = task.snapshot().id;
    handle.submit_local(executor.local(), task).unwrap();
    assert_eq!(turn(&mut executor).unwrap().runs, 1);
    assert!(answer.snapshot().admitted);
    assert_eq!(observations.pushes.get(), 2);
    assert_eq!(handle.internal_task_count(), 1);
    wake.borrow_mut().take().unwrap().wake();
    assert_eq!(
        observations.pushes.get(),
        3,
        "同线程唤醒(wake-up)立即尾插"
    );
    assert_eq!(handle.internal_task_count(), 2);
    assert_eq!(turn(&mut executor).unwrap().runs, 1);
    assert!(child_ran.get());
    assert_eq!(polls.get(), 1);
    assert_eq!(turn(&mut executor).unwrap().runs, 1);
    assert_eq!(polls.get(), 2);
    assert_eq!(handle.internal_task_count(), 0);

    let waker = wake.borrow_mut().take().unwrap();
    std::thread::spawn(move || waker.wake()).join().unwrap();
    assert_eq!(
        observations.pushes.get(),
        3,
        "跨线程唤醒(wake-up)先走原归属回送"
    );
    assert_eq!(handle.internal_task_count(), 1);
    assert_eq!(turn(&mut executor).unwrap().runs, 1);
    assert_eq!(observations.pushes.get(), 4);
    assert_eq!(polls.get(), 3);
    assert_eq!(handle.internal_task_count(), 0);
    assert_eq!(answer.snapshot().id, task_id);
    let mut answer = std::pin::pin!(answer);
    let mut context = Context::from_waker(Waker::noop());
    assert!(matches!(
        answer.as_mut().poll(&mut context),
        Poll::Ready(Ok(42))
    ));

    let cancelled_polls = Rc::new(Cell::new(0));
    let seen = Rc::clone(&cancelled_polls);
    let (task, cancelled) = handle
        .create_local(
            executor.local(),
            poll_fn(move |_| {
                seen.set(seen.get() + 1);
                Poll::<()>::Pending
            }),
            TaskConfig::new(()),
        )
        .unwrap();
    handle.submit_local(executor.local(), task).unwrap();
    assert_eq!(turn(&mut executor).unwrap().runs, 1);
    cancelled.control_handle().cancel();
    assert_eq!(handle.internal_task_count(), 1);
    turn(&mut executor).unwrap();
    assert_eq!(
        cancelled_polls.get(),
        1,
        "落实取消(cancellation)时不再轮询业务"
    );
    assert_eq!(handle.internal_task_count(), 0);
    let mut cancelled = std::pin::pin!(cancelled);
    assert!(matches!(
        cancelled.as_mut().poll(&mut context),
        Poll::Ready(Err(TaskError::Cancelled))
    ));

    handle.request_close();
    assert!(turn(&mut executor).unwrap().service_closed);
    assert_eq!(handle.close_state(), CloseState::Completed);
}

/// @api DefaultExecutor::with_internal_queue_factory
/// 一次构造回调(callback)取得实际所属域(owner domain),随后才构造定时驱动。
#[test]
fn test_factory_queue_uses_the_original_owner() {
    let (clock, external, idle) = sources();
    let owner = Cell::new(None);
    let timer_calls = Cell::new(0);
    let mut executor = Executor::<TaskQueue>::with_internal_queue_factory(
        clock,
        external,
        idle,
        |context| {
            assert!(owner.replace(Some(context.owner_id())).is_none());
            Ok(context.task_queue())
        },
        ExecutorOptions::default(),
        |id, clock, notifier| {
            assert!(owner.get().is_some());
            timer_calls.set(timer_calls.get() + 1);
            make_timer(id, clock, notifier)
        },
    )
    .unwrap();
    assert_eq!(
        owner.get(),
        Some(executor.local().with_owner(TaskThread::id).unwrap())
    );
    assert_eq!(timer_calls.get(), 1);
    executor.handle().request_close();
    assert!(turn(&mut executor).unwrap().service_closed);
    assert_eq!(executor.handle().close_state(), CloseState::Completed);
}

/// @api DefaultExecutor::with_internal_queue
/// 三种不合法的原实例各有详细错误,在定时构造前释放,并保留其它所属域(owner domain)。
#[test]
fn test_invalid_queue_precedes_timer_factory() {
    let other = TaskThread::new();
    let closed = Observations::default();
    let nonempty = Observations::default();
    let foreign = Observations::default();
    let mut closed_queue = TestInternalQueue::new(&closed, CloseOutcome::Complete);
    closed_queue.close_internal().unwrap();
    let mut nonempty_queue = TestInternalQueue::new(&nonempty, CloseOutcome::Complete);
    let task = create(
        ready(()),
        ReleaseOnWake,
        (),
        TaskOptions::intrusive_local_and_mpsc(),
    )
    .unwrap_or_else(|_| panic!("创建真实的未绑定任务(Task)"));
    nonempty_queue
        .try_push_internal_back(task.runnable)
        .unwrap_or_else(|_| panic!("交入原任务"));
    let mut foreign_queue = TestInternalQueue::new(&foreign, CloseOutcome::Complete);
    foreign_queue.owner = Some(other.id());
    for (queue, reason, observations) in [
        (closed_queue, "已经关闭", &closed),
        (nonempty_queue, "非空", &nonempty),
        (foreign_queue, "另一所属域", &foreign),
    ] {
        let (clock, external, idle) = sources();
        let timer_calls = Cell::new(0);
        let report = Executor::<_>::with_internal_queue(
            clock,
            external,
            idle,
            queue,
            ExecutorOptions::default(),
            |id, clock, notifier| {
                timer_calls.set(timer_calls.get() + 1);
                make_timer(id, clock, notifier)
            },
        )
        .err()
        .expect("拒绝不合法的队列");
        assert_eq!(report.current_context(), &ErrorKind::InvalidInput);
        assert!(report
            .downcast_ref::<&'static str>()
            .unwrap()
            .contains(reason));
        assert_eq!(timer_calls.get(), 0);
        assert_eq!(observations.drops.get(), 1);
        assert!(!other.is_closed());
    }
    assert_eq!(nonempty.remaining_on_drop.get(), 1);
    assert_eq!(foreign.close_calls.get(), 0);
}

/// @api DefaultExecutor::with_internal_queue_factory
/// 队列构造回调(callback)的原报告保留同一附件,并且不会调用定时构造。
#[test]
fn test_factory_error_returns_its_original_attachment() {
    let (clock, external, idle) = sources();
    let marker = Arc::new(42_u32);
    let report = Error::new(ErrorKind::Dependency).attach(Arc::clone(&marker));
    let result = Executor::<TaskQueue>::with_internal_queue_factory(
        clock,
        external,
        idle,
        |_| Err(report),
        ExecutorOptions::default(),
        |_, _, _| panic!("队列构造失败后不得调用定时构造"),
    );
    let report = result.err().expect("转交队列构造的错误");
    assert_eq!(report.current_context(), &ErrorKind::Dependency);
    assert!(Arc::ptr_eq(
        report.downcast_ref::<Arc<u32>>().unwrap(),
        &marker
    ));
}

/// @api DefaultExecutor::run_once
/// 队列实际尚有余项和队列返回原错误均只关闭一次,余项由同一队列的析构(drop)处理。
#[test]
fn test_incomplete_close_and_original_error_keep_requested() {
    let marker = Arc::new(42_u32);
    let outcomes = [
        (CloseOutcome::MoreWork, ErrorKind::InvalidState),
        (
            CloseOutcome::Error(Error::new(ErrorKind::Dependency).attach(Arc::clone(&marker))),
            ErrorKind::Dependency,
        ),
    ];
    for (outcome, kind) in outcomes {
        let observations = Observations::default();
        let mut executor = build(TestInternalQueue::new(&observations, outcome));
        submit_pending(&executor);
        let handle = executor.handle();
        handle.request_close();
        let report = turn(&mut executor).expect_err("清理尚未得到确认");
        assert_eq!(report.current_context(), &kind);
        match kind {
            ErrorKind::Dependency => assert!(Arc::ptr_eq(
                report.downcast_ref::<Arc<u32>>().unwrap(),
                &marker
            )),
            _ => assert!(report
                .downcast_ref::<&'static str>()
                .unwrap()
                .contains("尚未确认清理")),
        }
        assert!(turn(&mut executor).unwrap().service_closed);
        assert_eq!(handle.status(), RuntimeStatus::Closed);
        assert_eq!(handle.close_state(), CloseState::Requested);
        assert_eq!(handle.internal_task_count(), 0);
        assert_eq!(observations.close_calls.get(), 1);
        assert_eq!(observations.drops.get(), 1);
        assert_eq!(observations.remaining_on_drop.get(), 1);
    }
}

/// 由真实空闲任务队列(idle task queue)完成自身清理,随后使该来源报告原错误。
struct IdleWithCloseError(MpscIdleTaskQueue, Option<Error>);

impl IdleQueueManager for IdleWithCloseError {
    type Handle = MpscIdleTaskQueueHandle;

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

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

    fn close(&mut self) -> pi_result::Result<QueueCleanupProgress> {
        let progress = self.0.close()?;
        match self.1.take() {
            Some(report) => Err(report),
            None => Ok(progress),
        }
    }
}

/// @api DefaultExecutor::run_once
/// 空闲来源先报告出错时,后续内部队列仍然关闭,调用方得到原首错。
#[test]
fn test_internal_queue_does_not_replace_an_earlier_close_error() {
    let marker = Arc::new(42_u32);
    let observations = Observations::default();
    let (clock, external, idle) = sources();
    let idle = IdleWithCloseError(
        idle,
        Some(Error::new(ErrorKind::Dependency).attach(Arc::clone(&marker))),
    );
    let queue = TestInternalQueue::new(
        &observations,
        CloseOutcome::Error(Error::new(ErrorKind::InvalidState)),
    );
    let mut executor = Executor::<_, IdleWithCloseError>::with_internal_queue(
        clock,
        external,
        idle,
        queue,
        ExecutorOptions::default(),
        make_timer,
    )
    .unwrap();
    let handle = executor.handle();
    handle.request_close();
    let report = turn(&mut executor).expect_err("返回最早的来源错误");
    assert_eq!(report.current_context(), &ErrorKind::Dependency);
    assert!(Arc::ptr_eq(
        report.downcast_ref::<Arc<u32>>().unwrap(),
        &marker
    ));
    assert_eq!(observations.close_calls.get(), 1);
    assert_eq!(observations.drops.get(), 1);
    assert_eq!(handle.status(), RuntimeStatus::Closed);
    assert_eq!(handle.close_state(), CloseState::Requested);
}

/// @api DefaultExecutor::run_once
/// 在关闭方法或队列析构(drop)中第一次展开(unwinding)时,继续传播原载荷,先释放余项再归还计数。
#[test]
fn test_internal_queue_close_panic_releases_the_queue_before_count() {
    for (outcome, panic_on_drop, payload) in [
        (CloseOutcome::Panic, false, CLOSE_PANIC),
        (CloseOutcome::MoreWork, true, DROP_PANIC),
    ] {
        let observations = Observations::default();
        let mut queue = TestInternalQueue::new(&observations, outcome);
        queue.panic_on_drop = panic_on_drop;
        let mut executor = build(queue);
        let handle = executor.handle();
        submit_pending(&executor);
        let observer = handle.clone();
        observations
            .read_count
            .replace(Some(Box::new(move || observer.internal_task_count())));
        handle.request_close();
        let panic =
            catch_unwind(AssertUnwindSafe(|| turn(&mut executor))).expect_err("原载荷应沿推进传播");
        assert_eq!(panic.downcast_ref::<&'static str>(), Some(&payload));
        assert_eq!(observations.close_calls.get(), 1);
        assert_eq!(observations.drops.get(), 1);
        assert_eq!(observations.remaining_on_drop.get(), 1);
        assert_eq!(observations.count_on_drop.get(), Some(1));
        assert_eq!(handle.internal_task_count(), 0);
        assert_eq!(handle.status(), RuntimeStatus::Closed);
        assert_eq!(handle.close_state(), CloseState::Requested);
    }
}

/// @api ExecutorLocal::with_owner 与 DefaultExecutor::run_once
/// 已借出所属域(owner domain)时同步关闭报告未确认,归还借用后由同一队列析构接续。
#[test]
fn test_close_during_owner_borrow_is_settled_after_the_borrow() {
    let observations = Observations::default();
    let mut executor = build(TestInternalQueue::new(
        &observations,
        CloseOutcome::Complete,
    ));
    let handle = executor.handle();
    submit_pending(&executor);
    let local = Rc::clone(executor.local());
    local
        .with_owner(|_| {
            handle.request_close();
            let report = turn(&mut executor).expect_err("借用期间不能确认清理");
            assert_eq!(report.current_context(), &ErrorKind::InvalidState);
            assert_eq!(handle.status(), RuntimeStatus::Closing);
            assert_eq!(observations.close_calls.get(), 0);
            assert_eq!(observations.drops.get(), 0);
        })
        .unwrap();
    assert_eq!(observations.close_calls.get(), 0);
    assert_eq!(observations.drops.get(), 1);
    assert_eq!(observations.remaining_on_drop.get(), 1);
    assert_eq!(handle.internal_task_count(), 0);
    assert_eq!(handle.status(), RuntimeStatus::Closed);
    assert_eq!(handle.close_state(), CloseState::Requested);
}

/// @api DefaultExecutor 的析构(drop)
/// 直接释放执行器时,原队列通过析构释放余项,正常清理确认关闭。
#[test]
fn test_executor_drop_releases_the_original_queue() {
    let observations = Observations::default();
    let executor = build(TestInternalQueue::new(
        &observations,
        CloseOutcome::Complete,
    ));
    submit_pending(&executor);
    let handle = executor.handle();
    drop(executor);
    assert_eq!(observations.close_calls.get(), 0);
    assert_eq!(observations.drops.get(), 1);
    assert_eq!(observations.remaining_on_drop.get(), 1);
    assert_eq!(handle.internal_task_count(), 0);
    assert_eq!(handle.status(), RuntimeStatus::Closed);
    assert_eq!(handle.close_state(), CloseState::Completed);
}