adaptite 0.3.0

Fine-grained reactivity (signals, thunks, memos, effects, events) for the runite runtime
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
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
use alloc::boxed::Box;
use alloc::rc::{Rc, Weak};
use alloc::vec::Vec;
use core::any::Any;

use core::cell::{Cell, RefCell};
use core::panic::Location;
use std::panic::{AssertUnwindSafe, catch_unwind};

use crate::ownership::{self, OwnerTally};
use crate::{NodeId, trace_targets};

thread_local! {
    /// `None` entries are barriers pushed by [`unowned`]: they shadow any enclosing owner
    /// without establishing a new one.
    static OWNER_STACK: RefCell<Vec<Option<Rc<OwnerFrame>>>> = const { RefCell::new(Vec::new()) };

    /// Non-zero while cleanups or child disposals are running on this thread.
    ///
    /// Teardown installs an owner *barrier*, so `current_owner()` is `None` throughout — but
    /// "no owner" and "no owner because we are tearing one down" call for different diagnoses,
    /// and only this distinguishes them.
    static TEARDOWN_DEPTH: Cell<u32> = const { Cell::new(0) };
}

/// Marks the dynamic extent of a teardown, so `on_cleanup` can explain itself accurately.
struct TeardownMark;

impl TeardownMark {
    fn enter() -> Self {
        let _ = TEARDOWN_DEPTH.try_with(|depth| depth.set(depth.get() + 1));
        Self
    }
}

impl Drop for TeardownMark {
    fn drop(&mut self) {
        let _ = TEARDOWN_DEPTH.try_with(|depth| depth.set(depth.get().saturating_sub(1)));
    }
}

fn in_teardown() -> bool {
    TEARDOWN_DEPTH.try_with(Cell::get).unwrap_or(0) > 0
}

/// Handler installed by [`scope_catch`], invoked for panics from the effects a scope owns.
type ErrorHandler = Rc<dyn Fn(ErrorInfo)>;

/// A reactive resource that an owner can dispose when it is itself disposed or re-run.
pub(crate) trait OwnedDisposable {
    fn dispose_owned(&self);

    /// Whether this child has already been disposed by some other route — its own handle, or an
    /// inner owner — so that holding it no longer accomplishes anything.
    ///
    /// An owner that neither re-runs nor is disposed never calls [`OwnerFrame::reset`], so
    /// without this its `children` list is append-only: an application root re-entered with
    /// [`Owner::run_in`] once per frame accumulates every child ever created under it, and a
    /// disposed effect drags its whole captured environment along. See
    /// [`OwnerFrame::release_disposed_children`].
    ///
    /// Defaults to `false`, which means "never released early" — always safe, and the behaviour
    /// every child had before this existed.
    fn is_disposed_owned(&self) -> bool {
        false
    }
}

/// Ownership bookkeeping for a reactive owner (an effect or a scope): the children created
/// during its execution and the cleanups registered against it.
pub(crate) struct OwnerFrame {
    children: RefCell<Vec<Rc<dyn OwnedDisposable>>>,
    /// `children.len()` immediately after the last sweep, which is the threshold the next one
    /// waits for. See [`OwnerFrame::release_disposed_children`].
    swept_at: Cell<usize>,
    cleanups: RefCell<Vec<Box<dyn FnOnce()>>>,
    disposed: Cell<bool>,
    /// Counts this frame by existing. See [`crate::ownership`]: the live-owner gauge is this
    /// field's lifetime rather than a pair of increments someone has to remember.
    _tally: OwnerTally,
    /// The owner that was innermost when this frame was created.
    ///
    /// The thread-local owner stack describes the *dynamic* chain, which is empty by the time a
    /// scheduled effect actually runs. An error boundary has to be found from the effect's
    /// *lexical* ownership instead, so the link is recorded at construction. Weak, because the
    /// parent owns the child.
    parent: RefCell<Option<Weak<OwnerFrame>>>,
    error_handler: RefCell<Option<ErrorHandler>>,
}

impl OwnerFrame {
    pub(crate) fn new() -> Rc<Self> {
        // Built field by field rather than via `Default` so the tally is visible here: it is the
        // live-owner gauge, and a reader should be able to see where the count comes from.
        let frame = Rc::new(Self {
            children: RefCell::new(Vec::new()),
            swept_at: Cell::new(0),
            cleanups: RefCell::new(Vec::new()),
            disposed: Cell::new(false),
            _tally: OwnerTally::new(),
            parent: RefCell::new(current_owner().as_ref().map(Rc::downgrade)),
            error_handler: RefCell::new(None),
        });
        ownership::register(&frame);
        frame
    }

    /// Cleanups registered against this frame and not yet run. Used by the ownership audit, which
    /// exists in debug builds only.
    #[cfg(debug_assertions)]
    pub(crate) fn pending_cleanups(&self) -> usize {
        self.cleanups.borrow().len()
    }

    /// Effects and scopes this frame currently owns. Used by the ownership audit, which exists in
    /// debug builds only.
    #[cfg(debug_assertions)]
    pub(crate) fn owned_children(&self) -> usize {
        self.children.borrow().len()
    }

    /// Returns the nearest error handler at or above this frame.
    fn error_handler(self: &Rc<Self>) -> Option<ErrorHandler> {
        let mut frame = Rc::clone(self);
        loop {
            if let Some(handler) = frame.error_handler.borrow().as_ref() {
                return Some(Rc::clone(handler));
            }
            let parent = frame.parent.borrow().as_ref().and_then(Weak::upgrade);
            frame = parent?;
        }
    }

    /// Takes ownership of `child`, disposing it when this owner is reset or disposed. If the
    /// owner is already disposed, the child is disposed immediately.
    pub(crate) fn adopt(&self, child: Rc<dyn OwnedDisposable>) {
        if self.disposed.get() {
            child.dispose_owned();
            return;
        }
        // Deliberately bound to the end of this function: dropping a released child runs its
        // `Drop`, and for an effect that means dropping the closure and everything it captured —
        // arbitrary consumer code, which may itself adopt into this very frame. Nothing here is
        // borrowed by the time `_released` falls out of scope.
        let _released = self.release_disposed_children();
        self.children.borrow_mut().push(child);
        ownership::child_adopted();
    }

    /// Drops the children that have already been disposed by some other route, returning them so
    /// the caller decides when their destructors run.
    ///
    /// `reset` is the only other thing that empties `children`, and an owner that neither re-runs
    /// nor is disposed never calls it — which is exactly the shape [`Owner`] documents for an
    /// application root or a component frame re-entered with [`Owner::run_in`]. Without this,
    /// individually disposing a child leaves the owner holding it forever: linear, unbounded
    /// growth in which each unit is a whole captured environment. It is visible in
    /// [`crate::OwnershipStats::owned_children`], which is what that gauge is for, but a gauge is
    /// not a fix.
    ///
    /// Sweeping only once the list has doubled since the last sweep keeps this amortised `O(1)`
    /// per adoption and the retained set `O(live children)` — the same bargain, for the same
    /// reason, as the audit registry in [`crate::ownership::register`]. A sweep on every adoption
    /// would instead be `O(n²)` for a wide component tree, which is the common case and the one
    /// that has nothing wrong with it.
    ///
    /// Relative order is preserved, so the survivors still tear down in reverse registration
    /// order.
    fn release_disposed_children(&self) -> Vec<Rc<dyn OwnedDisposable>> {
        let mut children = self.children.borrow_mut();
        if children.len() < 8 || children.len() < self.swept_at.get().saturating_mul(2) {
            return Vec::new();
        }
        // `is_disposed_owned` reads a `Cell` on every implementor and runs no consumer code, so
        // holding the borrow across the scan is safe; the destructors are what must wait.
        let released = children
            .extract_if(.., |child| child.is_disposed_owned())
            .collect::<Vec<_>>();
        self.swept_at.set(children.len());
        drop(children);
        ownership::children_taken(released.len());
        released
    }

