1use 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
68const MAX_INLINE_TASK_FUTURE_SIZE: usize = crate::stack::MAX_INLINE_SIZE;
71
72const MAX_INLINE_TASK_CELL_SIZE: usize = 256;
76
77#[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 pub fn as_u64(self) -> u64 {
97 self.sequence
98 }
99
100 pub fn group_id(self) -> TaskGroupId {
102 self.group
103 }
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
111pub struct TaskGroupId(u64);
112
113impl TaskGroupId {
114 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#[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 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
201pub struct TaskGroupEventCounts {
202 pub poisoned_groups: u64,
204 pub closed_component_requests: u64,
207}
208
209#[derive(Debug, Default)]
212struct TaskGroupTreeState {
213 poisoned_groups: AtomicU64,
214 closed_component_requests: AtomicU64,
215 isolated_blocking: IsolatedBlockingTables,
216}
217
218#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
220pub enum TaskKind {
221 Service,
223 Worker,
225 ScheduledDriver,
227 ScheduledRun,
229 BlockingReaper,
231 Shutdown,
233 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
264pub enum TaskState {
265 Queued,
267 Running,
269 Completed,
271 Cancelled,
273 Aborted,
275 Panicked,
277 Leaked,
279}
280
281#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
283pub enum TaskResult {
284 Completed,
286 Cancelled,
288 Aborted,
290 Panicked,
292}
293
294#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
299pub enum TaskGroupLifecycleState {
300 Open,
302 Closing,
304 Closed,
306 ShutdownCompleted,
308 Poisoned,
310}
311
312impl TaskGroupLifecycleState {
313 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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
358pub(crate) enum TaskDetailScope {
359 Local,
361 Subtree,
363}
364
365#[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#[derive(Debug, Clone, Default)]
379pub(crate) struct TaskDetailScan {
380 pub(crate) scanned: usize,
382 pub(crate) group_entries_scanned: usize,
384 pub(crate) details: Vec<TaskDetail>,
386 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 parent: Option<Arc<TaskGroupInner>>,
402 tree: Arc<TaskGroupTreeState>,
403 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 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 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 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 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 pub fn parent_id(&self) -> Option<TaskGroupId> {
500 self.inner.parent_id
501 }
502
503 pub fn name(&self) -> &str {
505 &self.inner.name
506 }
507
508 pub fn cancellation_token(&self) -> CancellationToken {
510 self.inner.cancellation_token.clone()
511 }
512
513 pub fn shutdown_deadline(&self) -> Option<ShutdownDeadline> {
515 self.inner.shutdown.deadline()
516 }
517
518 pub fn lifecycle_state(&self) -> TaskGroupLifecycleState {
520 self.inner.lifecycle_state()
521 }
522
523 pub fn task_count(&self) -> usize {
527 self.inner.registry.tasks.len()
528 }
529
530 pub fn component_count(&self) -> usize {
532 self.inner.registry.component_count()
533 }
534
535 pub fn owns_task(&self, task_id: TaskId) -> bool {
538 task_id.group_id() == self.inner.id
539 }
540
541 pub fn contains_task(&self, task_id: TaskId) -> bool {
545 self.inner.registry.tasks.contains_key(&task_id)
546 }
547
548 #[cfg(test)]
551 pub(crate) fn lock_settlement_for_test(&self) -> parking_lot::MutexGuard<'_, ()> {
552 self.inner.settlement_gate.lock()
553 }
554
555 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 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 pub(crate) fn register_isolated_blocking(&self, table: &Arc<BlockingTaskTable>) {
578 self.inner.tree.isolated_blocking.register(table);
579 }
580
581 pub(crate) fn isolated_blocking_report(&self) -> (usize, Vec<BlockingTaskSnapshot>) {
584 self.inner.tree.isolated_blocking.report()
585 }
586
587 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 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 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 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 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 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 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 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 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 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 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 pub fn cancel(&self) {
878 self.inner.cancellation_token.cancel();
879 }
880
881 pub fn abort_task(&self, task_id: TaskId) -> bool {
887 self.abort_task_inner(task_id).is_some()
888 }
889
890 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 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 pub fn shutdown(&self, timeout: Duration) -> BoxFuture<'_, ShutdownReport> {
962 self.shutdown_until(ShutdownDeadline::after(timeout))
963 }
964
965 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 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 let descendants = self.close_admission_tree();
1028 self.tighten_shutdown_deadline(deadline);
1031 self.inner.cancellation_token.cancel();
1032 self.mark_closed(&descendants);
1033 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 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 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 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 retained.reverse();
1113 retained
1114 }
1115
1116 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 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 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 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 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 }
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 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 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}