incular-runtime 0.1.0

Application runtime and scheduling foundations for Incular
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
//! Tokio-backed application work and the UI-thread completion bridge.
//!
//! Tokio owns every general future, timer, and blocking job. This module owns
//! only Incular-specific lifetime metadata and a bounded message drain into the
//! retained UI runtime; it never polls a user future itself.

use std::{
    collections::HashMap,
    panic::{self, AssertUnwindSafe},
    rc::{Rc, Weak},
    sync::{
        Arc, Mutex, Weak as ArcWeak,
        atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
        mpsc,
    },
    time::Duration,
};

use incular_platform::WindowId;
use incular_widgets::internal::ElementId;
use tokio::{
    runtime::{Builder, Handle, Runtime as TokioRuntime},
    task::{AbortHandle, JoinHandle},
};

use crate::Runtime;

const DEFAULT_UI_MESSAGE_BUDGET: usize = 128;
const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(100);

/// Native event-loop wake bridge. Implementations are thread-safe and must
/// never borrow the retained UI runtime directly.
pub trait RuntimeWake: Send + Sync + 'static {
    fn wake(&self);
}

/// Failure of Tokio-backed work as observed by the UI owner.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TaskFailure {
    Cancelled,
    Panicked,
    RuntimeStopped,
}

/// A small application-state value for asynchronous results. It is not an
/// executor; applications normally store it in a [`Signal`](crate::Signal)
/// from a UI callback. The error type is application-owned so callers can
/// preserve structured domain failures instead of converting everything to a
/// string or a framework-specific snapshot.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AsyncState<T, E> {
    Idle,
    Loading,
    Ready(T),
    Error(E),
}

impl<T, E> AsyncState<T, E> {
    #[must_use]
    pub const fn is_loading(&self) -> bool {
        matches!(self, Self::Loading)
    }

    #[must_use]
    pub const fn is_terminal(&self) -> bool {
        matches!(self, Self::Ready(_) | Self::Error(_))
    }

    #[must_use]
    pub const fn is_idle(&self) -> bool {
        matches!(self, Self::Idle)
    }

    #[must_use]
    pub const fn is_ready(&self) -> bool {
        matches!(self, Self::Ready(_))
    }

    #[must_use]
    pub const fn is_error(&self) -> bool {
        matches!(self, Self::Error(_))
    }

    /// Maps a successful value while preserving loading/idle/error states.
    #[must_use]
    pub fn map<U>(self, map: impl FnOnce(T) -> U) -> AsyncState<U, E> {
        match self {
            Self::Idle => AsyncState::Idle,
            Self::Loading => AsyncState::Loading,
            Self::Ready(value) => AsyncState::Ready(map(value)),
            Self::Error(error) => AsyncState::Error(error),
        }
    }
}

/// Backwards-compatible task failure state. New application code should use
/// [`AsyncState<T, E>`] with its own error type; this alias is retained for
/// task handles whose cancellation errors are owned by the runtime.
pub type AsyncValue<T> = AsyncState<T, TaskFailure>;

/// A cancellation and diagnostics handle for Tokio work tracked by Incular.
/// It intentionally is not another `JoinHandle`: use [`TokioHandle`] for
/// direct Tokio APIs when component ownership is not required.
#[derive(Clone)]
pub struct TaskHandle {
    control: Arc<TaskControl>,
}

impl TaskHandle {
    /// Requests cancellation. Tokio async tasks are aborted; a started
    /// `spawn_blocking` job may finish, but its UI result is discarded.
    pub fn cancel(&self) {
        self.control.cancel();
    }

    #[must_use]
    pub fn is_cancelled(&self) -> bool {
        self.control.is_cancelled()
    }
}

/// A typed UI-observable result of a Tokio task. This wrapper adds ownership
/// and cancellation metadata; it does not implement `Future` or duplicate
/// Tokio's join API.
pub struct Task<T> {
    state: Arc<Mutex<AsyncValue<T>>>,
    handle: TaskHandle,
}

