tilo-resource 0.5.1

The Tilo resource layer: typed, hierarchical app resources.
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
//! Items with identity: [`Id`] and the ordered, keyed [`Collection`].

use std::fmt;
use tilo_sort::CompactSort as _;

use automerge::transaction::Transactable;
use automerge::{ObjId, ObjType, ReadDoc, ScalarValue, Value};

use std::collections::{HashMap, HashSet};
use std::sync::{Arc, OnceLock};

use crate::action::ActionCx;
use crate::delta::{Delta, Touch};
use crate::model::LocatedAt as _;
use crate::model::{Doc, Model, ModelError, Slot, Stores, read_key};
use crate::order;
use crate::path::{EditOp, Segment, Settable};
use crate::table::{ModelOps, ModelTable};
use std::any::Any;

/// A stable identity for an item in a resource. Minted deterministically by
/// [`ActionCx::id`](crate::ActionCx::id), so replaying an action on another
/// replica mints the same id.
///
/// The default id is empty: an item that refers to no other yet.
#[derive(
    Clone,
    Debug,
    Default,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    serde::Serialize,
    serde::Deserialize,
)]
#[serde(transparent)]
pub struct Id(String);

impl Id {
    /// Adopt an id that was minted earlier (read from a document, a URL or an
    /// action argument).
    #[must_use]
    pub fn from_raw(raw: impl Into<String>) -> Self {
        Self(raw.into())
    }

    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for Id {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl From<&str> for Id {
    fn from(raw: &str) -> Self {
        Self(raw.to_owned())
    }
}

impl From<String> for Id {
    fn from(raw: String) -> Self {
        Self(raw)
    }
}

impl std::str::FromStr for Id {
    type Err = std::convert::Infallible;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(s.to_owned()))
    }
}

impl Settable for Id {}
impl Model for Id {
    const SCALAR: bool = true;
    crate::__own_table!(Id);
    fn value_schema() -> serde_json::Value {
        serde_json::json!({"type": "string"})
    }
    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
        let _ = types;
        crate::FieldType::Text
    }
    crate::model::leaf_paths!();
    #[inline(never)]
    fn to_json(&self) -> serde_json::Value {
        serde_json::Value::String(self.0.clone())
    }
    #[inline(never)]
    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
        match value {
            serde_json::Value::String(text) => Ok(Self(text.clone())),
            _ => Err(ModelError::shape("an id")),
        }
    }
    #[inline(never)]
    fn load(_: &Doc, value: &Value<'_>, _: &ObjId) -> Result<Self, ModelError> {
        match value {
            Value::Scalar(scalar) => match scalar.as_ref() {
                ScalarValue::Str(text) => Ok(Self(text.to_string())),
                _ => Err(ModelError::shape("an id")),
            },
            Value::Object(_) => Err(ModelError::shape("an id")),
        }
    }
    #[inline(never)]
    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
        slot.put_scalar(doc, ScalarValue::Str(self.0.as_str().into()))
    }
    fn fresh(&self, _: automerge::TextEncoding) -> crate::model::Fresh {
        crate::model::Fresh::scalar(ScalarValue::Str(self.0.as_str().into()))
    }
}

pub(crate) const ORDER: &str = "k";
pub const VALUE: &str = "v";

/// The keys from the document's root down to the map `obj`, as a model names its fields: an
/// item's id for each collection on the way, never the entry key its value is kept under (`issues/<issue>/comments`
/// for the comments of an issue). `None` where a list stands on the way.
pub fn path_to(doc: &impl ReadDoc, obj: &ObjId) -> Option<Vec<String>> {
    let mut path = Vec::new();
    for parent in doc.parents(obj).ok()? {
        match parent.prop {
            automerge::Prop::Map(key) if key == VALUE => {}
            automerge::Prop::Map(key) => path.push(key),
            automerge::Prop::Seq(_) => return None,
        }
    }
    path.reverse();
    Some(path)
}

/// An ordered collection of items addressed by [`Id`].
///
/// Stored as a map from id to `{ k: order key, v: value }`. Editing an item
/// writes only that item; a move rewrites one order key; concurrent inserts
/// from several members interleave deterministically; deleting an item
/// never disturbs another item's identity. This is the default container for
/// anything a user adds, reorders or removes.
///
/// A collection read from a document remembers each item's order key, so a
/// later change re-reads only the items it touched
/// ([`Model::refresh`]) instead of the whole collection.
///
/// Cloning a collection shares its items: a clone copies one pointer per
/// item, and an item is copied only when one of the collections sharing it
/// changes it. A view holding the state it was shown therefore costs the
/// next change one copied item, not a copy of every item.
#[derive(Debug)]
pub struct Collection<T> {
    items: Vec<Entry<T>>,
    /// Each id's position, built on the first lookup after the order
    /// changed, so finding an item by id is constant time.
    index: Index,
    membership: Membership,
    /// How to copy an item another collection still shares.
    copier: Copier<T>,
    /// Stored items that did not read, and why: left out of the items,
    /// kept in the document for their repair ([`Self::quarantined`]).
    quarantine: Vec<Quarantined>,
    /// A quarantined item was repaired or discarded since the collection
    /// was read: only a whole write stores that as a whole read and write
    /// would, keeping the stored order key or deleting what it never read.
    whole_write: bool,
}

/// A stored item of a [`Collection`] that does not read as its type, left
/// out of the collection rather than making the whole record unreadable.
///
/// It stays in the document as it is. It is repaired by pushing a whole
/// item under its id ([`Collection::push`]), which stores every field, or
/// removed with the remove-item edit (or [`Collection::discard`]); a
/// migration may rewrite it in place.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Quarantined {
    pub id: Id,
    /// Why it does not read, where in the item.
    pub reason: String,
}

impl<T: Clone> Clone for Collection<T> {
    fn clone(&self) -> Self {
        let copy: fn(&T) -> T = T::clone;
        // Sharing starts here, so from here on either side may need to copy.
        let _ = self.copier.0.set(copy);
        Self {
            items: self.items.clone(),
            index: self.index.clone(),
            membership: self.membership,
            copier: Copier(OnceLock::from(copy)),
            quarantine: self.quarantine.clone(),
            whole_write: self.whole_write,
        }
    }
}

/// How a collection copies an item it shares with a clone. Recorded by the
/// first clone: items are shared by cloning alone, and only a collection of
/// `Clone` items clones.
struct Copier<T>(OnceLock<fn(&T) -> T>);

impl<T> Default for Copier<T> {
    fn default() -> Self {
        Self(OnceLock::new())
    }
}

impl<T> fmt::Debug for Copier<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Copier")
    }
}

impl<T> Copier<T> {
    /// The item `item` holds, to change: copied first when another
    /// collection still shares it, so that one keeps seeing it unchanged.
    /// `None` only for a shared item with no copier, which cannot be.
    fn unshare<'a>(&self, item: &'a mut Arc<T>) -> Option<&'a mut T> {
        if Arc::get_mut(item).is_none()
            && let Some(copy) = self.0.get()
        {
            *item = Arc::new(copy(item));
        }
        Arc::get_mut(item)
    }

    /// The item `item` holds, taken out of the collection: copied when
    /// another collection still shares it.
    fn take(&self, item: Arc<T>) -> Option<T> {
        match Arc::try_unwrap(item) {
            Ok(item) => Some(item),
            Err(shared) => self.0.get().map(|copy| copy(&shared)),
        }
    }
}

/// Which ids a [`Collection`] holds, in which order, as one value to
/// compare: two collections (or one collection at two times) with the same
/// membership hold the same ids in the same order. A list view keeps it to
/// tell that a change left its rows as they were without comparing every
/// id. Different memberships say nothing: the ids may still be the same.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Membership(u64);

impl Membership {
    /// The membership of every empty collection never changed since.
    const EMPTY: Self = Self(0);

    /// A membership no collection had before.
    fn fresh() -> Self {
        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
        Self(NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))
    }
}

/// Shared between clones until one of them moves an item.
#[derive(Clone, Default)]
struct Index(OnceLock<Arc<HashMap<Id, usize>>>);

impl fmt::Debug for Index {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Index")
    }
}

impl Index {
    fn get<T>(&self, items: &[Entry<T>], id: &Id) -> Option<usize> {
        if let Some(index) = self.0.get() {
            return index.get(id).copied();
        }
        self.build(
            items.len(),
            &|position| items.get(position).map(|entry| &entry.id),
            id,
        )
    }

    /// Build the index of `count` ids (`id_at` each), then find `id`.
    #[inline(never)]
    fn build<'a>(
        &self,
        count: usize,
        id_at: &dyn Fn(usize) -> Option<&'a Id>,
        id: &Id,
    ) -> Option<usize> {
        let mut index = HashMap::with_capacity(count);
        for position in 0..count {
            if let Some(entry) = id_at(position) {
                index.insert(entry.clone(), position);
            }
        }
        let _ = self.0.set(Arc::new(index));
        self.0.get()?.get(id).copied()
    }

    fn reset(&mut self) {
        self.0 = OnceLock::new();
    }

    /// Note an item appended at `position`, keeping a built index.
    fn appended(&mut self, id: &Id, position: usize) {
        let Some(index) = self.0.get_mut() else {
            return;
        };
        match Arc::get_mut(index) {
            Some(index) => {
                index.insert(id.clone(), position);
            }
            // A clone still looks items up in it: build a new one when next
            // asked rather than copy this one now.
            None => self.reset(),
        }
    }
}

#[derive(Debug)]
struct Entry<T> {
    id: Id,
    /// The stored order key, when this entry was read from a document and
    /// has not been moved since.
    key: Option<String>,
    item: Arc<T>,
}

impl<T> Clone for Entry<T> {
    fn clone(&self) -> Self {
        Self {
            id: self.id.clone(),
            key: self.key.clone(),
            item: Arc::clone(&self.item),
        }
    }
}

impl<T> Entry<T> {
    fn new(id: Id, item: T) -> Self {
        Self {
            id,
            key: None,
            item: Arc::new(item),
        }
    }
}

impl<T: PartialEq> PartialEq for Collection<T> {
    /// Equal items in equal order; where each item's order key came from is
    /// bookkeeping, not content. An item two clones still share is the same
    /// value and is not compared field by field.
    fn eq(&self, other: &Self) -> bool {
        if self.items.len() != other.items.len() {
            return false;
        }
        for at in 0..self.items.len() {
            match (self.items.get(at), other.items.get(at)) {
                (Some(a), Some(b))
                    if a.id == b.id && (Arc::ptr_eq(&a.item, &b.item) || a.item == b.item) => {}
                _ => return false,
            }
        }
        true
    }
}

impl<T> Default for Collection<T> {
    fn default() -> Self {
        Self {
            items: Vec::new(),
            index: Index::default(),
            membership: Membership::EMPTY,
            copier: Copier::default(),
            quarantine: Vec::new(),
            whole_write: false,
        }
    }
}

impl<T> Collection<T> {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    pub fn len(&self) -> usize {
        self.items.len()
    }

    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Which ids the collection holds, in which order ([`Membership`]).
    /// Editing an item keeps it; adding, removing or moving one changes it.
    pub fn membership(&self) -> Membership {
        self.membership
    }

    /// The ids or their order may have changed.
    fn moved(&mut self) {
        self.membership = Membership::fresh();
    }