    /// Registers a cleanup to run before the owner next re-runs or when it is disposed. If the
    /// owner is already disposed, the cleanup runs immediately.
    pub(crate) fn add_cleanup(&self, cleanup: Box<dyn FnOnce()>) {
        if self.disposed.get() {
            // Registered against a dead owner: it runs now and is never pending, so it counts as
            // registered and run without ever touching the live gauge.
            ownership::cleanup_run_immediately();
            cleanup();
            return;
        }
        self.cleanups.borrow_mut().push(cleanup);
        ownership::cleanup_registered();
    }

    /// Runs registered cleanups and disposes owned children, most recent first. Called before an
    /// effect re-runs and as part of disposal.
    ///
    /// # Teardown is total
    ///
    /// **Every cleanup and every child receives a teardown attempt, in reverse registration
    /// order, even when one of them panics.** Teardown is the path that releases subscriptions,
    /// timers, file handles and child subtrees; a single misbehaving cleanup must not be able to
    /// strand the rest, because the result is a leak with no error attached to it.
    ///
    /// Each entry therefore runs under its own [`catch_unwind`]. Cleanups and children are both
    /// taken from the frame *before* any of them runs, so a cleanup that panics cannot prevent
    /// the children being disposed either.
    ///
    /// # Panic precedence
    ///
    /// The **first** panic is preserved and re-raised once teardown has finished; later ones are
    /// dropped after being logged. First rather than last because subsequent failures are
    /// commonly caused by the first — the earliest failure is the one that explains the others.
    ///
    /// # Teardown that begins during an unwind
    ///
    /// `reset` is reachable from [`Drop`], so it can start while the thread is *already*
    /// unwinding. Re-raising there would be a panic during unwinding, which aborts the process.
    /// So when [`std::thread::panicking`] is set, a captured payload is logged at `error` and
    /// **not** re-raised: the teardown still completes, the original panic still propagates, and
    /// the process survives. This is the one case where a cleanup panic is not observable as a
    /// panic, and it is the only alternative to an abort.
    ///
    /// Cleanups and disposals also run untracked, so their reads never become dependencies of
    /// whatever observer triggered the reset.
    pub(crate) fn reset(&self) {
        // Both taken up front: teardown of the children must not depend on the cleanups
        // surviving, and the ownership gauges must not depend on reaching the end of a loop that
        // may unwind partway through.
        let mut cleanups = core::mem::take(&mut *self.cleanups.borrow_mut());
        let mut children = core::mem::take(&mut *self.children.borrow_mut());
        ownership::cleanups_taken(cleanups.len());
        ownership::children_taken(children.len());
        self.swept_at.set(0);

        let mut first_panic: Option<Box<dyn Any + Send>> = None;
        crate::untrack(|| {
            // An owner barrier, not merely an absence of one. Teardown can be reached with an
            // unrelated owner on the stack — a host that calls `flush_now` from inside a `scope`
            // does exactly that, and an effect re-running under that flush tears down here.
            // Without the barrier a cleanup that registers a cleanup silently attaches it to
            // whatever scope encloses the *flush*, so it outlives the effect it belongs to and
            // runs when that outer scope dies, which may be never. That is a leak with no error
            // attached to it. With the barrier, teardown is uniformly unowned and the attempt is
            // reported instead.
            with_owner_entry(None, || {
                let _teardown = TeardownMark::enter();
                for cleanup in cleanups.drain(..).rev() {
                    capture_panic(&mut first_panic, cleanup);
                }
                for child in children.drain(..).rev() {
                    capture_panic(&mut first_panic, || child.dispose_owned());
                }
            });
        });

        // Both lists are empty now — `drain` was used rather than `into_iter` precisely so the
        // capacity survives. An effect that registers cleanups on every run would otherwise
        // allocate a fresh Vec on every run. Only adopted when the slot has not already been
        // refilled with something larger, which a cleanup that re-registered during teardown can
        // have done.
        {
            let mut slot = self.cleanups.borrow_mut();
            if slot.is_empty() && slot.capacity() < cleanups.capacity() {
                *slot = cleanups;
            }
        }
        {
            let mut slot = self.children.borrow_mut();
            if slot.is_empty() && slot.capacity() < children.capacity() {
                *slot = children;
            }
        }

        let Some(payload) = first_panic else {
            return;
        };
        if std::thread::panicking() {
            // Resuming here would be a panic during unwinding, which aborts. The original panic
            // is already on its way out and carries more information than this one.
            tracing::error!(
                target: trace_targets::SCOPE,
                event = "cleanup_panic_during_unwind",
                "a reactive cleanup panicked while the thread was already unwinding; teardown \
                 completed and the panic was discarded to avoid aborting the process"
            );
            return;
        }
        std::panic::resume_unwind(payload);
    }

    /// Terminally disposes the owner: resets it and rejects future children.
    pub(crate) fn dispose(&self) {
        if self.disposed.replace(true) {
            return;
        }
        ownership::owner_disposed();
        tracing::debug!(
            target: trace_targets::SCOPE,
            event = "dispose_owner",
            "disposing reactive owner"
        );
        self.reset();
    }

    pub(crate) fn is_disposed(&self) -> bool {
        self.disposed.get()
    }
}

impl Drop for OwnerFrame {
    fn drop(&mut self) {
        // Covers the case where the closure passed to `scope` panics before a handle exists:
        // registered cleanups still run when the frame unwinds.
        self.dispose();
    }
}

/// Runs `f`, keeping the first panic it produces rather than letting it escape.
///
/// Teardown must reach every entry, so no single entry is allowed to unwind out of the loop.
fn capture_panic(slot: &mut Option<Box<dyn Any + Send>>, f: impl FnOnce()) {
    let Err(payload) = catch_unwind(AssertUnwindSafe(f)) else {
        return;
    };
    if slot.is_none() {
        *slot = Some(payload);
    } else {
        tracing::error!(
            target: trace_targets::SCOPE,
            event = "cleanup_panic_discarded",
            "a reactive cleanup panicked during teardown that was already failing; the first \
             panic is the one that propagates"
        );
    }
}

/// Runs `f` with `frame` as the innermost reactive owner on this thread.
pub(crate) fn with_owner<T>(frame: &Rc<OwnerFrame>, f: impl FnOnce() -> T) -> T {
    with_owner_entry(Some(Rc::clone(frame)), f)
}

