Skip to main content

rocketmq_runtime/
operation.rs

1// Copyright 2023 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::future::Future;
16use std::sync::atomic::AtomicBool;
17use std::sync::atomic::AtomicU64;
18use std::sync::atomic::AtomicU8;
19use std::sync::atomic::AtomicUsize;
20use std::sync::atomic::Ordering;
21use std::sync::Arc;
22use std::sync::OnceLock;
23use std::time::Duration;
24use std::time::Instant;
25
26use futures::future::join_all;
27use parking_lot::Mutex;
28use parking_lot::MutexGuard;
29use tokio::sync::Notify;
30use tokio_util::sync::CancellationToken;
31
32use crate::error::RuntimeError;
33use crate::error::RuntimeResult;
34use crate::shutdown_deadline::ShutdownDeadline;
35use crate::shutdown_deadline::ABORT_CONFIRMATION_TIMEOUT;
36use crate::task_group::TaskGroup;
37use crate::task_group::TaskGroupId;
38use crate::task_group::TaskKind;
39
40/// Why an accepted operation task finished, after its future was destroyed.
41///
42/// Completion means normal return, not business success. Explicit aborts are
43/// distinct from a cancellation branch selected by the task.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45#[repr(u8)]
46pub enum OperationTaskExitReason {
47    /// The future returned normally.
48    Completed = 1,
49    /// The operation-local cancellation branch won.
50    Cancelled = 2,
51    /// The operation's deadline branch won.
52    DeadlineExceeded = 3,
53    /// The component owner's cancellation branch won.
54    OwnerCancelled = 4,
55    /// Polling or destroying the future panicked.
56    Panicked = 5,
57    /// The future was discarded before selecting another terminal outcome.
58    Aborted = 6,
59}
60
61impl OperationTaskExitReason {
62    /// All outcomes in counter snapshot order.
63    pub const ALL: [Self; 6] = [
64        Self::Completed,
65        Self::Cancelled,
66        Self::DeadlineExceeded,
67        Self::OwnerCancelled,
68        Self::Panicked,
69        Self::Aborted,
70    ];
71
72    /// Stable, low-cardinality diagnostic label.
73    pub const fn as_str(self) -> &'static str {
74        match self {
75            Self::Completed => "completed",
76            Self::Cancelled => "cancelled",
77            Self::DeadlineExceeded => "deadline_exceeded",
78            Self::OwnerCancelled => "owner_cancelled",
79            Self::Panicked => "panicked",
80            Self::Aborted => "aborted",
81        }
82    }
83}
84
85/// Observes task outcomes after future destruction.
86///
87/// Callbacks must be short, nonblocking and panic-free, including during panic
88/// unwinding. They must not flush exporters or retain request data.
89pub trait OperationTaskExitObserver: std::fmt::Debug + Send + Sync {
90    /// Records one terminal task outcome using bounded labels.
91    fn on_outcome(&self, kind: TaskKind, outcome: OperationTaskExitReason);
92}
93
94/// Cancellation, deadline, and task-class metadata for one bounded operation.
95///
96/// An operation is not a lifecycle owner and does not create a child
97/// [`TaskGroup`]. Tasks spawned for the operation remain registered with a
98/// fixed component owner while this context supplies operation-local
99/// cancellation and bounded join semantics.
100#[derive(Debug, Clone)]
101pub struct OperationContext {
102    inner: Arc<OperationContextInner>,
103    task_kind: TaskKind,
104}
105
106/// Absolute deadlines for graceful completion and subsequent abort confirmation.
107#[derive(Debug, Clone, Copy)]
108pub struct OperationWaitPolicy {
109    graceful: ShutdownDeadline,
110    confirmation: ShutdownDeadline,
111}
112
113impl OperationWaitPolicy {
114    /// Creates a policy whose graceful phase cannot extend past confirmation.
115    ///
116    /// Passing the same deadline requests aborts at expiry without extending
117    /// the wait. An earlier confirmation deadline also tightens the grace phase.
118    pub fn new(graceful: ShutdownDeadline, confirmation: ShutdownDeadline) -> Self {
119        Self {
120            graceful: graceful.earliest(confirmation),
121            confirmation,
122        }
123    }
124}
125
126/// Whether task draining was confirmed when an operation's bounded wait stopped.
127///
128/// `Completed` confirms that tasks settled during the graceful phase; it does
129/// not describe whether the operation's business work succeeded.
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub enum OperationDrainStatus {
132    /// All tasks settled during the graceful phase.
133    Completed,
134    /// All tasks settled after aborts were requested.
135    AbortConfirmed,
136    /// The confirmation deadline expired with tasks still registered.
137    Unconfirmed {
138        /// Tasks whose final destruction and owner bookkeeping remain unconfirmed.
139        remaining_tasks: usize,
140    },
141}
142
143#[derive(Debug)]
144struct OperationContextInner {
145    /// Process-unique id; the owner's task registry tags operation tasks with it.
146    id: u64,
147    cancellation: CancellationToken,
148    deadline: Option<Instant>,
149    accepting: AtomicBool,
150    /// Serializes admission with `close_admission` and `cancel`.
151    spawn_gate: Mutex<()>,
152    /// Id of the component owner, or zero before the first submission.
153    owner_id: AtomicU64,
154    /// Accepted tasks whose futures have not yet been destroyed.
155    active: AtomicUsize,
156    /// Woken when `active` drops to zero.
157    idle: Notify,
158    outcomes: [AtomicU64; 6],
159    observer: OnceLock<Arc<dyn OperationTaskExitObserver>>,
160}
161
162impl OperationContext {
163    /// Closes operation admission and asynchronously waits using explicit deadlines.
164    ///
165    /// Tasks unfinished at the graceful deadline are asked to abort. The second
166    /// deadline bounds confirmation of future destruction and owner settlement.
167    /// An unconfirmed outcome leaves those tasks visible to the owner's report.
168    /// Deadlines bound cooperative waiting; blocked executor threads can delay
169    /// polling and this method does not promise a hard wall-clock return time.
170    ///
171    /// # Errors
172    ///
173    /// Returns an error without closing admission if `owner` is not this
174    /// operation's bound component owner.
175    pub async fn wait_with_policy(
176        &self,
177        owner: &TaskGroup,
178        policy: OperationWaitPolicy,
179    ) -> RuntimeResult<OperationDrainStatus> {
180        self.ensure_owner(owner.id())?;
181        self.close_admission();
182        if self.wait_until_settled(owner, policy.graceful.instant()).await? {
183            return Ok(OperationDrainStatus::Completed);
184        }
185        let remaining = owner.operation_task_ids(self.inner.id);
186        join_all(
187            remaining
188                .into_iter()
189                .map(|task_id| owner.abort_task_until(task_id, policy.confirmation)),
190        )
191        .await;
192        let remaining_tasks = owner.operation_task_ids(self.inner.id).len();
193        Ok(if remaining_tasks == 0 {
194            OperationDrainStatus::AbortConfirmed
195        } else {
196            OperationDrainStatus::Unconfirmed { remaining_tasks }
197        })
198    }
199
200    /// Creates an operation with an absolute deadline.
201    pub fn new(deadline: Instant, task_kind: TaskKind) -> Self {
202        Self::from_parts(Some(deadline), task_kind)
203    }
204
205    /// Creates an operation that remains active until explicitly cancelled.
206    pub fn without_deadline(task_kind: TaskKind) -> Self {
207        Self::from_parts(None, task_kind)
208    }
209
210    fn from_parts(deadline: Option<Instant>, task_kind: TaskKind) -> Self {
211        static NEXT_OPERATION_ID: AtomicU64 = AtomicU64::new(1);
212        Self {
213            inner: Arc::new(OperationContextInner {
214                id: NEXT_OPERATION_ID.fetch_add(1, Ordering::Relaxed),
215                cancellation: CancellationToken::new(),
216                deadline,
217                accepting: AtomicBool::new(true),
218                spawn_gate: Mutex::new(()),
219                owner_id: AtomicU64::new(0),
220                active: AtomicUsize::new(0),
221                idle: Notify::new(),
222                outcomes: std::array::from_fn(|_| AtomicU64::new(0)),
223                observer: OnceLock::new(),
224            }),
225            task_kind,
226        }
227    }
228
229    pub(crate) fn id(&self) -> u64 {
230        self.inner.id
231    }
232
233    /// Returns the operation-local cancellation token.
234    pub fn cancellation_token(&self) -> CancellationToken {
235        self.inner.cancellation.clone()
236    }
237
238    /// Returns the absolute deadline, when one was configured.
239    pub fn deadline(&self) -> Option<Instant> {
240        self.inner.deadline
241    }
242
243    /// Returns the task classification applied to operation tasks.
244    pub fn task_kind(&self) -> TaskKind {
245        self.task_kind
246    }
247
248    /// Returns a view of this operation with a different task classification.
249    ///
250    /// Cancellation, deadline, owner binding, and active-task tracking remain
251    /// shared with the original context.
252    pub fn with_task_kind(&self, task_kind: TaskKind) -> Self {
253        Self {
254            inner: Arc::clone(&self.inner),
255            task_kind,
256        }
257    }
258
259    /// Returns whether cancellation has been requested.
260    pub fn is_cancelled(&self) -> bool {
261        self.inner.cancellation.is_cancelled()
262    }
263
264    /// Requests cancellation for every task in this operation.
265    pub fn cancel(&self) {
266        let _spawn_guard = self.inner.spawn_gate.lock();
267        self.inner.accepting.store(false, Ordering::Release);
268        self.inner.cancellation.cancel();
269    }
270
271    /// Closes task admission without cancelling tasks that were already
272    /// accepted.
273    pub fn close_admission(&self) {
274        let _spawn_guard = self.inner.spawn_gate.lock();
275        self.inner.accepting.store(false, Ordering::Release);
276    }
277
278    /// Returns the number of operation tasks that have not completed.
279    pub fn active_task_count(&self) -> usize {
280        self.inner.active.load(Ordering::Acquire)
281    }
282
283    /// Reads counters without retaining individual task history.
284    ///
285    /// Counters share this operation's lifetime and are individually atomic;
286    /// completions can occur between fields in this snapshot.
287    pub fn outcomes(&self) -> [(OperationTaskExitReason, u64); 6] {
288        OperationTaskExitReason::ALL.map(|outcome| {
289            (
290                outcome,
291                self.inner.outcomes[outcome as usize - 1].load(Ordering::Acquire),
292            )
293        })
294    }
295
296    /// Binds an observer before the first submission attempt.
297    ///
298    /// # Errors
299    ///
300    /// Returns an error after owner binding or an earlier observer installation.
301    pub fn set_outcome_observer(&self, observer: Arc<dyn OperationTaskExitObserver>) -> RuntimeResult<()> {
302        let _gate = self.inner.spawn_gate.lock();
303        if self.inner.owner_id.load(Ordering::Acquire) != 0 || self.inner.observer.set(observer).is_err() {
304            return Err(RuntimeError::context_unavailable(
305                crate::RuntimeOperation::SpawnOperation,
306            ));
307        }
308        Ok(())
309    }
310
311    /// Cancels this operation and waits for all tasks registered with `owner`.
312    ///
313    /// Returns `true` when every task completed before the shared timeout.
314    /// Tasks still running at the deadline are aborted and awaited for a
315    /// confirmation window of at most one second beyond it. `false` does not
316    /// distinguish a confirmed abort from work whose destruction is still
317    /// unconfirmed. Use [`Self::wait_with_policy`] after [`Self::cancel`] for
318    /// explicit deadlines and completion evidence. Timers require the runtime
319    /// to make progress; they are not a hard wall-clock return guarantee.
320    ///
321    /// # Errors
322    ///
323    /// Returns an error when `owner` differs from the component owner used to
324    /// spawn the operation.
325    pub async fn cancel_and_wait(&self, owner: &TaskGroup, timeout: Duration) -> RuntimeResult<bool> {
326        self.cancel();
327        self.wait(owner, timeout).await
328    }
329
330    /// Cancels this operation and bounds its asynchronous wait by `deadline`.
331    ///
332    /// Behaves like [`Self::wait_until`] after requesting cancellation.
333    ///
334    /// # Errors
335    ///
336    /// Returns an error when `owner` differs from the component owner used to
337    /// spawn the operation.
338    pub async fn cancel_and_wait_until(&self, owner: &TaskGroup, deadline: ShutdownDeadline) -> RuntimeResult<bool> {
339        self.cancel();
340        self.wait_until(owner, deadline).await
341    }
342
343    /// Waits until no operation task is active and `owner` has settled every
344    /// one, without requesting cancellation. Tasks still running at the
345    /// deadline are aborted and awaited for a confirmation window of at most
346    /// one second, so the call can return up to one second after `timeout`.
347    ///
348    /// Tasks accepted during the wait are waited for too; close admission
349    /// first when new tasks may still be submitted. Returns `true` when every
350    /// task finished before the deadline; `owner` then no longer lists any of
351    /// them. `false` does not confirm destruction. Use [`Self::wait_until`] to
352    /// avoid an extra confirmation allowance, or [`Self::wait_with_policy`]
353    /// to distinguish confirmed aborts from unconfirmed work.
354    ///
355    /// # Errors
356    ///
357    /// Returns an error when `owner` differs from the component owner used to
358    /// spawn the operation.
359    pub async fn wait(&self, owner: &TaskGroup, timeout: Duration) -> RuntimeResult<bool> {
360        self.wait_for_tasks(owner, Instant::now() + timeout, ABORT_CONFIRMATION_TIMEOUT)
361            .await
362    }
363
364    /// Waits for this operation's tasks with no allowance beyond `deadline`.
365    ///
366    /// Tasks still running at the deadline are asked to abort and the call
367    /// returns `false` at once, without confirming that their futures were
368    /// dropped. They stay registered with `owner` until they are, so the
369    /// owner's shutdown report accounts for any that remain. This matches
370    /// [`TaskGroup::shutdown_until`], which also does not extend its deadline.
371    /// Runtime starvation or synchronous destructors can delay timer polling.
372    ///
373    /// # Errors
374    ///
375    /// Returns an error when `owner` differs from the component owner used to
376    /// spawn the operation.
377    pub async fn wait_until(&self, owner: &TaskGroup, deadline: ShutdownDeadline) -> RuntimeResult<bool> {
378        self.wait_for_tasks(owner, deadline.instant(), Duration::ZERO).await
379    }
380
381    /// Waits until `deadline`, then aborts what remains and waits up to
382    /// `abort_confirmation` for those futures to be dropped.
383    async fn wait_for_tasks(
384        &self,
385        owner: &TaskGroup,
386        deadline: Instant,
387        abort_confirmation: Duration,
388    ) -> RuntimeResult<bool> {
389        if self.wait_until_settled(owner, deadline).await? {
390            return Ok(true);
391        }
392        // A zero confirmation window only requests the aborts. Legacy callers
393        // retain their boolean outcome and relative confirmation allowance.
394        let remaining = owner.operation_task_ids(self.inner.id);
395        join_all(
396            remaining
397                .into_iter()
398                .map(|task_id| owner.abort_task_and_wait(task_id, abort_confirmation)),
399        )
400        .await;
401        Ok(false)
402    }
403
404    async fn wait_until_settled(&self, owner: &TaskGroup, deadline: Instant) -> RuntimeResult<bool> {
405        self.ensure_owner(owner.id())?;
406        loop {
407            // Registered before the check, so a wakeup in between is not lost.
408            let idle = self.inner.idle.notified();
409            if self.inner.active.load(Ordering::Acquire) == 0 {
410                // A task stops counting as active when its future is
411                // destroyed; its owner settles it just afterwards. Wait for
412                // that too, so a caller never finds a finished task still
413                // registered with the owner.
414                let unsettled = owner.operation_task_ids(self.inner.id);
415                if unsettled.is_empty() {
416                    return Ok(true);
417                }
418                let deadline = ShutdownDeadline::at(deadline);
419                let settled = join_all(
420                    unsettled
421                        .into_iter()
422                        .map(|task_id| owner.wait_task_until(task_id, deadline)),
423                )
424                .await;
425                if settled.into_iter().all(|settled| settled) {
426                    continue;
427                }
428                break;
429            }
430            if tokio::time::timeout_at(deadline.into(), idle).await.is_err() {
431                break;
432            }
433        }
434
435        Ok(false)
436    }
437
438    /// Admits one task: binds the owner and counts the task as active.
439    ///
440    /// The caller holds [`Self::spawn_guard`], so admission cannot interleave
441    /// with `close_admission` or `cancel`.
442    pub(crate) fn prepare_spawn(&self, owner_id: TaskGroupId) -> RuntimeResult<OperationTaskRegistration> {
443        self.bind_owner(owner_id)?;
444        if !self.inner.accepting.load(Ordering::Acquire)
445            || self.is_cancelled()
446            || self.inner.deadline.is_some_and(|deadline| deadline <= Instant::now())
447        {
448            return Err(RuntimeError::closed(crate::RuntimeOperation::SpawnOperation));
449        }
450        self.inner.active.fetch_add(1, Ordering::AcqRel);
451        Ok(OperationTaskRegistration::new(Arc::clone(&self.inner), self.task_kind))
452    }
453
454    pub(crate) fn spawn_guard(&self) -> MutexGuard<'_, ()> {
455        self.inner.spawn_gate.lock()
456    }
457
458    async fn run<F>(&self, future: F) -> OperationTaskExitReason
459    where
460        F: Future<Output = ()>,
461    {
462        match self.inner.deadline {
463            Some(deadline) => {
464                tokio::select! {
465                    biased;
466                    _ = self.inner.cancellation.cancelled() => OperationTaskExitReason::Cancelled,
467                    _ = tokio::time::sleep_until(deadline.into()) => OperationTaskExitReason::DeadlineExceeded,
468                    _ = future => OperationTaskExitReason::Completed,
469                }
470            }
471            None => {
472                tokio::select! {
473                    biased;
474                    _ = self.inner.cancellation.cancelled() => OperationTaskExitReason::Cancelled,
475                    _ = future => OperationTaskExitReason::Completed,
476                }
477            }
478        }
479    }
480
481    fn bind_owner(&self, owner_id: TaskGroupId) -> RuntimeResult<()> {
482        match self
483            .inner
484            .owner_id
485            .compare_exchange(0, owner_id.as_u64(), Ordering::AcqRel, Ordering::Acquire)
486        {
487            Ok(_) => Ok(()),
488            Err(bound_owner) if bound_owner == owner_id.as_u64() => Ok(()),
489            Err(_) => Err(RuntimeError::internal_failure(crate::RuntimeOperation::OperationOwner)),
490        }
491    }
492
493    fn ensure_owner(&self, owner_id: TaskGroupId) -> RuntimeResult<()> {
494        match self.inner.owner_id.load(Ordering::Acquire) {
495            0 => Ok(()),
496            bound_owner if bound_owner == owner_id.as_u64() => Ok(()),
497            _ => Err(RuntimeError::internal_failure(crate::RuntimeOperation::OperationOwner)),
498        }
499    }
500}
501
502pub(crate) struct OperationTaskRegistration {
503    state: Arc<OperationTaskRegistrationState>,
504}
505
506/// Set once the owner accepted the task.
507const TASK_REGISTERED: u8 = 1;
508/// Set once the task's future was destroyed.
509const TASK_COMPLETED: u8 = 2;
510
511struct OperationTaskRegistrationState {
512    /// `TASK_REGISTERED` and `TASK_COMPLETED` bits. Both sides set their bit
513    /// with one read-modify-write, so exactly one sees the other bit and
514    /// records the outcome.
515    progress: AtomicU8,
516    outcome: AtomicU8,
517    operation: Arc<OperationContextInner>,
518    task_kind: TaskKind,
519}
520
521impl OperationTaskRegistration {
522    fn new(operation: Arc<OperationContextInner>, task_kind: TaskKind) -> Self {
523        Self {
524            state: Arc::new(OperationTaskRegistrationState {
525                progress: AtomicU8::new(0),
526                outcome: AtomicU8::new(0),
527                operation,
528                task_kind,
529            }),
530        }
531    }
532
533    pub(crate) fn guard(&self) -> OperationTaskGuard {
534        OperationTaskGuard {
535            state: Arc::clone(&self.state),
536            outcome: OperationTaskExitReason::Aborted,
537        }
538    }
539
540    /// Marks the task as accepted by its owner. A task the owner rejected
541    /// never records an outcome.
542    pub(crate) fn finish_registration(self) {
543        let previous = self.state.progress.fetch_or(TASK_REGISTERED, Ordering::AcqRel);
544        if previous & TASK_COMPLETED != 0 {
545            self.state.record(self.state.outcome.load(Ordering::Acquire));
546        }
547    }
548}
549
550pub(crate) struct OperationTaskGuard {
551    state: Arc<OperationTaskRegistrationState>,
552    outcome: OperationTaskExitReason,
553}
554
555impl Drop for OperationTaskGuard {
556    fn drop(&mut self) {
557        let outcome = if std::thread::panicking() {
558            OperationTaskExitReason::Panicked
559        } else {
560            self.outcome
561        };
562        self.state.outcome.store(outcome as u8, Ordering::Release);
563        let previous = self.state.progress.fetch_or(TASK_COMPLETED, Ordering::AcqRel);
564        if previous & TASK_REGISTERED != 0 {
565            self.state.record(outcome as u8);
566        }
567        // Counters are published before a waiter can observe the operation idle.
568        let operation = &self.state.operation;
569        if operation.active.fetch_sub(1, Ordering::AcqRel) == 1 {
570            operation.idle.notify_waiters();
571        }
572    }
573}
574
575impl OperationTaskRegistrationState {
576    fn record(&self, value: u8) {
577        let Some(outcome) = OperationTaskExitReason::ALL
578            .into_iter()
579            .find(|outcome| *outcome as u8 == value)
580        else {
581            return;
582        };
583        self.operation.outcomes[value as usize - 1].fetch_add(1, Ordering::Release);
584        if let Some(observer) = self.operation.observer.get() {
585            observer.on_outcome(self.task_kind, outcome);
586        }
587    }
588}
589
590// Also destroys the user future first when an accepted task is never polled.
591pub(crate) struct OperationExecution<F> {
592    future: F,
593    finalizer: OperationTaskGuard,
594    operation: OperationContext,
595    owner_cancellation: Option<CancellationToken>,
596}
597
598impl<F: Future<Output = ()>> OperationExecution<F> {
599    pub(crate) fn new(
600        future: F,
601        finalizer: OperationTaskGuard,
602        operation: OperationContext,
603        owner_cancellation: Option<CancellationToken>,
604    ) -> Self {
605        Self {
606            future,
607            finalizer,
608            operation,
609            owner_cancellation,
610        }
611    }
612
613    pub(crate) async fn run(self) {
614        let mut finalizer = self.finalizer;
615        let outcome = match self.owner_cancellation {
616            Some(owner) => tokio::select! {
617                biased;
618                _ = owner.cancelled() => OperationTaskExitReason::OwnerCancelled,
619                outcome = self.operation.run(self.future) => outcome,
620            },
621            None => self.operation.run(self.future).await,
622        };
623        finalizer.outcome = outcome;
624    }
625}
626
627#[cfg(test)]
628mod tests {
629    use super::*;
630    use crate::RuntimeContext;
631
632    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
633    async fn wait_returns_only_after_the_owner_settles_the_tasks() {
634        let context = RuntimeContext::from_current("operation-settlement");
635        let owner = context.service_context("owner").task_group().clone();
636        let operation = OperationContext::without_deadline(TaskKind::Worker);
637        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
638        let task_id = owner
639            .spawn_operation(&operation, "settles-late", async move {
640                let _ = finish_rx.await;
641            })
642            .unwrap();
643
644        // Hold the owner's settlement gate on another thread, so the task's
645        // future can be destroyed while the owner cannot yet settle it.
646        let (locked_tx, locked_rx) = std::sync::mpsc::channel();
647        let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
648        let gate_owner = owner.clone();
649        let holder = std::thread::spawn(move || {
650            let _settlement = gate_owner.lock_settlement_for_test();
651            locked_tx.send(()).unwrap();
652            release_rx.recv().unwrap();
653        });
654        locked_rx.recv().unwrap();
655        finish_tx.send(()).unwrap();
656        while operation.active_task_count() != 0 {
657            tokio::task::yield_now().await;
658        }
659
660        let mut wait = Box::pin(operation.wait(&owner, Duration::from_secs(5)));
661        assert!(
662            futures::poll!(wait.as_mut()).is_pending(),
663            "a task the owner has not settled still belongs to the operation"
664        );
665        assert!(owner.contains_task(task_id));
666
667        release_tx.send(()).unwrap();
668        holder.join().unwrap();
669        assert!(wait.await.unwrap());
670        assert!(!owner.contains_task(task_id));
671        assert_eq!(owner.task_count(), 0);
672    }
673
674    struct OperationTaskExitTestFuture {
675        dropped: Arc<AtomicBool>,
676        ready: bool,
677        panic_poll: bool,
678        panic_drop: bool,
679    }
680
681    impl Future for OperationTaskExitTestFuture {
682        type Output = ();
683        fn poll(self: std::pin::Pin<&mut Self>, _: &mut std::task::Context<'_>) -> std::task::Poll<()> {
684            assert!(!self.panic_poll, "operation poll panic");
685            if self.ready {
686                std::task::Poll::Ready(())
687            } else {
688                std::task::Poll::Pending
689            }
690        }
691    }
692
693    impl Drop for OperationTaskExitTestFuture {
694        fn drop(&mut self) {
695            self.dropped.store(true, Ordering::Release);
696            assert!(!self.panic_drop, "operation destructor panic");
697        }
698    }
699
700    #[derive(Debug)]
701    struct RecordingTaskExitObserver {
702        dropped: Arc<AtomicBool>,
703        events: Mutex<Vec<OperationTaskExitReason>>,
704    }
705
706    impl OperationTaskExitObserver for RecordingTaskExitObserver {
707        fn on_outcome(&self, _kind: TaskKind, outcome: OperationTaskExitReason) {
708            assert!(
709                self.dropped.load(Ordering::Acquire),
710                "outcome preceded future destruction"
711            );
712            self.events.lock().push(outcome);
713        }
714    }
715
716    #[tokio::test(start_paused = true)]
717    async fn all_outcomes_are_recorded_once_after_future_destruction() {
718        for expected in OperationTaskExitReason::ALL {
719            let runtime = RuntimeContext::from_current("operation-outcome");
720            let owner = runtime.service_context("operation-owner");
721            let operation = if expected == OperationTaskExitReason::DeadlineExceeded {
722                OperationContext::new(Instant::now() + Duration::from_secs(60), TaskKind::Worker)
723            } else {
724                OperationContext::without_deadline(TaskKind::Worker)
725            };
726            let dropped = Arc::new(AtomicBool::new(false));
727            let observer = Arc::new(RecordingTaskExitObserver {
728                dropped: dropped.clone(),
729                events: Mutex::new(Vec::new()),
730            });
731            operation.set_outcome_observer(observer.clone()).unwrap();
732            let id = owner
733                .task_group()
734                .spawn_operation(
735                    &operation,
736                    "selected-outcome",
737                    OperationTaskExitTestFuture {
738                        dropped,
739                        ready: expected == OperationTaskExitReason::Completed,
740                        panic_poll: expected == OperationTaskExitReason::Panicked,
741                        panic_drop: false,
742                    },
743                )
744                .unwrap();
745            match expected {
746                OperationTaskExitReason::Cancelled => operation.cancel(),
747                OperationTaskExitReason::OwnerCancelled => owner.task_group().cancel(),
748                OperationTaskExitReason::DeadlineExceeded => tokio::time::advance(Duration::from_secs(61)).await,
749                OperationTaskExitReason::Aborted => {
750                    assert!(owner.task_group().abort_task(id));
751                }
752                OperationTaskExitReason::Completed | OperationTaskExitReason::Panicked => {}
753            }
754            while owner.task_group().task_count() != 0 {
755                tokio::task::yield_now().await;
756            }
757            assert_eq!(*observer.events.lock(), [expected]);
758            assert_eq!(operation.active_task_count(), 0);
759            for (outcome, count) in operation.outcomes() {
760                assert_eq!(count, u64::from(outcome == expected), "{expected:?}: {outcome:?}");
761            }
762            let report = runtime.shutdown_tasks(Duration::from_secs(1)).await;
763            assert_eq!(report.is_healthy(), expected != OperationTaskExitReason::Panicked);
764        }
765    }
766
767    #[tokio::test]
768    async fn destructor_panic_is_an_operation_failure_and_rejected_work_has_no_outcome() {
769        let runtime = RuntimeContext::from_current("operation-destructor");
770        let owner = runtime.service_context("operation-owner");
771        let operation = OperationContext::without_deadline(TaskKind::Worker);
772        let dropped = Arc::new(AtomicBool::new(false));
773        let observer = Arc::new(RecordingTaskExitObserver {
774            dropped: dropped.clone(),
775            events: Mutex::new(Vec::new()),
776        });
777        operation.set_outcome_observer(observer.clone()).unwrap();
778        owner
779            .task_group()
780            .spawn_operation(
781                &operation,
782                "destructor-panic",
783                OperationTaskExitTestFuture {
784                    dropped,
785                    ready: true,
786                    panic_poll: false,
787                    panic_drop: true,
788                },
789            )
790            .unwrap();
791        while owner.task_group().task_count() != 0 {
792            tokio::task::yield_now().await;
793        }
794        assert_eq!(*observer.events.lock(), [OperationTaskExitReason::Panicked]);
795        runtime.shutdown_tasks(Duration::from_secs(1)).await;
796
797        let rejected = OperationContext::without_deadline(TaskKind::Worker);
798        assert!(owner
799            .task_group()
800            .spawn_operation(&rejected, "closed", async {})
801            .is_err());
802        assert_eq!(rejected.active_task_count(), 0);
803        assert!(rejected.outcomes().into_iter().all(|(_, count)| count == 0));
804    }
805
806    #[tokio::test]
807    async fn completed_operations_leave_no_registry_history() {
808        const TASKS: usize = 1_024;
809
810        let runtime = RuntimeContext::from_current("operation-churn-test");
811        let owner = runtime.service_context("operations");
812        let baseline_components = owner.task_group().component_count();
813        let operation = OperationContext::without_deadline(TaskKind::Worker);
814
815        for _ in 0..TASKS {
816            owner
817                .task_group()
818                .spawn_operation(&operation, "short-operation", async {})
819                .expect("operation task should spawn");
820        }
821
822        tokio::time::timeout(Duration::from_secs(5), async {
823            while operation.active_task_count() != 0 || owner.task_group().task_count() != 0 {
824                tokio::task::yield_now().await;
825            }
826        })
827        .await
828        .expect("operation tasks should complete");
829
830        assert_eq!(owner.task_group().component_count(), baseline_components);
831        assert_eq!(
832            operation.outcomes()[0],
833            (OperationTaskExitReason::Completed, TASKS as u64)
834        );
835        let report = runtime.shutdown_tasks(Duration::from_secs(1)).await;
836        assert!(report.is_healthy(), "{}", report.to_json());
837    }
838
839    #[tokio::test]
840    async fn cancellation_joins_only_operation_tasks() {
841        let runtime = RuntimeContext::from_current("operation-cancellation-test");
842        let owner = runtime.service_context("operations");
843        let first = OperationContext::without_deadline(TaskKind::Worker);
844        let second = OperationContext::without_deadline(TaskKind::Worker);
845
846        owner
847            .task_group()
848            .spawn_operation(&first, "first-operation", std::future::pending())
849            .expect("first operation should spawn");
850        owner
851            .task_group()
852            .spawn_operation(&second, "second-operation", std::future::pending())
853            .expect("second operation should spawn");
854
855        assert!(first
856            .cancel_and_wait(owner.task_group(), Duration::from_secs(1))
857            .await
858            .expect("first operation should use its bound owner"));
859        assert_eq!(first.active_task_count(), 0);
860        assert_eq!(second.active_task_count(), 1);
861        assert_eq!(
862            owner.task_group().lifecycle_state(),
863            crate::TaskGroupLifecycleState::Open
864        );
865
866        assert!(second
867            .cancel_and_wait(owner.task_group(), Duration::from_secs(1))
868            .await
869            .expect("second operation should use its bound owner"));
870        let report = runtime.shutdown_tasks(Duration::from_secs(1)).await;
871        assert!(report.is_healthy(), "{}", report.to_json());
872    }
873
874    #[tokio::test]
875    async fn wait_confirms_cancellation_of_an_overrunning_operation() {
876        struct DropMarker(Arc<AtomicBool>);
877
878        impl Drop for DropMarker {
879            fn drop(&mut self) {
880                self.0.store(true, Ordering::Release);
881            }
882        }
883
884        let runtime = RuntimeContext::from_current("operation-abort-confirmation-test");
885        let owner = runtime.service_context("operations");
886        let operation = OperationContext::without_deadline(TaskKind::Worker);
887        let started = Arc::new(AtomicBool::new(false));
888        let dropped = Arc::new(AtomicBool::new(false));
889
890        owner
891            .task_group()
892            .spawn_operation(&operation, "overrunning-operation", {
893                let started = Arc::clone(&started);
894                let dropped = Arc::clone(&dropped);
895                async move {
896                    let _marker = DropMarker(dropped);
897                    started.store(true, Ordering::Release);
898                    std::future::pending::<()>().await
899                }
900            })
901            .expect("operation task should spawn");
902
903        tokio::time::timeout(Duration::from_secs(1), async {
904            while !started.load(Ordering::Acquire) {
905                tokio::task::yield_now().await;
906            }
907        })
908        .await
909        .expect("operation task should start");
910
911        assert!(
912            !operation
913                .wait(owner.task_group(), Duration::from_millis(10))
914                .await
915                .expect("operation should use its bound owner"),
916            "an overrunning operation must not report a clean drain"
917        );
918        assert!(
919            dropped.load(Ordering::Acquire),
920            "wait should confirm cancellation before returning"
921        );
922        assert_eq!(operation.active_task_count(), 0);
923
924        let report = runtime.shutdown_tasks(Duration::from_secs(1)).await;
925        assert!(report.is_healthy(), "{}", report.to_json());
926    }
927
928    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
929    async fn wait_until_returns_at_its_deadline_without_confirming_the_abort() {
930        // Dropping the aborted future blocks until released, so a wait that
931        // returns before the release cannot have confirmed the abort.
932        struct BlockingDrop(Option<std::sync::mpsc::Receiver<()>>);
933
934        impl Drop for BlockingDrop {
935            fn drop(&mut self) {
936                if let Some(release) = self.0.take() {
937                    let _ = release.recv();
938                }
939            }
940        }
941
942        let runtime = RuntimeContext::from_current("operation-wait-until-test");
943        let owner = runtime.service_context("operations");
944        let operation = OperationContext::without_deadline(TaskKind::Worker);
945        let started = Arc::new(AtomicBool::new(false));
946        let (release_tx, release_rx) = std::sync::mpsc::channel();
947
948        owner
949            .task_group()
950            .spawn_operation(&operation, "slow-to-drop-operation", {
951                let started = Arc::clone(&started);
952                async move {
953                    let _guard = BlockingDrop(Some(release_rx));
954                    started.store(true, Ordering::Release);
955                    std::future::pending::<()>().await
956                }
957            })
958            .expect("operation task should spawn");
959        tokio::time::timeout(Duration::from_secs(1), async {
960            while !started.load(Ordering::Acquire) {
961                tokio::task::yield_now().await;
962            }
963        })
964        .await
965        .expect("operation task should start");
966
967        let deadline = ShutdownDeadline::after(Duration::from_millis(20));
968        assert!(!operation
969            .wait_until(owner.task_group(), deadline)
970            .await
971            .expect("operation should use its bound owner"));
972        assert_eq!(
973            operation.active_task_count(),
974            1,
975            "wait_until must not wait for the aborted future to be dropped"
976        );
977
978        release_tx.send(()).unwrap();
979        assert!(
980            operation
981                .wait(owner.task_group(), Duration::from_secs(5))
982                .await
983                .expect("operation should use its bound owner"),
984            "the aborted task settles once its future is dropped"
985        );
986        let report = runtime.shutdown_tasks(Duration::from_secs(1)).await;
987        assert!(report.is_healthy(), "{}", report.to_json());
988    }
989
990    #[tokio::test]
991    async fn cancel_and_wait_until_joins_a_cooperative_operation() {
992        let runtime = RuntimeContext::from_current("operation-cancel-until-test");
993        let owner = runtime.service_context("operations");
994        let operation = OperationContext::without_deadline(TaskKind::Worker);
995        owner
996            .task_group()
997            .spawn_operation(&operation, "pending-operation", std::future::pending())
998            .expect("operation task should spawn");
999
1000        assert!(operation
1001            .cancel_and_wait_until(owner.task_group(), ShutdownDeadline::after(Duration::from_secs(5)))
1002            .await
1003            .expect("operation should use its bound owner"));
1004        assert_eq!(operation.active_task_count(), 0);
1005        let report = runtime.shutdown_tasks(Duration::from_secs(1)).await;
1006        assert!(report.is_healthy(), "{}", report.to_json());
1007    }
1008
1009    #[tokio::test]
1010    async fn owner_shutdown_cancels_operation_tasks() {
1011        let runtime = RuntimeContext::from_current("operation-owner-shutdown-test");
1012        let owner = runtime.service_context("operations");
1013        let operation = OperationContext::without_deadline(TaskKind::Worker);
1014
1015        owner
1016            .task_group()
1017            .spawn_operation(&operation, "owned-operation", std::future::pending())
1018            .expect("operation task should spawn");
1019
1020        let report = runtime.shutdown_tasks(Duration::from_secs(1)).await;
1021
1022        assert!(report.is_healthy(), "{}", report.to_json());
1023        assert_eq!(operation.active_task_count(), 0);
1024    }
1025}