day-model 0.7.6

Property observable store.
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
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! Per-property observation: a store whose writes wake only the readers of the field that
//! changed.
//!
//! With one `Signal<Vec<Item>>`, every observer of the store re-runs when any field of any
//! element changes. Day's `bind` equality gate keeps the *native* side precise, so what is wasted
//! is compute: every row's closures re-run and re-clone on every keystroke, and the waste grows
//! with the list. Here each (element, field) is its own dependency node, so a write wakes exactly
//! the readers of that field, plus readers who asked for something coarser by reading something
//! coarser.
//!
//! The pieces:
//!
//! - [`Store<T>`]: a `Copy`, process-lifetime handle to one value, like `Signal::global`.
//! - [`Keyed<T>`]: a collection addressed by stable key, with its own key→index map.
//! - [`Elem<T>`]: one element of a keyed store; [`Elem::exists`] is the tracked deletion guard.
//! - [`Field`]: one field projected out of any [`Source`]; `Copy`, itself a `Source` (so fields
//!   nest to any depth), and a [`Binding`], so every control binds to it directly.
//! - `#[derive(Observable)]` (in day-macros) generates the typed field accessors, so
//!   `store.elem(id).name()` is written once per struct, not once per call site.
//! - The **change log**: every write announces `(path components, field label, operation)`, with
//!   the slot's prior and new value captured when a consumer asks ([`record_values`]). What the
//!   tests read today; the persistence layer's input later.
//!
//! ## Paths
//!
//! A path names one observable slot: a store, one element of it, one field, a field of that
//! field, to any depth. Each gets its own `Trigger` (day-reactive's data-less dependency node),
//! created lazily on first observation: a path nobody reads has no trigger and costs nothing to
//! write. Reads track the most specific path they touched; writes notify that path and its
//! ancestors. That asymmetry is the entire granularity story.
//!
//! A path is a parent (an interned id) plus one component. The leaf component is not interned, so
//! building a field handle (the thing that happens on every read of every row) costs no lookup.
//! Interning happens only where a path is used as a *parent*: once per store, once per element
//! handle, once per nested struct.
//!
//! ## Reclamation
//!
//! Both tables shrink. Triggers are refcounted by the scopes observing them: a binding's scope
//! dies (a page popped, a row recycled) and the last watcher out disposes the trigger. Interner
//! entries are refcounted by their children and their triggers: when the last trigger under an
//! element is released, the element's entry (and any empty ancestors up to its pinned store root)
//! is freed. A freed slot's id carries a generation, and every handle validates its cached id
//! before use, re-interning through its own handle chain when stale, so a `Copy` handle held
//! across a reclamation heals itself, and everyone converges on the current identity.
//!
//! A claim made from inside a reactive computation belongs to that computation's current run,
//! not to a scope: it is released when the computation re-tracks or dies
//! ([`day_reactive::on_run_retrack`]), exactly mirroring day-reactive's own per-run source
//! bookkeeping. This is what keeps a long-lived recycled list cell from accumulating claims for
//! every row it ever showed: rotate a binding across a million rows and the claim count stays
//! at one row's worth. Outside any computation (a build seeding an initial value, an event
//! handler) a tracked read subscribes nothing and therefore claims nothing: no trigger is
//! created at all, because nothing could ever wake through it.
//!
//! ## Threads
//!
//! `Store` is `Send + Sync` (when `T` is); the trigger tables are thread-local to the main
//! thread. A worker edits through [`Store::transact`], naming what it touched as plain path
//! components; dropping the transaction commits the data and queues the announcements, and
//! [`Store::pump`], called on the main thread, wakes exactly the paths the worker named. (The
//! persistence container will schedule the pump itself; a bare store keeps delivery explicit.)

use std::any::Any;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::marker::PhantomData;
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, RwLock};

use day_reactive::{Binding, Scope, Trigger};

/// The Uuid key type, re-exported so a model file needs no direct `uuid` dependency:
/// `#[obs(key)] id: Uuid` beside `Uuid::now_v7()` (generation is native-target only until the
/// web pipeline's entropy import is wired; the type itself works everywhere).
#[doc(no_inline)]
pub use uuid::Uuid;

// ---------------------------------------------------------------------------
// Paths and the interner
// ---------------------------------------------------------------------------

/// An interned interior node: a path that something hangs off. Carries a generation so a handle
/// can tell a live id from one whose slot was reclaimed and reused.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct NodeId {
    idx: u32,
    generation: u32,
}

/// The parent of a store's own path.
const ROOT: NodeId = NodeId {
    idx: 0,
    generation: 0,
};

/// The reserved component naming a collection's shape (which keys, in what order) as opposed to
/// any element's contents.
pub const STRUCTURE: u64 = u64::MAX;

/// One observable slot: a parent, and one step down from it.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct Path {
    parent: NodeId,
    part: u64,
}

impl Path {
    /// A store's own path.
    fn root(id: u64) -> Path {
        Path {
            parent: ROOT,
            part: id,
        }
    }

    /// One step down. Cheap: the parent is already interned by whoever handed it over.
    #[must_use]
    pub fn under(parent: NodeId, part: u64) -> Path {
        Path { parent, part }
    }

    /// The path's components, outermost first, resolved through the interner.
    #[must_use]
    pub fn components(self) -> Vec<u64> {
        let mut out: Vec<u64> = self.chain().iter().map(|p| p.part).collect();
        out.reverse();
        out
    }

    /// This path and every resolvable ancestor, innermost first: exactly what a write wakes.
    fn chain(self) -> Vec<Path> {
        let mut out = vec![self];
        let mut at = self.parent;
        NODES.with(|n| {
            let nodes = n.borrow();
            while at != ROOT {
                match nodes.get(at) {
                    Some(p) => {
                        out.push(p);
                        at = p.parent;
                    }
                    None => break,
                }
            }
        });
        out
    }
}

/// A field's path component, derived from its name at compile time.
///
/// Hand-assigned indices are a hazard: two fields given the same number share a trigger, and the
/// symptom is a wakeup that fires too often, invisible until someone profiles it. A name is
/// already unique within a struct, so the compiler's own uniqueness rule becomes the path's.
#[must_use]
pub const fn field_id(name: &str) -> u64 {
    let bytes = name.as_bytes();
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    let mut i = 0;
    while i < bytes.len() {
        h ^= bytes[i] as u64;
        h = h.wrapping_mul(0x1000_0000_01b3);
        i += 1;
    }
    h
}

struct Slot {
    path: Path,
    generation: u32,
    alive: bool,
    /// A store root: never reclaimed, because the leaked `Store` handle is forever.
    pinned: bool,
    /// Live child slots whose `path.parent` is this id.
    children: u32,
    /// Live triggers on paths whose parent is this id.
    triggers: u32,
}

#[derive(Default)]
struct Interner {
    /// Index 0 is the root sentinel and is never read as a path.
    slots: Vec<Slot>,
    free: Vec<u32>,
    lookup: HashMap<Path, NodeId>,
}

impl Interner {
    fn get(&self, id: NodeId) -> Option<Path> {
        match self.slots.get(id.idx as usize) {
            Some(s) if s.alive && s.generation == id.generation => Some(s.path),
            _ => None,
        }
    }

    fn is_current(&self, id: NodeId) -> bool {
        id == ROOT || self.get(id).is_some()
    }

    /// Free `id` if nothing holds it, then walk up freeing empty ancestors. Stops at pinned
    /// store roots and at anything still watched or still a parent.
    fn maybe_free(&mut self, mut id: NodeId) {
        loop {
            let Some(s) = self.slots.get(id.idx as usize) else {
                return;
            };
            if !s.alive
                || s.generation != id.generation
                || s.pinned
                || s.children > 0
                || s.triggers > 0
            {
                return;
            }
            let path = s.path;
            self.lookup.remove(&path);
            let s = &mut self.slots[id.idx as usize];
            s.alive = false;
            s.generation = s.generation.wrapping_add(1);
            self.free.push(id.idx);
            if path.parent == ROOT {
                return;
            }
            if let Some(ps) = self.slots.get_mut(path.parent.idx as usize)
                && ps.alive
                && ps.generation == path.parent.generation
                && ps.children > 0
            {
                ps.children -= 1;
                id = path.parent;
                continue;
            }
            return;
        }
    }
}

day_reactive::tls_group! {
    static NODES: RefCell<Interner> = RefCell::new(Interner {
        slots: vec![Slot {
            path: Path { parent: ROOT, part: 0 },
            generation: 0,
            alive: true,
            pinned: true,
            children: 0,
            triggers: 0,
        }],
        free: Vec::new(),
        lookup: HashMap::new(),
    });

    /// Path → trigger. Each trigger lives in its own child of the root scope: created inside
    /// whichever page first observed it, it would be disposed with that page and every later
    /// read would panic. Its own scope is also what makes reclamation possible.
    static TRIGGERS: RefCell<HashMap<Path, Entry>> = RefCell::new(HashMap::new());

    /// Every change announced while recording is on: what the tests read and, with a schema
    /// beside it, the persistence change set.
    static RECORDER: RefCell<Option<Vec<Change>>> = const { RefCell::new(None) };

    /// Whether writes should capture prior/new values into the change log.
    static WANT_VALUES: Cell<bool> = const { Cell::new(false) };

    /// Standing want-values consumers (an installed undo stack), refcounted, unlike the
    /// scoped `RECORDER` flag above.
    static WANT_VALUES_STANDING: Cell<u32> = const { Cell::new(0) };

    /// True while a preview write applies: triggers wake (the UI follows the drag), but no
    /// change record is built, so sinks, the recorder, autosave and undo all stay quiet until
    /// the session commits (docs/model.md).
    static PREVIEW_WRITE: Cell<bool> = const { Cell::new(false) };

    /// Open preview sessions: field components → the pre-session value. Insert-once per
    /// session; taken at commit/cancel.
    static PREVIEWS: RefCell<HashMap<Vec<u64>, Rc<dyn Any>>> = RefCell::new(HashMap::new());

    /// The author tag stamped on changes born while set: "undo"/"redo" during replay, a sync
    /// engine's name during an import. `None` is the user.
    static CURRENT_AUTHOR: Cell<Option<&'static str>> = const { Cell::new(None) };

    /// Standing consumers of every announced change: the persistence container's dirty
    /// tracking. Unlike the scoped `RECORDER`, sinks persist until removed.
    static SINKS: RefCell<Vec<(u64, ChangeSink)>> = const { RefCell::new(Vec::new()) };

    static NEXT_SINK: Cell<u64> = const { Cell::new(1) };
}

type ChangeSink = Rc<dyn Fn(&Change)>;

/// Handle for one installed change sink; pass it back to [`remove_change_sink`].
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct ChangeSinkId(u64);

/// Install a standing consumer of every announced change (main thread). Where
/// [`record_changes`] is scoped to one closure, a sink lives until removed; it is how a
/// persistence container watches the stores it loaded. Sinks receive the same [`Change`] the
/// recorder would. A sink may write stores re-entrantly. The pipeline nests: a write made
/// from inside a sink completes its own announcement (sinks included) before the outer one
/// resumes, which is how relation maintenance cascades a delete. But a sink that writes owns
/// its own termination: nothing here bounds the recursion.
pub fn install_change_sink(f: impl Fn(&Change) + 'static) -> ChangeSinkId {
    let id = NEXT_SINK.with(|n| {
        let id = n.get();
        n.set(id + 1);
        id
    });
    SINKS.with(|s| s.borrow_mut().push((id, Rc::new(f))));
    ChangeSinkId(id)
}

pub fn remove_change_sink(id: ChangeSinkId) {
    // Best-effort on the drop path: a container falling out of a reactive runtime's own
    // thread-exit teardown may reach here after this TLS is gone, and that must not abort.
    let _ = SINKS.try_with(|s| s.borrow_mut().retain(|(i, _)| *i != id.0));
}

fn sinks_active() -> bool {
    SINKS.with(|s| !s.borrow().is_empty())
}