    /// Items in collection order.
    #[allow(
        clippy::iter_without_into_iter,
        reason = "a collection iterates its items by id; `for` over it would hide which"
    )]
    pub fn iter(&self) -> Iter<'_, T> {
        Iter(self.items.iter())
    }

    /// The item at `position` in collection order.
    pub fn at(&self, position: usize) -> Option<(&Id, &T)> {
        self.items
            .get(position)
            .map(|entry| (&entry.id, &*entry.item))
    }

    #[allow(
        clippy::iter_without_into_iter,
        reason = "a collection iterates its items by id; `for` over it would hide which"
    )]
    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
        IterMut {
            entries: self.items.iter_mut(),
            copier: &self.copier,
        }
    }

    pub fn values(&self) -> Values<'_, T> {
        Values(self.items.iter())
    }

    pub fn ids(&self) -> Ids<'_, T> {
        Ids(self.items.iter())
    }

    pub fn contains(&self, id: &Id) -> bool {
        self.position(id).is_some()
    }

    pub fn position(&self, id: &Id) -> Option<usize> {
        self.index.get(&self.items, id)
    }

    pub fn get(&self, id: &Id) -> Option<&T> {
        let position = self.position(id)?;
        self.items.get(position).map(|entry| &*entry.item)
    }

    /// The item `id`, to change. Copies it first when a clone of this
    /// collection still shares it; no other item is copied.
    pub fn get_mut(&mut self, id: &Id) -> Option<&mut T> {
        let position = self.position(id)?;
        let entry = self.items.get_mut(position)?;
        self.copier.unshare(&mut entry.item)
    }

    /// The stored items that did not read, each with why: the view shows
    /// the rest, and these are repaired by pushing a whole item under the
    /// id or removed ([`Quarantined`]).
    #[must_use]
    pub fn quarantined(&self) -> &[Quarantined] {
        &self.quarantine
    }

    /// Forget the quarantined item `id`: the next write deletes it from the
    /// document, as it deletes any item no longer in the collection.
    /// Whether it was quarantined.
    pub fn discard(&mut self, id: &Id) -> bool {
        forget_quarantined(&mut self.quarantine, &mut self.whole_write, id)
    }

    /// Stop holding the quarantined item `id`, as an item takes its place.
    fn repaired(&mut self, id: &Id) {
        forget_quarantined(&mut self.quarantine, &mut self.whole_write, id);
    }

    /// Append an item. Returns its id for chaining. An id already present
    /// is replaced in place; a quarantined one is repaired by it.
    pub fn push(&mut self, id: Id, item: T) -> Id {
        self.push_shared(id, Arc::new(item))
    }

    /// [`Self::push`] of an item already shared.
    fn push_shared(&mut self, id: Id, item: Arc<T>) -> Id {
        self.repaired(&id);
        if let Some(position) = self.position(&id)
            && let Some(existing) = self.items.get_mut(position)
        {
            existing.item = item;
            return id;
        }
        self.items.push(Entry {
            id: id.clone(),
            key: None,
            item,
        });
        let position = self.items.len().saturating_sub(1);
        self.index.appended(&id, position);
        self.moved();
        id
    }

    /// Insert an item at `index` (clamped to the end). An id already present
    /// is moved there.
    pub fn insert(&mut self, index: usize, id: Id, item: T) -> Id {
        self.repaired(&id);
        self.remove(&id);
        let index = index.min(self.items.len());
        self.items.insert(index, Entry::new(id.clone(), item));
        self.index.reset();
        self.moved();
        id
    }

    pub fn remove(&mut self, id: &Id) -> Option<T> {
        let index = self.position(id)?;
        self.index.reset();
        self.moved();
        self.copier.take(self.items.remove(index).item)
    }

    /// Move an item to `index` (clamped to the end). Returns whether it exists.
    pub fn move_to(&mut self, id: &Id, index: usize) -> bool {
        let Some(from) = self.position(id) else {
            return false;
        };
        let mut entry = self.items.remove(from);
        entry.key = None;
        let index = index.min(self.items.len());
        self.items.insert(index, entry);
        self.index.reset();
        self.moved();
        true
    }

    pub fn retain(&mut self, mut keep: impl FnMut(&Id, &T) -> bool) {
        let before = self.items.len();
        self.items.retain(|entry| keep(&entry.id, &*entry.item));
        // Retaining only removes: the same length is the same ids.
        if self.items.len() != before {
            self.index.reset();
            self.moved();
        }
    }

    pub fn sort_by(&mut self, mut compare: impl FnMut(&T, &T) -> std::cmp::Ordering) {
        crate::sort::sort_by(&mut self.items, |a, b| compare(&*a.item, &*b.item));
        for entry in &mut self.items {
            entry.key = None;
        }
        self.index.reset();
        self.moved();
    }
}

// Named iterators rather than closures over entries: one small set of
// methods per item type, whatever a caller chains onto them.

/// The items of a [`Collection`] with their ids, in order.
pub struct Iter<'a, T>(std::slice::Iter<'a, Entry<T>>);
/// The items of a [`Collection`], to change, with their ids. Each item a
/// clone of the collection still shares is copied as it is reached.
pub struct IterMut<'a, T> {
    entries: std::slice::IterMut<'a, Entry<T>>,
    copier: &'a Copier<T>,
}
/// The items of a [`Collection`], in order.
pub struct Values<'a, T>(std::slice::Iter<'a, Entry<T>>);
/// The ids of a [`Collection`], in order.
pub struct Ids<'a, T>(std::slice::Iter<'a, Entry<T>>);

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = (&'a Id, &'a T);
    fn next(&mut self) -> Option<Self::Item> {
        let entry = self.0.next()?;
        Some((&entry.id, &*entry.item))
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
    fn last(mut self) -> Option<Self::Item> {
        DoubleEndedIterator::next_back(&mut self)
    }
}
impl<T> DoubleEndedIterator for Iter<'_, T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        let entry = self.0.next_back()?;
        Some((&entry.id, &*entry.item))
    }
}
impl<T> ExactSizeIterator for Iter<'_, T> {}

impl<'a, T> Iterator for IterMut<'a, T> {
    type Item = (&'a Id, &'a mut T);
    fn next(&mut self) -> Option<Self::Item> {
        // An item is skipped only if it could not be unshared, which an
        // item shared by cloning always can.
        for entry in self.entries.by_ref() {
            if let Some(item) = self.copier.unshare(&mut entry.item) {
                return Some((&entry.id, item));
            }
        }
        None
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.entries.size_hint()
    }
}

impl<'a, T> Iterator for Values<'a, T> {
    type Item = &'a T;
    fn next(&mut self) -> Option<Self::Item> {
        Some(&*self.0.next()?.item)
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
    fn last(mut self) -> Option<Self::Item> {
        DoubleEndedIterator::next_back(&mut self)
    }
}
impl<T> DoubleEndedIterator for Values<'_, T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        Some(&*self.0.next_back()?.item)
    }
}
impl<T> ExactSizeIterator for Values<'_, T> {}

impl<'a, T> Iterator for Ids<'a, T> {
    type Item = &'a Id;
    fn next(&mut self) -> Option<Self::Item> {
        Some(&self.0.next()?.id)
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
    fn last(mut self) -> Option<Self::Item> {
        DoubleEndedIterator::next_back(&mut self)
    }
}
impl<T> DoubleEndedIterator for Ids<'_, T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        Some(&self.0.next_back()?.id)
    }
}
impl<T> ExactSizeIterator for Ids<'_, T> {}

impl<T> std::ops::Index<&Id> for Collection<T> {
    type Output = T;
    #[allow(
        clippy::panic,
        reason = "indexing by an absent id is a caller bug, exactly like slice indexing"
    )]
    fn index(&self, id: &Id) -> &T {
        match self.get(id) {
            Some(item) => item,
            None => panic!("no item with id {id} in collection"),
        }
    }
}

impl<T> FromIterator<(Id, T)> for Collection<T> {
    fn from_iter<I: IntoIterator<Item = (Id, T)>>(iter: I) -> Self {
        let mut collection = Self::default();
        for (id, item) in iter {
            collection.push(id, item);
        }
        collection
    }
}

/// One item of a collection map as stored: its id, its order key, its entry and what the
/// entry's value slot holds. [`stored_entries`] lists them in order.
pub struct Stored {
    pub id: Id,
    pub key: String,
    /// The entry's map; `None` for an item stored as its order key alone.
    pub entry: Option<ObjId>,
    /// What the entry's value slot holds, for reading the item.
    pub value: crate::model::MapSlot,
}

/// An entry of a collection map, not read yet: see [`collection_entries`].
pub struct StoredEntry {
    id: Id,
    slot: EntrySlot,
}

impl StoredEntry {
    /// The id of the item the entry holds.
    #[must_use]
    pub fn id(&self) -> &Id {
        &self.id
    }
}

enum EntrySlot {
    /// An item stored as its order key alone.
    Order(String),
    /// The entry's map, holding the order key and the value.
    Map(ObjId),
}

/// Whether items of the type `item` are stored as their order key alone:
/// an item that stores nothing (`()`, a [`Grid`](crate::Grid)'s rows and
/// columns) needs no map around the key.
pub(crate) fn order_only(item: &ModelTable) -> bool {
    std::ptr::eq(item, <() as Model>::TABLE)
}

/// Write the entry of the item `id` under the order key `key` into the
/// collection map `map`: the key itself for an item stored as its order key
/// alone (`order_only`), else a map `{ k, v }` holding the item. Answers the
/// entry's map, or `None` for an item stored as its order key alone.
///
/// An item that can be made whole goes in with its entry, in one batch
/// ([`Stores::made_to`]): the entry, the item's fields and the maps they
/// hold are one insert, where a store after the entry's would be another.
pub(crate) fn put_entry(
    doc: &mut Doc,
    map: &ObjId,
    id: &Id,
    key: String,
    order_only: bool,
    item: &dyn Stores,
) -> Result<Option<ObjId>, ModelError> {
    if order_only {
        crate::action::note_entry(map, id.as_str());
        Slot::Key(map, id.as_str()).put_scalar(doc, ScalarValue::Str(key.into()))?;
        return Ok(None);
    }
    let at = Slot::Key(map, id.as_str());
    let entry = if let Some((Value::Object(ObjType::Map), entry)) = at.current(doc)? {
        Slot::Key(&entry, ORDER).put_scalar(doc, ScalarValue::Str(key.into()))?;
        item.store_to(doc, Slot::Key(&entry, VALUE))
            .located(id.as_str())?;
        entry
    } else {
        crate::action::note_entry(map, id.as_str());
        if let Some((fields, later)) = item.made_to(doc.text_encoding()) {
            // The entry is made with its order key and the item whole: one
            // batch, the item's maps included.
            let mut entry = std::collections::HashMap::with_capacity(2);
            entry.insert(
                ORDER.to_owned(),
                automerge::hydrate::Value::Scalar(ScalarValue::Str(key.into())),
            );
            entry.insert(VALUE.to_owned(), automerge::hydrate::Value::Map(fields));
            let made = at.make(doc, &automerge::hydrate::Value::Map(entry.into()))?;
            let Some((Value::Object(ObjType::Map), value)) = doc.get(&made, VALUE)? else {
                return Err(ModelError::invalid("an entry holds no item"));
            };
            item.write_later_to(doc, &value, &later)?;
            made
        } else {
            // A new entry is made with its order key at once.
            let mut made = std::collections::HashMap::with_capacity(1);
            made.insert(
                ORDER.to_owned(),
                automerge::hydrate::Value::Scalar(ScalarValue::Str(key.into())),
            );
            let entry = at.make(doc, &automerge::hydrate::Value::Map(made.into()))?;
            item.store_to(doc, Slot::Key(&entry, VALUE))
                .located(id.as_str())?;
            entry
        }
    };
    Ok(Some(entry))
}

