icydb-core 0.98.1

IcyDB — A schema-first typed query engine and persistence runtime for Internet Computer canisters
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
//! Module: db::executor::tests::mutation_save
//! Covers save and mutation execution behavior in the executor layer.
//! Does not own: cross-module orchestration outside this module.
//! Boundary: exposes this module API while keeping implementation details internal.

use crate::{
    db::{
        Db, DbSession, EntityRuntimeHooks,
        codec::serialize_row_payload,
        commit::{
            CommitRowOp, commit_marker_present, ensure_recovered, init_commit_store_for_tests,
            prepare_row_commit_for_entity_with_structural_readers,
        },
        data::{
            CanonicalRow, DataKey, DataStore, RawRow, UpdatePatch,
            decode_persisted_custom_many_slot_payload, decode_persisted_scalar_slot_payload,
            encode_persisted_custom_many_slot_payload, encode_persisted_scalar_slot_payload,
        },
        executor::{
            DeleteExecutor, SaveExecutor,
            mutation::commit_window::{
                OpenCommitWindow, apply_prepared_row_ops, open_commit_window,
            },
        },
        index::IndexStore,
        predicate::MissingRowPolicy,
        query::intent::Query,
        registry::StoreRegistry,
        relation::{validate_delete_strong_relations_for_source, validate_save_strong_relations},
        schema::commit_schema_fingerprint_for_entity,
    },
    error::{ErrorClass, ErrorOrigin},
    metrics::{metrics_report, metrics_reset_all},
    model::{
        field::{FieldKind, FieldStorageDecode, RelationStrength},
        index::IndexModel,
    },
    testing::test_memory,
    traits::{EntityKind, EntitySchema, FieldValue, FieldValueKind, Path},
    types::{Account, Decimal, EntityTag, Id, Ulid},
    value::Value,
};
use icydb_derive::{FieldProjection, PersistedRow};
use serde::Deserialize;
use std::{
    cell::RefCell,
    collections::{BTreeMap, BTreeSet},
};

// TestCanister

crate::test_canister! {
    ident = TestCanister,
    commit_memory_id = crate::testing::test_commit_memory_id(),
}

// SourceStore

crate::test_store! {
    ident = SourceStore,
    canister = TestCanister,
}

// TargetStore

crate::test_store! {
    ident = TargetStore,
    canister = TestCanister,
}

const UNIQUE_INDEX_STORE_PATH: &str = SourceStore::PATH;

thread_local! {
    static SOURCE_DATA_STORE: RefCell<DataStore> =
        RefCell::new(DataStore::init(test_memory(0)));
    static TARGET_DATA_STORE: RefCell<DataStore> =
        RefCell::new(DataStore::init(test_memory(1)));
    static UNIQUE_INDEX_STORE: RefCell<IndexStore> =
        RefCell::new(IndexStore::init(test_memory(2)));
    static TARGET_INDEX_STORE: RefCell<IndexStore> =
        RefCell::new(IndexStore::init(test_memory(3)));
    static STORE_REGISTRY: StoreRegistry = {
        let mut reg = StoreRegistry::new();
        reg.register_store(SourceStore::PATH, &SOURCE_DATA_STORE, &UNIQUE_INDEX_STORE)
            .expect("source store registration should succeed");
        reg.register_store(TargetStore::PATH, &TARGET_DATA_STORE, &TARGET_INDEX_STORE)
            .expect("target store registration should succeed");
        reg
    };
}

fn with_data_store<R>(path: &'static str, f: impl FnOnce(&DataStore) -> R) -> R {
    DB.with_store_registry(|reg| reg.try_get_store(path).map(|store| store.with_data(f)))
        .expect("data store access should succeed")
}

fn with_data_store_mut<R>(path: &'static str, f: impl FnOnce(&mut DataStore) -> R) -> R {
    DB.with_store_registry(|reg| reg.try_get_store(path).map(|store| store.with_data_mut(f)))
        .expect("data store access should succeed")
}

fn with_index_store_mut<R>(path: &'static str, f: impl FnOnce(&mut IndexStore) -> R) -> R {
    DB.with_store_registry(|reg| reg.try_get_store(path).map(|store| store.with_index_mut(f)))
        .expect("index store access should succeed")
}

fn with_index_store<R>(path: &'static str, f: impl FnOnce(&IndexStore) -> R) -> R {
    DB.with_store_registry(|reg| reg.try_get_store(path).map(|store| store.with_index(f)))
        .expect("index store access should succeed")
}

// Clear test stores and ensure recovery has completed before each test mutation.
fn reset_store() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    ensure_recovered(&DB).expect("write-side recovery should succeed");
    with_data_store_mut(SourceStore::PATH, DataStore::clear);
    with_data_store_mut(TargetStore::PATH, DataStore::clear);
    with_index_store_mut(UNIQUE_INDEX_STORE_PATH, IndexStore::clear);
    with_index_store_mut(TargetStore::PATH, IndexStore::clear);
}

///
/// TargetEntity
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
struct TargetEntity {
    id: Ulid,
}

crate::test_entity_schema! {
    ident = TargetEntity,
    id = Ulid,
    id_field = id,
    entity_name = "TargetEntity",
    entity_tag = crate::testing::TARGET_ENTITY_TAG,
    pk_index = 0,
    fields = [("id", FieldKind::Ulid)],
    indexes = [],
    store = TargetStore,
    canister = TestCanister,
}

///
/// SourceEntity
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
struct SourceEntity {
    id: Ulid,
    target: Ulid,
}

crate::test_entity_schema! {
    ident = SourceEntity,
    id = Ulid,
    id_field = id,
    entity_name = "SourceEntity",
    entity_tag = crate::testing::SOURCE_ENTITY_TAG,
    pk_index = 0,
    fields = [
        ("id", FieldKind::Ulid),
        (
            "target",
            FieldKind::Relation {
                target_path: TargetEntity::PATH,
                target_entity_name:
                    <TargetEntity as crate::traits::EntitySchema>::MODEL.name(),
                target_entity_tag: TargetEntity::ENTITY_TAG,
                target_store_path: TargetStore::PATH,
                key_kind: &FieldKind::Ulid,
                strength: RelationStrength::Strong,
            }
        ),
    ],
    indexes = [],
    store = SourceStore,
    canister = TestCanister,
}

///
/// InvalidRelationMetadataEntity
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
struct InvalidRelationMetadataEntity {
    id: Ulid,
    target: Ulid,
}

crate::test_entity_schema! {
    ident = InvalidRelationMetadataEntity,
    id = Ulid,
    id_field = id,
    entity_name = "InvalidRelationMetadataEntity",
    entity_tag = crate::testing::INVALID_RELATION_METADATA_ENTITY_TAG,
    pk_index = 0,
    fields = [
        ("id", FieldKind::Ulid),
        (
            "target",
            FieldKind::Relation {
                target_path: TargetEntity::PATH,
                target_entity_name: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                target_entity_tag: TargetEntity::ENTITY_TAG,
                target_store_path: TargetStore::PATH,
                key_kind: &FieldKind::Ulid,
                strength: RelationStrength::Strong,
            }
        ),
    ],
    indexes = [],
    store = SourceStore,
    canister = TestCanister,
}

///
/// SourceSetEntity
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
struct SourceSetEntity {
    id: Ulid,
    targets: Vec<Ulid>,
}

static SOURCE_SET_TARGET_KIND: FieldKind = FieldKind::Relation {
    target_path: TargetEntity::PATH,
    target_entity_name: <TargetEntity as crate::traits::EntitySchema>::MODEL.name(),
    target_entity_tag: TargetEntity::ENTITY_TAG,
    target_store_path: TargetStore::PATH,
    key_kind: &FieldKind::Ulid,
    strength: RelationStrength::Strong,
};

crate::test_entity_schema! {
    ident = SourceSetEntity,
    id = Ulid,
    id_field = id,
    entity_name = "SourceSetEntity",
    entity_tag = crate::testing::SOURCE_SET_ENTITY_TAG,
    pk_index = 0,
    fields = [
        ("id", FieldKind::Ulid),
        ("targets", FieldKind::Set(&SOURCE_SET_TARGET_KIND)),
    ],
    indexes = [],
    store = SourceStore,
    canister = TestCanister,
}

///
/// SaveSelectedPart
///
/// SaveSelectedPart mirrors one nested record payload stored inside a queryable
/// collection field so save preflight can prove it accepts structured leaves
/// during typed writes instead of treating them as predicate literals.
///

#[derive(Clone, Debug, Default, Deserialize, Eq, Ord, PartialEq, PartialOrd)]
struct SaveSelectedPart {
    layer_id: Ulid,
    part_id: Ulid,
}

impl FieldValue for SaveSelectedPart {
    fn kind() -> FieldValueKind {
        FieldValueKind::Structured { queryable: false }
    }

    fn to_value(&self) -> Value {
        Value::from_map(vec![
            (
                Value::Text("layer_id".to_string()),
                Value::Ulid(self.layer_id),
            ),
            (
                Value::Text("part_id".to_string()),
                Value::Ulid(self.part_id),
            ),
        ])
        .expect("selected part map should be canonical")
    }

    fn from_value(value: &Value) -> Option<Self> {
        let Value::Map(entries) = value else {
            return None;
        };
        let normalized = Value::normalize_map_entries(entries.clone()).ok()?;
        if normalized.len() != 2 {
            return None;
        }

        let layer_id = normalized
            .iter()
            .find_map(|(entry_key, entry_value)| match entry_key {
                Value::Text(entry_key) if entry_key == "layer_id" => Some(entry_value),
                _ => None,
            })?;
        let part_id = normalized
            .iter()
            .find_map(|(entry_key, entry_value)| match entry_key {
                Value::Text(entry_key) if entry_key == "part_id" => Some(entry_value),
                _ => None,
            })?;

        Some(Self {
            layer_id: Ulid::from_value(layer_id)?,
            part_id: Ulid::from_value(part_id)?,
        })
    }
}

///
/// StructuredSelectionEntity
///
/// StructuredSelectionEntity keeps one repeated record field on the executor
/// test surface so typed save preflight can exercise the same `Vec<Record>`
/// contract that application entities use for `selected_parts`.
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq)]
struct StructuredSelectionEntity {
    id: Ulid,
    selected_parts: Vec<SaveSelectedPart>,
}

const STRUCTURED_SELECTION_ENTITY_TAG: EntityTag = EntityTag::new(0x1034);

static STRUCTURED_SELECTED_PART_KIND: FieldKind = FieldKind::Structured { queryable: false };