/// Deliver to every sink with the registry borrow released, so a sink's bookkeeping can never
/// collide with sink installation from another callback.
fn feed_sinks(change: &Change) {
    let sinks: Vec<ChangeSink> =
        SINKS.with(|s| s.borrow().iter().map(|(_, f)| f.clone()).collect());
    for f in sinks {
        f(change);
    }
}

/// A live trigger and who is watching it.
struct Entry {
    trigger: Trigger,
    /// The trigger's own scope, a child of root, so it can be disposed on its own.
    scope: Scope,
    /// One claim per observing computation, deduped; when the last one releases (on its
    /// re-track or death), the trigger goes with it.
    watchers: Vec<day_reactive::RunId>,
}

/// Give this path an id, so something can hang off it. Called once per source handle, never on
/// the per-field read path.
fn intern(p: Path) -> NodeId {
    NODES.with(|n| {
        let mut i = n.borrow_mut();
        if let Some(id) = i.lookup.get(&p) {
            return *id;
        }
        let id = if let Some(idx) = i.free.pop() {
            let s = &mut i.slots[idx as usize];
            s.path = p;
            s.alive = true;
            s.pinned = false;
            s.children = 0;
            s.triggers = 0;
            NodeId {
                idx,
                generation: s.generation,
            }
        } else {
            let idx = i.slots.len() as u32;
            i.slots.push(Slot {
                path: p,
                generation: 0,
                alive: true,
                pinned: false,
                children: 0,
                triggers: 0,
            });
            NodeId { idx, generation: 0 }
        };
        i.lookup.insert(p, id);
        if p.parent != ROOT
            && let Some(s) = i.slots.get_mut(p.parent.idx as usize)
            && s.alive
            && s.generation == p.parent.generation
        {
            s.children += 1;
        }
        id
    })
}

/// Whether an id still names a live slot. A handle whose cached id fails this re-interns
/// through its own chain — see the module docs on reclamation.
fn is_current(id: NodeId) -> bool {
    NODES.with(|n| n.borrow().is_current(id))
}

fn path_of(id: NodeId) -> Path {
    NODES.with(|n| n.borrow().get(id).unwrap_or(Path::root(0)))
}

fn pin(id: NodeId) {
    NODES.with(|n| {
        if let Some(s) = n.borrow_mut().slots.get_mut(id.idx as usize) {
            s.pinned = true;
        }
    });
}

/// How many interior nodes are currently interned (the sentinel excluded): the cost of
/// observation's second table, assertable in a test.
#[must_use]
pub fn interned_nodes() -> usize {
    NODES.with(|n| n.borrow().slots.iter().filter(|s| s.alive).count() - 1)
}

/// Subscribe the current reactive computation to exactly this path, and register the claim so
/// the trigger can be reclaimed on the computation's next re-track (or death).
///
/// Observation belongs to computations: outside any active run (a build seeding an initial
/// value, an event handler, `untrack`) a tracked read subscribes nothing in day-reactive, so
/// creating a trigger for it would be dead weight that some scope had to carry. It does
/// nothing; the read itself proceeds unobserved.
fn track(p: Path) {
    let Some(watcher) = day_reactive::active_run() else {
        return;
    };
    let (trigger, created, fresh) = TRIGGERS.with(|t| {
        let mut map = t.borrow_mut();
        let mut created = false;
        let entry = map.entry(p).or_insert_with(|| {
            created = true;
            // Its own child of root: outlives every observer, and disposable on its own.
            let scope = Scope::root().create_child();
            Entry {
                trigger: scope.enter(Trigger::new),
                scope,
                watchers: Vec::new(),
            }
        });
        let fresh = !entry.watchers.contains(&watcher);
        if fresh {
            entry.watchers.push(watcher);
        }
        (entry.trigger, created, fresh)
    });
    if created && p.parent != ROOT {
        NODES.with(|n| {
            let mut i = n.borrow_mut();
            if let Some(s) = i.slots.get_mut(p.parent.idx as usize)
                && s.alive
                && s.generation == p.parent.generation
            {
                s.triggers += 1;
            }
        });
    }
    if fresh {
        // The claim dies with the run: released when the computation re-tracks (having stopped
        // reading this path, or about to read it afresh) or is disposed.
        day_reactive::on_run_retrack(move || release(p, watcher));
    }
    trigger.track();
}

/// Drop one watcher's claim; the last one out disposes the trigger and lets the interner free
/// the ancestors nothing else holds.
fn release(p: Path, watcher: day_reactive::RunId) {
    let removed = TRIGGERS.with(|t| {
        let mut map = t.borrow_mut();
        let Some(entry) = map.get_mut(&p) else {
            return false;
        };
        entry.watchers.retain(|w| *w != watcher);
        if entry.watchers.is_empty() {
            let scope = entry.scope;
            map.remove(&p);
            drop(map);
            // A trigger holds nothing but a counter, so disposing it loses no state: the next
            // reader creates a fresh one.
            scope.dispose();
            true
        } else {
            false
        }
    });
    if removed && p.parent != ROOT {
        NODES.with(|n| {
            let mut i = n.borrow_mut();
            if let Some(s) = i.slots.get_mut(p.parent.idx as usize)
                && s.alive
                && s.generation == p.parent.generation
                && s.triggers > 0
            {
                s.triggers -= 1;
            }
            i.maybe_free(p.parent);
        });
    }
}

/// How many paths currently have a trigger: the cost of observation, assertable in a test.
#[must_use]
pub fn observed_paths() -> usize {
    TRIGGERS.with(|t| t.borrow().len())
}

// ---------------------------------------------------------------------------
// The change log
// ---------------------------------------------------------------------------

/// What kind of change was announced. A persistence layer needs this to choose between an
/// INSERT, an UPDATE and a DELETE; the UI does not care, which is why it rides alongside the
/// path rather than inside it.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Op {
    /// One field was written.
    Set,
    /// A row entered the collection.
    Insert,
    /// A row left it.
    Delete,
    /// The collection's order changed.
    Move,
}

/// One announced change, in the form a store outside the UI can consume.
///
/// `prior` and `value` are the slot's value before and after the write, captured only while a
/// consumer that wants them is active ([`record_values`], an [`UndoStack`]). A write with no such
/// consumer clones nothing. They are type-erased; downcast with [`Change::prior_as`] /
/// [`Change::value_as`]. A structural change carries positions as well: a `Delete` has the
/// removed row in `prior` and its index (`usize`) in `value`, an `Insert` the added row in
/// `value` and its index in `prior`, and a `Move` its index before and after.
#[derive(Clone)]
pub struct Change {
    /// The path's components, outermost first: store, key, field, …
    pub components: Vec<u64>,
    /// The field's name, which is also its column name.
    pub label: &'static str,
    pub op: Op,
    pub prior: Option<Rc<dyn Any>>,
    pub value: Option<Rc<dyn Any>>,
    /// Who made it: `None` is the user; an undo replay stamps "undo"/"redo"; an importer its
    /// own name ([`with_author`]). Consumers can decline their own echoes.
    pub author: Option<&'static str>,
}

impl Change {
    /// The value before the write, if captured and of type `T`.
    #[must_use]
    pub fn prior_as<T: 'static>(&self) -> Option<&T> {
        self.prior.as_deref().and_then(|v| v.downcast_ref())
    }

    /// The value after the write, if captured and of type `T`.
    #[must_use]
    pub fn value_as<T: 'static>(&self) -> Option<&T> {
        self.value.as_deref().and_then(|v| v.downcast_ref())
    }
}

impl fmt::Debug for Change {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Change")
            .field("components", &self.components)
            .field("label", &self.label)
            .field("op", &self.op)
            .field("prior", &self.prior.as_ref().map(|_| ".."))
            .field("value", &self.value.as_ref().map(|_| ".."))
            .field("author", &self.author)
            .finish()
    }
}

fn values_wanted() -> bool {
    WANT_VALUES.with(std::cell::Cell::get) || WANT_VALUES_STANDING.with(|w| w.get() > 0)
}

/// Whether any change consumer currently captures prior/new values: a scoped
/// [`record_values`], or a standing holder like an installed undo stack. A framework layer
/// (the persistence container) asks this to decide whether a delete must materialize its row
/// first: a value-free delete cannot be inverted, and capturing costs nothing when nobody
/// records.
#[must_use]
pub fn record_capture_active() -> bool {
    values_wanted()
}

/// Keep prior/new values flowing on every change while `on` holders exist: the undo stack's
/// standing form of what [`record_values`] does for one closure.
pub fn want_values_standing(on: bool) {
    WANT_VALUES_STANDING.with(|w| {
        let v = w.get();
        w.set(if on { v + 1 } else { v.saturating_sub(1) });
    });
}

fn previewing() -> bool {
    PREVIEW_WRITE.with(std::cell::Cell::get)
}

/// Run `f` with changes stamped as `author`: how an undo replay or an importer signs its
/// writes so consumers (a sync engine, a query) can tell them from the user's.
pub fn with_author<R>(author: &'static str, f: impl FnOnce() -> R) -> R {
    let previous = CURRENT_AUTHOR.with(|a| a.replace(Some(author)));
    // Restored on unwind too.
    let _restore = std::mem::DropGuard::new(previous, |previous| {
        CURRENT_AUTHOR.with(|a| a.set(previous));
    });
    f()
}

fn current_author() -> Option<&'static str> {
    CURRENT_AUTHOR.with(std::cell::Cell::get)
}

/// Record every change announced inside `f`. What the tests read, and the persistence layer's
/// input.
pub fn record_changes<R>(f: impl FnOnce() -> R) -> (R, Vec<Change>) {
    RECORDER.with(|r| *r.borrow_mut() = Some(Vec::new()));
    let out = f();
    let log = RECORDER.with(|r| r.borrow_mut().take().unwrap_or_default());
    (out, log)
}

/// [`record_changes`], with prior/new values captured on every field write inside `f`: the
/// form an undo unit needs. Costs one clone per write while active, nothing when not.
pub fn record_values<R>(f: impl FnOnce() -> R) -> (R, Vec<Change>) {
    WANT_VALUES.with(|w| w.set(true));
    let out = record_changes(f);
    WANT_VALUES.with(|w| w.set(false));
    out
}

/// Just the labels, for the tests that only care which fields moved.
pub fn record<R>(f: impl FnOnce() -> R) -> (R, Vec<&'static str>) {
    let (out, changes) = record_changes(f);
    (out, changes.into_iter().map(|c| c.label).collect())
}

/// Wake the observers of this path and of every ancestor, and nobody else. `components` is
/// resolved lazily: the change log wants the full path as data, but building the `Vec` is wasted
/// work when nothing records, which is almost always.
fn notify_change(
    p: Path,
    components: impl FnOnce() -> Vec<u64>,
    label: &'static str,
    op: Op,
    prior: Option<Rc<dyn Any>>,
    value: Option<Rc<dyn Any>>,
) {
    if previewing() {
        // A preview write: the UI follows, nothing durable hears it.
        wake(p);
        return;
    }
    let recording = RECORDER.with(|r| r.borrow().is_some());
    if recording || sinks_active() {
        let change = Change {
            components: components(),
            label,
            op,
            prior,
            value,
            author: current_author(),
        };
        feed_sinks(&change);
        if recording {
            RECORDER.with(|r| {
                if let Some(log) = r.borrow_mut().as_mut() {
                    log.push(change);
                }
            });
        }
    }
    wake(p);
}

fn wake(p: Path) {
    let chain = p.chain();
    let live: Vec<Trigger> = TRIGGERS.with(|t| {
        let map = t.borrow();
        chain
            .iter()
            .filter_map(|k| map.get(k).map(|e| e.trigger))
            .collect()
    });
    for tr in live {
        tr.notify();
    }
}

/// Announce a change named by plain components: how a background transaction's writes reach
/// the triggers on the main thread, and what a framework layer calls to wake a path it
/// maintains for a value that lives elsewhere (a relation index announcing a parent's to-many
/// field). Wakes the deepest path whose interior steps are interned; anything deeper cannot
/// have an observer, because observing is what interns. The change feeds sinks and the
/// recorder with the current author tag and op `Set`, carrying no values.
pub fn announce(parts: &[u64], label: &'static str) {
    announce_op(parts, label, Op::Set);
}

