krab_core 0.2.0

Shared runtime for the Krab framework: config, HTTP, database, telemetry, resilience, signals, and protocol governance
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
//! Krab reactive signal system.
//!
//! # Threading constraints
//!
//! **Signals are single-threaded.**  They use [`Rc`] and [`RefCell`] internally
//! so the Rust type system **statically prevents** moving a signal across thread
//! boundaries (`Rc` is `!Send + !Sync`).  Attempting to do so is a **compile
//! error**, not a runtime failure.
//!
//! Signals must only be created and used on the same thread.  In a server-side
//! rendering context (non-WASM), this means each request should set up its own
//! signal graph on the request handler thread.  In a WASM context there is
//! always exactly one thread (the JS event loop), so this is naturally enforced.
//!
//! Do **not** wrap signals in `Arc<Mutex<...>>` to try to share them across
//! threads — the design intentionally avoids locking overhead.  For shared
//! mutable state across async tasks, use the standard tokio primitives
//! (`Arc<Mutex<T>>`, channels, `tokio::sync::RwLock<T>`).
//!
//! The compile-time enforcement is verified by the `signals_are_not_send_sync`
//! test in this module.

use std::cell::{Cell, RefCell};
use std::rc::{Rc, Weak};
use std::sync::atomic::{AtomicU64, Ordering};

thread_local! {
    /// The reactive node currently executing, if any. Reads subscribe to it.
    static CURRENT_SUBSCRIBER: RefCell<Option<Subscriber>> = const { RefCell::new(None) };
    static ROOT_EFFECTS: RefCell<Vec<Rc<EffectState>>> = const { RefCell::new(Vec::new()) };
    /// Depth of nested [`batch`] scopes; effects are held while non-zero.
    static BATCH_DEPTH: Cell<u32> = const { Cell::new(0) };
    /// Effects deferred by an open [`batch`], deduplicated.
    static BATCHED_EFFECTS: RefCell<Vec<Rc<EffectState>>> = const { RefCell::new(Vec::new()) };
    #[cfg(feature = "web")]
    static PENDING_EFFECTS: RefCell<Vec<Rc<EffectState>>> = const { RefCell::new(Vec::new()) };
    #[cfg(feature = "web")]
    static MICROTASK_QUEUED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Something that depends on a signal.
///
/// A memo is both a subscriber *and* a source, which is why this is an enum
/// rather than a list of effects: `source -> memo -> effect` needs the middle
/// link to be notifiable and to notify in turn.
#[derive(Clone)]
enum Subscriber {
    Effect(Weak<EffectState>),
    Memo(Weak<MemoState>),
}

impl Subscriber {
    /// Whether two subscribers refer to the same reactive node.
    fn same_node(&self, other: &Subscriber) -> bool {
        match (self, other) {
            (Self::Effect(a), Self::Effect(b)) => Weak::ptr_eq(a, b),
            (Self::Memo(a), Self::Memo(b)) => Weak::ptr_eq(a, b),
            _ => false,
        }
    }
}

/// Subscribe `subscriber` unless the list's last entry is already it.
///
/// `get()` subscribes on every read, so an effect reading a signal `k` times in
/// one run would otherwise land `k` identical entries — and for a source that is
/// read by a re-running dependent but never itself written (so never drained),
/// the list grew by one per run for the life of the page.
fn push_subscriber(list: &mut Vec<Subscriber>, subscriber: &Subscriber) {
    if let Some(last) = list.last() {
        if last.same_node(subscriber) {
            return;
        }
    }
    list.push(subscriber.clone());
}

/// Restores [`CURRENT_SUBSCRIBER`] whether the scope exits normally or unwinds.
///
/// The same reasoning as [`BatchGuard`]: island factories run under
/// `catch_unwind` and `error_boundary` makes a panic recoverable, so execution
/// continues past one. Without this, a panic inside an effect, memo
/// computation, or `untrack` scope left the thread-local pointing at the
/// panicked node — every later read subscribed a zombie, and every later
/// `create_effect` was adopted by it and mass-disposed on its next run.
/// Restoring an `Option` in `Drop` runs no user code, so it cannot double-panic.
struct SubscriberGuard {
    previous: Option<Subscriber>,
}

impl SubscriberGuard {
    fn swap_in(next: Option<Subscriber>) -> Self {
        Self {
            previous: CURRENT_SUBSCRIBER.with(|current| current.replace(next)),
        }
    }
}

impl Drop for SubscriberGuard {
    fn drop(&mut self) {
        CURRENT_SUBSCRIBER.with(|current| {
            current.replace(self.previous.take());
        });
    }
}

/// A cached derived value.
///
/// Type-erased: the computed value lives in an `Rc<RefCell<Option<T>>>` closed
/// over by `recompute`, so memos of different `T` share one subscriber list.
struct MemoState {
    /// Whether a dependency changed since the last computation.
    ///
    /// Set by propagation, cleared on read. This split — mark dirty on write,
    /// recompute on read — is what makes a diamond settle once: both branches
    /// are marked before either is pulled, so the effect downstream runs once
    /// and sees two fresh values.
    dirty: Cell<bool>,
    /// Recomputes the cached value. Installed after construction, because it
    /// needs a `Weak` back to the state it lives in.
    recompute: RefCell<Option<Box<dyn Fn()>>>,
    subscribers: RefCell<Vec<Subscriber>>,
    disposed: Cell<bool>,
}

impl MemoState {
    /// Recompute now, tracking dependencies against this memo.
    ///
    /// Unwind-safe: the taken closure, the previous subscriber, and the dirty
    /// flag are all restored by guards if the computation panics, so a caught
    /// panic (island factories, `error_boundary`) leaves the memo stale and
    /// retryable — not permanently poisoned serving its old value.
    fn recompute_now(self: &Rc<Self>) {
        // Cleared before running so a read of this memo from inside its own
        // computation cannot re-enter and recurse.
        self.dirty.set(false);

        let _subscriber = SubscriberGuard::swap_in(Some(Subscriber::Memo(Rc::downgrade(self))));

        // The closure is taken out for the call: it may read other memos, whose
        // recomputation would otherwise need a second borrow of this RefCell.
        // The guard puts it back even if the computation unwinds — without
        // that, one caught panic left `recompute` empty forever and every
        // later read served the stale cached value with no way to recover.
        struct RecomputeGuard<'a> {
            state: &'a MemoState,
            compute: Option<Box<dyn Fn()>>,
            completed: bool,
        }
        impl Drop for RecomputeGuard<'_> {
            fn drop(&mut self) {
                *self.state.recompute.borrow_mut() = self.compute.take();
                if !self.completed {
                    // The computation did not finish, so the cached value is
                    // still the old one: stay dirty so the next read retries
                    // instead of serving it as fresh.
                    self.state.dirty.set(true);
                }
            }
        }

        let mut guard = RecomputeGuard {
            state: self,
            compute: self.recompute.borrow_mut().take(),
            completed: false,
        };
        if let Some(compute) = guard.compute.as_ref() {
            compute();
        }
        guard.completed = true;
    }
}