impl<T: Clone> Task<T> {
    #[must_use]
    pub fn value(&self) -> AsyncValue<T> {
        if self.handle.is_cancelled() {
            AsyncValue::Error(TaskFailure::Cancelled)
        } else {
            self.state.lock().expect("task state mutex").clone()
        }
    }
}

impl<T> Task<T> {
    pub fn cancel(&self) {
        self.handle.cancel();
    }

    #[must_use]
    pub fn handle(&self) -> TaskHandle {
        self.handle.clone()
    }
}

/// Structured Incular ownership for Tokio tasks. Scopes may be associated with
/// a generational element identity; completions verify that identity on the UI
/// thread before running a local callback.
#[derive(Clone)]
pub struct TaskScope {
    state: Arc<ScopeState>,
}

struct ScopeState {
    cancelled: AtomicBool,
    owner: Mutex<Option<ElementId>>,
    window: Mutex<Option<WindowId>>,
    children: Mutex<HashMap<u64, ArcWeak<TaskControl>>>,
    child_scopes: Mutex<Vec<ArcWeak<ScopeState>>>,
    parent: ArcWeak<ScopeState>,
}

impl TaskScope {
    fn new() -> Self {
        Self {
            state: Arc::new(ScopeState {
                cancelled: AtomicBool::new(false),
                owner: Mutex::new(None),
                window: Mutex::new(None),
                children: Mutex::new(HashMap::new()),
                child_scopes: Mutex::new(Vec::new()),
                parent: ArcWeak::new(),
            }),
        }
    }

    /// Creates a scope whose cancellation is bounded by this scope. This is
    /// the ownership relation used for application → window → component work.
    #[must_use]
    pub(crate) fn child(&self) -> Self {
        let child = Self {
            state: Arc::new(ScopeState {
                cancelled: AtomicBool::new(self.is_cancelled()),
                owner: Mutex::new(None),
                window: Mutex::new(self.window_id()),
                children: Mutex::new(HashMap::new()),
                child_scopes: Mutex::new(Vec::new()),
                parent: Arc::downgrade(&self.state),
            }),
        };
        self.state
            .child_scopes
            .lock()
            .expect("task scope children mutex")
            .push(Arc::downgrade(&child.state));
        child
    }

    pub fn cancel(&self) {
        if self.state.cancelled.swap(true, Ordering::AcqRel) {
            return;
        }
        let children: Vec<_> = self
            .state
            .children
            .lock()
            .expect("task scope mutex")
            .values()
            .filter_map(ArcWeak::upgrade)
            .collect();
        for child in children {
            child.cancel();
        }
        let child_scopes: Vec<_> = self
            .state
            .child_scopes
            .lock()
            .expect("task scope children mutex")
            .drain(..)
            .filter_map(|scope| scope.upgrade())
            .collect();
        for scope in child_scopes {
            TaskScope { state: scope }.cancel();
        }
    }

    #[must_use]
    pub fn is_cancelled(&self) -> bool {
        self.state.cancelled.load(Ordering::Acquire)
            || self
                .state
                .parent
                .upgrade()
                .is_some_and(|parent| parent.cancelled.load(Ordering::Acquire))
    }

    pub(crate) fn bind_owner(&self, owner: ElementId) {
        *self.state.owner.lock().expect("task scope owner mutex") = Some(owner);
    }

    pub(crate) fn bind_window(&self, window: WindowId) {
        *self.state.window.lock().expect("task scope window mutex") = Some(window);
    }

    #[must_use]
    pub(crate) fn window_id(&self) -> Option<WindowId> {
        (*self.state.window.lock().expect("task scope window mutex")).or_else(|| {
            self.state
                .parent
                .upgrade()
                .and_then(|parent| *parent.window.lock().expect("task scope window mutex"))
        })
    }

    fn attach(&self, control: &Arc<TaskControl>) {
        self.state
            .children
            .lock()
            .expect("task scope mutex")
            .insert(control.id, Arc::downgrade(control));
    }