/// [`announce`], with the operation named; what the undo replay calls.
fn announce_op(parts: &[u64], label: &'static str, op: Op) {
    let resolved = (|| {
        let (last, interior) = parts.split_last()?;
        let mut parent = ROOT;
        for part in interior {
            let step = Path::under(parent, *part);
            match NODES.with(|n| {
                let i = n.borrow();
                i.lookup.get(&step).copied().filter(|id| i.is_current(*id))
            }) {
                Some(id) => parent = id,
                // The step was never observed: wake it as a leaf, so coarser observers above
                // it still hear the change.
                None => return Some(step),
            }
        }
        Some(Path::under(parent, *last))
    })();
    let Some(p) = resolved else { return };
    let recording = RECORDER.with(|r| r.borrow().is_some());
    if recording || sinks_active() {
        let change = Change {
            components: parts.to_vec(),
            label,
            op,
            prior: None,
            value: None,
            author: current_author(),
        };
        feed_sinks(&change);
        if recording {
            RECORDER.with(|r| {
                if let Some(log) = r.borrow_mut().as_mut() {
                    log.push(change);
                }
            });
        }
    }
    wake(p);
}

// ---------------------------------------------------------------------------
// Source
// ---------------------------------------------------------------------------

/// Anything a field can be projected out of: the store itself, one element of a keyed
/// collection, or another field (which is how nesting works).
///
/// `with_value_untracked` is the one every projection reads through: a field must subscribe to
/// its path, not to its parent's, or the granularity is gone.
pub trait Source<T: 'static>: Copy + 'static {
    /// Whether this source's location can change over the handle's lifetime: a recycled list
    /// slot whose current row rotates. Fields projected from a dynamic source resolve their
    /// path through the source on every operation instead of trusting the one cached at
    /// projection time, and their tracked reads also run [`Source::track_extra`].
    const DYNAMIC: bool = false;

    /// Extra tracking a projected field's tracked reads perform. A dynamic source tracks its
    /// own rebind signal here, so a control bound at build follows the slot to its next row.
    fn track_extra(self) {}

    /// The path this source occupies. Implementations revalidate against the interner, so the
    /// result is always current.
    fn path(self) -> Path;
    /// This source's interned id, so a child can be built with no lookup of its own.
    ///
    /// Ids are minted per thread. They are the fast path for a handle built and used on the main
    /// thread, and must never cross a thread boundary — see `components`.
    fn node(self) -> NodeId;
    /// The path as plain components, resolved by walking the handle chain rather than the
    /// interner. This is what crosses a thread boundary: a worker names what it changed with
    /// components, and the main thread re-establishes them on its own side when it announces.
    fn components(self, out: &mut Vec<u64>);
    fn with_value_untracked<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R;
    /// Returns false when the value is gone (a deleted row), in which case nothing is
    /// announced either.
    fn update_value(self, f: impl FnOnce(&mut T)) -> bool;
    fn bump_version(self);

    /// Tracked read of the whole value: the coarse subscription.
    fn with<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R {
        self.track_extra();
        track(self.path());
        self.with_value_untracked(f)
    }
}

/// What a transaction touched, in a form that survives the trip to the main thread: the path's
/// components, outermost first, plus the label the change log records.
pub type TxPaths = Vec<(Vec<u64>, &'static str)>;

// ---------------------------------------------------------------------------
// Store
// ---------------------------------------------------------------------------

/// A `Copy`, process-lifetime handle to one observable value.
pub struct Store<T: 'static> {
    inner: &'static Inner<T>,
    node: NodeId,
    root_id: u64,
}

impl<T> Clone for Store<T> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<T> Copy for Store<T> {}

struct Inner<T> {
    data: RwLock<T>,
    pending: Mutex<TxPaths>,
    version: AtomicU64,
}

/// Store root ids are process-global so two stores can never collide.
static NEXT_STORE: AtomicU64 = AtomicU64::new(1);

impl<T: 'static> Store<T> {
    /// A process-lifetime store, leaked so the handle stays `Copy` (the property that makes a
    /// `Signal` pleasant to pass). Create once (a `thread_local!` + accessor fn is the
    /// idiom); the scoped owner arrives with the persistence container.
    pub fn new(value: T) -> Store<T> {
        let inner: &'static Inner<T> = Box::leak(Box::new(Inner {
            data: RwLock::new(value),
            pending: Mutex::new(Vec::new()),
            version: AtomicU64::new(0),
        }));
        let root_id = NEXT_STORE.fetch_add(1, Ordering::Relaxed);
        let node = intern(Path::root(root_id));
        pin(node);
        Store {
            inner,
            node,
            root_id,
        }
    }

    /// Read the whole value without subscribing the caller to changes.
    ///
    /// # Panics
    ///
    /// Panics if a thread panicked while holding the store's lock.
    pub fn with_untracked<R>(self, f: impl FnOnce(&T) -> R) -> R {
        f(&self.inner.data.read().expect("store poisoned"))
    }

    /// Mutate the whole value; announces a store-wide change (every reader wakes).
    ///
    /// # Panics
    ///
    /// Panics if a thread panicked while holding the store's lock.
    pub fn update(self, label: &'static str, f: impl FnOnce(&mut T)) {
        {
            let mut g = self.inner.data.write().expect("store poisoned");
            f(&mut g);
        }
        self.inner.version.fetch_add(1, Ordering::Relaxed);
        let root_id = self.root_id;
        notify_change(
            path_of(self.node),
            || vec![root_id],
            label,
            Op::Set,
            None,
            None,
        );
    }

    /// Bumped on every write; a cheap way for tests to ask "did anything change".
    #[must_use]
    pub fn version(self) -> u64 {
        self.inner.version.load(Ordering::Relaxed)
    }

    /// This store's root id, the first component of every path under it. A persistence
    /// container keys its table map on it.
    #[must_use]
    pub fn store_id(self) -> u64 {
        self.root_id
    }

    /// Announce everything background transactions committed, returning how many paths were
    /// queued. An app posts this to the main loop after a worker commits; a test calls it
    /// directly and asserts what it woke.
    ///
    /// # Panics
    ///
    /// Panics if a thread panicked while holding the store's pending-announcement queue.
    #[must_use]
    pub fn pump(self) -> usize {
        let drained: TxPaths = {
            let mut q = self.inner.pending.lock().expect("queue poisoned");
            std::mem::take(&mut *q)
        };
        let n = drained.len();
        day_reactive::batch(|| {
            for (parts, label) in drained {
                announce(&parts, label);
            }
        });
        n
    }
}

impl<T: 'static> Source<T> for Store<T> {
    fn path(self) -> Path {
        path_of(self.node)
    }
    fn node(self) -> NodeId {
        // Pinned at creation, so always current.
        self.node
    }
    fn components(self, out: &mut Vec<u64>) {
        out.push(self.root_id);
    }
    fn with_value_untracked<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R {
        f(Some(&self.inner.data.read().expect("store poisoned")))
    }
    fn update_value(self, f: impl FnOnce(&mut T)) -> bool {
        let mut g = self.inner.data.write().expect("store poisoned");
        f(&mut g);
        true
    }
    fn bump_version(self) {
        self.inner.version.fetch_add(1, Ordering::Relaxed);
    }
}

// SAFETY: the handle is a shared reference to data behind a lock plus Copy ids. The reactive
// triggers those ids name are touched only on the main thread; writes from other threads go
// through `transact`, whose announcements are queued and delivered by `pump`.
unsafe impl<T: Send + Sync> Send for Store<T> {}
unsafe impl<T: Send + Sync> Sync for Store<T> {}

// ---------------------------------------------------------------------------
// Transactions
// ---------------------------------------------------------------------------

impl<T: Send + Sync + 'static> Store<T> {
    /// Open a write transaction: the way a background thread edits. Holding it holds the
    /// store's write lock, so a reader never sees half of one; dropping it commits and queues
    /// the announcements for [`Store::pump`].
    ///
    /// # Panics
    ///
    /// Panics if a thread panicked while holding the store's lock.
    #[must_use]
    pub fn transact(self) -> Tx<T> {
        Tx {
            store: self,
            guard: Some(self.inner.data.write().expect("store poisoned")),
            touched: Vec::new(),
        }
    }
}

/// An open background transaction. Name what you touch with [`Field::touch`] (or push
/// components directly); commit by dropping.
pub struct Tx<T: Send + Sync + 'static> {
    store: Store<T>,
    guard: Option<std::sync::RwLockWriteGuard<'static, T>>,
    touched: TxPaths,
}

impl<T: Send + Sync + 'static> Tx<T> {
    #[expect(
        clippy::missing_panics_doc,
        reason = "the guard is taken in Drop alone, so the `expect` cannot fail on a live Tx"
    )]
    pub fn data(&mut self) -> &mut T {
        // A Tx is only reachable while uncommitted: the guard is taken in Drop alone.
        self.guard.as_mut().expect("transaction already committed")
    }
    pub fn touched(&mut self, parts: Vec<u64>, label: &'static str) {
        self.touched.push((parts, label));
    }
    pub fn paths(&mut self) -> &mut TxPaths {
        &mut self.touched
    }
}

impl<T: Send + Sync + 'static> Drop for Tx<T> {
    fn drop(&mut self) {
        let touched = std::mem::take(&mut self.touched);
        let store = self.store;
        // Release the data lock first: the commit is the unlock.
        drop(self.guard.take());
        store.inner.version.fetch_add(1, Ordering::Relaxed);
        store
            .inner
            .pending
            .lock()
            .expect("queue poisoned")
            .extend(touched);
        // Announcing is the main thread's job; see `Store::pump`. (Scheduling the pump
        // automatically is the persistence container's job later; a bare store keeps delivery
        // explicit so a headless test owns its own timing.)
    }
}

// ---------------------------------------------------------------------------
// Keys and identity
// ---------------------------------------------------------------------------

/// The floor of the interned-handle space. Plain `u64` keys pass through as their own handle
/// and stay below it; the top bit is what lets [`Key::of_handle`] tell an identity handle
/// from an interned one without any lookup. Integer `#[obs(key)]` fields assert the bound in
/// debug builds rather than silently colliding.
const WIDE_BASE: u64 = 1 << 63;

/// One element's key: what its paths, its [`Keyed`] slot, and (under persistence) its stored
/// row are addressed by.
///
/// A `u64` key is its own path handle, with no interner, lock or allocation: exactly the cost
/// integer keys always had. The wide forms (`Uuid`, `Str`, `Pair`) intern process-globally to
/// a `u64` handle on first use, so paths stay 12 bytes and every collection index stays
/// `u64`-keyed. A handle, once minted, is stable for the process's lifetime (undo records
/// and long-lived `ModelId`s rely on that) and reverses through [`Key::of_handle`]; the
/// interner's size is observable via [`interned_keys`].
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum Key {
    U64(u64),
    /// A UUID, carried as its raw 128 bits (`uuid::Uuid::as_u128`).
    Uuid(u128),
    /// A natural string key: a slug, an external system's id.
    Str(Arc<str>),
    /// Two handles as one key: how the persistence layer addresses join rows. Apps rarely
    /// construct one directly.
    Pair(u64, u64),
}

impl Key {
    /// The key's path handle: identity for `U64`, interned (once, then a read-locked lookup)
    /// for the wide forms. Callable from any thread; the interner is process-global.
    #[must_use]
    pub fn handle(&self) -> u64 {
        match self {
            Key::U64(k) => *k,
            Key::Uuid(u) => intern_wide(WideKey::Uuid(*u)),
            Key::Str(s) => intern_wide(WideKey::Str(s.clone())),
            Key::Pair(a, b) => intern_wide(WideKey::Pair(*a, *b)),
        }
    }

