delaunay 0.8.0

D-dimensional Delaunay triangulations and convex hulls in Rust, with exact predicates, deterministic degeneracy handling, explicit topology validation, and bistellar flips for finite point sets.
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
//! Durable UUID snapshots for [`Tds`] persistence boundaries.
//!
//! The runtime [`Tds`] stores topology with slotmap keys because those handles
//! are compact and fast in memory. A snapshot stores the same topology with
//! vertex and simplex UUIDs so the data can cross process, file, or codec
//! boundaries without treating storage-local keys as durable identifiers.
//!
//! This module keeps three roles separate:
//!
//! - `RawTdsSnapshot` is the codec-facing interchange record. It may come from
//!   untrusted input and can temporarily contain cross-field inconsistencies.
//! - `TdsSnapshot` is the validated UUID topology. It is proof-bearing: every
//!   simplex has checked vertex UUIDs, neighbor UUID slots, and optional periodic
//!   offsets before hydration starts.
//! - `Tds` is the runtime slotmap-backed topology. Hydration allocates fresh
//!   storage-local keys from a validated snapshot, rebuilds incidence, then runs
//!   TDS validation before returning the value.
//!
//! Downstream crates should normally use `Serialize`/`Deserialize` on `Tds<U, V, D>`
//! instead of these crate-private records. That path preserves vertex payloads
//! (`U`) and simplex payloads (`V`) whenever those types satisfy the crate's data
//! serialization bounds, while keeping `VertexKey` and `SimplexKey` out of the
//! durable format. The raw snapshot shape is serde-backed today, but its role is
//! a persistence boundary rather than a serde-specific domain model.

#![forbid(unsafe_code)]

use super::{
    SimplexKey, Tds, TdsError, TdsMutationError, TriangulationConstructionState, VertexKey,
    incidence::VertexIncidenceIndex,
};
use crate::core::{
    collections::{
        Entry, FastHashMap, FastHashSet, NeighborBuffer, PeriodicOffsetBuffer,
        SimplexVertexUuidBuffer, StorageMap, UuidToSimplexKeyMap, UuidToVertexKeyMap,
        fast_hash_map_with_capacity, fast_hash_set_with_capacity,
    },
    simplex::{Simplex, SimplexValidationError},
    traits::{DataDeserialize, DataSerialize},
    util::validate_uuid,
    vertex::Vertex,
};
use serde::{
    Deserialize, Deserializer, Serialize,
    de::{self, MapAccess, Visitor},
    ser::SerializeStruct,
};
use std::{
    fmt,
    marker::PhantomData,
    sync::{Arc, atomic::AtomicU64},
};
use thiserror::Error;
use uuid::Uuid;

// =============================================================================
// SNAPSHOT ERROR TYPES
// =============================================================================

/// Errors that can occur while building or parsing durable TDS snapshots.
///
/// Snapshots use UUIDs as interchange identities. Parsing a snapshot resolves
/// those UUIDs into fresh storage-local slotmap keys and rejects incomplete or
/// inconsistent topology before constructing a live [`Tds`].
#[derive(Clone, Debug, Error, PartialEq)]
#[non_exhaustive]
enum TdsSnapshotError {
    /// A simplex could not resolve one of its vertex keys to a vertex UUID while
    /// building a snapshot.
    #[error("Could not resolve vertex UUIDs for simplex {simplex_uuid}: {source}")]
    SimplexVertexUuidResolutionFailed {
        /// Simplex whose vertex UUIDs could not be resolved.
        simplex_uuid: Uuid,
        /// Structured simplex validation failure.
        #[source]
        source: SimplexValidationError,
    },
    /// A simplex has no assigned neighbor slots while building a snapshot.
    #[error("No assigned neighbor slots found for simplex {simplex_uuid}")]
    MissingSimplexNeighborSlots {
        /// Simplex whose runtime neighbor slots are absent.
        simplex_uuid: Uuid,
    },
    /// A runtime neighbor key could not be resolved to a simplex UUID.
    #[error(
        "Neighbor key {neighbor_key:?} referenced by simplex {simplex_uuid} not found in simplices"
    )]
    DanglingRuntimeNeighborKey {
        /// Simplex containing the dangling runtime neighbor key.
        simplex_uuid: Uuid,
        /// Neighbor key that could not be resolved.
        neighbor_key: SimplexKey,
    },
    /// The runtime TDS failed validation before snapshot serialization.
    #[error("Source TDS failed validation before snapshot serialization: {source}")]
    SourceValidationFailed {
        /// Structured validation failure from the source TDS.
        #[source]
        source: TdsError,
    },
    /// A snapshot vertex UUID appeared more than once.
    #[error("Duplicate vertex UUID {vertex_uuid} in TDS snapshot vertices")]
    DuplicateVertexUuid {
        /// Duplicate vertex UUID from the snapshot vertex records.
        vertex_uuid: Uuid,
    },
    /// A snapshot simplex record had no matching vertex-UUID relationship.
    #[error("No vertex UUIDs found for simplex {simplex_uuid}")]
    MissingSimplexVertexUuids {
        /// Simplex UUID missing from the `simplex_vertices` relationship map.
        simplex_uuid: Uuid,
    },
    /// A snapshot simplex record had no matching neighbor-UUID relationship.
    #[error("No neighbor UUIDs found for simplex {simplex_uuid}")]
    MissingSimplexNeighborUuids {
        /// Simplex UUID missing from the `simplex_neighbors` relationship map.
        simplex_uuid: Uuid,
    },
    /// A simplex's serialized vertex UUID slots did not contain exactly `D + 1`
    /// entries.
    #[error(
        "Simplex {simplex_uuid} has {actual} vertex UUID slots in snapshot, expected {expected}"
    )]
    InvalidSimplexVertexUuidSlotCount {
        /// Simplex whose vertex UUID slot count is malformed.
        simplex_uuid: Uuid,
        /// Number of vertex UUID slots present in the snapshot.
        actual: usize,
        /// Expected number of vertex UUID slots (`D + 1`).
        expected: usize,
    },
    /// A simplex referenced a vertex UUID that was not present in the snapshot.
    #[error("Vertex UUID {vertex_uuid} referenced by simplex {simplex_uuid} not found in vertices")]
    DanglingSimplexVertexUuid {
        /// Simplex containing the dangling vertex reference.
        simplex_uuid: Uuid,
        /// Vertex UUID that could not be resolved to a snapshot vertex.
        vertex_uuid: Uuid,
    },
    /// A simplex referenced a neighbor UUID that was not present in the snapshot.
    #[error(
        "Neighbor UUID {neighbor_uuid} referenced by simplex {simplex_uuid} not found in simplices"
    )]
    DanglingSimplexNeighborUuid {
        /// Simplex containing the dangling neighbor reference.
        simplex_uuid: Uuid,
        /// Neighbor UUID that could not be resolved to a snapshot simplex.
        neighbor_uuid: Uuid,
    },
    /// A simplex could not be constructed from its resolved vertex keys or
    /// neighbor keys.
    #[error("Invalid snapshot simplex {simplex_uuid}: {source}")]
    InvalidSimplex {
        /// UUID of the simplex being reconstructed.
        simplex_uuid: Uuid,
        /// Structured simplex validation failure.
        #[source]
        source: SimplexValidationError,
    },
    /// A snapshot simplex UUID appeared more than once.
    #[error("Duplicate simplex UUID {simplex_uuid} in TDS snapshot simplices")]
    DuplicateSimplexUuid {
        /// Duplicate simplex UUID from the snapshot simplex records.
        simplex_uuid: Uuid,
    },
    /// The vertex-UUID relationship map mentioned an unknown simplex.
    #[error("Vertex UUID mapping provided for unknown simplex {simplex_uuid}")]
    UnknownSimplexVertexMapping {
        /// Unknown simplex UUID present in `simplex_vertices`.
        simplex_uuid: Uuid,
    },
    /// The neighbor-UUID relationship map mentioned an unknown simplex.
    #[error("Neighbor UUID mapping provided for unknown simplex {simplex_uuid}")]
    UnknownSimplexNeighborMapping {
        /// Unknown simplex UUID present in `simplex_neighbors`.
        simplex_uuid: Uuid,
    },
    /// The periodic-offset relationship map mentioned an unknown simplex.
    #[error("Periodic offset mapping provided for unknown simplex {simplex_uuid}")]
    UnknownSimplexOffsetMapping {
        /// Unknown simplex UUID present in `simplex_vertex_offsets`.
        simplex_uuid: Uuid,
    },
    /// A serialized periodic offset had the wrong coordinate dimension.
    #[error(
        "Periodic offset {offset_index} for simplex {simplex_uuid} has dimension {actual}, expected {expected}"
    )]
    PeriodicOffsetDimensionMismatch {
        /// Simplex whose offset record is malformed.
        simplex_uuid: Uuid,
        /// Offset index within the simplex-local offset list.
        offset_index: usize,
        /// Expected coordinate dimension.
        expected: usize,
        /// Observed coordinate dimension.
        actual: usize,
    },
    /// Rebuilding vertex incident-simplex pointers from snapshot topology failed.
    #[error("Failed to rebuild TDS vertex incidence from snapshot: {source}")]
    IncidentSimplexRebuildFailed {
        /// Structured TDS mutation failure from incident-simplex assignment.
        #[source]
        source: TdsMutationError,
    },
    /// Final TDS validation failed after UUID relationships were resolved.
    #[error("TDS snapshot failed validation: {source}")]
    ValidationFailed {
        /// Structured validation failure from the rebuilt TDS.
        #[source]
        source: TdsError,
    },
}

// =============================================================================
// RAW SNAPSHOT RECORD TYPES
// =============================================================================

/// Raw durable UUID-based image of a TDS topology.
///
/// This type is intentionally heavier than the runtime TDS. It is for I/O and
/// codec boundaries only, where stable UUID relationships are more important
/// than slotmap-key locality. It can contain cross-field inconsistencies until
/// parsed into [`TdsSnapshot`].
#[derive(Debug, Deserialize, Serialize)]
#[serde(
    bound(
        serialize = "U: DataSerialize, V: DataSerialize",
        deserialize = "U: DataDeserialize, V: DataDeserialize"
    ),
    deny_unknown_fields
)]
struct RawTdsSnapshot<U, V, const D: usize> {
    vertices: Vec<Vertex<U, D>>,
    simplices: Vec<RawSnapshotSimplex<V>>,
    #[serde(deserialize_with = "deserialize_simplex_vertices_no_duplicates")]
    simplex_vertices: FastHashMap<Uuid, Vec<Uuid>>,
    #[serde(deserialize_with = "deserialize_simplex_neighbors_no_duplicates")]
    simplex_neighbors: FastHashMap<Uuid, Vec<Option<Uuid>>>,
    #[serde(
        default,
        deserialize_with = "deserialize_simplex_vertex_offsets_no_duplicates"
    )]
    simplex_vertex_offsets: FastHashMap<Uuid, Vec<Vec<i8>>>,
}

fn deserialize_simplex_vertices_no_duplicates<'de, De>(
    deserializer: De,
) -> Result<FastHashMap<Uuid, Vec<Uuid>>, De::Error>
where
    De: Deserializer<'de>,
{
    deserialize_uuid_map_no_duplicates("simplex_vertices", deserializer)
}

fn deserialize_simplex_neighbors_no_duplicates<'de, De>(
    deserializer: De,
) -> Result<FastHashMap<Uuid, Vec<Option<Uuid>>>, De::Error>
where
    De: Deserializer<'de>,
{
    deserialize_uuid_map_no_duplicates("simplex_neighbors", deserializer)
}

fn deserialize_simplex_vertex_offsets_no_duplicates<'de, De>(
    deserializer: De,
) -> Result<FastHashMap<Uuid, Vec<Vec<i8>>>, De::Error>
where
    De: Deserializer<'de>,
{
    deserialize_uuid_map_no_duplicates("simplex_vertex_offsets", deserializer)
}