crate::test_entity_schema! {
    ident = StructuredSelectionEntity,
    id = Ulid,
    id_field = id,
    entity_name = "StructuredSelectionEntity",
    entity_tag = STRUCTURED_SELECTION_ENTITY_TAG,
    pk_index = 0,
    fields = [
        ("id", FieldKind::Ulid),
        (
            "selected_parts",
            FieldKind::List(&STRUCTURED_SELECTED_PART_KIND),
            FieldStorageDecode::Value
        ),
    ],
    indexes = [],
    store = SourceStore,
    canister = TestCanister,
}

impl crate::db::PersistedRow for StructuredSelectionEntity {
    fn materialize_from_slots(
        slots: &mut dyn crate::db::SlotReader,
    ) -> Result<Self, crate::error::InternalError> {
        Ok(Self {
            id: match slots.get_bytes(0) {
                Some(bytes) => decode_persisted_scalar_slot_payload::<Ulid>(bytes, "id")?,
                None => return Err(crate::error::InternalError::missing_persisted_slot("id")),
            },
            selected_parts: match slots.get_bytes(1) {
                Some(bytes) => decode_persisted_custom_many_slot_payload::<SaveSelectedPart>(
                    bytes,
                    "selected_parts",
                )?,
                None => {
                    return Err(crate::error::InternalError::missing_persisted_slot(
                        "selected_parts",
                    ));
                }
            },
        })
    }

    fn write_slots(
        &self,
        out: &mut dyn crate::db::SlotWriter,
    ) -> Result<(), crate::error::InternalError> {
        let id_payload = encode_persisted_scalar_slot_payload(&self.id, "id")?;
        out.write_slot(0, Some(id_payload.as_slice()))?;

        let selected_parts_payload =
            encode_persisted_custom_many_slot_payload(&self.selected_parts, "selected_parts")?;
        out.write_slot(1, Some(selected_parts_payload.as_slice()))?;

        Ok(())
    }
}

fn load_structured_selection_entity(id: Ulid) -> Option<StructuredSelectionEntity> {
    let data_key = DataKey::try_new::<StructuredSelectionEntity>(id)
        .expect("structured selection data key should build")
        .to_raw()
        .expect("structured selection data key should encode");

    with_data_store(SourceStore::PATH, |data_store| {
        data_store.get(&data_key).map(|row| {
            row.try_decode::<StructuredSelectionEntity>()
                .expect("structured selection row decode should succeed")
        })
    })
}

///
/// SaveSelectedPartSet
///
/// SaveSelectedPartSet mirrors one generated set wrapper type so executor
/// tests can prove non-empty `Set<Record>` writes persist and reload through
/// the same typed save boundary as application entities.
///

#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
struct SaveSelectedPartSet(BTreeSet<SaveSelectedPart>);

impl FieldValue for SaveSelectedPartSet {
    fn kind() -> FieldValueKind {
        FieldValueKind::Structured { queryable: true }
    }

    fn to_value(&self) -> Value {
        Value::List(self.0.iter().map(FieldValue::to_value).collect())
    }

    fn from_value(value: &Value) -> Option<Self> {
        let Value::List(values) = value else {
            return None;
        };

        let mut out = BTreeSet::new();
        for value in values {
            if !out.insert(SaveSelectedPart::from_value(value)?) {
                return None;
            }
        }

        Some(Self(out))
    }
}

///
/// StructuredSelectionSetEntity
///
/// StructuredSelectionSetEntity keeps one set-valued structured field on the
/// executor test surface so save coverage now includes `Set<Record>` as well
/// as `List<Record>` and `Map<..., Record>`.
///

#[derive(Clone, Debug, Default, Deserialize, Eq, FieldProjection, PartialEq)]
struct StructuredSelectionSetEntity {
    id: Ulid,
    selected_parts: SaveSelectedPartSet,
}

const STRUCTURED_SELECTION_SET_ENTITY_TAG: EntityTag = EntityTag::new(0x1036);

static STRUCTURED_SELECTION_SET_KIND: FieldKind = FieldKind::Set(&STRUCTURED_SELECTED_PART_KIND);

crate::test_entity_schema! {
    ident = StructuredSelectionSetEntity,
    id = Ulid,
    id_field = id,
    entity_name = "StructuredSelectionSetEntity",
    entity_tag = STRUCTURED_SELECTION_SET_ENTITY_TAG,
    pk_index = 0,
    fields = [
        ("id", FieldKind::Ulid),
        (
            "selected_parts",
            STRUCTURED_SELECTION_SET_KIND,
            FieldStorageDecode::Value
        ),
    ],
    indexes = [],
    store = SourceStore,
    canister = TestCanister,
}

impl crate::db::PersistedRow for StructuredSelectionSetEntity {
    fn materialize_from_slots(
        slots: &mut dyn crate::db::SlotReader,
    ) -> Result<Self, crate::error::InternalError> {
        Ok(Self {
            id: match slots.get_bytes(0) {
                Some(bytes) => decode_persisted_scalar_slot_payload::<Ulid>(bytes, "id")?,
                None => return Err(crate::error::InternalError::missing_persisted_slot("id")),
            },
            selected_parts: match slots.get_bytes(1) {
                Some(bytes) => crate::db::decode_persisted_custom_slot_payload::<
                    SaveSelectedPartSet,
                >(bytes, "selected_parts")?,
                None => {
                    return Err(crate::error::InternalError::missing_persisted_slot(
                        "selected_parts",
                    ));
                }
            },
        })
    }

    fn write_slots(
        &self,
        out: &mut dyn crate::db::SlotWriter,
    ) -> Result<(), crate::error::InternalError> {
        let id_payload = encode_persisted_scalar_slot_payload(&self.id, "id")?;
        out.write_slot(0, Some(id_payload.as_slice()))?;

        let selected_parts_payload = crate::db::encode_persisted_custom_slot_payload(
            &self.selected_parts,
            "selected_parts",
        )?;
        out.write_slot(1, Some(selected_parts_payload.as_slice()))?;

        Ok(())
    }
}

fn load_structured_selection_set_entity(id: Ulid) -> Option<StructuredSelectionSetEntity> {
    let data_key = DataKey::try_new::<StructuredSelectionSetEntity>(id)
        .expect("structured selection set data key should build")
        .to_raw()
        .expect("structured selection set data key should encode");

    with_data_store(SourceStore::PATH, |data_store| {
        data_store.get(&data_key).map(|row| {
            row.try_decode::<StructuredSelectionSetEntity>()
                .expect("structured selection set row decode should succeed")
        })
    })
}

///
/// SaveSelectedPartMap
///
/// SaveSelectedPartMap mirrors one generated map wrapper type so executor tests
/// can prove map-valued typed writes survive the full save path and persist
/// with the expected canonical `Value::Map` payload shape.
///

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
struct SaveSelectedPartMap(BTreeMap<Ulid, SaveSelectedPart>);

impl FieldValue for SaveSelectedPartMap {
    fn kind() -> FieldValueKind {
        FieldValueKind::Structured { queryable: false }
    }

    fn to_value(&self) -> Value {
        let mut entries = self
            .0
            .iter()
            .map(|(key, value)| (Value::Ulid(*key), value.to_value()))
            .collect::<Vec<_>>();

        Value::sort_map_entries_in_place(entries.as_mut_slice());

        Value::Map(entries)
    }

    fn from_value(value: &Value) -> Option<Self> {
        let Value::Map(entries) = value else {
            return None;
        };

        let normalized = Value::normalize_map_entries(entries.clone()).ok()?;
        let mut out = BTreeMap::new();
        for (entry_key, entry_value) in normalized {
            out.insert(
                Ulid::from_value(&entry_key)?,
                SaveSelectedPart::from_value(&entry_value)?,
            );
        }

        Some(Self(out))
    }
}

///
/// StructuredSelectionMapEntity
///
/// StructuredSelectionMapEntity keeps one map-valued field on the executor
/// test surface so save tests cover the actual write boundary used for
/// persisted `Map<..., ...>` fields.
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq)]
struct StructuredSelectionMapEntity {
    id: Ulid,
    selected_parts_by_layer: SaveSelectedPartMap,
}

const STRUCTURED_SELECTION_MAP_ENTITY_TAG: EntityTag = EntityTag::new(0x1035);

static STRUCTURED_SELECTION_MAP_KIND: FieldKind = FieldKind::Map {
    key: &FieldKind::Ulid,
    value: &STRUCTURED_SELECTED_PART_KIND,
};

crate::test_entity_schema! {
    ident = StructuredSelectionMapEntity,
    id = Ulid,
    id_field = id,
    entity_name = "StructuredSelectionMapEntity",
    entity_tag = STRUCTURED_SELECTION_MAP_ENTITY_TAG,
    pk_index = 0,
    fields = [
        ("id", FieldKind::Ulid),
        (
            "selected_parts_by_layer",
            STRUCTURED_SELECTION_MAP_KIND,
            FieldStorageDecode::Value
        ),
    ],
    indexes = [],
    store = SourceStore,
    canister = TestCanister,
}

impl crate::db::PersistedRow for StructuredSelectionMapEntity {
    fn materialize_from_slots(
        slots: &mut dyn crate::db::SlotReader,
    ) -> Result<Self, crate::error::InternalError> {
        Ok(Self {
            id: match slots.get_bytes(0) {
                Some(bytes) => decode_persisted_scalar_slot_payload::<Ulid>(bytes, "id")?,
                None => return Err(crate::error::InternalError::missing_persisted_slot("id")),
            },
            selected_parts_by_layer: match slots.get_bytes(1) {
                Some(bytes) => crate::db::decode_persisted_custom_slot_payload::<
                    SaveSelectedPartMap,
                >(bytes, "selected_parts_by_layer")?,
                None => {
                    return Err(crate::error::InternalError::missing_persisted_slot(
                        "selected_parts_by_layer",
                    ));
                }
            },
        })
    }

    fn write_slots(
        &self,
        out: &mut dyn crate::db::SlotWriter,
    ) -> Result<(), crate::error::InternalError> {
        let id_payload = encode_persisted_scalar_slot_payload(&self.id, "id")?;
        out.write_slot(0, Some(id_payload.as_slice()))?;

        let selected_parts_by_layer_payload = crate::db::encode_persisted_custom_slot_payload(
            &self.selected_parts_by_layer,
            "selected_parts_by_layer",
        )?;
        out.write_slot(1, Some(selected_parts_by_layer_payload.as_slice()))?;

        Ok(())
    }
}