    /// The key a handle names: identity below the wide floor, the interner's record above
    /// it. `None` only for a wide handle nothing ever interned (a forged value).
    ///
    /// # Panics
    ///
    /// Panics if a thread panicked while holding the key interner's lock.
    #[must_use]
    pub fn of_handle(handle: u64) -> Option<Key> {
        if handle < WIDE_BASE {
            return Some(Key::U64(handle));
        }
        let idx = (handle - WIDE_BASE) as usize;
        wide_keys()
            .read()
            .expect("key interner poisoned")
            .reverse
            .get(idx)
            .map(|w| match w {
                WideKey::Uuid(u) => Key::Uuid(*u),
                WideKey::Str(s) => Key::Str(s.clone()),
                WideKey::Pair(a, b) => Key::Pair(*a, *b),
            })
    }

    #[must_use]
    pub fn as_u64(&self) -> Option<u64> {
        match self {
            Key::U64(k) => Some(*k),
            _ => None,
        }
    }

    #[must_use]
    pub fn as_uuid(&self) -> Option<uuid::Uuid> {
        match self {
            Key::Uuid(u) => Some(uuid::Uuid::from_u128(*u)),
            _ => None,
        }
    }

    #[must_use]
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Key::Str(s) => Some(s),
            _ => None,
        }
    }
}

impl fmt::Display for Key {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Key::U64(k) => write!(f, "{k}"),
            Key::Uuid(u) => write!(f, "{}", uuid::Uuid::from_u128(*u)),
            Key::Str(s) => f.write_str(s),
            Key::Pair(a, b) => write!(f, "{a}:{b}"),
        }
    }
}

/// The wide-key interner's stored form (`U64` never enters it).
#[derive(Clone, PartialEq, Eq, Hash)]
enum WideKey {
    Uuid(u128),
    Str(Arc<str>),
    Pair(u64, u64),
}

#[derive(Default)]
struct WideKeys {
    lookup: HashMap<WideKey, u64>,
    reverse: Vec<WideKey>,
}

/// Process-global, unlike the path interner: handles are embedded in `Keyed` indexes that
/// background transactions mutate, so a thread-local table would mint divergent handles, the
/// exact bug the path system's `components` method exists to prevent.
static WIDE_KEYS: OnceLock<RwLock<WideKeys>> = OnceLock::new();

fn wide_keys() -> &'static RwLock<WideKeys> {
    WIDE_KEYS.get_or_init(Default::default)
}

fn intern_wide(k: WideKey) -> u64 {
    if let Some(h) = wide_keys()
        .read()
        .expect("key interner poisoned")
        .lookup
        .get(&k)
    {
        return *h;
    }
    let mut w = wide_keys().write().expect("key interner poisoned");
    if let Some(h) = w.lookup.get(&k) {
        return *h; // another thread won the race between our two locks
    }
    let h = WIDE_BASE + w.reverse.len() as u64;
    w.reverse.push(k.clone());
    w.lookup.insert(k, h);
    h
}

/// How many wide keys the process has interned: the cost of wide-key identity itself,
/// assertable in a test. Entries are retained for the process's lifetime.
///
/// # Panics
///
/// Panics if a thread panicked while holding the key interner's lock.
#[must_use]
pub fn interned_keys() -> usize {
    wide_keys()
        .read()
        .expect("key interner poisoned")
        .reverse
        .len()
}

/// A value usable as a key: what an `#[obs(key)]` / `#[model(id)]` field's type implements.
/// Integer keys reserve the top bit (the interned-handle space); a negative cast or a
/// hash-derived id at or above `1 << 63` is refused in debug builds rather than silently
/// colliding with an interned handle.
pub trait AsKey {
    fn as_key(&self) -> Key;
}

fn int_key(k: u64) -> Key {
    debug_assert!(
        k < WIDE_BASE,
        "u64 keys reserve the top bit for interned handles (got {k:#x})"
    );
    Key::U64(k)
}

macro_rules! int_key {
    ($($t:ty),*) => {$(
        impl AsKey for $t {
            fn as_key(&self) -> Key {
                int_key(*self as u64)
            }
        }
    )*};
}
macro_rules! lossless_int_key {
    ($($t:ty),*) => {$(
        impl AsKey for $t {
            fn as_key(&self) -> Key {
                int_key(u64::from(*self))
            }
        }
    )*};
}
lossless_int_key!(u8, u16, u32);
int_key!(u64, usize, i8, i16, i32, i64, isize);

impl AsKey for String {
    fn as_key(&self) -> Key {
        Key::Str(Arc::from(self.as_str()))
    }
}
impl AsKey for &str {
    fn as_key(&self) -> Key {
        Key::Str(Arc::from(*self))
    }
}
impl AsKey for Arc<str> {
    fn as_key(&self) -> Key {
        Key::Str(self.clone())
    }
}
impl AsKey for uuid::Uuid {
    fn as_key(&self) -> Key {
        Key::Uuid(self.as_u128())
    }
}
impl AsKey for Key {
    fn as_key(&self) -> Key {
        self.clone()
    }
}

/// A typed, opaque id for one `M` row: `Copy`, 8 bytes, cheap to pass and compare. It wraps
/// the key's path handle: [`Store::elem`], query results, list slots and destinations all
/// speak it, and a wrong-model id is a compile error rather than a wrong row. [`ModelId::key`]
/// recovers the real key for display, deep links, or the persistence edge.
///
/// Ordering compares handles: meaningful for integer keys, arbitrary (but stable) for wide
/// ones; it exists so ids can live in sorted containers.
pub struct ModelId<M: ?Sized> {
    handle: u64,
    _m: PhantomData<fn() -> M>,
}

impl<M: ?Sized> Clone for ModelId<M> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<M: ?Sized> Copy for ModelId<M> {}
impl<M: ?Sized> PartialEq for ModelId<M> {
    fn eq(&self, other: &Self) -> bool {
        self.handle == other.handle
    }
}
impl<M: ?Sized> Eq for ModelId<M> {}
impl<M: ?Sized> std::hash::Hash for ModelId<M> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.handle.hash(state);
    }
}
impl<M: ?Sized> PartialOrd for ModelId<M> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl<M: ?Sized> Ord for ModelId<M> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.handle.cmp(&other.handle)
    }
}
impl<M: ?Sized> fmt::Debug for ModelId<M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match Key::of_handle(self.handle) {
            Some(k) => write!(f, "ModelId({k})"),
            None => write!(f, "ModelId(#{:x})", self.handle),
        }
    }
}

impl<M: ?Sized> ModelId<M> {
    /// The id for `key`, interning it if wide.
    #[expect(
        clippy::needless_pass_by_value,
        reason = "public signature; callers pass key literals and owned keys by value"
    )]
    pub fn of(key: impl AsKey) -> Self {
        Self::from_handle(key.as_key().handle())
    }
    /// Wrap an existing path handle (from [`Store::keys`], a slot token, a change record).
    #[must_use]
    pub const fn from_handle(handle: u64) -> Self {
        ModelId {
            handle,
            _m: PhantomData,
        }
    }
    #[must_use]
    pub fn handle(self) -> u64 {
        self.handle
    }
    /// The real key: identity for integer handles, the interner's record for wide ones.
    #[must_use]
    pub fn key(self) -> Key {
        Key::of_handle(self.handle).unwrap_or(Key::U64(self.handle))
    }
}

/// Integer-keyed ids compare against their key value directly: `assert_eq!(ids, [1, 3])`
/// reads the way integer-keyed code always has.
impl<M: ?Sized> PartialEq<u64> for ModelId<M> {
    fn eq(&self, other: &u64) -> bool {
        self.handle == *other
    }
}
impl<M: ?Sized> PartialEq<ModelId<M>> for u64 {
    fn eq(&self, other: &ModelId<M>) -> bool {
        *self == other.handle
    }
}

/// Raw path handles convert directly; this is how `store.elem(k)` keeps taking the values
/// [`Store::keys`] returns, and how integer keys stay literal-friendly.
impl<M: ?Sized> From<u64> for ModelId<M> {
    fn from(handle: u64) -> Self {
        ModelId::from_handle(handle)
    }
}
impl<M: ?Sized> From<u32> for ModelId<M> {
    fn from(k: u32) -> Self {
        ModelId::of(k)
    }
}
impl<M: ?Sized> From<i32> for ModelId<M> {
    fn from(k: i32) -> Self {
        ModelId::of(k)
    }
}
impl<M: ?Sized> From<usize> for ModelId<M> {
    fn from(k: usize) -> Self {
        ModelId::of(k)
    }
}
impl<M: ?Sized> From<uuid::Uuid> for ModelId<M> {
    fn from(k: uuid::Uuid) -> Self {
        ModelId::of(k)
    }
}
impl<M: ?Sized> From<&str> for ModelId<M> {
    fn from(k: &str) -> Self {
        ModelId::of(k)
    }
}
impl<M: ?Sized> From<String> for ModelId<M> {
    fn from(k: String) -> Self {
        ModelId::of(k)
    }
}
impl<M: ?Sized> From<Key> for ModelId<M> {
    fn from(k: Key) -> Self {
        ModelId::from_handle(k.handle())
    }
}
impl<M: ?Sized> From<&Key> for ModelId<M> {
    fn from(k: &Key) -> Self {
        ModelId::from_handle(k.handle())
    }
}

// ---------------------------------------------------------------------------
// Keyed collections
// ---------------------------------------------------------------------------

/// Gives an element the stable key its paths are addressed by. Implemented by
/// `#[derive(Observable)]` from the `#[obs(key)]` field.
pub trait Identified {
    /// The element's key, read from the `#[obs(key)]` field.
    fn key(&self) -> Key;

    /// The key as its path handle: identity for `u64` keys, interned otherwise.
    fn handle(&self) -> u64 {
        self.key().handle()
    }

    /// The typed id over the same handle. (Named to stay clear of the generated accessor for
    /// an `id` field, which nearly every model has.)
    fn model_id(&self) -> ModelId<Self>
    where
        Self: Sized,
    {
        ModelId::from_handle(self.handle())
    }
}

/// A keyed collection that keeps its own key→index map, so an element read is O(1) rather than
/// a scan, and no caller can forget to maintain the map, because the collection does it.
pub struct Keyed<T> {
    items: Vec<T>,
    index: HashMap<u64, usize>,
    /// Set when raw access ([`Keyed::items_mut`]) may have invalidated the map. The mutating
    /// methods keep it correct themselves, so the O(n) rebuild happens only where a caller
    /// reached past them, which is what keeps a bulk insert O(n) rather than O(n²).
    stale: bool,
}

impl<T: Identified> Default for Keyed<T> {
    fn default() -> Self {
        Keyed {
            items: Vec::new(),
            index: HashMap::new(),
            stale: false,
        }
    }
}

impl<T: Identified> Keyed<T> {
    #[must_use]
    pub fn new(items: Vec<T>) -> Self {
        let mut k = Keyed {
            items,
            index: HashMap::new(),
            stale: false,
        };
        k.reindex();
        k
    }

    /// Rebuild the map. O(n); integer keys pay no interner cost here, wide keys pay one
    /// read-locked lookup per row.
    pub fn reindex(&mut self) {
        self.index.clear();
        for (i, item) in self.items.iter().enumerate() {
            self.index.insert(item.handle(), i);
        }
        self.stale = false;
    }

    /// Rebuild only if raw access may have invalidated the map: what [`Store::restructure`]
    /// calls, so appending a row stays O(1) instead of rebuilding the whole index per insert.
    pub fn reindex_if_stale(&mut self) {
        if self.stale {
            self.reindex();
        }
    }

    #[must_use]
    pub fn get(&self, key: u64) -> Option<&T> {
        self.index.get(&key).and_then(|i| self.items.get(*i))
    }

    pub fn get_mut(&mut self, key: u64) -> Option<&mut T> {
        match self.index.get(&key) {
            Some(i) => self.items.get_mut(*i),
            None => None,
        }
    }

    #[must_use]
    pub fn keys(&self) -> Vec<u64> {
        self.items.iter().map(Identified::handle).collect()
    }

    #[must_use]
    pub fn items(&self) -> &[T] {
        &self.items
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.items.len()
    }

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

