krab_core 0.6.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
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
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
//! 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::any::{Any, TypeId};
use std::cell::{Cell, RefCell};
use std::rc::{Rc, Weak};

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()) };
    /// Nesting depth of synchronous flushes on the native path. A write inside
    /// an effect flushes synchronously, so chained writes across *distinct*
    /// effects stack these frames; the depth is capped at [`MAX_FLUSH_DEPTH`]
    /// as the backstop the per-effect running flag cannot provide.
    #[cfg(any(not(feature = "web"), not(target_arch = "wasm32")))]
    static FLUSH_DEPTH: Cell<u32> = const { Cell::new(0) };
    #[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) };
    /// Consecutive microtask drain generations on the browser path in which
    /// the effects that ran queued still more effects. This is the browser
    /// analogue of `FLUSH_DEPTH`: a write from inside an effect cannot nest
    /// a frame there, it lands in the next generation instead. Capped at
    /// [`MAX_FLUSH_DEPTH`]; reset the moment a generation settles.
    #[cfg(all(feature = "web", target_arch = "wasm32"))]
    static DRAIN_CHAIN_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}

/// 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,
        }
    }

    /// Whether the reactive node this subscriber points at is still alive.
    fn is_alive(&self) -> bool {
        match self {
            Self::Effect(weak) => weak.strong_count() > 0,
            Self::Memo(weak) => weak.strong_count() > 0,
        }
    }
}

/// Subscribe `subscriber` unless it is already in the list.
///
/// `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.
///
/// The whole list is scanned, not just its tail: interleaved reads (a parent
/// effect reads, its child effect reads, the parent reads again) put another
/// node between two reads by the same subscriber, and a tail-only check
/// re-added the parent on every run. Lists are short — one entry per live
/// dependent — so the scan is cheap, and it doubles as garbage collection:
/// entries whose node has been dropped are retained out while scanning.
fn push_subscriber(list: &mut Vec<Subscriber>, subscriber: &Subscriber) {
    let mut already_subscribed = false;
    list.retain(|existing| {
        if !existing.is_alive() {
            return false;
        }
        if existing.same_node(subscriber) {
            already_subscribed = true;
        }
        true
    });
    if !already_subscribed {
        list.push(subscriber.clone());
    }
}

/// Restores [`CURRENT_SUBSCRIBER`] whether the scope exits normally or unwinds.
///
/// The same reasoning as [`BatchGuard`]: on the server a panic is recoverable —
/// [`error_boundary`](crate::error_boundary) catches a panicking render and
/// keeps going — so execution really does continue 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());
        });
    }
}

// ── Owners and context ──────────────────────────────────────────────────────
//
// See ADR 0014. An owner is a node in a tree of *context scopes*. It is
// deliberately separate from effect ownership (`EffectState::children`), which
// decides what is disposed when: the context tree only answers "what has been
// provided above me?". Every effect and memo has an owner of its own, parented
// to whichever owner was current when it was created, so an effect re-running
// long after its creator returned still looks contexts up along the same
// chain.

thread_local! {
    /// The owner whose contexts `provide_context` writes to and
    /// `use_context` starts searching from.
    static CURRENT_OWNER: RefCell<Option<Rc<OwnerState>>> = const { RefCell::new(None) };
}

struct OwnerState {
    /// Strong, so a child that outlives its creator's stack frame — an effect
    /// that re-runs later — can still reach the contexts provided above it.
    /// Nothing points back down the tree, so this cannot form a cycle.
    parent: Option<Rc<OwnerState>>,
    /// Keyed by type. A `Vec` rather than a map: an owner holds a handful of
    /// contexts at most, usually none, and a scan beats hashing at that size.
    /// Values are `Rc` so a lookup can clone the handle out and release the
    /// borrow before running `T::clone`, which is user code.
    contexts: RefCell<Vec<(TypeId, Rc<dyn Any>)>>,
    disposed: Cell<bool>,
}

impl OwnerState {
    /// A new owner parented to the current one, or a root if there is none.
    fn child_of_current() -> Rc<Self> {
        Rc::new(Self {
            parent: CURRENT_OWNER.with(|current| current.borrow().clone()),
            contexts: RefCell::new(Vec::new()),
            disposed: Cell::new(false),
        })
    }

    /// Drop what this owner's current run provided. Called before an effect or
    /// memo re-runs, which provides afresh, and on disposal.
    ///
    /// Moved out before dropping: a context value's `Drop` is user code, and
    /// it must not find the `RefCell` borrowed.
    fn clear_contexts(&self) {
        let contexts = std::mem::take(&mut *self.contexts.borrow_mut());
        drop(contexts);
    }

    fn dispose(&self) {
        self.disposed.set(true);
        self.clear_contexts();
    }
}

/// Restores [`CURRENT_OWNER`] on scope exit, including by unwinding — the same
/// reasoning as [`SubscriberGuard`]: a caught panic must not leave a later
/// render providing into, or reading from, a scope that has already ended.
struct OwnerGuard {
    previous: Option<Rc<OwnerState>>,
}

impl OwnerGuard {
    fn swap_in(next: Rc<OwnerState>) -> Self {
        Self {
            previous: CURRENT_OWNER.with(|current| current.replace(Some(next))),
        }
    }
}

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

/// A context scope: the unit [`provide_context`] writes to and
/// [`use_context`] searches from.
///
/// Owners form a tree. A lookup starts at the current owner and walks up
/// through its parents, so a value provided in an outer scope is visible in
/// every scope created inside it, and a value provided in an inner scope
/// shadows an outer one of the same type for that subtree only.
///
/// Most code never touches an `Owner` directly:
///
/// - every component called through a `view!` tag (`<Card/>`) and every
///   `#[island]` runs in an owner of its own, created by the macro;
/// - every effect and memo has an owner, parented to the scope it was created
///   in, and runs under it each time it runs;
/// - [`with_owner`] opens a scope for a closure, which is what an SSR entry
///   point uses to give a request its contexts.
///
/// Like signals, owners are thread-local and `!Send`. Contexts provided while
/// rendering one request are visible only to code running inside that
/// request's scope on the same thread.
#[derive(Clone)]
pub struct Owner {
    state: Rc<OwnerState>,
}