fn with_owner_entry<T>(entry: Option<Rc<OwnerFrame>>, f: impl FnOnce() -> T) -> T {
    // `try_with` throughout, because teardown is reachable from `Drop` and therefore from a
    // thread-local destructor, by which point this thread-local may already be gone. Panicking
    // in a `Drop` that runs during thread shutdown aborts the process rather than failing a test.
    // A push that did not happen must not be popped, so the guard records whether it took effect.
    let pushed = OWNER_STACK
        .try_with(|stack| stack.borrow_mut().push(entry))
        .is_ok();

    struct Guard {
        pushed: bool,
    }

    impl Drop for Guard {
        fn drop(&mut self) {
            if !self.pushed {
                return;
            }
            let _ = OWNER_STACK.try_with(|stack| {
                stack.borrow_mut().pop();
            });
        }
    }

    let _guard = Guard { pushed };
    f()
}

/// Returns the innermost reactive owner on this thread, if any.
pub(crate) fn current_owner() -> Option<Rc<OwnerFrame>> {
    OWNER_STACK
        .try_with(|stack| stack.borrow().last().cloned().flatten())
        .unwrap_or(None)
}

/// Hands `child` to the innermost owner on this thread, returning `false` when no owner is
/// active (the child stays exclusively handle-managed).
pub(crate) fn adopt_into_current(child: Rc<dyn OwnedDisposable>) -> bool {
    match current_owner() {
        Some(owner) => {
            owner.adopt(child);
            true
        }
        None => false,
    }
}

/// A non-owning handle to a reactive owner (an effect or scope), used to re-enter it later.
///
/// Ownership is established by *where code runs*: an effect or subscription is adopted by the
/// owner active at its creation. Async work breaks that link — after an `.await`, the original
/// owner is no longer on the stack, so anything created there would be unowned and would
/// outlive the screen or component that spawned it. Capture an `Owner` before suspending and
/// use [`run_in`](Owner::run_in) to re-attach later work:
///
/// ```rust
/// use std::cell::RefCell;
/// use std::rc::Rc;
///
/// use adaptite::{effect, owner, scope, signal};
/// use runite::{queue_macrotask, run, yield_now};
///
/// let seen = Rc::new(RefCell::new(Vec::new()));
///
/// queue_macrotask({
///     let seen = Rc::clone(&seen);
///     move || {
///         let data = signal(0);
///         let (handle, ()) = scope({
///             let data = data.clone();
///             let seen = Rc::clone(&seen);
///             move || {
///                 // Capture the owner before suspending...
///                 let scope_owner = owner().expect("scope is the current owner");
///                 std::mem::drop(runite::spawn(async move {
///                     yield_now().await; // ... await a fetch ...
///                     // ...and re-enter it afterwards: the effect is owned again.
///                     scope_owner.run_in(|| {
///                         let _ = effect({
///                             let data = data.clone();
///                             let seen = Rc::clone(&seen);
///                             move || seen.borrow_mut().push(data.get())
///                         });
///                     });
///                 }));
///             }
///         });
///
///         runite::queue_macrotask({
///             let data = data.clone();
///             move || {
///                 handle.dispose();
///                 data.set(1); // disposed with the scope: not observed
///             }
///         });
///     }
/// });
/// run();
///
/// assert_eq!(*seen.borrow(), [0]);
/// ```
///
/// Unlike [`ScopeHandle`], dropping an `Owner` does **not** dispose anything: it is a
/// re-entry token, not a lifetime manager. If the owner has already been disposed when
/// [`run_in`](Owner::run_in) executes, children created inside are disposed immediately and
/// cleanups run immediately.
#[derive(Clone)]
pub struct Owner {
    frame: Rc<OwnerFrame>,
}

impl Owner {
    /// Runs `f` with this owner as the innermost reactive owner on the current thread.
    pub fn run_in<T>(&self, f: impl FnOnce() -> T) -> T {
        with_owner(&self.frame, f)
    }

    /// Returns `true` if the underlying owner has been disposed.
    pub fn is_disposed(&self) -> bool {
        self.frame.is_disposed()
    }
}

impl core::fmt::Debug for Owner {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Owner")
            .field("disposed", &self.frame.is_disposed())
            .finish()
    }
}

/// Captures the innermost reactive owner (the currently running effect, or the scope currently
/// being constructed) for later re-entry, or `None` when no owner is active.
///
/// See [`Owner`] for the async re-attachment pattern this enables.
pub fn owner() -> Option<Owner> {
    current_owner().map(|frame| Owner { frame })
}

/// Runs `f` with no current reactive owner.
///
/// Effects, scopes, and subscriptions created inside are unowned even when `unowned` is called
/// from within an effect run or a scope: they are kept alive by their handles and disposed when
/// the last handle drops (or kept for the remainder of the program via `leak`). Use it to start
/// background work from inside a component or effect without tying its lifetime to the
/// enclosing owner.
///
/// The suppression applies only at the boundary: an owner established *inside* `f` (a scope, or
/// an effect's own runs) works normally. [`owner`] returns `None` directly inside `f`, and
/// [`on_cleanup`] there panics, since no owner could ever run the cleanup.
///
/// # Examples
///
/// ```rust
/// use std::cell::RefCell;
/// use std::rc::Rc;
///
/// use adaptite::{effect, scope, signal, unowned};
/// use runite::{queue_macrotask, run};
///
/// let seen = Rc::new(RefCell::new(Vec::new()));
///
/// queue_macrotask({
///     let seen = Rc::clone(&seen);
///     move || {
///         let data = signal(0);
///         let (handle, background) = scope({
///             let data = data.clone();
///             let seen = Rc::clone(&seen);
///             move || {
///                 // Created inside the scope, but deliberately not owned by it.
///                 unowned(|| {
///                     effect({
///                         let data = data.clone();
///                         let seen = Rc::clone(&seen);
///                         move || seen.borrow_mut().push(data.get())
///                     })
///                 })
///             }
///         });
///
///         runite::queue_macrotask({
///             let data = data.clone();
///             move || {
///                 handle.dispose();
///                 data.set(1); // the scope is gone, but the unowned effect still reacts
///
///                 runite::queue_macrotask(move || {
///                     drop(background); // last handle dropped: now it is disposed
///                     data.set(2); // not observed
///                 });
///             }
///         });
///     }
/// });
/// run();
///
/// assert_eq!(*seen.borrow(), [0, 1]);
/// ```
pub fn unowned<T>(f: impl FnOnce() -> T) -> T {
    with_owner_entry(None, f)
}