/// Write `items`, in this order, as the map from id to `{ k, v }` a
/// [`Collection`] is stored as: items no longer there (and not
/// `quarantined`) are deleted, every
/// order key still consistent with the new order is kept (the longest
/// increasing run), and keys are minted only for new or moved items.
pub(crate) fn store_in_order(
    doc: &mut Doc,
    slot: Slot<'_>,
    items: &[(&Id, &dyn Stores)],
    (order_only, shared): (bool, &SharedAt<'_>),
    quarantined: &dyn Fn(&Id) -> bool,
) -> Result<(), ModelError> {
    let map = slot.object(doc, ObjType::Map)?;
    let stored = stored_entries(doc, &map);
    let present: HashSet<&Id> = items.iter().map(|(id, _)| *id).collect();
    for entry in &stored {
        // An item that did not read is kept as it is stored, for its
        // repair: not reading it is no reason to delete it.
        if !present.contains(&entry.id) && !quarantined(&entry.id) {
            doc.delete(&map, entry.id.as_str())?;
        }
    }
    let by_id: HashMap<&Id, &str> = stored
        .iter()
        .map(|entry| (&entry.id, entry.key.as_str()))
        .collect();
    let keys = order_keys(items.iter().map(|(id, _)| *id), &by_id);
    for (index, ((id, item), key)) in items.iter().zip(keys).enumerate() {
        let new = !by_id.contains_key(id);
        let entry = put_entry(doc, &map, id, key, order_only, *item)?;
        if new && let Some(entry) = &entry {
            let doc = &*doc;
            note_stored(Slot::Key(entry, VALUE), &|value| shared(index, doc, value));
        }
    }
    Ok(())
}

/// The item at a position, just stored whole into the new entry given, as
/// reading it back gives ([`shared_item`]); `None` when that cannot be told.
pub(crate) type SharedAt<'a> = dyn Fn(usize, &Doc, &ObjId) -> Option<Box<dyn Any>> + 'a;

/// The item `shared` gives was just stored whole as `value`, an entry's:
/// kept for the reader that follows this write
/// ([`crate::apply_cache::note_stored`]).
fn note_stored(value: Slot<'_>, shared: &dyn Fn(&ObjId) -> Option<Box<dyn Any>>) {
    if let Slot::Key(entry, _) = value {
        crate::apply_cache::note_stored(entry, &|| shared(entry));
    }
}

/// The order key each of `ids` is stored under, given the keys `stored`
/// holds: every stored key still consistent with the order (the longest
/// increasing run) is kept; new and moved items get minted keys.
fn order_keys<'a>(ids: impl Iterator<Item = &'a Id>, stored: &HashMap<&Id, &str>) -> Vec<String> {
    let existing: Vec<Option<&str>> = ids.map(|id| stored.get(id).copied()).collect();
    let kept = longest_increasing(&existing);
    let mut keys: Vec<Option<String>> = vec![None; existing.len()];
    for &index in &kept {
        if let (Some(slot), Some(Some(key))) = (keys.get_mut(index), existing.get(index)) {
            *slot = Some((*key).to_owned());
        }
    }
    let mut index = 0;
    while index < keys.len() {
        if keys.get(index).is_some_and(Option::is_some) {
            index = index.saturating_add(1);
            continue;
        }
        let start = index;
        while keys.get(index).is_some_and(Option::is_none) {
            index = index.saturating_add(1);
        }
        let low = start
            .checked_sub(1)
            .and_then(|before| keys.get(before))
            .and_then(Clone::clone);
        let high = keys.get(index).and_then(Clone::clone);
        let minted = order::sequence(low.as_deref(), high.as_deref(), index.saturating_sub(start));
        for (offset, key) in minted.into_iter().enumerate() {
            if let Some(slot) = keys.get_mut(start.saturating_add(offset)) {
                *slot = Some(key);
            }
        }
    }
    keys.into_iter().map(Option::unwrap_or_default).collect()
}

/// Edit a map of `{ k, v }` entries (a [`Collection`], an
/// [`Ordered`](crate::Ordered)) at `path`: into the item a path names, or
/// insert, remove and move items. What depends on the item type comes in as
/// functions, so this compiles once.
pub(crate) struct EntryEdits<'a> {
    /// Apply an edit inside the value slot of an item.
    pub(crate) item: &'a EditAt<'a>,
    /// A new item from its JSON form, checked, and the id it carries.
    pub(crate) parse: &'a ParseItem<'a>,
    /// The edit of the whole value, for any other operation.
    pub(crate) whole: &'a EditWhole<'a>,
    /// Items are stored as their order key alone ([`order_only`]).
    pub(crate) order_only: bool,
}

