Skip to main content

rocketmq_runtime/
task_group.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::AtomicU64;
17use std::sync::atomic::AtomicU8;
18use std::sync::atomic::AtomicUsize;
19use std::sync::atomic::Ordering;
20use std::sync::Arc;
21use std::time::Duration;
22use std::time::Instant;
23
24use dashmap::mapref::entry::Entry;
25use futures::future::join_all;
26use futures::future::BoxFuture;
27use futures::future::FutureExt;
28use parking_lot::Mutex;
29use serde::Serialize;
30use tokio::sync::Notify;
31use tokio::task::AbortHandle;
32use tokio_util::sync::CancellationToken;
33use tokio_util::task::TaskTracker;
34
35use crate::blocking::BlockingTaskSnapshot;
36use crate::blocking::BlockingTaskTable;
37use crate::blocking::IsolatedBlockingTables;
38use crate::critical::CriticalFailureState;
39use crate::critical::CriticalRegistration;
40use crate::error::RuntimeError;
41use crate::error::RuntimeResult;
42use crate::handle::RuntimeHandle;
43use crate::operation::OperationContext;
44use crate::service_context::RootGroupPermit;
45use crate::shutdown_deadline::ShutdownDeadline;
46use crate::shutdown_report::ShutdownAnnotation;
47use crate::shutdown_report::ShutdownReport;
48use crate::shutdown_report::TaskSnapshot;
49
50mod completion;
51mod counted;
52mod diagnostics;
53mod registry;
54mod shutdown;
55mod submission;
56
57pub use counted::CountedTaskSet;
58
59use registry::ActiveTaskRegistry;
60use shutdown::ShutdownCoordinator;
61
62const STATE_OPEN: u8 = 0;
63const STATE_CLOSING: u8 = 1;
64const STATE_CLOSED: u8 = 2;
65const STATE_SHUTDOWN_COMPLETED: u8 = 3;
66const STATE_POISONED: u8 = 4;
67
68// Apply the large-future boundary before adding lifecycle and tracker wrappers. Waiting for
69// Tokio's spawn boundary leaves their by-value stack frames live during task submission.
70const MAX_INLINE_TASK_FUTURE_SIZE: usize = crate::stack::MAX_INLINE_SIZE;
71
72// A wrapped task future larger than this is boxed before it reaches Tokio. Tokio and the
73// tracker copy the future about five times over a task's life, which for a request task of
74// about 1.5 KB costs more than one allocation; a small future stays inline.
75const MAX_INLINE_TASK_CELL_SIZE: usize = 256;
76
77/// Identifies a task within the group that owns it.
78///
79/// The id records its owning group, so a group never mistakes another
80/// group's task for one of its own finished tasks. It serializes as the
81/// per-group sequence number; reports carry the group id separately.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
83#[serde(transparent)]
84pub struct TaskId {
85    sequence: u64,
86    #[serde(skip)]
87    group: TaskGroupId,
88}
89
90impl TaskId {
91    pub(crate) fn new(group: TaskGroupId, sequence: u64) -> Self {
92        Self { sequence, group }
93    }
94
95    /// Returns the sequence number of this task within its group.
96    pub fn as_u64(self) -> u64 {
97        self.sequence
98    }
99
100    /// Returns the id of the group that owns this task.
101    pub fn group_id(self) -> TaskGroupId {
102        self.group
103    }
104}
105
106/// Identifies a task group.
107///
108/// Ids are unique within the process: groups of different runtime owners or
109/// contexts never share an id.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
111pub struct TaskGroupId(u64);
112
113impl TaskGroupId {
114    /// Borrows this value as u64.
115    pub fn as_u64(self) -> u64 {
116        self.0
117    }
118
119    fn next() -> Self {
120        static NEXT_TASK_GROUP_ID: AtomicU64 = AtomicU64::new(1);
121        Self(NEXT_TASK_GROUP_ID.fetch_add(1, Ordering::Relaxed))
122    }
123}
124
125/// Name of a task, shown in shutdown reports and diagnostics.
126///
127/// A `&'static str` is stored without allocating; owned and shared strings
128/// are kept as they are.
129#[derive(Debug, Clone, PartialEq, Eq, Hash)]
130pub struct TaskName(TaskNameRepr);
131
132#[derive(Debug, Clone, PartialEq, Eq, Hash)]
133enum TaskNameRepr {
134    Static(&'static str),
135    Shared(Arc<str>),
136}
137
138impl TaskName {
139    /// Returns the name.
140    pub fn as_str(&self) -> &str {
141        match &self.0 {
142            TaskNameRepr::Static(name) => name,
143            TaskNameRepr::Shared(name) => name,
144        }
145    }
146}
147
148impl std::fmt::Display for TaskName {
149    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150        formatter.write_str(self.as_str())
151    }
152}
153
154impl From<&'static str> for TaskName {
155    fn from(name: &'static str) -> Self {
156        Self(TaskNameRepr::Static(name))
157    }
158}
159
160impl From<String> for TaskName {
161    fn from(name: String) -> Self {
162        Self(TaskNameRepr::Shared(Arc::from(name)))
163    }
164}
165
166impl From<&String> for TaskName {
167    fn from(name: &String) -> Self {
168        Self(TaskNameRepr::Shared(Arc::from(name.as_str())))
169    }
170}
171
172impl From<Arc<str>> for TaskName {
173    fn from(name: Arc<str>) -> Self {
174        Self(TaskNameRepr::Shared(name))
175    }
176}
177
178impl From<&Arc<str>> for TaskName {
179    fn from(name: &Arc<str>) -> Self {
180        Self(TaskNameRepr::Shared(Arc::clone(name)))
181    }
182}
183
184impl From<Box<str>> for TaskName {
185    fn from(name: Box<str>) -> Self {
186        Self(TaskNameRepr::Shared(Arc::from(name)))
187    }
188}
189
190impl From<std::borrow::Cow<'static, str>> for TaskName {
191    fn from(name: std::borrow::Cow<'static, str>) -> Self {
192        match name {
193            std::borrow::Cow::Borrowed(name) => Self::from(name),
194            std::borrow::Cow::Owned(name) => Self::from(name),
195        }
196    }
197}
198
199/// Counts of failures that a task group tree absorbs without an error.
200#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
201pub struct TaskGroupEventCounts {
202    /// Groups poisoned by a panicking task.
203    pub poisoned_groups: u64,
204    /// Component requests answered with an already closed group, because the
205    /// owner no longer admitted children.
206    pub closed_component_requests: u64,
207}
208
209/// State shared by every group of one tree: absorbed-failure counters and the
210/// isolated blocking executors whose work the tree owner reports.
211#[derive(Debug, Default)]
212struct TaskGroupTreeState {
213    poisoned_groups: AtomicU64,
214    closed_component_requests: AtomicU64,
215    isolated_blocking: IsolatedBlockingTables,
216}
217
218/// Identifies the task kind state.
219#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
220pub enum TaskKind {
221    /// Represents the service case.
222    Service,
223    /// Represents the worker case.
224    Worker,
225    /// Represents the scheduled driver case.
226    ScheduledDriver,
227    /// Represents the scheduled run case.
228    ScheduledRun,
229    /// Represents the blocking reaper case.
230    BlockingReaper,
231    /// Represents the shutdown case.
232    Shutdown,
233    /// Represents the other case.
234    Other,
235}
236
237impl TaskKind {
238    pub(crate) const ALL: [Self; 7] = [
239        Self::Service,
240        Self::Worker,
241        Self::ScheduledDriver,
242        Self::ScheduledRun,
243        Self::BlockingReaper,
244        Self::Shutdown,
245        Self::Other,
246    ];
247    pub(crate) const COUNT: usize = Self::ALL.len();
248
249    pub(crate) const fn index(self) -> usize {
250        match self {
251            Self::Service => 0,
252            Self::Worker => 1,
253            Self::ScheduledDriver => 2,
254            Self::ScheduledRun => 3,
255            Self::BlockingReaper => 4,
256            Self::Shutdown => 5,
257            Self::Other => 6,
258        }
259    }
260}
261
262/// Identifies the task state.
263#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
264pub enum TaskState {
265    /// Represents the queued case.
266    Queued,
267    /// Represents the running case.
268    Running,
269    /// Represents the completed case.
270    Completed,
271    /// Represents the cancelled case.
272    Cancelled,
273    /// Represents the aborted case.
274    Aborted,
275    /// Represents the panicked case.
276    Panicked,
277    /// Represents the leaked case.
278    Leaked,
279}
280
281/// Identifies the task result state.
282#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
283pub enum TaskResult {
284    /// Represents the completed case.
285    Completed,
286    /// Represents the cancelled case.
287    Cancelled,
288    /// Represents the aborted case.
289    Aborted,
290    /// Represents the panicked case.
291    Panicked,
292}
293
294/// Lifecycle state of a task group.
295///
296/// A shutdown moves a group through `Closing`, `Closed` and
297/// `ShutdownCompleted` in that order.
298#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
299pub enum TaskGroupLifecycleState {
300    /// Accepts tasks and child groups.
301    Open,
302    /// Admission is closed; cancellation has not yet reached every task.
303    Closing,
304    /// Admission is closed and cancellation was broadcast; owned work is draining.
305    Closed,
306    /// Shutdown finished and its report is published.
307    ShutdownCompleted,
308    /// A task panicked; the group rejects new work until it is shut down.
309    Poisoned,
310}
311
312impl TaskGroupLifecycleState {
313    /// Returns the failure reported to a submission rejected in this state.
314    ///
315    /// Callers use it only after observing a state other than `Open`.
316    pub(crate) fn admission_error(self, operation: crate::RuntimeOperation) -> RuntimeError {
317        match self {
318            Self::Poisoned => RuntimeError::poisoned(operation),
319            Self::Open | Self::Closing | Self::Closed | Self::ShutdownCompleted => RuntimeError::closed(operation),
320        }
321    }
322}
323
324/// Represents a task-group owner.
325///
326/// Cloning a task group keeps the same owner and cancellation token. Use
327/// [`Self::try_child`] when work needs an independently cancellable owner whose
328/// lifetime remains bounded by this parent.
329///
330/// Dropping a handle does not request cancellation or wait for cleanup.
331/// Active descendants retain their ancestor ownership path. Call
332/// [`Self::shutdown_until`] to close admission, cancel and await the subtree.
333/// A task panic poisons its group against new submissions; it remains owned
334/// and can still be shut down and reported.
335#[derive(Debug, Clone)]
336pub struct TaskGroup {
337    inner: Arc<TaskGroupInner>,
338}
339
340#[derive(Debug, Clone, Copy)]
341pub(crate) struct TaskKindDiagnostics {
342    pub(crate) kind: TaskKind,
343    pub(crate) active: usize,
344    pub(crate) long_running: usize,
345    pub(crate) max_elapsed: Duration,
346}
347
348#[derive(Debug, Clone)]
349pub(crate) struct TaskGroupDiagnostics {
350    pub(crate) local_task_count: usize,
351    pub(crate) group_count: usize,
352    pub(crate) task_count: usize,
353    pub(crate) task_kinds: Vec<TaskKindDiagnostics>,
354}
355
356/// Which population one bounded task detail was observed in.
357#[derive(Debug, Clone, Copy, PartialEq, Eq)]
358pub(crate) enum TaskDetailScope {
359    /// A task of the group the scan started from.
360    Local,
361    /// A task of one of its descendant groups.
362    Subtree,
363}
364
365/// One bounded task detail.
366///
367/// Deliberately carries no task identifier, task name, or group name: a detail
368/// list is served through an authenticated endpoint, and those values are
369/// caller-provided labels that diagnostics must not disclose.
370#[derive(Debug, Clone)]
371pub(crate) struct TaskDetail {
372    pub(crate) kind: TaskKind,
373    pub(crate) scope: TaskDetailScope,
374    pub(crate) elapsed: Duration,
375}
376
377/// The result of one bounded detail scan.
378#[derive(Debug, Clone, Default)]
379pub(crate) struct TaskDetailScan {
380    /// How many tasks were examined before the scan budget was reached.
381    pub(crate) scanned: usize,
382    /// Descendant registrations examined, including expired weak entries.
383    pub(crate) group_entries_scanned: usize,
384    /// The details that fit inside the output budget.
385    pub(crate) details: Vec<TaskDetail>,
386    /// Whether either budget stopped the scan short of every task.
387    pub(crate) truncated: bool,
388}
389
390#[derive(Debug)]
391struct TaskGroupInner {
392    id: TaskGroupId,
393    parent_id: Option<TaskGroupId>,
394    name: Arc<str>,
395    runtime: RuntimeHandle,
396    cancellation_token: CancellationToken,
397    tracker: TaskTracker,
398    registry: Arc<ActiveTaskRegistry>,
399    // A live descendant retains the entire ownership path. The parent's
400    // registry points back weakly, so dropping an idle subtree releases it.
401    parent: Option<Arc<TaskGroupInner>>,
402    tree: Arc<TaskGroupTreeState>,
403    // Component requests this group answered with a closed group.
404    closed_component_requests: AtomicUsize,
405    next_task_id: AtomicU64,
406    completed: AtomicUsize,
407    cancelled: AtomicUsize,
408    aborted: AtomicUsize,
409    panicked: AtomicUsize,
410    lifecycle: AtomicU8,
411    spawn_gate: Mutex<()>,
412    settlement_gate: Mutex<()>,
413    shutdown: ShutdownCoordinator,
414    // Sets whose tasks this group tracks without registering them; a shutdown that reaches its
415    // deadline stops their tasks as it aborts registered ones.
416    counted_sets: Mutex<Vec<std::sync::Weak<counted::CountedTaskSetInner>>>,
417}
418
419#[derive(Debug, Clone)]
420struct TaskMeta {
421    id: TaskId,
422    name: TaskName,
423    group_id: TaskGroupId,
424    group_name: Arc<str>,
425    kind: TaskKind,
426    state: TaskState,
427    started_at: Instant,
428    abort_handle: Option<AbortHandle>,
429    abort_requested: bool,
430    completion: Arc<TaskCompletion>,
431    /// Id of the operation that submitted the task, if any.
432    operation: Option<u64>,
433}
434
435#[derive(Debug)]
436struct TaskCompletion {
437    done: AtomicU8,
438    notify: Notify,
439}
440
441impl TaskCompletion {
442    fn new() -> Self {
443        Self {
444            done: AtomicU8::new(0),
445            notify: Notify::new(),
446        }
447    }
448
449    fn mark_done(&self) {
450        if self.done.swap(1, Ordering::AcqRel) == 0 {
451            self.notify.notify_waiters();
452        }
453    }
454
455    fn is_done(&self) -> bool {
456        self.done.load(Ordering::Acquire) != 0
457    }
458
459    async fn wait(&self) {
460        loop {
461            let notified = self.notify.notified();
462            if self.is_done() {
463                return;
464            }
465            notified.await;
466        }
467    }
468}
469
470impl TaskGroup {
471    /// Creates the root group of a runtime scope tree.
472    ///
473    /// Only [`RootServiceContext::new`](crate::RootServiceContext) can create
474    /// the permit, so every other group is a descendant of a root context.
475    pub(crate) fn root(name: Arc<str>, runtime: RuntimeHandle, _permit: RootGroupPermit) -> Self {
476        Self {
477            inner: Arc::new(TaskGroupInner::new(
478                TaskGroupId::next(),
479                None,
480                name,
481                runtime,
482                CancellationToken::new(),
483                None,
484                Arc::default(),
485            )),
486        }
487    }
488
489    /// Returns the id.
490    pub fn id(&self) -> TaskGroupId {
491        self.inner.id
492    }
493
494    pub(crate) fn runtime(&self) -> &RuntimeHandle {
495        &self.inner.runtime
496    }
497
498    /// Returns the parent id.
499    pub fn parent_id(&self) -> Option<TaskGroupId> {
500        self.inner.parent_id
501    }
502
503    /// Returns the name.
504    pub fn name(&self) -> &str {
505        &self.inner.name
506    }
507
508    /// Returns the cancellation token.
509    pub fn cancellation_token(&self) -> CancellationToken {
510        self.inner.cancellation_token.clone()
511    }
512
513    /// Returns the earliest absolute deadline installed by a shutdown owner.
514    pub fn shutdown_deadline(&self) -> Option<ShutdownDeadline> {
515        self.inner.shutdown.deadline()
516    }
517
518    /// Returns the lifecycle state.
519    pub fn lifecycle_state(&self) -> TaskGroupLifecycleState {
520        self.inner.lifecycle_state()
521    }
522
523    /// Returns the active count registered directly in this group.
524    ///
525    /// Descendants are excluded; subtree diagnostics aggregate them separately.
526    pub fn task_count(&self) -> usize {
527        self.inner.registry.tasks.len()
528    }
529
530    /// Returns the number of active component groups directly owned by this group.
531    pub fn component_count(&self) -> usize {
532        self.inner.registry.component_count()
533    }
534
535    /// Returns whether `task_id` was issued by this group, whether or not the
536    /// task is still registered.
537    pub fn owns_task(&self, task_id: TaskId) -> bool {
538        task_id.group_id() == self.inner.id
539    }
540
541    /// Returns whether `task_id` is a registered task of this group.
542    ///
543    /// Returns `false` for an id issued by another group.
544    pub fn contains_task(&self, task_id: TaskId) -> bool {
545        self.inner.registry.tasks.contains_key(&task_id)
546    }
547
548    /// Holds the settlement gate, so a finished task stays registered until
549    /// the guard is dropped.
550    #[cfg(test)]
551    pub(crate) fn lock_settlement_for_test(&self) -> parking_lot::MutexGuard<'_, ()> {
552        self.inner.settlement_gate.lock()
553    }
554
555    /// Returns the registered tasks of the operation with id `operation`.
556    pub(crate) fn operation_task_ids(&self, operation: u64) -> Vec<TaskId> {
557        self.inner
558            .registry
559            .tasks
560            .iter()
561            .filter(|entry| entry.operation == Some(operation))
562            .map(|entry| entry.id)
563            .collect()
564    }
565
566    /// Returns the counts of absorbed failures over this group's whole tree.
567    pub fn event_counts(&self) -> TaskGroupEventCounts {
568        let tree = &self.inner.tree;
569        TaskGroupEventCounts {
570            poisoned_groups: tree.poisoned_groups.load(Ordering::Relaxed),
571            closed_component_requests: tree.closed_component_requests.load(Ordering::Relaxed),
572        }
573    }
574
575    /// Keeps an isolated executor's task table visible to the owner of this
576    /// group's tree.
577    pub(crate) fn register_isolated_blocking(&self, table: &Arc<BlockingTaskTable>) {
578        self.inner.tree.isolated_blocking.register(table);
579    }
580
581    /// Returns the still-running count and task snapshots of the isolated
582    /// executors bound to this group's tree.
583    pub(crate) fn isolated_blocking_report(&self) -> (usize, Vec<BlockingTaskSnapshot>) {
584        self.inner.tree.isolated_blocking.report()
585    }
586
587    /// Creates a component, or a closed group once this owner stops admitting children.
588    ///
589    /// Callers keep a usable handle either way; the first closed answer per
590    /// owner is logged and every one is counted in [`Self::event_counts`].
591    pub(crate) fn component(&self, name: impl Into<Arc<str>>) -> Self {
592        let name = name.into();
593        self.try_child(name.clone()).unwrap_or_else(|_error| {
594            self.inner
595                .tree
596                .closed_component_requests
597                .fetch_add(1, Ordering::Relaxed);
598            if self.inner.closed_component_requests.fetch_add(1, Ordering::Relaxed) == 0 {
599                tracing::warn!(
600                    group = %self.inner.path(),
601                    component = %name,
602                    state = ?self.lifecycle_state(),
603                    "component requested after its owner stopped admitting children; returning a closed group"
604                );
605            }
606            self.closed_component(name)
607        })
608    }
609
610    /// Creates an independently cancellable child owned by this task group.
611    ///
612    /// Parent cancellation propagates to the returned child. Cancelling the
613    /// child does not cancel this parent or any sibling child. In contrast,
614    /// [`Clone::clone`] keeps the same owner and cancellation token.
615    ///
616    /// # Errors
617    ///
618    /// Returns a [`crate::RuntimeErrorKind::Closed`] failure after this owner
619    /// starts shutting down, or [`crate::RuntimeErrorKind::Poisoned`] after a
620    /// task panic poisoned it.
621    pub fn try_child(&self, name: impl Into<Arc<str>>) -> RuntimeResult<Self> {
622        let name = name.into();
623        let _spawn_guard = self.inner.spawn_gate.lock();
624        let state = self.inner.lifecycle_state();
625        if state != TaskGroupLifecycleState::Open {
626            return Err(state.admission_error(crate::RuntimeOperation::CreateTaskGroupChild));
627        }
628
629        let child = self.open_component(name);
630        self.inner
631            .registry
632            .register_component(child.id(), Arc::downgrade(&child.inner));
633        Ok(child)
634    }
635
636    fn open_component(&self, name: Arc<str>) -> Self {
637        Self {
638            inner: Arc::new(TaskGroupInner::new(
639                TaskGroupId::next(),
640                Some(self.inner.id),
641                name,
642                self.inner.runtime.clone(),
643                self.inner.cancellation_token.child_token(),
644                Some(self.inner.clone()),
645                Arc::clone(&self.inner.tree),
646            )),
647        }
648    }
649
650    fn closed_component(&self, name: Arc<str>) -> Self {
651        let child = self.open_component(name);
652        child.inner.tracker.close();
653        child.inner.cancellation_token.cancel();
654        child.inner.lifecycle.store(STATE_SHUTDOWN_COMPLETED, Ordering::Release);
655        child
656    }
657
658    /// Spawns the supplied task.
659    pub fn spawn<F>(&self, name: impl Into<TaskName>, kind: TaskKind, future: F) -> RuntimeResult<TaskId>
660    where
661        F: Future<Output = ()> + Send + 'static,
662    {
663        self.spawn_inner(name.into(), kind, future)
664    }
665
666    /// Spawns a task whose panic is recorded as a critical failure.
667    ///
668    /// Registration is explicit and opt-in: a task spawned the ordinary way keeps
669    /// today's behavior. A normal completion is not a failure here, because a
670    /// worker or job may legitimately return; use [`Self::spawn_critical_service`]
671    /// when returning before owner cancellation must be treated as one.
672    ///
673    /// # Errors
674    ///
675    /// Returns an error when this task group is shutting down or closed.
676    pub fn spawn_critical<F>(
677        &self,
678        name: impl Into<TaskName>,
679        kind: TaskKind,
680        failures: CriticalFailureState,
681        future: F,
682    ) -> RuntimeResult<TaskId>
683    where
684        F: Future<Output = ()> + Send + 'static,
685    {
686        let registration = CriticalRegistration {
687            failures,
688            task_kind: kind,
689            expects_until_cancelled: false,
690        };
691        let (task_id, join_handle) =
692            self.spawn_inner_with_handle(name.into(), kind, false, Some(registration), None, future)?;
693        drop(join_handle);
694        Ok(task_id)
695    }
696
697    /// Spawns a critical service that must run until its owner is cancelled.
698    ///
699    /// Both a panic and a return before owner cancellation are recorded as
700    /// critical failures. Owner cancellation is an expected exit and records
701    /// nothing, so an ordinary shutdown never triggers failure handling.
702    ///
703    /// # Errors
704    ///
705    /// Returns an error when this task group is shutting down or closed.
706    pub fn spawn_critical_service<F>(
707        &self,
708        name: impl Into<TaskName>,
709        failures: CriticalFailureState,
710        future: F,
711    ) -> RuntimeResult<TaskId>
712    where
713        F: Future<Output = ()> + Send + 'static,
714    {
715        let registration = CriticalRegistration {
716            failures,
717            task_kind: TaskKind::Service,
718            expects_until_cancelled: true,
719        };
720        let (task_id, join_handle) =
721            self.spawn_inner_with_handle(name.into(), TaskKind::Service, false, Some(registration), None, future)?;
722        drop(join_handle);
723        Ok(task_id)
724    }
725
726    /// Spawns a service that owns its shutdown protocol.
727    ///
728    /// The service remains tracked during owner shutdown, but its future must
729    /// observe an appropriate cancellation signal and perform any required
730    /// ordered cleanup itself. Use [`Self::spawn_cancellable_service`] when it
731    /// is safe to drop the service future as soon as its owner is cancelled.
732    pub fn spawn_service<F>(&self, name: impl Into<TaskName>, future: F) -> RuntimeResult<TaskId>
733    where
734        F: Future<Output = ()> + Send + 'static,
735    {
736        self.spawn(name, TaskKind::Service, future)
737    }
738
739    /// Spawns a service that exits when either its future completes or its owner is cancelled.
740    ///
741    /// Owner cancellation drops `future`; services that require an ordered
742    /// cleanup sequence must use [`Self::spawn_service`] and observe a
743    /// cancellation token explicitly.
744    ///
745    /// # Errors
746    ///
747    /// Returns an error when this task group is shutting down or closed.
748    pub fn spawn_cancellable_service<F>(&self, name: impl Into<TaskName>, future: F) -> RuntimeResult<TaskId>
749    where
750        F: Future<Output = ()> + Send + 'static,
751    {
752        if std::mem::size_of::<F>() > MAX_INLINE_TASK_FUTURE_SIZE {
753            self.spawn_cancellable_service_inner(name.into(), Box::pin(future))
754        } else {
755            self.spawn_cancellable_service_inner(name.into(), future)
756        }
757    }
758
759    fn spawn_cancellable_service_inner<F>(&self, name: TaskName, future: F) -> RuntimeResult<TaskId>
760    where
761        F: Future<Output = ()> + Send + 'static,
762    {
763        let owner_cancellation = self.cancellation_token();
764        self.spawn_service(name, async move {
765            tokio::select! {
766                biased;
767                _ = owner_cancellation.cancelled() => {}
768                _ = future => {}
769            }
770        })
771    }
772
773    /// Spawns work for a bounded operation under this fixed component owner.
774    ///
775    /// The operation context supplies task classification, cancellation, and
776    /// an optional deadline without creating a child task group.
777    pub fn spawn_operation<F>(
778        &self,
779        context: &OperationContext,
780        name: impl Into<TaskName>,
781        future: F,
782    ) -> RuntimeResult<TaskId>
783    where
784        F: Future<Output = ()> + Send + 'static,
785    {
786        self.spawn_operation_with_cancellation(context, name.into(), future, Some(self.cancellation_token()))
787    }
788
789    /// Spawns accepted operation work that must drain during owner shutdown.
790    ///
791    /// Unlike [`Self::spawn_operation`], owner cancellation does not drop the
792    /// supplied future. The operation context still enforces its own
793    /// cancellation and deadline, and [`OperationContext::wait`] aborts work
794    /// that outlives the caller's drain deadline. This is intended for work
795    /// that has already been accepted and whose ordered shutdown protocol is
796    /// owned by a tracked service.
797    pub fn spawn_draining_operation<F>(
798        &self,
799        context: &OperationContext,
800        name: impl Into<TaskName>,
801        future: F,
802    ) -> RuntimeResult<TaskId>
803    where
804        F: Future<Output = ()> + Send + 'static,
805    {
806        self.spawn_operation_with_cancellation(context, name.into(), future, None)
807    }
808
809    fn spawn_operation_with_cancellation<F>(
810        &self,
811        context: &OperationContext,
812        name: TaskName,
813        future: F,
814        owner_cancellation: Option<CancellationToken>,
815    ) -> RuntimeResult<TaskId>
816    where
817        F: Future<Output = ()> + Send + 'static,
818    {
819        if std::mem::size_of::<F>() > MAX_INLINE_TASK_FUTURE_SIZE {
820            self.spawn_operation_inner(context, name, Box::pin(future), owner_cancellation)
821        } else {
822            self.spawn_operation_inner(context, name, future, owner_cancellation)
823        }
824    }
825
826    fn spawn_operation_inner<F>(
827        &self,
828        context: &OperationContext,
829        name: TaskName,
830        future: F,
831        owner_cancellation: Option<CancellationToken>,
832    ) -> RuntimeResult<TaskId>
833    where
834        F: Future<Output = ()> + Send + 'static,
835    {
836        let registration = {
837            let _operation_spawn_guard = context.spawn_guard();
838            context.prepare_spawn(self.id())?
839        };
840        let guard = registration.guard();
841        let execution = crate::operation::OperationExecution::new(future, guard, context.clone(), owner_cancellation);
842        let task_id = self.spawn_operation_task(name, context.task_kind(), context.id(), execution.run())?;
843        registration.finish_registration();
844        Ok(task_id)
845    }
846
847    /// Spawns with handle.
848    pub fn spawn_with_handle<F>(
849        &self,
850        name: impl Into<TaskName>,
851        kind: TaskKind,
852        future: F,
853    ) -> RuntimeResult<(TaskId, tokio::task::JoinHandle<()>)>
854    where
855        F: Future<Output = ()> + Send + 'static,
856    {
857        self.spawn_inner_with_handle(name.into(), kind, true, None, None, future)
858    }
859
860    /// Spawns service with handle.
861    pub fn spawn_service_with_handle<F>(
862        &self,
863        name: impl Into<TaskName>,
864        future: F,
865    ) -> RuntimeResult<(TaskId, tokio::task::JoinHandle<()>)>
866    where
867        F: Future<Output = ()> + Send + 'static,
868    {
869        self.spawn_with_handle(name, TaskKind::Service, future)
870    }
871
872    /// Signals cancellation to this group and its descendants without waiting.
873    ///
874    /// The signal does not close submission admission or confirm task
875    /// destruction. Services must observe it and perform their own cleanup.
876    /// Use [`Self::shutdown_until`] for the complete shutdown boundary.
877    pub fn cancel(&self) {
878        self.inner.cancellation_token.cancel();
879    }
880
881    /// Requests cancellation of an active task without waiting for destruction.
882    ///
883    /// Returns whether the task was still registered. Its record and resources
884    /// remain owned until the executor destroys the future. An id issued by
885    /// another group is never registered here, so it returns `false`.
886    pub fn abort_task(&self, task_id: TaskId) -> bool {
887        self.abort_task_inner(task_id).is_some()
888    }
889
890    /// Requests cancellation and waits until the user future is destroyed.
891    ///
892    /// Returns `false` if the task was already absent, was issued by another
893    /// group, or the wait expired. A timeout does not remove the task's record
894    /// or confirm cancellation.
895    pub async fn abort_task_and_wait(&self, task_id: TaskId, timeout: Duration) -> bool {
896        self.abort_task_until(task_id, ShutdownDeadline::after(timeout)).await
897    }
898
899    pub(crate) async fn abort_task_until(&self, task_id: TaskId, deadline: ShutdownDeadline) -> bool {
900        let Some(completion) = self.abort_task_inner(task_id) else {
901            return false;
902        };
903
904        if completion.is_done() {
905            return true;
906        }
907
908        if deadline.is_expired() {
909            return false;
910        }
911
912        tokio::time::timeout_at(deadline.instant().into(), completion.wait())
913            .await
914            .is_ok()
915    }
916
917    /// Asynchronously waits for a local task's future to be destroyed.
918    ///
919    /// Returns `true` when this group's task is already absent, including after
920    /// earlier completion, and `false` when a registered task outlives the
921    /// timeout. Unlike [`Self::abort_task_and_wait`], absence is treated as
922    /// success. An id issued by another group returns `false` immediately:
923    /// this group cannot tell whether that task finished; see
924    /// [`Self::owns_task`]. This does not request cancellation or prove
925    /// business-level success.
926    pub async fn wait_task(&self, task_id: TaskId, timeout: Duration) -> bool {
927        self.wait_task_until(task_id, ShutdownDeadline::after(timeout)).await
928    }
929
930    pub(crate) async fn wait_task_until(&self, task_id: TaskId, deadline: ShutdownDeadline) -> bool {
931        if !self.owns_task(task_id) {
932            return false;
933        }
934        let Some(completion) = self
935            .inner
936            .registry
937            .tasks
938            .get(&task_id)
939            .map(|meta| meta.completion.clone())
940        else {
941            return true;
942        };
943
944        if completion.is_done() {
945            return true;
946        }
947
948        if deadline.is_expired() {
949            return false;
950        }
951
952        tokio::time::timeout_at(deadline.instant().into(), completion.wait())
953            .await
954            .is_ok()
955    }
956
957    /// Closes and asynchronously drains this subtree within a relative budget.
958    ///
959    /// The budget is converted once to an absolute deadline. See
960    /// [`Self::shutdown_until`] for repeated calls and completion semantics.
961    pub fn shutdown(&self, timeout: Duration) -> BoxFuture<'_, ShutdownReport> {
962        self.shutdown_until(ShutdownDeadline::after(timeout))
963    }
964
965    /// Closes admission, signals cancellation and asynchronously awaits owned work.
966    ///
967    /// All children share the absolute deadline. A later call can tighten but
968    /// cannot extend it. Tasks that do not finish in time are asked to abort;
969    /// the report distinguishes confirmed destruction from remaining work.
970    /// Once published, the report is retained and returned by subsequent calls.
971    pub fn shutdown_until(&self, deadline: ShutdownDeadline) -> BoxFuture<'_, ShutdownReport> {
972        self.tighten_shutdown_deadline(deadline);
973        async move {
974            let report = self
975                .inner
976                .shutdown
977                .report
978                .get_or_init(|| async { self.shutdown_inner().await })
979                .await;
980            self.inner.shutdown.report_ready.notify_waiters();
981            report.clone()
982        }
983        .boxed()
984    }
985
986    /// Requests immediate shutdown without waiting for future destruction.
987    ///
988    /// The retained report may contain unconfirmed remaining work even when
989    /// cancellation completes shortly afterward. A later graceful call returns
990    /// that same report; it does not turn this call into an awaited drain.
991    pub fn shutdown_now(&self) -> ShutdownReport {
992        if let Some(report) = self.inner.shutdown.report.get() {
993            return report.clone();
994        }
995
996        let report = self.shutdown_now_inner();
997        let _ = self.inner.shutdown.report.set(report.clone());
998        self.inner.shutdown.report_ready.notify_waiters();
999        report
1000    }
1001
1002    fn tighten_shutdown_deadline(&self, deadline: ShutdownDeadline) {
1003        let mut pending = vec![(self.clone(), deadline)];
1004        while let Some((group, deadline)) = pending.pop() {
1005            let installed = group.inner.shutdown.tighten(deadline);
1006            pending.extend(
1007                group
1008                    .inner
1009                    .registry
1010                    .components_snapshot()
1011                    .into_iter()
1012                    .map(|child| (child, installed)),
1013            );
1014        }
1015    }
1016
1017    async fn shutdown_inner(&self) -> ShutdownReport {
1018        let started_at = Instant::now();
1019        let deadline = self
1020            .inner
1021            .shutdown
1022            .deadline()
1023            .unwrap_or_else(|| ShutdownDeadline::after(Duration::ZERO));
1024        // Retain the entire accepted subtree before propagating cancellation.
1025        // A fast-finishing leaf must not erase its ancestors and outcomes while
1026        // shutdown is still walking the tree.
1027        let descendants = self.close_admission_tree();
1028        // Reapply after sealing admission, including children created between
1029        // the initial deadline traversal and the admission traversal.
1030        self.tighten_shutdown_deadline(deadline);
1031        self.inner.cancellation_token.cancel();
1032        self.mark_closed(&descendants);
1033        // Poll every scope at one level. A scope observes child reports via
1034        // notifications rather than recursively polling their shutdown futures.
1035        let children = join_all(descendants.iter().map(|group| async move {
1036            group.inner.shutdown.report.get_or_init(|| group.shutdown_one()).await;
1037            group.inner.shutdown.report_ready.notify_waiters();
1038        }));
1039        let (_, mut report) = tokio::join!(children, self.shutdown_one());
1040        report.elapsed = started_at.elapsed();
1041        report
1042    }
1043
1044    async fn shutdown_one(&self) -> ShutdownReport {
1045        let started_at = Instant::now();
1046        let children = self.inner.registry.components_snapshot();
1047
1048        let child_reports = async {
1049            join_all(
1050                children
1051                    .into_iter()
1052                    .map(|child| async move { child.inner.shutdown.wait_report().await.clone() }),
1053            )
1054            .await
1055        };
1056        // On a deadline, returns the abort count seen just before this
1057        // shutdown aborted the remaining tasks.
1058        let tracked_shutdown = async {
1059            if self.inner.shutdown.run_until(self.inner.tracker.wait()).await.is_err() {
1060                let aborted_before_timeout = self.inner.aborted.load(Ordering::Acquire);
1061                self.abort_tracked_tasks();
1062                let _ = self.inner.shutdown.run_until(self.inner.tracker.wait()).await;
1063                Some(aborted_before_timeout)
1064            } else {
1065                None
1066            }
1067        };
1068
1069        let (child_reports, aborted_before_timeout) = tokio::join!(child_reports, tracked_shutdown);
1070
1071        let mut report = ShutdownReport::new(self.inner.name.to_string(), started_at.elapsed());
1072        report.children = child_reports;
1073        self.record_task_outcomes(&mut report);
1074
1075        if let Some(aborted_before_timeout) = aborted_before_timeout {
1076            // Aborts requested earlier through `abort_task` are not timeouts.
1077            let aborted_by_timeout = report.aborted.saturating_sub(aborted_before_timeout);
1078            if aborted_by_timeout > 0 {
1079                report.annotations.push(ShutdownAnnotation::new(format!(
1080                    "confirmed cancellation of {aborted_by_timeout} aborted tasks"
1081                )));
1082            }
1083            report.timed_out = aborted_by_timeout + report.leaked;
1084        }
1085
1086        self.inner.lifecycle.store(STATE_SHUTDOWN_COMPLETED, Ordering::Release);
1087        report
1088    }
1089
1090    fn close_admission_tree(&self) -> Vec<TaskGroup> {
1091        let mut retained = Vec::new();
1092        let mut pending = vec![self.clone()];
1093        while let Some(group) = pending.pop() {
1094            {
1095                let _spawn_guard = group.inner.spawn_gate.lock();
1096                // Admission is sealed under the spawn gate. `Closed` follows
1097                // once cancellation has reached the whole tree.
1098                let _ = group
1099                    .inner
1100                    .lifecycle
1101                    .fetch_update(Ordering::AcqRel, Ordering::Acquire, |state| {
1102                        matches!(state, STATE_OPEN | STATE_POISONED).then_some(STATE_CLOSING)
1103                    });
1104                group.inner.tracker.close();
1105                pending.extend(group.inner.registry.components_snapshot());
1106            }
1107            if group.id() != self.id() {
1108                retained.push(group);
1109            }
1110        }
1111        // Descendants precede parents for immediate report assembly.
1112        retained.reverse();
1113        retained
1114    }
1115
1116    /// Moves the groups closed by this shutdown from `Closing` to `Closed`.
1117    ///
1118    /// Called after cancellation was broadcast, so a group observed as
1119    /// `Closed` has a cancelled token. Readers already see `Closed` once the
1120    /// token is cancelled; this stores the state they derive.
1121    fn mark_closed(&self, descendants: &[TaskGroup]) {
1122        for group in descendants.iter().chain(std::iter::once(self)) {
1123            let _ = group.inner.lifecycle.compare_exchange(
1124                STATE_CLOSING,
1125                STATE_CLOSED,
1126                Ordering::AcqRel,
1127                Ordering::Acquire,
1128            );
1129        }
1130    }
1131
1132    fn shutdown_now_inner(&self) -> ShutdownReport {
1133        let started_at = Instant::now();
1134        let descendants = self.close_admission_tree();
1135        self.inner.cancellation_token.cancel();
1136        self.mark_closed(&descendants);
1137        let mut reports = std::collections::HashMap::new();
1138        for group in &descendants {
1139            let children = group
1140                .inner
1141                .registry
1142                .components_snapshot()
1143                .into_iter()
1144                .filter_map(|child| reports.remove(&child.id()))
1145                .collect();
1146            let report = if let Some(report) = group.inner.shutdown.report.get() {
1147                report.clone()
1148            } else {
1149                let report = group.shutdown_now_one(children);
1150                let _ = group.inner.shutdown.report.set(report.clone());
1151                group.inner.shutdown.report_ready.notify_waiters();
1152                report
1153            };
1154            reports.insert(group.id(), report);
1155        }
1156        let children = self
1157            .inner
1158            .registry
1159            .components_snapshot()
1160            .into_iter()
1161            .filter_map(|child| reports.remove(&child.id()))
1162            .collect();
1163        let mut report = self.shutdown_now_one(children);
1164        report.elapsed = started_at.elapsed();
1165        report
1166    }
1167
1168    fn shutdown_now_one(&self, child_reports: Vec<ShutdownReport>) -> ShutdownReport {
1169        let started_at = Instant::now();
1170
1171        let aborted_before = self.inner.aborted.load(Ordering::Acquire);
1172        self.abort_tracked_tasks();
1173
1174        let mut report = ShutdownReport::new(self.inner.name.to_string(), started_at.elapsed());
1175        report.children = child_reports;
1176        self.record_task_outcomes(&mut report);
1177
1178        let aborted_now = report.aborted.saturating_sub(aborted_before);
1179        if aborted_now > 0 {
1180            report.annotations.push(ShutdownAnnotation::new(format!(
1181                "confirmed cancellation of {aborted_now} aborted tasks"
1182            )));
1183        }
1184
1185        self.inner.lifecycle.store(STATE_SHUTDOWN_COMPLETED, Ordering::Release);
1186        report
1187    }
1188
1189    fn abort_tracked_tasks(&self) {
1190        for mut entry in self.inner.registry.tasks.iter_mut() {
1191            entry.abort_requested = true;
1192            if let Some(abort_handle) = &entry.abort_handle {
1193                abort_handle.abort();
1194            }
1195        }
1196        let stopped = counted::stop_counted_sets(&self.inner.counted_sets);
1197        self.inner.aborted.fetch_add(stopped, Ordering::AcqRel);
1198    }
1199
1200    fn record_task_outcomes(&self, report: &mut ShutdownReport) {
1201        // Snapshot counters and active records together: a concurrent finalizer
1202        // must not make a task disappear between these two observations.
1203        let _settlement = self.inner.settlement_gate.lock();
1204        report.completed = self.inner.completed.load(Ordering::Relaxed);
1205        report.cancelled = self.inner.cancelled.load(Ordering::Relaxed);
1206        report.panicked = self.inner.panicked.load(Ordering::Relaxed);
1207        report.aborted = self.inner.aborted.load(Ordering::Relaxed);
1208        let closed_components = self.inner.closed_component_requests.load(Ordering::Relaxed);
1209        if closed_components > 0 {
1210            report.annotations.push(ShutdownAnnotation::new(format!(
1211                "{closed_components} component requests after admission closed received closed groups"
1212            )));
1213        }
1214        let mut requested = 0;
1215        for entry in self.inner.registry.tasks.iter() {
1216            requested += usize::from(entry.abort_requested);
1217            report.leaked += 1;
1218            report.push_remaining_task(entry.snapshot(TaskState::Leaked));
1219        }
1220        if requested > 0 {
1221            report.annotations.push(ShutdownAnnotation::new(format!(
1222                "abort requested for {requested} tasks whose destruction is not yet confirmed"
1223            )));
1224        }
1225    }
1226}
1227
1228impl TaskGroupInner {
1229    fn new(
1230        id: TaskGroupId,
1231        parent_id: Option<TaskGroupId>,
1232        name: Arc<str>,
1233        runtime: RuntimeHandle,
1234        cancellation_token: CancellationToken,
1235        parent: Option<Arc<TaskGroupInner>>,
1236        tree: Arc<TaskGroupTreeState>,
1237    ) -> Self {
1238        Self {
1239            id,
1240            parent_id,
1241            name,
1242            runtime,
1243            cancellation_token,
1244            tracker: TaskTracker::new(),
1245            registry: Arc::new(ActiveTaskRegistry::new()),
1246            parent,
1247            tree,
1248            closed_component_requests: AtomicUsize::new(0),
1249            next_task_id: AtomicU64::new(1),
1250            completed: AtomicUsize::new(0),
1251            cancelled: AtomicUsize::new(0),
1252            aborted: AtomicUsize::new(0),
1253            panicked: AtomicUsize::new(0),
1254            lifecycle: AtomicU8::new(STATE_OPEN),
1255            spawn_gate: Mutex::new(()),
1256            settlement_gate: Mutex::new(()),
1257            shutdown: ShutdownCoordinator::new(),
1258            counted_sets: Mutex::new(Vec::new()),
1259        }
1260    }
1261
1262    fn lifecycle_state(&self) -> TaskGroupLifecycleState {
1263        match self.lifecycle.load(Ordering::Acquire) {
1264            STATE_OPEN => TaskGroupLifecycleState::Open,
1265            // Shutdown cancels the whole tree before `mark_closed` stores
1266            // `Closed`. Deriving `Closed` from the cancelled token closes that
1267            // window, so a task woken by the cancellation on another worker
1268            // never observes `Closing`.
1269            STATE_CLOSING if self.cancellation_token.is_cancelled() => TaskGroupLifecycleState::Closed,
1270            STATE_CLOSING => TaskGroupLifecycleState::Closing,
1271            STATE_CLOSED => TaskGroupLifecycleState::Closed,
1272            STATE_SHUTDOWN_COMPLETED => TaskGroupLifecycleState::ShutdownCompleted,
1273            _ => TaskGroupLifecycleState::Poisoned,
1274        }
1275    }
1276
1277    fn mark_poisoned_if_open(&self) {
1278        if self
1279            .lifecycle
1280            .compare_exchange(STATE_OPEN, STATE_POISONED, Ordering::AcqRel, Ordering::Acquire)
1281            .is_ok()
1282        {
1283            self.tree.poisoned_groups.fetch_add(1, Ordering::Relaxed);
1284            tracing::error!(
1285                group = %self.path(),
1286                "task group poisoned by a panicking task; it no longer admits work"
1287            );
1288        }
1289    }
1290
1291    /// Returns the names from the root to this group, separated by `/`.
1292    fn path(&self) -> String {
1293        let mut names = vec![self.name.as_ref()];
1294        let mut parent = self.parent.as_deref();
1295        while let Some(group) = parent {
1296            names.push(group.name.as_ref());
1297            parent = group.parent.as_deref();
1298        }
1299        names.reverse();
1300        names.join("/")
1301    }
1302
1303    fn finish_task(&self, task_id: TaskId, result: TaskResult) {
1304        let _settlement = self.settlement_gate.lock();
1305        let Entry::Occupied(entry) = self.registry.tasks.entry(task_id) else {
1306            return;
1307        };
1308
1309        match result {
1310            TaskResult::Completed => {
1311                self.completed.fetch_add(1, Ordering::Relaxed);
1312            }
1313            TaskResult::Cancelled => {
1314                self.cancelled.fetch_add(1, Ordering::Relaxed);
1315            }
1316            TaskResult::Panicked => {
1317                self.panicked.fetch_add(1, Ordering::Relaxed);
1318                self.mark_poisoned_if_open();
1319            }
1320            TaskResult::Aborted => {
1321                self.aborted.fetch_add(1, Ordering::Relaxed);
1322            }
1323        }
1324        // A missing record is also treated as finished by wait_task. Publish
1325        // the counters before removing it, after user resources were dropped.
1326        self.registry.remove_task_detail(task_id);
1327        entry.remove();
1328    }
1329}
1330
1331impl Drop for TaskGroupInner {
1332    fn drop(&mut self) {
1333        let mut parent = self.parent.take();
1334        let mut child_id = self.id;
1335        while let Some(ancestor) = parent {
1336            ancestor.registry.unregister_component(child_id);
1337            let Some(mut ancestor) = Arc::into_inner(ancestor) else {
1338                break;
1339            };
1340            child_id = ancestor.id;
1341            parent = ancestor.parent.take();
1342            // Its parent is now detached, so dropping this owned node does
1343            // not recursively destroy the rest of a long ownership chain.
1344        }
1345    }
1346}
1347
1348impl TaskMeta {
1349    fn snapshot(&self, override_state: TaskState) -> TaskSnapshot {
1350        TaskSnapshot {
1351            id: self.id,
1352            name: self.name.to_string(),
1353            group_id: self.group_id,
1354            group_name: self.group_name.to_string(),
1355            kind: self.kind,
1356            state: override_state,
1357            elapsed: self.started_at.elapsed(),
1358        }
1359    }
1360}
1361
1362#[cfg(test)]
1363mod tests {
1364    use super::*;
1365    use crate::RuntimeContext;
1366
1367    #[tokio::test]
1368    async fn a_closing_group_reports_closed_as_soon_as_its_token_is_cancelled() {
1369        let context = RuntimeContext::from_current("closing-then-cancelled");
1370        let group = context.service_context("owner").task_group().clone();
1371        let child = group.try_child("child").unwrap();
1372
1373        // Replay the shutdown steps one at a time, stopping in the window
1374        // between the cancellation broadcast and `mark_closed`.
1375        let descendants = group.close_admission_tree();
1376        assert_eq!(group.lifecycle_state(), TaskGroupLifecycleState::Closing);
1377        assert_eq!(child.lifecycle_state(), TaskGroupLifecycleState::Closing);
1378        group.inner.cancellation_token.cancel();
1379        assert_eq!(group.lifecycle_state(), TaskGroupLifecycleState::Closed);
1380        assert_eq!(child.lifecycle_state(), TaskGroupLifecycleState::Closed);
1381
1382        group.mark_closed(&descendants);
1383        assert_eq!(group.lifecycle_state(), TaskGroupLifecycleState::Closed);
1384        assert!(group.shutdown(Duration::from_secs(1)).await.is_healthy());
1385        assert_eq!(group.lifecycle_state(), TaskGroupLifecycleState::ShutdownCompleted);
1386    }
1387
1388    #[tokio::test]
1389    async fn the_task_wrapper_adds_little_to_the_size_of_the_future_it_runs() {
1390        let context = RuntimeContext::from_current("task-wrapper-size");
1391        let group = context.service_context("owner").task_group().clone();
1392        let payload = [7u8; 512];
1393        let future = async move {
1394            std::hint::black_box(&payload);
1395        };
1396        let future_size = std::mem::size_of_val(&future);
1397        let wrapped = completion::TaskExecution::new(
1398            future,
1399            group.inner.clone(),
1400            TaskId::new(group.inner.id, 0),
1401            Arc::new(TaskCompletion::new()),
1402            false,
1403            None,
1404        )
1405        .run();
1406
1407        // As an `async fn` the wrapper kept both its argument and the future moved out of
1408        // it, about three times the size of the future it runs.
1409        assert!(
1410            std::mem::size_of_val(&wrapped) <= future_size + 128,
1411            "wrapper {} bytes around a {future_size}-byte future",
1412            std::mem::size_of_val(&wrapped)
1413        );
1414        drop(wrapped);
1415    }
1416}