/// Registers `cleanup` against the innermost reactive owner (the currently running effect, or
/// the scope currently being constructed).
///
/// The cleanup runs before the owning effect next re-runs, and when the owner is disposed. Use
/// it to release resources acquired during an effect run.
///
/// Cleanups run untracked (their reads do not become dependencies of whatever triggered the
/// teardown) and in reverse registration order: the most recently registered cleanup runs
/// first, before any children of the owner are disposed.
///
/// # Panics
///
/// Panics when there is no innermost owner to register against, since the cleanup could never
/// run. That is one condition, but it is reached two ways, and the second is not obvious:
///
/// - **No owner at all** — called outside any effect run or scope, or directly inside
///   [`unowned`].
/// - **During teardown** — called from inside a cleanup, or from inside the disposal of a child.
///   Teardown installs an owner *barrier* rather than merely running with no owner: the frame
///   being torn down has already taken its cleanup list, and an enclosing owner that happens to
///   be on the stack (a host calling `flush_now` from inside a [`scope`] puts one there) is
///   deliberately shadowed, because attaching to it would silently outlive the effect the
///   cleanup belongs to. Register the cleanup from the effect body or scope being torn down, or
///   open a [`scope`] inside the cleanup if you need resources released after it.
///
/// The two cases report themselves with different messages. The second is newly reported in 0.3;
/// before the barrier it silently attached the cleanup to whatever owner enclosed the flush.
///
/// # Examples
///
/// ```rust
/// use std::cell::RefCell;
/// use std::rc::Rc;
///
/// use adaptite::{on_cleanup, scope};
///
/// let log = Rc::new(RefCell::new(Vec::new()));
///
/// let (handle, ()) = scope({
///     let log = Rc::clone(&log);
///     move || {
///         log.borrow_mut().push("setup");
///         on_cleanup({
///             let log = Rc::clone(&log);
///             move || log.borrow_mut().push("teardown")
///         });
///     }
/// });
///
/// assert_eq!(*log.borrow(), ["setup"]);
/// handle.dispose();
/// assert_eq!(*log.borrow(), ["setup", "teardown"]);
/// ```
///
/// Cleanups pair naturally with effect re-runs for subscribe/unsubscribe patterns:
///
/// ```rust
/// use std::cell::RefCell;
/// use std::rc::Rc;
///
/// use adaptite::{effect, on_cleanup, signal};
/// use runite::{queue_macrotask, run};
///
/// let log = Rc::new(RefCell::new(Vec::new()));
///
/// queue_macrotask({
///     let log = Rc::clone(&log);
///     move || {
///         let channel = signal("news");
///         effect({
///             let channel = channel.clone();
///             let log = Rc::clone(&log);
///             move || {
///                 let name = channel.get();
///                 log.borrow_mut().push(format!("subscribe {name}"));
///                 on_cleanup({
///                     let log = Rc::clone(&log);
///                     move || log.borrow_mut().push(format!("unsubscribe {name}"))
///                 });
///             }
///         })
///         .leak();
///
///         runite::queue_macrotask(move || {
///             channel.set("sports");
///         });
///     }
/// });
/// run();
///
/// assert_eq!(
///     *log.borrow(),
///     ["subscribe news", "unsubscribe news", "subscribe sports"]
/// );
/// ```
pub fn on_cleanup(cleanup: impl FnOnce() + 'static) {
    let Some(owner) = current_owner() else {
        if in_teardown() {
            panic!(
                "adaptite: on_cleanup called from inside a cleanup, while its owner is being \
                 torn down; the owner's cleanup list has already been taken, so there is no \
                 point at which this cleanup could run. Register it from the effect body or \
                 scope that is being cleaned up, or create a `scope` inside the cleanup if you \
                 need resources released after it"
            );
        }
        panic!(
            "adaptite: on_cleanup called outside a reactive owner (an effect run or a scope); \
             the cleanup would never execute"
        );
    };
    owner.add_cleanup(Box::new(cleanup));
}

/// A panic caught by an error boundary, delivered to the handler registered with [`scope_catch`].
pub struct ErrorInfo {
    payload: Box<dyn Any + Send>,
    node: NodeId,
    origin: Option<&'static Location<'static>>,
}

impl ErrorInfo {
    /// Returns the panic payload.
    pub fn payload(&self) -> &(dyn Any + Send) {
        &*self.payload
    }

    /// Consumes this value and returns the panic payload, for re-raising with
    /// [`std::panic::resume_unwind`].
    pub fn into_payload(self) -> Box<dyn Any + Send> {
        self.payload
    }

    /// Returns the panic message when the payload is a string, which covers `panic!` with a
    /// format string and every panic the standard library raises.
    pub fn message(&self) -> Option<&str> {
        if let Some(message) = self.payload.downcast_ref::<&'static str>() {
            return Some(message);
        }
        self.payload
            .downcast_ref::<alloc::string::String>()
            .map(alloc::string::String::as_str)
    }

    /// Returns the node id of the effect that panicked.
    pub fn node(&self) -> NodeId {
        self.node
    }

    /// Returns the source location where the failing effect was created, which is usually more
    /// useful than the panic site for finding the buggy subtree.
    pub fn origin(&self) -> Option<&'static Location<'static>> {
        self.origin
    }
}

impl core::fmt::Debug for ErrorInfo {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("ErrorInfo")
            .field("node", &self.node)
            .field("message", &self.message())
            .field("origin", &self.origin)
            .finish_non_exhaustive()
    }
}

impl core::fmt::Display for ErrorInfo {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "effect {} panicked", self.node.get())?;
        if let Some(origin) = self.origin {
            write!(f, " (created at {origin})")?;
        }
        if let Some(message) = self.message() {
            write!(f, ": {message}")?;
        }
        Ok(())
    }
}

pub(crate) fn build_error_info(
    payload: Box<dyn Any + Send>,
    node: NodeId,
    origin: Option<&'static Location<'static>>,
) -> ErrorInfo {
    ErrorInfo {
        payload,
        node,
        origin,
    }
}

/// Finds the error handler governing `frame`, if any.
pub(crate) fn error_handler_for(frame: &Rc<OwnerFrame>) -> Option<ErrorHandler> {
    frame.error_handler()
}