/// [`Model::edit`] at a slot.
pub(crate) type EditAt<'a> =
    dyn Fn(&mut Doc, Slot<'_>, &[Segment], &EditOp, &mut ActionCx) -> Result<(), ModelError> + 'a;
/// A new item from its JSON form, and the id it carries.
pub(crate) type ParseItem<'a> =
    dyn Fn(&serde_json::Value) -> Result<(Option<Id>, Box<dyn Stores + 'a>), ModelError> + 'a;
pub(crate) type EditWhole<'a> =
    dyn Fn(&mut Doc, Slot<'_>, &[Segment], &EditOp) -> Result<(), ModelError> + 'a;
/// Write the item at a position over the one it was, in an entry's slot.
type WriteChanged<'a> =
    dyn Fn(usize, usize, &mut Doc, &ObjId, &Delta) -> Result<(), ModelError> + 'a;
/// Store the item at a position, or the whole value, into a slot.
type Created<'a> =
    dyn Fn(usize, &mut Doc, &ObjId, &Id, String, bool) -> Result<Option<ObjId>, ModelError> + 'a;
type StoreWhole<'a> = dyn Fn(&mut Doc, Slot<'_>) -> Result<(), ModelError> + 'a;

pub(crate) fn edit_entries(
    doc: &mut Doc,
    slot: Slot<'_>,
    path: &[Segment],
    op: &EditOp,
    cx: &mut ActionCx,
    edits: &EntryEdits<'_>,
) -> Result<(), ModelError> {
    match (path.split_first(), op) {
        (Some((Segment::Item(id), rest)), _) => {
            let map = slot.object(doc, ObjType::Map)?;
            let Some((Value::Object(ObjType::Map), entry)) = doc.get(&map, id.as_str())? else {
                return Err(ModelError::invalid(format!("no item `{id}`")));
            };
            // An edit inside an item whose value is gone would make the
            // value anew holding the edited field alone: an item missing
            // every other field.
            if !rest.is_empty() && doc.get(&entry, VALUE)?.is_none() {
                return Err(ModelError::invalid(format!(
                    "item `{id}` holds nothing to edit"
                )));
            }
            (edits.item)(doc, Slot::Key(&entry, VALUE), rest, op, cx).located(id.as_str())
        }
        (None, EditOp::InsertItem { id, at, value }) => {
            let (carried, item) = (edits.parse)(value)?;
            let map = slot.object(doc, ObjType::Map)?;
            let id = carried.or_else(|| id.clone()).unwrap_or_else(|| cx.id());
            if doc.get(&map, id.as_str())?.is_some() {
                return Err(ModelError::invalid(format!("an item `{id}` exists")));
            }
            let stored = stored_entries(doc, &map);
            let key = key_at(&stored, at, None)?;
            put_entry(doc, &map, &id, key, edits.order_only, item.as_ref()).map(drop)
        }
        (
            None,
            EditOp::UpsertItem {
                matching,
                value,
                id,
            },
        ) => {
            let map = slot.object(doc, ObjType::Map)?;
            let mut entries = Vec::new();
            let mut candidates = Vec::new();
            for stored in stored_entries(doc, &map) {
                let Some(entry) = stored.entry else { continue };
                if let Some((Value::Object(ObjType::Map), fields)) = doc.get(&entry, VALUE)? {
                    entries.push(entry);
                    candidates.push(crate::upsert::Candidate {
                        id: stored.id,
                        fields,
                    });
                }
            }
            let found = crate::upsert::matching_one(doc, &candidates, matching)?
                .and_then(|found| candidates.iter().position(|item| item.id == found.id));
            if let Some(index) = found
                && let (Some(entry), Some(item)) = (entries.get(index), candidates.get(index))
            {
                for (key, field) in crate::upsert::changed_fields(doc, &item.fields, value)? {
                    (edits.item)(
                        doc,
                        Slot::Key(entry, VALUE),
                        &[Segment::Field(key)],
                        &EditOp::Set { value: field },
                        cx,
                    )
                    .located(item.id.as_str())?;
                }
                return Ok(());
            }
            let insert = upserted(doc, &map, matching, value, id.as_ref())?;
            edit_entries(doc, slot, path, &insert, cx, edits)
        }
        (None, EditOp::RemoveItem { id }) => {
            let map = slot.object(doc, ObjType::Map)?;
            if doc.get(&map, id.as_str())?.is_none() {
                return Err(ModelError::invalid(format!("no item `{id}`")));
            }
            doc.delete(&map, id.as_str())?;
            Ok(())
        }
        (None, EditOp::MoveTo { id, at }) => {
            let map = slot.object(doc, ObjType::Map)?;
            let stored = stored_entries(doc, &map);
            let Some(entry) = stored.iter().find(|entry| &entry.id == id) else {
                return Err(ModelError::invalid(format!("no item `{id}`")));
            };
            let key = key_at(&stored, at, Some(id))?;
            match &entry.entry {
                Some(entry) => {
                    Slot::Key(entry, ORDER).put_scalar(doc, ScalarValue::Str(key.into()))
                }
                None => Slot::Key(&map, id.as_str()).put_scalar(doc, ScalarValue::Str(key.into())),
            }
        }
        _ => (edits.whole)(doc, slot, path, op),
    }
}

/// What [`store_entries_changed`] writes of the items through their type:
/// by position now (`now`) and in the record as it was (`was`).
pub(crate) struct EntryWrites<'a> {
    /// Whether the item now would store as the one it was.
    pub(crate) same: &'a dyn Fn(usize, usize) -> bool,
    /// Write the item at a position into a new entry of the collection map,
    /// under the id and order key given: the item made with its entry in one
    /// batch when it can be. Answers the entry's map, and keeps what was
    /// written for the read that follows.
    pub(crate) created: &'a Created<'a>,
    /// Write the item now over the value of the entry that held it.
    pub(crate) changed: &'a WriteChanged<'a>,
    /// Store the whole collection, when only the document can say.
    pub(crate) whole: &'a StoreWhole<'a>,
    /// Items are stored as their order key alone ([`order_only`]).
    pub(crate) order_only: bool,
}

/// [`Model::store_changed`] of a map of `{ k, v }` entries: the items `ids`
/// over the `stored` ones (id and order key each) they replace; only new,
/// moved and changed items are visited, and an item someone else touched
/// (`dirty`) is written as `store` writes it.
pub(crate) fn store_entries_changed(
    doc: &mut Doc,
    slot: Slot<'_>,
    ids: &[&Id],
    stored: &[(&Id, Option<&str>)],
    dirty: &Delta,
    writes: &EntryWrites<'_>,
) -> Result<(), ModelError> {
    let current: HashSet<&Id> = ids.iter().copied().collect();
    // What was read from a document knows each item's stored order key;
    // with one missing, or an id twice over, only the document can say.
    if current.len() != ids.len() || stored.iter().any(|(_, key)| key.is_none()) {
        return (writes.whole)(doc, slot);
    }
    let map = slot.object(doc, ObjType::Map)?;
    // `stored` is in stored order, the order `store` deletes in.
    for (id, _) in stored {
        if !current.contains(id) {
            doc.delete(&map, id.as_str())?;
        }
    }
    let was: HashMap<&Id, (usize, &str)> = stored
        .iter()
        .enumerate()
        .filter_map(|(at, (id, key))| Some((*id, (at, (*key)?))))
        .collect();
    let by_id: HashMap<&Id, &str> = was.iter().map(|(id, (_, key))| (*id, *key)).collect();
    for ((now, id), key) in ids
        .iter()
        .enumerate()
        .zip(order_keys(ids.iter().copied(), &by_id))
    {
        let touched = dirty.key(&map, id.as_str());
        let Some(&(at, stored_key)) = was.get(id).filter(|_| touched != Touch::Written) else {
            // New here, or replaced by someone else: written whole.
            (writes.created)(now, doc, &map, id, key, writes.order_only)?;
            continue;
        };
        let kept = touched == Touch::Untouched && stored_key == key;
        if kept && (writes.same)(now, at) {
            continue;
        }
        // The entry this item was read from is gone from the document (a
        // change it raced deleted it): written whole, as a whole write
        // would, never as the fields that changed in an entry made now.
        if !writes.order_only
            && !matches!(
                doc.get(&map, id.as_str())?,
                Some((Value::Object(ObjType::Map), _))
            )
        {
            (writes.created)(now, doc, &map, id, key, false)?;
            continue;
        }
        if writes.order_only {
            if !kept {
                Slot::Key(&map, id.as_str()).put_scalar(doc, ScalarValue::Str(key.into()))?;
            }
            continue;
        }
        let entry = Slot::Key(&map, id.as_str()).object(doc, ObjType::Map)?;
        if !kept {
            Slot::Key(&entry, ORDER).put_scalar(doc, ScalarValue::Str(key.into()))?;
        }
        (writes.changed)(now, at, doc, &entry, dirty).located(id.as_str())?;
    }
    Ok(())
}

/// What a change did to the entry `key` of a collection's map.
enum Touched {
    /// It is gone.
    Gone,
    /// Something inside the entry already read changed: its order key, when
    /// that changed, and its value's slot.
    Below { entry: ObjId, order: Option<String> },
    /// A new entry, or one replaced whole.
    Fresh { entry: ObjId, order: String },
    /// An item stored as its order key alone, new or moved.
    Order { order: String },
}

/// How `delta` touched the entry `key` of the collection map `map`; `below`
/// when the entry was read before and only changed inside.
fn touched_entry(
    doc: &Doc,
    map: &ObjId,
    key: &str,
    delta: &Delta,
    below: bool,
) -> Result<Touched, ModelError> {
    let entry = match doc.get(map, key)? {
        Some((Value::Object(ObjType::Map), entry)) => entry,
        Some((Value::Scalar(scalar), _)) => {
            return match scalar.as_ref() {
                ScalarValue::Str(order) => Ok(Touched::Order {
                    order: order.to_string(),
                }),
                _ => Err(ModelError::shape("an order key").at(key)),
            };
        }
        _ => return Ok(Touched::Gone),
    };
    let order = |doc: &Doc| {
        read_key::<crate::Atom>(doc, &entry, ORDER)
            .map(|k| k.0)
            .located(key)
    };
    if below {
        let order = if delta.key(&entry, ORDER) == Touch::Untouched {
            None
        } else {
            Some(order(doc)?)
        };
        return Ok(Touched::Below { entry, order });
    }
    let order = order(doc)?;
    Ok(Touched::Fresh { entry, order })
}

#[inline(never)]
fn entries_schema(item: serde_json::Value) -> serde_json::Value {
    let mut properties = serde_json::Map::new();
    properties.insert("id".into(), serde_json::json!({"type": "string"}));
    properties.insert("value".into(), item);
    let mut entry = serde_json::Map::new();
    entry.insert("type".into(), "object".into());
    entry.insert("properties".into(), properties.into());
    let mut schema = serde_json::Map::new();
    schema.insert("type".into(), "array".into());
    schema.insert("items".into(), entry.into());
    schema.into()
}

/// An item's entry in a collection's JSON form.
#[inline(never)]
fn entry_json(id: &Id, value: serde_json::Value) -> serde_json::Value {
    let mut entry = serde_json::Map::new();
    entry.insert("id".into(), id.as_str().into());
    entry.insert("value".into(), value);
    entry.into()
}

/// The id and value of the entry at `index` of a collection's JSON form.
#[inline(never)]
fn entry_parts(
    index: usize,
    entry: &serde_json::Value,
) -> Result<(Id, &serde_json::Value), ModelError> {
    let id = entry
        .get("id")
        .map(Id::from_json)
        .transpose()?
        .ok_or_else(|| {
            ModelError::Missing {
                path: index.to_string(),
            }
            .at("id")
        })?;
    Ok((id, entry.get("value").unwrap_or(&serde_json::Value::Null)))
}

/// Read every `{ k, v }` entry of the map `id` in stored order, handing
/// each entry's value slot to `read`.
pub(crate) fn load_entries(
    doc: &Doc,
    value: &Value<'_>,
    id: &ObjId,
    read: &mut dyn FnMut(Stored) -> Result<(), ModelError>,
) -> Result<(), ModelError> {
    if !matches!(value, Value::Object(ObjType::Map)) {
        return Err(ModelError::shape("a collection"));
    }
    for stored in stored_entries(doc, id) {
        let at = stored.id.clone();
        read(stored).located(at.as_str())?;
    }
    Ok(())
}

/// The positions of entries in stored order: by order key, ties by id.
/// Sorting positions rather than entries compiles one sort for every item
/// type.
fn stored_order(keys: &[(Option<&str>, &Id)]) -> Vec<usize> {
    let mut order: Vec<usize> = (0..keys.len()).collect();
    order.compact_sort_by(|&a, &b| keys.get(a).cmp(&keys.get(b)));
    order
}

/// The entries of the collection map `map`, in one walk of the map, without reading any:
/// [`read_entry`] reads each and [`in_stored_order`] orders what they read, which is what
/// [`stored_entries`] does. Each read opens its entry's map, so a reader of a large
/// collection may spread the reads over threads.
#[must_use]
pub fn collection_entries(doc: &Doc, map: &ObjId) -> Vec<StoredEntry> {
    let mut entries = Vec::new();
    for item in doc.map_range(map, ..) {
        let id = Id(item.key.clone().into_owned());
        // An item stored as its order key alone.
        if let automerge::ValueRef::Scalar(automerge::ScalarValueRef::Str(order)) = &item.value {
            entries.push(StoredEntry {
                id,
                slot: EntrySlot::Order(order.to_string()),
            });
        } else if item.value == automerge::ValueRef::Object(ObjType::Map) {
            entries.push(StoredEntry {
                id,
                slot: EntrySlot::Map(item.id()),
            });
        }
    }
    entries
}

/// The item an entry holds: its order key and value slot, read with one walk of the entry.
/// `None` for an entry without a readable order key: no entry anyone placed, left out, never
/// the reason its whole collection does not read.
#[must_use]
pub fn read_entry(doc: &Doc, entry: StoredEntry) -> Option<Stored> {
    match entry.slot {
        EntrySlot::Order(key) => Some(Stored {
            id: entry.id,
            key,
            entry: None,
            value: None,
        }),
        EntrySlot::Map(map) => {
            let [order, value] = crate::model::read_slots(doc, &map, [ORDER, VALUE]);
            let order = crate::model::load_slot::<crate::Atom>(doc, order, ORDER).ok()?;
            Some(Stored {
                id: entry.id,
                key: order.0,
                entry: Some(map),
                value,
            })
        }
    }
}

/// Put read entries in stored order: by order key, ties by id.
pub fn in_stored_order(entries: &mut [Stored]) {
    // `(order key, id)` is unique, so an unstable sort orders as a stable one.
    entries.compact_sort_by(|a, b| a.key.cmp(&b.key).then_with(|| a.id.cmp(&b.id)));
}

/// The stored entries of the collection map `map`, in order. One walk of
/// the map lists the entries and one walk of each entry reads its order key
/// and value slot: a lookup per key would open each map again.
pub(crate) fn stored_entries(doc: &Doc, map: &ObjId) -> Vec<Stored> {
    let mut entries: Vec<Stored> = collection_entries(doc, map)
        .into_iter()
        .filter_map(|entry| read_entry(doc, entry))
        .collect();
    in_stored_order(&mut entries);
    entries
}

/// The ids of the items of the collection map `map`, in stored order, without reading any
/// item: what a reader that needs a collection's membership and order, and not its items,
/// walks.
#[must_use]
pub fn stored_ids(doc: &Doc, map: &ObjId) -> Vec<Id> {
    stored_entries(doc, map)
        .into_iter()
        .map(|stored| stored.id)
        .collect()
}

/// The stored entry of the item `id` of the collection map `map`, with its order key: `None`
/// when there is no such item or it has no readable order key. One item is read without
/// listing the others: what a reader that keeps a collection's order applies a change by.
#[must_use]
pub fn stored_entry(doc: &Doc, map: &ObjId, id: &str) -> Option<Stored> {
    let slot = match doc.get(map, id).ok()?? {
        (Value::Scalar(scalar), _) => match scalar.as_ref() {
            ScalarValue::Str(order) => EntrySlot::Order(order.to_string()),
            _ => return None,
        },
        (Value::Object(ObjType::Map), entry) => EntrySlot::Map(entry),
        (Value::Object(_), _) => return None,
    };
    read_entry(
        doc,
        StoredEntry {
            id: Id(id.to_owned()),
            slot,
        },
    )
}

/// The value map of the item `id` of the collection map `map`: `None` when there is no such
/// item, `Some(None)` for an item stored as its order key alone (it reads as its type's
/// default), so one item is reached without reading the others.
#[must_use]
pub fn stored_item(doc: &Doc, map: &ObjId, id: &str) -> Option<Option<ObjId>> {
    match doc.get(map, id).ok()?? {
        (Value::Scalar(_), _) => Some(None),
        (Value::Object(ObjType::Map), entry) => match doc.get(&entry, VALUE).ok().flatten() {
            Some((Value::Object(_), value)) => Some(Some(value)),
            _ => Some(None),
        },
        (Value::Object(_), _) => None,
    }
}

/// An order key placing an item at `at` among `stored` (which may hold the
/// item itself, `moving`, which does not count).
pub(crate) fn key_at(
    stored: &[Stored],
    at: &crate::At,
    moving: Option<&Id>,
) -> Result<String, ModelError> {
    let others: Vec<&Stored> = stored
        .iter()
        .filter(|entry| Some(&entry.id) != moving)
        .collect();
    let ids: Vec<&Id> = others.iter().map(|entry| &entry.id).collect();
    let at = at.index(&ids)?;
    let low = at
        .checked_sub(1)
        .and_then(|before| others.get(before))
        .map(|entry| entry.key.as_str());
    let high = others.get(at).map(|entry| entry.key.as_str());
    Ok(order::between(low, high))
}

/// The insert an upsert that matched no item of the map `map` makes: at the
/// end, under `id` when given, else under the id its key mints when no item
/// holds that one yet.
pub(crate) fn upserted(
    doc: &Doc,
    map: &ObjId,
    matching: &serde_json::Map<String, serde_json::Value>,
    value: &serde_json::Value,
    id: Option<&Id>,
) -> Result<EditOp, ModelError> {
    let minted = crate::upsert::key_id(matching);
    let id = if let Some(id) = id {
        Some(id.clone())
    } else {
        doc.get(map, minted.as_str())?.is_none().then_some(minted)
    };
    Ok(EditOp::InsertItem {
        id,
        at: crate::At::End,
        value: crate::upsert::inserted(matching, value)?,
    })
}

/// Indices (into `keys`) of one longest strictly increasing subsequence.
fn longest_increasing(keys: &[Option<&str>]) -> Vec<usize> {
    // Patience sorting over the present keys, O(n log n).
    let mut tails: Vec<usize> = Vec::new();
    let mut previous: Vec<Option<usize>> = vec![None; keys.len()];
    for (index, key) in keys.iter().enumerate() {
        let Some(key) = key else { continue };
        let position =
            tails.partition_point(|&tail| keys.get(tail).copied().flatten() < Some(*key));
        if let Some(before) = position.checked_sub(1)
            && let Some(slot) = previous.get_mut(index)
        {
            *slot = tails.get(before).copied();
        }
        if position == tails.len() {
            tails.push(index);
        } else if let Some(tail) = tails.get_mut(position) {
            *tail = index;
        }
    }
    let mut chain = Vec::with_capacity(tails.len());
    let mut cursor = tails.last().copied();
    while let Some(index) = cursor {
        chain.push(index);
        cursor = previous.get(index).copied().flatten();
    }
    chain.reverse();
    chain
}

impl<T: Model> Collection<T> {
    /// Read item `id` again from `map`, the collection's map in `doc`, with
    /// every field as stored: what a view's reader left unread of it
    /// (`#[model(demanded)]`) too. A resource's [`load`](crate::Resource::load)
    /// reads so the items a view demands. Whether the collection holds `id`
    /// and its entry read.
    ///
    /// # Errors
    /// Why the stored item does not read.
    pub fn read_whole(&mut self, doc: &Doc, map: &ObjId, id: &Id) -> Result<bool, ModelError> {
        read_item_whole(self, T::TABLE, doc, map, id)
    }
}

/// [`Collection::read_whole`], compiled once for every item type.
#[inline(never)]
fn read_item_whole(
    entries: &mut dyn Entries,
    item: &'static ModelTable,
    doc: &Doc,
    map: &ObjId,
    id: &Id,
) -> Result<bool, ModelError> {
    let Some(at) = entries.find(id) else {
        return Ok(false);
    };
    let Some(stored) = stored_entry(doc, map, id.as_str()) else {
        return Ok(false);
    };
    let held = stored.value;
    crate::table::whole(|| {
        entries.replace_filled(at, Some(stored.key), &mut |into| {
            let held = held.as_ref().map(|(value, obj)| (value, obj));
            fill_item(item, doc, (map, id.as_str()), held, into)
                .map(drop)
                .located(VALUE)
        })
    })?;
    Ok(true)
}

impl<T> Collection<T> {
    /// Sort the items as stored: by order key, ties by id.
    fn reorder_by_keys(&mut self) {
        let items = &self.items;
        let order = stored_order_of(items.len(), &|at| {
            items.get(at).map(|entry| (entry.key.as_deref(), &entry.id))
        });
        permute(order, &mut |at, from| self.items.swap(at, from));
    }
}

/// [`stored_order`] of the `count` entries whose order key and id `key_at`
/// gives. Compiled once for every item type.
#[inline(never)]
fn stored_order_of<'a>(
    count: usize,
    key_at: &dyn Fn(usize) -> Option<(Option<&'a str>, &'a Id)>,
) -> Vec<usize> {
    let keys: Vec<(Option<&str>, &Id)> = (0..count).filter_map(key_at).collect();
    stored_order(&keys)
}