/// Deserializes a UUID relationship map while rejecting duplicate simplex keys.
///
/// This protects the public [`Tds`] deserialization contract: untrusted snapshot
/// input must not be able to rely on codec-level "last key wins" behavior to
/// replace vertex, neighbor, or periodic-offset relationships silently.
fn deserialize_uuid_map_no_duplicates<'de, De, T>(
    field_name: &'static str,
    deserializer: De,
) -> Result<FastHashMap<Uuid, T>, De::Error>
where
    De: Deserializer<'de>,
    T: Deserialize<'de>,
{
    struct UuidMapVisitor<T> {
        field_name: &'static str,
        _phantom: PhantomData<T>,
    }

    impl<'de, T> Visitor<'de> for UuidMapVisitor<T>
    where
        T: Deserialize<'de>,
    {
        type Value = FastHashMap<Uuid, T>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            write!(
                formatter,
                "a UUID-keyed TDS snapshot `{}` relationship map",
                self.field_name
            )
        }

        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
        where
            A: MapAccess<'de>,
        {
            let mut values = fast_hash_map_with_capacity(map.size_hint().unwrap_or(0));

            while let Some((simplex_uuid, value)) = map.next_entry::<Uuid, T>()? {
                match values.entry(simplex_uuid) {
                    Entry::Occupied(entry) => {
                        return Err(de::Error::custom(format!(
                            "duplicate simplex UUID key `{}` in TDS snapshot `{}` relationship map",
                            entry.key(),
                            self.field_name
                        )));
                    }
                    Entry::Vacant(entry) => {
                        entry.insert(value);
                    }
                }
            }

            Ok(values)
        }
    }

    deserializer.deserialize_map(UuidMapVisitor {
        field_name,
        _phantom: PhantomData,
    })
}

/// Raw snapshot simplex record used by [`RawTdsSnapshot`].
///
/// The record stores only durable simplex identity and optional payload. TDS
/// topology relationships live in `RawTdsSnapshot`'s UUID maps.
#[derive(Debug)]
struct RawSnapshotSimplex<V> {
    uuid: Uuid,
    data: Option<V>,
}

// =============================================================================
// VALIDATED SNAPSHOT TYPES
// =============================================================================

/// Validated durable UUID snapshot for a TDS topology.
///
/// This proof-bearing type is the internal boundary between raw interchange
/// records and live slotmap-backed runtime storage. Its private fields carry
/// UUID relationships that have already been checked for duplicate identities,
/// missing relationship records, dangling UUID references, and malformed
/// per-simplex arity.
#[derive(Debug)]
struct TdsSnapshot<U, V, const D: usize> {
    vertices: Vec<Vertex<U, D>>,
    simplices: Vec<TdsSnapshotSimplex<V, D>>,
}

/// Validated durable simplex identity and UUID connectivity.
///
/// Runtime `Simplex` values keep slotmap-local vertex and neighbor keys. This
/// snapshot simplex keeps the same relationships as UUIDs so hydration can
/// allocate fresh keys without trusting process-local handles from disk.
#[derive(Debug)]
struct TdsSnapshotSimplex<V, const D: usize> {
    uuid: Uuid,
    data: Option<V>,
    vertex_uuids: SnapshotVertexUuidSlots<D>,
    neighbor_uuids: SnapshotNeighborUuidSlots<D>,
    periodic_vertex_offsets: Option<SnapshotPeriodicOffsetSlots<D>>,
}

/// Validated UUID slots aligned with one D-simplex's vertex positions.
///
/// The raw interchange shape uses `Vec<Uuid>` because codecs cannot express the
/// `D + 1` invariant. This private wrapper is the parsed representation: it is
/// constructed only after checking arity, dangling UUID references, and duplicate
/// lifted vertex identities.
#[derive(Debug)]
struct SnapshotVertexUuidSlots<const D: usize> {
    slots: SimplexVertexUuidBuffer,
}

impl<const D: usize> SnapshotVertexUuidSlots<D> {
    /// Parses untrusted vertex UUID slots and proves they match one D-simplex.
    fn parse(
        simplex_uuid: Uuid,
        slots: &[Uuid],
        vertex_uuids: &SnapshotUuidSet,
        periodic_offsets: Option<&SnapshotPeriodicOffsetSlots<D>>,
    ) -> Result<Self, TdsSnapshotError> {
        validate_snapshot_vertex_slot_arity::<D>(simplex_uuid, slots.len())?;

        for (index, &vertex_uuid) in slots.iter().enumerate() {
            if !vertex_uuids.contains(&vertex_uuid) {
                return Err(TdsSnapshotError::DanglingSimplexVertexUuid {
                    simplex_uuid,
                    vertex_uuid,
                });
            }
            if (0..index).any(|earlier| {
                slots[earlier] == vertex_uuid
                    && periodic_offsets
                        .is_none_or(|offsets| offsets.slots[earlier] == offsets.slots[index])
            }) {
                return Err(TdsSnapshotError::InvalidSimplex {
                    simplex_uuid,
                    source: SimplexValidationError::DuplicateVertices,
                });
            }
        }

        Ok(Self::from_validated_slice(slots))
    }

    /// Builds vertex UUID slots from validated runtime state before serialization.
    fn try_from_runtime(
        simplex_uuid: Uuid,
        slots: &[Uuid],
        periodic_offsets: Option<&SnapshotPeriodicOffsetSlots<D>>,
    ) -> Result<Self, TdsSnapshotError> {
        validate_snapshot_vertex_slot_arity::<D>(simplex_uuid, slots.len())?;

        for (index, &vertex_uuid) in slots.iter().enumerate() {
            if (0..index).any(|earlier| {
                slots[earlier] == vertex_uuid
                    && periodic_offsets
                        .is_none_or(|offsets| offsets.slots[earlier] == offsets.slots[index])
            }) {
                return Err(TdsSnapshotError::InvalidSimplex {
                    simplex_uuid,
                    source: SimplexValidationError::DuplicateVertices,
                });
            }
        }

        Ok(Self::from_validated_slice(slots))
    }

    /// Stores an already checked vertex UUID slice in the snapshot buffer type.
    fn from_validated_slice(slots: &[Uuid]) -> Self {
        let mut checked_slots = SimplexVertexUuidBuffer::with_capacity(slots.len());
        checked_slots.extend(slots.iter().copied());
        Self {
            slots: checked_slots,
        }
    }

    /// Exposes checked vertex UUID slots without reopening raw parse validation.
    fn iter(&self) -> impl Iterator<Item = &Uuid> {
        self.slots.iter()
    }

    /// Converts checked vertex UUID slots back to the raw codec-friendly shape.
    fn into_vec(self) -> Vec<Uuid> {
        self.slots.into_vec()
    }
}

/// Validated optional neighbor UUID slots aligned with one D-simplex's facets.
#[derive(Debug)]
struct SnapshotNeighborUuidSlots<const D: usize> {
    slots: NeighborBuffer<Option<Uuid>>,
}

impl<const D: usize> SnapshotNeighborUuidSlots<D> {
    /// Parses untrusted neighbor UUID slots and proves referenced simplices exist.
    fn parse(
        simplex_uuid: Uuid,
        slots: &[Option<Uuid>],
        simplex_uuids: &SnapshotUuidSet,
    ) -> Result<Self, TdsSnapshotError> {
        validate_snapshot_neighbor_slot_arity::<D>(simplex_uuid, slots.len())?;

        for &neighbor_uuid in slots.iter().flatten() {
            if !simplex_uuids.contains(&neighbor_uuid) {
                return Err(TdsSnapshotError::DanglingSimplexNeighborUuid {
                    simplex_uuid,
                    neighbor_uuid,
                });
            }
        }

        Ok(Self::from_validated_slice(slots))
    }

    /// Builds neighbor UUID slots from validated runtime neighbor keys.
    fn try_from_runtime(
        simplex_uuid: Uuid,
        slots: &[Option<Uuid>],
    ) -> Result<Self, TdsSnapshotError> {
        validate_snapshot_neighbor_slot_arity::<D>(simplex_uuid, slots.len())?;
        Ok(Self::from_validated_slice(slots))
    }

    /// Stores an already checked neighbor UUID slice in the snapshot buffer type.
    fn from_validated_slice(slots: &[Option<Uuid>]) -> Self {
        let mut checked_slots = NeighborBuffer::with_capacity(slots.len());
        checked_slots.extend(slots.iter().copied());
        Self {
            slots: checked_slots,
        }
    }

    /// Exposes checked neighbor UUID slots for hydration into slotmap keys.
    fn iter(&self) -> impl Iterator<Item = &Option<Uuid>> {
        self.slots.iter()
    }

    /// Converts checked neighbor UUID slots back to the raw codec-friendly shape.
    fn into_vec(self) -> Vec<Option<Uuid>> {
        self.slots.into_vec()
    }
}

/// Validated periodic-offset slots aligned with one D-simplex's vertex slots.
#[derive(Debug)]
struct SnapshotPeriodicOffsetSlots<const D: usize> {
    slots: PeriodicOffsetBuffer<D>,
}

impl<const D: usize> SnapshotPeriodicOffsetSlots<D> {
    /// Parses raw periodic-offset rows and proves they match simplex vertex slots.
    fn parse(simplex_uuid: Uuid, offsets: &[Vec<i8>]) -> Result<Self, TdsSnapshotError> {
        let mut slots = PeriodicOffsetBuffer::new();
        for (offset_index, offset) in offsets.iter().enumerate() {
            let parsed_offset = offset.as_slice().try_into().map_err(|_| {
                TdsSnapshotError::PeriodicOffsetDimensionMismatch {
                    simplex_uuid,
                    offset_index,
                    expected: D,
                    actual: offset.len(),
                }
            })?;
            slots.push(parsed_offset);
        }
        Self::try_from_parsed_offsets(simplex_uuid, slots)
    }

    /// Builds periodic-offset slots from runtime fixed-size offset arrays.
    fn try_from_runtime(simplex_uuid: Uuid, offsets: &[[i8; D]]) -> Result<Self, TdsSnapshotError> {
        Self::try_from_parsed_offsets(simplex_uuid, offsets.iter().copied())
    }

    /// Stores parsed offsets after proving there is one offset per simplex vertex.
    fn try_from_parsed_offsets(
        simplex_uuid: Uuid,
        offsets: impl IntoIterator<Item = [i8; D]>,
    ) -> Result<Self, TdsSnapshotError> {
        let mut slots = PeriodicOffsetBuffer::new();
        slots.extend(offsets);
        if slots.len() != D + 1 {
            return Err(TdsSnapshotError::InvalidSimplex {
                simplex_uuid,
                source: SimplexValidationError::PeriodicOffsetLengthMismatch {
                    expected: D + 1,
                    found: slots.len(),
                },
            });
        }
        Ok(Self { slots })
    }

    /// Converts checked offsets to the runtime buffer expected by `Simplex`.
    fn into_buffer(self) -> PeriodicOffsetBuffer<D> {
        self.slots
    }

    /// Converts checked offsets back to the raw row-based codec shape.
    fn into_raw_rows(self) -> Vec<Vec<i8>> {
        self.slots
            .into_iter()
            .map(|offset| offset.to_vec())
            .collect()
    }
}

impl<SnapshotData, const D: usize> TdsSnapshotSimplex<SnapshotData, D> {
    /// Builds validated UUID relationships around caller-selected snapshot payload data.
    ///
    /// The relationship checks are identical for owned and borrowed payloads, so
    /// this helper lets [`Tds`] serialization borrow `U`/`V` data while tests can
    /// still build owned raw snapshots for mutation.
    fn try_from_simplex_with_data<U, RuntimeData>(
        tds: &Tds<U, RuntimeData, D>,
        simplex: &Simplex<RuntimeData, D>,
        data: Option<SnapshotData>,
    ) -> Result<Self, TdsSnapshotError> {
        let simplex_uuid = simplex.uuid();
        let vertex_uuids = simplex.vertex_uuids(tds).map_err(|source| {
            TdsSnapshotError::SimplexVertexUuidResolutionFailed {
                simplex_uuid,
                source,
            }
        })?;
        let neighbor_uuids = simplex
            .neighbor_keys()
            .ok_or(TdsSnapshotError::MissingSimplexNeighborSlots { simplex_uuid })?
            .map(|neighbor_key| {
                neighbor_key
                    .map(|neighbor_key| {
                        tds.simplex_uuid_from_key(neighbor_key).ok_or(
                            TdsSnapshotError::DanglingRuntimeNeighborKey {
                                simplex_uuid,
                                neighbor_key,
                            },
                        )
                    })
                    .transpose()
            })
            .collect::<Result<Vec<_>, TdsSnapshotError>>()?;
        let periodic_vertex_offsets = simplex
            .periodic_vertex_offsets()
            .map(|offsets| SnapshotPeriodicOffsetSlots::try_from_runtime(simplex_uuid, offsets))
            .transpose()?;
        let vertex_uuids = SnapshotVertexUuidSlots::try_from_runtime(
            simplex_uuid,
            &vertex_uuids,
            periodic_vertex_offsets.as_ref(),
        )?;
        let neighbor_uuids =
            SnapshotNeighborUuidSlots::try_from_runtime(simplex_uuid, &neighbor_uuids)?;

        Ok(Self {
            uuid: simplex_uuid,
            data,
            neighbor_uuids,
            vertex_uuids,
            periodic_vertex_offsets,
        })
    }