/// Creates an ownership scope that catches panics from the effects it owns.
///
/// One buggy widget's panicking effect otherwise unwinds out of the whole flush. A boundary
/// confines the blast radius: a panic from any effect owned by this scope — at any depth — is
/// delivered to `on_error` instead of propagating, and the rest of the application keeps running.
///
/// # What happens on a panic
///
/// The panicking effect is **disposed** before `on_error` runs: its cleanups run, the children it
/// owns are torn down, and it is unhooked from the graph. This is deliberate. An effect that
/// panicked has already had its dependency tracking cut short, and leaving it live would re-run
/// and re-panic on the next invalidation — or immediately, since a panic during dependency
/// verification re-queues the effect. Disposing it makes the failure terminal for that effect and
/// leaves the handler to decide what replaces it, which is the same shape as Solid's
/// `ErrorBoundary`. The rest of the scope survives.
///
/// The nearest enclosing handler wins; boundaries nest. With no handler anywhere above the
/// effect, the panic propagates exactly as it does today.
///
/// # Caveats
///
/// - This catches *panics*, which are bugs. Recoverable failures — a fetch that 404s, a parse that
///   fails — belong in the graph as `Result` values so that downstream nodes can react to them;
///   an error boundary is not a substitute for that.
/// - Under `panic = "abort"` there is nothing to catch and the process aborts. The boundary
///   compiles and is simply never invoked.
/// - The handler runs on the reactor's thread, inside the flush that ran the failing effect. It
///   should tear down or replace the subtree, not do lengthy work.
/// - A panic raised by `f` itself — the scope's own body, run synchronously — is *not* caught.
///   Only effects owned by the scope are covered.
/// - Coverage follows ownership, so an effect created inside [`unowned`] is outside every
///   boundary above it and its panics propagate as usual. That is the same opt-out `unowned`
///   already applies to disposal; take an [`Owner`] and [`run_in`](Owner::run_in) to keep async
///   work under the boundary that created it.
///
/// # Examples
///
/// ```rust
/// use std::cell::RefCell;
/// use std::rc::Rc;
///
/// use adaptite::{Reactor, scope_catch, signal_in};
///
/// let reactor = Reactor::new();
/// let errors = Rc::new(RefCell::new(Vec::new()));
/// let healthy_runs = Rc::new(RefCell::new(0));
///
/// let value = signal_in(&reactor, 1);
/// let (boundary, ()) = scope_catch(
///     {
///         let reactor = reactor.clone();
///         let value = value.clone();
///         let healthy_runs = Rc::clone(&healthy_runs);
///         move || {
///             // A buggy widget...
///             reactor.effect({
///                 let value = value.clone();
///                 move || {
///                     if value.get() == 2 {
///                         panic!("widget exploded");
///                     }
///                 }
///             }).leak();
///
///             // ...and a healthy sibling that must survive it.
///             reactor.effect({
///                 let value = value.clone();
///                 let healthy_runs = Rc::clone(&healthy_runs);
///                 move || {
///                     value.get();
///                     *healthy_runs.borrow_mut() += 1;
///                 }
///             }).leak();
///         }
///     },
///     {
///         let errors = Rc::clone(&errors);
///         move |error: adaptite::ErrorInfo| {
///             errors.borrow_mut().push(error.message().unwrap_or("?").to_string());
///         }
///     },
/// );
///
/// reactor.flush_now();
/// assert!(errors.borrow().is_empty());
/// assert_eq!(*healthy_runs.borrow(), 1);
///
/// // The panic is contained: reported, not propagated.
/// value.set(2);
/// reactor.flush_now();
/// assert_eq!(*errors.borrow(), ["widget exploded"]);
/// assert_eq!(*healthy_runs.borrow(), 2, "the sibling still ran");
///
/// // And the application keeps working afterwards.
/// value.set(3);
/// reactor.flush_now();
/// assert_eq!(*healthy_runs.borrow(), 3);
/// # boundary.dispose();
/// ```
pub fn scope_catch<T>(
    f: impl FnOnce() -> T,
    on_error: impl Fn(ErrorInfo) + 'static,
) -> (ScopeHandle, T) {
    let frame = OwnerFrame::new();
    *frame.error_handler.borrow_mut() = Some(Rc::new(on_error));
    tracing::debug!(
        target: trace_targets::SCOPE,
        event = "create_scope",
        catching = true,
        "created reactive scope with an error boundary"
    );
    let result = with_owner(&frame, f);
    let handle = ScopeHandle {
        inner: Rc::new(ScopeInner { frame }),
    };
    let inner: Rc<dyn OwnedDisposable> = handle.inner.clone();
    let _ = adopt_into_current(inner);
    (handle, result)
}

/// Runs `f` inside a new ownership scope and returns its result along with a handle to the
/// scope.
///
/// Effects (and nested scopes) created while `f` executes are owned by the scope: they stay
/// alive without their handles being held, and they are disposed together when the scope is
/// disposed.
///
/// A scope created inside another owner (an effect's run, or an enclosing scope) is kept alive
/// by that owner — even if every [`ScopeHandle`] clone is dropped — and is disposed with it. An
/// unowned scope is disposed when the last clone of its handle is dropped; call
/// [`leak`](ScopeHandle::leak) to keep it alive for the remainder of the program.
///
/// # Examples
///
/// ```rust
/// use std::cell::RefCell;
/// use std::rc::Rc;
///
/// use adaptite::{on_cleanup, scope};
///
/// let torn_down = Rc::new(RefCell::new(false));
///
/// let (handle, greeting) = scope({
///     let torn_down = Rc::clone(&torn_down);
///     move || {
///         // Effects created here would be owned by the scope and disposed with it.
///         on_cleanup(move || *torn_down.borrow_mut() = true);
///         "hello"
///     }
/// });
///
/// assert_eq!(greeting, "hello");
/// assert!(!handle.is_disposed());
///
/// handle.dispose();
/// assert!(*torn_down.borrow());
/// ```
pub fn scope<T>(f: impl FnOnce() -> T) -> (ScopeHandle, T) {
    let frame = OwnerFrame::new();
    tracing::debug!(
        target: trace_targets::SCOPE,
        event = "create_scope",
        "created reactive scope"
    );
    let result = with_owner(&frame, f);
    let handle = ScopeHandle {
        inner: Rc::new(ScopeInner { frame }),
    };
    let inner: Rc<dyn OwnedDisposable> = handle.inner.clone();
    let _ = adopt_into_current(inner);
    (handle, result)
}

/// Disposable handle for an ownership scope created with [`scope`].
///
/// Clones share the same scope. An unowned scope is disposed when the last clone is dropped; a
/// scope created inside another owner is kept alive by that owner regardless of handles and is
/// disposed with it. [`dispose`](ScopeHandle::dispose) tears the scope down immediately;
/// [`leak`](ScopeHandle::leak) keeps an unowned scope alive for the remainder of the program.
#[derive(Clone)]
#[must_use = "scopes are disposed when dropped, so you must keep the handle or explicitly leak it"]
pub struct ScopeHandle {
    inner: Rc<ScopeInner>,
}

impl ScopeHandle {
    /// Disposes the scope immediately: runs its cleanups and disposes everything it owns.
    pub fn dispose(&self) {
        self.inner.frame.dispose();
    }

    /// Returns `true` if the scope has been disposed.
    pub fn is_disposed(&self) -> bool {
        self.inner.frame.is_disposed()
    }

    /// Consumes the handle without disposing the scope, letting an unowned scope live for the
    /// remainder of the program.
    ///
    /// This forfeits only the handle's lifetime management: a scope created inside an owner (an
    /// effect's run, or an enclosing [`scope`]) is still disposed with that owner — `leak` is not
    /// a way to detach from it. The same carve-out as [`crate::EffectHandle::leak`]. You CANNOT
    /// recover a `ScopeHandle` after calling this method.
    pub fn leak(self) {
        core::mem::forget(self);
    }

    /// Returns a non-owning [`Owner`] for this scope, for re-entering it later (for example
    /// from async work). Dropping the returned owner does not dispose the scope.
    pub fn owner(&self) -> Owner {
        Owner {
            frame: Rc::clone(&self.inner.frame),
        }
    }
}

impl core::fmt::Debug for ScopeHandle {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("ScopeHandle")
            .field("disposed", &self.inner.frame.is_disposed())
            .finish()
    }
}

struct ScopeInner {
    frame: Rc<OwnerFrame>,
}

impl OwnedDisposable for ScopeInner {
    fn dispose_owned(&self) {
        self.frame.dispose();
    }

    fn is_disposed_owned(&self) -> bool {
        self.frame.is_disposed()
    }
}

impl Drop for ScopeInner {
    fn drop(&mut self) {
        self.frame.dispose();
    }
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;
    use std::panic::{AssertUnwindSafe, catch_unwind};
    use std::rc::Rc;