/// Move the entry at `order[at]` to each position `at`, in place, one cycle
/// of the permutation at a time, swapping two positions with `swap`.
/// Compiled once for every item type.
#[inline(never)]
fn permute(mut order: Vec<usize>, swap: &mut dyn FnMut(usize, usize)) {
    for start in 0..order.len() {
        let mut at = start;
        while let Some(from) = order.get_mut(at).map(|from| std::mem::replace(from, at)) {
            if from == start {
                break;
            }
            swap(at, from);
            at = from;
        }
    }
}

/// Forget the quarantined item `id` in `quarantine`, noting in
/// `whole_write` that only a whole write stores that; whether it was
/// quarantined. Compiled once for every item type.
#[inline(never)]
fn forget_quarantined(quarantine: &mut Vec<Quarantined>, whole_write: &mut bool, id: &Id) -> bool {
    let before = quarantine.len();
    quarantine.retain(|held| &held.id != id);
    let forgotten = quarantine.len() != before;
    *whole_write |= forgotten;
    forgotten
}

/// Hold the stored item `id` in `quarantine`, for `reason`. Compiled once
/// for every item type.
#[inline(never)]
fn hold_quarantined(quarantine: &mut Vec<Quarantined>, id: Id, reason: String) {
    match quarantine.iter_mut().find(|held| held.id == id) {
        Some(held) => held.reason = reason,
        None => quarantine.push(Quarantined { id, reason }),
    }
}

/// Stop holding `id` in `quarantine`. Compiled once for every item type.
#[inline(never)]
fn release_quarantined(quarantine: &mut Vec<Quarantined>, id: &Id) {
    quarantine.retain(|held| &held.id != id);
}

impl<T: Model> crate::items::ItemSource for Collection<T> {
    fn item_collection(&self, field: &'static str) -> crate::items::ItemCollection {
        listed_items(T::TABLE, self, field)
    }
    fn item_presence(&self) -> usize {
        usize::from(!self.items.is_empty())
    }
    fn label_of_item(&self, id: &Id) -> Option<String> {
        let entries: &dyn Entries = self;
        let item = entries.item_at(entries.find(id)?)?;
        Some(label_of(T::TABLE, id, item))
    }
    fn item_texts(&self, field: &'static str, found: &mut Vec<crate::items::ItemText>) {
        item_texts(T::TABLE, self, field, found);
    }
    fn nested_items(&self, field: &'static str, out: &mut Vec<crate::items::ItemCollection>) {
        nested_items(T::TABLE, self, field, out);
    }
}

/// Items with their ids, whatever their type and wherever their ids are
/// kept: what listing them for publication and search reads.
#[doc(hidden)]
pub trait ItemList {
    fn count(&self) -> usize;
    fn item(&self, at: usize) -> Option<(Id, &dyn Any)>;
    /// Whether `id` is an item kept out of the list because it no longer
    /// reads ([`Collection::quarantined`]).
    fn quarantines(&self, id: &str) -> bool {
        let _ = id;
        false
    }
}

impl<T: Model> crate::table::PublishedItems for Collection<T> {
    const ITEM_TABLE: &'static ModelTable = T::TABLE;
}

impl<T: 'static> ItemList for Collection<T> {
    fn count(&self) -> usize {
        self.items.len()
    }

    fn item(&self, at: usize) -> Option<(Id, &dyn Any)> {
        let entry = self.items.get(at)?;
        Some((entry.id.clone(), &*entry.item as &dyn Any))
    }

    fn quarantines(&self, id: &str) -> bool {
        self.quarantine.iter().any(|held| held.id.as_str() == id)
    }
}

/// The label an item is offered under: its `#[model(label)]` (the word for an item nobody named
/// when that is blank), else its first text, else its id.
pub(crate) fn label_of(item: &ModelTable, id: &Id, value: &dyn Any) -> String {
    if let Some(label) = (item.ops.label)(item, value)
        && !label.is_empty()
    {
        return label;
    }
    // A record that names itself by a field of its own is named by that field alone: one nobody
    // named reads as the person's word for an item that has no name, never by its other text, so
    // what a list shows and what assistive tools announce are the same name.
    let names_itself = item.record().is_some_and(|record| {
        record.label.is_some() || record.label_with.is_some() || !record.label_parts.is_empty()
    });
    if names_itself {
        return crate::word!("resource-unnamed-item").read();
    }
    let mut text = Vec::new();
    (item.ops.collect_text)(item, value, &mut text);
    crate::__private::first_line_of(text).unwrap_or_else(|| id.to_string())
}

/// [`ItemSource::item_collection`](crate::items::ItemSource::item_collection)
/// of `entries`, items of the type `item`.
pub(crate) fn listed_items(
    item: &ModelTable,
    entries: &dyn ItemList,
    field: &'static str,
) -> crate::items::ItemCollection {
    let mut labelled = false;
    let mut listed = Vec::new();
    for at in 0..entries.count().min(crate::items::ITEM_PAGE) {
        let Some((id, value)) = entries.item(at) else {
            continue;
        };
        if at == 0 {
            labelled = (item.ops.label)(item, value).is_some();
        }
        let label = label_of(item, &id, value);
        listed.push((id, label));
    }
    crate::items::ItemCollection {
        within: Vec::new(),
        field,
        labelled,
        items: listed,
    }
}

/// [`ItemSource::item_texts`](crate::items::ItemSource::item_texts) of
/// `entries`.
pub(crate) fn item_texts(
    item: &ModelTable,
    entries: &dyn ItemList,
    field: &'static str,
    found: &mut Vec<crate::items::ItemText>,
) {
    for at in 0..entries.count() {
        let Some((id, value)) = entries.item(at) else {
            continue;
        };
        if let Some(label) = (item.ops.label)(item, value) {
            let mut text = Vec::new();
            (item.ops.collect_text)(item, value, &mut text);
            found.push(crate::items::ItemText {
                field,
                id,
                label,
                text: text.join("\n"),
            });
        }
    }
}

/// [`ItemSource::nested_items`](crate::items::ItemSource::nested_items) of
/// `entries`.
pub(crate) fn nested_items(
    item: &ModelTable,
    entries: &dyn ItemList,
    field: &'static str,
    out: &mut Vec<crate::items::ItemCollection>,
) {
    for at in 0..entries.count().min(crate::items::ITEM_PAGE) {
        let Some((id, value)) = entries.item(at) else {
            continue;
        };
        for mut inner in (item.ops.nested_collections)(item, value) {
            inner.within.insert(0, (field, id.clone()));
            out.push(inner);
        }
    }
}

impl<T: Model> Model for Collection<T> {
    fn value_schema() -> serde_json::Value {
        entries_schema(T::value_schema())
    }
    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
        crate::FieldType::Collection(Box::new(T::field_type(types)))
    }
    const SHAPE: crate::Shape = crate::Shape::Collection(&T::SHAPE);
    const CHECKS: bool = T::CHECKS;
    const OPS: bool = T::OPS;
    const TABLE: &'static ModelTable = &CollectionOf::<T>::TABLE;
    crate::model::leaf_paths!();
    crate::__table_functions!();
    fn missing() -> Result<Self, ModelError> {
        Ok(Self::default())
    }
}

/// The item `fill` puts into an `Option` of its type, shared: the one copy
/// for each item type of what [`Entries::push_filled`] and
/// [`Entries::replace_filled`] do with the value itself, so the large moves
/// of a big item are compiled once rather than in each of them.
#[inline(never)]
fn filled_shared<T: 'static>(
    fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
) -> Result<Arc<T>, ModelError> {
    let mut slot: Option<T> = None;
    fill(&mut slot)?;
    crate::table::filled(slot).map(Arc::new)
}

/// A collection's entries, whatever its item type: what the collection
/// functions below reach into one with.
pub(crate) trait Entries {
    fn count(&self) -> usize;
    fn id_at(&self, at: usize) -> Option<&Id>;
    fn order_at(&self, at: usize) -> Option<&str>;
    fn item_at(&self, at: usize) -> Option<&dyn Any>;
    fn item_at_mut(&mut self, at: usize) -> Option<&mut dyn Any>;
    fn find(&self, id: &Id) -> Option<usize>;
    /// Append an entry (with `replace`, replace the item of an id already
    /// present), its item put by `fill` into an `Option` of the item type.
    fn push_filled(
        &mut self,
        entry: (Id, Option<String>, bool),
        fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
    ) -> Result<(), ModelError>;
    /// Replace the entry at `at`, as [`Self::push_filled`].
    fn replace_filled(
        &mut self,
        at: usize,
        order: Option<String>,
        fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
    ) -> Result<(), ModelError>;
    fn remove_at(&mut self, at: usize);
    fn set_order(&mut self, at: usize, order: Option<String>);
    /// Sort the entries by their order keys; the ids may have moved.
    fn reorder(&mut self);
    /// The ids changed.
    fn changed(&mut self);
    /// Whether the stored item `id` is quarantined.
    fn is_quarantined(&self, id: &Id) -> bool;
    /// Hold the stored item `id` as quarantined, for `reason`.
    fn quarantine(&mut self, id: Id, reason: String);
    /// Stop holding `id` as quarantined: it reads again, or is gone.
    fn release(&mut self, id: &Id);
    /// Only a whole write stores the collection as it now is.
    fn needs_whole_write(&self) -> bool;
    /// The item at `at` as this collection shares it: an `Arc` of it, with
    /// how to copy it.
    fn shared_at(&self, at: usize) -> Option<Box<dyn Any>>;
    /// A copy of the item at `at`, changed by `settle`, as [`Self::shared_at`]
    /// gives an item; `None` when `settle` fails.
    fn settled_at(
        &self,
        at: usize,
        settle: &mut dyn FnMut(&mut dyn Any) -> bool,
    ) -> Option<Box<dyn Any>>;
    /// Put `stored`, an item as [`Self::shared_at`] gave it, at `at` or
    /// appended, as `entry`: its id and order key. Whether it was one of this
    /// collection's items.
    fn put_shared(&mut self, at: Option<usize>, entry: (Id, String), stored: &dyn Any) -> bool;
}