impl Owner {
    /// A new owner, parented to the current one if there is one.
    ///
    /// It is not made current; run code under it with [`with`](Self::with).
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Self {
            state: OwnerState::child_of_current(),
        }
    }

    /// The owner code is currently running under, if any.
    pub fn current() -> Option<Self> {
        CURRENT_OWNER.with(|current| current.borrow().clone().map(|state| Self { state }))
    }

    /// Run `f` with this owner current, restoring the previous owner
    /// afterwards, even if `f` panics.
    ///
    /// Useful for re-entering a scope from a callback that runs outside it —
    /// capture `Owner::current()` while inside, call `with` later.
    pub fn with<T>(&self, f: impl FnOnce() -> T) -> T {
        let _guard = OwnerGuard::swap_in(self.state.clone());
        f()
    }

    /// Drop every context this owner holds. Later `provide_context` calls
    /// under it are ignored and later lookups skip it, continuing to its
    /// parent. Idempotent.
    ///
    /// An owner is also released simply by dropping every handle to it; this
    /// is for releasing its contexts *before* that, while an effect created
    /// in the scope still holds it.
    pub fn dispose(&self) {
        self.state.dispose();
    }
}

/// Run `f` in a new context scope, parented to the current one.
///
/// Contexts `f` provides are visible to everything it calls, and to effects
/// and memos it creates for as long as they live; they are not visible to the
/// caller. This is the SSR entry point for contexts:
///
/// ```
/// use krab_core::signal::{provide_context, use_context, with_owner};
///
/// #[derive(Clone)]
/// struct Locale(&'static str);
///
/// fn greeting() -> String {
///     match use_context::<Locale>() {
///         Some(Locale("fr")) => "Bonjour".to_string(),
///         _ => "Hello".to_string(),
///     }
/// }
///
/// let html = with_owner(|| {
///     provide_context(Locale("fr"));
///     greeting()
/// });
/// assert_eq!(html, "Bonjour");
/// // The scope has ended: nothing is provided out here.
/// assert!(use_context::<Locale>().is_none());
/// ```
///
/// `view!` wraps every component tag in `with_owner`, so a component's
/// `provide_context` reaches the components *it* renders without leaking to
/// its siblings.
pub fn with_owner<T>(f: impl FnOnce() -> T) -> T {
    Owner::new().with(f)
}

/// Make `value` available to [`use_context::<T>()`](use_context) in the
/// current scope and every scope created inside it.
///
/// Providing a second value of the same type in the same scope replaces the
/// first. Providing one in an inner scope shadows the outer value for that
/// scope only.
///
/// Outside any scope this does nothing except emit a
/// `context_provided_without_owner` warning. There is deliberately no
/// thread-wide fallback scope: on a server, one thread renders many requests
/// in turn, and a value provided for one request must never be visible to the
/// next. Open a scope with [`with_owner`] first.
pub fn provide_context<T: Clone + 'static>(value: T) {
    let Some(owner) = CURRENT_OWNER.with(|current| current.borrow().clone()) else {
        tracing::warn!(
            krab.context_type = std::any::type_name::<T>(),
            "context_provided_without_owner"
        );
        return;
    };
    if owner.disposed.get() {
        return;
    }

    let value: Rc<dyn Any> = Rc::new(value);
    let id = TypeId::of::<T>();
    // The replaced value, if any, is dropped after the borrow ends, for the
    // same reason `clear_contexts` moves values out before dropping them.
    let replaced = {
        let mut contexts = owner.contexts.borrow_mut();
        match contexts.iter_mut().find(|(existing, _)| *existing == id) {
            Some(slot) => Some(std::mem::replace(&mut slot.1, value)),
            None => {
                contexts.push((id, value));
                None
            }
        }
    };
    drop(replaced);
}

/// The nearest value of type `T` provided in the current scope or any scope
/// enclosing it, or `None` if there is none.
///
/// Call it in a component's body, while the component runs, and move the
/// result into any closures that need it. A closure that runs later — a
/// `Node::Dynamic` rendered after the component returned, an event handler —
/// runs outside the scope unless it re-enters one with [`Owner::with`]. An
/// effect created in the body is the exception: it keeps its scope, and sees
/// the same contexts every time it runs.
pub fn use_context<T: Clone + 'static>() -> Option<T> {
    let id = TypeId::of::<T>();
    let mut owner = CURRENT_OWNER.with(|current| current.borrow().clone());
    while let Some(state) = owner {
        let found = state
            .contexts
            .borrow()
            .iter()
            .find(|(existing, _)| *existing == id)
            .map(|(_, value)| value.clone());
        if let Some(value) = found {
            // The borrow is released before `clone`, which is user code and
            // may itself call `use_context` or `provide_context`.
            return value.downcast_ref::<T>().cloned();
        }
        owner = state.parent.clone();
    }
    None
}