    /// Converts this validated simplex relationship record back into the raw
    /// simplex record and raw relationship maps used by the interchange shape.
    fn into_raw_parts(self) -> RawSnapshotSimplexParts<SnapshotData> {
        let raw_simplex = RawSnapshotSimplex {
            uuid: self.uuid,
            data: self.data,
        };
        let raw_offsets = self
            .periodic_vertex_offsets
            .map(SnapshotPeriodicOffsetSlots::into_raw_rows);
        (
            raw_simplex,
            self.vertex_uuids.into_vec(),
            self.neighbor_uuids.into_vec(),
            raw_offsets,
        )
    }
}

impl<V> Serialize for RawSnapshotSimplex<V>
where
    V: DataSerialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let has_data = self.data.is_some();
        let field_count = if has_data { 2 } else { 1 };
        let mut state = serializer.serialize_struct("Simplex", field_count)?;
        state.serialize_field("uuid", &self.uuid)?;
        if has_data {
            state.serialize_field("data", &self.data)?;
        }
        state.end()
    }
}

impl<'de, V> Deserialize<'de> for RawSnapshotSimplex<V>
where
    V: DataDeserialize,
{
    fn deserialize<De>(deserializer: De) -> Result<Self, De::Error>
    where
        De: Deserializer<'de>,
    {
        struct SnapshotSimplexVisitor<V> {
            _phantom: PhantomData<V>,
        }

        impl<'de, V> Visitor<'de> for SnapshotSimplexVisitor<V>
        where
            V: DataDeserialize,
        {
            type Value = RawSnapshotSimplex<V>;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a TDS snapshot simplex record")
            }

            fn visit_map<A>(self, mut map: A) -> Result<RawSnapshotSimplex<V>, A::Error>
            where
                A: MapAccess<'de>,
            {
                let mut uuid = None;
                let mut data: Option<V> = None;

                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "uuid" => {
                            if uuid.is_some() {
                                return Err(de::Error::duplicate_field("uuid"));
                            }
                            uuid = Some(map.next_value()?);
                        }
                        "data" => {
                            if data.is_some() {
                                return Err(de::Error::duplicate_field("data"));
                            }
                            data = Some(map.next_value()?);
                        }
                        "vertices" | "neighbors" | "periodic_vertex_offsets" => {
                            return Err(de::Error::custom(format!(
                                "{key} is storage-local simplex state and must not be deserialized; deserialize Tds so UUID relationships can be reconstructed",
                            )));
                        }
                        _ => {
                            return Err(de::Error::custom(format!(
                                "unknown snapshot simplex field `{key}`, expected `uuid` or `data`"
                            )));
                        }
                    }
                }

                let uuid: Uuid = uuid.ok_or_else(|| de::Error::missing_field("uuid"))?;
                validate_uuid(&uuid)
                    .map_err(|source| de::Error::custom(format!("invalid uuid: {source}")))?;

                Ok(RawSnapshotSimplex { uuid, data })
            }
        }

        const FIELDS: &[&str] = &["uuid", "data"];
        deserializer.deserialize_struct(
            "RawSnapshotSimplex",
            FIELDS,
            SnapshotSimplexVisitor {
                _phantom: PhantomData,
            },
        )
    }
}

struct ParsedVertexStorage<U, const D: usize> {
    vertices: StorageMap<VertexKey, Vertex<U, D>>,
    uuid_to_vertex_key: UuidToVertexKeyMap,
}

struct ParsedSimplexStorage<V, const D: usize> {
    simplices: StorageMap<SimplexKey, Simplex<V, D>>,
    uuid_to_simplex_key: UuidToSimplexKeyMap,
}

type SnapshotUuidSet = FastHashSet<Uuid>;
type SnapshotNeighborAssignments<const D: usize> =
    Vec<(Uuid, SimplexKey, SnapshotNeighborUuidSlots<D>)>;
type RawSnapshotSimplexParts<V> = (
    RawSnapshotSimplex<V>,
    Vec<Uuid>,
    Vec<Option<Uuid>>,
    Option<Vec<Vec<i8>>>,
);

// =============================================================================
// SNAPSHOT CONVERSION
// =============================================================================

impl<U, V, const D: usize> RawTdsSnapshot<U, V, D> {
    /// Parses raw snapshot records into a validated UUID snapshot.
    fn parse(self) -> Result<TdsSnapshot<U, V, D>, TdsSnapshotError> {
        let Self {
            vertices,
            simplices,
            simplex_vertices,
            simplex_neighbors,
            simplex_vertex_offsets,
        } = self;

        let vertex_uuids = collect_vertex_uuids(&vertices)?;
        let simplex_uuids = collect_simplex_uuids(&simplices)?;
        validate_relationship_keys(
            &simplex_uuids,
            &simplex_vertices,
            &simplex_neighbors,
            &simplex_vertex_offsets,
        )?;

        let simplices = simplices
            .into_iter()
            .map(|raw_simplex| {
                parse_raw_simplex(
                    raw_simplex,
                    &vertex_uuids,
                    &simplex_uuids,
                    &simplex_vertices,
                    &simplex_neighbors,
                    &simplex_vertex_offsets,
                )
            })
            .collect::<Result<Vec<_>, TdsSnapshotError>>()?;

        Ok(TdsSnapshot {
            vertices,
            simplices,
        })
    }
}

impl<U, V, const D: usize> TdsSnapshot<U, V, D> {
    /// Converts a valid live key-based TDS into an owned snapshot for mutation tests.
    ///
    /// Production serialization uses the borrowed `from_tds` path below so non-`Copy`
    /// payloads can still cross the public [`Tds`] codec boundary.
    #[cfg(test)]
    fn try_from_tds_owned(tds: &Tds<U, V, D>) -> Result<Self, TdsSnapshotError>
    where
        U: Copy,
        V: Copy,
    {
        tds.validate()
            .map_err(|source| TdsSnapshotError::SourceValidationFailed { source })?;

        let vertices = tds
            .vertices()
            .map(|(_vertex_key, vertex)| *vertex)
            .collect();
        let simplices = tds
            .simplices()
            .map(|(_simplex_key, simplex)| {
                TdsSnapshotSimplex::try_from_simplex_with_data(tds, simplex, simplex.data)
            })
            .collect::<Result<Vec<_>, TdsSnapshotError>>()?;

        Ok(Self {
            vertices,
            simplices,
        })
    }

    /// Converts this validated snapshot into the raw serializable shape.
    fn into_raw(self) -> RawTdsSnapshot<U, V, D> {
        let mut raw_simplices = Vec::with_capacity(self.simplices.len());
        let mut simplex_vertices = fast_hash_map_with_capacity(self.simplices.len());
        let mut simplex_neighbors = fast_hash_map_with_capacity(self.simplices.len());
        let mut simplex_vertex_offsets = fast_hash_map_with_capacity(self.simplices.len());

        for simplex in self.simplices {
            let simplex_uuid = simplex.uuid;
            let (raw_simplex, vertex_uuids, neighbor_uuids, offsets) = simplex.into_raw_parts();
            raw_simplices.push(raw_simplex);
            simplex_vertices.insert(simplex_uuid, vertex_uuids);
            simplex_neighbors.insert(simplex_uuid, neighbor_uuids);
            if let Some(offsets) = offsets {
                simplex_vertex_offsets.insert(simplex_uuid, offsets);
            }
        }

        RawTdsSnapshot {
            vertices: self.vertices,
            simplices: raw_simplices,
            simplex_vertices,
            simplex_neighbors,
            simplex_vertex_offsets,
        }
    }

    /// Parses a durable UUID snapshot into a fresh key-based runtime TDS.
    fn into_tds(self) -> Result<Tds<U, V, D>, TdsSnapshotError> {
        let ParsedVertexStorage {
            vertices,
            uuid_to_vertex_key,
        } = rebuild_vertices(self.vertices);

        let ParsedSimplexStorage {
            simplices,
            uuid_to_simplex_key,
        } = rebuild_simplices(&uuid_to_vertex_key, self.simplices)?;

        let mut tds = Tds {
            vertices,
            simplices,
            uuid_to_vertex_key,
            uuid_to_simplex_key,
            vertex_to_simplices: VertexIncidenceIndex::default(),
            construction_state: TriangulationConstructionState::Constructed,
            generation: Arc::new(AtomicU64::new(0)),
            identity: Arc::new(Uuid::new_v4()),
        };

        tds.assign_incident_simplices()
            .map_err(|source| TdsSnapshotError::IncidentSimplexRebuildFailed { source })?;
        tds.validate()
            .map_err(|source| TdsSnapshotError::ValidationFailed { source })?;

        Ok(tds)
    }
}

impl<'a, U, V, const D: usize> TdsSnapshot<&'a U, &'a V, D> {
    /// Converts a valid live key-based TDS into a borrowed durable UUID snapshot.
    ///
    /// This is the production serialization path for [`Tds`]. It validates the
    /// live topology, stores UUID relationships, and borrows payload data so
    /// callers only need [`DataSerialize`] rather than `Copy`.
    fn try_from_tds(tds: &'a Tds<U, V, D>) -> Result<Self, TdsSnapshotError> {
        tds.validate()
            .map_err(|source| TdsSnapshotError::SourceValidationFailed { source })?;

        let vertices = tds
            .vertices()
            .map(|(_vertex_key, vertex)| {
                let mut snapshot_vertex = Vertex::from_validated_point_with_uuid(
                    *vertex.point(),
                    vertex.uuid(),
                    vertex.data(),
                );
                snapshot_vertex.set_incident_simplex(vertex.incident_simplex());
                snapshot_vertex
            })
            .collect();
        let simplices = tds
            .simplices()
            .map(|(_simplex_key, simplex)| {
                TdsSnapshotSimplex::try_from_simplex_with_data(tds, simplex, simplex.data())
            })
            .collect::<Result<Vec<_>, TdsSnapshotError>>()?;

        Ok(Self {
            vertices,
            simplices,
        })
    }
}

/// Rebuilds vertex storage and UUID mappings from validated snapshot vertex records.
///
/// This consumes the `TdsSnapshot` proof that vertex UUIDs are unique. Raw input
/// must pass through `RawTdsSnapshot::parse` before reaching this hydration step.
fn rebuild_vertices<U, const D: usize>(
    snapshot_vertices: Vec<Vertex<U, D>>,
) -> ParsedVertexStorage<U, D> {
    let mut vertices = StorageMap::with_capacity_and_key(snapshot_vertices.len());
    let mut uuid_to_vertex_key = fast_hash_map_with_capacity(snapshot_vertices.len());

    for vertex in snapshot_vertices {
        let vertex_uuid = vertex.uuid();
        let vertex_key = vertices.insert(vertex);
        uuid_to_vertex_key.insert(vertex_uuid, vertex_key);
    }

    ParsedVertexStorage {
        vertices,
        uuid_to_vertex_key,
    }
}

/// Collects vertex UUIDs from raw snapshot vertices and rejects duplicates.
fn collect_vertex_uuids<U, const D: usize>(
    snapshot_vertices: &[Vertex<U, D>],
) -> Result<SnapshotUuidSet, TdsSnapshotError> {
    let mut vertex_uuids = fast_hash_set_with_capacity(snapshot_vertices.len());
    for vertex in snapshot_vertices {
        let vertex_uuid = vertex.uuid();
        if !vertex_uuids.insert(vertex_uuid) {
            return Err(TdsSnapshotError::DuplicateVertexUuid { vertex_uuid });
        }
    }
    Ok(vertex_uuids)
}