    /// The next free integer key: one past the largest in use (1 for an empty collection), or
    /// the lowest unused key from 1 once that would reach the top bit integer keys reserve
    /// (see [`AsKey`]). Interned keys (`Uuid`, `Str`, `Pair`) are not counted.
    #[must_use]
    pub fn next_key(&self) -> u64 {
        let used = || {
            self.items
                .iter()
                .map(Identified::handle)
                .filter(|h| (1..WIDE_BASE).contains(h))
        };
        match used().max() {
            None => 1,
            Some(max) if max + 1 < WIDE_BASE => max + 1,
            Some(_) => {
                let mut keys: Vec<u64> = used().collect();
                keys.sort_unstable();
                // A sorted run of distinct keys from 1 first skips a value where
                // `keys[i] != i + 1`.
                let gap = keys.iter().zip(1u64..).find(|(k, want)| **k != *want);
                gap.map_or(keys.len() as u64 + 1, |(_, want)| want)
            }
        }
    }

    // --- structural operations: each leaves the index correct ---------------------------------

    pub fn push(&mut self, item: T) {
        self.index.insert(item.handle(), self.items.len());
        self.items.push(item);
    }

    pub fn remove(&mut self, key: u64) -> Option<T> {
        let i = self.index.remove(&key)?;
        let item = self.items.remove(i);
        self.reindex();
        Some(item)
    }

    pub fn move_item(&mut self, from: usize, to: usize) {
        if from >= self.items.len() || to >= self.items.len() {
            return;
        }
        let item = self.items.remove(from);
        self.items.insert(to, item);
        self.reindex();
    }

    /// Remove every row. What a reload wants before pushing the new set, in one call rather
    /// than a [`Keyed::remove`] (and a reindex) per key.
    pub fn clear(&mut self) {
        self.items.clear();
        self.index.clear();
        self.stale = false;
    }

    /// The raw list, for a structural edit inside [`Store::restructure`] that the helpers above
    /// do not cover. Taking it marks the key map stale, so the store rebuilds it after the
    /// caller's closure returns; the helpers above stay index-correct on their own and pay
    /// nothing for this.
    pub fn items_mut(&mut self) -> &mut Vec<T> {
        self.stale = true;
        &mut self.items
    }
}

// ---------------------------------------------------------------------------
// Elements
// ---------------------------------------------------------------------------

/// One element of a keyed store, addressed by a key that survives reordering.
pub struct Elem<T: 'static> {
    store: Store<Keyed<T>>,
    key: u64,
    /// Interned once per handle, not once per field read; revalidated on use.
    node: NodeId,
}

impl<T> Clone for Elem<T> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<T> Copy for Elem<T> {}

impl<T: Identified + 'static> Store<Keyed<T>> {
    /// One element, addressed by its id: a [`ModelId`], a raw handle from [`Store::keys`],
    /// an integer key, a `Uuid`, or a string key all convert. O(1), because the collection keeps a
    /// handle→index map.
    pub fn elem(self, key: impl Into<ModelId<T>>) -> Elem<T> {
        let key = key.into().handle();
        Elem {
            store: self,
            key,
            node: intern(Path::under(self.node, key)),
        }
    }

    /// Tracked read of the collection's shape (which keys, in what order): what a list widget
    /// wants. A field write does not wake it; an insert, a removal or a reorder does.
    #[must_use]
    pub fn keys(self) -> Vec<u64> {
        track(Path::under(self.node, STRUCTURE));
        self.with_untracked(|k| k.keys().clone())
    }

    /// [`Store::keys`], typed — the same tracked read, as [`ModelId`]s.
    pub fn ids(self) -> Vec<ModelId<T>> {
        self.keys().into_iter().map(ModelId::from_handle).collect()
    }

    /// Structural change: insert, remove, reorder.
    ///
    /// The affected key and the operation are announced alongside the shape path, because a
    /// persistence layer has to choose between an INSERT and a DELETE and cannot infer it from
    /// "the shape changed", while the UI, which only re-reads `keys()`, ignores both.
    ///
    /// # Panics
    ///
    /// Panics if a thread panicked while holding the store's lock.
    pub fn restructure(
        self,
        label: &'static str,
        op: Op,
        key: impl Into<ModelId<T>>,
        f: impl FnOnce(&mut Keyed<T>),
    ) where
        T: Clone,
    {
        let key = key.into().handle();
        // When a values consumer stands by (an undo stack), a Delete carries the row it
        // removed and an Insert the row it added, each with its index, and a Move its index
        // before and after: the whole of what inversion needs (see `Change`).
        let capture = values_wanted();
        let mut prior: Option<Rc<dyn Any>> = None;
        let mut value: Option<Rc<dyn Any>> = None;
        {
            let mut g = self.inner.data.write().expect("store poisoned");
            let index = |k: &Keyed<T>| k.items().iter().position(|t| t.handle() == key);
            let before = if capture { index(&g) } else { None };
            if capture && op == Op::Delete {
                prior = g.get(key).cloned().map(|r| Rc::new(r) as Rc<dyn Any>);
            }
            f(&mut g);
            g.reindex_if_stale();
            if capture {
                let after = index(&g);
                let at = |i: Option<usize>| i.map(|i| Rc::new(i) as Rc<dyn Any>);
                match op {
                    Op::Insert => {
                        value = g.get(key).cloned().map(|r| Rc::new(r) as Rc<dyn Any>);
                        prior = at(after);
                    }
                    Op::Delete => value = at(before),
                    Op::Move => (prior, value) = (at(before), at(after)),
                    Op::Set => {}
                }
            }
        }
        self.inner.version.fetch_add(1, Ordering::Relaxed);
        let root_id = self.root_id;
        notify_change(
            Path::under(self.node, key),
            || vec![root_id, key],
            label,
            op,
            prior,
            value,
        );
        notify_change(
            Path::under(self.node, STRUCTURE),
            || vec![root_id, STRUCTURE],
            label,
            op,
            None,
            None,
        );
    }

    /// Append `item`: the [`Store::restructure`] insert, announced under its own key.
    pub fn push(self, item: T)
    where
        T: Clone,
    {
        let key = item.handle();
        self.restructure("push", Op::Insert, ModelId::from_handle(key), |k| {
            k.push(item);
        });
    }

    /// Remove the row with `key`: the [`Store::restructure`] delete. Returns false, announcing
    /// nothing, when no such row exists.
    pub fn remove(self, key: impl Into<ModelId<T>>) -> bool
    where
        T: Clone,
    {
        let key = key.into().handle();
        if self.with_untracked(|k| k.get(key).is_none()) {
            return false;
        }
        self.restructure("remove", Op::Delete, ModelId::from_handle(key), |k| {
            k.remove(key);
        });
        true
    }

    /// Move the row at index `from` to index `to`, the shape a native list's reorder gesture
    /// reports. Returns false, announcing nothing, when the move is out of range or in place.
    pub fn move_row(self, from: usize, to: usize) -> bool
    where
        T: Clone,
    {
        let key = self.with_untracked(|k| {
            if from == to || to >= k.len() {
                return None;
            }
            k.items().get(from).map(Identified::handle)
        });
        let Some(key) = key else { return false };
        self.restructure("move", Op::Move, ModelId::from_handle(key), |k| {
            k.move_item(from, to);
        });
        true
    }

    /// The next free integer key: one past the largest in use, for a model keyed by a `u64`
    /// field. Untracked. See [`Keyed::next_key`].
    #[must_use]
    pub fn next_key(self) -> u64 {
        self.with_untracked(Keyed::next_key)
    }

    /// Feed one row's new value from outside the app's own editing (another connection's
    /// committed write arriving through a persistence container, an import), replacing the
    /// stored value and announcing each label in `changed` as that field's `Set`. The
    /// announcement is precise: readers of the named fields wake, along with everything
    /// coarser, where a wholesale [`Store::update`] wakes only readers of the store itself.
    /// The announcements carry no values (a background transaction's shape) and the current
    /// author tag; wrap the call in [`with_author`] so consumers can tell the merge from the
    /// user's own edits. Returns false, announcing nothing, when the row is absent: an absent
    /// row is an insert, which is [`Store::restructure`]'s job.
    ///
    /// # Panics
    ///
    /// Panics if a thread panicked while holding the store's lock.
    pub fn merge_row(self, key: impl Into<ModelId<T>>, value: T, changed: &[&'static str]) -> bool
    where
        T: Clone,
    {
        let key = key.into().handle();
        {
            let mut g = self.inner.data.write().expect("store poisoned");
            match g.get_mut(key) {
                Some(slot) => *slot = value,
                None => return false,
            }
        }
        self.inner.version.fetch_add(1, Ordering::Relaxed);
        let elem = intern(Path::under(self.node, key));
        let root_id = self.root_id;
        for &label in changed {
            notify_change(
                Path::under(elem, field_id(label)),
                || vec![root_id, key, field_id(label)],
                label,
                Op::Set,
                None,
                None,
            );
        }
        true
    }

    /// Write one field by label: front-door semantics (announced at the field's own path,
    /// prior/new values captured while a consumer wants them, undoable, persisted) without
    /// the generated accessor in scope. The relation machinery writes foreign keys and order
    /// values through this; it is public because any framework-level maintenance faces the
    /// same need. Returns false, announcing nothing, when the row is absent or when
    /// `label`/`V` name no field of `T` (the [`ApplyField`] downcast refused).
    ///
    /// # Panics
    ///
    /// Panics if a thread panicked while holding the store's lock.
    pub fn write_field<V: Clone + 'static>(
        self,
        key: impl Into<ModelId<T>>,
        label: &'static str,
        value: V,
    ) -> bool
    where
        T: ApplyField,
    {
        let key = key.into().handle();
        let capture = values_wanted() && !previewing();
        let mut prior: Option<Rc<dyn Any>> = None;
        let ok = {
            let mut g = self.inner.data.write().expect("store poisoned");
            match g.get_mut(key) {
                Some(t) => {
                    if capture {
                        prior = t.read_field(label);
                    }
                    t.apply_field(label, &value)
                }
                None => false,
            }
        };
        if !ok {
            return false;
        }
        self.inner.version.fetch_add(1, Ordering::Relaxed);
        let elem = intern(Path::under(self.node, key));
        let after: Option<Rc<dyn Any>> = if capture { Some(Rc::new(value)) } else { None };
        let root_id = self.root_id;
        notify_change(
            Path::under(elem, field_id(label)),
            || vec![root_id, key, field_id(label)],
            label,
            Op::Set,
            prior,
            after,
        );
        true
    }

    /// Insert-or-replace rows without announcing: the persistence layer faulting stored rows
    /// into its cache. No change record is born (sinks, undo and autosave all stay quiet: the
    /// rows are the database's own contents arriving, not edits), and no trigger wakes: a
    /// faulting read populates before anything binds, so there is nobody to wake yet. The
    /// version still bumps, so version-watching tests see the population.
    ///
    /// # Panics
    ///
    /// Panics if a thread panicked while holding the store's lock.
    pub fn populate(self, rows: Vec<T>) {
        {
            let mut g = self.inner.data.write().expect("store poisoned");
            for row in rows {
                let key = row.handle();
                match g.get_mut(key) {
                    Some(slot) => *slot = row,
                    None => g.push(row),
                }
            }
        }
        self.inner.version.fetch_add(1, Ordering::Relaxed);
    }

    /// Remove one row without announcing: the persistence layer evicting a clean cached row.
    /// The row is not deleted anywhere; it stops being resident, and a later fault
    /// brings it back. Callers guard with [`Store::is_observed`]: evicting a row something is
    /// bound to would flip that binding to its `Default` with no wakeup to correct it.
    ///
    /// # Panics
    ///
    /// Panics if a thread panicked while holding the store's lock.
    pub fn depopulate(self, key: impl Into<ModelId<T>>) -> bool {
        let key = key.into().handle();
        let removed = {
            let mut g = self.inner.data.write().expect("store poisoned");
            g.remove(key).is_some()
        };
        if removed {
            self.inner.version.fetch_add(1, Ordering::Relaxed);
        }
        removed
    }

    /// [`Store::depopulate`], batched: One retain and one reindex for the whole set, where
    /// per-key removal would rebuild the key map per row, the difference between an eviction
    /// pass costing O(cache) and O(cache × evicted). Returns how many rows left.
    ///
    /// # Panics
    ///
    /// Panics if a thread panicked while holding the store's lock.
    pub fn depopulate_many(self, keys: &[u64]) -> usize {
        if keys.is_empty() {
            return 0;
        }
        let set: std::collections::HashSet<u64> = keys.iter().copied().collect();
        let removed = {
            let mut g = self.inner.data.write().expect("store poisoned");
            let before = g.len();
            g.items_mut().retain(|item| !set.contains(&item.handle()));
            g.reindex_if_stale();
            before - g.len()
        };
        if removed > 0 {
            self.inner.version.fetch_add(1, Ordering::Relaxed);
        }
        removed
    }

    /// Release all row payloads after an owning database queue has permanently closed.
    /// This sends no notifications: callers must first detach every observer and undo history.
    /// Handles remain allocated (Store is Copy), but large row data and indexes are reclaimed.
    /// Poisoned data is discarded too; a failed worker must never retain its working set.
    #[doc(hidden)]
    pub fn dispose_contents(self) {
        let old = {
            let mut data = self
                .inner
                .data
                .write()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            std::mem::replace(&mut *data, Keyed::new(Vec::new()))
        };
        // User row destructors may re-enter other code. Do not run them under the data lock.
        drop(old);
    }

    /// Whether anything currently observes this element: a trigger on the element's own path,
    /// or on any path under it (a bound field, a nested struct). The eviction guard: a row
    /// nobody observes can leave the cache silently, because the next reader faults it back.
    pub fn is_observed(self, key: impl Into<ModelId<T>>) -> bool {
        let key = key.into().handle();
        let elem = Path::under(self.node, key);
        if TRIGGERS.with(|t| t.borrow().contains_key(&elem)) {
            return true;
        }
        NODES.with(|n| {
            let i = n.borrow();
            match i.lookup.get(&elem) {
                Some(id) => match i.slots.get(id.idx as usize) {
                    Some(s) if s.alive && s.generation == id.generation => {
                        s.triggers > 0 || s.children > 0
                    }
                    _ => false,
                },
                None => false,
            }
        })
    }
}