fn load_structured_selection_map_entity(id: Ulid) -> Option<StructuredSelectionMapEntity> {
    let data_key = DataKey::try_new::<StructuredSelectionMapEntity>(id)
        .expect("structured selection map data key should build")
        .to_raw()
        .expect("structured selection map data key should encode");

    with_data_store(SourceStore::PATH, |data_store| {
        data_store.get(&data_key).map(|row| {
            row.try_decode::<StructuredSelectionMapEntity>()
                .expect("structured selection map row decode should succeed")
        })
    })
}

///
/// UniqueEmailEntity
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
struct UniqueEmailEntity {
    id: Ulid,
    email: String,
}

static UNIQUE_EMAIL_INDEX_FIELDS: [&str; 1] = ["email"];
static UNIQUE_EMAIL_INDEX: IndexModel = IndexModel::generated(
    "save_tests::UniqueEmailEntity::email",
    UNIQUE_INDEX_STORE_PATH,
    &UNIQUE_EMAIL_INDEX_FIELDS,
    true,
);

crate::test_entity_schema! {
    ident = UniqueEmailEntity,
    id = Ulid,
    id_field = id,
    entity_name = "UniqueEmailEntity",
    entity_tag = crate::testing::UNIQUE_EMAIL_ENTITY_TAG,
    pk_index = 0,
    fields = [("id", FieldKind::Ulid), ("email", FieldKind::Text)],
    indexes = [&UNIQUE_EMAIL_INDEX],
    store = SourceStore,
    canister = TestCanister,
}

fn load_unique_email_entity(id: Ulid) -> Option<UniqueEmailEntity> {
    let data_key = DataKey::try_new::<UniqueEmailEntity>(id)
        .expect("unique email data key should build")
        .to_raw()
        .expect("unique email data key should encode");

    with_data_store(SourceStore::PATH, |data_store| {
        data_store.get(&data_key).map(|row| {
            row.try_decode::<UniqueEmailEntity>()
                .expect("unique email row decode should succeed")
        })
    })
}

fn unique_email_patch(id: Ulid, email: &str) -> UpdatePatch {
    UpdatePatch::new()
        .set_field(UniqueEmailEntity::MODEL, "id", Value::Ulid(id))
        .expect("resolve id slot")
        .set_field(
            UniqueEmailEntity::MODEL,
            "email",
            Value::Text(email.to_string()),
        )
        .expect("resolve email slot")
}

fn load_source_set_entity(id: Ulid) -> Option<SourceSetEntity> {
    let data_key = DataKey::try_new::<SourceSetEntity>(id)
        .expect("source-set data key should build")
        .to_raw()
        .expect("source-set data key should encode");

    with_data_store(SourceStore::PATH, |data_store| {
        data_store.get(&data_key).map(|row| {
            row.try_decode::<SourceSetEntity>()
                .expect("source-set row decode should succeed")
        })
    })
}

fn load_nullable_account_event_entity(id: Ulid) -> Option<NullableAccountEventEntity> {
    let data_key = DataKey::try_new::<NullableAccountEventEntity>(id)
        .expect("nullable account event data key should build")
        .to_raw()
        .expect("nullable account event data key should encode");

    with_data_store(SourceStore::PATH, |data_store| {
        data_store.get(&data_key).map(|row| {
            row.try_decode::<NullableAccountEventEntity>()
                .expect("nullable account event row decode should succeed")
        })
    })
}

///
/// MismatchedPkEntity
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
struct MismatchedPkEntity {
    id: Ulid,
    actual_id: Ulid,
}

crate::test_entity_schema! {
    ident = MismatchedPkEntity,
    id = Ulid,
    id_field = actual_id,
    entity_name = "MismatchedPkEntity",
    entity_tag = crate::testing::MISMATCHED_PK_ENTITY_TAG,
    pk_index = 0,
    fields = [("id", FieldKind::Ulid), ("actual_id", FieldKind::Ulid)],
    indexes = [],
    store = SourceStore,
    canister = TestCanister,
}

///
/// DecimalScaleEntity
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
struct DecimalScaleEntity {
    id: Ulid,
    #[icydb(scale = 2)]
    amount: Decimal,
}

crate::test_entity_schema! {
    ident = DecimalScaleEntity,
    id = Ulid,
    id_field = id,
    entity_name = "DecimalScaleEntity",
    entity_tag = crate::testing::DECIMAL_SCALE_ENTITY_TAG,
    pk_index = 0,
    fields = [
        ("id", FieldKind::Ulid),
        ("amount", FieldKind::Decimal { scale: 2 }),
    ],
    indexes = [],
    store = SourceStore,
    canister = TestCanister,
}

///
/// NullableAccountEventEntity
///

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq, PersistedRow)]
struct NullableAccountEventEntity {
    id: Ulid,
    from: Option<Account>,
    to: Option<Account>,
}

crate::impl_test_entity_markers!(NullableAccountEventEntity);

crate::impl_test_entity_model_storage!(
    NullableAccountEventEntity,
    "NullableAccountEventEntity",
    0,
    fields = [
        crate::model::field::FieldModel::generated("id", FieldKind::Ulid),
        crate::model::field::FieldModel::generated_with_storage_decode_and_nullability(
            "from",
            FieldKind::Account,
            crate::model::field::FieldStorageDecode::ByKind,
            true,
        ),
        crate::model::field::FieldModel::generated_with_storage_decode_and_nullability(
            "to",
            FieldKind::Account,
            crate::model::field::FieldStorageDecode::ByKind,
            true,
        )
    ],
    indexes = [],
);

crate::impl_test_entity_runtime_surface!(
    NullableAccountEventEntity,
    Ulid,
    "NullableAccountEventEntity",
    MODEL_DEF
);

impl crate::traits::EntityPlacement for NullableAccountEventEntity {
    type Store = SourceStore;
    type Canister = TestCanister;
}

impl EntityKind for NullableAccountEventEntity {
    const ENTITY_TAG: EntityTag = crate::testing::NULLABLE_ACCOUNT_EVENT_ENTITY_TAG;
}

impl crate::traits::EntityValue for NullableAccountEventEntity {
    fn id(&self) -> Id<Self> {
        Id::from_key(self.id)
    }
}

static ENTITY_RUNTIME_HOOKS: &[EntityRuntimeHooks<TestCanister>] = &[
    EntityRuntimeHooks::new(
        TargetEntity::ENTITY_TAG,
        <TargetEntity as crate::traits::EntitySchema>::MODEL,
        TargetEntity::PATH,
        TargetStore::PATH,
        prepare_row_commit_for_entity_with_structural_readers::<TargetEntity>,
        validate_delete_strong_relations_for_source::<TargetEntity>,
    ),
    EntityRuntimeHooks::new(
        SourceEntity::ENTITY_TAG,
        <SourceEntity as crate::traits::EntitySchema>::MODEL,
        SourceEntity::PATH,
        SourceStore::PATH,
        prepare_row_commit_for_entity_with_structural_readers::<SourceEntity>,
        validate_delete_strong_relations_for_source::<SourceEntity>,
    ),
    EntityRuntimeHooks::new(
        InvalidRelationMetadataEntity::ENTITY_TAG,
        <InvalidRelationMetadataEntity as crate::traits::EntitySchema>::MODEL,
        InvalidRelationMetadataEntity::PATH,
        SourceStore::PATH,
        prepare_row_commit_for_entity_with_structural_readers::<InvalidRelationMetadataEntity>,
        validate_delete_strong_relations_for_source::<InvalidRelationMetadataEntity>,
    ),
    EntityRuntimeHooks::new(
        SourceSetEntity::ENTITY_TAG,
        <SourceSetEntity as crate::traits::EntitySchema>::MODEL,
        SourceSetEntity::PATH,
        SourceStore::PATH,
        prepare_row_commit_for_entity_with_structural_readers::<SourceSetEntity>,
        validate_delete_strong_relations_for_source::<SourceSetEntity>,
    ),
    EntityRuntimeHooks::new(
        UniqueEmailEntity::ENTITY_TAG,
        <UniqueEmailEntity as crate::traits::EntitySchema>::MODEL,
        UniqueEmailEntity::PATH,
        SourceStore::PATH,
        prepare_row_commit_for_entity_with_structural_readers::<UniqueEmailEntity>,
        validate_delete_strong_relations_for_source::<UniqueEmailEntity>,
    ),
    EntityRuntimeHooks::new(
        MismatchedPkEntity::ENTITY_TAG,
        <MismatchedPkEntity as crate::traits::EntitySchema>::MODEL,
        MismatchedPkEntity::PATH,
        SourceStore::PATH,
        prepare_row_commit_for_entity_with_structural_readers::<MismatchedPkEntity>,
        validate_delete_strong_relations_for_source::<MismatchedPkEntity>,
    ),
    EntityRuntimeHooks::new(
        DecimalScaleEntity::ENTITY_TAG,
        <DecimalScaleEntity as crate::traits::EntitySchema>::MODEL,
        DecimalScaleEntity::PATH,
        SourceStore::PATH,
        prepare_row_commit_for_entity_with_structural_readers::<DecimalScaleEntity>,
        validate_delete_strong_relations_for_source::<DecimalScaleEntity>,
    ),
    EntityRuntimeHooks::new(
        NullableAccountEventEntity::ENTITY_TAG,
        <NullableAccountEventEntity as crate::traits::EntitySchema>::MODEL,
        NullableAccountEventEntity::PATH,
        SourceStore::PATH,
        prepare_row_commit_for_entity_with_structural_readers::<NullableAccountEventEntity>,
        validate_delete_strong_relations_for_source::<NullableAccountEventEntity>,
    ),
];

static DB: Db<TestCanister> = Db::new_with_hooks(&STORE_REGISTRY, ENTITY_RUNTIME_HOOKS);

#[test]
fn strong_relation_missing_fails_preflight() {
    let entity = SourceEntity {
        id: Ulid::generate(),
        target: Ulid::generate(), // non-existent target
    };

    let err = validate_save_strong_relations::<SourceEntity>(&DB, &entity)
        .expect_err("expected missing strong relation to fail");

    assert_eq!(
        err.class,
        ErrorClass::Unsupported,
        "missing strong relation should classify as unsupported",
    );
    assert_eq!(
        err.origin,
        ErrorOrigin::Executor,
        "missing strong relation should originate from executor validation",
    );
    assert!(
        err.message.contains("strong relation missing"),
        "unexpected error: {err:?}"
    );
}