/// 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>,
    /// Whether `recompute_now` for this memo is currently on the stack.
    ///
    /// A read of the memo while this is set is a self-referential computation:
    /// the memo's own closure (directly or through a chain) read the memo back.
    /// Such a read is served the stale cached value, untracked, with a
    /// `memo_self_reference_detected` error event — recomputing would recurse.
    computing: 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>,
    /// The context scope the computation runs under, parented to the scope
    /// the memo was created in — so a recomputation triggered from anywhere
    /// still sees the contexts its creator saw.
    owner: Rc<OwnerState>,
}

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);
        // Raised for the duration of the computation so a self-referential
        // read is detected rather than served silently. Cleared by
        // `RecomputeGuard` below, so a caught panic cannot leave it wedged.
        self.computing.set(true);

        let _subscriber = SubscriberGuard::swap_in(Some(Subscriber::Memo(Rc::downgrade(self))));
        // Anything the previous computation provided is stale; this one
        // provides afresh.
        self.owner.clear_contexts();
        let _owner = OwnerGuard::swap_in(self.owner.clone());

        // 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.computing.set(false);
                *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>,
    /// Whether this effect's body is currently on the stack.
    ///
    /// A `set()` inside an effect on one of the effect's own dependencies
    /// notifies the effect itself; natively that delivery is synchronous, so
    /// without this flag `run_effect` re-entered on the same stack and
    /// recursed until it overflowed. See [`run_effect`].
    running: Cell<bool>,
    /// Set when a notification for this effect arrived while it was running.
    /// The refused re-entrant run is owed: [`run_effect`] delivers it after
    /// the current body finishes, so the effect still converges.
    rerun_requested: Cell<bool>,
    /// Whether `signal_effect_cycle_detected` has been emitted for this
    /// effect. The event identifies a coding bug, so it is reported once per
    /// effect rather than once per refused re-entry.
    cycle_reported: 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()>>>,
    /// The context scope the body runs under, parented to the scope the
    /// effect was created in. This is what lets a re-run — triggered by a
    /// signal write from anywhere, long after the creating component returned
    /// — see the contexts that were provided around it.
    owner: Rc<OwnerState>,
}

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);
            memo.owner.dispose();
        }

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

        // Last, so cleanups above could still have read them. What the body
        // provided belongs to the run that provided it.
        self.owner.clear_contexts();
    }

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

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

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

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

/// Creates a signal holding `value`, returning its read and write halves.
///
/// Both halves are cheap to clone and share the same value. Single-threaded
/// (see the module docs).
pub fn create_signal<T>(value: T) -> (ReadSignal<T>, WriteSignal<T>) {
    let inner = SignalInner {
        state: Rc::new(RefCell::new(SignalState {
            value,
            subscribers: Vec::new(),
        })),
    };

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

/// The read half of a signal, from [`create_signal`]. Reading it inside an
/// effect or memo subscribes that effect or memo to later writes.
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> {
    /// A clone of the current value, subscribing the running effect or memo,
    /// if any.
    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> {
    /// Calls `f` with a reference to the current value, without cloning it,
    /// and subscribes the running effect or memo like [`ReadSignal::get`].
    /// Writing to the same signal from inside `f` panics (the value is
    /// borrowed).
    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)
    }
}

/// The write half of a signal, from [`create_signal`].
///
/// Every write notifies the signal's subscribers, whether or not the value
/// changed. Natively the affected effects run before the write returns; in
/// the browser (feature `web` on `wasm32`) they run in a microtask; inside a
/// [`batch`] they run when the batch ends.
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> {
    /// Replaces the value and notifies subscribers.
    pub fn set(&self, new_value: T) {
        {
            let mut state = self.inner.state.borrow_mut();
            state.value = new_value;
        } // Drop borrow

        self.notify();
    }

    /// Mutates the value in place with `f`, then notifies subscribers.
    /// Reading the same signal from inside `f` panics (the value is
    /// borrowed mutably).
    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 on the server: `error_boundary` exists precisely to make a
/// panic recoverable, so execution really does continue past one.
///
/// In the browser it cannot happen, and the guard is belt-and-braces there:
/// `wasm32-unknown-unknown` is `panic = "abort"`, so a panic traps the module
/// and nothing resumes to observe a wedged depth.
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"))]
    {
        // Scheduling never rejects work. The cutoff belongs to the drain
        // itself, below: a write made from inside an effect lands in the next
        // microtask generation, so counting *generations that kept feeding the
        // next one* is the browser equivalent of the native `FLUSH_DEPTH`
        // frame count. Counting the writes themselves, as this used to, made
        // sixty-four effects each writing one signal in a single flush look
        // like a livelock and silently dropped every later delivery — a stale
        // DOM, no diagnostic, from an entirely legitimate wide fan-out.
        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);
                }

                // Anything queued while the loop above ran was written by one
                // of those effects, so this generation chained into another.
                let chained = PENDING_EFFECTS.with(|pending| !pending.borrow().is_empty());
                if !chained {
                    DRAIN_CHAIN_DEPTH.with(|d| d.set(0));
                    return;
                }

                let depth = DRAIN_CHAIN_DEPTH.with(|d| {
                    let next = d.get() + 1;
                    d.set(next);
                    next
                });
                if depth >= MAX_FLUSH_DEPTH {
                    // Effects have been feeding each other for
                    // `MAX_FLUSH_DEPTH` consecutive generations with no sign
                    // of settling. Drop the queue rather than spin the
                    // microtask loop forever; the values are already
                    // committed, so the next legitimate write re-runs the
                    // dependents.
                    let dropped = PENDING_EFFECTS.with(|pending| {
                        let mut p = pending.borrow_mut();
                        let n = p.len();
                        p.clear();
                        n
                    });
                    DRAIN_CHAIN_DEPTH.with(|d| d.set(0));
                    tracing::error!(chain_depth = depth, dropped, "signal_flush_depth_exceeded");
                }
            });

            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")))]
    {
        // Restores the depth even if an effect body panics under
        // `catch_unwind`; a wedged depth would make every later flush on the
        // thread look nested and eventually refuse to deliver anything.
        struct FlushDepthGuard;
        impl Drop for FlushDepthGuard {
            fn drop(&mut self) {
                FLUSH_DEPTH.with(|depth| depth.set(depth.get().saturating_sub(1)));
            }
        }

        let depth = FLUSH_DEPTH.with(|depth| depth.get());
        if depth >= MAX_FLUSH_DEPTH {
            // A chain of effects each writing another's dependency has nested
            // this deep synchronously — a livelock. Drop the delivery rather
            // than overflow the stack; the values are already committed, so
            // the next legitimate write re-runs the dependents.
            tracing::error!(
                depth,
                dropped = effects.len(),
                "signal_flush_depth_exceeded"
            );
            return;
        }
        FLUSH_DEPTH.with(|depth| depth.set(depth.get() + 1));
        let _guard = FlushDepthGuard;

        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 on the server, where
/// [`error_boundary`](crate::error_boundary) exists to keep rendering after
/// one. (In a `wasm32` browser build they are not: that target is
/// `panic = "abort"`, so a panic traps the module rather than unwinding.)
/// 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) {
        if self.state.computing.get() {
            // The memo's own computation is on the stack and has read the memo
            // back. Recomputing would recurse without bound, and subscribing
            // would make the memo its own dependent, so the read is treated as
            // untracked and stale: it serves whatever value is cached.
            tracing::error!("memo_self_reference_detected");
            return;
        }

        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.
    ///
    /// A self-referential read — the memo's computation reading the memo back —
    /// is served the previous (stale) value with a `memo_self_reference_detected`
    /// error event rather than recursing. Because [`create_memo`] computes
    /// eagerly before any handle to the memo exists, a value is always present
    /// by the time a self-read is reachable through the public API.
    pub fn with<U, F>(&self, f: F) -> U
    where
        F: FnOnce(&T) -> U,
    {
        self.track_and_refresh();
        {
            let value = self.value.borrow();
            if let Some(value) = value.as_ref() {
                return f(value);
            }
        }

        // No value has ever been computed. `create_memo` computes eagerly
        // before returning, so the only route here is a first computation that
        // panicked (and was caught upstream) followed by a later read. If no
        // computation is on the stack, retry it now and serve the result.
        if !self.state.computing.get() && !self.state.disposed.get() {
            self.state.dirty.set(true);
            self.state.recompute_now();
            let value = self.value.borrow();
            if let Some(value) = value.as_ref() {
                return f(value);
            }
        }

        // A self-referential read during the memo's *first* computation: there
        // is no stale value to serve and no way to conjure a `T`, so this is
        // unsatisfiable. It is unreachable through the public API (no handle
        // exists until the first computation has completed); the panic below —
        // preceded by the error event — is a guarded invariant, not a control
        // path, and the enclosing `RecomputeGuard` leaves the memo retryable.
        tracing::error!("memo_self_reference_detected");
        panic!(
            "memo read its own value during its first computation; no previous value \
             exists to break the cycle"
        );
    }
}

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),
        computing: Cell::new(false),
        recompute: RefCell::new(None),
        subscribers: RefCell::new(Vec::new()),
        disposed: Cell::new(false),
        owner: OwnerState::child_of_current(),
    });

    {
        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
}