    fn detach(&self, id: u64) {
        self.state
            .children
            .lock()
            .expect("task scope mutex")
            .remove(&id);
    }
}

impl Drop for TaskScope {
    fn drop(&mut self) {
        // A task only keeps a weak reference to its scope. The final owner
        // therefore cancels children rather than accidentally extending them.
        if Arc::strong_count(&self.state) == 1 {
            self.cancel();
        }
    }
}

pub(crate) struct TaskControl {
    id: u64,
    cancelled: AtomicBool,
    scope: ArcWeak<ScopeState>,
    abort: Mutex<Option<AbortHandle>>,
}

impl TaskControl {
    fn cancel(&self) {
        self.cancelled.store(true, Ordering::Release);
        if let Some(abort) = self.abort.lock().expect("task abort mutex").as_ref() {
            abort.abort();
        }
    }

    pub(crate) fn is_cancelled(&self) -> bool {
        self.cancelled.load(Ordering::Acquire)
            || self
                .scope
                .upgrade()
                .is_none_or(|scope| scope.cancelled.load(Ordering::Acquire))
    }

    pub(crate) fn owner_is_stale(&self, runtime: &Runtime) -> bool {
        let Some(scope) = self.scope.upgrade() else {
            return true;
        };
        scope
            .owner
            .lock()
            .expect("task scope owner mutex")
            .is_some_and(|owner| !runtime.tree().element_exists(owner))
    }

    pub(crate) fn window_id(&self) -> Option<WindowId> {
        self.scope.upgrade().and_then(|scope| {
            (*scope.window.lock().expect("task scope window mutex")).or_else(|| {
                scope
                    .parent
                    .upgrade()
                    .and_then(|parent| *parent.window.lock().expect("task scope window mutex"))
            })
        })
    }
}

/// The explicit Tokio handle exposed for advanced libraries. Direct tasks use
/// Tokio/application lifetime; they are not automatically component-scoped.
pub type TokioHandle = Handle;

/// UI-thread-only helper that launches Tokio work with Incular owner tracking.
#[derive(Clone)]
pub struct RuntimeSpawner {
    scheduler: Weak<std::cell::RefCell<TaskScheduler>>,
    application_scope: TaskScope,
    window_id: Option<WindowId>,
}

impl RuntimeSpawner {
    pub(crate) const fn window_id(&self) -> Option<WindowId> {
        self.window_id
    }