impl<T: 'static> Entries for Collection<T> {
    fn count(&self) -> usize {
        self.items.len()
    }

    fn id_at(&self, at: usize) -> Option<&Id> {
        self.items.get(at).map(|entry| &entry.id)
    }

    fn order_at(&self, at: usize) -> Option<&str> {
        self.items.get(at)?.key.as_deref()
    }

    fn item_at(&self, at: usize) -> Option<&dyn Any> {
        self.items.get(at).map(|entry| &*entry.item as &dyn Any)
    }

    /// Copies the item first when a clone of the collection still shares
    /// it: a refresh changes only the items a change touched.
    fn item_at_mut(&mut self, at: usize) -> Option<&mut dyn Any> {
        let entry = self.items.get_mut(at)?;
        let item = self.copier.unshare(&mut entry.item)?;
        Some(item as &mut dyn Any)
    }

    fn find(&self, id: &Id) -> Option<usize> {
        self.position(id)
    }

    fn push_filled(
        &mut self,
        (id, order, replace): (Id, Option<String>, bool),
        fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
    ) -> Result<(), ModelError> {
        let item = filled_shared::<T>(fill)?;
        if replace {
            self.push_shared(id, item);
        } else {
            self.items.push(Entry {
                id,
                key: order,
                item,
            });
            self.index.reset();
        }
        Ok(())
    }

    fn replace_filled(
        &mut self,
        at: usize,
        order: Option<String>,
        fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
    ) -> Result<(), ModelError> {
        let item = filled_shared::<T>(fill)?;
        if let Some(entry) = self.items.get_mut(at) {
            entry.item = item;
            entry.key = order;
        }
        Ok(())
    }

    fn remove_at(&mut self, at: usize) {
        if at < self.items.len() {
            self.items.remove(at);
        }
    }

    fn set_order(&mut self, at: usize, order: Option<String>) {
        if let Some(entry) = self.items.get_mut(at) {
            entry.key = order;
        }
    }

    fn reorder(&mut self) {
        self.reorder_by_keys();
        self.index.reset();
        self.moved();
    }

    fn changed(&mut self) {
        self.index.reset();
        self.moved();
    }

    fn is_quarantined(&self, id: &Id) -> bool {
        self.quarantine.iter().any(|held| &held.id == id)
    }

    fn quarantine(&mut self, id: Id, reason: String) {
        hold_quarantined(&mut self.quarantine, id, reason);
    }

    fn release(&mut self, id: &Id) {
        release_quarantined(&mut self.quarantine, id);
    }

    fn needs_whole_write(&self) -> bool {
        self.whole_write
    }

    /// Only from a collection that can copy what it shares: the one taking it
    /// must be able to copy it before changing it.
    fn shared_at(&self, at: usize) -> Option<Box<dyn Any>> {
        let entry = self.items.get(at)?;
        let copy = *self.copier.0.get()?;
        Some(Box::new((Arc::clone(&entry.item), copy)))
    }

    fn settled_at(
        &self,
        at: usize,
        settle: &mut dyn FnMut(&mut dyn Any) -> bool,
    ) -> Option<Box<dyn Any>> {
        let entry = self.items.get(at)?;
        let copy = *self.copier.0.get()?;
        let mut item = copy(&entry.item);
        settle(&mut item).then(|| Box::new((Arc::new(item), copy)) as Box<dyn Any>)
    }

    fn put_shared(
        &mut self,
        at: Option<usize>,
        (id, order): (Id, String),
        stored: &dyn Any,
    ) -> bool {
        let Some((item, copy)) = stored.downcast_ref::<(Arc<T>, fn(&T) -> T)>() else {
            return false;
        };
        // Shared from here on: copied before it is changed.
        let _ = self.copier.0.set(*copy);
        let item = Arc::clone(item);
        if let Some(entry) = at.and_then(|at| self.items.get_mut(at)) {
            entry.item = item;
            entry.key = Some(order);
        } else {
            self.items.push(Entry {
                id,
                key: Some(order),
                item,
            });
            self.index.reset();
        }
        true
    }
}

/// The item at `at` of `entries`, of the type `item`, just stored whole into
/// `entry`, as reading it back gives: as they share it, or, for an item
/// holding what reads back as the document's own structure (rich text), a
/// copy with that read again ([`crate::table::settle`]).
fn shared_item(
    item: &ModelTable,
    entries: &dyn Entries,
    at: usize,
    (doc, entry): (&Doc, &ObjId),
) -> Option<Box<dyn Any>> {
    if !item.has_ops {
        return entries.shared_at(at);
    }
    entries.settled_at(at, &mut |value| {
        crate::table::settle(item, value, doc, (entry, VALUE)).is_ok()
    })
}

/// What `Collection<T>`'s table reaches into one with.
pub struct CollectionDesc {
    item: &'static ModelTable,
    entries: for<'a> fn(&'a dyn Any) -> Option<&'a dyn Entries>,
    entries_mut: for<'a> fn(&'a mut dyn Any) -> Option<&'a mut dyn Entries>,
    /// Put an empty collection into `out` (an `Option` of it), and hand it
    /// back.
    fresh: for<'a> fn(&'a mut dyn Any) -> Option<&'a mut dyn Entries>,
    /// An empty `Option` of a collection, the collection in a filled one,
    /// and moving it out over another.
    staged: (fn() -> Box<dyn Any>, crate::table::Unstage),
    replace: fn(&mut dyn Any, &mut dyn Any) -> Result<(), ModelError>,
    /// An empty `Option` of an item and the item in a filled one.
    item_staged: (fn() -> Box<dyn Any>, crate::table::Unstage),
}

impl CollectionDesc {
    /// Its item type's table.
    pub(crate) const fn item(&self) -> &'static ModelTable {
        self.item
    }
}

pub struct CollectionOf<T>(std::marker::PhantomData<T>);

impl<T: Model> CollectionOf<T> {
    pub const DESC: CollectionDesc = CollectionDesc {
        item: T::TABLE,
        entries: entries_of::<T>,
        entries_mut: entries_mut_of::<T>,
        fresh: fresh_of::<T>,
        staged: (
            crate::table::empty_of::<Collection<T>>,
            crate::table::unwrap_of::<Collection<T>>,
        ),
        replace: crate::table::replace_of::<Collection<T>>,
        item_staged: (crate::table::empty_of::<T>, crate::table::unwrap_of::<T>),
    };

    pub const TABLE: ModelTable = ModelTable::of_collection(&Self::DESC, T::CHECKS, T::OPS);
}

fn entries_of<T: 'static>(value: &dyn Any) -> Option<&dyn Entries> {
    Some(value.downcast_ref::<Collection<T>>()? as &dyn Entries)
}

fn entries_mut_of<T: 'static>(value: &mut dyn Any) -> Option<&mut dyn Entries> {
    Some(value.downcast_mut::<Collection<T>>()? as &mut dyn Entries)
}

fn fresh_of<T: 'static>(out: &mut dyn Any) -> Option<&mut dyn Entries> {
    let out = out.downcast_mut::<Option<Collection<T>>>()?;
    let collection = out.insert(Collection::default());
    Some(collection as &mut dyn Entries)
}

fn listed(table: &ModelTable) -> Result<&'static CollectionDesc, ModelError> {
    table.collection().ok_or_else(crate::table::mismatch)
}

/// An item as [`store_in_order`] writes it, through its table.
pub(crate) struct TableItem<'a> {
    pub(crate) table: &'static ModelTable,
    pub(crate) value: &'a dyn Any,
}

impl Stores for TableItem<'_> {
    fn store_to(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
        (self.table.ops.store)(self.table, self.value, doc, slot)
    }

    fn made_to(&self, encoding: automerge::TextEncoding) -> Option<crate::table::Fields> {
        let desc = crate::table::described(self.table).ok()?;
        crate::table::fresh::fields_made_of(desc, self.value, encoding)
    }

    fn write_later_to(
        &self,
        doc: &mut Doc,
        value: &ObjId,
        later: &[(usize, bool)],
    ) -> Result<(), ModelError> {
        let desc = crate::table::described(self.table)?;
        crate::table::fresh::write_later(desc, self.value, doc, value, later)
    }
}

/// An item made from its JSON form, staged in an `Option` of its type.
struct StagedItem {
    table: &'static ModelTable,
    staged: Box<dyn Any>,
    unstage: crate::table::Unstage,
}

impl Stores for StagedItem {
    fn store_to(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
        let value = (self.unstage)(self.staged.as_ref()).ok_or_else(crate::table::mismatch)?;
        (self.table.ops.store)(self.table, value, doc, slot)
    }

    fn made_to(&self, encoding: automerge::TextEncoding) -> Option<crate::table::Fields> {
        let desc = crate::table::described(self.table).ok()?;
        let value = (self.unstage)(self.staged.as_ref())?;
        crate::table::fresh::fields_made_of(desc, value, encoding)
    }

    fn write_later_to(
        &self,
        doc: &mut Doc,
        value: &ObjId,
        later: &[(usize, bool)],
    ) -> Result<(), ModelError> {
        let desc = crate::table::described(self.table)?;
        let item = (self.unstage)(self.staged.as_ref()).ok_or_else(crate::table::mismatch)?;
        crate::table::fresh::write_later(desc, item, doc, value, later)
    }
}

/// Whether `error` says a stored value does not read as its type (absent,
/// of another shape, invalid): what quarantines one item rather than
/// failing its whole record. A document error is no such thing.
fn quarantines(error: &ModelError) -> bool {
    matches!(
        error,
        ModelError::Missing { .. } | ModelError::Shape { .. } | ModelError::Invalid { .. }
    )
}

/// The value maps the entry `key` of the collection map `map` holds: the
/// winning entry's first, then those of the entries (and values) that
/// replicas made concurrently and the document keeps in conflict beside it.
fn conflicting_values(doc: &Doc, (map, key): (&ObjId, &str)) -> Vec<ObjId> {
    fn maps(doc: &Doc, obj: &ObjId, key: &str, out: &mut Vec<ObjId>) {
        if let Ok(Some((Value::Object(ObjType::Map), winner))) = doc.get(obj, key)
            && !out.contains(&winner)
        {
            out.push(winner);
        }
        for (value, id) in doc.get_all(obj, key).unwrap_or_default() {
            if matches!(value, Value::Object(ObjType::Map)) && !out.contains(&id) {
                out.push(id);
            }
        }
    }
    let mut entries = Vec::new();
    maps(doc, map, key, &mut entries);
    let mut values = Vec::new();
    for entry in &entries {
        maps(doc, entry, VALUE, &mut values);
    }
    values
}