impl<T: Identified + 'static> Elem<T> {
    /// The path handle this element addresses: the raw form of [`Elem::model_id`].
    #[must_use]
    pub fn key(self) -> u64 {
        self.key
    }

    /// The element's typed id. (Named to stay clear of the `id` field accessor an inherent
    /// `id()` would shadow on every model that has one.)
    #[must_use]
    pub fn model_id(self) -> ModelId<T> {
        ModelId::from_handle(self.key)
    }

    /// Whether the row is (still) present. Tracked, so a guard re-runs when the row is deleted
    /// or comes back. This is the deletion story: reads of a gone row return the field's
    /// `Default`, and this is the one signal a page needs to degrade instead.
    #[must_use]
    pub fn exists(self) -> bool {
        track(self.path());
        self.with_value_untracked(|v| v.is_some())
    }

    /// The cached id when still live, a fresh interning otherwise: the self-healing described
    /// in the module docs.
    fn live_node(self) -> NodeId {
        if is_current(self.node) {
            self.node
        } else {
            intern(Path::under(self.store.node, self.key))
        }
    }
}

impl<T: Identified + 'static> Source<T> for Elem<T> {
    fn path(self) -> Path {
        // The store root is pinned, so this Path is stable across reclamation.
        Path::under(self.store.node, self.key)
    }
    fn node(self) -> NodeId {
        self.live_node()
    }
    fn components(self, out: &mut Vec<u64>) {
        self.store.components(out);
        out.push(self.key);
    }
    fn with_value_untracked<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R {
        let g = self.store.inner.data.read().expect("store poisoned");
        f(g.get(self.key))
    }
    fn update_value(self, f: impl FnOnce(&mut T)) -> bool {
        let mut g = self.store.inner.data.write().expect("store poisoned");
        match g.get_mut(self.key) {
            Some(t) => {
                f(t);
                true
            }
            None => false,
        }
    }
    fn bump_version(self) {
        self.store.inner.version.fetch_add(1, Ordering::Relaxed);
    }
}

// ---------------------------------------------------------------------------
// Fields
// ---------------------------------------------------------------------------

/// One field, projected out of any [`Source`]. `Copy`, itself a `Source` (so fields nest), and a
/// [`Binding`] (so every control binds to it).
pub struct Field<S, T: 'static, V: 'static> {
    src: S,
    path: Path,
    part: u64,
    label: &'static str,
    get: fn(&T) -> &V,
    get_mut: fn(&mut T) -> &mut V,
}

impl<S: Copy, T, V> Clone for Field<S, T, V> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<S: Copy, T, V> Copy for Field<S, T, V> {}

/// What the derive calls. Named `project` rather than `field` so a struct may have a field
/// called `field` without a collision.
pub fn project<S: Source<T>, T: 'static, V: 'static>(
    src: S,
    label: &'static str,
    get: fn(&T) -> &V,
    get_mut: fn(&mut T) -> &mut V,
) -> Field<S, T, V> {
    let part = field_id(label);
    Field {
        src,
        // No interning here: this is the per-read path, and the parent is already an id.
        path: Path::under(src.node(), part),
        part,
        label,
        get,
        get_mut,
    }
}

impl<S: Source<T>, T: 'static, V: 'static> Field<S, T, V> {
    /// The cached path when its parent is still live, a rebuilt one otherwise. A dynamic
    /// source (a recycled slot) never trusts the cache: its location is wherever the source
    /// says it is right now.
    fn live_path(self) -> Path {
        if !S::DYNAMIC && is_current(self.path.parent) {
            self.path
        } else {
            Path::under(self.src.node(), self.part)
        }
    }

    /// Tracked read of this field only.
    pub fn with<R>(self, f: impl FnOnce(Option<&V>) -> R) -> R {
        self.src.track_extra();
        track(self.live_path());
        self.src.with_value_untracked(|t| f(t.map(self.get)))
    }

    pub fn with_untracked<R>(self, f: impl FnOnce(Option<&V>) -> R) -> R {
        self.src.with_value_untracked(|t| f(t.map(self.get)))
    }

    /// Write, waking readers of this field and of anything coarser. When a change-log consumer
    /// asked for values ([`record_values`]), the slot's prior and new value ride along.
    pub fn update(self, f: impl FnOnce(&mut V))
    where
        V: Clone,
    {
        let capture = values_wanted() && !previewing();
        let mut prior: Option<Rc<dyn Any>> = None;
        let mut after: Option<Rc<dyn Any>> = None;
        let get_mut = self.get_mut;
        let ok = self.src.update_value(|t| {
            let slot = get_mut(t);
            if capture {
                prior = Some(Rc::new(slot.clone()));
            }
            f(slot);
            if capture {
                after = Some(Rc::new(slot.clone()));
            }
        });
        if ok {
            self.src.bump_version();
            notify_change(
                self.live_path(),
                || {
                    let mut parts = Vec::new();
                    Source::<V>::components(self, &mut parts);
                    parts
                },
                self.label,
                Op::Set,
                prior,
                after,
            );
        }
    }

    /// Name this field inside a background transaction. Portable: what is queued is the path's
    /// components, which the main thread re-establishes on its own side when it announces.
    pub fn touch(self, tx: &mut TxPaths) {
        let mut parts = Vec::new();
        Source::<V>::components(self, &mut parts);
        tx.push((parts, self.label));
    }

    pub fn path(self) -> Path {
        self.live_path()
    }

    pub fn label(self) -> &'static str {
        self.label
    }
}

/// A field is itself a source, so `item.address().city()` works.
impl<S: Source<T>, T: 'static, V: 'static> Source<V> for Field<S, T, V> {
    // Nesting inherits the source's dynamism: a field of a slot's struct field still rides the
    // slot's current row.
    const DYNAMIC: bool = S::DYNAMIC;
    fn track_extra(self) {
        self.src.track_extra();
    }
    fn path(self) -> Path {
        self.live_path()
    }
    /// Interning happens here and only here: when a field is used as a parent, which is what
    /// nesting one struct inside another means.
    fn node(self) -> NodeId {
        intern(self.live_path())
    }
    fn components(self, out: &mut Vec<u64>) {
        self.src.components(out);
        out.push(self.part);
    }
    fn with_value_untracked<R>(self, f: impl FnOnce(Option<&V>) -> R) -> R {
        self.with_untracked(f)
    }
    fn update_value(self, f: impl FnOnce(&mut V)) -> bool {
        let get_mut = self.get_mut;
        self.src.update_value(|t| f(get_mut(t)))
    }
    fn bump_version(self) {
        self.src.bump_version();
    }
}

/// A field is a two-way binding: every control takes one, unchanged.
impl<S: Source<T>, T: 'static, V: Clone + Default + 'static> Binding<V> for Field<S, T, V> {
    fn read(&self) -> V {
        self.with(|v| v.cloned().unwrap_or_default())
    }
    fn peek(&self) -> V {
        self.with_untracked(|v| v.cloned().unwrap_or_default())
    }
    fn write(&self, v: V) {
        self.update(move |slot| *slot = v);
    }
    fn write_preview(&self, v: V) {
        Field::write_preview(*self, v);
    }
    fn write_commit(&self, v: V) {
        Field::write_commit(*self, v);
    }
    fn end_preview(&self) {
        Field::end_preview(*self);
    }
}

// ---------------------------------------------------------------------------
// Conversions
// ---------------------------------------------------------------------------

/// A converted view of a field: an ISO string as a date, `#RRGGBB` as a color, an index into a
/// table as the value it names. `Copy`, and still a binding, so it goes straight into a control.
pub struct Mapped<F, V: 'static, U: 'static> {
    inner: F,
    to: fn(&V) -> U,
    from: fn(&U) -> V,
    /// The mapped-over field's own label, so a converted write still names its column in the
    /// change log (a literal "mapped" would be invisible to the SQL fold).
    label: &'static str,
}

impl<F: Copy, V, U> Clone for Mapped<F, V, U> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<F: Copy, V, U> Copy for Mapped<F, V, U> {}

impl<S: Source<T>, T: 'static, V: 'static> Field<S, T, V> {
    /// Read this field through `to`, write it back through `from`. Both are fn pointers, so the
    /// result stays `Copy`.
    pub fn map<U: 'static>(self, to: fn(&V) -> U, from: fn(&U) -> V) -> Mapped<Self, V, U> {
        Mapped {
            inner: self,
            to,
            from,
            label: self.label,
        }
    }
}

/// The missing case converts the stored type's default rather than requiring the UI type to have
/// one: a `Color` has no `Default`, and asking every converted type for one would be a tax paid
/// by every caller for a case only a deleted row reaches.
impl<F: Source<V>, V: Clone + Default + 'static, U: Clone + 'static> Binding<U>
    for Mapped<F, V, U>
{
    fn read(&self) -> U {
        self.inner.track_extra();
        track(self.inner.path());
        self.peek()
    }
    fn peek(&self) -> U {
        self.inner.with_value_untracked(|v| match v {
            Some(v) => (self.to)(v),
            None => (self.to)(&V::default()),
        })
    }
    fn write_preview(&self, u: U) {
        let v = (self.from)(&u);
        let inner = self.inner;
        let mut parts = Vec::new();
        inner.components(&mut parts);
        PREVIEWS.with(|p| {
            p.borrow_mut().entry(parts).or_insert_with(|| {
                Rc::new(inner.with_value_untracked(|s| s.cloned().unwrap_or_default()))
            });
        });
        PREVIEW_WRITE.with(|f| f.set(true));
        let ok = inner.update_value(|slot| *slot = v);
        if ok {
            inner.bump_version();
            notify_change(inner.path(), Vec::new, self.label, Op::Set, None, None);
        }
        PREVIEW_WRITE.with(|f| f.set(false));
    }
    fn end_preview(&self) {
        let mut parts = Vec::new();
        self.inner.components(&mut parts);
        PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
    }
    fn write_commit(&self, u: U) {
        let inner = self.inner;
        let mut parts = Vec::new();
        inner.components(&mut parts);
        let open = PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
        match open {
            None => self.write(u),
            Some(prior) => {
                let v = (self.from)(&u);
                PREVIEW_WRITE.with(|f| f.set(true));
                let ok = inner.update_value(|slot| *slot = v);
                PREVIEW_WRITE.with(|f| f.set(false));
                if ok {
                    inner.bump_version();
                    let after: Rc<dyn Any> =
                        Rc::new(inner.with_value_untracked(|s| s.cloned().unwrap_or_default()));
                    notify_change(
                        inner.path(),
                        || parts,
                        self.label,
                        Op::Set,
                        Some(prior),
                        Some(after),
                    );
                }
            }
        }
    }
    fn write(&self, u: U) {
        let v = (self.from)(&u);
        let inner = self.inner;
        let capture = values_wanted();
        let mut prior: Option<Rc<dyn Any>> = None;
        let mut after: Option<Rc<dyn Any>> = None;
        let ok = inner.update_value(|slot| {
            if capture {
                prior = Some(Rc::new(slot.clone()));
            }
            *slot = v;
            if capture {
                after = Some(Rc::new(slot.clone()));
            }
        });
        if ok {
            inner.bump_version();
            notify_change(
                inner.path(),
                || {
                    let mut parts = Vec::new();
                    inner.components(&mut parts);
                    parts
                },
                self.label,
                Op::Set,
                prior,
                after,
            );
        }
    }
}