#[test]
fn strong_relation_invalid_metadata_fails_internal() {
    let entity = InvalidRelationMetadataEntity {
        id: Ulid::generate(),
        target: Ulid::generate(),
    };

    let err = validate_save_strong_relations::<InvalidRelationMetadataEntity>(&DB, &entity)
        .expect_err("invalid relation metadata should fail deterministic preflight");
    assert_eq!(
        err.class,
        ErrorClass::Internal,
        "invalid relation metadata should classify as internal",
    );
    assert_eq!(
        err.origin,
        ErrorOrigin::Executor,
        "invalid relation metadata should originate from executor boundary",
    );
    assert!(
        err.message.contains("strong relation target name invalid"),
        "unexpected error: {err:?}",
    );
}

#[test]
fn strong_set_relation_missing_key_fails_save() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let executor = SaveExecutor::<SourceSetEntity>::new(DB, false);
    let missing = Ulid::generate();
    let entity = SourceSetEntity {
        id: Ulid::generate(),
        targets: vec![missing],
    };

    let err = executor
        .insert(entity)
        .expect_err("missing set relation should fail");
    assert_eq!(
        err.class,
        ErrorClass::Unsupported,
        "missing set relation should classify as unsupported",
    );
    assert_eq!(
        err.origin,
        ErrorOrigin::Executor,
        "missing set relation should originate from executor validation",
    );
    assert!(
        err.message.contains("strong relation missing"),
        "unexpected error: {err:?}"
    );

    let source_empty = with_data_store(SourceStore::PATH, |data_store| {
        data_store.iter().next().is_none()
    });
    assert!(
        source_empty,
        "source store must remain empty after failed save"
    );
}

#[test]
fn strong_set_relation_all_present_save_succeeds() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let target_save = SaveExecutor::<TargetEntity>::new(DB, false);
    let target_a = Ulid::generate();
    let target_b = Ulid::generate();
    target_save
        .insert(TargetEntity { id: target_a })
        .expect("target A save should succeed");
    target_save
        .insert(TargetEntity { id: target_b })
        .expect("target B save should succeed");

    let source_save = SaveExecutor::<SourceSetEntity>::new(DB, false);
    let saved = source_save
        .insert(SourceSetEntity {
            id: Ulid::generate(),
            targets: vec![target_a, target_b],
        })
        .expect("source save should succeed when all targets exist");

    assert!(saved.targets.contains(&target_a));
    assert!(saved.targets.contains(&target_b));
}

#[test]
fn save_accepts_non_empty_queryable_collection_of_structured_values() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let entity = StructuredSelectionEntity {
        id: Ulid::from_u128(70),
        selected_parts: vec![
            SaveSelectedPart {
                layer_id: Ulid::from_u128(701),
                part_id: Ulid::from_u128(702),
            },
            SaveSelectedPart {
                layer_id: Ulid::from_u128(703),
                part_id: Ulid::from_u128(704),
            },
        ],
    };

    let save = SaveExecutor::<StructuredSelectionEntity>::new(DB, false);
    let saved = save
        .insert(entity.clone())
        .expect("structured collection save should succeed");

    assert_eq!(saved, entity);
    assert_eq!(
        load_structured_selection_entity(entity.id),
        Some(entity),
        "structured collection save should persist the typed after-image",
    );
}

#[test]
fn save_accepts_set_with_structured_values() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let entity = StructuredSelectionSetEntity {
        id: Ulid::from_u128(75),
        selected_parts: SaveSelectedPartSet(
            [
                SaveSelectedPart {
                    layer_id: Ulid::from_u128(751),
                    part_id: Ulid::from_u128(752),
                },
                SaveSelectedPart {
                    layer_id: Ulid::from_u128(753),
                    part_id: Ulid::from_u128(754),
                },
            ]
            .into_iter()
            .collect(),
        ),
    };

    let save = SaveExecutor::<StructuredSelectionSetEntity>::new(DB, false);
    let saved = save
        .insert(entity.clone())
        .expect("structured set save should succeed");

    assert_eq!(saved, entity);
    assert_eq!(
        load_structured_selection_set_entity(entity.id),
        Some(entity),
        "structured set save should persist the typed after-image",
    );
}

#[test]
fn save_accepts_map_with_structured_values() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let mut selected_parts_by_layer = BTreeMap::new();
    selected_parts_by_layer.insert(
        Ulid::from_u128(801),
        SaveSelectedPart {
            layer_id: Ulid::from_u128(801),
            part_id: Ulid::from_u128(802),
        },
    );
    selected_parts_by_layer.insert(
        Ulid::from_u128(803),
        SaveSelectedPart {
            layer_id: Ulid::from_u128(803),
            part_id: Ulid::from_u128(804),
        },
    );

    let entity = StructuredSelectionMapEntity {
        id: Ulid::from_u128(80),
        selected_parts_by_layer: SaveSelectedPartMap(selected_parts_by_layer),
    };

    let save = SaveExecutor::<StructuredSelectionMapEntity>::new(DB, false);
    let saved = save
        .insert(entity.clone())
        .expect("structured map save should succeed");

    assert_eq!(saved, entity);
    assert_eq!(
        load_structured_selection_map_entity(entity.id),
        Some(entity),
        "structured map save should persist the typed after-image",
    );
}

#[test]
fn strong_set_relation_mixed_valid_invalid_fails_atomically() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let target_save = SaveExecutor::<TargetEntity>::new(DB, false);
    let valid = Ulid::generate();
    target_save
        .insert(TargetEntity { id: valid })
        .expect("valid target save should succeed");

    let invalid = Ulid::generate();
    let source_save = SaveExecutor::<SourceSetEntity>::new(DB, false);
    let err = source_save
        .insert(SourceSetEntity {
            id: Ulid::generate(),
            targets: vec![valid, invalid],
        })
        .expect_err("mixed valid/invalid set relation should fail");
    assert_eq!(
        err.class,
        ErrorClass::Unsupported,
        "missing strong relation in set should classify as unsupported",
    );
    assert_eq!(
        err.origin,
        ErrorOrigin::Executor,
        "missing strong relation in set should originate from executor validation",
    );
    assert!(
        err.message.contains("strong relation missing"),
        "unexpected error: {err:?}"
    );

    let source_empty = with_data_store(SourceStore::PATH, |data_store| {
        data_store.iter().next().is_none()
    });
    assert!(
        source_empty,
        "source save must be atomic: failed save must not persist partial rows"
    );
}

#[test]
fn insert_many_atomic_rejects_partial_commit_on_late_failure() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let save = SaveExecutor::<TargetEntity>::new(DB, false);
    let existing = Ulid::from_u128(41);
    save.insert(TargetEntity { id: existing })
        .expect("seed row insert should succeed");

    let new_id = Ulid::from_u128(42);
    let err = save
        .insert_many_atomic(vec![
            TargetEntity { id: new_id },
            TargetEntity { id: existing },
        ])
        .expect_err("atomic insert batch should fail on duplicate key");
    assert_eq!(
        err.class,
        ErrorClass::Conflict,
        "duplicate key should classify as conflict",
    );
    assert_eq!(
        err.origin,
        ErrorOrigin::Store,
        "duplicate key should originate from store checks",
    );

    let rows = with_data_store(TargetStore::PATH, |data_store| data_store.iter().count());
    assert_eq!(
        rows, 1,
        "atomic insert batch must not persist earlier rows when a later row fails"
    );
}

#[test]
fn insert_many_atomic_rejects_duplicate_keys_in_request() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let save = SaveExecutor::<TargetEntity>::new(DB, false);
    let dup = Ulid::from_u128(47);
    let err = save
        .insert_many_atomic(vec![TargetEntity { id: dup }, TargetEntity { id: dup }])
        .expect_err("atomic insert batch should reject duplicate keys in one request");
    assert_eq!(
        err.class,
        ErrorClass::Unsupported,
        "duplicate key request should fail deterministic pre-commit validation",
    );
    assert_eq!(
        err.origin,
        ErrorOrigin::Executor,
        "duplicate key request should fail at executor boundary",
    );
    assert!(
        err.message.contains("duplicate key"),
        "unexpected error: {err:?}",
    );

    let rows = with_data_store(TargetStore::PATH, |data_store| data_store.iter().count());
    assert_eq!(
        rows, 0,
        "duplicate-key atomic batch must not persist any row"
    );
}

#[test]
fn insert_many_non_atomic_commits_prefix_before_late_failure() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let save = SaveExecutor::<TargetEntity>::new(DB, false);
    let existing = Ulid::from_u128(51);
    save.insert(TargetEntity { id: existing })
        .expect("seed row insert should succeed");

    let new_id = Ulid::from_u128(52);
    let err = save
        .insert_many_non_atomic(vec![
            TargetEntity { id: new_id },
            TargetEntity { id: existing },
        ])
        .expect_err("non-atomic insert batch should fail on duplicate key");
    assert_eq!(
        err.class,
        ErrorClass::Conflict,
        "duplicate key should classify as conflict",
    );

    let rows = with_data_store(TargetStore::PATH, |data_store| data_store.iter().count());
    assert_eq!(
        rows, 2,
        "non-atomic insert batch must preserve earlier committed rows before failure"
    );
}

#[test]
fn insert_many_empty_batch_is_noop_for_atomic_and_non_atomic_lanes() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let save = SaveExecutor::<TargetEntity>::new(DB, false);
    let atomic = save
        .insert_many_atomic(Vec::<TargetEntity>::new())
        .expect("atomic empty batch should succeed");
    let non_atomic = save
        .insert_many_non_atomic(Vec::<TargetEntity>::new())
        .expect("non-atomic empty batch should succeed");

    assert!(
        atomic.is_empty(),
        "atomic empty batch should return no rows"
    );
    assert!(
        non_atomic.is_empty(),
        "non-atomic empty batch should return no rows",
    );

    let rows = with_data_store(TargetStore::PATH, |data_store| data_store.iter().count());
    assert_eq!(rows, 0, "empty batches must not persist rows");
}