struct EffectState {
    execute: Box<dyn Fn()>,
    /// Set when this effect is torn down. A disposed effect never runs again,
    /// even if a stale subscription still points at it.
    disposed: Cell<bool>,
    /// Effects created *during* this effect's last run.
    ///
    /// This is what makes disposal possible. `create_dom_node` calls
    /// `create_effect` for every nested `Dynamic` it builds, so without
    /// ownership every re-render of a parent left the previous run's effects
    /// alive, still subscribed, still patching DOM nodes that had already been
    /// detached. Ten updates meant ten zombie effects doing work.
    children: RefCell<Vec<Rc<EffectState>>>,
    /// Memos created during this effect's last run, disposed with it.
    owned_memos: RefCell<Vec<Rc<MemoState>>>,
    /// Callbacks registered by [`on_cleanup`] during the last run.
    cleanups: RefCell<Vec<Box<dyn FnOnce()>>>,
}

impl EffectState {
    fn run(&self) {
        (self.execute)();
    }

    /// Release everything the last run created: cleanups first, then children.
    ///
    /// Both collections are moved out before anything is invoked, so a cleanup
    /// that itself calls [`on_cleanup`] or creates an effect cannot re-enter a
    /// live `RefCell` borrow and panic.
    fn dispose_children(&self) {
        let cleanups = std::mem::take(&mut *self.cleanups.borrow_mut());
        for cleanup in cleanups {
            cleanup();
        }

        let memos = std::mem::take(&mut *self.owned_memos.borrow_mut());
        for memo in memos {
            memo.disposed.set(true);
        }

        let children = std::mem::take(&mut *self.children.borrow_mut());
        for child in children {
            child.dispose();
        }
    }