impl<F: Source<V> + Copy, V: 'static> Mapped<F, V, usize> {
    /// `usize` as the `f64` a slider speaks: the adapter every numeric control needs somewhere.
    pub fn map_to_f64(self) -> Numeric<Self> {
        Numeric { inner: self }
    }
}

/// `usize` ⇄ `f64`.
pub struct Numeric<M> {
    inner: M,
}

#[expect(
    clippy::expl_impl_clone_on_copy,
    reason = "a derive would widen `Clone` to non-`Copy` bindings; this keeps the public bounds"
)]
impl<M: Copy> Clone for Numeric<M> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<M: Copy> Copy for Numeric<M> {}

impl<M: Binding<usize> + Copy + 'static> Binding<f64> for Numeric<M> {
    fn read(&self) -> f64 {
        self.inner.read() as f64
    }
    fn peek(&self) -> f64 {
        self.inner.peek() as f64
    }
    fn write(&self, v: f64) {
        self.inner.write(v.round().max(0.0) as usize);
    }
}

// ---------------------------------------------------------------------------
// Preview sessions (docs/model.md): the write-side of ValueChanged / ValueCommitted
// ---------------------------------------------------------------------------

impl<S: Source<T>, T: 'static, V: Clone + Default + 'static> Field<S, T, V> {
    /// A live write: the value lands and this field's readers wake (a label tracking a
    /// dragged slider follows), but no change record is born, so autosave, the undo stack and
    /// every sink stay quiet. The first preview since the last commit captures the
    /// pre-session value; [`Field::write_commit`] turns the whole gesture into one record.
    pub fn write_preview(self, v: V) {
        let mut parts = Vec::new();
        Source::<V>::components(self, &mut parts);
        PREVIEWS.with(|p| {
            p.borrow_mut().entry(parts).or_insert_with(|| {
                Rc::new(self.with_untracked(|s| s.cloned().unwrap_or_default()))
            });
        });
        PREVIEW_WRITE.with(|f| f.set(true));
        self.update(move |slot| *slot = v);
        PREVIEW_WRITE.with(|f| f.set(false));
    }

    /// The settled value that ends a preview sequence: applies `v`, then announces one change
    /// whose prior is the pre-session value, so sixty thumb positions become one record, one
    /// undo unit, one UPDATE. Without an open session this is a plain [`Binding::write`].
    pub fn write_commit(self, v: V) {
        let mut parts = Vec::new();
        Source::<V>::components(self, &mut parts);
        let open = PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
        // A session whose row was deleted meanwhile (a field torn down with its row) ends
        // here with nothing to record: there is no value left for the change to describe.
        let open = open.filter(|_| self.with_untracked(|s| s.is_some()));
        match open {
            None => self.update(move |slot| *slot = v),
            Some(prior) => {
                PREVIEW_WRITE.with(|f| f.set(true));
                self.update(move |slot| *slot = v);
                PREVIEW_WRITE.with(|f| f.set(false));
                let after: Rc<dyn Any> =
                    Rc::new(self.with_untracked(|s| s.cloned().unwrap_or_default()));
                notify_change(
                    self.live_path(),
                    || parts,
                    self.label,
                    Op::Set,
                    Some(prior),
                    Some(after),
                );
            }
        }
    }

    /// Close an open preview session without a record (`Binding::end_preview`): an app write
    /// replaced what the gesture previewed and recorded its own change, so the session's
    /// pre-gesture value no longer describes the field. The next preview captures the current
    /// value as its prior. Without an open session this does nothing.
    pub fn end_preview(self) {
        let mut parts = Vec::new();
        Source::<V>::components(self, &mut parts);
        PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
    }

    /// The explicit session handle, for custom pieces and programmatic gestures; bindings
    /// drive [`Field::write_preview`]/[`Field::write_commit`] on their own.
    pub fn session(self) -> FieldSession<S, T, V> {
        FieldSession { field: self }
    }
}

/// An explicit preview session over one field (see [`Field::session`]). `Copy`, like the
/// field itself.
pub struct FieldSession<S: 'static, T: 'static, V: 'static> {
    field: Field<S, T, V>,
}

impl<S: Copy, T, V> Clone for FieldSession<S, T, V> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<S: Copy, T, V> Copy for FieldSession<S, T, V> {}

impl<S: Source<T>, T: 'static, V: Clone + Default + 'static> FieldSession<S, T, V> {
    pub fn preview(self, v: V) {
        self.field.write_preview(v);
    }
    /// Seal the session at the current value.
    pub fn commit(self) {
        let v = self
            .field
            .with_untracked(|s| s.cloned().unwrap_or_default());
        self.field.write_commit(v);
    }
    /// Abandon the session: the pre-session value comes back (readers wake), and no record of
    /// any of it exists (what Escape does).
    pub fn cancel(self) {
        let mut parts = Vec::new();
        Source::<V>::components(self.field, &mut parts);
        if let Some(prior) = PREVIEWS.with(|p| p.borrow_mut().remove(&parts))
            && let Ok(prior) = prior.downcast::<V>()
        {
            self.field.write_preview((*prior).clone());
            // The restore write re-opened a session pointing at itself; drop it.
            let mut parts = Vec::new();
            Source::<V>::components(self.field, &mut parts);
            PREVIEWS.with(|p| p.borrow_mut().remove(&parts));
        }
    }
}

// ---------------------------------------------------------------------------
// Undo (docs/model.md): the change log read backward
// ---------------------------------------------------------------------------

/// Write one captured field value back into a struct, by label. Implemented by
/// `#[derive(Observable)]`; this trait is how a type-erased undo unit re-enters the
/// store it came from.
pub trait ApplyField {
    fn apply_field(&mut self, label: &str, value: &dyn Any) -> bool;

    /// The field's current value, cloned and type-erased; `None` for an unknown label. The
    /// derive implements it; [`Store::write_field`] captures priors through it.
    fn read_field(&self, label: &str) -> Option<Rc<dyn Any>> {
        let _ = label;
        None
    }
}