    /// Starts application-scoped Tokio work. Its output is observed through the
    /// returned state handle; use `spawn_into` to update UI-local state.
    pub fn spawn<F, T>(&self, future: F) -> Task<T>
    where
        F: std::future::Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        self.spawn_in(&self.application_scope, future)
    }

    pub fn spawn_in<F, T>(&self, scope: &TaskScope, future: F) -> Task<T>
    where
        F: std::future::Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        self.scheduler
            .upgrade()
            .expect("runtime spawner outlived runtime")
            .borrow_mut()
            .spawn_task(scope, future)
    }

    /// Starts Tokio work and invokes `complete` later on the UI thread. The
    /// callback may capture non-`Send` `Signal`s because only the `Send` output
    /// crosses the Tokio/UI boundary.
    pub fn spawn_into<F, T>(
        &self,
        future: F,
        complete: impl FnOnce(Result<T, TaskFailure>, &mut Runtime) + 'static,
    ) -> TaskHandle
    where
        F: std::future::Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        self.spawn_into_in(&self.application_scope, future, complete)
    }

    pub fn spawn_into_in<F, T>(
        &self,
        scope: &TaskScope,
        future: F,
        complete: impl FnOnce(Result<T, TaskFailure>, &mut Runtime) + 'static,
    ) -> TaskHandle
    where
        F: std::future::Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        self.scheduler
            .upgrade()
            .expect("runtime spawner outlived runtime")
            .borrow_mut()
            .spawn_into(scope, future, complete)
    }

    /// Submits work to Tokio's blocking facility. A cancellation after work
    /// begins is represented as an uninterested/discarded UI completion.
    pub fn spawn_blocking<T>(
        &self,
        work: impl FnOnce() -> T + Send + 'static,
        complete: impl FnOnce(Result<T, TaskFailure>, &mut Runtime) + 'static,
    ) -> TaskHandle
    where
        T: Send + 'static,
    {
        self.spawn_blocking_in(&self.application_scope, work, complete)
    }

    pub fn spawn_blocking_in<T>(
        &self,
        scope: &TaskScope,
        work: impl FnOnce() -> T + Send + 'static,
        complete: impl FnOnce(Result<T, TaskFailure>, &mut Runtime) + 'static,
    ) -> TaskHandle
    where
        T: Send + 'static,
    {
        self.scheduler
            .upgrade()
            .expect("runtime spawner outlived runtime")
            .borrow_mut()
            .spawn_blocking_in(scope, work, complete)
    }

    #[must_use]
    pub fn scope(&self) -> TaskScope {
        self.application_scope.child()
    }

    #[must_use]
    pub fn tokio_handle(&self) -> TokioHandle {
        self.scheduler
            .upgrade()
            .expect("runtime spawner outlived runtime")
            .borrow()
            .tokio_handle()
    }

    #[must_use]
    pub fn dispatcher(&self) -> UiDispatcher {
        self.scheduler
            .upgrade()
            .expect("runtime spawner outlived runtime")
            .borrow()
            .dispatcher_for(self.window_id)
    }
}

/// Cross-thread dispatcher into the unique UI owner. It is a message sender,
/// not access to `Runtime`, and does not imply a redraw.
#[derive(Clone)]
pub struct UiDispatcher {
    bridge: Arc<RuntimeBridge>,
    window_id: Option<WindowId>,
}

impl UiDispatcher {
    pub fn dispatch(&self, callback: impl FnOnce(&mut Runtime) + Send + 'static) {
        self.bridge.enqueue(RuntimeMessage::Dispatch {
            window_id: self.window_id,
            callback: Box::new(callback),
        });
    }
}

pub(crate) type UiCallback = Box<dyn FnOnce(&mut Runtime) + Send>;
pub(crate) type TaskFinish = Box<dyn FnOnce(&mut Runtime) -> Option<TaskFailure>>;
pub(crate) type TaskDiscard = Box<dyn FnOnce()>;

enum RuntimeMessage {
    TaskCompleted(u64),
    Dispatch {
        window_id: Option<WindowId>,
        callback: UiCallback,
    },
}

struct RuntimeBridge {
    sender: mpsc::Sender<RuntimeMessage>,
    wake: Mutex<Option<Arc<dyn RuntimeWake>>>,
    accepting: AtomicBool,
    wake_pending: AtomicBool,
    queued: AtomicUsize,
    queue_peak: AtomicUsize,
    messages_enqueued: AtomicU64,
    wakes: AtomicU64,
    coalesced_wakes: AtomicU64,
}

impl RuntimeBridge {
    fn enqueue(&self, message: RuntimeMessage) {
        if !self.accepting.load(Ordering::Acquire) {
            return;
        }
        if self.sender.send(message).is_err() {
            return;
        }
        self.messages_enqueued.fetch_add(1, Ordering::Relaxed);
        let queued = self.queued.fetch_add(1, Ordering::AcqRel) + 1;
        self.queue_peak.fetch_max(queued, Ordering::Relaxed);
        self.request_wake();
    }

    fn request_wake(&self) {
        if self.wake_pending.swap(true, Ordering::AcqRel) {
            self.coalesced_wakes.fetch_add(1, Ordering::Relaxed);
            return;
        }
        self.wakes.fetch_add(1, Ordering::Relaxed);
        if let Some(wake) = self.wake.lock().expect("runtime wake mutex").as_ref() {
            wake.wake();
        }
    }