    use runite::{queue_macrotask, run};

    use super::{ErrorInfo, ScopeHandle, on_cleanup, scope, scope_catch, unowned};
    use crate::{Reactor, signal_in};

    /// Collects the messages a boundary reports.
    fn error_log() -> (Rc<RefCell<Vec<String>>>, impl Fn(ErrorInfo) + 'static) {
        let log = Rc::new(RefCell::new(Vec::new()));
        let handler = {
            let log = Rc::clone(&log);
            move |error: ErrorInfo| {
                log.borrow_mut()
                    .push(error.message().unwrap_or("<opaque>").to_string());
            }
        };
        (log, handler)
    }

    #[test]
    fn a_boundary_contains_a_panicking_effect_and_spares_its_siblings() {
        let reactor = Reactor::new();
        let (errors, handler) = error_log();
        let value = signal_in(&reactor, 1);
        let sibling_runs = Rc::new(RefCell::new(0));

        let (boundary, ()) = scope_catch(
            {
                let reactor = reactor.clone();
                let value = value.clone();
                let sibling_runs = Rc::clone(&sibling_runs);
                move || {
                    reactor
                        .effect({
                            let value = value.clone();
                            move || {
                                if value.get() == 2 {
                                    panic!("boom");
                                }
                            }
                        })
                        .leak();
                    reactor
                        .effect({
                            let value = value.clone();
                            let sibling_runs = Rc::clone(&sibling_runs);
                            move || {
                                value.get();
                                *sibling_runs.borrow_mut() += 1;
                            }
                        })
                        .leak();
                }
            },
            handler,
        );

        reactor.flush_now();
        assert!(errors.borrow().is_empty());
        assert_eq!(*sibling_runs.borrow(), 1);

        value.set(2);
        reactor.flush_now();
        assert_eq!(*errors.borrow(), ["boom"]);
        assert_eq!(
            *sibling_runs.borrow(),
            2,
            "the sibling ran despite the panic"
        );

        // The graph keeps working, and the failed effect stays down rather than re-panicking.
        value.set(3);
        reactor.flush_now();
        assert_eq!(*sibling_runs.borrow(), 3);
        assert_eq!(
            *errors.borrow(),
            ["boom"],
            "reported once, not on every run"
        );

        boundary.dispose();
    }

    #[test]
    fn the_panicking_effect_is_disposed_and_its_cleanups_run() {
        let reactor = Reactor::new();
        let (errors, handler) = error_log();
        let value = signal_in(&reactor, 1);
        let torn_down = Rc::new(RefCell::new(false));

        let (boundary, ()) = scope_catch(
            {
                let reactor = reactor.clone();
                let value = value.clone();
                let torn_down = Rc::clone(&torn_down);
                move || {
                    reactor
                        .effect({
                            let value = value.clone();
                            let torn_down = Rc::clone(&torn_down);
                            move || {
                                on_cleanup({
                                    let torn_down = Rc::clone(&torn_down);
                                    move || *torn_down.borrow_mut() = true
                                });
                                if value.get() == 2 {
                                    panic!("boom");
                                }
                            }
                        })
                        .leak();
                }
            },
            handler,
        );

        reactor.flush_now();
        assert!(!*torn_down.borrow());

        value.set(2);
        reactor.flush_now();
        assert_eq!(*errors.borrow(), ["boom"]);
        assert!(
            *torn_down.borrow(),
            "disposal must run the failed effect's cleanups"
        );

        boundary.dispose();
    }

    #[test]
    fn without_a_boundary_a_panic_still_propagates() {
        let reactor = Reactor::new();
        let value = signal_in(&reactor, 1);

        let effect = reactor.effect({
            let value = value.clone();
            move || {
                if value.get() == 2 {
                    panic!("boom");
                }
            }
        });
        reactor.flush_now();

        value.set(2);
        let result = catch_unwind(AssertUnwindSafe(|| reactor.flush_now()));
        assert!(result.is_err(), "an uncaught panic must not be swallowed");

        effect.dispose();
    }

    #[test]
    fn the_nearest_boundary_wins_and_boundaries_nest() {
        let reactor = Reactor::new();
        let (outer_errors, outer_handler) = error_log();
        let (inner_errors, inner_handler) = error_log();
        let value = signal_in(&reactor, 1);

        let (boundary, ()) = scope_catch(
            {
                let reactor = reactor.clone();
                let value = value.clone();
                move || {
                    // An effect governed by the outer boundary only.
                    reactor
                        .effect({
                            let value = value.clone();
                            move || {
                                if value.get() == 3 {
                                    panic!("outer child");
                                }
                            }
                        })
                        .leak();

                    let (inner, ()) = scope_catch(
                        {
                            let reactor = reactor.clone();
                            let value = value.clone();
                            move || {
                                reactor
                                    .effect({
                                        let value = value.clone();
                                        move || {
                                            if value.get() == 2 {
                                                panic!("inner child");
                                            }
                                        }
                                    })
                                    .leak();
                            }
                        },
                        inner_handler,
                    );
                    inner.leak();
                }
            },
            outer_handler,
        );

        reactor.flush_now();

        value.set(2);
        reactor.flush_now();
        assert_eq!(*inner_errors.borrow(), ["inner child"]);
        assert!(
            outer_errors.borrow().is_empty(),
            "the inner boundary caught it"
        );

        value.set(3);
        reactor.flush_now();
        assert_eq!(*outer_errors.borrow(), ["outer child"]);
        assert_eq!(*inner_errors.borrow(), ["inner child"], "unchanged");

        boundary.dispose();
    }

    #[test]
    fn a_boundary_catches_effects_nested_below_it() {
        // The handler is found through the *lexical* owner chain, which must survive the effect
        // being run later from an empty owner stack.
        let reactor = Reactor::new();
        let (errors, handler) = error_log();
        let value = signal_in(&reactor, 1);

        let (boundary, ()) = scope_catch(
            {
                let reactor = reactor.clone();
                let value = value.clone();
                move || {
                    let (nested, ()) = scope({
                        let reactor = reactor.clone();
                        let value = value.clone();
                        move || {
                            reactor
                                .effect({
                                    let value = value.clone();
                                    move || {
                                        if value.get() == 2 {
                                            panic!("deep");
                                        }
                                    }
                                })
                                .leak();
                        }
                    });
                    nested.leak();
                }
            },
            handler,
        );

        reactor.flush_now();
        value.set(2);
        reactor.flush_now();
        assert_eq!(
            *errors.borrow(),
            ["deep"],
            "a plain scope between the effect and the boundary is transparent"
        );

        boundary.dispose();
    }