#[test]
fn commit_window_preflight_does_not_mutate_real_stores_before_apply() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let entity = UniqueEmailEntity {
        id: Ulid::from_u128(89),
        email: "preflight@example.com".to_string(),
    };
    let data_key = DataKey::try_new::<UniqueEmailEntity>(entity.id)
        .expect("data key should build for preflight test")
        .to_raw()
        .expect("data key should encode for preflight test");
    let row = CanonicalRow::from_entity(&entity)
        .expect("row encoding should succeed for preflight test")
        .into_raw_row();
    let row_op = CommitRowOp::new(
        UniqueEmailEntity::PATH,
        data_key,
        None,
        Some(row.as_bytes().to_vec()),
        commit_schema_fingerprint_for_entity::<UniqueEmailEntity>(),
    );

    let baseline_index_generation =
        with_index_store(UNIQUE_INDEX_STORE_PATH, IndexStore::generation);
    let baseline_index_len = with_index_store(UNIQUE_INDEX_STORE_PATH, IndexStore::len);

    let OpenCommitWindow {
        commit,
        prepared_row_ops,
        index_store_guards,
        ..
    } = open_commit_window::<UniqueEmailEntity>(&DB, vec![row_op])
        .expect("commit window open should succeed");

    assert!(
        commit_marker_present().expect("commit marker probe should succeed"),
        "open commit window should persist commit marker before apply",
    );
    assert!(
        load_unique_email_entity(entity.id).is_none(),
        "preflight must not persist data rows before apply",
    );
    assert_eq!(
        with_index_store(UNIQUE_INDEX_STORE_PATH, IndexStore::len),
        baseline_index_len,
        "preflight must not persist index rows before apply",
    );
    assert_eq!(
        with_index_store(UNIQUE_INDEX_STORE_PATH, IndexStore::generation),
        baseline_index_generation,
        "preflight must not mutate index generation before apply",
    );

    apply_prepared_row_ops(
        commit,
        "save_row_apply_preflight_purity_test",
        prepared_row_ops,
        index_store_guards,
        || {},
        || {},
    )
    .expect("apply should persist prepared row ops");

    assert!(
        load_unique_email_entity(entity.id).is_some(),
        "apply should persist the prepared row",
    );
    assert!(
        with_index_store(UNIQUE_INDEX_STORE_PATH, IndexStore::len) > baseline_index_len,
        "apply should persist index entry after preflight-only open",
    );
}

#[test]
fn commit_window_rejects_apply_when_index_store_generation_changes() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let entity = UniqueEmailEntity {
        id: Ulid::from_u128(90),
        email: "guard@example.com".to_string(),
    };
    let data_key = DataKey::try_new::<UniqueEmailEntity>(entity.id)
        .expect("data key should build for generation guard test")
        .to_raw()
        .expect("data key should encode for generation guard test");
    let row = CanonicalRow::from_entity(&entity)
        .expect("row encoding should succeed for generation guard test")
        .into_raw_row();
    let row_op = CommitRowOp::new(
        UniqueEmailEntity::PATH,
        data_key,
        None,
        Some(row.as_bytes().to_vec()),
        commit_schema_fingerprint_for_entity::<UniqueEmailEntity>(),
    );

    let OpenCommitWindow {
        commit,
        prepared_row_ops,
        index_store_guards,
        ..
    } = open_commit_window::<UniqueEmailEntity>(&DB, vec![row_op])
        .expect("commit window open should succeed");

    // Simulate cross-phase drift: preflight saw one generation, apply sees another.
    with_index_store_mut(UNIQUE_INDEX_STORE_PATH, IndexStore::clear);

    let err = apply_prepared_row_ops(
        commit,
        "save_row_apply_generation_guard_test",
        prepared_row_ops,
        index_store_guards,
        || {},
        || {},
    )
    .expect_err("generation mismatch must fail before apply");
    assert_eq!(
        err.class,
        ErrorClass::InvariantViolation,
        "generation mismatch should classify as invariant violation",
    );
    assert_eq!(
        err.origin,
        ErrorOrigin::Executor,
        "generation mismatch should originate from executor apply invariants",
    );
    assert!(
        err.message
            .contains("index store generation changed between preflight and apply"),
        "unexpected error: {err:?}",
    );

    let persisted = load_unique_email_entity(entity.id);
    assert!(
        persisted.is_none(),
        "generation guard failure must prevent row persistence"
    );
}

#[test]
fn update_many_atomic_rejects_partial_commit_on_late_conflict() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let save = SaveExecutor::<UniqueEmailEntity>::new(DB, false);
    let first = Ulid::from_u128(60);
    let second = Ulid::from_u128(61);
    save.insert(UniqueEmailEntity {
        id: first,
        email: "a@example.com".to_string(),
    })
    .expect("first seed row should save");
    save.insert(UniqueEmailEntity {
        id: second,
        email: "b@example.com".to_string(),
    })
    .expect("second seed row should save");

    let err = save
        .update_many_atomic(vec![
            UniqueEmailEntity {
                id: first,
                email: "carol@example.com".to_string(),
            },
            UniqueEmailEntity {
                id: second,
                email: "carol@example.com".to_string(),
            },
        ])
        .expect_err("atomic update batch should fail on unique index conflict");
    assert_eq!(
        err.class,
        ErrorClass::Conflict,
        "expected conflict error class",
    );
    assert_eq!(
        err.origin,
        ErrorOrigin::Index,
        "expected index error origin",
    );

    let first_row = load_unique_email_entity(first).expect("first row should remain");
    let second_row = load_unique_email_entity(second).expect("second row should remain");
    assert_eq!(
        first_row.email, "a@example.com",
        "atomic update batch failure must not persist earlier updates",
    );
    assert_eq!(
        second_row.email, "b@example.com",
        "atomic update batch failure must not persist later updates",
    );
}

#[test]
fn update_many_non_atomic_commits_prefix_before_late_conflict() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let save = SaveExecutor::<UniqueEmailEntity>::new(DB, false);
    let first = Ulid::from_u128(62);
    let second = Ulid::from_u128(63);
    save.insert(UniqueEmailEntity {
        id: first,
        email: "a@example.com".to_string(),
    })
    .expect("first seed row should save");
    save.insert(UniqueEmailEntity {
        id: second,
        email: "b@example.com".to_string(),
    })
    .expect("second seed row should save");

    let err = save
        .update_many_non_atomic(vec![
            UniqueEmailEntity {
                id: first,
                email: "carol@example.com".to_string(),
            },
            UniqueEmailEntity {
                id: second,
                email: "carol@example.com".to_string(),
            },
        ])
        .expect_err("non-atomic update batch should fail on unique index conflict");
    assert_eq!(
        err.class,
        ErrorClass::Conflict,
        "expected conflict error class",
    );
    assert_eq!(
        err.origin,
        ErrorOrigin::Index,
        "expected index error origin",
    );

    let first_row = load_unique_email_entity(first).expect("first row should remain");
    let second_row = load_unique_email_entity(second).expect("second row should remain");
    assert_eq!(
        first_row.email, "carol@example.com",
        "non-atomic update batch should keep earlier committed updates",
    );
    assert_eq!(
        second_row.email, "b@example.com",
        "non-atomic update batch should leave later row unchanged on failure",
    );
}

#[test]
fn replace_many_atomic_mixed_existing_missing_rejects_partial_commit_on_conflict() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let save = SaveExecutor::<UniqueEmailEntity>::new(DB, false);
    let existing = Ulid::from_u128(70);
    let missing = Ulid::from_u128(72);
    save.insert(UniqueEmailEntity {
        id: existing,
        email: "a@example.com".to_string(),
    })
    .expect("existing seed row should save");

    let err = save
        .replace_many_atomic(vec![
            UniqueEmailEntity {
                id: existing,
                email: "carol@example.com".to_string(),
            },
            UniqueEmailEntity {
                id: missing,
                email: "carol@example.com".to_string(),
            },
        ])
        .expect_err("atomic replace batch should fail on unique index conflict");
    assert_eq!(
        err.class,
        ErrorClass::Conflict,
        "expected conflict error class",
    );
    assert_eq!(
        err.origin,
        ErrorOrigin::Index,
        "expected index error origin",
    );

    let existing_row = load_unique_email_entity(existing).expect("existing row should remain");
    assert_eq!(
        existing_row.email, "a@example.com",
        "atomic replace failure must not persist earlier replacements",
    );
    let missing_row = load_unique_email_entity(missing);
    assert!(
        missing_row.is_none(),
        "atomic replace failure must not insert missing-row replacement",
    );
}

#[test]
fn replace_many_non_atomic_mixed_existing_missing_commits_prefix_before_conflict() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let save = SaveExecutor::<UniqueEmailEntity>::new(DB, false);
    let existing = Ulid::from_u128(73);
    let missing = Ulid::from_u128(74);
    save.insert(UniqueEmailEntity {
        id: existing,
        email: "a@example.com".to_string(),
    })
    .expect("existing seed row should save");

    let err = save
        .replace_many_non_atomic(vec![
            UniqueEmailEntity {
                id: existing,
                email: "carol@example.com".to_string(),
            },
            UniqueEmailEntity {
                id: missing,
                email: "carol@example.com".to_string(),
            },
        ])
        .expect_err("non-atomic replace batch should fail on unique index conflict");
    assert_eq!(
        err.class,
        ErrorClass::Conflict,
        "expected conflict error class",
    );
    assert_eq!(
        err.origin,
        ErrorOrigin::Index,
        "expected index error origin",
    );

    let existing_row = load_unique_email_entity(existing).expect("existing row should remain");
    assert_eq!(
        existing_row.email, "carol@example.com",
        "non-atomic replace batch should keep earlier committed replacements",
    );
    let missing_row = load_unique_email_entity(missing);
    assert!(
        missing_row.is_none(),
        "failed non-atomic replacement should not persist the failing item",
    );
}

#[test]
fn insert_many_atomic_with_strong_relations_mixed_valid_invalid_fails_atomically() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let target_save = SaveExecutor::<TargetEntity>::new(DB, false);
    let valid_target = Ulid::from_u128(80);
    target_save
        .insert(TargetEntity { id: valid_target })
        .expect("valid target should save");

    let missing_target = Ulid::from_u128(81);
    let source_save = SaveExecutor::<SourceSetEntity>::new(DB, false);
    let err = source_save
        .insert_many_atomic(vec![
            SourceSetEntity {
                id: Ulid::from_u128(82),
                targets: vec![valid_target],
            },
            SourceSetEntity {
                id: Ulid::from_u128(83),
                targets: vec![valid_target, missing_target],
            },
        ])
        .expect_err("atomic relation batch should fail when one item has missing strong relation");
    assert_eq!(
        err.class,
        ErrorClass::Unsupported,
        "missing strong relation should classify as unsupported",
    );
    assert_eq!(
        err.origin,
        ErrorOrigin::Executor,
        "missing strong relation should originate from executor validation",
    );
    assert!(
        err.message.contains("strong relation missing"),
        "unexpected error: {err:?}",
    );

    let source_rows = with_data_store(SourceStore::PATH, |data_store| data_store.iter().count());
    assert_eq!(
        source_rows, 0,
        "atomic relation batch failure must not persist any source row",
    );
}