/// Build a fresh, not-yet-run effect state.
#[cfg(any(feature = "web", test))]
fn new_effect_state(f: impl Fn() + 'static) -> Rc<EffectState> {
    Rc::new(EffectState {
        execute: Box::new(f),
        disposed: Cell::new(false),
        running: Cell::new(false),
        rerun_requested: Cell::new(false),
        cycle_reported: Cell::new(false),
        children: RefCell::new(Vec::new()),
        owned_memos: RefCell::new(Vec::new()),
        cleanups: RefCell::new(Vec::new()),
        owner: OwnerState::child_of_current(),
    })
}

/// 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.
///
/// # Permanence
///
/// A top-level effect created this way is **permanent by design**: it is
/// retained in the thread's root-effect list and there is no API to tear it
/// down. That is the right lifetime for the common callers — hydration effects
/// that must live as long as the page. An effect whose lifetime is shorter
/// than the thread (per-widget, per-subscription) should use
/// [`create_effect_scoped`], which returns a disposable [`EffectHandle`].
pub fn create_effect<F>(#[allow(unused_variables)] f: F)
where
    F: Fn() + 'static,
{
    #[cfg(any(feature = "web", test))]
    {
        let effect = new_effect_state(f);

        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);
    }
}

/// A handle to an effect created with [`create_effect_scoped`].
///
/// Disposing the handle tears the effect down permanently: it never runs
/// again, its cleanups and children are released, and its entry in the
/// thread's root-effect list is removed, so the effect's memory can actually
/// be reclaimed. Dropping the handle *without* calling
/// [`dispose`](Self::dispose) leaves the effect running for the life of the
/// thread, exactly like [`create_effect`].
pub struct EffectHandle {
    state: Rc<EffectState>,
}

impl EffectHandle {
    /// Tear the effect down: mark it disposed, run its cleanups, dispose
    /// everything it owns, and release its root-list retention.
    ///
    /// Idempotent — disposing twice is a no-op.
    pub fn dispose(&self) {
        self.state.dispose();
        ROOT_EFFECTS.with(|roots| {
            roots
                .borrow_mut()
                .retain(|root| !Rc::ptr_eq(root, &self.state));
        });
    }
}

/// Like [`create_effect`], but returns an [`EffectHandle`] that can tear the
/// effect down.
///
/// The effect is always retained as a **root** effect — it is never adopted as
/// a child of an enclosing effect — so its lifetime is governed solely by the
/// returned handle. Use this for effects scoped to something shorter-lived
/// than the thread; use [`create_effect`] for effects that should live as long
/// as the page.
#[cfg(any(feature = "web", test))]
pub fn create_effect_scoped<F>(f: F) -> EffectHandle
where
    F: Fn() + 'static,
{
    let effect = new_effect_state(f);
    ROOT_EFFECTS.with(|roots| {
        roots.borrow_mut().push(effect.clone());
    });
    run_effect(effect.clone());
    EffectHandle { state: effect }
}

/// See the enabled variant above. Without the `web` feature nothing runs
/// effects on this target, matching [`create_effect`]; the returned handle
/// controls an inert, already-disposed effect so `dispose()` is a no-op.
#[cfg(not(any(feature = "web", test)))]
pub fn create_effect_scoped<F>(f: F) -> EffectHandle
where
    F: Fn() + 'static,
{
    let _ = f;
    EffectHandle {
        state: Rc::new(EffectState {
            execute: Box::new(|| {}),
            disposed: Cell::new(true),
            running: Cell::new(false),
            rerun_requested: Cell::new(false),
            cycle_reported: Cell::new(false),
            children: RefCell::new(Vec::new()),
            owned_memos: RefCell::new(Vec::new()),
            cleanups: RefCell::new(Vec::new()),
            owner: OwnerState::child_of_current(),
        }),
    }
}