    #[test]
    fn error_info_reports_the_effects_creation_site() {
        let reactor = Reactor::new();
        type Captured = Rc<RefCell<Option<(u64, Option<String>, Option<u32>)>>>;
        let captured: Captured = Rc::new(RefCell::new(None));
        let value = signal_in(&reactor, 1);

        let (boundary, creation_line) = scope_catch(
            {
                let reactor = reactor.clone();
                let value = value.clone();
                move || {
                    // Hoisted so the creation call below is a single short statement: it keeps
                    // the panic site on a different line from the `#[track_caller]` call site,
                    // which is the distinction this test exists to check.
                    let body = move || {
                        if value.get() == 2 {
                            panic!("located");
                        }
                    };
                    let creation_line = line!() + 1;
                    reactor.effect(body).leak();
                    creation_line
                }
            },
            {
                let captured = Rc::clone(&captured);
                move |error: ErrorInfo| {
                    *captured.borrow_mut() = Some((
                        error.node().get(),
                        // `Location::file` uses the host's path separator, so compare the file
                        // name rather than a hardcoded path.
                        error.origin().and_then(|origin| {
                            origin
                                .file()
                                .rsplit(['/', '\\'])
                                .next()
                                .map(alloc::string::ToString::to_string)
                        }),
                        error.origin().map(core::panic::Location::line),
                    ));
                }
            },
        );

        reactor.flush_now();
        value.set(2);
        reactor.flush_now();

        let captured = captured.borrow();
        let (node, file, line) = captured.as_ref().expect("the handler ran");
        assert!(*node > 0);
        assert_eq!(file.as_deref(), Some("scope.rs"));
        assert_eq!(
            *line,
            Some(creation_line),
            "the origin points at the effect's creation site, not where it panicked"
        );

        boundary.dispose();
    }

    #[test]
    fn a_panic_during_dependency_verification_reaches_the_boundary() {
        // Verification executes upstream computations, so it is a distinct failure path from the
        // effect body — and one an unguarded effect recovers from by re-queueing, which would
        // spin forever behind a boundary if disposal did not stop it.
        let reactor = Reactor::new();
        let (errors, handler) = error_log();
        let value = signal_in(&reactor, 1);

        let upstream = reactor.memo({
            let value = value.clone();
            move || {
                if value.get() == 2 {
                    panic!("upstream exploded");
                }
                value.get()
            }
        });

        let (boundary, ()) = scope_catch(
            {
                let reactor = reactor.clone();
                let upstream = upstream.clone();
                move || {
                    reactor
                        .effect(move || {
                            upstream.get();
                        })
                        .leak();
                }
            },
            handler,
        );

        reactor.flush_now();
        assert!(errors.borrow().is_empty());

        value.set(2);
        reactor.flush_now();
        assert_eq!(*errors.borrow(), ["upstream exploded"]);

        // Crucially, it does not spin: the effect was disposed rather than re-queued.
        reactor.flush_now();
        assert_eq!(*errors.borrow(), ["upstream exploded"]);

        boundary.dispose();
    }

    #[test]
    fn an_unowned_effect_is_outside_every_boundary() {
        // Coverage follows ownership, and `unowned` opts out of it. Pinned because the escape is
        // surprising enough to be worth a deliberate decision rather than an accident.
        let reactor = Reactor::new();
        let (errors, handler) = error_log();
        let value = signal_in(&reactor, 1);

        let (boundary, effect) = scope_catch(
            {
                let reactor = reactor.clone();
                let value = value.clone();
                move || {
                    unowned(|| {
                        reactor.effect(move || {
                            if value.get() == 2 {
                                panic!("escaped");
                            }
                        })
                    })
                }
            },
            handler,
        );
        reactor.flush_now();

        value.set(2);
        let result = catch_unwind(AssertUnwindSafe(|| reactor.flush_now()));
        assert!(result.is_err(), "the panic propagates past the boundary");
        assert!(errors.borrow().is_empty(), "the handler was not consulted");

        effect.dispose();
        boundary.dispose();
    }

    #[test]
    fn on_cleanup_outside_an_owner_panics() {
        let result = catch_unwind(AssertUnwindSafe(|| on_cleanup(|| {})));
        let panic = result.expect_err("on_cleanup should panic outside an owner");
        let message = panic
            .downcast_ref::<&str>()
            .expect("panic payload should be a string");
        assert!(message.contains("outside a reactive owner"));
    }