#[test]
fn update_many_atomic_with_strong_relations_mixed_valid_invalid_fails_atomically() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let target_save = SaveExecutor::<TargetEntity>::new(DB, false);
    let valid_a = Ulid::from_u128(84);
    let valid_b = Ulid::from_u128(85);
    target_save
        .insert(TargetEntity { id: valid_a })
        .expect("valid target A should save");
    target_save
        .insert(TargetEntity { id: valid_b })
        .expect("valid target B should save");

    let source_save = SaveExecutor::<SourceSetEntity>::new(DB, false);
    let first_id = Ulid::from_u128(86);
    let second_id = Ulid::from_u128(87);
    source_save
        .insert(SourceSetEntity {
            id: first_id,
            targets: vec![valid_a],
        })
        .expect("first source seed row should save");
    source_save
        .insert(SourceSetEntity {
            id: second_id,
            targets: vec![valid_a],
        })
        .expect("second source seed row should save");

    let missing_target = Ulid::from_u128(88);
    let err = source_save
        .update_many_atomic(vec![
            SourceSetEntity {
                id: first_id,
                targets: vec![valid_b],
            },
            SourceSetEntity {
                id: second_id,
                targets: vec![valid_b, missing_target],
            },
        ])
        .expect_err("atomic relation update batch should fail when one item has missing relation");
    assert_eq!(
        err.class,
        ErrorClass::Unsupported,
        "missing strong relation should classify as unsupported",
    );
    assert_eq!(
        err.origin,
        ErrorOrigin::Executor,
        "missing strong relation should originate from executor validation",
    );

    let first_row = load_source_set_entity(first_id).expect("first source row should remain");
    let second_row = load_source_set_entity(second_id).expect("second source row should remain");
    assert_eq!(
        first_row.targets,
        vec![valid_a],
        "atomic relation update failure must not persist earlier updates",
    );
    assert_eq!(
        second_row.targets,
        vec![valid_a],
        "atomic relation update failure must not persist later updates",
    );
}

#[test]
fn replace_many_atomic_with_strong_relations_mixed_valid_invalid_fails_atomically() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let target_save = SaveExecutor::<TargetEntity>::new(DB, false);
    let valid_target = Ulid::from_u128(89);
    target_save
        .insert(TargetEntity { id: valid_target })
        .expect("valid target should save");

    let source_save = SaveExecutor::<SourceSetEntity>::new(DB, false);
    let existing_id = Ulid::from_u128(90);
    source_save
        .insert(SourceSetEntity {
            id: existing_id,
            targets: vec![valid_target],
        })
        .expect("existing source row should save");

    let missing_target = Ulid::from_u128(91);
    let inserted_id = Ulid::from_u128(92);
    let err = source_save
        .replace_many_atomic(vec![
            SourceSetEntity {
                id: existing_id,
                targets: vec![valid_target],
            },
            SourceSetEntity {
                id: inserted_id,
                targets: vec![valid_target, missing_target],
            },
        ])
        .expect_err("atomic relation replace batch should fail when one item has missing relation");
    assert_eq!(
        err.class,
        ErrorClass::Unsupported,
        "missing strong relation should classify as unsupported",
    );
    assert_eq!(
        err.origin,
        ErrorOrigin::Executor,
        "missing strong relation should originate from executor validation",
    );

    let existing_row =
        load_source_set_entity(existing_id).expect("existing source row should remain");
    assert_eq!(
        existing_row.targets,
        vec![valid_target],
        "atomic relation replace failure must not persist earlier replacements",
    );
    let inserted_row = load_source_set_entity(inserted_id);
    assert!(
        inserted_row.is_none(),
        "atomic relation replace failure must not insert later rows",
    );
}

#[test]
fn batch_lane_metrics_atomic_success_failure_and_non_atomic_partial_are_distinct() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();
    metrics_reset_all();

    let save = SaveExecutor::<UniqueEmailEntity>::new(DB, false);

    // Atomic success: both rows commit, so both index inserts are counted.
    save.insert_many_atomic(vec![
        UniqueEmailEntity {
            id: Ulid::from_u128(93),
            email: "x@example.com".to_string(),
        },
        UniqueEmailEntity {
            id: Ulid::from_u128(94),
            email: "y@example.com".to_string(),
        },
    ])
    .expect("atomic insert batch should succeed");
    let after_atomic_success_report = metrics_report(None);
    let after_atomic_success = after_atomic_success_report
        .counters()
        .expect("metrics counters should exist after atomic success");
    assert_eq!(
        after_atomic_success.ops.save_calls, 1,
        "atomic batch success should count as one save execution call",
    );
    assert_eq!(
        after_atomic_success.ops.index_inserts, 2,
        "atomic success should emit index inserts for all committed rows",
    );

    // Atomic pre-commit failure: no index delta should be emitted.
    metrics_reset_all();
    let err = save
        .insert_many_atomic(vec![
            UniqueEmailEntity {
                id: Ulid::from_u128(95),
                email: "z@example.com".to_string(),
            },
            UniqueEmailEntity {
                id: Ulid::from_u128(95),
                email: "z@example.com".to_string(),
            },
        ])
        .expect_err("atomic duplicate-key batch should fail pre-commit");
    assert_eq!(err.class, ErrorClass::Unsupported);
    let after_atomic_failure_report = metrics_report(None);
    let after_atomic_failure = after_atomic_failure_report
        .counters()
        .expect("metrics counters should exist after atomic failure");
    assert_eq!(
        after_atomic_failure.ops.save_calls, 1,
        "atomic batch failure should still count as one attempted save execution call",
    );
    assert_eq!(
        after_atomic_failure.ops.index_inserts, 0,
        "atomic pre-commit failure must not emit index insert deltas",
    );
    assert_eq!(
        after_atomic_failure.ops.index_removes, 0,
        "atomic pre-commit failure must not emit index remove deltas",
    );

    // Non-atomic partial failure: successful prefix should emit index delta.
    metrics_reset_all();
    let existing = Ulid::from_u128(96);
    save.insert(UniqueEmailEntity {
        id: existing,
        email: "base@example.com".to_string(),
    })
    .expect("seed row should save");
    save.insert_many_non_atomic(vec![
        UniqueEmailEntity {
            id: Ulid::from_u128(97),
            email: "partial@example.com".to_string(),
        },
        UniqueEmailEntity {
            id: existing,
            email: "base@example.com".to_string(),
        },
    ])
    .expect_err("non-atomic batch should fail after prefix commit");
    let after_non_atomic_partial_report = metrics_report(None);
    let after_non_atomic_partial = after_non_atomic_partial_report
        .counters()
        .expect("metrics counters should exist after non-atomic partial failure");
    assert_eq!(
        after_non_atomic_partial.ops.save_calls, 2,
        "non-atomic batch should count one seed save plus one batch save call",
    );
    assert_eq!(
        after_non_atomic_partial.ops.index_inserts, 2,
        "non-atomic path should count seed insert + committed prefix insert",
    );
}

#[test]
fn set_field_encoding_requires_canonical_order_and_uniqueness() {
    let kind = FieldKind::Set(&FieldKind::Ulid);
    let lower = Value::Ulid(Ulid::from_u128(1));
    let higher = Value::Ulid(Ulid::from_u128(2));

    let err = SaveExecutor::<SourceSetEntity>::validate_deterministic_field_value(
        "targets",
        &kind,
        &Value::List(vec![higher, lower]),
    )
    .expect_err("unordered set encoding must fail");
    assert!(
        err.message
            .contains("set field must be strictly ordered and deduplicated"),
        "unexpected error: {err:?}"
    );

    let dup = Value::Ulid(Ulid::from_u128(7));
    let err = SaveExecutor::<SourceSetEntity>::validate_deterministic_field_value(
        "targets",
        &kind,
        &Value::List(vec![dup.clone(), dup]),
    )
    .expect_err("duplicate set entries must fail");
    assert!(
        err.message
            .contains("set field must be strictly ordered and deduplicated"),
        "unexpected error: {err:?}"
    );
}

#[test]
fn map_field_encoding_requires_canonical_entry_order() {
    let kind = FieldKind::Map {
        key: &FieldKind::Text,
        value: &FieldKind::Uint,
    };
    let unordered = Value::Map(vec![
        (Value::Text("z".to_string()), Value::Uint(9u64)),
        (Value::Text("a".to_string()), Value::Uint(1u64)),
    ]);

    let err = SaveExecutor::<SourceSetEntity>::validate_deterministic_field_value(
        "settings", &kind, &unordered,
    )
    .expect_err("unordered map entries must fail");
    assert!(
        err.message
            .contains("map field entries are not in canonical deterministic order"),
        "unexpected error: {err:?}"
    );
}

#[test]
fn save_rejects_primary_key_field_and_identity_mismatch() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let executor = SaveExecutor::<MismatchedPkEntity>::new(DB, false);
    let entity = MismatchedPkEntity {
        id: Ulid::from_u128(10),
        actual_id: Ulid::from_u128(20),
    };

    let err = executor
        .insert(entity)
        .expect_err("mismatched primary key identity should fail save");
    assert!(
        err.message.contains("entity primary key mismatch"),
        "unexpected error: {err:?}"
    );

    let source_empty = with_data_store(SourceStore::PATH, |data_store| {
        data_store.iter().next().is_none()
    });
    assert!(
        source_empty,
        "failed invariant checks must not persist rows"
    );
}

#[test]
fn unique_index_violation_rejected_on_insert() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let save = SaveExecutor::<UniqueEmailEntity>::new(DB, false);
    save.insert(UniqueEmailEntity {
        id: Ulid::from_u128(10),
        email: "alice@example.com".to_string(),
    })
    .expect("first unique insert should succeed");

    let err = save
        .insert(UniqueEmailEntity {
            id: Ulid::from_u128(11),
            email: "alice@example.com".to_string(),
        })
        .expect_err("duplicate unique index value should fail");
    assert_eq!(
        err.class,
        ErrorClass::Conflict,
        "expected conflict error class"
    );
    assert_eq!(
        err.origin,
        ErrorOrigin::Index,
        "expected index error origin"
    );
    assert!(
        err.message.contains("index constraint violation"),
        "unexpected error: {err:?}"
    );

    let rows = with_data_store(SourceStore::PATH, |data_store| data_store.iter().count());
    assert_eq!(rows, 1, "conflicting insert must not persist");
}