/// 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));
            }
        });
    }
}

// ── Recovery from an abandoned run ──────────────────────────────────────────

/// The reactive runtime's per-thread "where am I" state: the current
/// subscriber and owner, and the batch and flush depths.
///
/// Every one of these is restored by a drop guard when its scope exits,
/// including by unwinding. On `wasm32-unknown-unknown` a panic does not unwind
/// — it traps — and `krab_client` contains the trap in JavaScript, one island
/// at a time. The Rust frames that trapped are discarded without running a
/// single destructor, so the guards never run, and the state is left as the
/// dead island had it: its owner current (so the next island's `with_owner`
/// is parented to it and `use_context` finds the dead island's values), its
/// effect the current subscriber, a `batch` depth that never returns to zero
/// (deferring every later signal write on the page).
///
/// `krab_client` takes a snapshot before each isolated call and restores it
/// after a trap. Not for application code.
#[doc(hidden)]
pub struct ReactiveSnapshot {
    subscriber: Option<Subscriber>,
    owner: Option<Rc<OwnerState>>,
    batch_depth: u32,
    #[cfg(any(not(feature = "web"), not(target_arch = "wasm32")))]
    flush_depth: u32,
    #[cfg(all(feature = "web", target_arch = "wasm32"))]
    drain_chain_depth: u32,
}

/// Capture the state [`restore_reactive_state`] puts back. See
/// [`ReactiveSnapshot`].
///
/// Tolerant of a cell a previous trap left borrowed: the value is then taken
/// as empty rather than panicking.
#[doc(hidden)]
pub fn snapshot_reactive_state() -> ReactiveSnapshot {
    ReactiveSnapshot {
        subscriber: CURRENT_SUBSCRIBER
            .try_with(|current| current.try_borrow().ok().and_then(|s| s.clone()))
            .ok()
            .flatten(),
        owner: CURRENT_OWNER
            .try_with(|current| current.try_borrow().ok().and_then(|o| o.clone()))
            .ok()
            .flatten(),
        batch_depth: BATCH_DEPTH.try_with(Cell::get).unwrap_or(0),
        #[cfg(any(not(feature = "web"), not(target_arch = "wasm32")))]
        flush_depth: FLUSH_DEPTH.try_with(Cell::get).unwrap_or(0),
        #[cfg(all(feature = "web", target_arch = "wasm32"))]
        drain_chain_depth: DRAIN_CHAIN_DEPTH.try_with(Cell::get).unwrap_or(0),
    }
}

/// Put back the state captured by [`snapshot_reactive_state`], after a run
/// was abandoned without its guards running (a wasm trap). Runs no user code.
///
/// Returns `false` if a cell was still borrowed — the trap happened while the
/// runtime held it — and so could not be restored. A borrow flag stuck by a
/// trap cannot be cleared from safe code; the caller should report it, since
/// the next access to that cell will panic.
///
/// Effects an abandoned `batch` had deferred stay queued and run when the next
/// batch on the page closes; they are live effects subscribed to signals that
/// really were written, so dropping them would leave their DOM stale.
#[doc(hidden)]
pub fn restore_reactive_state(snapshot: ReactiveSnapshot) -> bool {
    let ReactiveSnapshot {
        subscriber,
        owner,
        batch_depth,
        #[cfg(any(not(feature = "web"), not(target_arch = "wasm32")))]
        flush_depth,
        #[cfg(all(feature = "web", target_arch = "wasm32"))]
        drain_chain_depth,
    } = snapshot;

    let subscriber_restored = CURRENT_SUBSCRIBER
        .try_with(|current| match current.try_borrow_mut() {
            Ok(mut slot) => {
                *slot = subscriber;
                true
            }
            Err(_) => false,
        })
        .unwrap_or(false);
    let owner_restored = CURRENT_OWNER
        .try_with(|current| match current.try_borrow_mut() {
            Ok(mut slot) => {
                *slot = owner;
                true
            }
            Err(_) => false,
        })
        .unwrap_or(false);
    let _ = BATCH_DEPTH.try_with(|depth| depth.set(batch_depth));
    #[cfg(any(not(feature = "web"), not(target_arch = "wasm32")))]
    let _ = FLUSH_DEPTH.try_with(|depth| depth.set(flush_depth));
    #[cfg(all(feature = "web", target_arch = "wasm32"))]
    let _ = DRAIN_CHAIN_DEPTH.try_with(|depth| depth.set(drain_chain_depth));

    subscriber_restored && owner_restored
}

/// Ceiling on consecutive owed re-runs of one effect, and on nested
/// synchronous flushes. High enough that any legitimately converging effect
/// settles long before it; low enough that a genuine livelock is cut off with
/// a `signal_flush_depth_exceeded` error event instead of hanging the thread.
const MAX_FLUSH_DEPTH: u32 = 64;

/// Clears an effect's `running` flag when the scope exits, normally or by
/// unwinding. On the server `error_boundary` makes a panic recoverable, so
/// execution continues past one — a wedged flag would make every later run of
/// the effect refuse as a false cycle. On `wasm32` a panic aborts instead, so
/// there is nothing left to wedge; the guard costs nothing and keeps one
/// behaviour across both targets.
struct RunningGuard<'a> {
    flag: &'a Cell<bool>,
}

impl<'a> RunningGuard<'a> {
    fn arm(flag: &'a Cell<bool>) -> Self {
        flag.set(true);
        Self { flag }
    }
}