    fn set_wake(&self, wake: Arc<dyn RuntimeWake>) {
        *self.wake.lock().expect("runtime wake mutex") = Some(wake.clone());
        if self.queued.load(Ordering::Acquire) > 0 {
            self.wakes.fetch_add(1, Ordering::Relaxed);
            wake.wake();
        }
    }
}

pub(crate) struct PendingTask {
    pub(crate) control: Arc<TaskControl>,
    pub(crate) finish: TaskFinish,
    pub(crate) discard: TaskDiscard,
    pub(crate) blocking: bool,
}

/// Diagnostics of Incular/Tokio integration, not Tokio's internal executor.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RuntimeDiagnostics {
    pub app_scoped_tasks_spawned: u64,
    pub owner_scoped_tasks_spawned: u64,
    pub active_tracked_tasks: usize,
    pub tasks_completed: u64,
    pub tasks_cancelled: u64,
    pub task_join_failures: u64,
    pub task_panics: u64,
    pub blocking_jobs_spawned: u64,
    pub blocking_jobs_completed: u64,
    pub blocking_results_discarded: u64,
    pub ui_messages_enqueued: u64,
    pub ui_messages_processed: u64,
    pub ui_message_queue_peak: usize,
    pub winit_runtime_wakes: u64,
    pub coalesced_wakes: u64,
    pub stale_completion_rejections: u64,
}

pub(crate) enum UiWork {
    Dispatch {
        window_id: Option<WindowId>,
        callback: UiCallback,
    },
    Task(PendingTask),
}

/// Owns a Tokio runtime and a UI-thread message receiver. It is not an
/// executor implementation: it starts Tokio tasks and drains their owned UI
/// completion messages fairly.
pub(crate) struct TaskScheduler {
    bridge: Arc<RuntimeBridge>,
    receiver: mpsc::Receiver<RuntimeMessage>,
    pending: HashMap<u64, PendingTask>,
    /// Started by the first task: most windows never spawn async work, and
    /// a multi-thread runtime parks one worker thread per core.
    tokio: std::cell::OnceCell<TokioRuntime>,
    /// Handle of the shut-down runtime; later spawns resolve as stopped
    /// instead of starting a new runtime.
    stopped: Option<TokioHandle>,
    application_scope: TaskScope,
    next_task: u64,
    diagnostics: RuntimeDiagnostics,
}

impl TaskScheduler {
    pub(crate) fn new() -> Rc<std::cell::RefCell<Self>> {
        let (sender, receiver) = mpsc::channel();
        let bridge = Arc::new(RuntimeBridge {
            sender,
            wake: Mutex::new(None),
            accepting: AtomicBool::new(true),
            wake_pending: AtomicBool::new(false),
            queued: AtomicUsize::new(0),
            queue_peak: AtomicUsize::new(0),
            messages_enqueued: AtomicU64::new(0),
            wakes: AtomicU64::new(0),
            coalesced_wakes: AtomicU64::new(0),
        });
        Rc::new(std::cell::RefCell::new(Self {
            bridge,
            receiver,
            pending: HashMap::new(),
            tokio: std::cell::OnceCell::new(),
            stopped: None,
            application_scope: TaskScope::new(),
            next_task: 1,
            diagnostics: RuntimeDiagnostics::default(),
        }))
    }

    pub(crate) fn spawner(scheduler: &Rc<std::cell::RefCell<Self>>) -> RuntimeSpawner {
        let borrowed = scheduler.borrow();
        RuntimeSpawner {
            scheduler: Rc::downgrade(scheduler),
            application_scope: borrowed.application_scope.clone(),
            window_id: None,
        }
    }

    pub(crate) fn spawner_for(
        scheduler: &Rc<std::cell::RefCell<Self>>,
        window_id: WindowId,
    ) -> RuntimeSpawner {
        let mut spawner = Self::spawner(scheduler);
        spawner.window_id = Some(window_id);
        spawner
    }