    /// Tear this effect down permanently, and everything it owns.
    fn dispose(&self) {
        self.disposed.set(true);
        self.dispose_children();
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
struct SignalId(u64);

impl SignalId {
    fn new() -> Self {
        static NEXT_ID: AtomicU64 = AtomicU64::new(0);
        SignalId(NEXT_ID.fetch_add(1, Ordering::Relaxed))
    }
}

struct SignalState<T> {
    value: T,
    subscribers: Vec<Subscriber>,
}

struct SignalInner<T> {
    id: SignalId,
    state: Rc<RefCell<SignalState<T>>>,
}

impl<T> Clone for SignalInner<T> {
    fn clone(&self) -> Self {
        Self {
            id: self.id,
            state: self.state.clone(),
        }
    }
}

pub fn create_signal<T>(value: T) -> (ReadSignal<T>, WriteSignal<T>) {
    let inner = SignalInner {
        id: SignalId::new(),
        state: Rc::new(RefCell::new(SignalState {
            value,
            subscribers: Vec::new(),
        })),
    };

    (
        ReadSignal {
            inner: inner.clone(),
        },
        WriteSignal { inner },
    )
}

pub struct ReadSignal<T> {
    inner: SignalInner<T>,
}

impl<T> Clone for ReadSignal<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<T: Clone> ReadSignal<T> {
    pub fn get(&self) -> T {
        // Track dependency
        CURRENT_SUBSCRIBER.with(|current| {
            if let Some(subscriber) = current.borrow().as_ref() {
                let mut state = self.inner.state.borrow_mut();
                push_subscriber(&mut state.subscribers, subscriber);
            }
        });
        self.inner.state.borrow().value.clone()
    }
}

impl<T> ReadSignal<T> {
    pub fn with<U, F>(&self, f: F) -> U
    where
        F: FnOnce(&T) -> U,
    {
        CURRENT_SUBSCRIBER.with(|current| {
            if let Some(subscriber) = current.borrow().as_ref() {
                let mut state = self.inner.state.borrow_mut();
                push_subscriber(&mut state.subscribers, subscriber);
            }
        });
        let state = self.inner.state.borrow();
        f(&state.value)
    }
}

pub struct WriteSignal<T> {
    inner: SignalInner<T>,
}

impl<T> Clone for WriteSignal<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<T> WriteSignal<T> {
    pub fn set(&self, new_value: T) {
        {
            let mut state = self.inner.state.borrow_mut();
            state.value = new_value;
        } // Drop borrow

        self.notify();
    }

    pub fn update<F>(&self, f: F)
    where
        F: FnOnce(&mut T),
    {
        {
            let mut state = self.inner.state.borrow_mut();
            f(&mut state.value);
        }
        self.notify();
    }

    fn notify(&self) {
        // Subscribers are drained before running: effects re-subscribe to the
        // signals they read, so keeping the old entries would compound them on
        // every notification.
        //
        // Deduplicated here rather than per-platform. `get()` and `with()`
        // subscribe on every read, so an effect that reads a signal three times
        // lands three subscriptions. The wasm path already collapsed those in
        // `PENDING_EFFECTS`; the native path did not, and ran the effect once
        // per read. Disposed effects are dropped too — a stale subscription
        // must not resurrect one.
        let subscribers: Vec<Subscriber> = {
            let mut state = self.inner.state.borrow_mut();
            state.subscribers.drain(..).collect()
        };

        let mut to_run: Vec<Rc<EffectState>> = Vec::new();
        for subscriber in subscribers {
            collect_dependents(&subscriber, &mut to_run);
        }

        schedule_effects(to_run);
    }
}

/// Queue `effect` unless the same `Rc` is already queued.
///
/// One definition for the dedup rule all queues share — previously four
/// hand-rolled copies that had to stay identical.
fn push_unique(queue: &mut Vec<Rc<EffectState>>, effect: Rc<EffectState>) {
    if !queue.iter().any(|seen| Rc::ptr_eq(seen, &effect)) {
        queue.push(effect);
    }
}

/// Drop `effects` from the wasm microtask queue before a synchronous flush.
///
/// A batch flush runs its effects immediately; any of them still sitting in
/// [`PENDING_EFFECTS`] from an earlier unbatched write in the same task would
/// otherwise be run a second time when the microtask fires — observing no state
/// change, but paying a full dispose-and-rebuild cycle (or issuing a duplicate
/// identical fetch from a `Resource`). Removal happens *before* the flush so a
/// write occurring during it can legitimately re-enqueue.
fn unschedule_pending(#[allow(unused_variables)] effects: &[Rc<EffectState>]) {
    #[cfg(all(feature = "web", target_arch = "wasm32"))]
    PENDING_EFFECTS.with(|pending| {
        pending
            .borrow_mut()
            .retain(|queued| !effects.iter().any(|e| Rc::ptr_eq(e, queued)));
    });
}

/// Hand effects to the platform runner, or hold them if a [`batch`] is open.
///
/// One place decides *when* effects run, so `batch` does not need a second
/// mechanism and cannot diverge from the unbatched path.
fn schedule_effects(effects: Vec<Rc<EffectState>>) {
    if BATCH_DEPTH.with(|depth| depth.get()) > 0 {
        queue_batched(effects);
        return;
    }

    // A batch that unwound left its queue behind deliberately (running effects
    // while a panic is in flight risks a double panic, which aborts). Draining
    // it here means those notifications are delivered by the next write rather
    // than stranded.
    let mut pending = take_batched();
    for effect in effects {
        push_unique(&mut pending, effect);
    }

    if pending.is_empty() {
        return;
    }

    schedule_async(pending);
}

fn queue_batched(effects: Vec<Rc<EffectState>>) {
    BATCHED_EFFECTS.with(|batched| {
        let mut batched = batched.borrow_mut();
        for effect in effects {
            push_unique(&mut batched, effect);
        }
    });
}

fn take_batched() -> Vec<Rc<EffectState>> {
    BATCHED_EFFECTS.with(|batched| std::mem::take(&mut *batched.borrow_mut()))
}

/// Run effects immediately, on every platform.
///
/// Used to flush a [`batch`], so the scope has the same observable timing in a
/// browser as it does natively.
fn run_now(effects: Vec<Rc<EffectState>>) {
    for effect in effects {
        run_effect(effect);
    }
}

/// Restores [`BATCH_DEPTH`] whether the scope exits normally or unwinds.
///
/// Without this a panic inside a batch left the depth raised forever, and every
/// later write on that thread queued into [`BATCHED_EFFECTS`] and was never
/// flushed — the reactive system silently stopped working. That is not
/// hypothetical: `krab_client` wraps island factories in `catch_unwind`, and
/// `error_boundary` exists precisely to make a panic recoverable, so execution
/// really does continue past one.
struct BatchGuard;

impl BatchGuard {
    fn enter() -> Self {
        BATCH_DEPTH.with(|depth| depth.set(depth.get() + 1));
        Self
    }
}

impl Drop for BatchGuard {
    fn drop(&mut self) {
        BATCH_DEPTH.with(|depth| depth.set(depth.get().saturating_sub(1)));
    }
}

/// Deliver effects using the platform's own scheduling.
///
/// On wasm this coalesces into a microtask, which is an implicit per-task batch;
/// natively there is no such queue, so they run immediately. Use [`batch`] when
/// you need the same observable behaviour on both.
fn schedule_async(#[allow(unused_variables)] effects: Vec<Rc<EffectState>>) {
    #[cfg(all(feature = "web", target_arch = "wasm32"))]
    {
        PENDING_EFFECTS.with(|pending| {
            let mut p = pending.borrow_mut();
            for effect in effects {
                push_unique(&mut p, effect);
            }
        });

        if !MICROTASK_QUEUED.with(|q| q.get()) {
            MICROTASK_QUEUED.with(|q| q.set(true));
            let closure = wasm_bindgen::closure::Closure::once(|_val: wasm_bindgen::JsValue| {
                MICROTASK_QUEUED.with(|q| q.set(false));
                let effects = PENDING_EFFECTS.with(|pending| {
                    let mut p = pending.borrow_mut();
                    std::mem::take(&mut *p)
                });
                for effect in effects {
                    run_effect(effect);
                }
            });

            let promise = js_sys::Promise::resolve(&wasm_bindgen::JsValue::UNDEFINED);
            let _ = promise.then(&closure);
            closure.forget();
        }
    }

    #[cfg(any(not(feature = "web"), not(target_arch = "wasm32")))]
    {
        for effect in effects {
            run_effect(effect);
        }
    }
}

/// Group writes so dependent effects run once, after the last one.
///
/// Without this, each `set()` fans out immediately: three writes that share a
/// dependent effect run it three times, and observers can see intermediate
/// states that never logically existed.
///
/// ```
/// use krab_core::signal::{batch, create_signal, create_effect};
///
/// let (first, set_first) = create_signal(0);
/// let (second, set_second) = create_signal(0);
///
/// create_effect(move || {
///     let _ = first.get();
///     let _ = second.get();
/// });
///
/// batch(|| {
///     set_first.set(1);
///     set_second.set(2);
/// }); // the effect runs once here, not twice
/// ```
///
/// Nesting is safe: only the outermost `batch` flushes.
///
/// # Guarantees
///
/// Effects have run by the time `batch` returns, on **every** platform. An
/// unbatched write does not promise this: on wasm it coalesces into a microtask
/// and runs just after the current task, while natively it runs immediately.
/// `batch` is therefore the portable way to get deterministic behaviour — both
/// the run count and the moment.
///
/// # Panics
///
/// If `f` panics, the batch depth is restored and the panic propagates. The
/// queued effects are **not** run while unwinding — invoking user code from a
/// `Drop` during a panic risks a second panic, which aborts the process — so
/// they are delivered by the next write instead.
///
/// This matters because panics here are recoverable in practice:
/// `krab_client` wraps island factories in `catch_unwind`, and
/// [`error_boundary`](crate::error_boundary) exists to keep rendering after
/// one. An earlier version leaked the raised depth on unwind, which silently
/// stopped every subsequent effect on the thread from ever running.
pub fn batch<T, F>(f: F) -> T
where
    F: FnOnce() -> T,
{
    let result = {
        // Restores the depth on unwind as well as on the normal path.
        let _guard = BatchGuard::enter();
        f()
    };

    // Reached only when `f` returned normally. On unwind the queue is left in
    // place on purpose — running user effects from a `Drop` during a panic
    // risks a second panic, which aborts. `schedule_effects` drains the
    // leftovers on the next write instead.
    if BATCH_DEPTH.with(|depth| depth.get()) == 0 {
        let effects = take_batched();
        // On wasm, cancel any still-pending microtask delivery for these
        // effects: the flush below already delivers the latest state, and the
        // stale entry would re-run them for nothing.
        unschedule_pending(&effects);
        run_now(effects);
    }

    result
}

/// Walk a subscriber, marking memos dirty and collecting the effects to run.
///
/// Memos are marked but **not** recomputed. Recomputation happens on read, so a
/// diamond (`source -> a`, `source -> b`, `effect(a, b)`) marks both branches
/// before the effect runs, and the effect then pulls two already-fresh values.
/// Recomputing eagerly here would run the effect once per branch — the glitch
/// this ordering exists to prevent.
///
/// Traversal does not stop at an already-dirty memo. A memo can be dirtied by
/// one write and, before any read, dirtied again by another; skipping it would
/// drop the second write's effects. Effects are deduplicated by pointer, so
/// revisiting a node is redundant work rather than a duplicate run.
fn collect_dependents(subscriber: &Subscriber, effects: &mut Vec<Rc<EffectState>>) {
    match subscriber {
        Subscriber::Effect(weak) => {
            let Some(effect) = weak.upgrade() else {
                return;
            };
            if effect.disposed.get() {
                return;
            }
            push_unique(effects, effect);
        }
        Subscriber::Memo(weak) => {
            let Some(memo) = weak.upgrade() else {
                return;
            };
            if memo.disposed.get() {
                return;
            }
            memo.dirty.set(true);

            // Drained, exactly as `WriteSignal::notify` drains a signal's
            // list: dependents re-subscribe on their next read. Cloning here
            // (the previous behaviour) left every historical subscription in
            // place, so the list grew by one entry per dependent re-run for
            // the memo's whole life — an unbounded leak with O(n) walk cost
            // per write. Draining also garbage-collects dead `Weak`s. Moved
            // out before recursing: a dependent may read back into this list.
            let downstream: Vec<Subscriber> = memo.subscribers.borrow_mut().drain(..).collect();
            for next in &downstream {
                collect_dependents(next, effects);
            }
        }
    }
}

/// Read signals without subscribing to them.
///
/// Inside an effect or memo, every `get()` creates a dependency. `untrack` is
/// the escape hatch for reading state that should not cause a re-run — a
/// previous value, a configuration flag, a counter used only for logging.
///
/// ```
/// use krab_core::signal::{create_signal, create_effect, untrack};
///
/// let (tracked, set_tracked) = create_signal(0);
/// let (ignored, set_ignored) = create_signal(0);
///
/// create_effect(move || {
///     let _ = tracked.get();
///     let _ = untrack(|| ignored.get());
/// });
///
/// set_ignored.set(1); // does not re-run the effect
/// set_tracked.set(1); // does
/// ```
pub fn untrack<T, F>(f: F) -> T
where
    F: FnOnce() -> T,
{
    // Guard, not sequential replace calls: if `f` panics and the panic is
    // caught upstream, tracking must still be restored or every subsequent
    // read on the thread stays untracked.
    let _guard = SubscriberGuard::swap_in(None);
    f()
}

/// A cached derived value that recomputes only when a dependency changed.
///
/// Cloning is cheap and shares the same computation.
pub struct Memo<T> {
    state: Rc<MemoState>,
    value: Rc<RefCell<Option<T>>>,
}

impl<T> Clone for Memo<T> {
    fn clone(&self) -> Self {
        Self {
            state: self.state.clone(),
            value: self.value.clone(),
        }
    }
}

impl<T> Memo<T> {
    /// Subscribe the current reactive node, and recompute if stale.
    fn track_and_refresh(&self) {
        CURRENT_SUBSCRIBER.with(|current| {
            if let Some(subscriber) = current.borrow().as_ref() {
                push_subscriber(&mut self.state.subscribers.borrow_mut(), subscriber);
            }
        });

        if self.state.dirty.get() && !self.state.disposed.get() {
            self.state.recompute_now();
        }
    }

    /// Borrow the computed value.
    pub fn with<U, F>(&self, f: F) -> U
    where
        F: FnOnce(&T) -> U,
    {
        self.track_and_refresh();
        let value = self.value.borrow();
        let value = value
            .as_ref()
            .expect("memo value is absent after computation");
        f(value)
    }
}

impl<T: Clone> Memo<T> {
    /// The computed value, recomputing first if a dependency changed.
    pub fn get(&self) -> T {
        self.with(|value| value.clone())
    }
}

/// Create a cached derived value.
///
/// `f` runs once immediately, then only when a signal or memo it read has
/// changed **and** the memo is read again. A memo that nothing reads costs
/// nothing to keep up to date.
///
/// ```
/// use krab_core::signal::{create_signal, create_memo};
///
/// let (count, set_count) = create_signal(2);
/// let doubled = create_memo(move || count.get() * 2);
///
/// assert_eq!(doubled.get(), 4);
/// set_count.set(5);
/// assert_eq!(doubled.get(), 10);
/// ```
///
/// A memo created inside an effect is owned by it and disposed when that effect
/// re-runs, in the same way a nested effect is.
pub fn create_memo<T, F>(f: F) -> Memo<T>
where
    T: 'static,
    F: Fn() -> T + 'static,
{
    let value: Rc<RefCell<Option<T>>> = Rc::new(RefCell::new(None));
    let state = Rc::new(MemoState {
        // Starts dirty so the first read computes it; nothing is evaluated
        // until then.
        dirty: Cell::new(true),
        recompute: RefCell::new(None),
        subscribers: RefCell::new(Vec::new()),
        disposed: Cell::new(false),
    });

    {
        let value_slot = value.clone();
        *state.recompute.borrow_mut() = Some(Box::new(move || {
            let next = f();
            *value_slot.borrow_mut() = Some(next);
        }));
    }

    // Owned by the enclosing effect, if any, so it is disposed with it.
    CURRENT_SUBSCRIBER.with(|current| {
        if let Some(Subscriber::Effect(owner)) = current.borrow().as_ref() {
            if let Some(owner) = owner.upgrade() {
                owner.owned_memos.borrow_mut().push(state.clone());
            }
        }
    });

    let memo = Memo { state, value };
    // Compute eagerly once so `get()` never observes an empty slot, and so
    // dependencies are registered before the first write can occur.
    memo.state.recompute_now();
    memo
}

/// Run `f` now, and again whenever a signal it read changes.
///
/// # Ownership
///
/// An effect created *while another effect is running* becomes that effect's
/// child, and is disposed when the parent re-runs. Only a top-level effect —
/// one created outside any running effect — is retained for the lifetime of the
/// thread.
///
/// This is what stops nested [`Dynamic`](crate::Node::Dynamic) nodes leaking:
/// the client rebuilds their effects on every parent re-render, and without
/// ownership each rebuild left the previous effects subscribed and patching
/// detached DOM.
pub fn create_effect<F>(#[allow(unused_variables)] f: F)
where
    F: Fn() + 'static,
{
    #[cfg(any(feature = "web", test))]
    {
        let effect = Rc::new(EffectState {
            execute: Box::new(f),
            disposed: Cell::new(false),
            children: RefCell::new(Vec::new()),
            owned_memos: RefCell::new(Vec::new()),
            cleanups: RefCell::new(Vec::new()),
        });

        let owned_by_parent = CURRENT_SUBSCRIBER.with(|current| {
            match current.borrow().as_ref() {
                Some(Subscriber::Effect(parent)) => match parent.upgrade() {
                    Some(parent) => {
                        parent.children.borrow_mut().push(effect.clone());
                        true
                    }
                    None => false,
                },
                // An effect created inside a memo computation is not owned by
                // it: memos are meant to be pure, and adopting the effect would
                // silently dispose it on the next recomputation.
                _ => false,
            }
        });

        if !owned_by_parent {
            ROOT_EFFECTS.with(|roots| {
                roots.borrow_mut().push(effect.clone());
            });
        }

        run_effect(effect);
    }
}

/// Register a callback to run when the current effect is disposed or re-runs.
///
/// Outside an effect this is a no-op — there is nothing to attach to.
pub fn on_cleanup<F>(#[allow(unused_variables)] f: F)
where
    F: FnOnce() + 'static,
{
    #[cfg(any(feature = "web", test))]
    {
        CURRENT_SUBSCRIBER.with(|current| {
            let effect = match current.borrow().as_ref() {
                Some(Subscriber::Effect(effect)) => effect.upgrade(),
                _ => None,
            };
            if let Some(effect) = effect {
                effect.cleanups.borrow_mut().push(Box::new(f));
            }
        });
    }
}

fn run_effect(effect: Rc<EffectState>) {
    if effect.disposed.get() {
        return;
    }

    // A re-run invalidates everything the previous run created.
    effect.dispose_children();

    // Guard, not sequential replace calls: an effect body that panics under
    // `catch_unwind` must not leave the thread-local pointing at itself —
    // that zombie subscriber adopted every later top-level effect and then
    // mass-disposed them on its next run.
    let _guard = SubscriberGuard::swap_in(Some(Subscriber::Effect(Rc::downgrade(&effect))));
    effect.run();
}

#[cfg(test)]
mod tests {
    use super::*;

    // Compile-time guards: assert that signals are !Send and !Sync.
    // These lines will cause a compile error if someone accidentally makes
    // ReadSignal or WriteSignal implement Send or Sync.
    fn _assert_read_signal_not_send<T: 'static>() {
        fn _not_send<X: ?Sized + Send>() {}
        // This must NOT compile if ReadSignal is Send.
        // We use a negative impl check via a trait bound that we do NOT want.
        // The simplest approach: static assertions via trait object coercion.
        // Because Rc is !Send, this function body is unreachable but the type
        // check verifies ReadSignal<T> does not auto-impl Send.
        let _ = std::marker::PhantomData::<ReadSignal<T>>;
    }

    #[test]
    #[allow(dead_code, clippy::extra_unused_type_parameters)]
    fn signals_are_not_send_sync() {
        // Runtime confirmation that the types are as expected.
        // The real compile-time check is that Rc<RefCell<...>> is !Send + !Sync,
        // which the compiler enforces automatically.
        fn is_send<T: Send>() -> bool {
            true
        }
        fn is_not_send<T>() -> bool
        where
            T: ?Sized,
        {
            std::thread::available_parallelism().is_ok()
        }
        // These would be compile errors if ReadSignal or WriteSignal were Send:
        // is_send::<ReadSignal<i32>>();
        // is_send::<WriteSignal<i32>>();
        //
        // The runtime assertion below is a documentation aid only.
        let _ = is_not_send::<ReadSignal<i32>>;
        let _ = is_not_send::<WriteSignal<i32>>;
    }

    #[test]
    fn test_signal_basic() {
        let (read, write) = create_signal(0);
        assert_eq!(read.get(), 0);
        write.set(1);
        assert_eq!(read.get(), 1);
    }

    #[cfg(target_arch = "wasm32")]
    #[test]
    fn test_effect() {
        let (read, write) = create_signal(0);
        let output = Rc::new(RefCell::new(0));
        let output_clone = output.clone();

        create_effect(move || {
            *output_clone.borrow_mut() = read.get();
        });

        assert_eq!(*output.borrow(), 0);
        write.set(10);
        assert_eq!(*output.borrow(), 10);
    }

    #[test]
    fn test_clone_signal() {
        let (read, _) = create_signal(42);
        let read2 = read.clone();
        assert_eq!(read.get(), 42);
        assert_eq!(read2.get(), 42);
    }

    #[derive(Debug, PartialEq)]
    struct NonCloneable(i32);

    #[test]
    fn test_non_cloneable_signal() {
        // Signals hold T. ReadSignal::get() requires T: Clone.
        // But we can use ReadSignal::with()
        let (read, _write) = create_signal(NonCloneable(10));

        read.with(|v| assert_eq!(v, &NonCloneable(10)));

        // This should clone the signal handle, not the value inside (which is not cloneable)
        let read2 = read.clone();
        read2.with(|v| assert_eq!(v, &NonCloneable(10)));
    }
}

#[cfg(test)]
mod disposal_tests {
    use super::*;
    use std::cell::Cell as StdCell;
    use std::rc::Rc as StdRc;

    /// The leak, reduced: a parent effect that creates a child effect on every
    /// run. Before ownership existed, each parent re-run left the previous
    /// child alive and subscribed, so N parent runs meant N live children all
    /// reacting to the same signal.
    #[test]
    fn re_running_a_parent_disposes_the_children_of_its_previous_run() {
        let (outer, set_outer) = create_signal(0);
        let (inner, set_inner) = create_signal(0);

        let child_runs = StdRc::new(StdCell::new(0));
        let child_runs_effect = child_runs.clone();

        create_effect(move || {
            // Subscribe the parent to `outer`.
            let _ = outer.get();

            let counter = child_runs_effect.clone();
            let inner = inner.clone();
            create_effect(move || {
                let _ = inner.get();
                counter.set(counter.get() + 1);
            });
        });

        // Parent ran once, creating one child, which ran once.
        assert_eq!(child_runs.get(), 1);

        // Re-run the parent three times: each disposes the previous child and
        // creates a fresh one, so exactly one new child run each time.
        for _ in 0..3 {
            set_outer.update(|v| *v += 1);
        }
        assert_eq!(
            child_runs.get(),
            4,
            "each parent run should create one child"
        );

        // Only the newest child is still subscribed to `inner`.
        child_runs.set(0);
        set_inner.update(|v| *v += 1);
        assert_eq!(
            child_runs.get(),
            1,
            "disposed children must not still react; got {} live effects",
            child_runs.get()
        );
    }

    #[test]
    fn on_cleanup_runs_when_the_owning_effect_re_runs() {
        let (trigger, set_trigger) = create_signal(0);
        let cleanups = StdRc::new(StdCell::new(0));
        let cleanups_effect = cleanups.clone();

        create_effect(move || {
            let _ = trigger.get();
            let counter = cleanups_effect.clone();
            on_cleanup(move || counter.set(counter.get() + 1));
        });

        assert_eq!(cleanups.get(), 0, "nothing disposed yet");

        set_trigger.update(|v| *v += 1);
        assert_eq!(
            cleanups.get(),
            1,
            "re-running must run the previous cleanup"
        );

        set_trigger.update(|v| *v += 1);
        assert_eq!(cleanups.get(), 2);
    }

    /// `get()` subscribes on every read, so an effect reading a signal three
    /// times used to run three times per write on the native path. The wasm
    /// path collapsed them in `PENDING_EFFECTS`; this makes both agree.
    #[test]
    fn reading_a_signal_repeatedly_does_not_multiply_effect_runs() {
        let (value, set_value) = create_signal(0);
        let runs = StdRc::new(StdCell::new(0));
        let runs_effect = runs.clone();

        create_effect(move || {
            let _ = value.get();
            let _ = value.get();
            let _ = value.get();
            runs_effect.set(runs_effect.get() + 1);
        });

        assert_eq!(runs.get(), 1);

        runs.set(0);
        set_value.update(|v| *v += 1);
        assert_eq!(
            runs.get(),
            1,
            "three reads must still mean one run, not {}",
            runs.get()
        );
    }

    #[test]
    fn a_top_level_effect_is_retained() {
        // Ownership must not accidentally dispose effects with no parent.
        let (value, set_value) = create_signal(0);
        let runs = StdRc::new(StdCell::new(0));
        let runs_effect = runs.clone();

        create_effect(move || {
            let _ = value.get();
            runs_effect.set(runs_effect.get() + 1);
        });

        set_value.update(|v| *v += 1);
        set_value.update(|v| *v += 1);
        assert_eq!(runs.get(), 3, "initial run plus two writes");
    }
}

#[cfg(test)]
mod memo_tests {
    use super::*;
    use std::cell::Cell as StdCell;
    use std::rc::Rc as StdRc;

    fn counter() -> (StdRc<StdCell<u32>>, StdRc<StdCell<u32>>) {
        let c = StdRc::new(StdCell::new(0));
        (c.clone(), c)
    }

    #[test]
    fn a_memo_caches_across_reads() {
        let (source, _set) = create_signal(2);
        let (computations, probe) = counter();

        let doubled = create_memo(move || {
            computations.set(computations.get() + 1);
            source.get() * 2
        });

        // Eager first computation.
        assert_eq!(probe.get(), 1);

        assert_eq!(doubled.get(), 4);
        assert_eq!(doubled.get(), 4);
        assert_eq!(doubled.get(), 4);
        assert_eq!(probe.get(), 1, "three reads must not recompute");
    }

    #[test]
    fn a_memo_recomputes_after_a_dependency_changes() {
        let (source, set_source) = create_signal(2);
        let (computations, probe) = counter();

        let doubled = create_memo(move || {
            computations.set(computations.get() + 1);
            source.get() * 2
        });

        assert_eq!(doubled.get(), 4);
        set_source.set(5);
        assert_eq!(doubled.get(), 10, "must see the new value");
        assert_eq!(probe.get(), 2, "exactly one recomputation");
    }

    /// A memo nothing reads costs nothing to keep current: the write marks it
    /// dirty, but the computation is deferred until somebody asks.
    #[test]
    fn a_dirty_memo_is_not_recomputed_until_read() {
        let (source, set_source) = create_signal(1);
        let (computations, probe) = counter();

        let memo = create_memo(move || {
            computations.set(computations.get() + 1);
            source.get()
        });

        assert_eq!(probe.get(), 1);
        set_source.set(2);
        set_source.set(3);
        set_source.set(4);
        assert_eq!(probe.get(), 1, "writes alone must not recompute");

        assert_eq!(memo.get(), 4, "the read settles it at the latest value");
        assert_eq!(probe.get(), 2, "and computes exactly once to do so");
    }

    /// The reason memos mark dirty on write and recompute on read.
    ///
    /// `source` feeds two memos, and one effect reads both. Under naive push
    /// propagation — recompute each memo as it is notified, running downstream
    /// effects immediately — the effect runs once per branch, and the first run
    /// observes one fresh and one stale value. This asserts it runs once.
    #[test]
    fn a_diamond_settles_once_per_write() {
        let (source, set_source) = create_signal(1);

        let source_a = source.clone();
        let doubled = create_memo(move || source_a.get() * 2);
        let source_b = source.clone();
        let incremented = create_memo(move || source_b.get() + 1);

        let (runs, runs_probe) = counter();
        let seen = StdRc::new(StdCell::new((0, 0)));
        let seen_effect = seen.clone();

        create_effect(move || {
            let a = doubled.get();
            let b = incremented.get();
            runs.set(runs.get() + 1);
            seen_effect.set((a, b));
        });

        assert_eq!(runs_probe.get(), 1);
        assert_eq!(seen.get(), (2, 2));

        set_source.set(10);

        assert_eq!(
            runs_probe.get(),
            2,
            "the effect must run once per write, not once per memo branch"
        );
        assert_eq!(
            seen.get(),
            (20, 11),
            "both branches must be fresh in the same run — a glitch would show \
             one updated and one stale"
        );
    }

    #[test]
    fn memos_compose() {
        let (source, set_source) = create_signal(2);
        let doubled = create_memo(move || source.get() * 2);
        let doubled_for_chain = doubled.clone();
        let quadrupled = create_memo(move || doubled_for_chain.get() * 2);

        assert_eq!(quadrupled.get(), 8);
        set_source.set(3);
        assert_eq!(
            quadrupled.get(),
            12,
            "dirtiness must propagate through the chain"
        );
    }

    #[test]
    fn untrack_reads_without_subscribing() {
        let (tracked, set_tracked) = create_signal(0);
        let (ignored, set_ignored) = create_signal(0);
        let (runs, probe) = counter();

        create_effect(move || {
            let _ = tracked.get();
            let _ = untrack(|| ignored.get());
            runs.set(runs.get() + 1);
        });

        assert_eq!(probe.get(), 1);

        set_ignored.set(99);
        assert_eq!(probe.get(), 1, "an untracked read must not subscribe");

        set_tracked.set(1);
        assert_eq!(probe.get(), 2, "a tracked read still does");
    }

    #[test]
    fn untrack_restores_the_previous_subscriber() {
        // Reads after the untracked block must subscribe again.
        let (before, set_before) = create_signal(0);
        let (after, set_after) = create_signal(0);
        let (runs, probe) = counter();

        create_effect(move || {
            let _ = before.get();
            let _ = untrack(|| 1 + 1);
            let _ = after.get();
            runs.set(runs.get() + 1);
        });

        set_after.set(1);
        assert_eq!(probe.get(), 2, "the read after untrack must still track");
        set_before.set(1);
        assert_eq!(probe.get(), 3);
    }

    #[test]
    fn a_memo_owned_by_an_effect_is_disposed_with_it() {
        let (outer, set_outer) = create_signal(0);
        let (inner, set_inner) = create_signal(0);
        let (computations, probe) = counter();

        create_effect(move || {
            let _ = outer.get();
            let computations = computations.clone();
            let inner = inner.clone();
            let memo = create_memo(move || {
                computations.set(computations.get() + 1);
                inner.get()
            });
            // Read it so it registers a dependency on `inner`.
            let _ = memo.get();
        });

        assert_eq!(probe.get(), 1);

        // Re-run the parent: the old memo is disposed, a new one created.
        set_outer.set(1);
        assert_eq!(probe.get(), 2, "one fresh memo per parent run");

        // Only the live memo should react.
        set_inner.set(5);
        assert_eq!(
            probe.get(),
            3,
            "a disposed memo must not recompute; got {} computations",
            probe.get()
        );
    }
}

#[cfg(test)]
mod batch_tests {
    use super::*;
    use std::cell::Cell as StdCell;
    use std::rc::Rc as StdRc;

    fn counter() -> (StdRc<StdCell<u32>>, StdRc<StdCell<u32>>) {
        let c = StdRc::new(StdCell::new(0));
        (c.clone(), c)
    }

    #[test]
    fn writes_in_a_batch_run_a_dependent_effect_once() {
        let (first, set_first) = create_signal(0);
        let (second, set_second) = create_signal(0);
        let (runs, probe) = counter();

        create_effect(move || {
            let _ = first.get();
            let _ = second.get();
            runs.set(runs.get() + 1);
        });
        assert_eq!(probe.get(), 1);

        batch(|| {
            set_first.set(1);
            set_second.set(2);
        });

        assert_eq!(probe.get(), 2, "two writes in a batch mean one re-run");
    }

    #[test]
    fn the_same_writes_unbatched_run_it_twice() {
        // The control for the test above: without batching each write fans out.
        let (first, set_first) = create_signal(0);
        let (second, set_second) = create_signal(0);
        let (runs, probe) = counter();

        create_effect(move || {
            let _ = first.get();
            let _ = second.get();
            runs.set(runs.get() + 1);
        });

        set_first.set(1);
        set_second.set(2);

        assert_eq!(probe.get(), 3, "initial run plus one per write");
    }

    #[test]
    fn effects_do_not_run_until_the_batch_closes() {
        let (value, set_value) = create_signal(0);
        let (runs, probe) = counter();

        create_effect(move || {
            let _ = value.get();
            runs.set(runs.get() + 1);
        });

        batch(|| {
            set_value.set(1);
            assert_eq!(probe.get(), 1, "still deferred inside the batch");
            set_value.set(2);
            assert_eq!(probe.get(), 1);
        });

        assert_eq!(probe.get(), 2);
    }

    #[test]
    fn only_the_outermost_batch_flushes() {
        let (value, set_value) = create_signal(0);
        let (runs, probe) = counter();

        create_effect(move || {
            let _ = value.get();
            runs.set(runs.get() + 1);
        });

        batch(|| {
            set_value.set(1);
            batch(|| {
                set_value.set(2);
            });
            assert_eq!(
                probe.get(),
                1,
                "an inner batch closing must not flush the outer one"
            );
        });

        assert_eq!(probe.get(), 2);
    }

    #[test]
    fn a_batch_returns_the_closure_value() {
        let (value, set_value) = create_signal(1);
        let doubled = batch(|| {
            set_value.set(21);
            value.get() * 2
        });
        assert_eq!(doubled, 42);
    }

    #[test]
    fn distinct_effects_each_run_once_per_batch() {
        let (value, set_value) = create_signal(0);
        let (first_runs, first_probe) = counter();
        let (second_runs, second_probe) = counter();

        let value_a = value.clone();
        create_effect(move || {
            let _ = value_a.get();
            first_runs.set(first_runs.get() + 1);
        });
        let value_b = value.clone();
        create_effect(move || {
            let _ = value_b.get();
            second_runs.set(second_runs.get() + 1);
        });

        batch(|| {
            set_value.set(1);
            set_value.set(2);
            set_value.set(3);
        });

        assert_eq!(first_probe.get(), 2, "deduped, not skipped");
        assert_eq!(second_probe.get(), 2);
    }

    #[test]
    fn a_batch_settles_memos_once() {
        let (source, set_source) = create_signal(1);
        let (computations, probe) = counter();

        let doubled = create_memo(move || {
            computations.set(computations.get() + 1);
            source.get() * 2
        });
        assert_eq!(probe.get(), 1);

        batch(|| {
            set_source.set(2);
            set_source.set(3);
            set_source.set(4);
        });

        assert_eq!(
            probe.get(),
            1,
            "marking dirty is not recomputing; nothing read it yet"
        );
        assert_eq!(doubled.get(), 8);
        assert_eq!(probe.get(), 2, "one recomputation for three writes");
    }
}

#[cfg(test)]
mod batch_unwind_tests {
    use super::*;
    use std::cell::Cell as StdCell;
    use std::panic::{catch_unwind, AssertUnwindSafe};
    use std::rc::Rc as StdRc;

    fn counter() -> (StdRc<StdCell<u32>>, StdRc<StdCell<u32>>) {
        let c = StdRc::new(StdCell::new(0));
        (c.clone(), c)
    }

    /// The defect this guards: a panic inside a batch used to leave
    /// `BATCH_DEPTH` raised forever, after which every write on the thread
    /// queued and nothing ever ran again.
    ///
    /// Not hypothetical — `krab_client` runs island factories inside
    /// `catch_unwind`, and `error_boundary` exists to continue after a panic,
    /// so execution really does reach the next write.
    #[test]
    fn a_panic_inside_a_batch_does_not_wedge_the_reactive_system() {
        let (value, set_value) = create_signal(0);
        let (runs, probe) = counter();

        create_effect(move || {
            let _ = value.get();
            runs.set(runs.get() + 1);
        });
        assert_eq!(probe.get(), 1);

        let set_in_batch = set_value.clone();
        let panicked = catch_unwind(AssertUnwindSafe(|| {
            batch(|| {
                set_in_batch.set(1);
                panic!("something inside the batch failed");
            });
        }));
        assert!(
            panicked.is_err(),
            "the panic must propagate, not be swallowed"
        );

        assert_eq!(
            BATCH_DEPTH.with(|depth| depth.get()),
            0,
            "the batch depth must be restored on unwind"
        );

        // The system must still work. This write also delivers the effect the
        // aborted batch had queued.
        set_value.set(2);
        assert!(
            probe.get() > 1,
            "effects stopped running after a panic inside a batch"
        );
    }

    /// A write that completed before the panic must not be silently dropped:
    /// its value is already committed, so its dependents have to be told.
    #[test]
    fn writes_made_before_a_panic_are_delivered_by_the_next_write() {
        let (value, set_value) = create_signal(0);
        let seen = StdRc::new(StdCell::new(0));
        let seen_effect = seen.clone();

        create_effect(move || {
            seen_effect.set(value.get());
        });
        assert_eq!(seen.get(), 0);

        let set_in_batch = set_value.clone();
        let _ = catch_unwind(AssertUnwindSafe(|| {
            batch(|| {
                set_in_batch.set(7);
                panic!("abort mid-batch");
            });
        }));

        // The value was committed even though the batch aborted.
        set_value.set(9);
        assert_eq!(
            seen.get(),
            9,
            "the effect must observe the committed state after recovery"
        );
    }

    #[test]
    fn a_panic_in_a_nested_batch_restores_the_whole_depth() {
        let _ = catch_unwind(AssertUnwindSafe(|| {
            batch(|| {
                batch(|| {
                    batch(|| panic!("deep failure"));
                });
            });
        }));

        assert_eq!(
            BATCH_DEPTH.with(|depth| depth.get()),
            0,
            "every nested guard must unwind"
        );
    }

    /// Parity: effects have run by the time `batch` returns. Natively this was
    /// already true; the wasm flush now runs synchronously too rather than
    /// deferring to a microtask, so the scope means the same thing on both.
    #[test]
    fn effects_have_run_by_the_time_batch_returns() {
        let (value, set_value) = create_signal(0);
        let (runs, probe) = counter();

        create_effect(move || {
            let _ = value.get();
            runs.set(runs.get() + 1);
        });

        batch(|| {
            set_value.set(1);
        });

        assert_eq!(
            probe.get(),
            2,
            "the flush must be synchronous, not deferred past the scope"
        );
    }
}

/// Unwind recovery and subscriber-growth regression tests. Each test is named
/// for the failure it prevents; all of them passed *before* their fix only by
/// accident of not exercising the panic or growth path.
#[cfg(test)]
mod unwind_and_growth_tests {
    use super::*;
    use std::panic::{catch_unwind, AssertUnwindSafe};

    /// The zombie-subscriber bug: an effect that panicked under `catch_unwind`
    /// left `CURRENT_SUBSCRIBER` pointing at itself, so every later top-level
    /// effect was adopted as its child and mass-disposed on its next run.
    #[test]
    fn a_panicking_effect_does_not_leave_a_zombie_subscriber() {
        let result = catch_unwind(AssertUnwindSafe(|| {
            create_effect(|| panic!("boom"));
        }));
        assert!(result.is_err(), "the panic must propagate");

        assert!(
            CURRENT_SUBSCRIBER.with(|c| c.borrow().is_none()),
            "a caught effect panic must not leave the thread tracking the dead effect"
        );

        // A new top-level effect must be independent — not adopted by a zombie.
        let (count, set_count) = create_signal(0);
        let runs = Rc::new(Cell::new(0));
        let seen = runs.clone();
        create_effect(move || {
            let _ = count.get();
            seen.set(seen.get() + 1);
        });
        set_count.set(1);
        assert_eq!(runs.get(), 2, "initial run plus one re-run");
    }

    /// The memo-poisoning bug: the recompute closure was `take()`n and never
    /// restored on unwind, so one caught panic froze the memo on its stale
    /// value forever.
    #[test]
    fn a_panicking_memo_recovers_and_recomputes_on_the_next_read() {
        let (source, set_source) = create_signal(1);
        let should_panic = Rc::new(Cell::new(false));
        let flag = should_panic.clone();

        let memo = create_memo(move || {
            if flag.get() {
                panic!("transient failure");
            }
            source.get() * 10
        });
        assert_eq!(memo.get(), 10);

        should_panic.set(true);
        set_source.set(2);
        let result = catch_unwind(AssertUnwindSafe(|| memo.get()));
        assert!(result.is_err(), "the recompute panic must propagate");
        assert!(
            CURRENT_SUBSCRIBER.with(|c| c.borrow().is_none()),
            "a caught memo panic must not leave the thread tracking the memo"
        );

        // Recovered: the closure is back and the memo is still dirty, so the
        // next read retries rather than serving 10 as if it were fresh.
        should_panic.set(false);
        assert_eq!(
            memo.get(),
            20,
            "after recovery the memo must recompute, not serve the stale value"
        );
    }

    /// `untrack` shares the unguarded replace-before/replace-after pattern the
    /// other two sites had; a panic inside it must not kill tracking.
    #[test]
    fn a_panic_inside_untrack_restores_tracking() {
        let result = catch_unwind(AssertUnwindSafe(|| {
            untrack(|| -> i32 { panic!("boom") });
        }));
        assert!(result.is_err());
        assert!(
            CURRENT_SUBSCRIBER.with(|c| c.borrow().is_none()),
            "untrack must restore the previous subscriber on unwind"
        );

        // Tracking still works afterwards.
        let (value, set_value) = create_signal(0);
        let runs = Rc::new(Cell::new(0));
        let seen = runs.clone();
        create_effect(move || {
            let _ = value.get();
            seen.set(seen.get() + 1);
        });
        set_value.set(1);
        assert_eq!(runs.get(), 2);
    }

    /// The memo-subscriber leak: the list was cloned on notify but never
    /// drained, growing one entry per dependent re-run for the memo's life.
    #[test]
    fn memo_subscribers_do_not_accumulate_across_writes() {
        let (source, set_source) = create_signal(0);
        let memo = create_memo(move || source.get() * 2);
        let observer = memo.clone();
        create_effect(move || {
            let _ = observer.get();
        });

        for i in 1..=25 {
            set_source.set(i);
        }

        let len = memo.state.subscribers.borrow().len();
        assert!(
            len <= 1,
            "memo subscriber list must stay bounded (drained on notify), found {len}"
        );
    }

    /// Reading the same signal several times in one run must land one
    /// subscription, not one per read.
    #[test]
    fn repeated_reads_do_not_duplicate_signal_subscriptions() {
        let (value, _set_value) = create_signal(0);
        let probe = value.clone();
        create_effect(move || {
            let _ = probe.get();
            let _ = probe.get();
            let _ = probe.get();
        });

        let len = value.inner.state.borrow().subscribers.len();
        assert_eq!(
            len, 1,
            "three reads in one effect run must produce one subscription"
        );
    }

    /// A source that is read by a re-running effect but never itself written is
    /// never drained by notify — subscribe-time dedup has to bound it instead.
    #[test]
    fn an_unwritten_source_does_not_accumulate_subscribers() {
        let (written, set_written) = create_signal(0);
        let (unwritten, _set_unwritten) = create_signal(0);
        let probe = unwritten.clone();
        create_effect(move || {
            let _ = written.get();
            let _ = probe.get();
        });

        for i in 1..=25 {
            set_written.set(i);
        }

        let len = unwritten.inner.state.borrow().subscribers.len();
        assert!(
            len <= 2,
            "an unwritten source's subscriber list must stay bounded, found {len}"
        );
    }
}