impl Drop for RunningGuard<'_> {
    fn drop(&mut self) {
        self.flag.set(false);
    }
}

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

    if effect.running.get() {
        // Re-entry: a write inside this effect's own body notified the effect
        // itself, and the native path delivers notifications synchronously on
        // the same stack. Running here would recurse without bound (the
        // pre-guard failure mode was a stack overflow). Refuse the nested run
        // and remember that one re-run is owed once the current body
        // finishes, so the effect still observes the value it wrote.
        if !effect.cycle_reported.get() {
            effect.cycle_reported.set(true);
            tracing::error!("signal_effect_cycle_detected");
        }
        effect.rerun_requested.set(true);
        return;
    }

    let mut reruns: u32 = 0;
    loop {
        effect.rerun_requested.set(false);

        {
            // Drop guard so a panic in the body cannot wedge the flag.
            let _running = RunningGuard::arm(&effect.running);

            // 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 _subscriber =
                SubscriberGuard::swap_in(Some(Subscriber::Effect(Rc::downgrade(&effect))));
            let _owner = OwnerGuard::swap_in(effect.owner.clone());
            effect.run();
        }

        // Deliver the re-run a refused re-entry left owing, now that the body
        // is off the stack. Bounded: an effect that unconditionally rewrites
        // its own dependency would otherwise loop forever.
        if effect.disposed.get() || !effect.rerun_requested.get() {
            break;
        }
        reruns += 1;
        if reruns >= MAX_FLUSH_DEPTH {
            tracing::error!(reruns, "signal_flush_depth_exceeded");
            effect.rerun_requested.set(false);
            break;
        }
    }
}

/// A wasm trap discards the island's frames without running their guards.
/// `std::mem::forget` on each guard reproduces exactly that, natively.
#[cfg(test)]
mod abandoned_run_tests {
    use super::*;

    #[derive(Clone, Debug, PartialEq)]
    struct Leaked(u32);

    /// Island A enters an owner, provides a context, opens a batch and is
    /// mid-effect when it "traps". Without a restore, island B inherits all of
    /// it; with one, B starts clean and reactivity works.
    #[test]
    fn restoring_a_snapshot_undoes_an_abandoned_run() {
        let snapshot = snapshot_reactive_state();

        let dead_owner = OwnerState::child_of_current();
        std::mem::forget(OwnerGuard::swap_in(dead_owner));
        provide_context(Leaked(7));
        std::mem::forget(BatchGuard::enter());
        let dead_effect = new_effect_state(|| {});
        std::mem::forget(SubscriberGuard::swap_in(Some(Subscriber::Effect(
            Rc::downgrade(&dead_effect),
        ))));
        FLUSH_DEPTH.with(|depth| depth.set(depth.get() + 3));

        // The leak the snapshot exists to undo: a fresh scope for the next
        // island is parented to the dead one.
        assert_eq!(with_owner(use_context::<Leaked>), Some(Leaked(7)));

        assert!(restore_reactive_state(snapshot));

        assert_eq!(with_owner(use_context::<Leaked>), None);
        assert!(Owner::current().is_none());
        assert!(CURRENT_SUBSCRIBER.with(|current| current.borrow().is_none()));
        assert_eq!(BATCH_DEPTH.with(Cell::get), 0);
        assert_eq!(FLUSH_DEPTH.with(Cell::get), 0);

        // Writes deliver again: a stuck batch depth would defer this forever.
        let (value, set_value) = create_signal(0);
        let seen = Rc::new(Cell::new(-1));
        let sink = seen.clone();
        create_effect(move || sink.set(value.get()));
        set_value.set(5);
        assert_eq!(seen.get(), 5);
    }

    #[test]
    fn a_cell_left_borrowed_is_reported_not_panicked_on() {
        let snapshot = snapshot_reactive_state();
        let restored = CURRENT_OWNER.with(|current| {
            let _held = current.borrow();
            restore_reactive_state(snapshot)
        });
        assert!(!restored);
    }
}

#[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 on the server — `error_boundary` exists to continue
    /// after a panic, so execution really does reach the next write. (A
    /// `wasm32` browser build aborts on panic instead, so this guard is
    /// belt-and-braces there rather than load-bearing.)
    #[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}"
        );
    }

    /// The interleaved variant the tail-only dedup missed: a parent effect and
    /// its child both read the same unwritten signal, and the parent reads it
    /// again after the child is created. With `last()`-only dedup the parent's
    /// second read always landed a duplicate, one per parent re-run.
    #[test]
    fn interleaved_parent_and_child_reads_do_not_accumulate_subscribers() {
        let (written, set_written) = create_signal(0);
        let (unwritten, _set_unwritten) = create_signal(0);

        let parent_probe = unwritten.clone();
        let child_probe = unwritten.clone();
        create_effect(move || {
            let _ = written.get();
            // Parent subscribes; list tail is now the parent.
            let _ = parent_probe.get();
            let probe = child_probe.clone();
            create_effect(move || {
                // Child subscribes; list tail is now the child.
                let _ = probe.get();
            });
            // Parent reads again: the tail is the child, so a tail-only check
            // pushed a second parent entry every run.
            let _ = parent_probe.get();
        });

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

        let len = unwritten.inner.state.borrow().subscribers.len();
        assert!(
            len <= 2,
            "one parent and one child must mean at most two subscriptions, found {len}"
        );
    }
}

/// Guards against reactive cycles: an effect writing its own dependency, a
/// memo reading itself, and the disposal API for root effects.
#[cfg(test)]
mod cycle_guard_tests {
    use super::*;
    use std::panic::{catch_unwind, AssertUnwindSafe};

    /// The stack-overflow bug: natively a `set()` inside an effect ran the
    /// effect again synchronously on the same stack, so an effect that wrote
    /// its own dependency recursed until it overflowed. The running flag
    /// refuses the re-entrant run and delivers it after the body finishes, so
    /// the effect terminates *and* settles on the value it wrote.
    #[test]
    fn an_effect_writing_its_own_dependency_terminates_and_converges() {
        let (count, set_count) = create_signal(0u32);
        let runs = Rc::new(Cell::new(0u32));

        let reader = count.clone();
        let seen = runs.clone();
        create_effect(move || {
            seen.set(seen.get() + 1);
            let current = reader.get();
            if current < 5 {
                set_count.set(current + 1);
            }
        });

        assert_eq!(count.get(), 5, "the effect must converge on its own writes");
        assert_eq!(runs.get(), 6, "initial run plus one owed re-run per write");
    }