    pub(crate) fn tokio_handle(&self) -> TokioHandle {
        if let Some(stopped) = &self.stopped {
            return stopped.clone();
        }
        self.tokio
            .get_or_init(|| {
                Builder::new_multi_thread()
                    .enable_time()
                    .enable_io()
                    .build()
                    .expect("Tokio runtime construction")
            })
            .handle()
            .clone()
    }

    fn next_control(&mut self, scope: &TaskScope) -> Arc<TaskControl> {
        let id = self.next_task;
        self.next_task = self
            .next_task
            .checked_add(1)
            .expect("runtime task identity space exhausted");
        let control = Arc::new(TaskControl {
            id,
            cancelled: AtomicBool::new(
                scope.is_cancelled() || !self.bridge.accepting.load(Ordering::Acquire),
            ),
            scope: Arc::downgrade(&scope.state),
            abort: Mutex::new(None),
        });
        scope.attach(&control);
        // The declarative root is bound to its Element after its initial
        // builder returns, so scope identity—not only an already-bound ID—is
        // the stable classification during application construction.
        if !Arc::ptr_eq(&scope.state, &self.application_scope.state) {
            self.diagnostics.owner_scoped_tasks_spawned += 1;
        } else {
            self.diagnostics.app_scoped_tasks_spawned += 1;
        }
        control
    }