type SetFieldFn = Rc<dyn Fn(u64, &'static str, &Rc<dyn Any>) -> bool>;
type InsertRowFn = Rc<dyn Fn(u64, &Rc<dyn Any>, Option<usize>) -> bool>;

struct StoreOps {
    set_field: SetFieldFn,
    insert_row: InsertRowFn,
    remove_row: Rc<dyn Fn(u64) -> bool>,
    move_row: Rc<dyn Fn(u64, usize) -> bool>,
}

#[derive(Clone)]
struct UndoUnit {
    label: &'static str,
    changes: Vec<Change>,
    /// Transient UI state as of this unit's seal ([`UndoStack::set_transient_context`]);
    /// `None` for a unit sealed with no hook installed. Never persisted.
    context: Option<Rc<dyn Any>>,
}

/// A restore closure over one captured snapshot ([`UndoStack::set_transient_context`]).
type ContextRestore = Rc<dyn Fn(&dyn Any)>;

/// The app's transient-context hook ([`UndoStack::set_transient_context`]).
struct ContextHook {
    capture: Rc<dyn Fn() -> Rc<dyn Any>>,
    restore: ContextRestore,
    /// The state before any unit: what undoing the whole history restores.
    base: Rc<dyn Any>,
}

#[derive(Clone, Copy, PartialEq)]
enum Replay {
    No,
    Undoing,
    Redoing,
}

struct UndoInner {
    levels: usize,
    undo: RefCell<std::collections::VecDeque<UndoUnit>>,
    redo: RefCell<Vec<UndoUnit>>,
    open: RefCell<Vec<Change>>,
    group_label: Cell<Option<&'static str>>,
    grouping: Cell<usize>,
    replaying: Cell<Replay>,
    ops: RefCell<HashMap<u64, StoreOps>>,
    can_undo: day_reactive::Signal<bool>,
    can_redo: day_reactive::Signal<bool>,
    undo_label: day_reactive::Signal<String>,
    redo_label: day_reactive::Signal<String>,
    resolver: RefCell<Rc<dyn Fn(&'static str) -> String>>,
    sink: Cell<Option<ChangeSinkId>>,
    context: RefCell<Option<ContextHook>>,
}

/// One undo history over the stores it [`UndoStack::watch`]es: units are turns (everything one
/// event's dispatch changed), inverted, not snapshots. Enabling it turns on standing value
/// capture; drop the stack and the capture stops.
#[derive(Clone)]
pub struct UndoStack {
    inner: Rc<UndoInner>,
}

/// Queue-confined history checkpoint for a persistence transaction. Restore it only after
/// rolling back the corresponding model changes. It does not snapshot the models themselves.
pub struct UndoCheckpoint {
    undo: std::collections::VecDeque<UndoUnit>,
    redo: Vec<UndoUnit>,
    open: Vec<Change>,
}

/// RAII lifetime of an undo group; dropping the last nested guard seals its changes.
#[must_use = "keep the group alive until the interaction finishes"]
pub struct UndoGroup {
    stack: UndoStack,
}

impl Drop for UndoGroup {
    fn drop(&mut self) {
        let depth = self.stack.inner.grouping.get() - 1;
        self.stack.inner.grouping.set(depth);
        if depth == 0 {
            self.stack.seal();
            // Empty groups must not lend their label to the next unrelated edit.
            self.stack.inner.group_label.set(None);
        }
    }
}

impl UndoStack {
    /// A stack holding at most `levels` units: the bound on what history keeps in RAM.
    #[must_use]
    pub fn new(levels: usize) -> UndoStack {
        let (can_undo, can_redo, undo_label, redo_label) =
            day_reactive::Scope::detached().enter(|| {
                (
                    day_reactive::Signal::new(false),
                    day_reactive::Signal::new(false),
                    day_reactive::Signal::new(String::new()),
                    day_reactive::Signal::new(String::new()),
                )
            });
        let stack = UndoStack {
            inner: Rc::new(UndoInner {
                levels: levels.max(1),
                undo: RefCell::new(std::collections::VecDeque::new()),
                redo: RefCell::new(Vec::new()),
                open: RefCell::new(Vec::new()),
                group_label: Cell::new(None),
                grouping: Cell::new(0),
                replaying: Cell::new(Replay::No),
                ops: RefCell::new(HashMap::new()),
                can_undo,
                can_redo,
                undo_label,
                redo_label,
                resolver: RefCell::new(Rc::new(|label: &'static str| {
                    let mut s: String = label.replace(['_', '-'], " ");
                    if let Some(first) = s.get_mut(0..1) {
                        first.make_ascii_uppercase();
                    }
                    s
                })),
                sink: Cell::new(None),
                context: RefCell::new(None),
            }),
        };
        want_values_standing(true);
        let weak = Rc::downgrade(&stack.inner);
        let sink = install_change_sink(move |change| {
            if let Some(inner) = weak.upgrade() {
                UndoStack { inner }.capture(change);
            }
        });
        stack.inner.sink.set(Some(sink));
        let weak = Rc::downgrade(&stack.inner);
        day_reactive::on_turn_end(move || {
            if let Some(inner) = weak.upgrade() {
                let stack = UndoStack { inner };
                if stack.inner.grouping.get() == 0 {
                    stack.seal();
                }
            }
        });
        stack
    }

    /// Bring one store under this history. Only watched stores are captured; a change in any
    /// other store passes the stack by.
    pub fn watch<T: ApplyField + Identified + Clone + 'static>(&self, store: Store<Keyed<T>>) {
        let ops = StoreOps {
            set_field: {
                Rc::new(move |key: u64, label: &'static str, value: &Rc<dyn Any>| {
                    let elem = store.elem(key);
                    let mut applied = false;
                    let ok = elem.update_value(|row| {
                        applied = row.apply_field(label, value.as_ref());
                    });
                    if ok && applied {
                        elem.bump_version();
                        announce_op(&[store.store_id(), key, field_id(label)], label, Op::Set);
                    }
                    ok && applied
                })
            },
            insert_row: {
                Rc::new(move |key: u64, row: &Rc<dyn Any>, at: Option<usize>| {
                    let Some(row) = row.downcast_ref::<T>() else {
                        return false;
                    };
                    let row = row.clone();
                    store.restructure("undo", Op::Insert, key, move |k| match at {
                        Some(at) if at < k.len() => k.items_mut().insert(at, row),
                        _ => k.push(row),
                    });
                    true
                })
            },
            remove_row: {
                Rc::new(move |key: u64| {
                    store.restructure("undo", Op::Delete, key, move |k| {
                        k.remove(key);
                    });
                    true
                })
            },
            move_row: {
                Rc::new(move |key: u64, to: usize| {
                    let from =
                        store.with_untracked(|k| k.items().iter().position(|t| t.handle() == key));
                    from.is_some_and(|from| store.move_row(from, to))
                })
            },
        };
        self.inner.ops.borrow_mut().insert(store.store_id(), ops);
    }

    fn capture(&self, change: &Change) {
        if self.inner.replaying.get() != Replay::No {
            return;
        }
        // Another author's writes (an importer, a sync engine) are not the user's history:
        // undoing them from the user's stack would revert work the user never did. Their tag
        // is exactly the evidence this decision needs.
        if change.author.is_some() {
            return;
        }
        let Some(&store) = change.components.first() else {
            return;
        };
        if !self.inner.ops.borrow().contains_key(&store) {
            return;
        }
        let Some(&key) = change.components.get(1) else {
            // A wholesale rewrite: history no longer describes reachable states.
            self.clear();
            return;
        };
        if key == STRUCTURE {
            return;
        }
        if change.op == Op::Set && change.components.len() >= 3 && change.prior.is_none() {
            // A value-less field Set (an author's announce) cannot invert; skip it.
            return;
        }
        self.inner.open.borrow_mut().push(change.clone());
    }

    /// Close the open unit (turn end does this; a group does it once at its end).
    fn seal(&self) {
        let changes = std::mem::take(&mut *self.inner.open.borrow_mut());
        if changes.is_empty() {
            return;
        }
        let label = self
            .inner
            .group_label
            .take()
            .unwrap_or_else(|| changes.first().map_or("", |c| c.label));
        // The unit's transient UI state is the state at seal, the end of the turn (or group),
        // after any selection writes the same event made. Selection changes between units are
        // not captured anywhere: they are not history.
        let context = self.inner.context.borrow().as_ref().map(|h| (h.capture)());
        let mut undo = self.inner.undo.borrow_mut();
        undo.push_back(UndoUnit {
            label,
            changes,
            context,
        });
        while undo.len() > self.inner.levels {
            undo.pop_front();
        }
        drop(undo);
        // A new user unit forks history: redo is gone.
        self.inner.redo.borrow_mut().clear();
        self.refresh();
    }

    /// Everything `f` changes lands as one unit named `label`: a multi-field commit, an
    /// inspector applying twelve properties.
    pub fn grouped(&self, label: &'static str, f: impl FnOnce()) {
        let _group = self.begin_group(label);
        f();
    }

    /// Keep one undo unit open across event turns, until the returned guard is dropped.
    /// Nested groups join the outer unit and retain its label. Keep the guard only for the
    /// duration of the interaction: all watched edits in that interval belong to the group.
    pub fn begin_group(&self, label: &'static str) -> UndoGroup {
        if self.inner.grouping.get() == 0 {
            self.seal();
            self.inner.group_label.set(Some(label));
        }
        self.inner.grouping.set(self.inner.grouping.get() + 1);
        UndoGroup {
            stack: self.clone(),
        }
    }

    /// Preserve history before an atomic persistence operation. Failed commits must restore
    /// both the database/cache and this checkpoint, including an existing redo branch.
    #[must_use]
    pub fn checkpoint(&self) -> UndoCheckpoint {
        UndoCheckpoint {
            undo: self.inner.undo.borrow().clone(),
            redo: self.inner.redo.borrow().clone(),
            open: self.inner.open.borrow().clone(),
        }
    }

    pub fn restore_checkpoint(&self, checkpoint: UndoCheckpoint) {
        *self.inner.undo.borrow_mut() = checkpoint.undo;
        *self.inner.redo.borrow_mut() = checkpoint.redo;
        *self.inner.open.borrow_mut() = checkpoint.open;
        self.refresh();
    }

    #[must_use]
    pub fn can_undo(&self) -> day_reactive::Signal<bool> {
        self.inner.can_undo
    }
    #[must_use]
    pub fn can_redo(&self) -> day_reactive::Signal<bool> {
        self.inner.can_redo
    }
    /// The next undo unit's display label ("Name", or whatever the resolver makes of it),
    /// empty when there is nothing to undo. What a menu title interpolates.
    #[must_use]
    pub fn undo_label(&self) -> day_reactive::Signal<String> {
        self.inner.undo_label
    }
    #[must_use]
    pub fn redo_label(&self) -> day_reactive::Signal<String> {
        self.inner.redo_label
    }

    /// How unit labels become display text (Fluent lookup, capitalization); the default
    /// capitalizes the raw label.
    pub fn set_label_resolver(&self, f: impl Fn(&'static str) -> String + 'static) {
        *self.inner.resolver.borrow_mut() = Rc::new(f);
        self.refresh();
    }

    /// Ride transient UI state (a selection, a scroll position) along the history: captured,
    /// never persisted (docs/model.md "Transient UI state").
    ///
    /// `capture` runs as each unit seals, so a snapshot is the UI state at that point of
    /// document history, including any selection writes the same turn made. Undo restores the
    /// snapshot of the unit history lands on: the previous unit's, or the base snapshot
    /// (taken here, at install) once the last unit is undone; redo restores the redone unit's
    /// own. UI changes between units restore nowhere: they are not history, which is what
    /// makes "select A, move it, select B, move it, undo" land on A (the state as it stood
    /// when A's move sealed) rather than on B.
    ///
    /// `restore` must not write a watched store (that would fork history from inside a
    /// replay); write plain signals. A unit sealed before this call carries no snapshot and
    /// restores nothing.
    pub fn set_transient_context(
        &self,
        capture: impl Fn() -> Rc<dyn Any> + 'static,
        restore: impl Fn(&dyn Any) + 'static,
    ) {
        let base = capture();
        *self.inner.context.borrow_mut() = Some(ContextHook {
            capture: Rc::new(capture),
            restore: Rc::new(restore),
            base,
        });
    }

    /// Restore the snapshot history just landed on: the top unit's snapshot slot. A unit that
    /// recorded nothing restores nothing; the empty stack restores the base. Every borrow is
    /// released before the restore closure runs: it is app code.
    fn restore_context(&self) {
        let (target, restore) = {
            let hook = self.inner.context.borrow();
            let Some(h) = hook.as_ref() else { return };
            let target = match self.inner.undo.borrow().back() {
                Some(unit) => unit.context.clone(),
                None => Some(h.base.clone()),
            };
            (target, h.restore.clone())
        };
        if let Some(ctx) = target {
            restore(&*ctx);
        }
    }

    pub fn undo(&self) -> bool {
        // Never replay a partially completed interaction under its live gesture state.
        if self.inner.grouping.get() > 0 {
            return false;
        }
        self.seal();
        let Some(unit) = self.inner.undo.borrow_mut().pop_back() else {
            return false;
        };
        self.inner.replaying.set(Replay::Undoing);
        with_author("undo", || {
            day_reactive::batch(|| {
                for ch in unit.changes.iter().rev() {
                    self.apply(ch, true);
                }
            });
        });
        self.inner.replaying.set(Replay::No);
        self.inner.redo.borrow_mut().push(unit);
        // History landed on the previous unit's point: restore its transient state (base
        // when the stack just emptied). After the replay flag drops: restores write plain
        // signals, never watched stores.
        self.restore_context();
        self.refresh();
        true
    }

    pub fn redo(&self) -> bool {
        // Never replay a partially completed interaction under its live gesture state.
        if self.inner.grouping.get() > 0 {
            return false;
        }
        let Some(unit) = self.inner.redo.borrow_mut().pop() else {
            return false;
        };
        self.inner.replaying.set(Replay::Redoing);
        with_author("redo", || {
            day_reactive::batch(|| {
                for ch in &unit.changes {
                    self.apply(ch, false);
                }
            });
        });
        self.inner.replaying.set(Replay::No);
        self.inner.undo.borrow_mut().push_back(unit);
        // History landed back on the redone unit: restore its own transient state.
        self.restore_context();
        self.refresh();
        true
    }

    /// Drop all history (a schema migration, a wholesale reload).
    pub fn clear(&self) {
        self.inner.undo.borrow_mut().clear();
        self.inner.redo.borrow_mut().clear();
        self.inner.open.borrow_mut().clear();
        self.refresh();
    }

    fn apply(&self, ch: &Change, invert: bool) {
        let (Some(&store), Some(&key)) = (ch.components.first(), ch.components.get(1)) else {
            return;
        };
        let ops = self.inner.ops.borrow();
        let Some(ops) = ops.get(&store) else {
            return;
        };
        let effective = if invert {
            match ch.op {
                Op::Set => Op::Set,
                Op::Insert => Op::Delete,
                Op::Delete => Op::Insert,
                Op::Move => Op::Move,
            }
        } else {
            ch.op
        };
        let index = |v: &Option<Rc<dyn Any>>| {
            v.as_deref()
                .and_then(|v| v.downcast_ref::<usize>().copied())
        };
        match effective {
            Op::Set => {
                let v = if invert { &ch.prior } else { &ch.value };
                if let Some(v) = v {
                    (ops.set_field)(key, ch.label, v);
                }
            }
            Op::Insert => {
                // Undoing a Delete puts the row back where it was; redoing an Insert, where it went.
                let (row, at) = if invert {
                    (&ch.prior, index(&ch.value))
                } else {
                    (&ch.value, index(&ch.prior))
                };
                if let Some(row) = row {
                    (ops.insert_row)(key, row, at);
                }
            }
            Op::Delete => {
                (ops.remove_row)(key);
            }
            Op::Move => {
                let to = if invert { &ch.prior } else { &ch.value };
                if let Some(to) = index(to) {
                    (ops.move_row)(key, to);
                }
            }
        }
    }

    fn refresh(&self) {
        let resolver = self.inner.resolver.borrow().clone();
        let undo = self.inner.undo.borrow();
        self.inner.can_undo.set_if_changed(!undo.is_empty());
        self.inner
            .undo_label
            .set_if_changed(undo.back().map_or_default(|u| resolver(u.label)));
        drop(undo);
        let redo = self.inner.redo.borrow();
        self.inner.can_redo.set_if_changed(!redo.is_empty());
        self.inner
            .redo_label
            .set_if_changed(redo.last().map_or_default(|u| resolver(u.label)));
    }
}

impl Drop for UndoInner {
    fn drop(&mut self) {
        if let Some(sink) = self.sink.take() {
            remove_change_sink(sink);
        }
        // Balance the standing want-values this stack held (best-effort at thread teardown).
        let _ = WANT_VALUES_STANDING.try_with(|w| w.set(w.get().saturating_sub(1)));
    }
}