/// Collects simplex UUIDs from raw snapshot simplex records and rejects duplicates.
fn collect_simplex_uuids<V>(
    snapshot_simplices: &[RawSnapshotSimplex<V>],
) -> Result<SnapshotUuidSet, TdsSnapshotError> {
    let mut simplex_uuids = fast_hash_set_with_capacity(snapshot_simplices.len());
    for simplex in snapshot_simplices {
        let simplex_uuid = simplex.uuid;
        if !simplex_uuids.insert(simplex_uuid) {
            return Err(TdsSnapshotError::DuplicateSimplexUuid { simplex_uuid });
        }
    }
    Ok(simplex_uuids)
}

/// Parses one raw simplex record into a validated UUID connectivity record.
fn parse_raw_simplex<V, const D: usize>(
    raw_simplex: RawSnapshotSimplex<V>,
    vertex_uuids: &SnapshotUuidSet,
    simplex_uuids: &SnapshotUuidSet,
    simplex_vertices: &FastHashMap<Uuid, Vec<Uuid>>,
    simplex_neighbors: &FastHashMap<Uuid, Vec<Option<Uuid>>>,
    simplex_vertex_offsets: &FastHashMap<Uuid, Vec<Vec<i8>>>,
) -> Result<TdsSnapshotSimplex<V, D>, TdsSnapshotError> {
    let simplex_uuid = raw_simplex.uuid;
    let data = raw_simplex.data;
    let periodic_vertex_offsets = simplex_vertex_offsets
        .get(&simplex_uuid)
        .map(|offsets| SnapshotPeriodicOffsetSlots::parse(simplex_uuid, offsets))
        .transpose()?;

    let vertex_uuid_slots = simplex_vertices
        .get(&simplex_uuid)
        .ok_or(TdsSnapshotError::MissingSimplexVertexUuids { simplex_uuid })?;
    let vertex_uuids = SnapshotVertexUuidSlots::parse(
        simplex_uuid,
        vertex_uuid_slots,
        vertex_uuids,
        periodic_vertex_offsets.as_ref(),
    )?;

    let neighbor_uuid_slots = simplex_neighbors
        .get(&simplex_uuid)
        .ok_or(TdsSnapshotError::MissingSimplexNeighborUuids { simplex_uuid })?;
    let neighbor_uuids =
        SnapshotNeighborUuidSlots::parse(simplex_uuid, neighbor_uuid_slots, simplex_uuids)?;

    Ok(TdsSnapshotSimplex {
        uuid: simplex_uuid,
        data,
        vertex_uuids,
        neighbor_uuids,
        periodic_vertex_offsets,
    })
}

/// Validates the vertex UUID slot count for one parsed snapshot simplex.
fn validate_snapshot_vertex_slot_arity<const D: usize>(
    simplex_uuid: Uuid,
    actual: usize,
) -> Result<(), TdsSnapshotError> {
    if actual != D + 1 {
        return Err(TdsSnapshotError::InvalidSimplexVertexUuidSlotCount {
            simplex_uuid,
            actual,
            expected: D + 1,
        });
    }
    Ok(())
}

/// Validates the neighbor UUID slot count for one parsed snapshot simplex.
fn validate_snapshot_neighbor_slot_arity<const D: usize>(
    simplex_uuid: Uuid,
    actual: usize,
) -> Result<(), TdsSnapshotError> {
    if actual != D + 1 {
        return Err(TdsSnapshotError::InvalidSimplex {
            simplex_uuid,
            source: SimplexValidationError::InvalidNeighborsLength {
                actual,
                expected: D + 1,
                dimension: D,
            },
        });
    }
    Ok(())
}

/// Rebuilds simplex storage from validated snapshot UUID connectivity maps.
///
/// This consumes the `TdsSnapshot` proof that simplex UUIDs are unique, every
/// simplex has `D + 1` vertex and neighbor slots, relationship maps are complete,
/// and all serialized UUID references are non-dangling.
fn rebuild_simplices<V, const D: usize>(
    uuid_to_vertex_key: &UuidToVertexKeyMap,
    snapshot_simplices: Vec<TdsSnapshotSimplex<V, D>>,
) -> Result<ParsedSimplexStorage<V, D>, TdsSnapshotError> {
    let mut simplices = StorageMap::with_capacity_and_key(snapshot_simplices.len());
    let mut uuid_to_simplex_key = fast_hash_map_with_capacity(snapshot_simplices.len());
    let mut snapshot_neighbor_assignments = Vec::with_capacity(snapshot_simplices.len());

    for snapshot_simplex in snapshot_simplices {
        let simplex_uuid = snapshot_simplex.uuid;
        let vertex_keys = snapshot_simplex
            .vertex_uuids
            .iter()
            .map(|&vertex_uuid| {
                uuid_to_vertex_key.get(&vertex_uuid).copied().ok_or(
                    TdsSnapshotError::DanglingSimplexVertexUuid {
                        simplex_uuid,
                        vertex_uuid,
                    },
                )
            })
            .collect::<Result<Vec<_>, TdsSnapshotError>>()?;

        let simplex = match snapshot_simplex.periodic_vertex_offsets {
            Some(offsets) => Simplex::try_new_periodic_with_uuid(
                vertex_keys,
                offsets.into_buffer(),
                simplex_uuid,
                snapshot_simplex.data,
            ),
            None => Simplex::try_new_with_uuid(vertex_keys, simplex_uuid, snapshot_simplex.data),
        }
        .map_err(|source| TdsSnapshotError::InvalidSimplex {
            simplex_uuid,
            source,
        })?;

        let simplex_key = simplices.insert(simplex);
        uuid_to_simplex_key.insert(simplex_uuid, simplex_key);
        snapshot_neighbor_assignments.push((
            simplex_uuid,
            simplex_key,
            snapshot_simplex.neighbor_uuids,
        ));
    }

    assign_neighbors(
        &mut simplices,
        &uuid_to_simplex_key,
        snapshot_neighbor_assignments,
    )?;

    Ok(ParsedSimplexStorage {
        simplices,
        uuid_to_simplex_key,
    })
}

/// Rejects relationship maps that mention simplices absent from the snapshot
/// simplex records.
fn validate_relationship_keys(
    simplex_uuids: &SnapshotUuidSet,
    simplex_vertices: &FastHashMap<Uuid, Vec<Uuid>>,
    simplex_neighbors: &FastHashMap<Uuid, Vec<Option<Uuid>>>,
    simplex_vertex_offsets: &FastHashMap<Uuid, Vec<Vec<i8>>>,
) -> Result<(), TdsSnapshotError> {
    for &simplex_uuid in simplex_vertices.keys() {
        if !simplex_uuids.contains(&simplex_uuid) {
            return Err(TdsSnapshotError::UnknownSimplexVertexMapping { simplex_uuid });
        }
    }
    for &simplex_uuid in simplex_neighbors.keys() {
        if !simplex_uuids.contains(&simplex_uuid) {
            return Err(TdsSnapshotError::UnknownSimplexNeighborMapping { simplex_uuid });
        }
    }
    for &simplex_uuid in simplex_vertex_offsets.keys() {
        if !simplex_uuids.contains(&simplex_uuid) {
            return Err(TdsSnapshotError::UnknownSimplexOffsetMapping { simplex_uuid });
        }
    }

    Ok(())
}

/// Resolves snapshot neighbor UUID slots to live simplex-key slots.
fn assign_neighbors<V, const D: usize>(
    simplices: &mut StorageMap<SimplexKey, Simplex<V, D>>,
    uuid_to_simplex_key: &UuidToSimplexKeyMap,
    snapshot_neighbor_assignments: SnapshotNeighborAssignments<D>,
) -> Result<(), TdsSnapshotError> {
    for (simplex_uuid, simplex_key, neighbor_uuids) in snapshot_neighbor_assignments {
        let neighbor_keys = neighbor_uuids
            .iter()
            .map(|&neighbor_uuid| {
                neighbor_uuid
                    .map(|neighbor_uuid| {
                        uuid_to_simplex_key.get(&neighbor_uuid).copied().ok_or(
                            TdsSnapshotError::DanglingSimplexNeighborUuid {
                                simplex_uuid,
                                neighbor_uuid,
                            },
                        )
                    })
                    .transpose()
            })
            .collect::<Result<Vec<_>, TdsSnapshotError>>()?;

        let simplex = simplices
            .get_mut(simplex_key)
            .ok_or(TdsSnapshotError::UnknownSimplexNeighborMapping { simplex_uuid })?;
        simplex
            .set_neighbors_from_keys(neighbor_keys)
            .map_err(|source| TdsSnapshotError::InvalidSimplex {
                simplex_uuid,
                source,
            })?;
    }

    Ok(())
}

// =============================================================================
// TDS CODEC IMPLEMENTATIONS
// =============================================================================

impl<U, V, const D: usize> Serialize for Tds<U, V, D>
where
    U: DataSerialize,
    V: DataSerialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        TdsSnapshot::try_from_tds(self)
            .map_err(serde::ser::Error::custom)?
            .into_raw()
            .serialize(serializer)
    }
}

impl<'de, U, V, const D: usize> Deserialize<'de> for Tds<U, V, D>
where
    U: DataDeserialize,
    V: DataDeserialize,
{
    fn deserialize<De>(deserializer: De) -> Result<Self, De::Error>
    where
        De: Deserializer<'de>,
    {
        RawTdsSnapshot::<U, V, D>::deserialize(deserializer)?
            .parse()
            .map_err(de::Error::custom)?
            .into_tds()
            .map_err(de::Error::custom)
    }
}