    /// An effect that unconditionally rewrites its own dependency can never
    /// converge; the iteration cap must cut it off instead of hanging.
    #[test]
    fn an_unconditional_self_write_is_cut_off_by_the_flush_cap() {
        let (value, set_value) = create_signal(0u64);
        let runs = Rc::new(Cell::new(0u32));

        let reader = value.clone();
        let seen = runs.clone();
        create_effect(move || {
            seen.set(seen.get() + 1);
            set_value.set(reader.get() + 1);
        });

        assert_eq!(
            runs.get(),
            MAX_FLUSH_DEPTH,
            "consecutive runs of a livelocked effect are capped at MAX_FLUSH_DEPTH"
        );
    }

    /// A panic inside a self-notifying effect must not wedge the running flag:
    /// the drop guard clears it, so the effect is not refused as a false cycle
    /// on its next legitimate run.
    #[test]
    fn a_panicking_effect_does_not_wedge_the_running_flag() {
        let (value, set_value) = create_signal(0);
        let should_panic = Rc::new(Cell::new(true));
        let runs = Rc::new(Cell::new(0u32));

        let flag = should_panic.clone();
        let seen = runs.clone();
        let result = catch_unwind(AssertUnwindSafe(|| {
            create_effect(move || {
                let _ = value.get();
                seen.set(seen.get() + 1);
                if flag.get() {
                    panic!("first run fails");
                }
            });
        }));
        assert!(result.is_err(), "the panic must propagate");

        should_panic.set(false);
        set_value.set(1);
        assert_eq!(
            runs.get(),
            2,
            "after a caught panic the effect must run again, not be refused as a cycle"
        );
    }

    /// The self-referential-memo panic: the memo's closure reading the memo
    /// back found `dirty` already cleared and an (on the panicking path)
    /// absent value, and `with()` `expect()`ed. The computing flag now serves
    /// the stale value to the self-read, so the computation completes
    /// deterministically instead of panicking.
    #[test]
    fn a_self_referential_memo_serves_the_stale_value_instead_of_panicking() {
        let handle: Rc<RefCell<Option<Memo<i32>>>> = Rc::new(RefCell::new(None));
        let (source, set_source) = create_signal(1);

        let handle_in_closure = handle.clone();
        let memo = create_memo(move || {
            let base = source.get();
            // On the eager first computation the handle is still empty, so
            // there is a non-recursive base case; every recomputation after
            // that reads the memo back through the handle.
            let previous = handle_in_closure
                .borrow()
                .as_ref()
                .map(|memo: &Memo<i32>| memo.get())
                .unwrap_or(0);
            base + previous
        });
        *handle.borrow_mut() = Some(memo.clone());

        assert_eq!(memo.get(), 1, "eager run: base 1 with no previous value");

        set_source.set(10);
        let result = catch_unwind(AssertUnwindSafe(|| memo.get()));
        let value = result.expect("a self-referential memo must not panic");
        assert_eq!(
            value, 11,
            "the self-read must see the stale value (1), giving 10 + 1"
        );

        // Deterministic thereafter: reading again without a write serves the
        // cached value, no recomputation, no panic.
        assert_eq!(memo.get(), 11);
    }

    /// Root effects were pushed into `ROOT_EFFECTS` forever with no disposal
    /// API; `create_effect_scoped` must return the list to its baseline.
    #[test]
    fn disposing_a_scoped_effect_returns_root_effects_to_baseline() {
        let baseline = ROOT_EFFECTS.with(|roots| roots.borrow().len());

        let (value, set_value) = create_signal(0);
        let runs = Rc::new(Cell::new(0u32));

        let reader = value.clone();
        let seen = runs.clone();
        let handle = create_effect_scoped(move || {
            let _ = reader.get();
            seen.set(seen.get() + 1);
        });

        assert_eq!(
            ROOT_EFFECTS.with(|roots| roots.borrow().len()),
            baseline + 1,
            "a scoped effect is retained while live"
        );
        set_value.set(1);
        assert_eq!(runs.get(), 2, "a live scoped effect reacts to writes");

        handle.dispose();
        assert_eq!(
            ROOT_EFFECTS.with(|roots| roots.borrow().len()),
            baseline,
            "dispose must remove the retained Rc from ROOT_EFFECTS"
        );

        set_value.set(2);
        assert_eq!(runs.get(), 2, "a disposed scoped effect must not run again");

        // Idempotent: a second dispose must not remove anything else.
        handle.dispose();
        assert_eq!(ROOT_EFFECTS.with(|roots| roots.borrow().len()), baseline);
    }