#[test]
fn unique_index_row_key_mismatch_surfaces_store_invariant_violation() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let existing_id = Ulid::from_u128(510);
    let save = SaveExecutor::<UniqueEmailEntity>::new(DB, false);
    save.insert(UniqueEmailEntity {
        id: existing_id,
        email: "alice@example.com".to_string(),
    })
    .expect("seed unique row should save");

    let raw_key = DataKey::try_new::<UniqueEmailEntity>(existing_id)
        .expect("existing key should build")
        .to_raw()
        .expect("existing key should encode");
    let mismatched_row = UniqueEmailEntity {
        id: Ulid::from_u128(511),
        email: "alice@example.com".to_string(),
    };
    let raw_row = CanonicalRow::from_entity(&mismatched_row)
        .expect("mismatched row should encode")
        .into_raw_row();
    with_data_store_mut(SourceStore::PATH, |data_store| {
        data_store.insert_raw_for_test(raw_key, raw_row);
    });

    let err = save
        .insert(UniqueEmailEntity {
            id: Ulid::from_u128(512),
            email: "alice@example.com".to_string(),
        })
        .expect_err("row-key mismatch should fail unique validation");
    assert_eq!(err.class, ErrorClass::Corruption);
    assert_eq!(err.origin, ErrorOrigin::Serialize);
    assert!(
        err.message
            .contains("failed to decode structural primary-key slot"),
        "row-key mismatch should fail through the canonical unique-validation structural decode lane: {err:?}"
    );
    assert!(
        err.message.contains("row key mismatch"),
        "row-key mismatch details should remain visible in the wrapped corruption: {err:?}"
    );
}

#[test]
fn decimal_scale_mixed_writes_reject_noncanonical_scale() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let save = SaveExecutor::<DecimalScaleEntity>::new(DB, false);
    save.insert(DecimalScaleEntity {
        id: Ulid::from_u128(8101),
        amount: Decimal::new(123, 2),
    })
    .expect("canonical decimal scale should save");

    let err = save
        .insert(DecimalScaleEntity {
            id: Ulid::from_u128(8102),
            amount: Decimal::new(1234, 3),
        })
        .expect_err("mixed decimal scale write must be rejected");
    assert_eq!(err.class, ErrorClass::Unsupported);
    assert_eq!(err.origin, ErrorOrigin::Executor);
    assert!(
        err.message.contains("decimal field scale mismatch"),
        "unexpected error: {err:?}"
    );

    let rows = with_data_store(SourceStore::PATH, |data_store| data_store.iter().count());
    assert_eq!(rows, 1, "rejected mixed-scale write must not persist");
}

#[test]
fn save_update_rejects_persisted_row_with_decimal_scale_drift() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let id = Ulid::from_u128(8201);
    let data_key = DataKey::try_new::<DecimalScaleEntity>(id)
        .expect("decimal entity key should build")
        .to_raw()
        .expect("decimal entity raw key should encode");
    let id_payload =
        encode_persisted_scalar_slot_payload(&id, "id").expect("id slot payload should encode");
    let amount_payload = crate::db::data::encode_structural_field_by_kind_bytes(
        crate::model::field::FieldKind::Decimal { scale: 3 },
        &crate::value::Value::Decimal(Decimal::new(1234, 3)),
        "amount",
    )
    .expect("amount slot payload should encode");
    let slot_payloads = [id_payload, amount_payload];
    let mut row_payload = Vec::new();
    let slot_count = u16::try_from(slot_payloads.len()).expect("slot count should fit in u16");
    row_payload.extend_from_slice(&slot_count.to_be_bytes());
    let mut payload_start = 0u32;
    for payload in &slot_payloads {
        let payload_len = u32::try_from(payload.len()).expect("payload length should fit in u32");
        row_payload.extend_from_slice(&payload_start.to_be_bytes());
        row_payload.extend_from_slice(&payload_len.to_be_bytes());
        payload_start = payload_start.saturating_add(payload_len);
    }
    for payload in &slot_payloads {
        row_payload.extend_from_slice(payload);
    }
    let raw_row =
        RawRow::try_new(serialize_row_payload(row_payload).expect("row payload should serialize"))
            .expect("malformed row bytes should satisfy row bound");
    with_data_store_mut(SourceStore::PATH, |data_store| {
        data_store.insert_raw_for_test(data_key, raw_row);
    });

    let save = SaveExecutor::<DecimalScaleEntity>::new(DB, false);
    let err = save
        .update(DecimalScaleEntity {
            id,
            amount: Decimal::new(123, 2),
        })
        .expect_err("decode path must reject persisted decimal scale drift");
    assert_eq!(err.class, ErrorClass::Corruption);
    assert_eq!(err.origin, ErrorOrigin::Store);
    assert!(
        err.message.contains("persisted row invariant violation"),
        "unexpected error: {err:?}"
    );
    assert!(
        err.message.contains("decimal field scale mismatch"),
        "unexpected error: {err:?}"
    );
}

#[test]
fn unique_index_violation_rejected_on_update() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let save = SaveExecutor::<UniqueEmailEntity>::new(DB, false);
    save.insert(UniqueEmailEntity {
        id: Ulid::from_u128(20),
        email: "alice@example.com".to_string(),
    })
    .expect("first unique row should save");
    save.insert(UniqueEmailEntity {
        id: Ulid::from_u128(21),
        email: "bob@example.com".to_string(),
    })
    .expect("second unique row should save");

    let err = save
        .update(UniqueEmailEntity {
            id: Ulid::from_u128(21),
            email: "alice@example.com".to_string(),
        })
        .expect_err("update that collides with unique index should fail");
    assert_eq!(
        err.class,
        ErrorClass::Conflict,
        "expected conflict error class"
    );
    assert_eq!(
        err.origin,
        ErrorOrigin::Index,
        "expected index error origin"
    );
    assert!(
        err.message.contains("index constraint violation"),
        "unexpected error: {err:?}"
    );

    let rows = with_data_store(SourceStore::PATH, |data_store| data_store.iter().count());
    assert_eq!(rows, 2, "failed update must not remove persisted rows");
}

#[test]
fn structural_update_applies_patch_to_existing_row() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let session = DbSession::new(DB);
    let save = SaveExecutor::<UniqueEmailEntity>::new(DB, false);
    let id = Ulid::from_u128(22);
    save.insert(UniqueEmailEntity {
        id,
        email: "alice@example.com".to_string(),
    })
    .expect("seed unique row should save");

    let patched: UniqueEmailEntity = session
        .update_structural::<UniqueEmailEntity>(
            id,
            UpdatePatch::new()
                .set_field(
                    UniqueEmailEntity::MODEL,
                    "email",
                    Value::Text("grace@example.com".to_string()),
                )
                .expect("resolve email slot"),
        )
        .expect("structural update should succeed");

    assert_eq!(patched.id, id);
    assert_eq!(patched.email, "grace@example.com");

    let persisted = load_unique_email_entity(id).expect("row should remain after patch update");
    assert_eq!(persisted.email, "grace@example.com");
}

#[test]
fn structural_update_rejects_primary_key_mismatch() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let session = DbSession::new(DB);
    let save = SaveExecutor::<UniqueEmailEntity>::new(DB, false);
    let id = Ulid::from_u128(23);
    save.insert(UniqueEmailEntity {
        id,
        email: "alice@example.com".to_string(),
    })
    .expect("seed unique row should save");

    let err = session
        .update_structural::<UniqueEmailEntity>(
            id,
            UpdatePatch::new()
                .set_field(
                    UniqueEmailEntity::MODEL,
                    "id",
                    Value::Ulid(Ulid::from_u128(24)),
                )
                .expect("resolve id slot"),
        )
        .expect_err("primary key mismatch patch must fail");

    assert_eq!(err.class, ErrorClass::InvariantViolation);
    assert_eq!(err.origin, ErrorOrigin::Executor);
    assert!(
        err.message.contains("entity primary key mismatch"),
        "unexpected error: {err:?}"
    );
}

#[test]
fn structural_update_builder_rejects_unknown_field_names() {
    let err = UpdatePatch::new()
        .set_field(
            UniqueEmailEntity::MODEL,
            "missing_email",
            Value::Text("grace@example.com".to_string()),
        )
        .expect_err("unknown structural field names must fail");

    assert_eq!(err.class, ErrorClass::InvariantViolation);
    assert_eq!(err.origin, ErrorOrigin::Executor);
    assert!(
        err.message.contains("mutation field not found"),
        "unexpected error: {err:?}"
    );
}

#[test]
fn structural_insert_rejects_missing_required_fields_after_sparse_materialization() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let session = DbSession::new(DB);
    let id = Ulid::from_u128(24);
    let err = session
        .insert_structural::<UniqueEmailEntity>(
            id,
            UpdatePatch::new()
                .set_field(UniqueEmailEntity::MODEL, "id", Value::Ulid(id))
                .expect("resolve id slot"),
        )
        .expect_err("structural insert without required fields must still fail");

    assert_eq!(err.class, ErrorClass::InvariantViolation);
    assert_eq!(err.origin, ErrorOrigin::Executor);
    assert!(
        err.message.contains("missing required field 'email'"),
        "unexpected error: {err:?}"
    );
}

#[test]
fn structural_update_reuses_typed_unique_index_conflicts() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let session = DbSession::new(DB);
    let save = SaveExecutor::<UniqueEmailEntity>::new(DB, false);
    let first_id = Ulid::from_u128(25);
    let second_id = Ulid::from_u128(26);
    save.insert(UniqueEmailEntity {
        id: first_id,
        email: "alice@example.com".to_string(),
    })
    .expect("first unique row should save");
    save.insert(UniqueEmailEntity {
        id: second_id,
        email: "bob@example.com".to_string(),
    })
    .expect("second unique row should save");

    let err = session
        .update_structural::<UniqueEmailEntity>(
            first_id,
            UpdatePatch::new()
                .set_field(
                    UniqueEmailEntity::MODEL,
                    "email",
                    Value::Text("bob@example.com".to_string()),
                )
                .expect("resolve email slot"),
        )
        .expect_err("structural update that collides with unique index must fail");

    assert_eq!(err.class, ErrorClass::Conflict);
    assert_eq!(err.origin, ErrorOrigin::Index);
    assert!(
        err.message.contains("index constraint violation"),
        "unexpected error: {err:?}"
    );
}

#[test]
fn structural_replace_rejects_missing_required_fields_after_sparse_materialization() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let session = DbSession::new(DB);
    let save = SaveExecutor::<UniqueEmailEntity>::new(DB, false);
    let id = Ulid::from_u128(27);
    save.insert(UniqueEmailEntity {
        id,
        email: "alice@example.com".to_string(),
    })
    .expect("seed unique row should save");

    let err = session
        .replace_structural::<UniqueEmailEntity>(
            id,
            UpdatePatch::new()
                .set_field(UniqueEmailEntity::MODEL, "id", Value::Ulid(id))
                .expect("resolve id slot"),
        )
        .expect_err("structural replace without required fields must still fail");

    assert_eq!(err.class, ErrorClass::InvariantViolation);
    assert_eq!(err.origin, ErrorOrigin::Executor);
    assert!(
        err.message.contains("missing required field 'email'"),
        "unexpected error: {err:?}"
    );
}