// =============================================================================
// TESTS
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::DelaunayTriangulation;
    use crate::core::simplex::SimplexValidationError;
    use crate::core::tds::TriangulationConstructionState;
    use crate::core::vertex::Vertex;
    use crate::geometry::point::Point;
    use crate::vertex;
    use proptest::prelude::*;
    use slotmap::KeyData;
    use std::assert_matches;

    fn initial_simplex_vertices_3d() -> [Vertex<(), 3>; 4] {
        [
            vertex!([0.0, 0.0, 0.0]).unwrap(),
            vertex!([1.0, 0.0, 0.0]).unwrap(),
            vertex!([0.0, 1.0, 0.0]).unwrap(),
            vertex!([0.0, 0.0, 1.0]).unwrap(),
        ]
    }

    fn periodic_offset_tds_2d() -> (Tds<(), (), 2>, Uuid, Vec<[i8; 2]>) {
        let offsets = vec![[0_i8, 0_i8], [1_i8, 0_i8], [0_i8, 1_i8]];
        let (tds, simplex_uuid) = periodic_offset_tds(&offsets);
        (tds, simplex_uuid, offsets)
    }

    fn raw_snapshot_from_tds<U, V, const D: usize>(tds: &Tds<U, V, D>) -> RawTdsSnapshot<U, V, D>
    where
        U: Copy,
        V: Copy,
    {
        TdsSnapshot::try_from_tds_owned(tds)
            .expect("TDS should snapshot")
            .into_raw()
    }

    #[derive(Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
    struct NonCopyPayload {
        label: String,
    }

    /// Builds a one-simplex TDS with caller-selected aligned periodic offsets.
    fn periodic_offset_tds<const D: usize>(offsets: &[[i8; D]]) -> (Tds<(), (), D>, Uuid) {
        assert_eq!(offsets.len(), D + 1);
        let mut tds = Tds::empty();
        let vertex_keys: Vec<_> = (0..=D)
            .map(|index| {
                let coordinate =
                    f64::from(u32::try_from(index).expect("test vertex index fits in u32"));
                let coords = std::array::from_fn(|axis| if axis == 0 { coordinate } else { 0.0 });
                tds.insert_vertex_with_mapping(
                    vertex!(coords).expect("test coordinates are finite"),
                )
                .expect("generated vertex should insert")
            })
            .collect();
        let mut simplex =
            Simplex::try_new(vertex_keys).expect("generated simplex keys are distinct");
        simplex
            .set_periodic_vertex_offsets(offsets.to_vec())
            .expect("one offset per simplex vertex");
        let simplex_uuid = simplex.uuid();
        tds.insert_simplex_with_mapping(simplex)
            .expect("generated simplex should insert");
        tds.construction_state = TriangulationConstructionState::Constructed;
        tds.assign_neighbors()
            .expect("generated simplex facets should be indexable");
        tds.assign_incident_simplices()
            .expect("generated incidence should assign");
        (tds, simplex_uuid)
    }

    /// Builds raw snapshot JSON with a duplicated object key in one relationship map.
    ///
    /// `serde_json::Value` cannot represent duplicate object keys, so this helper
    /// constructs the JSON text needed to exercise duplicate-key deserialization.
    fn snapshot_json_with_duplicate_relationship_key(field: &str) -> String {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();
        let snapshot = raw_snapshot_from_tds(dt.tds());
        let simplex_uuid = snapshot
            .simplices
            .first()
            .expect("snapshot should contain a simplex")
            .uuid;

        let duplicate_value = match field {
            "simplex_vertices" => serde_json::to_string(
                snapshot
                    .simplex_vertices
                    .get(&simplex_uuid)
                    .expect("snapshot should contain simplex vertex UUIDs"),
            ),
            "simplex_neighbors" => serde_json::to_string(
                snapshot
                    .simplex_neighbors
                    .get(&simplex_uuid)
                    .expect("snapshot should contain simplex neighbor UUIDs"),
            ),
            "simplex_vertex_offsets" => serde_json::to_string(&[[0_i8; 3]; 4]),
            _ => panic!("unknown relationship map field {field}"),
        }
        .expect("duplicate relationship value should serialize");
        let duplicate_map =
            format!(r#"{{"{simplex_uuid}":{duplicate_value},"{simplex_uuid}":{duplicate_value}}}"#);

        let vertices =
            serde_json::to_string(&snapshot.vertices).expect("snapshot vertices should serialize");
        let simplices = serde_json::to_string(&snapshot.simplices)
            .expect("snapshot simplices should serialize");
        let simplex_vertices = if field == "simplex_vertices" {
            duplicate_map.clone()
        } else {
            serde_json::to_string(&snapshot.simplex_vertices)
                .expect("simplex_vertices should serialize")
        };
        let simplex_neighbors = if field == "simplex_neighbors" {
            duplicate_map.clone()
        } else {
            serde_json::to_string(&snapshot.simplex_neighbors)
                .expect("simplex_neighbors should serialize")
        };
        let simplex_vertex_offsets = if field == "simplex_vertex_offsets" {
            duplicate_map
        } else {
            serde_json::to_string(&snapshot.simplex_vertex_offsets)
                .expect("simplex_vertex_offsets should serialize")
        };

        format!(
            r#"{{"vertices":{vertices},"simplices":{simplices},"simplex_vertices":{simplex_vertices},"simplex_neighbors":{simplex_neighbors},"simplex_vertex_offsets":{simplex_vertex_offsets}}}"#
        )
    }

    fn serialized_records<'a>(json: &'a serde_json::Value, field: &str) -> &'a [serde_json::Value] {
        let Some(records) = json.get(field).and_then(serde_json::Value::as_array) else {
            panic!("serialized TDS should contain {field} records");
        };
        let records = records.as_slice();

        for record in records {
            assert!(
                record.get("value").is_none(),
                "serialized TDS {field} records must not use slotmap value wrappers"
            );
        }

        records
    }

    fn serialized_uuid_field(json: &serde_json::Value, field: &str) -> Uuid {
        let uuid = json
            .get(field)
            .and_then(serde_json::Value::as_str)
            .and_then(|value| Uuid::parse_str(value).ok())
            .unwrap_or_else(|| panic!("serialized record should contain {field} UUID"));
        assert!(!uuid.is_nil(), "serialized {field} UUID should not be nil");
        uuid
    }

    /// Generates periodic snapshot round-trip properties in every practical dimension.
    macro_rules! gen_periodic_snapshot_properties {
        ($dim:literal, $uniform:path) => {
            pastey::paste! {
                proptest! {
                    #![proptest_config(ProptestConfig::with_cases(32))]

                    /// Snapshot hydration preserves every periodic offset slot exactly.
                    #[test]
                    fn [<prop_periodic_snapshot_round_trip_ $dim d>](
                        offsets in prop::collection::vec(
                            $uniform(-32_i8..=32_i8),
                            ($dim + 1)..=($dim + 1),
                        ),
                    ) {
                        let (original, simplex_uuid) = periodic_offset_tds::<$dim>(&offsets);
                        let json = serde_json::to_value(&original)
                            .expect("generated periodic TDS should serialize");
                        let restored_result = serde_json::from_value::<Tds<(), (), $dim>>(json);
                        prop_assert!(
                            restored_result.is_ok(),
                            "generated periodic snapshot failed to hydrate: {:?}",
                            restored_result.as_ref().err(),
                        );
                        let restored = restored_result.expect("successful result checked above");
                        let simplex_key = restored
                            .simplex_key_from_uuid(&simplex_uuid)
                            .expect("simplex UUID should survive round-trip");
                        let restored_offsets = restored
                            .simplex(simplex_key)
                            .and_then(Simplex::periodic_vertex_offsets)
                            .expect("periodic offsets should survive round-trip");

                        prop_assert_eq!(restored_offsets, offsets.as_slice());
                        prop_assert!(restored.is_valid().is_ok());
                    }
                }
            }
        };
    }

    gen_periodic_snapshot_properties!(2, prop::array::uniform2);
    gen_periodic_snapshot_properties!(3, prop::array::uniform3);
    gen_periodic_snapshot_properties!(4, prop::array::uniform4);
    gen_periodic_snapshot_properties!(5, prop::array::uniform5);

    #[test]
    fn test_tds_snapshot_serialization_includes_stable_uuid_relationships() {
        let vertices = [
            vertex!([0.0, 0.0, 0.0]).unwrap(),
            vertex!([1.0, 0.0, 0.0]).unwrap(),
            vertex!([0.0, 1.0, 0.0]).unwrap(),
            vertex!([0.0, 0.0, 1.0]).unwrap(),
            vertex!([0.5, 0.5, 0.5]).unwrap(),
        ];
        let dt = DelaunayTriangulation::builder(&vertices).build().unwrap();
        let original = dt.tds().clone();
        let json = serde_json::to_value(&original).expect("serialize TDS to JSON value");

        let vertex_uuids: Vec<_> = serialized_records(&json, "vertices")
            .iter()
            .map(|vertex| serialized_uuid_field(vertex, "uuid"))
            .collect();
        assert_eq!(vertex_uuids.len(), original.number_of_vertices());
        for (_, vertex) in original.vertices() {
            assert!(vertex_uuids.contains(&vertex.uuid()));
        }

        let simplex_uuids: Vec<_> = serialized_records(&json, "simplices")
            .iter()
            .map(|simplex| {
                assert!(
                    simplex.get("vertices").is_none(),
                    "serialized Simplex must not store slotmap VertexKey values"
                );
                serialized_uuid_field(simplex, "uuid")
            })
            .collect();
        assert_eq!(simplex_uuids.len(), original.number_of_simplices());
        for (_, simplex) in original.simplices() {
            assert!(simplex_uuids.contains(&simplex.uuid()));
        }

        let simplex_vertices = json
            .get("simplex_vertices")
            .and_then(serde_json::Value::as_object)
            .expect("serialized TDS should contain simplex_vertices object");
        assert_eq!(simplex_vertices.len(), original.number_of_simplices());

        for (simplex_uuid, serialized_vertex_uuids) in simplex_vertices {
            let simplex_uuid =
                Uuid::parse_str(simplex_uuid).expect("simplex_vertices keys should be UUIDs");
            assert!(simplex_uuids.contains(&simplex_uuid));
            let simplex_key = original
                .simplex_key_from_uuid(&simplex_uuid)
                .expect("serialized simplex UUID should resolve in original TDS");
            let expected_vertex_uuids = original
                .simplex(simplex_key)
                .expect("serialized simplex key should resolve")
                .vertex_uuids(&original)
                .expect("simplex vertex UUIDs should resolve");
            let serialized_vertex_uuids: Vec<_> = serialized_vertex_uuids
                .as_array()
                .expect("simplex_vertices values should be UUID arrays")
                .iter()
                .map(|vertex_uuid| {
                    let vertex_uuid = vertex_uuid
                        .as_str()
                        .and_then(|value| Uuid::parse_str(value).ok())
                        .expect("simplex vertex reference should be a UUID string");
                    assert!(vertex_uuids.contains(&vertex_uuid));
                    vertex_uuid
                })
                .collect();
            assert_eq!(
                serialized_vertex_uuids.as_slice(),
                expected_vertex_uuids.as_slice()
            );
        }

        let simplex_neighbors = json
            .get("simplex_neighbors")
            .and_then(serde_json::Value::as_object)
            .expect("serialized TDS should contain simplex_neighbors object");
        assert_eq!(simplex_neighbors.len(), original.number_of_simplices());

        for (simplex_uuid, serialized_neighbor_uuids) in simplex_neighbors {
            let simplex_uuid =
                Uuid::parse_str(simplex_uuid).expect("simplex_neighbors keys should be UUIDs");
            assert!(simplex_uuids.contains(&simplex_uuid));
            let simplex_key = original
                .simplex_key_from_uuid(&simplex_uuid)
                .expect("serialized simplex UUID should resolve in original TDS");
            let expected_neighbor_uuids: Vec<_> = original
                .simplex(simplex_key)
                .expect("serialized simplex key should resolve")
                .neighbors()
                .expect("serialized TDS should have assigned neighbor slots")
                .map(|neighbor_key| {
                    neighbor_key.and_then(|key| original.simplex_uuid_from_key(key))
                })
                .collect();
            let serialized_neighbor_uuids: Vec<_> = serialized_neighbor_uuids
                .as_array()
                .expect("simplex_neighbors values should be nullable UUID arrays")
                .iter()
                .map(|neighbor_uuid| {
                    neighbor_uuid.as_str().map(|value| {
                        Uuid::parse_str(value).expect("simplex neighbor reference should be a UUID")
                    })
                })
                .collect();
            assert_eq!(serialized_neighbor_uuids, expected_neighbor_uuids);
        }
    }

    #[test]
    fn test_tds_snapshot_deserialize_rejects_unknown_simplex_record_fields() {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();
        let mut json = serde_json::to_value(dt.tds()).expect("serialize TDS to JSON value");

        let simplex_record = json
            .get_mut("simplices")
            .and_then(serde_json::Value::as_array_mut)
            .and_then(|simplices| simplices.first_mut())
            .and_then(serde_json::Value::as_object_mut)
            .expect("serialized TDS should contain a simplex record object");
        simplex_record.insert("unexpected".to_owned(), serde_json::json!(true));

        let err = serde_json::from_value::<Tds<(), (), 3>>(json)
            .expect_err("unknown snapshot simplex fields should be rejected");

        assert!(
            err.to_string()
                .contains("unknown snapshot simplex field `unexpected`"),
            "unexpected error for unknown snapshot simplex field: {err}"
        );
    }

    #[test]
    fn test_raw_snapshot_simplex_rejects_duplicate_fields() {
        let uuid = Uuid::new_v4();
        let duplicate_uuid = Uuid::new_v4();
        let duplicate_uuid_json = format!(r#"{{"uuid":"{uuid}","uuid":"{duplicate_uuid}"}}"#);

        let err = serde_json::from_str::<RawSnapshotSimplex<()>>(&duplicate_uuid_json)
            .expect_err("duplicate raw simplex UUID fields should be rejected");
        assert!(
            err.to_string().contains("duplicate field `uuid`"),
            "unexpected error for duplicate raw simplex UUID field: {err}"
        );

        let duplicate_data_json = format!(r#"{{"uuid":"{uuid}","data":null,"data":null}}"#);

        let err = serde_json::from_str::<RawSnapshotSimplex<()>>(&duplicate_data_json)
            .expect_err("duplicate raw simplex data fields should be rejected");
        assert!(
            err.to_string().contains("duplicate field `data`"),
            "unexpected error for duplicate raw simplex data field: {err}"
        );
    }

    #[test]
    fn test_raw_snapshot_simplex_preserves_explicit_null_payload() {
        let uuid = Uuid::new_v4();
        let explicit_null_json = format!(r#"{{"uuid":"{uuid}","data":null}}"#);
        let raw = serde_json::from_str::<RawSnapshotSimplex<Option<i32>>>(&explicit_null_json)
            .expect("explicit null payload should deserialize");

        assert_eq!(raw.data, Some(None));

        let missing_data_json = format!(r#"{{"uuid":"{uuid}"}}"#);
        let raw = serde_json::from_str::<RawSnapshotSimplex<Option<i32>>>(&missing_data_json)
            .expect("missing payload should deserialize");

        assert_eq!(raw.data, None);
    }

    #[test]
    fn test_tds_snapshot_deserialize_rejects_duplicate_relationship_map_keys() {
        for field in [
            "simplex_vertices",
            "simplex_neighbors",
            "simplex_vertex_offsets",
        ] {
            let json = snapshot_json_with_duplicate_relationship_key(field);
            let err = serde_json::from_str::<RawTdsSnapshot<(), (), 3>>(&json)
                .expect_err("duplicate relationship map keys should be rejected");
            let message = err.to_string();

            assert!(
                message.contains("duplicate simplex UUID key"),
                "unexpected error for duplicate {field} key: {err}"
            );
            assert!(
                message.contains(field),
                "duplicate relationship map error should identify {field}: {err}"
            );
        }
    }

    #[test]
    fn test_raw_snapshot_simplex_rejects_storage_local_fields() {
        let uuid = Uuid::new_v4();

        for field in ["vertices", "neighbors", "periodic_vertex_offsets"] {
            let err = serde_json::from_value::<RawSnapshotSimplex<()>>(serde_json::json!({
                "uuid": uuid,
                field: [],
            }))
            .expect_err("storage-local raw simplex fields should be rejected");

            assert!(
                err.to_string().contains("storage-local simplex state"),
                "unexpected error for storage-local raw simplex field {field}: {err}"
            );
        }
    }

    #[test]
    fn test_tds_snapshot_deserialize_rejects_unknown_top_level_fields() {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();
        let mut json = serde_json::to_value(dt.tds()).expect("serialize TDS to JSON value");
        json.as_object_mut()
            .expect("serialized TDS should be an object")
            .insert("unexpected".to_owned(), serde_json::json!(true));

        let err = serde_json::from_value::<Tds<(), (), 3>>(json)
            .expect_err("unknown top-level snapshot fields should be rejected");

        assert!(
            err.to_string().contains("unknown field `unexpected`"),
            "unexpected error for unknown top-level snapshot field: {err}"
        );
    }

    #[test]
    fn test_tds_snapshot_deserialize_rejects_missing_top_level_neighbor_map() {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();
        let mut json = serde_json::to_value(dt.tds()).expect("serialize TDS to JSON value");
        json.as_object_mut()
            .expect("serialized TDS should be an object")
            .remove("simplex_neighbors")
            .expect("serialized TDS should contain simplex_neighbors");

        let err = serde_json::from_value::<Tds<(), (), 3>>(json)
            .expect_err("missing top-level simplex_neighbors should be rejected");

        assert!(
            err.to_string()
                .contains("missing field `simplex_neighbors`"),
            "unexpected error for missing top-level simplex_neighbors: {err}"
        );
    }

    #[test]
    fn test_tds_snapshot_serde_round_trip_preserves_tds_structure() {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();
        let original = dt.tds().clone();

        let json = serde_json::to_string(&original).expect("serialize failed");
        let deserialized: Tds<(), (), 3> = serde_json::from_str(&json).expect("deserialize failed");

        assert_eq!(
            deserialized.number_of_vertices(),
            original.number_of_vertices()
        );
        assert_eq!(
            deserialized.number_of_simplices(),
            original.number_of_simplices()
        );
        assert_eq!(deserialized.dim(), original.dim());
        assert_eq!(deserialized, original);
        assert!(deserialized.is_valid().is_ok());
    }

    #[test]
    fn test_tds_snapshot_serde_round_trip_multi_simplex_triangulation() {
        let vertices = [
            vertex!([0.0, 0.0, 0.0]).unwrap(),
            vertex!([1.0, 0.0, 0.0]).unwrap(),
            vertex!([0.0, 1.0, 0.0]).unwrap(),
            vertex!([0.0, 0.0, 1.0]).unwrap(),
            vertex!([0.5, 0.5, 0.5]).unwrap(),
        ];
        let dt = DelaunayTriangulation::builder(&vertices).build().unwrap();
        let original = dt.tds().clone();
        assert!(original.number_of_simplices() > 1);

        let json = serde_json::to_string(&original).unwrap();
        let deserialized: Tds<(), (), 3> = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized, original);
        assert!(deserialized.is_valid().is_ok());
        assert!(deserialized.is_connected());
        assert!(deserialized.is_coherently_oriented());
    }

    #[test]
    fn test_tds_snapshot_serde_round_trip_2d() {
        let vertices = [
            vertex!([0.0, 0.0]).unwrap(),
            vertex!([1.0, 0.0]).unwrap(),
            vertex!([0.0, 1.0]).unwrap(),
            vertex!([1.0, 1.0]).unwrap(),
        ];
        let dt: DelaunayTriangulation<_, (), (), 2> =
            DelaunayTriangulation::builder(&vertices).build().unwrap();
        let original = dt.tds().clone();

        let json = serde_json::to_string(&original).unwrap();
        let deserialized: Tds<(), (), 2> = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized, original);
        assert!(deserialized.is_valid().is_ok());
    }

    #[test]
    fn test_tds_snapshot_serde_round_trip_preserves_periodic_offsets() {
        let (original, simplex_uuid, expected_offsets) = periodic_offset_tds_2d();
        let json = serde_json::to_value(&original).expect("serialize periodic-offset TDS");

        let offset_records = json
            .get("simplex_vertex_offsets")
            .and_then(serde_json::Value::as_object)
            .expect("serialized TDS should contain periodic offset map");
        let serialized_offsets = offset_records
            .get(&simplex_uuid.to_string())
            .and_then(serde_json::Value::as_array)
            .expect("serialized offset map should contain the simplex UUID");
        assert_eq!(serialized_offsets.len(), expected_offsets.len());

        let deserialized: Tds<(), (), 2> =
            serde_json::from_value(json).expect("deserialize periodic-offset TDS");
        let deserialized_simplex_key = deserialized
            .simplex_key_from_uuid(&simplex_uuid)
            .expect("simplex UUID should resolve after round-trip");
        let restored_offsets = deserialized
            .simplex(deserialized_simplex_key)
            .and_then(Simplex::periodic_vertex_offsets)
            .expect("periodic offsets should survive TDS serde round-trip");

        assert_eq!(restored_offsets, expected_offsets.as_slice());
        assert!(deserialized.is_valid().is_ok());
    }

    #[test]
    fn test_tds_snapshot_round_trip_preserves_distinct_lifted_duplicate_key_slots() {
        let mut original: Tds<(), (), 2> = Tds::empty();
        let first = original
            .insert_vertex_with_mapping(vertex!([0.0, 0.0]).unwrap())
            .unwrap();
        let second = original
            .insert_vertex_with_mapping(vertex!([0.5, 0.5]).unwrap())
            .unwrap();
        let offsets = vec![[0_i8, 0_i8], [0_i8, 0_i8], [1_i8, 0_i8]];
        let mut simplex = Simplex::try_new_periodic(vec![first, second, first], offsets.clone())
            .expect("repeated canonical key has distinct lifted identities");
        simplex
            .set_neighbors_from_keys(vec![None; 3])
            .expect("2D simplex should have three neighbor slots");
        let simplex_uuid = simplex.uuid();
        original
            .insert_simplex_with_mapping(simplex)
            .expect("periodic simplex should insert");
        original
            .assign_incident_simplices()
            .expect("canonical incidence should deduplicate repeated slots");
        original.construction_state = TriangulationConstructionState::Constructed;

        let json = serde_json::to_value(&original).expect("serialize lifted duplicate slots");
        let restored: Tds<(), (), 2> =
            serde_json::from_value(json).expect("deserialize lifted duplicate slots");
        let restored_key = restored
            .simplex_key_from_uuid(&simplex_uuid)
            .expect("simplex UUID should survive round-trip");
        let restored_simplex = restored
            .simplex(restored_key)
            .expect("simplex should exist");

        assert_eq!(
            restored_simplex.vertices()[0],
            restored_simplex.vertices()[2]
        );
        assert_eq!(
            restored_simplex.periodic_vertex_offsets(),
            Some(offsets.as_slice())
        );
        assert!(restored.is_valid().is_ok());

        let mut duplicate_identity_json =
            serde_json::to_value(&original).expect("serialize duplicate-identity fixture");
        let serialized_offsets = duplicate_identity_json
            .get_mut("simplex_vertex_offsets")
            .and_then(serde_json::Value::as_object_mut)
            .and_then(|offsets_by_simplex| offsets_by_simplex.get_mut(&simplex_uuid.to_string()))
            .and_then(serde_json::Value::as_array_mut)
            .expect("serialized periodic offsets should contain the simplex");
        serialized_offsets[2] = serde_json::json!([0_i8, 0_i8]);
        let error = serde_json::from_value::<Tds<(), (), 2>>(duplicate_identity_json)
            .expect_err("an identical UUID-offset pair must be rejected during hydration");
        assert!(
            error.to_string().contains("non-unique vertex identities"),
            "unexpected duplicate lifted-identity error: {error}",
        );
    }

    #[test]
    fn test_tds_snapshot_deserialize_rejects_invalid_periodic_offset_mappings() {
        let (original, simplex_uuid, _expected_offsets) = periodic_offset_tds_2d();
        let json = serde_json::to_value(&original).expect("serialize periodic-offset TDS");

        let mut wrong_offset_count = json.clone();
        wrong_offset_count
            .get_mut("simplex_vertex_offsets")
            .and_then(serde_json::Value::as_object_mut)
            .expect("serialized TDS should contain periodic offset map")
            .insert(simplex_uuid.to_string(), serde_json::json!([[0_i8, 0_i8]]));
        let err = serde_json::from_value::<Tds<(), (), 2>>(wrong_offset_count)
            .expect_err("wrong periodic offset count should be rejected");
        assert!(
            err.to_string().contains("Periodic offset length mismatch"),
            "unexpected error for wrong periodic offset count: {err}"
        );

        let mut wrong_offset_dimension = json.clone();
        wrong_offset_dimension
            .get_mut("simplex_vertex_offsets")
            .and_then(serde_json::Value::as_object_mut)
            .expect("serialized TDS should contain periodic offset map")
            .insert(
                simplex_uuid.to_string(),
                serde_json::json!([[0_i8, 0_i8], [1_i8], [0_i8, 1_i8]]),
            );
        let err = serde_json::from_value::<Tds<(), (), 2>>(wrong_offset_dimension)
            .expect_err("wrong periodic offset dimension should be rejected");
        assert!(
            err.to_string().contains("has dimension 1, expected 2"),
            "unexpected error for wrong periodic offset dimension: {err}"
        );

        let mut unknown_simplex = json;
        unknown_simplex
            .get_mut("simplex_vertex_offsets")
            .and_then(serde_json::Value::as_object_mut)
            .expect("serialized TDS should contain periodic offset map")
            .insert(
                Uuid::new_v4().to_string(),
                serde_json::json!([[0_i8, 0_i8], [1_i8, 0_i8], [0_i8, 1_i8]]),
            );
        let err = serde_json::from_value::<Tds<(), (), 2>>(unknown_simplex)
            .expect_err("unknown periodic-offset simplex UUID should be rejected");
        assert!(
            err.to_string().contains("unknown simplex"),
            "unexpected error for unknown periodic-offset simplex UUID: {err}"
        );
    }

    #[test]
    fn test_tds_snapshot_deserialize_rejects_duplicate_vertex_uuids() {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();
        let original = dt.tds().clone();
        let mut json = serde_json::to_value(&original).expect("serialize TDS to JSON value");

        let vertex_records = json
            .get_mut("vertices")
            .and_then(serde_json::Value::as_array_mut)
            .expect("serialized TDS should contain vertex records");
        assert!(
            vertex_records
                .iter()
                .all(|record| record.get("value").is_none()),
            "serialized vertices must not use slotmap value wrappers"
        );
        let mut populated_vertices = vertex_records.iter_mut();
        let first_uuid = populated_vertices
            .next()
            .and_then(|vertex| vertex.get("uuid"))
            .cloned()
            .expect("first serialized vertex should contain uuid");
        populated_vertices
            .next()
            .and_then(|vertex| vertex.get_mut("uuid"))
            .map(|uuid| *uuid = first_uuid)
            .expect("second serialized vertex should contain uuid");

        let err = serde_json::from_value::<Tds<(), (), 3>>(json)
            .expect_err("duplicate serialized vertex UUIDs should be rejected");
        assert!(
            err.to_string().contains("Duplicate vertex UUID"),
            "unexpected error for duplicate vertex UUIDs: {err}"
        );
    }

    #[test]
    fn test_tds_snapshot_deserialize_rejects_extra_simplex_vertex_uuid_mapping() {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();
        let original = dt.tds().clone();
        let mut json = serde_json::to_value(&original).expect("serialize TDS to JSON value");
        let (_, simplex) = original
            .simplices()
            .next()
            .expect("single tetrahedron should have a simplex");
        let vertex_uuids = simplex
            .vertex_uuids(&original)
            .expect("simplex vertices should resolve");
        let unknown_simplex_uuid = Uuid::new_v4();

        json.get_mut("simplex_vertices")
            .and_then(serde_json::Value::as_object_mut)
            .expect("serialized TDS should contain simplex_vertices")
            .insert(
                unknown_simplex_uuid.to_string(),
                serde_json::json!(vertex_uuids.to_vec()),
            );

        let err = serde_json::from_value::<Tds<(), (), 3>>(json)
            .expect_err("extra simplex UUID mapping should be rejected");
        assert!(
            err.to_string().contains("unknown simplex"),
            "unexpected error for extra simplex UUID mapping: {err}"
        );
    }

    #[test]
    fn test_tds_snapshot_error_preserves_unknown_relationship_map_simplex_uuids() {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();

        let mut snapshot = raw_snapshot_from_tds(dt.tds());
        let unknown_neighbor_simplex_uuid = Uuid::new_v4();
        snapshot
            .simplex_neighbors
            .insert(unknown_neighbor_simplex_uuid, vec![None, None, None, None]);

        let err = snapshot
            .parse()
            .expect_err("unknown simplex neighbor mapping should be rejected");

        assert_matches!(
            err,
            TdsSnapshotError::UnknownSimplexNeighborMapping { simplex_uuid }
                if simplex_uuid == unknown_neighbor_simplex_uuid
        );

        let mut snapshot = raw_snapshot_from_tds(dt.tds());
        let unknown_offset_simplex_uuid = Uuid::new_v4();
        snapshot
            .simplex_vertex_offsets
            .insert(unknown_offset_simplex_uuid, vec![vec![0_i8, 0_i8, 0_i8]; 4]);

        let err = snapshot
            .parse()
            .expect_err("unknown simplex offset mapping should be rejected");

        assert_matches!(
            err,
            TdsSnapshotError::UnknownSimplexOffsetMapping { simplex_uuid }
                if simplex_uuid == unknown_offset_simplex_uuid
        );
    }

    #[test]
    fn test_tds_snapshot_deserialize_rejects_invalid_simplex_vertex_uuid_mappings() {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();
        let original = dt.tds().clone();
        let json = serde_json::to_value(&original).expect("serialize TDS to JSON value");
        let (_, simplex) = original
            .simplices()
            .next()
            .expect("single tetrahedron should have a simplex");
        let simplex_uuid = simplex.uuid();
        let vertex_uuids = simplex
            .vertex_uuids(&original)
            .expect("simplex vertices should resolve");

        let mut too_few_vertices = json.clone();
        too_few_vertices
            .get_mut("simplex_vertices")
            .and_then(serde_json::Value::as_object_mut)
            .expect("serialized TDS should contain simplex_vertices")
            .insert(
                simplex_uuid.to_string(),
                serde_json::json!([vertex_uuids[0]]),
            );
        let err = serde_json::from_value::<Tds<(), (), 3>>(too_few_vertices)
            .expect_err("wrong simplex vertex count should be rejected");
        assert!(
            err.to_string().contains("vertex UUID slots"),
            "unexpected error for wrong vertex count: {err}"
        );

        let mut duplicate_vertex = json.clone();
        duplicate_vertex
            .get_mut("simplex_vertices")
            .and_then(serde_json::Value::as_object_mut)
            .expect("serialized TDS should contain simplex_vertices")
            .insert(
                simplex_uuid.to_string(),
                serde_json::json!([
                    vertex_uuids[0],
                    vertex_uuids[0],
                    vertex_uuids[0],
                    vertex_uuids[0]
                ]),
            );
        let err = serde_json::from_value::<Tds<(), (), 3>>(duplicate_vertex)
            .expect_err("duplicate simplex vertex UUIDs should be rejected");
        assert!(
            err.to_string().contains("Duplicate vertices"),
            "unexpected error for duplicate vertex UUIDs: {err}"
        );

        let mut unknown_vertex = json;
        let unknown_uuid = Uuid::new_v4();
        unknown_vertex
            .get_mut("simplex_vertices")
            .and_then(serde_json::Value::as_object_mut)
            .expect("serialized TDS should contain simplex_vertices")
            .insert(
                simplex_uuid.to_string(),
                serde_json::json!([
                    vertex_uuids[0],
                    vertex_uuids[1],
                    vertex_uuids[2],
                    unknown_uuid
                ]),
            );
        let err = serde_json::from_value::<Tds<(), (), 3>>(unknown_vertex)
            .expect_err("unknown vertex UUID should be rejected");
        assert!(
            err.to_string().contains("not found in vertices"),
            "unexpected error for unknown vertex UUID: {err}"
        );
    }

    #[test]
    fn test_tds_snapshot_deserialize_rejects_duplicate_simplex_vertex_uuid_sets() {
        let vertices = [
            vertex!([0.0, 0.0, 0.0]).unwrap(),
            vertex!([1.0, 0.0, 0.0]).unwrap(),
            vertex!([0.0, 1.0, 0.0]).unwrap(),
            vertex!([0.0, 0.0, 1.0]).unwrap(),
            vertex!([0.5, 0.5, 0.5]).unwrap(),
        ];
        let dt = DelaunayTriangulation::builder(&vertices).build().unwrap();
        let original = dt.tds().clone();
        assert!(original.number_of_simplices() > 1);
        let mut json = serde_json::to_value(&original).expect("serialize TDS to JSON value");

        let simplex_uuids: Vec<_> = serialized_records(&json, "simplices")
            .iter()
            .map(|simplex| serialized_uuid_field(simplex, "uuid"))
            .collect();
        let [first_simplex_uuid, second_simplex_uuid, ..] = simplex_uuids.as_slice() else {
            panic!("test triangulation should serialize at least two simplices");
        };
        let simplex_vertices = json
            .get_mut("simplex_vertices")
            .and_then(serde_json::Value::as_object_mut)
            .expect("serialized TDS should contain simplex_vertices");
        let duplicated_vertices = simplex_vertices
            .get(&first_simplex_uuid.to_string())
            .cloned()
            .expect("first simplex should have serialized vertex UUIDs");
        simplex_vertices.insert(second_simplex_uuid.to_string(), duplicated_vertices);

        let err = serde_json::from_value::<Tds<(), (), 3>>(json)
            .expect_err("duplicate simplex vertex UUID sets should be rejected");
        let error_message = err.to_string();
        assert!(
            error_message.contains("Duplicate simplices")
                || error_message.contains("Facet with key")
                || error_message.contains("2-manifold"),
            "unexpected error for duplicate simplex vertex UUID sets: {err}"
        );
    }

    #[test]
    fn test_tds_snapshot_round_trips_vertex_and_simplex_payload_data() {
        let mut tds: Tds<i32, i32, 2> = Tds::empty();
        let v0 = tds
            .insert_vertex_with_mapping(vertex!([0.0, 0.0]; data = 10).unwrap())
            .unwrap();
        let v1 = tds
            .insert_vertex_with_mapping(vertex!([1.0, 0.0]; data = 20).unwrap())
            .unwrap();
        let v2 = tds
            .insert_vertex_with_mapping(vertex!([0.0, 1.0]; data = 30).unwrap())
            .unwrap();
        let simplex = Simplex::try_new_with_data(vec![v0, v1, v2], Some(99)).unwrap();

        tds.insert_simplex_with_mapping(simplex).unwrap();
        tds.construction_state = TriangulationConstructionState::Constructed;
        tds.assign_neighbors().unwrap();
        tds.assign_incident_simplices().unwrap();

        let json = serde_json::to_string(&tds).expect("TDS snapshot should serialize");
        let restored: Tds<i32, i32, 2> =
            serde_json::from_str(&json).expect("TDS snapshot should deserialize");

        restored.validate().expect("restored TDS should be valid");
        let mut vertex_data = restored
            .vertices()
            .map(|(_vertex_key, vertex)| vertex.data().copied())
            .collect::<Vec<_>>();
        vertex_data.sort_unstable();
        let simplex_data = restored
            .simplices()
            .map(|(_simplex_key, simplex)| simplex.data().copied())
            .collect::<Vec<_>>();

        assert_eq!(vertex_data, vec![Some(10), Some(20), Some(30)]);
        assert_eq!(simplex_data, vec![Some(99)]);
    }

    #[test]
    fn test_tds_snapshot_serializes_non_copy_payload_data() {
        let mut tds: Tds<NonCopyPayload, NonCopyPayload, 2> = Tds::empty();
        let v0 = tds
            .insert_vertex_with_mapping(
                vertex!([0.0, 0.0]; data = NonCopyPayload {
                    label: "v0".to_owned(),
                })
                .unwrap(),
            )
            .unwrap();
        let v1 = tds
            .insert_vertex_with_mapping(
                vertex!([1.0, 0.0]; data = NonCopyPayload {
                    label: "v1".to_owned(),
                })
                .unwrap(),
            )
            .unwrap();
        let v2 = tds
            .insert_vertex_with_mapping(
                vertex!([0.0, 1.0]; data = NonCopyPayload {
                    label: "v2".to_owned(),
                })
                .unwrap(),
            )
            .unwrap();
        let simplex = Simplex::try_new_with_data(
            vec![v0, v1, v2],
            Some(NonCopyPayload {
                label: "simplex".to_owned(),
            }),
        )
        .unwrap();

        tds.insert_simplex_with_mapping(simplex).unwrap();
        tds.construction_state = TriangulationConstructionState::Constructed;
        tds.assign_neighbors().unwrap();
        tds.assign_incident_simplices().unwrap();

        let json = serde_json::to_string(&tds).expect("TDS snapshot should serialize");
        let restored: Tds<NonCopyPayload, NonCopyPayload, 2> =
            serde_json::from_str(&json).expect("TDS snapshot should deserialize");

        restored.validate().expect("restored TDS should be valid");
        let mut vertex_data = restored
            .vertices()
            .filter_map(|(_vertex_key, vertex)| vertex.data().map(|payload| payload.label.as_str()))
            .collect::<Vec<_>>();
        vertex_data.sort_unstable();
        let simplex_data = restored
            .simplices()
            .filter_map(|(_simplex_key, simplex)| {
                simplex.data().map(|payload| payload.label.as_str())
            })
            .collect::<Vec<_>>();

        assert_eq!(vertex_data, vec!["v0", "v1", "v2"]);
        assert_eq!(simplex_data, vec!["simplex"]);
    }

    #[test]
    fn test_tds_snapshot_rejects_missing_runtime_neighbor_slots() {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();
        let mut tds = dt.tds().clone();
        let simplex_uuid = tds
            .simplices()
            .next()
            .map(|(_simplex_key, simplex)| simplex)
            .expect("test TDS should contain a simplex")
            .uuid();
        tds.clear_all_neighbors();

        let err = TdsSnapshot::try_from_tds(&tds)
            .expect_err("snapshotting a TDS without assigned neighbors should fail");

        assert_matches!(
            err,
            TdsSnapshotError::MissingSimplexNeighborSlots { simplex_uuid: found }
                if found == simplex_uuid
        );
    }

    #[test]
    fn test_tds_snapshot_error_preserves_duplicate_vertex_uuid() {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();
        let mut snapshot = raw_snapshot_from_tds(dt.tds());

        let duplicate_uuid = snapshot
            .vertices
            .first()
            .expect("snapshot should contain vertices")
            .uuid();
        let duplicate_point = *snapshot
            .vertices
            .get(1)
            .expect("snapshot should contain at least two vertices")
            .point();
        snapshot.vertices[1] = Vertex::try_new_with_uuid(duplicate_point, duplicate_uuid, None)
            .expect("duplicate UUID fixture should still be a valid vertex record");

        let err = snapshot
            .parse()
            .expect_err("duplicate snapshot vertex UUIDs should be rejected");

        assert_matches!(
            err,
            TdsSnapshotError::DuplicateVertexUuid { vertex_uuid }
                if vertex_uuid == duplicate_uuid
        );
    }

    #[test]
    fn test_tds_snapshot_hydration_relies_on_validated_vertex_uuid_uniqueness() {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();
        let mut snapshot = raw_snapshot_from_tds(dt.tds())
            .parse()
            .expect("raw snapshot should parse into a validated snapshot");

        let duplicate_uuid = snapshot
            .vertices
            .first()
            .expect("snapshot should contain vertices")
            .uuid();
        let duplicate_point = *snapshot
            .vertices
            .get(1)
            .expect("snapshot should contain at least two vertices")
            .point();
        snapshot.vertices[1] = Vertex::try_new_with_uuid(duplicate_point, duplicate_uuid, None)
            .expect("duplicate UUID fixture should still be a valid vertex record");

        let err = snapshot
            .into_tds()
            .expect_err("invalid internal snapshot proof should fail during hydration");

        assert_matches!(err, TdsSnapshotError::DanglingSimplexVertexUuid { .. });
    }

    #[test]
    fn test_tds_snapshot_error_preserves_missing_simplex_vertex_mapping() {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();
        let mut snapshot = raw_snapshot_from_tds(dt.tds());
        let simplex_uuid = snapshot
            .simplices
            .first()
            .expect("snapshot should contain a simplex")
            .uuid;

        snapshot.simplex_vertices.remove(&simplex_uuid);

        let err = snapshot
            .parse()
            .expect_err("missing simplex vertex UUID mapping should be rejected");

        assert_matches!(
            err,
            TdsSnapshotError::MissingSimplexVertexUuids { simplex_uuid: found }
                if found == simplex_uuid
        );
    }

    #[test]
    fn test_tds_snapshot_error_preserves_invalid_simplex_vertex_uuid_slot_count() {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();
        let mut snapshot = raw_snapshot_from_tds(dt.tds());
        let simplex_uuid = snapshot
            .simplices
            .first()
            .expect("snapshot should contain a simplex")
            .uuid;
        let vertex_uuids = snapshot
            .simplex_vertices
            .get_mut(&simplex_uuid)
            .expect("simplex should have snapshot vertex UUIDs");

        vertex_uuids.push(Uuid::new_v4());

        let err = snapshot
            .parse()
            .expect_err("too many simplex vertex UUID slots should be rejected");

        assert_matches!(
            err,
            TdsSnapshotError::InvalidSimplexVertexUuidSlotCount {
                simplex_uuid: found,
                actual: 5,
                expected: 4,
            } if found == simplex_uuid
        );
    }

    #[test]
    fn test_tds_snapshot_error_preserves_missing_simplex_neighbor_mapping() {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();
        let mut snapshot = raw_snapshot_from_tds(dt.tds());
        let simplex_uuid = snapshot
            .simplices
            .first()
            .expect("snapshot should contain a simplex")
            .uuid;

        snapshot.simplex_neighbors.remove(&simplex_uuid);

        let err = snapshot
            .parse()
            .expect_err("missing simplex neighbor UUID mapping should be rejected");

        assert_matches!(
            err,
            TdsSnapshotError::MissingSimplexNeighborUuids { simplex_uuid: found }
                if found == simplex_uuid
        );
    }

    #[test]
    fn test_tds_snapshot_error_preserves_dangling_vertex_uuid_reference() {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();
        let mut snapshot = raw_snapshot_from_tds(dt.tds());
        let simplex_uuid = snapshot
            .simplices
            .first()
            .expect("snapshot should contain a simplex")
            .uuid;
        let dangling_vertex_uuid = Uuid::new_v4();

        snapshot
            .simplex_vertices
            .get_mut(&simplex_uuid)
            .expect("simplex should have snapshot vertex UUIDs")[0] = dangling_vertex_uuid;

        let err = snapshot
            .parse()
            .expect_err("dangling simplex vertex UUID should be rejected");

        assert_matches!(
            err,
            TdsSnapshotError::DanglingSimplexVertexUuid {
                simplex_uuid: found_simplex,
                vertex_uuid: found_vertex,
            } if found_simplex == simplex_uuid && found_vertex == dangling_vertex_uuid
        );
    }

    #[test]
    fn test_tds_snapshot_error_preserves_dangling_neighbor_uuid_reference() {
        let vertices = [
            vertex!([0.0, 0.0, 0.0]).unwrap(),
            vertex!([1.0, 0.0, 0.0]).unwrap(),
            vertex!([0.0, 1.0, 0.0]).unwrap(),
            vertex!([0.0, 0.0, 1.0]).unwrap(),
            vertex!([0.5, 0.5, 0.5]).unwrap(),
        ];
        let dt = DelaunayTriangulation::builder(&vertices).build().unwrap();
        let mut snapshot = raw_snapshot_from_tds(dt.tds());
        let simplex_uuid = *snapshot
            .simplex_neighbors
            .iter()
            .find_map(|(simplex_uuid, neighbors)| {
                neighbors
                    .iter()
                    .any(Option::is_some)
                    .then_some(simplex_uuid)
            })
            .expect("multi-simplex TDS should have an interior neighbor");
        let dangling_neighbor_uuid = Uuid::new_v4();

        let neighbors = snapshot
            .simplex_neighbors
            .get_mut(&simplex_uuid)
            .expect("simplex should have snapshot neighbor UUIDs");
        let interior_slot = neighbors
            .iter()
            .position(Option::is_some)
            .expect("simplex should have an interior neighbor");
        neighbors[interior_slot] = Some(dangling_neighbor_uuid);

        let err = snapshot
            .parse()
            .expect_err("dangling simplex neighbor UUID should be rejected");

        assert_matches!(
            err,
            TdsSnapshotError::DanglingSimplexNeighborUuid {
                simplex_uuid: found_simplex,
                neighbor_uuid: found_neighbor,
            } if found_simplex == simplex_uuid && found_neighbor == dangling_neighbor_uuid
        );
    }

    #[test]
    fn test_tds_snapshot_error_preserves_periodic_offset_dimension_mismatch() {
        let (_original, simplex_uuid, _expected_offsets) = periodic_offset_tds_2d();
        let offsets = vec![vec![0_i8, 0_i8], vec![1_i8], vec![0_i8, 1_i8]];

        let err = SnapshotPeriodicOffsetSlots::<2>::parse(simplex_uuid, &offsets)
            .expect_err("wrong periodic offset dimension should be rejected");

        assert_matches!(
            err,
            TdsSnapshotError::PeriodicOffsetDimensionMismatch {
                simplex_uuid: found_simplex,
                offset_index: 1,
                expected: 2,
                actual: 1,
            } if found_simplex == simplex_uuid
        );
    }

    #[test]
    fn test_tds_snapshot_error_preserves_duplicate_simplex_uuid() {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();
        let mut snapshot = raw_snapshot_from_tds(dt.tds());
        let simplex_uuid = snapshot
            .simplices
            .first()
            .expect("snapshot should contain a simplex")
            .uuid;

        snapshot.simplices.push(RawSnapshotSimplex {
            uuid: simplex_uuid,
            data: None,
        });

        let err = snapshot
            .parse()
            .expect_err("duplicate snapshot simplex UUIDs should be rejected");

        assert_matches!(
            err,
            TdsSnapshotError::DuplicateSimplexUuid { simplex_uuid: found }
                if found == simplex_uuid
        );
    }

    #[test]
    fn test_tds_snapshot_error_preserves_inconsistent_neighbor_connectivity() {
        let vertices = [
            vertex!([0.0, 0.0, 0.0]).unwrap(),
            vertex!([1.0, 0.0, 0.0]).unwrap(),
            vertex!([0.0, 1.0, 0.0]).unwrap(),
            vertex!([0.0, 0.0, 1.0]).unwrap(),
            vertex!([0.5, 0.5, 0.5]).unwrap(),
        ];
        let dt = DelaunayTriangulation::builder(&vertices).build().unwrap();
        let mut snapshot = raw_snapshot_from_tds(dt.tds());
        let (simplex_uuid, neighbors) = snapshot
            .simplex_neighbors
            .iter_mut()
            .find(|(_, neighbors)| neighbors.iter().any(Option::is_some))
            .expect("multi-simplex TDS should have an interior neighbor");
        let interior_slot = neighbors
            .iter()
            .position(Option::is_some)
            .expect("simplex should have an interior neighbor");
        neighbors[interior_slot] = None;
        let simplex_uuid = *simplex_uuid;

        let err = snapshot
            .parse()
            .expect("one-sided neighbor deletion is a structurally complete snapshot")
            .into_tds()
            .expect_err("one-sided neighbor deletion should be rejected");

        assert_matches!(err, TdsSnapshotError::ValidationFailed { .. });
        assert!(
            err.to_string().contains(&simplex_uuid.to_string())
                || err.to_string().contains("neighbor")
        );
    }

    #[test]
    fn test_tds_snapshot_rejects_wrong_neighbor_slot_count() {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();
        let mut snapshot = raw_snapshot_from_tds(dt.tds());
        let simplex_uuid = snapshot
            .simplices
            .first()
            .expect("snapshot should contain a simplex")
            .uuid;

        snapshot
            .simplex_neighbors
            .insert(simplex_uuid, vec![None, None]);

        let err = snapshot
            .parse()
            .expect_err("wrong neighbor slot count should be rejected");

        assert_matches!(
            err,
            TdsSnapshotError::InvalidSimplex {
                simplex_uuid: found,
                source: SimplexValidationError::InvalidNeighborsLength { .. },
            } if found == simplex_uuid
        );
    }

    #[test]
    fn test_tds_snapshot_rejects_dangling_runtime_neighbor_key() {
        let verts = initial_simplex_vertices_3d();
        let dt = DelaunayTriangulation::builder(&verts).build().unwrap();
        let mut tds = dt.tds().clone();
        let simplex_key = tds
            .simplices()
            .next()
            .map(|(simplex_key, _simplex)| simplex_key)
            .expect("test TDS should contain a simplex");
        let simplex = tds
            .simplex_mut(simplex_key)
            .expect("test simplex key should still resolve");
        simplex
            .set_neighbors_from_keys([
                Some(SimplexKey::from(KeyData::from_ffi(0xBAD))),
                None,
                None,
                None,
            ])
            .expect("fixture neighbor arity should match");

        let err = TdsSnapshot::try_from_tds(&tds)
            .expect_err("snapshotting dangling runtime neighbor key should fail");

        assert_matches!(err, TdsSnapshotError::SourceValidationFailed { .. });
    }

    #[test]
    fn test_tds_snapshot_vertex_records_can_use_existing_vertex_type() {
        let point = Point::try_new([1.0, 2.0, 3.0]).expect("finite point");
        let vertex =
            Vertex::try_new_with_uuid(point, Uuid::new_v4(), Some(7_i32)).expect("valid vertex");

        let json = serde_json::to_value(vertex).expect("vertex should serialize");

        assert!(json.get("uuid").is_some());
        assert!(json.get("point").is_some());
        assert!(json.get("data").is_some());
        assert!(
            json.get("incident_simplex").is_none(),
            "runtime incident simplex keys must not enter snapshot vertex records"
        );
    }
}