/// Read the item stored under the entry `key` of the collection map `map`
/// into `into` (an `Option` of `item`'s type), from the value slot `slot`
/// its entry holds. When that does not read and replicas made the entry
/// concurrently, the copies the document keeps in conflict are read as one
/// item, each field from the first copy holding it: the same id made on two
/// devices is one complete item, never one missing what the other copy
/// holds. `Ok(true)` when it was read so.
fn fill_item(
    item: &ModelTable,
    doc: &Doc,
    entry: (&ObjId, &str),
    slot: Option<(&Value<'_>, &ObjId)>,
    into: &mut dyn Any,
) -> Result<bool, ModelError> {
    let _read = crate::profiling::Phase::start("collection.read_item");
    let error = match crate::table::load_slot(item, doc, slot, into) {
        Ok(()) => return Ok(false),
        Err(error) if quarantines(&error) => error,
        Err(error) => return Err(error),
    };
    let copies = conflicting_values(doc, entry);
    if copies.len() < 2 {
        return Err(error);
    }
    let merged = match item.record() {
        Some(record) => crate::table::read_fields_merged(record, doc, &copies, into).is_ok(),
        None => copies.iter().any(|copy| {
            crate::table::load_slot(item, doc, Some((&Value::Object(ObjType::Map), copy)), into)
                .is_ok()
        }),
    };
    if merged { Ok(true) } else { Err(error) }
}

/// The item just appended to `entries` was read from conflicting copies:
/// it forgets its order key, so the next write stores it whole, over the
/// winning copy, and the document holds it complete again.
fn mark_merged(entries: &mut dyn Entries) {
    if let Some(last) = entries.count().checked_sub(1) {
        entries.set_order(last, None);
    }
}

/// Read a collection stored in the map `id` into `out`, a fresh one.
fn load_into(
    desc: &CollectionDesc,
    doc: &Doc,
    value: &Value<'_>,
    id: &ObjId,
    out: &mut dyn Entries,
) -> Result<(), ModelError> {
    let item = desc.item;
    load_entries(doc, value, id, &mut |stored| {
        // Stored by the write the state is read after: taken as it was written.
        if let Some(entry) = &stored.entry
            && crate::apply_cache::take_stored(entry, &mut |taken| {
                out.put_shared(None, (stored.id.clone(), stored.key.clone()), taken)
            })
        {
            return Ok(());
        }
        let slot = stored.value;
        let key = stored.id.clone();
        let mut merged = false;
        let read = out.push_filled((stored.id, Some(stored.key), false), &mut |into| {
            let slot = slot.as_ref().map(|(v, i)| (v, i));
            merged = fill_item(item, doc, (id, key.as_str()), slot, into).located(VALUE)?;
            Ok(())
        });
        match read {
            Ok(()) => {
                if merged {
                    mark_merged(&mut *out);
                }
                Ok(())
            }
            Err(error) if quarantines(&error) => {
                let reason = error.at(key.as_str()).to_string();
                out.quarantine(key, reason);
                Ok(())
            }
            Err(error) => Err(error),
        }
    })?;
    // What was read is a membership of its own.
    out.changed();
    Ok(())
}

/// The functions of every [`Collection`], over its item type's table.
pub static COLLECTION_OPS: ModelOps = ModelOps {
    without_absent: crate::shape::kept_whole,
    // An empty collection is an empty map; one holding items mints their
    // order keys as its `store` writes them.
    fresh: |table, value, _| match table.collection().and_then(|desc| (desc.entries)(value)) {
        Some(entries) if entries.count() == 0 => {
            crate::model::Fresh::Value(automerge::hydrate::Value::map())
        }
        _ => crate::model::Fresh::Store,
    },
    to_json: |table, value| {
        let (Ok(desc), Some(entries)) = (
            listed(table),
            table.collection().and_then(|desc| (desc.entries)(value)),
        ) else {
            return serde_json::Value::Null;
        };
        let mut out = Vec::with_capacity(entries.count());
        for at in 0..entries.count() {
            if let (Some(id), Some(item)) = (entries.id_at(at), entries.item_at(at)) {
                out.push(entry_json(id, (desc.item.ops.to_json)(desc.item, item)));
            }
        }
        serde_json::Value::Array(out)
    },
    from_json: |table, value, out| {
        let desc = listed(table)?;
        let serde_json::Value::Array(items) = value else {
            return Err(ModelError::shape("a list of items"));
        };
        let collection = (desc.fresh)(out).ok_or_else(crate::table::mismatch)?;
        for (index, entry) in items.iter().enumerate() {
            let (id, value) = entry_parts(index, entry)?;
            let at = id.clone();
            collection.push_filled((id, None, true), &mut |into| {
                (desc.item.ops.from_json)(desc.item, value, into).located(at.as_str())
            })?;
        }
        Ok(())
    },
    load: |table, doc, value, id, out| {
        let desc = listed(table)?;
        let collection = (desc.fresh)(out).ok_or_else(crate::table::mismatch)?;
        load_into(desc, doc, value, id, collection)
    },
    missing: |table, out| {
        let desc = listed(table)?;
        (desc.fresh)(out).ok_or_else(crate::table::mismatch)?;
        Ok(())
    },
    reload: |table, target, doc, slot| {
        let desc = listed(table)?;
        let mut staged = (desc.staged.0)();
        match slot {
            Some((value, id)) => (COLLECTION_OPS.load)(table, doc, value, id, staged.as_mut())?,
            None => (COLLECTION_OPS.missing)(table, staged.as_mut())?,
        }
        (desc.replace)(target, staged.as_mut())
    },
    store: |table, value, doc, slot| {
        let desc = listed(table)?;
        let entries = (desc.entries)(value).ok_or_else(crate::table::mismatch)?;
        let mut held: Vec<(&Id, TableItem<'_>)> = Vec::with_capacity(entries.count());
        for at in 0..entries.count() {
            if let (Some(id), Some(item)) = (entries.id_at(at), entries.item_at(at)) {
                held.push((
                    id,
                    TableItem {
                        table: desc.item,
                        value: item,
                    },
                ));
            }
        }
        let mut items: Vec<(&Id, &dyn Stores)> = Vec::with_capacity(held.len());
        for (id, item) in &held {
            items.push((*id, item as &dyn Stores));
        }
        let shared = |at: usize, doc: &Doc, entry: &ObjId| {
            let at = entries.find(held.get(at)?.0)?;
            shared_item(desc.item, entries, at, (doc, entry))
        };
        store_in_order(doc, slot, &items, (order_only(desc.item), &shared), &|id| {
            entries.is_quarantined(id)
        })
    },
    stores_as: |table, value, before| {
        let Some(desc) = table.collection() else {
            return false;
        };
        let (Some(now), Some(was)) = ((desc.entries)(value), (desc.entries)(before)) else {
            return false;
        };
        if now.needs_whole_write() || now.count() != was.count() || !strictly_ordered_entries(was) {
            return false;
        }
        for at in 0..now.count() {
            match (
                now.id_at(at),
                was.id_at(at),
                now.item_at(at),
                was.item_at(at),
            ) {
                (Some(id), Some(was_id), Some(item), Some(was_item))
                    if id == was_id
                        && (one_item(item, was_item)
                            || (desc.item.ops.stores_as)(desc.item, item, was_item)) => {}
                _ => return false,
            }
        }
        true
    },
    store_changed: |table, value, before, doc, slot, dirty| {
        let desc = listed(table)?;
        let now = (desc.entries)(value).ok_or_else(crate::table::mismatch)?;
        let was = (desc.entries)(before).ok_or_else(crate::table::mismatch)?;
        if now.needs_whole_write() {
            return (COLLECTION_OPS.store)(table, value, doc, slot);
        }
        let mut ids: Vec<&Id> = Vec::with_capacity(now.count());
        for at in 0..now.count() {
            if let Some(id) = now.id_at(at) {
                ids.push(id);
            }
        }
        let mut stored: Vec<(&Id, Option<&str>)> = Vec::with_capacity(was.count());
        for at in 0..was.count() {
            if let Some(id) = was.id_at(at) {
                stored.push((id, was.order_at(at)));
            }
        }
        let item = desc.item;
        store_entries_changed(
            doc,
            slot,
            &ids,
            &stored,
            dirty,
            &EntryWrites {
                same: &|at_now, at_was| match (now.item_at(at_now), was.item_at(at_was)) {
                    (Some(now), Some(was)) => {
                        one_item(now, was) || (item.ops.stores_as)(item, now, was)
                    }
                    _ => false,
                },
                created: &|at_now, doc, map, id, key, order_only| {
                    let Some(value) = now.item_at(at_now) else {
                        return Ok(None);
                    };
                    let made = TableItem { table: item, value };
                    let entry = put_entry(doc, map, id, key, order_only, &made)?;
                    if let Some(entry) = &entry {
                        let doc = &*doc;
                        note_stored(Slot::Key(entry, VALUE), &|value| {
                            shared_item(item, now, at_now, (doc, value))
                        });
                    }
                    Ok(entry)
                },
                changed: &|at_now, at_was, doc, entry, dirty| match (
                    now.item_at(at_now),
                    was.item_at(at_was),
                ) {
                    (Some(value), Some(before)) => crate::table::write_key_changed(
                        item,
                        (value, before),
                        doc,
                        entry,
                        VALUE,
                        dirty,
                    ),
                    _ => Ok(()),
                },
                whole: &|doc, slot| (COLLECTION_OPS.store)(table, value, doc, slot),
                order_only: order_only(item),
            },
        )
    },
    refresh: |table, target, doc, value, id, delta| {
        refresh_entries(listed(table)?, table, target, doc, (value, id), delta)
    },
    read_whole: |_, _, _| Ok(()),
    edit: |table, doc, slot, path, op, cx| {
        let desc = listed(table)?;
        let item = desc.item;
        edit_entries(
            doc,
            slot,
            path,
            op,
            cx,
            &EntryEdits {
                item: &|doc, slot, path, op, cx| (item.ops.edit)(item, doc, slot, path, op, cx),
                parse: &|value| {
                    let mut staged = (desc.item_staged.0)();
                    (item.ops.from_json)(item, value, staged.as_mut())?;
                    let made =
                        (desc.item_staged.1)(staged.as_ref()).ok_or_else(crate::table::mismatch)?;
                    (item.ops.check)(item, made).map_err(ModelError::refused)?;
                    Ok((
                        None,
                        Box::new(StagedItem {
                            table: item,
                            staged,
                            unstage: desc.item_staged.1,
                        }) as Box<dyn Stores + '_>,
                    ))
                },
                whole: &|doc, slot, path, op| {
                    let staged = ((desc.staged.0)(), desc.staged.1);
                    crate::table::edit_whole(table, staged, false, doc, slot, path, op)
                },
                order_only: order_only(item),
            },
        )
    },
    diff: |table, before, after, path, out| {
        let Some(desc) = table.collection() else {
            return;
        };
        let (Some(was), Some(now)) = ((desc.entries)(before), (desc.entries)(after)) else {
            return;
        };
        diff_entries(desc.item, (was, now), path, out);
    },
    collect_text: |table, value, out| {
        if let Some(desc) = table.collection()
            && let Some(entries) = (desc.entries)(value)
        {
            for at in 0..entries.count() {
                if let Some(item) = entries.item_at(at) {
                    (desc.item.ops.collect_text)(desc.item, item, out);
                }
            }
        }
    },
    check: |table, value| {
        let Some(desc) = table.collection() else {
            return Ok(());
        };
        if !desc.item.checks {
            return Ok(());
        }
        if let Some(entries) = (desc.entries)(value) {
            for at in 0..entries.count() {
                if let Some(item) = entries.item_at(at) {
                    (desc.item.ops.check)(desc.item, item)?;
                }
            }
        }
        Ok(())
    },
    get_at: |table, value, path| match path.split_first() {
        None => Some(value),
        Some((Segment::Item(id), rest)) => {
            let desc = table.collection()?;
            let entries = (desc.entries)(value)?;
            let item = entries.item_at(entries.find(id)?)?;
            (desc.item.ops.get_at)(desc.item, item, rest)
        }
        Some(_) => None,
    },
    label: crate::table::no_label,
    nested_collections: crate::table::no_nested,
    op_coalesces: |table, path, previous, next| match path.split_first() {
        Some((Segment::Item(_), rest)) if table.has_ops => {
            let item = table.collection()?.item;
            (item.ops.op_coalesces)(item, rest, previous, next)
        }
        _ => None,
    },
    op_continuable: |table, path, op| match path.split_first() {
        Some((Segment::Item(_), rest)) if table.has_ops => {
            let item = table.collection()?.item;
            (item.ops.op_continuable)(item, rest, op)
        }
        _ => None,
    },
    op_describe: |table, path, op| match path.split_first() {
        Some((Segment::Item(_), rest)) if table.has_ops => {
            let item = table.collection()?.item;
            (item.ops.op_describe)(item, rest, op)
        }
        _ => None,
    },
    op_lands: |table, value, path, op| match path.split_first() {
        Some((Segment::Item(id), rest)) if table.has_ops => {
            let desc = table.collection()?;
            let entries = (desc.entries)(value)?;
            let item = entries.item_at(entries.find(id)?)?;
            (desc.item.ops.op_lands)(desc.item, item, rest, op)
        }
        _ => None,
    },
    op_schemas: |table, prefix, out| {
        if table.has_ops
            && let Some(desc) = table.collection()
        {
            (desc.item.ops.op_schemas)(desc.item, &format!("{prefix}*."), out);
        }
    },
};

/// Whether two items are one item, which two clones of a collection still
/// share: it stores as it is without being compared, however its fields
/// compare (a value stored as JSON text compares only by writing it).
fn one_item(item: &dyn Any, other: &dyn Any) -> bool {
    std::ptr::addr_eq(item, other)
}

/// Whether every entry has a stored order key, each above the one before:
/// the keys a write keeps all of.
fn strictly_ordered_entries(entries: &dyn Entries) -> bool {
    let mut previous: Option<&str> = None;
    for at in 0..entries.count() {
        let Some(key) = entries.order_at(at) else {
            return false;
        };
        if let Some(previous) = previous
            && previous >= key
        {
            return false;
        }
        previous = Some(key);
    }
    true
}

/// The field edits that turn the entries `was` into `now` at `path`.
fn diff_entries(
    item: &ModelTable,
    (was, now): (&dyn Entries, &dyn Entries),
    path: &[Segment],
    out: &mut Vec<crate::Edit<()>>,
) {
    for at in 0..was.count() {
        let (Some(id), Some(before)) = (was.id_at(at), was.item_at(at)) else {
            continue;
        };
        match now.find(id).and_then(|position| now.item_at(position)) {
            // One item, which both still share: no edit.
            Some(next) if one_item(before, next) => {}
            Some(next) => {
                let mut path = path.to_vec();
                path.push(Segment::Item(id.clone()));
                (item.ops.diff)(item, before, next, &path, out);
            }
            None => out.push(crate::Edit::new(
                path.to_vec(),
                EditOp::RemoveItem { id: id.clone() },
            )),
        }
    }
    for index in 0..now.count() {
        let (Some(id), Some(next)) = (now.id_at(index), now.item_at(index)) else {
            continue;
        };
        match was.find(id) {
            Some(position) => {
                if position != index {
                    out.push(crate::Edit::new(
                        path.to_vec(),
                        EditOp::MoveTo {
                            id: id.clone(),
                            at: crate::At::Index(index),
                        },
                    ));
                }
            }
            None => out.push(crate::Edit::new(
                path.to_vec(),
                EditOp::InsertItem {
                    id: Some(id.clone()),
                    at: crate::At::Index(index),
                    value: (item.ops.to_json)(item, next),
                },
            )),
        }
    }
}

/// [`Model::refresh`] of a collection: read anew when changed all over or
/// edited in memory since it was read, else only the entries `delta`
/// touched.
#[allow(
    clippy::too_many_lines,
    reason = "one pass over the touched entries: read, place, order and quarantine share its state"
)]
fn refresh_entries(
    desc: &CollectionDesc,
    table: &ModelTable,
    target: &mut dyn Any,
    doc: &Doc,
    (value, id): (&Value<'_>, &ObjId),
    delta: &Delta,
) -> Result<(), ModelError> {
    let touched = delta.under(id);
    let unkeyed = {
        let entries = (desc.entries)(target).ok_or_else(crate::table::mismatch)?;
        (0..entries.count()).any(|at| entries.order_at(at).is_none())
    };
    // A collection edited in memory since it was read no longer knows
    // every stored order key; read it again rather than guess.
    if touched.is_all() || unkeyed {
        return (COLLECTION_OPS.reload)(table, target, doc, Some((value, id)));
    }
    let item = desc.item;
    let entries = (desc.entries_mut)(target).ok_or_else(crate::table::mismatch)?;
    let mut reorder = false;
    for key in touched.keys() {
        let item_id = Id(key.to_owned());
        let position = entries.find(&item_id);
        let below = touched.key(key) == Touch::Below && position.is_some();
        let touched_now = match touched_entry(doc, id, key, delta, below) {
            Ok(touched_now) => touched_now,
            Err(error) if quarantines(&error) => {
                if let Some(position) = position {
                    entries.remove_at(position);
                    entries.changed();
                }
                entries.quarantine(item_id, error.to_string());
                continue;
            }
            Err(error) => return Err(error),
        };
        match touched_now {
            Touched::Gone => {
                entries.release(&item_id);
                if let Some(position) = position {
                    entries.remove_at(position);
                    entries.changed();
                }
            }
            // Something inside an item already read: its order key, its value.
            Touched::Below { entry, order } => {
                if let Some(position) = position {
                    if order.is_some() {
                        entries.set_order(position, order);
                        reorder = true;
                    }
                    let refreshed = match entries.item_at_mut(position) {
                        Some(existing) => {
                            crate::table::refresh_slot(item, existing, doc, &entry, VALUE, delta)
                                .located(key)
                        }
                        None => Ok(()),
                    };
                    match refreshed {
                        Ok(()) => {}
                        // It no longer reads: out of the items, held for repair.
                        Err(error) if quarantines(&error) => {
                            entries.remove_at(position);
                            entries.changed();
                            entries.quarantine(item_id, error.to_string());
                        }
                        Err(error) => return Err(error),
                    }
                }
            }
            // An item stored as its order key: new, or moved.
            Touched::Order { order } => {
                if let Some(position) = position {
                    entries.set_order(position, Some(order));
                } else {
                    entries.push_filled(
                        (item_id, Some(order), false),
                        &mut |into: &mut dyn Any| {
                            crate::table::load_slot(item, doc, None, into)
                                .located(VALUE)
                                .located(key)
                        },
                    )?;
                    entries.changed();
                }
                reorder = true;
            }
            // A new item, or one whose entry was replaced.
            Touched::Fresh { entry, order } => {
                // Stored by the write this follows: taken as it was written.
                let shared = crate::apply_cache::take_stored(&entry, &mut |stored| {
                    entries.put_shared(position, (item_id.clone(), order.clone()), stored)
                });
                if shared {
                    entries.release(&item_id);
                    if position.is_none() {
                        entries.changed();
                    }
                    reorder = true;
                    continue;
                }
                let slot = crate::model::get_slot(doc, &entry, VALUE).located(key)?;
                let mut merged = false;
                let mut fill = |into: &mut dyn Any| -> Result<(), ModelError> {
                    let slot = slot.as_ref().map(|(v, i)| (v, i));
                    merged = fill_item(item, doc, (id, key), slot, into)
                        .located(VALUE)
                        .located(key)?;
                    Ok(())
                };
                let read = match position {
                    Some(position) => entries.replace_filled(position, Some(order), &mut fill),
                    None => entries.push_filled((item_id.clone(), Some(order), false), &mut fill),
                };
                match read {
                    Ok(()) => {
                        entries.release(&item_id);
                        let at = if position.is_some() {
                            position
                        } else {
                            entries.changed();
                            entries.count().checked_sub(1)
                        };
                        if merged && let Some(at) = at {
                            entries.set_order(at, None);
                        }
                    }
                    // It does not read: out of the items, held for repair.
                    Err(error) if quarantines(&error) => {
                        if let Some(position) = position {
                            entries.remove_at(position);
                            entries.changed();
                        }
                        entries.quarantine(item_id, error.to_string());
                    }
                    Err(error) => return Err(error),
                }
                reorder = true;
            }
        }
    }
    // A moved order key or a new entry: sorting may move items.
    if reorder {
        entries.reorder();
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::write_key;
    use automerge::ROOT;
    use tilo_automerge::ApplyIncoming;

    fn ids(collection: &Collection<String>) -> Vec<String> {
        collection.values().cloned().collect()
    }

    /// The collection read key by key: the oracle the one-walk read
    /// must equal, order keys included.
    fn read_key_by_key<T: Model>(doc: &Doc, map: &ObjId) -> Vec<(Id, Option<String>, T)> {
        let mut entries = Vec::new();
        for key in doc.keys(map) {
            let Some((Value::Object(ObjType::Map), entry)) = doc.get(map, key.as_str()).unwrap()
            else {
                continue;
            };
            let order: crate::Atom = read_key(doc, &entry, ORDER).unwrap();
            let item: T = read_key(doc, &entry, VALUE).unwrap();
            entries.push((Id(key), Some(order.0), item));
        }
        entries.compact_sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0)));
        entries
    }

    tilo_test_env::scenario! {
        fn a_stored_collection_reads_walks_and_moves_by_key;

        phase one_entry_reads_as_the_listing_has_it;
        {
            let mut doc = Doc::new();
            let mut list: Collection<u32> = Collection::new();
            for n in 0..20_u32 {
                list.push(Id::from_raw(format!("i{n:02}")), n);
            }
            write_key(&mut doc, &ROOT, "items", &list).unwrap();
            let Some((_, map)) = doc.get(&ROOT, "items").unwrap() else {
                panic!("the collection is stored");
            };
            for listed in stored_entries(&doc, &map) {
                let one = stored_entry(&doc, &map, listed.id.as_str()).expect("the entry");
                assert_eq!((one.id, one.key), (listed.id, listed.key));
            }
            assert!(stored_entry(&doc, &map, "nobody").is_none());
        }

        phase one_walk_reads_what_key_by_key_reads;
        {
            let mut doc = Doc::new();
            let mut list: Collection<Vec<i64>> = Collection::new();
            for n in 0..40 {
                list.push(Id::from_raw(format!("i{n:02}")), vec![n]);
            }
            write_key(&mut doc, &ROOT, "items", &list).unwrap();
            doc.commit();
            // History under every key: moved order keys, rewritten values, a
            // removed item, and a stray non-entry value beside the entries.
            for round in 0..3_i64 {
                list.move_to(&Id::from_raw(format!("i{:02}", 39 - round)), 0);
                if let Some(item) = list.get_mut(&Id::from_raw("i05")) {
                    item.push(round);
                }
                write_key(&mut doc, &ROOT, "items", &list).unwrap();
                doc.commit();
            }
            list.remove(&Id::from_raw("i07"));
            write_key(&mut doc, &ROOT, "items", &list).unwrap();
            let Some((_, map)) = doc.get(&ROOT, "items").unwrap() else {
                panic!("the collection is stored");
            };
            doc.put(&map, "stray", 1_i64).unwrap();
            doc.commit();
            // Concurrent moves and inserts from two actors: conflicting order keys.
            let mut left = doc.fork();
            let mut right = doc.fork();
            let read: Collection<Vec<i64>> = read_key(&doc, &ROOT, "items").unwrap();
            let mut l = read.clone();
            l.move_to(&Id::from_raw("i10"), 2);
            l.insert(3, Id::from_raw("left"), vec![-1]);
            write_key(&mut left, &ROOT, "items", &l).unwrap();
            let mut r = read;
            r.move_to(&Id::from_raw("i10"), 30);
            r.insert(3, Id::from_raw("right"), vec![-2]);
            write_key(&mut right, &ROOT, "items", &r).unwrap();
            left.merge_incoming(&mut right).unwrap();

            let Some((value, map)) = left.get(&ROOT, "items").unwrap() else {
                panic!("the collection is stored");
            };
            let read = Collection::<Vec<i64>>::load(&left, &value, &map).unwrap();
            let walked: Vec<_> = read
                .items
                .into_iter()
                .map(|entry| (entry.id, entry.key, (*entry.item).clone()))
                .collect();
            assert_eq!(walked, read_key_by_key::<Vec<i64>>(&left, &map));
            assert_eq!(walked.len(), 41);
        }

        phase moves_touch_one_key_and_concurrent_inserts_keep_both;
        {
            let mut doc = Doc::new();
            let mut list: Collection<String> = Collection::new();
            for (n, word) in ["a", "b", "c", "d"].iter().enumerate() {
                list.push(Id::from_raw(format!("i{n}")), (*word).to_owned());
            }
            write_key(&mut doc, &ROOT, "items", &list).unwrap();
            doc.commit();
            list.move_to(&Id::from_raw("i3"), 0);
            write_key(&mut doc, &ROOT, "items", &list).unwrap();
            // One order key rewritten.
            assert_eq!(doc.pending_ops(), 1);
            doc.commit();
            let read: Collection<String> = read_key(&doc, &ROOT, "items").unwrap();
            assert_eq!(ids(&read), ["d", "a", "b", "c"]);

            let mut left = doc.fork();
            let mut right = doc.fork();
            let mut l = read.clone();
            l.insert(1, Id::from_raw("left"), "L".into());
            write_key(&mut left, &ROOT, "items", &l).unwrap();
            let mut r = read;
            r.insert(1, Id::from_raw("right"), "R".into());
            r.remove(&Id::from_raw("i1"));
            write_key(&mut right, &ROOT, "items", &r).unwrap();
            left.merge_incoming(&mut right).unwrap();
            let merged: Collection<String> = read_key(&left, &ROOT, "items").unwrap();
            let merged = ids(&merged);
            assert_eq!(merged.len(), 5);
            assert_eq!(merged.first().map(String::as_str), Some("d"));
            assert!(merged.contains(&"L".to_owned()) && merged.contains(&"R".to_owned()));
            assert!(!merged.contains(&"b".to_owned()));
        }
    }

    #[test]
    fn appended_items_keep_short_order_keys() {
        // One push per action, as a list someone adds to item by item, and a
        // bulk push: either way the stored keys stay a few characters long
        // (they grew by one character every ~6 items).
        let mut doc = Doc::new();
        let mut list: Collection<u32> = Collection::new();
        for n in 0..300_u32 {
            list.push(Id::from_raw(format!("one{n:05}")), n);
            write_key(&mut doc, &ROOT, "items", &list).unwrap();
            list = read_key(&doc, &ROOT, "items").unwrap();
        }
        for n in 0..10_000_u32 {
            list.push(Id::from_raw(format!("bulk{n:05}")), n);
        }
        write_key(&mut doc, &ROOT, "items", &list).unwrap();
        let Some((_, map)) = doc.get(&ROOT, "items").unwrap() else {
            panic!("the collection is stored");
        };
        let stored = stored_entries(&doc, &map);
        assert_eq!(stored.len(), 10_300);
        let longest = stored.iter().map(|entry| entry.key.len()).max().unwrap();
        assert!(longest <= 5, "longest order key: {longest} characters");
        let read: Collection<u32> = read_key(&doc, &ROOT, "items").unwrap();
        assert!(read.values().copied().eq((0..300).chain(0..10_000)));
    }
}