#[test]
fn structural_insert_matches_typed_insert_outcome() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let session = DbSession::new(DB);
    let id = Ulid::from_u128(28);
    let inserted = session
        .insert_structural(
            id,
            UpdatePatch::new()
                .set_field(UniqueEmailEntity::MODEL, "id", Value::Ulid(id))
                .expect("resolve id slot")
                .set_field(
                    UniqueEmailEntity::MODEL,
                    "email",
                    Value::Text("grace@example.com".to_string()),
                )
                .expect("resolve email slot"),
        )
        .expect("structural insert should succeed");

    assert_eq!(
        inserted,
        UniqueEmailEntity {
            id,
            email: "grace@example.com".to_string(),
        }
    );

    let persisted = load_unique_email_entity(id).expect("inserted row should persist");
    assert_eq!(persisted, inserted);
}

#[test]
fn structural_insert_matches_typed_insert_parity() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let session = DbSession::new(DB);
    let typed_id = Ulid::from_u128(280);
    let structural_id = Ulid::from_u128(281);
    let typed_email = "grace@example.com";
    let structural_email = "heidi@example.com";

    let typed = SaveExecutor::<UniqueEmailEntity>::new(DB, false)
        .insert(UniqueEmailEntity {
            id: typed_id,
            email: typed_email.to_string(),
        })
        .expect("typed create should succeed");
    let structural: UniqueEmailEntity = session
        .insert_structural(
            structural_id,
            unique_email_patch(structural_id, structural_email),
        )
        .expect("structural insert should succeed");

    assert_eq!(typed.email, typed_email);
    assert_eq!(structural.email, structural_email);
    assert_eq!(
        load_unique_email_entity(typed_id)
            .expect("typed row should persist")
            .email,
        typed_email
    );
    assert_eq!(
        load_unique_email_entity(structural_id)
            .expect("structural row should persist")
            .email,
        structural_email
    );
}

#[test]
fn structural_replace_matches_typed_replace_for_existing_rows() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let session = DbSession::new(DB);
    let save = SaveExecutor::<UniqueEmailEntity>::new(DB, false);
    let id = Ulid::from_u128(29);
    save.insert(UniqueEmailEntity {
        id,
        email: "alice@example.com".to_string(),
    })
    .expect("seed unique row should save");

    let replaced = session
        .replace_structural(
            id,
            UpdatePatch::new()
                .set_field(UniqueEmailEntity::MODEL, "id", Value::Ulid(id))
                .expect("resolve id slot")
                .set_field(
                    UniqueEmailEntity::MODEL,
                    "email",
                    Value::Text("grace@example.com".to_string()),
                )
                .expect("resolve email slot"),
        )
        .expect("structural replace should succeed");

    assert_eq!(
        replaced,
        UniqueEmailEntity {
            id,
            email: "grace@example.com".to_string(),
        }
    );

    let persisted = load_unique_email_entity(id).expect("replaced row should persist");
    assert_eq!(persisted, replaced);
}

#[test]
fn structural_update_matches_typed_update_parity() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let session = DbSession::new(DB);
    let save = SaveExecutor::<UniqueEmailEntity>::new(DB, false);
    let typed_id = Ulid::from_u128(290);
    let structural_id = Ulid::from_u128(291);
    let typed_email = "grace@example.com";
    let structural_email = "heidi@example.com";
    save.insert(UniqueEmailEntity {
        id: typed_id,
        email: "alice@example.com".to_string(),
    })
    .expect("typed seed row should save");
    save.insert(UniqueEmailEntity {
        id: structural_id,
        email: "bob@example.com".to_string(),
    })
    .expect("structural seed row should save");

    let typed = save
        .update(UniqueEmailEntity {
            id: typed_id,
            email: typed_email.to_string(),
        })
        .expect("typed update should succeed");
    let structural: UniqueEmailEntity = session
        .update_structural(
            structural_id,
            UpdatePatch::new()
                .set_field(
                    UniqueEmailEntity::MODEL,
                    "email",
                    Value::Text(structural_email.to_string()),
                )
                .expect("resolve email slot"),
        )
        .expect("structural update should succeed");

    assert_eq!(typed.email, typed_email);
    assert_eq!(structural.email, structural_email);
    assert_eq!(
        load_unique_email_entity(typed_id)
            .expect("typed row should persist")
            .email,
        typed_email
    );
    assert_eq!(
        load_unique_email_entity(structural_id)
            .expect("structural row should persist")
            .email,
        structural_email
    );
}

#[test]
fn structural_replace_matches_typed_replace_parity() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let session = DbSession::new(DB);
    let save = SaveExecutor::<UniqueEmailEntity>::new(DB, false);
    let typed_id = Ulid::from_u128(292);
    let structural_id = Ulid::from_u128(293);
    let typed_email = "grace@example.com";
    let structural_email = "heidi@example.com";
    save.insert(UniqueEmailEntity {
        id: typed_id,
        email: "alice@example.com".to_string(),
    })
    .expect("typed seed row should save");
    save.insert(UniqueEmailEntity {
        id: structural_id,
        email: "bob@example.com".to_string(),
    })
    .expect("structural seed row should save");

    let typed = save
        .replace(UniqueEmailEntity {
            id: typed_id,
            email: typed_email.to_string(),
        })
        .expect("typed replace should succeed");
    let structural: UniqueEmailEntity = session
        .replace_structural::<UniqueEmailEntity>(
            structural_id,
            unique_email_patch(structural_id, structural_email),
        )
        .expect("structural replace should succeed");

    assert_eq!(typed.email, typed_email);
    assert_eq!(structural.email, structural_email);
    assert_eq!(
        load_unique_email_entity(typed_id)
            .expect("typed row should persist")
            .email,
        typed_email
    );
    assert_eq!(
        load_unique_email_entity(structural_id)
            .expect("structural row should persist")
            .email,
        structural_email
    );
}

#[test]
fn structural_replace_inserts_missing_rows_with_sparse_after_image_when_required_fields_present() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let session = DbSession::new(DB);
    let id = Ulid::from_u128(30);
    let replaced = session
        .replace_structural(
            id,
            UpdatePatch::new()
                .set_field(UniqueEmailEntity::MODEL, "id", Value::Ulid(id))
                .expect("resolve id slot")
                .set_field(
                    UniqueEmailEntity::MODEL,
                    "email",
                    Value::Text("grace@example.com".to_string()),
                )
                .expect("resolve email slot"),
        )
        .expect("structural replace should insert missing rows");

    assert_eq!(
        replaced,
        UniqueEmailEntity {
            id,
            email: "grace@example.com".to_string(),
        }
    );

    let persisted = load_unique_email_entity(id).expect("replaced row should persist");
    assert_eq!(persisted, replaced);
}

#[test]
fn unique_index_update_same_pk_same_components_is_allowed() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let save = SaveExecutor::<UniqueEmailEntity>::new(DB, false);
    let id = Ulid::from_u128(31);
    save.insert(UniqueEmailEntity {
        id,
        email: "alice@example.com".to_string(),
    })
    .expect("seed unique row should save");

    let updated = save
        .update(UniqueEmailEntity {
            id,
            email: "alice@example.com".to_string(),
        })
        .expect("update with same pk and identical unique components should succeed");
    assert_eq!(updated.id, id);
    assert_eq!(updated.email, "alice@example.com");

    let persisted = load_unique_email_entity(id).expect("row should remain after no-op update");
    assert_eq!(persisted.email, "alice@example.com");
}

#[test]
fn unique_index_delete_then_insert_same_value_succeeds() {
    init_commit_store_for_tests().expect("commit store init should succeed");
    reset_store();

    let save = SaveExecutor::<UniqueEmailEntity>::new(DB, false);
    let delete = DeleteExecutor::<UniqueEmailEntity>::new(DB);

    let original = Ulid::from_u128(40);
    save.insert(UniqueEmailEntity {
        id: original,
        email: "alice@example.com".to_string(),
    })
    .expect("seed unique row should save");

    let delete_plan = Query::<UniqueEmailEntity>::new(MissingRowPolicy::Ignore)
        .delete()
        .by_id(original)
        .plan()
        .map(crate::db::executor::PreparedExecutionPlan::from)
        .expect("delete plan should build");
    let deleted = delete
        .execute(delete_plan)
        .expect("delete should clear existing unique row");
    assert_eq!(deleted.len(), 1);

    let replacement = Ulid::from_u128(41);
    save.insert(UniqueEmailEntity {
        id: replacement,
        email: "alice@example.com".to_string(),
    })
    .expect("reinsert after delete should succeed for same unique value");

    let original_row = load_unique_email_entity(original);
    let replacement_row = load_unique_email_entity(replacement);
    assert!(original_row.is_none(), "deleted row should remain removed");
    assert!(
        replacement_row.is_some(),
        "replacement row should persist with reclaimed unique value"
    );
}

#[test]
fn save_executor_insert_allows_nullable_account_event_with_missing_from() {
    reset_store();

    let save = SaveExecutor::<NullableAccountEventEntity>::new(DB, false);
    let id = Ulid::from_u128(400);
    let account = Account::dummy(7);
    let saved = save
        .insert(NullableAccountEventEntity {
            id,
            from: None,
            to: Some(account),
        })
        .expect("mint-style nullable account event should save");

    assert_eq!(saved.from, None);
    assert_eq!(saved.to, Some(account));

    let persisted = load_nullable_account_event_entity(id)
        .expect("mint-style nullable account event should persist");
    assert_eq!(persisted, saved);
}

#[test]
fn save_executor_insert_allows_nullable_account_event_with_missing_to() {
    reset_store();

    let save = SaveExecutor::<NullableAccountEventEntity>::new(DB, false);
    let id = Ulid::from_u128(401);
    let account = Account::dummy(9);
    let saved = save
        .insert(NullableAccountEventEntity {
            id,
            from: Some(account),
            to: None,
        })
        .expect("burn-style nullable account event should save");

    assert_eq!(saved.from, Some(account));
    assert_eq!(saved.to, None);

    let persisted = load_nullable_account_event_entity(id)
        .expect("burn-style nullable account event should persist");
    assert_eq!(persisted, saved);
}