    #[test]
    fn disposing_a_scope_disposes_owned_effects_and_runs_cleanups() {
        let seen = Rc::new(RefCell::new(Vec::new()));
        let events = Rc::new(RefCell::new(Vec::<&'static str>::new()));

        queue_macrotask({
            let seen = Rc::clone(&seen);
            let events = Rc::clone(&events);
            move || {
                let reactor = Reactor::new();
                let source = signal_in(&reactor, 1usize);

                let (handle, source) = scope({
                    let seen = Rc::clone(&seen);
                    let events = Rc::clone(&events);
                    move || {
                        // The scope owns this effect: no handle is kept, yet it stays alive
                        // until the scope is disposed.
                        let _ = reactor.effect({
                            let seen = Rc::clone(&seen);
                            let source = source.clone();
                            move || seen.borrow_mut().push(source.get())
                        });
                        on_cleanup({
                            let events = Rc::clone(&events);
                            move || events.borrow_mut().push("scope cleanup")
                        });
                        source
                    }
                });

                runite::queue_macrotask({
                    let events = Rc::clone(&events);
                    move || {
                        source.set(2);

                        runite::queue_macrotask(move || {
                            assert!(!handle.is_disposed());
                            handle.dispose();
                            assert!(handle.is_disposed());
                            events.borrow_mut().push("disposed");

                            // Writes after disposal must not rerun the effect.
                            source.set(3);
                        });
                    }
                });
            }
        });

        run();
        assert_eq!(&*seen.borrow(), &[1, 2]);
        assert_eq!(&*events.borrow(), &["scope cleanup", "disposed"]);
    }

    #[test]
    fn effect_reruns_dispose_nested_effects_and_run_cleanups() {
        let events = Rc::new(RefCell::new(Vec::<String>::new()));
        let scope_slot = Rc::new(RefCell::new(None::<ScopeHandle>));

        queue_macrotask({
            let events = Rc::clone(&events);
            let scope_slot = Rc::clone(&scope_slot);
            move || {
                let reactor = Reactor::new();
                let outer_dep = signal_in(&reactor, 0usize);
                let inner_dep = signal_in(&reactor, 0usize);

                let (handle, ()) = scope({
                    let events = Rc::clone(&events);
                    let outer_dep = outer_dep.clone();
                    let inner_dep = inner_dep.clone();
                    let inner_reactor = reactor.clone();
                    move || {
                        let _ = reactor.effect({
                            let events = Rc::clone(&events);
                            let outer_dep = outer_dep.clone();
                            let inner_dep = inner_dep.clone();
                            move || {
                                let generation = outer_dep.get();
                                events.borrow_mut().push(format!("outer {generation}"));
                                on_cleanup({
                                    let events = Rc::clone(&events);
                                    move || {
                                        events.borrow_mut().push(format!("cleanup {generation}"))
                                    }
                                });
                                // A nested effect, re-created on every outer run. The previous
                                // generation must be disposed before this one is created.
                                let _ = crate::effect_in(&inner_reactor, {
                                    let events = Rc::clone(&events);
                                    let inner_dep = inner_dep.clone();
                                    move || {
                                        events.borrow_mut().push(format!(
                                            "inner {generation}: {}",
                                            inner_dep.get()
                                        ));
                                    }
                                });
                            }
                        });
                    }
                });
                *scope_slot.borrow_mut() = Some(handle);

                runite::queue_macrotask({
                    let inner_dep = inner_dep.clone();
                    move || {
                        inner_dep.set(1);

                        runite::queue_macrotask({
                            let outer_dep = outer_dep.clone();
                            move || {
                                outer_dep.set(1);

                                runite::queue_macrotask(move || {
                                    // Only the generation-1 inner effect may respond now.
                                    inner_dep.set(2);
                                });
                            }
                        });
                    }
                });
            }
        });

        run();
        assert_eq!(
            &*events.borrow(),
            &[
                "outer 0",
                "inner 0: 0",
                "inner 0: 1",
                "cleanup 0",
                "outer 1",
                "inner 1: 1",
                "inner 1: 2",
            ]
        );
    }

    #[test]
    fn a_panicking_scope_closure_still_runs_registered_cleanups() {
        use std::cell::Cell;

        let ran = Rc::new(Cell::new(false));

        let result = catch_unwind(AssertUnwindSafe({
            let ran = Rc::clone(&ran);
            move || {
                let _ = scope(move || {
                    on_cleanup(move || ran.set(true));
                    panic!("scope body panics");
                });
            }
        }));

        assert!(result.is_err());
        assert!(
            ran.get(),
            "cleanups registered before the panic must still run"
        );
    }

    #[test]
    fn problem_effects_created_after_an_await_escape_their_scope() {
        // Validates the problem Owner exists to solve: ownership is established by the owner
        // stack at creation time, so an effect created in a spawned task -- after the scope
        // closure has returned -- is NOT owned by the scope, and disposing the scope does not
        // stop it. (See `owner_run_in_reattaches_async_work_to_its_scope` for the fix.)
        let seen = Rc::new(RefCell::new(Vec::new()));

        queue_macrotask({
            let seen = Rc::clone(&seen);
            move || {
                let reactor = Reactor::new();
                let data = signal_in(&reactor, 0usize);

                let (handle, ()) = scope({
                    let reactor = reactor.clone();
                    let data = data.clone();
                    let seen = Rc::clone(&seen);
                    move || {
                        std::mem::drop(runite::spawn(async move {
                            runite::yield_now().await;
                            // The scope closure returned long ago: this effect is unowned.
                            crate::effect_in(&reactor, {
                                let data = data.clone();
                                let seen = Rc::clone(&seen);
                                move || seen.borrow_mut().push(data.get())
                            })
                            .leak();
                        }));
                    }
                });

                runite::queue_macrotask({
                    let data = data.clone();
                    move || {
                        handle.dispose();
                        // The scope is gone, but the escaped effect still reacts.
                        data.set(1);
                    }
                });
            }
        });

        run();
        assert_eq!(
            &*seen.borrow(),
            &[0, 1],
            "without owner capture, the effect escapes its scope (this documents the problem)"
        );
    }

    #[test]
    fn owner_run_in_reattaches_async_work_to_its_scope() {
        let seen = Rc::new(RefCell::new(Vec::new()));

        queue_macrotask({
            let seen = Rc::clone(&seen);
            move || {
                let reactor = Reactor::new();
                let data = signal_in(&reactor, 0usize);

                let (handle, ()) = scope({
                    let reactor = reactor.clone();
                    let data = data.clone();
                    let seen = Rc::clone(&seen);
                    move || {
                        // Capture the owner before suspending...
                        let scope_owner = super::owner().expect("scope should be the owner");
                        std::mem::drop(runite::spawn(async move {
                            runite::yield_now().await;
                            // ...and re-enter it after the await: the effect is owned again.
                            scope_owner.run_in(|| {
                                let _ = crate::effect_in(&reactor, {
                                    let data = data.clone();
                                    let seen = Rc::clone(&seen);
                                    move || seen.borrow_mut().push(data.get())
                                });
                            });
                        }));
                    }
                });

                runite::queue_macrotask({
                    let data = data.clone();
                    move || {
                        handle.dispose();
                        // Disposed with the scope: this write must not be observed.
                        data.set(1);
                    }
                });
            }
        });

        run();
        assert_eq!(
            &*seen.borrow(),
            &[0],
            "the re-attached effect must be disposed with its scope"
        );
    }

    #[test]
    fn run_in_on_a_disposed_owner_disposes_children_immediately() {
        let seen = Rc::new(RefCell::new(Vec::new()));

        queue_macrotask({
            let seen = Rc::clone(&seen);
            move || {
                let reactor = Reactor::new();
                let data = signal_in(&reactor, 0usize);

                let (handle, ()) = scope(|| {});
                let scope_owner = handle.owner();
                handle.dispose();
                assert!(scope_owner.is_disposed());

                scope_owner.run_in(|| {
                    let _ = crate::effect_in(&reactor, {
                        let data = data.clone();
                        let seen = Rc::clone(&seen);
                        move || seen.borrow_mut().push(data.get())
                    });
                });
                reactor.flush_now();
            }
        });

        run();
        assert!(
            seen.borrow().is_empty(),
            "children created under a disposed owner must never run"
        );
    }

    #[test]
    fn unowned_suppresses_the_enclosing_owner_at_the_boundary_only() {
        let (_handle, ()) = scope(|| {
            assert!(super::owner().is_some(), "the scope is the current owner");
            super::unowned(|| {
                assert!(
                    super::owner().is_none(),
                    "no owner is current inside unowned"
                );
                // An owner established inside `unowned` works normally.
                let (_inner, ()) = scope(|| {
                    assert!(
                        super::owner().is_some(),
                        "a scope created inside unowned is the current owner"
                    );
                });
            });
            assert!(
                super::owner().is_some(),
                "the enclosing owner is restored after unowned returns"
            );
        });
    }

    #[test]
    fn unowned_effects_escape_their_scope_and_die_with_their_handle() {
        let seen = Rc::new(RefCell::new(Vec::new()));

        queue_macrotask({
            let seen = Rc::clone(&seen);
            move || {
                let reactor = Reactor::new();
                let data = signal_in(&reactor, 0usize);

                let (handle, background) = scope({
                    let reactor = reactor.clone();
                    let data = data.clone();
                    let seen = Rc::clone(&seen);
                    move || {
                        super::unowned(|| {
                            crate::effect_in(&reactor, {
                                let data = data.clone();
                                let seen = Rc::clone(&seen);
                                move || seen.borrow_mut().push(data.get())
                            })
                        })
                    }
                });

                runite::queue_macrotask({
                    let data = data.clone();
                    move || {
                        handle.dispose();
                        // The scope is gone, but the unowned effect still reacts.
                        data.set(1);

                        runite::queue_macrotask(move || {
                            // The last handle is the effect's only tether.
                            drop(background);
                            data.set(2);
                        });
                    }
                });
            }
        });

        run();
        assert_eq!(
            &*seen.borrow(),
            &[0, 1],
            "the effect must survive scope disposal and die when its handle drops"
        );
    }

    #[test]
    fn nested_scopes_are_disposed_with_their_parent() {
        let (parent, child) = scope(|| {
            let (child, ()) = scope(|| {});
            child
        });

        assert!(!child.is_disposed());
        parent.dispose();
        assert!(
            child.is_disposed(),
            "disposing the parent scope must dispose nested scopes"
        );
    }
}