    fn spawn_task<F, T>(&mut self, scope: &TaskScope, future: F) -> Task<T>
    where
        F: std::future::Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        let state = Arc::new(Mutex::new(AsyncValue::Loading));
        let state_for_finish = state.clone();
        let state_for_discard = state.clone();
        let handle = self.spawn_impl(
            scope,
            future,
            move |outcome, _| {
                let failure = outcome.as_ref().err().cloned();
                *state_for_finish.lock().expect("task state mutex") = match outcome {
                    Ok(value) => AsyncValue::Ready(value),
                    Err(failure) => AsyncValue::Error(failure),
                };
                failure
            },
            move || {
                *state_for_discard.lock().expect("task state mutex") =
                    AsyncValue::Error(TaskFailure::Cancelled);
            },
        );
        Task { state, handle }
    }

    fn spawn_into<F, T>(
        &mut self,
        scope: &TaskScope,
        future: F,
        complete: impl FnOnce(Result<T, TaskFailure>, &mut Runtime) + 'static,
    ) -> TaskHandle
    where
        F: std::future::Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        self.spawn_impl(
            scope,
            future,
            move |outcome, runtime| {
                let failure = outcome.as_ref().err().cloned();
                let callback = panic::catch_unwind(AssertUnwindSafe(|| complete(outcome, runtime)));
                if callback.is_err() {
                    Some(TaskFailure::Panicked)
                } else {
                    failure
                }
            },
            || {},
        )
    }

    pub(crate) fn spawn_blocking<T>(
        &mut self,
        work: impl FnOnce() -> T + Send + 'static,
        complete: impl FnOnce(Result<T, TaskFailure>, &mut Runtime) + 'static,
    ) -> TaskHandle
    where
        T: Send + 'static,
    {
        let scope = self.application_scope.clone();
        self.spawn_blocking_in(&scope, work, complete)
    }

    fn spawn_blocking_in<T>(
        &mut self,
        scope: &TaskScope,
        work: impl FnOnce() -> T + Send + 'static,
        complete: impl FnOnce(Result<T, TaskFailure>, &mut Runtime) + 'static,
    ) -> TaskHandle
    where
        T: Send + 'static,
    {
        self.diagnostics.blocking_jobs_spawned += 1;
        let join = self.tokio_handle().spawn_blocking(work);
        self.register_join(
            scope,
            true,
            join,
            move |outcome, runtime| {
                let failure = outcome.as_ref().err().cloned();
                let callback = panic::catch_unwind(AssertUnwindSafe(|| complete(outcome, runtime)));
                if callback.is_err() {
                    Some(TaskFailure::Panicked)
                } else {
                    failure
                }
            },
            || {},
        )
    }

    fn spawn_impl<F, T>(
        &mut self,
        scope: &TaskScope,
        future: F,
        finish: impl FnOnce(Result<T, TaskFailure>, &mut Runtime) -> Option<TaskFailure> + 'static,
        discard: impl FnOnce() + 'static,
    ) -> TaskHandle
    where
        F: std::future::Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        let join = self.tokio_handle().spawn(future);
        self.register_join(scope, false, join, finish, discard)
    }

    fn register_join<T>(
        &mut self,
        scope: &TaskScope,
        blocking: bool,
        join: JoinHandle<T>,
        finish: impl FnOnce(Result<T, TaskFailure>, &mut Runtime) -> Option<TaskFailure> + 'static,
        discard: impl FnOnce() + 'static,
    ) -> TaskHandle
    where
        T: Send + 'static,
    {
        let control = self.next_control(scope);
        let task_handle = TaskHandle {
            control: control.clone(),
        };
        if control.is_cancelled() {
            join.abort();
            discard();
            self.diagnostics.tasks_cancelled += u64::from(!blocking);
            self.diagnostics.blocking_results_discarded += u64::from(blocking);
            scope.detach(control.id);
            return task_handle;
        }

        let result = Arc::new(Mutex::new(None));
        let result_for_completion = result.clone();
        let complete_id = control.id;
        let bridge = self.bridge.clone();
        *control.abort.lock().expect("task abort mutex") = Some(join.abort_handle());
        self.tokio_handle().spawn(async move {
            let outcome = match join.await {
                Ok(value) => Ok(value),
                Err(error) if error.is_cancelled() => Err(TaskFailure::Cancelled),
                Err(error) if error.is_panic() => Err(TaskFailure::Panicked),
                Err(_) => Err(TaskFailure::RuntimeStopped),
            };
            *result_for_completion.lock().expect("task result mutex") = Some(outcome);
            bridge.enqueue(RuntimeMessage::TaskCompleted(complete_id));
        });
        self.pending.insert(
            control.id,
            PendingTask {
                control,
                finish: Box::new(move |runtime| {
                    let outcome = result
                        .lock()
                        .expect("task result mutex")
                        .take()
                        .unwrap_or(Err(TaskFailure::RuntimeStopped));
                    finish(outcome, runtime)
                }),
                discard: Box::new(discard),
                blocking,
            },
        );
        task_handle
    }

    pub(crate) fn take_turn(&mut self) -> Vec<UiWork> {
        // Clearing before the drain prevents a producer racing with this turn
        // from being lost: it will enqueue one new native user event.
        self.bridge.wake_pending.store(false, Ordering::Release);
        let mut work = Vec::new();
        let mut processed = 0;
        while processed < DEFAULT_UI_MESSAGE_BUDGET {
            let message = match self.receiver.try_recv() {
                Ok(message) => message,
                Err(mpsc::TryRecvError::Empty | mpsc::TryRecvError::Disconnected) => break,
            };
            processed += 1;
            self.bridge.queued.fetch_sub(1, Ordering::AcqRel);
            self.diagnostics.ui_messages_processed += 1;
            match message {
                RuntimeMessage::Dispatch {
                    window_id,
                    callback,
                } => work.push(UiWork::Dispatch {
                    window_id,
                    callback,
                }),
                RuntimeMessage::TaskCompleted(id) => {
                    if let Some(pending) = self.pending.remove(&id) {
                        work.push(UiWork::Task(pending));
                    }
                }
            }
        }
        if processed == DEFAULT_UI_MESSAGE_BUDGET && self.bridge.queued.load(Ordering::Acquire) > 0
        {
            self.bridge.request_wake();
        }
        work
    }

    pub(crate) fn accepting(&self) -> bool {
        self.bridge.accepting.load(Ordering::Acquire)
    }

    pub(crate) fn detach_scope(&self, control: &TaskControl) {
        if let Some(scope) = control.scope.upgrade() {
            TaskScope { state: scope }.detach(control.id);
        }
    }

    pub(crate) fn record_discard(&mut self, blocking: bool, stale_owner: bool) {
        if blocking {
            self.diagnostics.blocking_results_discarded += 1;
        } else {
            self.diagnostics.tasks_cancelled += 1;
        }
        if stale_owner {
            self.diagnostics.stale_completion_rejections += 1;
        }
    }

    pub(crate) fn record_completion(
        &mut self,
        blocking: bool,
        failure: Option<TaskFailure>,
    ) -> Option<TaskFailure> {
        if blocking {
            self.diagnostics.blocking_jobs_completed += 1;
        } else {
            self.diagnostics.tasks_completed += 1;
        }
        match failure {
            Some(TaskFailure::Cancelled) => {
                self.diagnostics.tasks_cancelled += 1;
                None
            }
            Some(TaskFailure::Panicked) => {
                self.diagnostics.task_join_failures += 1;
                self.diagnostics.task_panics += 1;
                Some(TaskFailure::Panicked)
            }
            Some(TaskFailure::RuntimeStopped) => {
                self.diagnostics.task_join_failures += 1;
                None
            }
            None => None,
        }
    }

    pub(crate) fn dispatcher_for(&self, window_id: Option<WindowId>) -> UiDispatcher {
        UiDispatcher {
            bridge: self.bridge.clone(),
            window_id,
        }
    }

    pub(crate) fn set_wake(&self, wake: Arc<dyn RuntimeWake>) {
        self.bridge.set_wake(wake);
    }

    pub(crate) fn shutdown(&mut self) {
        if !self.bridge.accepting.swap(false, Ordering::AcqRel) {
            return;
        }
        self.application_scope.cancel();
        let pending = std::mem::take(&mut self.pending);
        for (_, task) in pending {
            task.control.cancel();
            (task.discard)();
            if task.blocking {
                self.diagnostics.blocking_results_discarded += 1;
            } else {
                self.diagnostics.tasks_cancelled += 1;
            }
        }
        while self.receiver.try_recv().is_ok() {
            self.bridge.queued.fetch_sub(1, Ordering::AcqRel);
        }
        // A runtime that never started is replaced by a thread-free one so
        // spawns after shutdown keep resolving as stopped.
        let tokio = self.tokio.take().unwrap_or_else(|| {
            Builder::new_current_thread()
                .build()
                .expect("Tokio runtime construction")
        });
        self.stopped = Some(tokio.handle().clone());
        // Tokio does not force-stop an already-running blocking closure.
        // The bounded wait keeps UI shutdown from hanging indefinitely.
        tokio.shutdown_timeout(SHUTDOWN_TIMEOUT);
    }

    pub(crate) fn diagnostics(&self) -> RuntimeDiagnostics {
        let mut diagnostics = self.diagnostics;
        diagnostics.active_tracked_tasks = self.pending.len();
        diagnostics.ui_messages_enqueued = self.bridge.messages_enqueued.load(Ordering::Relaxed);
        diagnostics.ui_message_queue_peak = self.bridge.queue_peak.load(Ordering::Relaxed);
        diagnostics.winit_runtime_wakes = self.bridge.wakes.load(Ordering::Relaxed);
        diagnostics.coalesced_wakes = self.bridge.coalesced_wakes.load(Ordering::Relaxed);
        diagnostics
    }

    pub(crate) fn active_ownership(&self) -> (usize, usize) {
        self.pending.values().fold((0, 0), |(app, owner), task| {
            let application_owned = task
                .control
                .scope
                .upgrade()
                .is_some_and(|scope| Arc::ptr_eq(&scope, &self.application_scope.state));
            if application_owned {
                (app + 1, owner)
            } else {
                (app, owner + 1)
            }
        })
    }
}

impl Drop for TaskScheduler {
    fn drop(&mut self) {
        // A headless/runtime owner that is simply dropped gets the same bounded
        // Tokio shutdown policy as an explicit native-window close.
        self.shutdown();
    }
}