    /// `on_cleanup` callbacks registered by a scoped effect run at dispose.
    #[test]
    fn disposing_a_scoped_effect_runs_its_cleanups() {
        let cleanups = Rc::new(Cell::new(0u32));

        let counter = cleanups.clone();
        let handle = create_effect_scoped(move || {
            let counter = counter.clone();
            on_cleanup(move || counter.set(counter.get() + 1));
        });

        assert_eq!(cleanups.get(), 0);
        handle.dispose();
        assert_eq!(cleanups.get(), 1, "dispose must run the registered cleanup");
    }
}

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

    #[derive(Clone, Debug, PartialEq)]
    struct Theme(&'static str);

    #[derive(Clone, Debug, PartialEq)]
    struct User(&'static str);

    /// SSR shape: components are plain function calls made while the parent
    /// runs, each in its own scope, as `view!` component tags produce.
    fn child_component() -> Option<Theme> {
        use_context::<Theme>()
    }

    fn parent_component() -> (Option<Theme>, Option<Theme>, Option<Theme>) {
        provide_context(Theme("dark"));
        let first = with_owner(child_component);
        let shadowed = with_owner(|| {
            provide_context(Theme("light"));
            with_owner(child_component)
        });
        // A sibling rendered after the shadowing one sees the parent's value:
        // the inner provide was confined to its own scope.
        let sibling = with_owner(child_component);
        (first, shadowed, sibling)
    }

    #[test]
    fn a_context_reaches_nested_calls_and_inner_provides_shadow_outer_ones() {
        let (first, shadowed, sibling) = with_owner(parent_component);
        assert_eq!(first, Some(Theme("dark")));
        assert_eq!(shadowed, Some(Theme("light")));
        assert_eq!(sibling, Some(Theme("dark")));
    }

    #[test]
    fn contexts_of_different_types_are_independent() {
        with_owner(|| {
            provide_context(Theme("dark"));
            with_owner(|| {
                provide_context(User("ada"));
                assert_eq!(use_context::<Theme>(), Some(Theme("dark")));
                assert_eq!(use_context::<User>(), Some(User("ada")));
            });
            assert_eq!(use_context::<User>(), None);
        });
    }

    #[test]
    fn providing_twice_in_one_scope_replaces_the_value() {
        with_owner(|| {
            provide_context(Theme("dark"));
            provide_context(Theme("light"));
            assert_eq!(use_context::<Theme>(), Some(Theme("light")));
        });
    }

    #[test]
    fn an_absent_context_is_none() {
        assert_eq!(use_context::<Theme>(), None);
        with_owner(|| assert_eq!(use_context::<Theme>(), None));
    }

    /// No thread-wide fallback: on a server the next request on this thread
    /// must not see what an earlier one provided.
    #[test]
    fn providing_outside_any_scope_is_not_visible_anywhere() {
        provide_context(Theme("leaked"));
        assert_eq!(use_context::<Theme>(), None);
        with_owner(|| assert_eq!(use_context::<Theme>(), None));
    }

    #[test]
    fn a_scope_ends_with_its_closure() {
        with_owner(|| provide_context(Theme("dark")));
        assert_eq!(use_context::<Theme>(), None);
        assert!(Owner::current().is_none());
    }

    #[test]
    fn a_panicking_scope_restores_the_previous_owner() {
        with_owner(|| {
            provide_context(Theme("outer"));
            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                with_owner(|| {
                    provide_context(Theme("inner"));
                    panic!("render failed");
                })
            }));
            assert!(result.is_err());
            assert_eq!(use_context::<Theme>(), Some(Theme("outer")));
        });
    }

    #[test]
    fn an_effect_sees_its_scope_on_every_run() {
        let (count, set_count) = create_signal(0);
        let seen = StdRc::new(RefCell::new(Vec::new()));

        let handle = with_owner(|| {
            provide_context(Theme("dark"));
            let seen = seen.clone();
            create_effect_scoped(move || {
                count.get();
                seen.borrow_mut().push(use_context::<Theme>());
            })
        });

        // The scope's closure has returned; the writes below re-run the
        // effect from outside it.
        assert!(Owner::current().is_none());
        set_count.set(1);
        set_count.set(2);

        assert_eq!(
            *seen.borrow(),
            vec![Some(Theme("dark")); 3],
            "every run, including re-runs after the scope returned, must see the context"
        );
        handle.dispose();
    }

    #[test]
    fn a_context_provided_in_an_effect_reaches_its_child_effects() {
        let seen = StdRc::new(RefCell::new(None));
        let handle = with_owner(|| {
            let seen = seen.clone();
            create_effect_scoped(move || {
                provide_context(User("from-effect"));
                let seen = seen.clone();
                create_effect(move || {
                    *seen.borrow_mut() = use_context::<User>();
                });
            })
        });
        assert_eq!(*seen.borrow(), Some(User("from-effect")));
        handle.dispose();
    }

    #[test]
    fn a_memo_recomputes_under_the_scope_it_was_created_in() {
        let (count, set_count) = create_signal(1);
        let memo = with_owner(|| {
            provide_context(Theme("dark"));
            create_memo(move || (count.get(), use_context::<Theme>()))
        });
        set_count.set(2);
        assert_eq!(memo.get(), (2, Some(Theme("dark"))));
    }

    /// Disposal drops the value, observable through a context whose `Drop`
    /// is counted.
    #[test]
    fn disposing_an_effect_drops_the_contexts_it_provided() {
        #[derive(Clone)]
        struct Tracked(StdRc<StdCell<u32>>);
        impl Drop for Tracked {
            fn drop(&mut self) {
                self.0.set(self.0.get() + 1);
            }
        }

        let drops = StdRc::new(StdCell::new(0));
        let handle = {
            let drops = drops.clone();
            create_effect_scoped(move || provide_context(Tracked(drops.clone())))
        };
        let before = drops.get();
        handle.dispose();
        assert_eq!(
            drops.get(),
            before + 1,
            "dispose must drop the provided value"
        );
    }

    #[test]
    fn a_disposed_owner_is_skipped_by_lookups() {
        with_owner(|| {
            provide_context(Theme("outer"));
            let inner = Owner::new();
            inner.with(|| provide_context(Theme("inner")));
            inner.with(|| assert_eq!(use_context::<Theme>(), Some(Theme("inner"))));

            inner.dispose();
            inner.with(|| {
                assert_eq!(use_context::<Theme>(), Some(Theme("outer")));
                provide_context(Theme("ignored"));
                assert_eq!(use_context::<Theme>(), Some(Theme("outer")));
            });
        });
    }

    #[test]
    fn a_re_run_forgets_what_the_previous_run_provided() {
        let (provide, set_provide) = create_signal(true);
        let seen = StdRc::new(RefCell::new(Vec::new()));
        let handle = {
            let seen = seen.clone();
            create_effect_scoped(move || {
                if provide.get() {
                    provide_context(User("first-run"));
                }
                seen.borrow_mut().push(use_context::<User>());
            })
        };
        set_provide.set(false);
        assert_eq!(*seen.borrow(), vec![Some(User("first-run")), None]);
        handle.dispose();
    }
}