visloc-rs 0.4.0

Visual localization foundation library using SfM / visual maps.
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
//! Lossless, versioned snapshots for an already verified pair stream.
//!
//! This module deliberately uses a small dependency-free binary codec.  The
//! codec stores integer and floating-point values as their exact little-endian
//! bit patterns, keeps vectors in source order, and checks the payload with a
//! stable FNV-1a checksum.  It is an interchange format for the example
//! executable, not a replacement for the historical human-readable imports.

use std::fs::OpenOptions;
use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

pub const SCHEMA_VERSION: u32 = 1;

mod shared;
pub use shared::{write_shared_atomic, SharedPairChunk, SharedSnapshotWriter};

const MAGIC: &[u8] = b"VISLOC-VERIFIED-PAIR-SNAPSHOT\0";
const MAX_VECTOR_ITEMS: usize = 50_000_000;

/// One accepted pair and the verifier information needed to replay it.
///
/// The vectors intentionally retain the order produced by the verifier.  The
/// accepted/essential inlier index fields refer to the raw matcher vector used
/// during the original verification pass; matches and essential_matches are
/// the feature-index subsets consumed by the mapper.
#[derive(Debug, Clone, PartialEq)]
pub struct PairRecord {
    pub image_i: u64,
    pub image_j: u64,
    pub raw_match_count: u64,
    /// The exact correspondence stream presented to the final verifier.  It
    /// is retained even though the mapper consumes only `matches`, so an
    /// imported snapshot can be audited without rerunning matching.
    pub raw_matches: Vec<(u64, u64)>,
    pub accepted_inlier_indices: Vec<u64>,
    pub essential_inlier_indices: Vec<u64>,
    pub matches: Vec<(u64, u64)>,
    pub essential_matches: Option<Vec<(u64, u64)>>,
    pub config: u8,
    pub calibrated: bool,
    pub e_inlier_count: u64,
    pub f_inlier_count: u64,
    pub h_inlier_count: u64,
    pub essential_matrix_bits: Option<[u64; 9]>,
    pub fundamental_matrix_bits: Option<[u64; 9]>,
    pub homography_matrix_bits: Option<[u64; 9]>,
    pub relative_rotation_bits: Option<[u64; 9]>,
    pub relative_translation_bits: Option<[u64; 3]>,
}

/// Complete snapshot envelope. Manifest/configuration hashes are checked on
/// import. The embedded configuration is deliberately path-independent so
/// the same inputs produce identical bytes in different resumable run roots;
/// full command paths remain in the runner log and shard index.
#[derive(Debug, Clone, PartialEq)]
pub struct Snapshot {
    pub schema_version: u32,
    pub image_names: Vec<String>,
    pub image_manifest_hash: u64,
    pub feature_manifest_hash: u64,
    pub feature_counts: Vec<u64>,
    pub width: u64,
    pub height: u64,
    pub intrinsics_bits: [u64; 4],
    pub effective_config_hash: u64,
    pub effective_config: String,
    pub verifier_config_hash: u64,
    pub verifier_config: String,
    pub pair_order_hash: u64,
    pub unordered_edge_hash: u64,
    pub accepted_match_count: u64,
    pub pairs: Vec<PairRecord>,
}

/// Merge complete, hash-validated shard payloads without changing the pair
/// order inside any shard.
///
/// A snapshot shard carries the complete image/feature/configuration envelope
/// even when it contains only a subset of candidate pairs.  This helper is
/// intentionally strict about that envelope and rejects overlapping pairs so
/// a resumed run cannot silently double-count a shard.  The returned snapshot
/// uses the argument order as its deterministic pair order and recomputes the
/// two stream-integrity hashes and accepted-match count.
pub fn merge(snapshots: &[Snapshot]) -> Result<Snapshot, String> {
    merge_owned(snapshots.to_vec())
}

/// Merge owned snapshot shards while moving pair payloads into the result.
///
/// This is the bounded-memory path for large shard sets: unlike [`merge`], it
/// does not clone every raw/inlier/mapping vector while the decoded inputs are
/// still resident. Envelope validation and output ordering are identical.
pub fn merge_owned(mut snapshots: Vec<Snapshot>) -> Result<Snapshot, String> {
    let first = snapshots
        .first()
        .ok_or_else(|| "cannot merge an empty verified-pair snapshot list".to_owned())?;
    for (index, snapshot) in snapshots.iter().enumerate() {
        if snapshot.schema_version != SCHEMA_VERSION {
            return Err(format!(
                "snapshot shard {index} has unsupported schema {} (expected {SCHEMA_VERSION})",
                snapshot.schema_version
            ));
        }
        if snapshot.image_names != first.image_names {
            return Err(format!(
                "snapshot shard {index} image manifest differs from shard 0"
            ));
        }
        if snapshot.feature_manifest_hash != first.feature_manifest_hash
            || snapshot.feature_counts != first.feature_counts
            || snapshot.image_manifest_hash != first.image_manifest_hash
        {
            return Err(format!(
                "snapshot shard {index} feature/image manifest differs from shard 0"
            ));
        }
        if snapshot.width != first.width
            || snapshot.height != first.height
            || snapshot.intrinsics_bits != first.intrinsics_bits
        {
            return Err(format!(
                "snapshot shard {index} camera envelope differs from shard 0"
            ));
        }
        // Older shards may carry a complete CLI diagnostic in
        // `effective_config`, including candidate/output paths. Stream
        // compatibility is defined by the path-independent verifier config;
        // the merged envelope below canonicalizes old and new shards alike.
        if snapshot.verifier_config_hash != first.verifier_config_hash
            || snapshot.verifier_config != first.verifier_config
        {
            return Err(format!(
                "snapshot shard {index} matcher/verifier configuration differs from shard 0"
            ));
        }
    }

    let image_names = first.image_names.clone();
    let image_manifest_hash = first.image_manifest_hash;
    let feature_manifest_hash = first.feature_manifest_hash;
    let feature_counts = first.feature_counts.clone();
    let width = first.width;
    let height = first.height;
    let intrinsics_bits = first.intrinsics_bits;
    let verifier_config_hash = first.verifier_config_hash;
    let verifier_config = first.verifier_config.clone();
    let image_count = image_names.len();
    let pair_count = snapshots.iter().map(|snapshot| snapshot.pairs.len()).sum();
    let mut pairs = Vec::with_capacity(pair_count);
    let mut seen = std::collections::HashSet::new();
    for snapshot in &mut snapshots {
        for pair in &snapshot.pairs {
            let image_i = usize::try_from(pair.image_i)
                .map_err(|_| "snapshot pair image_i does not fit usize".to_owned())?;
            let image_j = usize::try_from(pair.image_j)
                .map_err(|_| "snapshot pair image_j does not fit usize".to_owned())?;
            if image_i >= image_count || image_j >= image_count || image_i == image_j {
                return Err(format!(
                    "snapshot pair has invalid image indices ({image_i},{image_j})"
                ));
            }
            let key = (image_i.min(image_j), image_i.max(image_j));
            if !seen.insert(key) {
                return Err(format!(
                    "snapshot shards overlap at image pair ({},{})",
                    key.0, key.1
                ));
            }
        }
        pairs.append(&mut snapshot.pairs);
    }

    let accepted_match_count = pairs
        .iter()
        .map(|pair| pair.matches.len() as u64)
        .sum::<u64>();
    let effective_config = format!("verified-pair-export-v1;{verifier_config}");
    let effective_config_hash = fnv1a64(effective_config.as_bytes());
    Ok(Snapshot {
        schema_version: SCHEMA_VERSION,
        image_names,
        image_manifest_hash,
        feature_manifest_hash,
        feature_counts,
        width,
        height,
        intrinsics_bits,
        effective_config_hash,
        effective_config,
        verifier_config_hash,
        verifier_config,
        pair_order_hash: ordered_pair_hash(&pairs),
        unordered_edge_hash: unordered_edge_hash(&pairs),
        accepted_match_count,
        pairs,
    })
}

/// Write a complete snapshot through a same-directory temporary file and an
/// atomic rename.  A caller may safely retry after an interrupted write; only
/// the final path is considered complete.
pub fn write_atomic(path: &Path, snapshot: &Snapshot) -> Result<(), String> {
    let parent = path.parent().unwrap_or_else(|| Path::new("."));
    std::fs::create_dir_all(parent)
        .map_err(|error| format!("create snapshot directory {}: {error}", parent.display()))?;
    let filename = path
        .file_name()
        .and_then(|value| value.to_str())
        .ok_or_else(|| format!("snapshot path has no valid filename: {}", path.display()))?;
    let temporary = parent.join(format!(".{filename}.tmp-{}", std::process::id()));
    write(&temporary, snapshot)?;
    std::fs::rename(&temporary, path).map_err(|error| {
        let _ = std::fs::remove_file(&temporary);
        format!("install snapshot {}: {error}", path.display())
    })
}

#[derive(Debug, Clone)]
struct MergePairIndex {
    image_i: u64,
    image_j: u64,
    normalized_i: u64,
    normalized_j: u64,
    edge_offset: u64,
    match_count: u64,
    encoded_len: u64,
    encoded_hash: u64,
}

struct MergeSnapshot {
    envelope: std::sync::Arc<Snapshot>,
    pairs: Vec<PairRecord>,
    pair_order_hash: u64,
    unordered_edge_hash: u64,
    accepted_match_count: u64,
}

impl std::ops::Deref for MergeSnapshot {
    type Target = Snapshot;
    fn deref(&self) -> &Snapshot {
        &self.envelope
    }
}

impl MergeSnapshot {
    fn from_owned(mut snapshot: Snapshot) -> Self {
        let pairs = std::mem::take(&mut snapshot.pairs);
        Self {
            pairs,
            pair_order_hash: snapshot.pair_order_hash,
            unordered_edge_hash: snapshot.unordered_edge_hash,
            accepted_match_count: snapshot.accepted_match_count,
            envelope: std::sync::Arc::new(snapshot),
        }
    }

    fn into_owned(self) -> Snapshot {
        let mut snapshot = std::sync::Arc::try_unwrap(self.envelope)
            .unwrap_or_else(|envelope| (*envelope).clone());
        snapshot.pairs = self.pairs;
        snapshot.pair_order_hash = self.pair_order_hash;
        snapshot.unordered_edge_hash = self.unordered_edge_hash;
        snapshot.accepted_match_count = self.accepted_match_count;
        snapshot
    }
}

fn read_for_merge(path: &Path, cache: &mut shared::EnvelopeCache) -> Result<MergeSnapshot, String> {
    let mut file = std::fs::File::open(path).map_err(|error| error.to_string())?;
    let mut magic = vec![0; shared::MAGIC.len()];
    file.read_exact(&mut magic)
        .map_err(|error| error.to_string())?;
    if magic == shared::MAGIC {
        shared::read_merge(path, true, None, Some(cache))
    } else {
        read(path).map(MergeSnapshot::from_owned)
    }
}

fn validate_cached_merge_envelope(
    index: usize,
    snapshot: &MergeSnapshot,
    first: &Snapshot,
    previous: &mut Option<std::sync::Arc<Snapshot>>,
) -> Result<(), String> {
    if !previous
        .as_ref()
        .is_some_and(|old| std::sync::Arc::ptr_eq(old, &snapshot.envelope))
    {
        validate_merge_envelope(index, snapshot, first)?;
        *previous = Some(std::sync::Arc::clone(&snapshot.envelope));
    }
    Ok(())
}

/// Bounded-memory structural readback statistics, not reconstruction quality.
#[derive(Debug, PartialEq)]
pub struct ReadbackSummary {
    pub images: usize,
    pub shards: usize,
    pub pairs: usize,
    pub accepted_matches: u64,
    pub envelope_loads: usize,
}

/// Read and validate all shard payload checksums, raw/inlier relationships,
/// compatible envelopes, image indices and disjoint pair membership. Retains
/// one shard and O(pair count) edge keys. Does not validate external feature
/// banks or recompute the declared pair-order/unordered-edge hashes.
pub fn validate_files<P: AsRef<Path>>(inputs: &[P]) -> Result<ReadbackSummary, String> {
    if inputs.is_empty() {
        return Err("cannot validate an empty snapshot list".to_owned());
    }
    let mut cache = shared::EnvelopeCache::default();
    let mut previous = None;
    let mut first = None;
    let mut edges = std::collections::HashSet::new();
    let mut accepted_matches = 0u64;
    for (index, path) in inputs.iter().enumerate() {
        let snapshot = read_for_merge(path.as_ref(), &mut cache)?;
        if let Some(envelope) = &first {
            validate_cached_merge_envelope(index, &snapshot, envelope, &mut previous)?;
        } else {
            first = Some(snapshot_envelope(&snapshot));
            previous = Some(std::sync::Arc::clone(&snapshot.envelope));
        }
        let mut shard_matches = 0u64;
        for pair in &snapshot.pairs {
            let edge = validate_merge_pair(pair, snapshot.image_names.len())?;
            if !edges.insert(edge) {
                return Err(format!("snapshot shards overlap at pair {edge:?}"));
            }
            shard_matches = shard_matches
                .checked_add(pair.matches.len() as u64)
                .ok_or("snapshot match count overflow")?;
        }
        if shard_matches != snapshot.accepted_match_count {
            return Err("snapshot accepted-match count mismatch".to_owned());
        }
        accepted_matches = accepted_matches
            .checked_add(shard_matches)
            .ok_or("snapshot match count overflow")?;
    }
    cache.finish()?;
    Ok(ReadbackSummary {
        images: first.unwrap().image_names.len(),
        shards: inputs.len(),
        pairs: edges.len(),
        accepted_matches,
        envelope_loads: cache.loads,
    })
}

fn snapshot_envelope(snapshot: &Snapshot) -> Snapshot {
    let effective_config = format!("verified-pair-export-v1;{}", snapshot.verifier_config);
    Snapshot {
        schema_version: snapshot.schema_version,
        image_names: snapshot.image_names.clone(),
        image_manifest_hash: snapshot.image_manifest_hash,
        feature_manifest_hash: snapshot.feature_manifest_hash,
        feature_counts: snapshot.feature_counts.clone(),
        width: snapshot.width,
        height: snapshot.height,
        intrinsics_bits: snapshot.intrinsics_bits,
        effective_config_hash: fnv1a64(effective_config.as_bytes()),
        effective_config,
        verifier_config_hash: snapshot.verifier_config_hash,
        verifier_config: snapshot.verifier_config.clone(),
        pair_order_hash: 0,
        unordered_edge_hash: 0,
        accepted_match_count: 0,
        pairs: Vec::new(),
    }
}

fn validate_merge_envelope(
    shard_index: usize,
    snapshot: &Snapshot,
    first: &Snapshot,
) -> Result<(), String> {
    if snapshot.schema_version != SCHEMA_VERSION {
        return Err(format!(
            "snapshot shard {shard_index} has unsupported schema {} (expected {SCHEMA_VERSION})",
            snapshot.schema_version
        ));
    }
    if snapshot.image_names != first.image_names {
        return Err(format!(
            "snapshot shard {shard_index} image manifest differs from shard 0"
        ));
    }
    if snapshot.feature_manifest_hash != first.feature_manifest_hash
        || snapshot.feature_counts != first.feature_counts
        || snapshot.image_manifest_hash != first.image_manifest_hash
    {
        return Err(format!(
            "snapshot shard {shard_index} feature/image manifest differs from shard 0"
        ));
    }
    if snapshot.width != first.width
        || snapshot.height != first.height
        || snapshot.intrinsics_bits != first.intrinsics_bits
    {
        return Err(format!(
            "snapshot shard {shard_index} camera envelope differs from shard 0"
        ));
    }
    if snapshot.verifier_config_hash != first.verifier_config_hash
        || snapshot.verifier_config != first.verifier_config
    {
        return Err(format!(
            "snapshot shard {shard_index} matcher/verifier configuration differs from shard 0"
        ));
    }
    Ok(())
}

fn validate_merge_pair(pair: &PairRecord, image_count: usize) -> Result<(u64, u64), String> {
    let image_i = usize::try_from(pair.image_i)
        .map_err(|_| "snapshot pair image_i does not fit usize".to_owned())?;
    let image_j = usize::try_from(pair.image_j)
        .map_err(|_| "snapshot pair image_j does not fit usize".to_owned())?;
    if image_i >= image_count || image_j >= image_count || image_i == image_j {
        return Err(format!(
            "snapshot pair has invalid image indices ({image_i},{image_j})"
        ));
    }
    Ok((
        pair.image_i.min(pair.image_j),
        pair.image_i.max(pair.image_j),
    ))
}

fn encoded_pair_hash(pair: &PairRecord) -> Result<u64, String> {
    let mut digest = PayloadDigestWriter::new(std::io::sink());
    encode_pair(pair, &mut digest)?;
    Ok(digest.checksum)
}

fn read_spool_u64(reader: &mut BufReader<std::fs::File>) -> Result<u64, String> {
    let mut bytes = [0; 8];
    reader
        .read_exact(&mut bytes)
        .map_err(|error| format!("read merge edge spool: {error}"))?;
    Ok(u64::from_le_bytes(bytes))
}

fn unordered_edge_hash_from_spool(
    path: &Path,
    pair_indexes: &[MergePairIndex],
    edge_len: u64,
) -> Result<u64, String> {
    let expected_len = pair_indexes.iter().try_fold(0u64, |total, pair| {
        let bytes = pair
            .match_count
            .checked_mul(16)
            .ok_or_else(|| "merge edge spool length overflow".to_owned())?;
        total
            .checked_add(bytes)
            .ok_or_else(|| "merge edge spool length overflow".to_owned())
    })?;
    if edge_len != expected_len {
        return Err(format!(
            "merge edge spool length {edge_len} differs from expected {expected_len}"
        ));
    }

    let mut order = pair_indexes.to_vec();
    order.sort_unstable_by_key(|pair| (pair.normalized_i, pair.normalized_j));
    let file = std::fs::File::open(path)
        .map_err(|error| format!("read merge edge spool {}: {error}", path.display()))?;
    let mut reader = BufReader::new(file);
    let mut hash = 0xcbf29ce484222325u64;
    for pair in order {
        reader
            .seek(SeekFrom::Start(pair.edge_offset))
            .map_err(|error| format!("seek merge edge spool {}: {error}", path.display()))?;
        for _ in 0..pair.match_count {
            let left = read_spool_u64(&mut reader)?;
            let right = read_spool_u64(&mut reader)?;
            hash = hash_u64(hash, pair.normalized_i);
            hash = hash_u64(hash, pair.normalized_j);
            hash = hash_u64(hash, left);
            hash = hash_u64(hash, right);
        }
    }
    Ok(hash)
}

fn payload_pair_order_hash_offset(snapshot: &Snapshot) -> Result<u64, String> {
    validate_snapshot_envelope(snapshot)?;
    let mut offset = 4u64 + 8;
    let mut add = |value: u64| -> Result<(), String> {
        offset = offset
            .checked_add(value)
            .ok_or_else(|| "snapshot payload offset overflow".to_owned())?;
        Ok(())
    };
    for name in &snapshot.image_names {
        add(8 + name.len() as u64)?;
    }
    add(8 + 8 + 8 + 8 * snapshot.feature_counts.len() as u64)?;
    add(8 + 8 + 8 * 4)?;
    add(8 + 8 + snapshot.effective_config.len() as u64)?;
    add(8 + 8 + snapshot.verifier_config.len() as u64)?;
    Ok(offset)
}

static MERGE_TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);

struct MergeTemporaryFile {
    path: PathBuf,
}

impl Drop for MergeTemporaryFile {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.path);
    }
}

fn create_merge_temporary_file(
    parent: &Path,
    filename: &str,
    role: &str,
) -> Result<(MergeTemporaryFile, std::fs::File), String> {
    for _ in 0..128 {
        let counter = MERGE_TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
        let path = parent.join(format!(
            ".{filename}.{role}-{}-{counter}.tmp",
            std::process::id()
        ));
        match OpenOptions::new()
            .create_new(true)
            .read(true)
            .write(true)
            .open(&path)
        {
            Ok(file) => return Ok((MergeTemporaryFile { path }, file)),
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(error) => {
                return Err(format!(
                    "create merge temporary file {}: {error}",
                    path.display()
                ));
            }
        }
    }
    Err("could not allocate a unique merge temporary file".to_owned())
}

fn write_streamed_merge_temp(
    temporary_path: &Path,
    file: std::fs::File,
    input_paths: &[PathBuf],
    first: &Snapshot,
    merged: &Snapshot,
    expected_pairs: &[MergePairIndex],
    payload_len: u64,
) -> Result<(), String> {
    let header_len = (MAGIC.len() + 4 + 8) as u64;
    let pair_order_offset = payload_pair_order_hash_offset(merged)?;
    let pair_order_file_offset = header_len
        .checked_add(pair_order_offset)
        .ok_or_else(|| "snapshot pair-order offset overflow".to_owned())?;
    let mut writer = BufWriter::new(file);
    writer
        .write_all(MAGIC)
        .and_then(|()| writer.write_all(&SCHEMA_VERSION.to_le_bytes()))
        .and_then(|()| writer.write_all(&payload_len.to_le_bytes()))
        .map_err(|error| {
            format!(
                "write merge temporary {}: {error}",
                temporary_path.display()
            )
        })?;

    let ordered_hash = {
        let mut payload_writer = PayloadDigestWriter::new(&mut writer);
        encode_payload_prefix(
            merged,
            0,
            merged.unordered_edge_hash,
            merged.accepted_match_count,
            expected_pairs.len() as u64,
            &mut payload_writer,
        )?;
        let mut ordered_hash = ordered_pair_hash_seed(expected_pairs.len() as u64);
        let mut pair_cursor = 0usize;
        let mut encoded_pair_bytes = 0u64;
        let mut accepted_match_count = 0u64;
        let mut envelope_cache = shared::EnvelopeCache::default();
        let mut previous_envelope = None;
        for (shard_index, path) in input_paths.iter().enumerate() {
            let snapshot = read_for_merge(path, &mut envelope_cache)?;
            validate_cached_merge_envelope(shard_index, &snapshot, first, &mut previous_envelope)?;
            for pair in &snapshot.pairs {
                let expected = expected_pairs.get(pair_cursor).ok_or_else(|| {
                    format!("merge input shard {shard_index} contains an unexpected pair")
                })?;
                let (normalized_i, normalized_j) =
                    validate_merge_pair(pair, first.image_names.len())?;
                let encoded_len = pair_payload_len(pair)?;
                let encoded_hash = encoded_pair_hash(pair)?;
                if pair.image_i != expected.image_i
                    || pair.image_j != expected.image_j
                    || normalized_i != expected.normalized_i
                    || normalized_j != expected.normalized_j
                    || pair.matches.len() as u64 != expected.match_count
                    || encoded_len != expected.encoded_len
                    || encoded_hash != expected.encoded_hash
                {
                    return Err(format!(
                        "merge input pair {pair_cursor} changed between validation passes"
                    ));
                }
                ordered_hash = hash_ordered_pair(ordered_hash, pair);
                encode_pair(pair, &mut payload_writer)?;
                encoded_pair_bytes = encoded_pair_bytes
                    .checked_add(encoded_len)
                    .ok_or_else(|| "snapshot payload length overflow".to_owned())?;
                accepted_match_count = accepted_match_count
                    .checked_add(pair.matches.len() as u64)
                    .ok_or_else(|| "snapshot accepted match count overflow".to_owned())?;
                pair_cursor += 1;
            }
        }
        envelope_cache.finish()?;
        if pair_cursor != expected_pairs.len() {
            return Err(format!(
                "merge inputs contain {pair_cursor} pairs but validation found {}",
                expected_pairs.len()
            ));
        }
        let prefix_len = payload_prefix_len(merged)?;
        let expected_pair_bytes = payload_len
            .checked_sub(prefix_len)
            .ok_or_else(|| "snapshot payload length is smaller than its envelope".to_owned())?;
        if encoded_pair_bytes != expected_pair_bytes {
            return Err(format!(
            "merge encoded pair length {encoded_pair_bytes} differs from expected {expected_pair_bytes}"
        ));
        }
        if accepted_match_count != merged.accepted_match_count {
            return Err(format!(
                "merge accepted match count {accepted_match_count} differs from expected {}",
                merged.accepted_match_count
            ));
        }
        if payload_writer.len != payload_len {
            return Err(format!(
                "merge encoded payload length {} differs from expected {payload_len}",
                payload_writer.len
            ));
        }
        payload_writer.flush().map_err(|error| {
            format!(
                "flush merge temporary {}: {error}",
                temporary_path.display()
            )
        })?;
        ordered_hash
    };
    writer.flush().map_err(|error| {
        format!(
            "flush merge temporary {}: {error}",
            temporary_path.display()
        )
    })?;
    drop(writer);

    let mut file = OpenOptions::new()
        .read(true)
        .write(true)
        .open(temporary_path)
        .map_err(|error| {
            format!(
                "reopen merge temporary {}: {error}",
                temporary_path.display()
            )
        })?;
    let expected_file_len = header_len
        .checked_add(payload_len)
        .ok_or_else(|| "snapshot output length overflow".to_owned())?;
    if file
        .metadata()
        .map_err(|error| format!("stat merge temporary {}: {error}", temporary_path.display()))?
        .len()
        != expected_file_len
    {
        return Err(format!(
            "merge temporary {} has an unexpected length",
            temporary_path.display()
        ));
    }
    file.seek(SeekFrom::Start(pair_order_file_offset))
        .map_err(|error| format!("seek merge temporary {}: {error}", temporary_path.display()))?;
    file.write_all(&ordered_hash.to_le_bytes())
        .map_err(|error| format!("write merge pair-order hash: {error}"))?;
    file.seek(SeekFrom::Start(header_len))
        .map_err(|error| format!("seek merge payload {}: {error}", temporary_path.display()))?;
    let mut remaining = payload_len;
    let mut checksum = 0xcbf29ce484222325u64;
    let mut buffer = vec![0; 1024 * 1024];
    while remaining > 0 {
        let chunk_len = usize::try_from(remaining.min(buffer.len() as u64))
            .map_err(|_| "snapshot checksum chunk does not fit usize".to_owned())?;
        file.read_exact(&mut buffer[..chunk_len])
            .map_err(|error| format!("read merge payload: {error}"))?;
        for byte in &buffer[..chunk_len] {
            checksum ^= u64::from(*byte);
            checksum = checksum.wrapping_mul(0x100000001b3);
        }
        remaining -= chunk_len as u64;
    }
    file.seek(SeekFrom::Start(expected_file_len))
        .map_err(|error| format!("seek merge checksum: {error}"))?;
    file.write_all(&checksum.to_le_bytes())
        .map_err(|error| format!("write merge checksum: {error}"))?;
    file.flush()
        .map_err(|error| format!("flush merge checksum: {error}"))?;
    Ok(())
}

/// Merge snapshot files with bounded memory and atomically publish the result.
///
/// The input files are decoded one at a time.  The first pass performs the
/// normal checksum, envelope, raw-index, and cross-shard overlap validation
/// while retaining only compact pair metadata and an on-disk accepted-edge
/// spool.  A second pass streams the canonical pair encoding into a temporary
/// output, so the final path is not changed unless every input and the output
/// checksum succeed.  The resulting bytes are identical to
/// `write_atomic(output, &merge_owned(decoded_inputs))`.
pub fn merge_files_atomic<P: AsRef<Path>>(output: &Path, inputs: &[P]) -> Result<(), String> {
    if inputs.is_empty() {
        return Err("cannot merge an empty verified-pair snapshot list".to_owned());
    }
    let input_paths = inputs
        .iter()
        .map(|path| path.as_ref().to_path_buf())
        .collect::<Vec<_>>();
    let parent = output
        .parent()
        .filter(|path| !path.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));
    std::fs::create_dir_all(parent).map_err(|error| {
        format!(
            "create merge output directory {}: {error}",
            parent.display()
        )
    })?;
    let filename = output
        .file_name()
        .and_then(|value| value.to_str())
        .ok_or_else(|| format!("snapshot path has no valid filename: {}", output.display()))?;

    let (edge_temporary, edge_file) = create_merge_temporary_file(parent, filename, "edges")?;
    let edge_path = edge_temporary.path.clone();
    let mut edge_writer = BufWriter::new(edge_file);
    let mut first = None;
    let mut seen = std::collections::HashSet::new();
    let mut pair_indexes = Vec::new();
    let mut edge_offset = 0u64;
    let mut pair_count = 0u64;
    let mut pair_payload_bytes = 0u64;
    let mut accepted_match_count = 0u64;
    let mut envelope_cache = shared::EnvelopeCache::default();
    let mut previous_envelope = None;
    for (shard_index, path) in input_paths.iter().enumerate() {
        let snapshot = read_for_merge(path, &mut envelope_cache)?;
        if let Some(first_snapshot) = first.as_ref() {
            validate_cached_merge_envelope(
                shard_index,
                &snapshot,
                first_snapshot,
                &mut previous_envelope,
            )?;
        } else {
            validate_snapshot_envelope(&snapshot)?;
            first = Some(snapshot_envelope(&snapshot));
            previous_envelope = Some(std::sync::Arc::clone(&snapshot.envelope));
        }
        let image_count = first
            .as_ref()
            .map_or(0, |snapshot| snapshot.image_names.len());
        for pair in snapshot.pairs {
            let (normalized_i, normalized_j) = validate_merge_pair(&pair, image_count)?;
            if !seen.insert((normalized_i, normalized_j)) {
                return Err(format!(
                    "snapshot shards overlap at image pair ({normalized_i},{normalized_j})"
                ));
            }
            let encoded_len = pair_payload_len(&pair)?;
            let encoded_hash = encoded_pair_hash(&pair)?;
            let match_count = pair.matches.len() as u64;
            let edge_start = edge_offset;
            let mut normalized_matches = pair
                .matches
                .iter()
                .map(|&(left, right)| {
                    if pair.image_i > pair.image_j {
                        (right, left)
                    } else {
                        (left, right)
                    }
                })
                .collect::<Vec<_>>();
            normalized_matches.sort_unstable();
            for &(left, right) in &normalized_matches {
                put_u64(&mut edge_writer, left)?;
                put_u64(&mut edge_writer, right)?;
            }
            edge_offset = edge_offset
                .checked_add(
                    match_count
                        .checked_mul(16)
                        .ok_or_else(|| "merge edge spool length overflow".to_owned())?,
                )
                .ok_or_else(|| "merge edge spool length overflow".to_owned())?;
            pair_count = pair_count
                .checked_add(1)
                .ok_or_else(|| "snapshot pair count overflow".to_owned())?;
            pair_payload_bytes = pair_payload_bytes
                .checked_add(encoded_len)
                .ok_or_else(|| "snapshot payload length overflow".to_owned())?;
            accepted_match_count = accepted_match_count
                .checked_add(match_count)
                .ok_or_else(|| "snapshot accepted match count overflow".to_owned())?;
            pair_indexes.push(MergePairIndex {
                image_i: pair.image_i,
                image_j: pair.image_j,
                normalized_i,
                normalized_j,
                edge_offset: edge_start,
                match_count,
                encoded_len,
                encoded_hash,
            });
        }
    }
    envelope_cache.finish()?;
    edge_writer
        .flush()
        .map_err(|error| format!("flush merge edge spool {}: {error}", edge_path.display()))?;
    drop(edge_writer);

    let first =
        first.ok_or_else(|| "cannot merge an empty verified-pair snapshot list".to_owned())?;
    let edge_len = std::fs::metadata(&edge_path)
        .map_err(|error| format!("stat merge edge spool {}: {error}", edge_path.display()))?
        .len();
    let unordered_edge_hash = unordered_edge_hash_from_spool(&edge_path, &pair_indexes, edge_len)?;
    let mut merged = snapshot_envelope(&first);
    merged.unordered_edge_hash = unordered_edge_hash;
    merged.accepted_match_count = accepted_match_count;
    let payload_len = payload_prefix_len(&merged)?
        .checked_add(pair_payload_bytes)
        .ok_or_else(|| "snapshot payload length overflow".to_owned())?;
    if pair_count != pair_indexes.len() as u64 {
        return Err("merge pair index count overflow".to_owned());
    }

    let (output_temporary, output_file) = create_merge_temporary_file(parent, filename, "output")?;
    let output_path = output_temporary.path.clone();
    write_streamed_merge_temp(
        &output_path,
        output_file,
        &input_paths,
        &first,
        &merged,
        &pair_indexes,
        payload_len,
    )?;
    std::fs::rename(&output_path, output).map_err(|error| {
        format!(
            "install merged verified-pair snapshot {}: {error}",
            output.display()
        )
    })?;
    // The temporary path has been atomically moved to the requested output.
    // It is safe for the guard to remove this now-nonexistent path.
    drop(output_temporary);
    drop(edge_temporary);
    Ok(())
}

fn fnv1a64(bytes: &[u8]) -> u64 {
    let mut hash = 0xcbf29ce484222325u64;
    for byte in bytes {
        hash ^= u64::from(*byte);
        hash = hash.wrapping_mul(0x100000001b3);
    }
    hash
}

fn hash_u64(mut hash: u64, value: u64) -> u64 {
    for byte in value.to_le_bytes() {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(0x100000001b3);
    }
    hash
}

fn ordered_pair_hash(pairs: &[PairRecord]) -> u64 {
    let mut hash = ordered_pair_hash_seed(pairs.len() as u64);
    for pair in pairs {
        hash = hash_ordered_pair(hash, pair);
    }
    hash
}

fn ordered_pair_hash_seed(pair_count: u64) -> u64 {
    hash_u64(0xcbf29ce484222325u64, pair_count)
}

fn hash_ordered_pair(mut hash: u64, pair: &PairRecord) -> u64 {
    hash = hash_u64(hash, pair.image_i);
    hash = hash_u64(hash, pair.image_j);
    hash = hash_u64(hash, u64::from(pair.config));
    hash = hash_u64(hash, pair.matches.len() as u64);
    for &(left, right) in &pair.matches {
        hash = hash_u64(hash, left);
        hash = hash_u64(hash, right);
    }
    if let Some(matches) = &pair.essential_matches {
        hash = hash_u64(hash, 1);
        hash = hash_u64(hash, matches.len() as u64);
        for &(left, right) in matches {
            hash = hash_u64(hash, left);
            hash = hash_u64(hash, right);
        }
    } else {
        hash = hash_u64(hash, 0);
    }
    if let Some(matrix) = pair.essential_matrix_bits {
        hash = hash_u64(hash, 1);
        for value in matrix {
            hash = hash_u64(hash, value);
        }
    } else {
        hash = hash_u64(hash, 0);
    }
    hash
}

fn unordered_edge_hash(pairs: &[PairRecord]) -> u64 {
    let mut pair_order = pairs
        .iter()
        .enumerate()
        .map(|(index, pair)| {
            (
                pair.image_i.min(pair.image_j),
                pair.image_i.max(pair.image_j),
                index,
            )
        })
        .collect::<Vec<_>>();
    pair_order.sort_unstable_by_key(|&(image_i, image_j, _)| (image_i, image_j));
    let mut hash = 0xcbf29ce484222325u64;
    let mut group_start = 0;
    while group_start < pair_order.len() {
        let (image_i, image_j, _) = pair_order[group_start];
        let mut group_end = group_start + 1;
        while group_end < pair_order.len()
            && pair_order[group_end].0 == image_i
            && pair_order[group_end].1 == image_j
        {
            group_end += 1;
        }
        let group_match_count = pair_order[group_start..group_end]
            .iter()
            .map(|&(_, _, index)| pairs[index].matches.len())
            .sum();
        let mut matches = Vec::with_capacity(group_match_count);
        for &(_, _, index) in &pair_order[group_start..group_end] {
            let pair = &pairs[index];
            let swapped = pair.image_i > pair.image_j;
            matches.extend(pair.matches.iter().map(|&(left, right)| {
                if swapped {
                    (right, left)
                } else {
                    (left, right)
                }
            }));
        }
        matches.sort_unstable();
        for (left, right) in matches {
            hash = hash_u64(hash, image_i);
            hash = hash_u64(hash, image_j);
            hash = hash_u64(hash, left);
            hash = hash_u64(hash, right);
        }
        group_start = group_end;
    }
    hash
}

fn put_u8<W: Write>(out: &mut W, value: u8) -> Result<(), String> {
    out.write_all(&[value]).map_err(|error| error.to_string())
}

fn put_u32<W: Write>(out: &mut W, value: u32) -> Result<(), String> {
    out.write_all(&value.to_le_bytes())
        .map_err(|error| error.to_string())
}

fn put_u64<W: Write>(out: &mut W, value: u64) -> Result<(), String> {
    out.write_all(&value.to_le_bytes())
        .map_err(|error| error.to_string())
}

fn put_bool<W: Write>(out: &mut W, value: bool) -> Result<(), String> {
    put_u8(out, u8::from(value))
}

fn put_bytes<W: Write>(out: &mut W, bytes: &[u8]) -> Result<(), String> {
    put_u64(out, bytes.len() as u64)?;
    out.write_all(bytes).map_err(|error| error.to_string())
}

fn put_string<W: Write>(out: &mut W, value: &str) -> Result<(), String> {
    put_bytes(out, value.as_bytes())
}

fn put_u64_vec<W: Write>(out: &mut W, values: &[u64]) -> Result<(), String> {
    put_u64(out, values.len() as u64)?;
    for value in values {
        put_u64(out, *value)?;
    }
    Ok(())
}

fn put_match_vec<W: Write>(out: &mut W, values: &[(u64, u64)]) -> Result<(), String> {
    put_u64(out, values.len() as u64)?;
    for &(left, right) in values {
        put_u64(out, left)?;
        put_u64(out, right)?;
    }
    Ok(())
}

fn put_matrix9<W: Write>(out: &mut W, value: &Option<[u64; 9]>) -> Result<(), String> {
    put_bool(out, value.is_some())?;
    if let Some(values) = value {
        for value in values {
            put_u64(out, *value)?;
        }
    }
    Ok(())
}

fn put_matrix3<W: Write>(out: &mut W, value: &Option<[u64; 3]>) -> Result<(), String> {
    put_bool(out, value.is_some())?;
    if let Some(values) = value {
        for value in values {
            put_u64(out, *value)?;
        }
    }
    Ok(())
}

fn validate_snapshot_envelope(snapshot: &Snapshot) -> Result<(), String> {
    if snapshot.schema_version != SCHEMA_VERSION {
        return Err(format!(
            "unsupported verified-pair snapshot schema {} (expected {})",
            snapshot.schema_version, SCHEMA_VERSION
        ));
    }
    if snapshot.image_names.len() != snapshot.feature_counts.len() {
        return Err(format!(
            "snapshot image/feature manifest length mismatch: {} names vs {} feature counts",
            snapshot.image_names.len(),
            snapshot.feature_counts.len()
        ));
    }
    Ok(())
}

fn encode_payload_prefix<W: Write>(
    snapshot: &Snapshot,
    pair_order_hash: u64,
    unordered_edge_hash: u64,
    accepted_match_count: u64,
    pair_count: u64,
    out: &mut W,
) -> Result<(), String> {
    validate_snapshot_envelope(snapshot)?;
    put_u32(out, snapshot.schema_version)?;
    put_u64(out, snapshot.image_names.len() as u64)?;
    for name in &snapshot.image_names {
        put_string(out, name)?;
    }
    put_u64(out, snapshot.image_manifest_hash)?;
    put_u64(out, snapshot.feature_manifest_hash)?;
    put_u64_vec(out, &snapshot.feature_counts)?;
    put_u64(out, snapshot.width)?;
    put_u64(out, snapshot.height)?;
    for value in snapshot.intrinsics_bits {
        put_u64(out, value)?;
    }
    put_u64(out, snapshot.effective_config_hash)?;
    put_string(out, &snapshot.effective_config)?;
    put_u64(out, snapshot.verifier_config_hash)?;
    put_string(out, &snapshot.verifier_config)?;
    put_u64(out, pair_order_hash)?;
    put_u64(out, unordered_edge_hash)?;
    put_u64(out, accepted_match_count)?;
    put_u64(out, pair_count)?;
    Ok(())
}

fn encode_pair<W: Write>(pair: &PairRecord, out: &mut W) -> Result<(), String> {
    if pair.raw_match_count != pair.raw_matches.len() as u64 {
        return Err(format!(
            "snapshot raw match count {} does not match raw stream length {} for pair ({},{})",
            pair.raw_match_count,
            pair.raw_matches.len(),
            pair.image_i,
            pair.image_j,
        ));
    }
    put_u64(out, pair.image_i)?;
    put_u64(out, pair.image_j)?;
    put_u64(out, pair.raw_match_count)?;
    put_match_vec(out, &pair.raw_matches)?;
    put_u64_vec(out, &pair.accepted_inlier_indices)?;
    put_u64_vec(out, &pair.essential_inlier_indices)?;
    put_match_vec(out, &pair.matches)?;
    put_bool(out, pair.essential_matches.is_some())?;
    if let Some(matches) = &pair.essential_matches {
        put_match_vec(out, matches)?;
    }
    put_u8(out, pair.config)?;
    put_bool(out, pair.calibrated)?;
    put_u64(out, pair.e_inlier_count)?;
    put_u64(out, pair.f_inlier_count)?;
    put_u64(out, pair.h_inlier_count)?;
    put_matrix9(out, &pair.essential_matrix_bits)?;
    put_matrix9(out, &pair.fundamental_matrix_bits)?;
    put_matrix9(out, &pair.homography_matrix_bits)?;
    put_matrix9(out, &pair.relative_rotation_bits)?;
    put_matrix3(out, &pair.relative_translation_bits)?;
    Ok(())
}

fn encode_payload<W: Write>(snapshot: &Snapshot, out: &mut W) -> Result<(), String> {
    encode_payload_prefix(
        snapshot,
        snapshot.pair_order_hash,
        snapshot.unordered_edge_hash,
        snapshot.accepted_match_count,
        snapshot.pairs.len() as u64,
        out,
    )?;
    for pair in &snapshot.pairs {
        encode_pair(pair, out)?;
    }
    Ok(())
}

struct Reader<R> {
    inner: R,
    offset: u64,
    payload_len: u64,
}

impl<R: Read> Reader<R> {
    const fn new(inner: R, payload_len: u64) -> Self {
        Self {
            inner,
            offset: 0,
            payload_len,
        }
    }

    fn read_exact(&mut self, bytes: &mut [u8]) -> Result<(), String> {
        let count = bytes.len() as u64;
        let end = self
            .offset
            .checked_add(count)
            .ok_or_else(|| "snapshot offset overflow".to_owned())?;
        if end > self.payload_len {
            return Err(format!(
                "truncated verified-pair snapshot at byte {} (need {} bytes)",
                self.offset, count
            ));
        }
        self.inner.read_exact(bytes).map_err(|error| {
            format!(
                "truncated verified-pair snapshot at byte {} (need {count} bytes): {error}",
                self.offset
            )
        })?;
        self.offset = end;
        Ok(())
    }

    fn u8(&mut self) -> Result<u8, String> {
        let mut bytes = [0; 1];
        self.read_exact(&mut bytes)?;
        Ok(bytes[0])
    }

    fn u32(&mut self) -> Result<u32, String> {
        let mut bytes = [0; 4];
        self.read_exact(&mut bytes)?;
        Ok(u32::from_le_bytes(bytes))
    }

    fn u64(&mut self) -> Result<u64, String> {
        let mut bytes = [0; 8];
        self.read_exact(&mut bytes)?;
        Ok(u64::from_le_bytes(bytes))
    }

    fn bool(&mut self) -> Result<bool, String> {
        match self.u8()? {
            0 => Ok(false),
            1 => Ok(true),
            value => Err(format!("invalid snapshot boolean {value}")),
        }
    }

    fn len(&mut self, label: &str) -> Result<usize, String> {
        let value = self.u64()?;
        let length = usize::try_from(value)
            .map_err(|_| format!("snapshot {label} length {value} does not fit usize"))?;
        if length > MAX_VECTOR_ITEMS {
            return Err(format!(
                "snapshot {label} length {length} exceeds safety limit {MAX_VECTOR_ITEMS}"
            ));
        }
        Ok(length)
    }

    fn bytes(&mut self, label: &str) -> Result<Vec<u8>, String> {
        let length = self.len(label)?;
        let mut bytes = vec![0; length];
        self.read_exact(&mut bytes)?;
        Ok(bytes)
    }

    fn string(&mut self, label: &str) -> Result<String, String> {
        String::from_utf8(self.bytes(label)?)
            .map_err(|error| format!("snapshot {label} is not valid UTF-8: {error}"))
    }

    fn u64_vec(&mut self, label: &str) -> Result<Vec<u64>, String> {
        let length = self.len(label)?;
        (0..length).map(|_| self.u64()).collect()
    }

    fn match_vec(&mut self, label: &str) -> Result<Vec<(u64, u64)>, String> {
        let length = self.len(label)?;
        (0..length)
            .map(|_| Ok((self.u64()?, self.u64()?)))
            .collect()
    }

    fn matrix9(&mut self, label: &str) -> Result<Option<[u64; 9]>, String> {
        if !self.bool()? {
            return Ok(None);
        }
        let mut values = [0; 9];
        for value in &mut values {
            *value = self.u64()?;
        }
        let _ = label;
        Ok(Some(values))
    }

    fn matrix3(&mut self, label: &str) -> Result<Option<[u64; 3]>, String> {
        if !self.bool()? {
            return Ok(None);
        }
        let mut values = [0; 3];
        for value in &mut values {
            *value = self.u64()?;
        }
        let _ = label;
        Ok(Some(values))
    }

    const fn done(&self) -> bool {
        self.offset == self.payload_len
    }
}

fn decode_payload<R: Read>(
    input: R,
    payload_len: u64,
    retain_audit_streams: bool,
    mapper_match_limit: Option<usize>,
) -> Result<Snapshot, String> {
    let mut reader = Reader::new(input, payload_len);
    let schema_version = reader.u32()?;
    if schema_version != SCHEMA_VERSION {
        return Err(format!(
            "unsupported verified-pair snapshot schema {schema_version} (expected {SCHEMA_VERSION})"
        ));
    }
    let image_count = reader.len("image names")?;
    let image_names = (0..image_count)
        .map(|_| reader.string("image name"))
        .collect::<Result<Vec<_>, _>>()?;
    let image_manifest_hash = reader.u64()?;
    let feature_manifest_hash = reader.u64()?;
    let feature_counts = reader.u64_vec("feature counts")?;
    if feature_counts.len() != image_names.len() {
        return Err(format!(
            "snapshot feature counts {} do not match image names {}",
            feature_counts.len(),
            image_names.len()
        ));
    }
    let width = reader.u64()?;
    let height = reader.u64()?;
    let mut intrinsics_bits = [0; 4];
    for value in &mut intrinsics_bits {
        *value = reader.u64()?;
    }
    let effective_config_hash = reader.u64()?;
    let effective_config = reader.string("effective config")?;
    let verifier_config_hash = reader.u64()?;
    let verifier_config = reader.string("verifier config")?;
    let chunk = decode_pair_payload(&mut reader, retain_audit_streams, mapper_match_limit)?;
    Ok(Snapshot {
        schema_version,
        image_names,
        image_manifest_hash,
        feature_manifest_hash,
        feature_counts,
        width,
        height,
        intrinsics_bits,
        effective_config_hash,
        effective_config,
        verifier_config_hash,
        verifier_config,
        pair_order_hash: chunk.pair_order_hash,
        unordered_edge_hash: chunk.unordered_edge_hash,
        accepted_match_count: chunk.accepted_match_count,
        pairs: chunk.pairs,
    })
}

struct DecodedPairs {
    pair_order_hash: u64,
    unordered_edge_hash: u64,
    accepted_match_count: u64,
    pairs: Vec<PairRecord>,
}

fn decode_pair_payload<R: Read>(
    reader: &mut Reader<R>,
    retain_audit_streams: bool,
    mapper_match_limit: Option<usize>,
) -> Result<DecodedPairs, String> {
    let pair_order_hash = reader.u64()?;
    let unordered_edge_hash = reader.u64()?;
    let accepted_match_count = reader.u64()?;
    let pair_count = reader.len("pairs")?;
    let mut pairs = Vec::with_capacity(pair_count);
    for pair_number in 0..pair_count {
        let image_i = reader.u64()?;
        let image_j = reader.u64()?;
        let raw_match_count = reader.u64()?;
        let raw_matches = reader.match_vec("raw matches")?;
        if raw_match_count != raw_matches.len() as u64 {
            return Err(format!(
                "snapshot raw match count {raw_match_count} does not match raw stream length {}",
                raw_matches.len()
            ));
        }
        let accepted_inlier_indices = reader.u64_vec("accepted inlier indices")?;
        let essential_inlier_indices = reader.u64_vec("essential inlier indices")?;
        let mut matches = reader.match_vec("accepted matches")?;
        let mut essential_matches = if reader.bool()? {
            Some(reader.match_vec("essential matches")?)
        } else {
            None
        };
        if accepted_inlier_indices.len() != matches.len() {
            return Err(format!(
                "snapshot pair {pair_number} has {} accepted indices but {} accepted matches",
                accepted_inlier_indices.len(),
                matches.len()
            ));
        }
        for (position, (&raw_index, &accepted)) in
            accepted_inlier_indices.iter().zip(&matches).enumerate()
        {
            let raw_index = usize::try_from(raw_index).map_err(|_| {
                format!("snapshot pair {pair_number} accepted index does not fit usize")
            })?;
            if raw_matches.get(raw_index) != Some(&accepted) {
                return Err(format!(
                    "snapshot pair {pair_number} accepted match at position {position} disagrees with raw index {raw_index}"
                ));
            }
        }
        match &essential_matches {
            Some(essential) if essential_inlier_indices.len() == essential.len() => {
                for (position, (&raw_index, &accepted)) in
                    essential_inlier_indices.iter().zip(essential).enumerate()
                {
                    let raw_index = usize::try_from(raw_index).map_err(|_| {
                        format!("snapshot pair {pair_number} essential index does not fit usize")
                    })?;
                    if raw_matches.get(raw_index) != Some(&accepted) {
                        return Err(format!(
                            "snapshot pair {pair_number} essential match at position {position} disagrees with raw index {raw_index}"
                        ));
                    }
                }
            }
            Some(essential) => {
                return Err(format!(
                    "snapshot pair {pair_number} has {} essential indices but {} essential matches",
                    essential_inlier_indices.len(),
                    essential.len()
                ));
            }
            None if !essential_inlier_indices.is_empty() => {
                return Err(format!(
                    "snapshot pair {pair_number} has essential indices but no essential matches"
                ));
            }
            None => {}
        }
        let config = reader.u8()?;
        let calibrated = reader.bool()?;
        let e_inlier_count = reader.u64()?;
        let f_inlier_count = reader.u64()?;
        let h_inlier_count = reader.u64()?;
        let essential_matrix_bits = reader.matrix9("essential matrix")?;
        let fundamental_matrix_bits = reader.matrix9("fundamental matrix")?;
        let homography_matrix_bits = reader.matrix9("homography matrix")?;
        let relative_rotation_bits = reader.matrix9("relative rotation")?;
        let relative_translation_bits = reader.matrix3("relative translation")?;
        if let Some(limit) = mapper_match_limit {
            matches.truncate(limit);
            // Generalized mapper replay consumes only the selected accepted
            // stream. Essential matches were checked against their raw
            // indices above, then can be released at the pair boundary
            // instead of duplicating the graph-wide correspondence payload.
            essential_matches = None;
        }
        pairs.push(PairRecord {
            image_i,
            image_j,
            raw_match_count: if retain_audit_streams {
                raw_match_count
            } else {
                0
            },
            raw_matches: if retain_audit_streams {
                raw_matches
            } else {
                Vec::new()
            },
            accepted_inlier_indices: if retain_audit_streams {
                accepted_inlier_indices
            } else {
                Vec::new()
            },
            essential_inlier_indices: if retain_audit_streams {
                essential_inlier_indices
            } else {
                Vec::new()
            },
            matches,
            essential_matches,
            config,
            calibrated,
            e_inlier_count,
            f_inlier_count,
            h_inlier_count,
            essential_matrix_bits,
            fundamental_matrix_bits,
            homography_matrix_bits,
            relative_rotation_bits,
            relative_translation_bits,
        });
    }
    if !reader.done() {
        return Err(format!(
            "verified-pair snapshot has {} trailing bytes",
            reader.payload_len - reader.offset
        ));
    }
    let accepted_match_count = mapper_match_limit.map_or(accepted_match_count, |_| {
        pairs.iter().map(|pair| pair.matches.len() as u64).sum()
    });
    Ok(DecodedPairs {
        pair_order_hash,
        unordered_edge_hash,
        accepted_match_count,
        pairs,
    })
}

struct PayloadDigestWriter<W> {
    inner: W,
    checksum: u64,
    len: u64,
}

fn payload_prefix_len(snapshot: &Snapshot) -> Result<u64, String> {
    validate_snapshot_envelope(snapshot)?;
    let mut len = 4u64 + 8;
    let mut add = |value: u64| -> Result<(), String> {
        len = len
            .checked_add(value)
            .ok_or_else(|| "snapshot payload length overflow".to_owned())?;
        Ok(())
    };
    for name in &snapshot.image_names {
        add(8 + name.len() as u64)?;
    }
    add(8 + 8 + 8 + 8 * snapshot.feature_counts.len() as u64)?;
    add(8 + 8 + 8 * 4)?;
    add(8 + 8 + snapshot.effective_config.len() as u64)?;
    add(8 + 8 + snapshot.verifier_config.len() as u64)?;
    add(8 + 8 + 8 + 8)?;
    Ok(len)
}

fn pair_payload_len(pair: &PairRecord) -> Result<u64, String> {
    let mut len = 0u64;
    let mut add = |value: u64| -> Result<(), String> {
        len = len
            .checked_add(value)
            .ok_or_else(|| "snapshot payload length overflow".to_owned())?;
        Ok(())
    };
    if pair.raw_match_count != pair.raw_matches.len() as u64 {
        return Err(format!(
            "snapshot raw match count {} does not match raw stream length {} for pair ({},{})",
            pair.raw_match_count,
            pair.raw_matches.len(),
            pair.image_i,
            pair.image_j,
        ));
    }
    add(8 * 3)?;
    add(8 + 16 * pair.raw_matches.len() as u64)?;
    add(8 + 8 * pair.accepted_inlier_indices.len() as u64)?;
    add(8 + 8 * pair.essential_inlier_indices.len() as u64)?;
    add(8 + 16 * pair.matches.len() as u64)?;
    add(1)?;
    if let Some(matches) = &pair.essential_matches {
        add(8 + 16 * matches.len() as u64)?;
    }
    add(1 + 1 + 8 * 3)?;
    for matrix in [
        &pair.essential_matrix_bits,
        &pair.fundamental_matrix_bits,
        &pair.homography_matrix_bits,
        &pair.relative_rotation_bits,
    ] {
        add(1 + if matrix.is_some() { 8 * 9 } else { 0 })?;
    }
    add(1 + if pair.relative_translation_bits.is_some() {
        8 * 3
    } else {
        0
    })?;
    Ok(len)
}

fn payload_len(snapshot: &Snapshot) -> Result<u64, String> {
    let mut len = payload_prefix_len(snapshot)?;
    let mut add = |value: u64| -> Result<(), String> {
        len = len
            .checked_add(value)
            .ok_or_else(|| "snapshot payload length overflow".to_owned())?;
        Ok(())
    };
    for pair in &snapshot.pairs {
        add(pair_payload_len(pair)?)?;
    }
    Ok(len)
}

impl<W> PayloadDigestWriter<W> {
    const fn new(inner: W) -> Self {
        Self {
            inner,
            checksum: 0xcbf29ce484222325,
            len: 0,
        }
    }
}

impl<W: Write> Write for PayloadDigestWriter<W> {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        let written = self.inner.write(bytes)?;
        for byte in &bytes[..written] {
            self.checksum ^= u64::from(*byte);
            self.checksum = self.checksum.wrapping_mul(0x100000001b3);
        }
        self.len = self
            .len
            .checked_add(written as u64)
            .ok_or_else(|| std::io::Error::other("snapshot payload length overflow"))?;
        Ok(written)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.inner.flush()
    }
}

/// Write a complete snapshot and append a checksum over its exact payload.
///
/// The payload length is computed from vector/string lengths, then the payload
/// is streamed directly to the destination while its checksum is accumulated.
/// This keeps peak memory independent of encoded size and visits each
/// correspondence only once while preserving the original byte-for-byte
/// format.
pub fn write(path: &Path, snapshot: &Snapshot) -> Result<(), String> {
    let payload_len = payload_len(snapshot)?;
    let file = std::fs::File::create(path)
        .map_err(|error| format!("create {}: {error}", path.display()))?;
    let mut writer = BufWriter::new(file);
    writer
        .write_all(MAGIC)
        .and_then(|()| writer.write_all(&SCHEMA_VERSION.to_le_bytes()))
        .and_then(|()| writer.write_all(&payload_len.to_le_bytes()))
        .map_err(|error| format!("write {}: {error}", path.display()))?;
    let mut payload_writer = PayloadDigestWriter::new(&mut writer);
    encode_payload(snapshot, &mut payload_writer)
        .map_err(|error| format!("write {}: {error}", path.display()))?;
    if payload_writer.len != payload_len {
        return Err(format!(
            "snapshot encoded payload length {} differs from computed length {payload_len}",
            payload_writer.len
        ));
    }
    let checksum = payload_writer.checksum;
    writer
        .write_all(&checksum.to_le_bytes())
        .and_then(|()| writer.flush())
        .map_err(|error| format!("write {}: {error}", path.display()))
}

fn read_with_retention(
    path: &Path,
    retain_audit_streams: bool,
    mapper_match_limit: Option<usize>,
) -> Result<Snapshot, String> {
    read_with_cache(path, retain_audit_streams, mapper_match_limit, None)
}

fn read_with_cache(
    path: &Path,
    retain_audit_streams: bool,
    mapper_match_limit: Option<usize>,
    cache: Option<&mut shared::EnvelopeCache>,
) -> Result<Snapshot, String> {
    let header_len = MAGIC.len() + 4 + 8;
    let mut file =
        std::fs::File::open(path).map_err(|error| format!("read {}: {error}", path.display()))?;
    let file_len = file
        .metadata()
        .map_err(|error| format!("stat {}: {error}", path.display()))?
        .len();
    if file_len < (header_len + 8) as u64 {
        return Err(format!(
            "{} is not a verified-pair snapshot (bad magic or truncated header)",
            path.display()
        ));
    }
    let mut magic = vec![0; MAGIC.len()];
    file.read_exact(&mut magic)
        .map_err(|error| format!("read {} header: {error}", path.display()))?;
    if magic.starts_with(shared::MAGIC) {
        return shared::read(path, retain_audit_streams, mapper_match_limit, cache);
    }
    if magic != MAGIC {
        return Err(format!(
            "{} is not a verified-pair snapshot (bad magic or truncated header)",
            path.display()
        ));
    }
    let mut u32_bytes = [0; 4];
    file.read_exact(&mut u32_bytes)
        .map_err(|error| format!("read {} schema: {error}", path.display()))?;
    let version = u32::from_le_bytes(u32_bytes);
    if version != SCHEMA_VERSION {
        return Err(format!(
            "unsupported verified-pair snapshot header schema {version} (expected {SCHEMA_VERSION})"
        ));
    }
    let mut u64_bytes = [0; 8];
    file.read_exact(&mut u64_bytes)
        .map_err(|error| format!("read {} payload length: {error}", path.display()))?;
    let payload_len = u64::from_le_bytes(u64_bytes);
    let expected_file_len = (header_len as u64)
        .checked_add(payload_len)
        .and_then(|value| value.checked_add(8))
        .ok_or_else(|| "snapshot payload offset overflow".to_owned())?;
    if expected_file_len != file_len {
        return Err(format!(
            "snapshot payload length {payload_len} does not match file size {}",
            file_len
        ));
    }
    let mut remaining = payload_len;
    let mut actual = 0xcbf29ce484222325u64;
    let mut buffer = vec![0; 1024 * 1024];
    while remaining > 0 {
        let chunk_len = usize::try_from(remaining.min(buffer.len() as u64))
            .map_err(|_| "snapshot checksum chunk does not fit usize".to_owned())?;
        file.read_exact(&mut buffer[..chunk_len])
            .map_err(|error| format!("read {} payload: {error}", path.display()))?;
        for byte in &buffer[..chunk_len] {
            actual ^= u64::from(*byte);
            actual = actual.wrapping_mul(0x100000001b3);
        }
        remaining -= chunk_len as u64;
    }
    file.read_exact(&mut u64_bytes)
        .map_err(|error| format!("read {} checksum: {error}", path.display()))?;
    let expected = u64::from_le_bytes(u64_bytes);
    if expected != actual {
        return Err(format!(
            "verified-pair snapshot checksum mismatch: expected {expected:016x}, computed {actual:016x}"
        ));
    }
    file.seek(SeekFrom::Start(header_len as u64))
        .map_err(|error| format!("seek {} payload: {error}", path.display()))?;
    decode_payload(
        BufReader::new(file.take(payload_len)),
        payload_len,
        retain_audit_streams,
        mapper_match_limit,
    )
}

/// Read, checksum-validate, and losslessly decode a snapshot without reordering anything.
pub fn read(path: &Path) -> Result<Snapshot, String> {
    read_with_retention(path, true, None)
}

/// Read a snapshot for mapper replay while bounding transient memory per pair.
///
/// The complete file checksum and every raw-index-to-accepted-match relation
/// are validated as the payload streams past. Raw matcher vectors and their
/// inlier-index arrays are then released at each pair boundary; the returned
/// snapshot retains the exact mapper stream, two-view metadata, and envelope.
/// It is intentionally lossy and must not be re-exported as a full snapshot.
pub fn read_mapper_compact(path: &Path) -> Result<Snapshot, String> {
    read_with_retention(path, false, None)
}

/// Read a mapper snapshot while retaining at most `limit` accepted
/// correspondences per image pair and dropping the mapper-unused essential
/// match stream after validation.
///
/// The checksum, raw streams, and all raw-index relations are still consumed
/// and validated before truncation. Unlike truncating the decoded snapshot,
/// discarded pair payloads never accumulate across the image graph.
pub fn read_mapper_compact_capped(path: &Path, limit: usize) -> Result<Snapshot, String> {
    read_with_retention(path, false, Some(limit))
}

#[cfg(test)]
mod tests {
    use super::{
        merge, merge_files_atomic, read, read_mapper_compact, read_mapper_compact_capped, write,
        PairRecord, Snapshot, SCHEMA_VERSION,
    };
    use std::path::PathBuf;

    fn sample() -> Snapshot {
        Snapshot {
            schema_version: SCHEMA_VERSION,
            image_names: vec!["a.png".into(), "b.png".into()],
            image_manifest_hash: 11,
            feature_manifest_hash: 22,
            feature_counts: vec![3, 4],
            width: 1600,
            height: 1066,
            intrinsics_bits: [
                1.25f64.to_bits(),
                2.5f64.to_bits(),
                3.75f64.to_bits(),
                4.0f64.to_bits(),
            ],
            effective_config_hash: 33,
            effective_config: "effective".into(),
            verifier_config_hash: 44,
            verifier_config: "verifier".into(),
            pair_order_hash: 55,
            unordered_edge_hash: 66,
            accepted_match_count: 2,
            pairs: vec![PairRecord {
                image_i: 1,
                image_j: 0,
                raw_match_count: 3,
                raw_matches: vec![(0, 0), (1, 1), (2, 2)],
                accepted_inlier_indices: vec![2, 0],
                essential_inlier_indices: vec![2],
                matches: vec![(2, 2), (0, 0)],
                essential_matches: Some(vec![(2, 2)]),
                config: 3,
                calibrated: true,
                e_inlier_count: 1,
                f_inlier_count: 2,
                h_inlier_count: 0,
                essential_matrix_bits: Some(std::array::from_fn(|i| (i as f64 + 0.25).to_bits())),
                fundamental_matrix_bits: Some(std::array::from_fn(|i| (i as f64 - 0.5).to_bits())),
                homography_matrix_bits: None,
                relative_rotation_bits: Some([
                    1.0f64.to_bits(),
                    0.0f64.to_bits(),
                    0.0f64.to_bits(),
                    0.0f64.to_bits(),
                    1.0f64.to_bits(),
                    0.0f64.to_bits(),
                    0.0f64.to_bits(),
                    0.0f64.to_bits(),
                    1.0f64.to_bits(),
                ]),
                relative_translation_bits: Some([
                    0.1f64.to_bits(),
                    0.2f64.to_bits(),
                    0.3f64.to_bits(),
                ]),
            }],
        }
    }

    fn temp_path(tag: &str) -> PathBuf {
        std::env::temp_dir().join(format!(
            "visloc_verified_pair_snapshot_{tag}_{}",
            std::process::id()
        ))
    }

    #[test]
    fn readback_checks_counts_and_overlaps() {
        let root = temp_path("readback");
        std::fs::create_dir(&root).unwrap();
        let path = root.join("one.vps");
        let mut snapshot = sample();
        super::write_shared_atomic(&path, &snapshot).unwrap();
        let summary = super::validate_files(std::slice::from_ref(&path)).unwrap();
        assert_eq!(
            summary,
            super::ReadbackSummary {
                images: 2,
                shards: 1,
                pairs: 1,
                accepted_matches: 2,
                envelope_loads: 1
            }
        );
        assert!(super::validate_files(&[&path, &path])
            .unwrap_err()
            .contains("overlap"));
        snapshot.accepted_match_count += 1;
        super::write_shared_atomic(&path, &snapshot).unwrap();
        assert!(super::validate_files(std::slice::from_ref(&path))
            .unwrap_err()
            .contains("count mismatch"));
        assert!(super::validate_files::<PathBuf>(&[]).is_err());
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn merge_reader_borrows_one_decoded_envelope_and_rejects_mismatches() {
        let root = temp_path("borrowed_envelope");
        std::fs::create_dir(&root).unwrap();
        let snapshot = sample();
        let first_path = root.join("first.vps");
        super::write_shared_atomic(&first_path, &snapshot).unwrap();
        let mut cache = super::shared::EnvelopeCache::default();
        let first = super::read_for_merge(&first_path, &mut cache).unwrap();
        let second = super::read_for_merge(&first_path, &mut cache).unwrap();
        assert!(std::sync::Arc::ptr_eq(&first.envelope, &second.envelope));
        assert_eq!(cache.loads, 1);
        assert_eq!(first.into_owned(), snapshot);
        assert_eq!(second.into_owned(), snapshot);
        cache.finish().unwrap();

        let mut other = sample();
        other.feature_manifest_hash += 1;
        let second_path = root.join("second.vps");
        super::write_shared_atomic(&second_path, &other).unwrap();
        let output = root.join("merged.vps");
        std::fs::write(&output, b"prior-output").unwrap();
        assert!(merge_files_atomic(&output, &[first_path, second_path])
            .unwrap_err()
            .contains("manifest"));
        assert_eq!(std::fs::read(&output).unwrap(), b"prior-output");
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn prepared_shared_writer_preserves_chunks_and_rejects_wrong_directory() {
        let root = temp_path("prepared_shared");
        std::fs::create_dir(&root).unwrap();
        let snapshot = sample();
        let writer = super::SharedSnapshotWriter::new(&root, &snapshot).unwrap();
        for index in 0..3 {
            let path = root.join(format!("{index}.vps"));
            writer
                .write_chunk(
                    &path,
                    super::SharedPairChunk {
                        pair_order_hash: snapshot.pair_order_hash,
                        unordered_edge_hash: snapshot.unordered_edge_hash,
                        accepted_match_count: snapshot.accepted_match_count,
                        pairs: &snapshot.pairs,
                    },
                )
                .unwrap();
            assert_eq!(read(&path).unwrap(), snapshot);
        }
        assert!(writer
            .write_chunk(
                &root.join("elsewhere/0.vps"),
                super::SharedPairChunk {
                    pair_order_hash: 0,
                    unordered_edge_hash: 0,
                    accepted_match_count: 0,
                    pairs: &[],
                }
            )
            .is_err());
        writer.finish().unwrap();
        assert_eq!(std::fs::read_dir(&root).unwrap().count(), 4);
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn shared_envelope_cache_is_bounded_and_revalidates_changes() {
        let root = temp_path("shared_cache");
        std::fs::create_dir(&root).unwrap();
        let snapshot = sample();
        let path = root.join("first.vps");
        super::write_shared_atomic(&path, &snapshot).unwrap();
        let mut cache = super::shared::EnvelopeCache::default();
        for _ in 0..8 {
            assert_eq!(
                super::read_with_cache(&path, true, None, Some(&mut cache)).unwrap(),
                snapshot
            );
        }
        assert_eq!(cache.loads, 1);
        let mut other = snapshot.clone();
        other.image_manifest_hash += 1;
        let second = root.join("second.vps");
        super::write_shared_atomic(&second, &other).unwrap();
        assert_eq!(
            super::read_with_cache(&second, true, None, Some(&mut cache)).unwrap(),
            other
        );
        assert_eq!(cache.loads, 2);
        assert_eq!(
            super::read_with_cache(&path, true, None, Some(&mut cache)).unwrap(),
            snapshot
        );
        assert_eq!(cache.loads, 3); // Previous envelope was evicted, not accumulated.
        for entry in std::fs::read_dir(&root).unwrap() {
            let path = entry.unwrap().path();
            if path.extension().is_some_and(|extension| extension == "vpe") {
                std::fs::write(path, b"corrupt").unwrap();
            }
        }
        assert!(cache.finish().unwrap_err().contains("changed"));
        assert!(super::read_with_cache(&path, true, None, Some(&mut cache)).is_err());
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn shared_envelope_concurrent_publication_is_exact() {
        let root = temp_path("shared_concurrent");
        std::fs::create_dir(&root).unwrap();
        std::thread::scope(|scope| {
            for index in 0..8 {
                let path = root.join(format!("{index}.vps"));
                scope.spawn(move || super::write_shared_atomic(&path, &sample()).unwrap());
            }
        });
        assert_eq!(std::fs::read_dir(&root).unwrap().count(), 9);
        for index in 0..8 {
            assert_eq!(read(&root.join(format!("{index}.vps"))).unwrap(), sample());
        }
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn shared_chunks_round_trip_reuse_envelope_and_merge() {
        let root = temp_path("shared_roundtrip");
        std::fs::create_dir(&root).unwrap();
        let snapshot = sample();
        let first = root.join("first.vps");
        let second = root.join("second.vps");
        super::write_shared_atomic(&first, &snapshot).unwrap();
        super::write_shared_atomic(&second, &snapshot).unwrap();
        assert_eq!(read(&first).unwrap(), snapshot);
        assert_eq!(
            std::fs::read(&first).unwrap(),
            std::fs::read(&second).unwrap()
        );
        assert_eq!(std::fs::read_dir(&root).unwrap().count(), 3);
        let legacy = root.join("legacy.vps");
        write(&legacy, &snapshot).unwrap();
        assert_eq!(
            read_mapper_compact(&first).unwrap(),
            read_mapper_compact(&legacy).unwrap()
        );
        assert_eq!(
            read_mapper_compact_capped(&first, 1).unwrap(),
            read_mapper_compact_capped(&legacy, 1).unwrap()
        );
        let merged_shared = root.join("merged_shared.vps");
        let merged_legacy = root.join("merged_legacy.vps");
        merge_files_atomic(&merged_shared, std::slice::from_ref(&first)).unwrap();
        merge_files_atomic(&merged_legacy, &[legacy]).unwrap();
        assert_eq!(
            std::fs::read(merged_shared).unwrap(),
            std::fs::read(merged_legacy).unwrap()
        );
        // Retry publication produces exactly the same complete bytes.
        super::write_shared_atomic(&first, &snapshot).unwrap();
        assert_eq!(read(&first).unwrap(), snapshot);
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn shared_chunks_reject_corruption_and_missing_envelope() {
        let root = temp_path("shared_corruption");
        std::fs::create_dir(&root).unwrap();
        let path = root.join("chunk.vps");
        super::write_shared_atomic(&path, &sample()).unwrap();
        let envelope = std::fs::read_dir(&root)
            .unwrap()
            .map(|entry| entry.unwrap().path())
            .find(|path| path.extension().is_some_and(|extension| extension == "vpe"))
            .unwrap();
        let original = std::fs::read(&envelope).unwrap();
        std::fs::write(&envelope, b"corrupt").unwrap();
        assert!(read(&path).unwrap_err().contains("SHA-256"));
        assert!(super::write_shared_atomic(&path, &sample())
            .unwrap_err()
            .contains("mismatch"));
        std::fs::remove_file(&envelope).unwrap();
        assert!(read(&path).unwrap_err().contains("read shared envelope"));
        std::fs::write(&envelope, original).unwrap();
        let mut bytes = std::fs::read(&path).unwrap();
        let last = bytes.len() - 1;
        bytes[last] ^= 1;
        std::fs::write(&path, &bytes).unwrap();
        assert!(read(&path).unwrap_err().contains("checksum"));
        std::fs::write(&path, &bytes[..last]).unwrap();
        assert!(read(&path).unwrap_err().contains("length"));
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn round_trip_preserves_order_and_float_bits() {
        let path = temp_path("roundtrip");
        let snapshot = sample();
        write(&path, &snapshot).unwrap();
        assert_eq!(read(&path).unwrap(), snapshot);
        std::fs::remove_file(path).unwrap();
    }

    #[test]
    fn compact_mapper_read_validates_then_drops_audit_streams() {
        let path = temp_path("compact");
        let snapshot = sample();
        write(&path, &snapshot).unwrap();
        let compact = read_mapper_compact(&path).unwrap();
        assert_eq!(compact.image_names, snapshot.image_names);
        assert_eq!(compact.accepted_match_count, snapshot.accepted_match_count);
        assert_eq!(compact.pairs[0].matches, snapshot.pairs[0].matches);
        assert_eq!(
            compact.pairs[0].essential_matches,
            snapshot.pairs[0].essential_matches
        );
        assert_eq!(
            compact.pairs[0].essential_matrix_bits,
            snapshot.pairs[0].essential_matrix_bits
        );
        assert_eq!(
            compact.pairs[0].relative_rotation_bits,
            snapshot.pairs[0].relative_rotation_bits
        );
        assert_eq!(compact.pairs[0].raw_match_count, 0);
        assert!(compact.pairs[0].raw_matches.is_empty());
        assert!(compact.pairs[0].accepted_inlier_indices.is_empty());
        assert!(compact.pairs[0].essential_inlier_indices.is_empty());
        std::fs::remove_file(path).unwrap();
    }

    #[test]
    fn capped_mapper_read_validates_full_pair_then_retains_prefix() {
        let path = temp_path("compact_capped");
        let snapshot = sample();
        write(&path, &snapshot).unwrap();
        let compact = read_mapper_compact_capped(&path, 1).unwrap();
        assert_eq!(compact.accepted_match_count, 1);
        assert_eq!(compact.pairs[0].matches, &snapshot.pairs[0].matches[..1]);
        assert!(compact.pairs[0].essential_matches.is_none());
        assert_eq!(
            compact.pairs[0].relative_rotation_bits,
            snapshot.pairs[0].relative_rotation_bits
        );
        assert!(compact.pairs[0].raw_matches.is_empty());
        assert!(compact.pairs[0].accepted_inlier_indices.is_empty());
        std::fs::remove_file(path).unwrap();
    }

    #[test]
    fn compact_mapper_read_rejects_an_invalid_raw_index_relation() {
        let path = temp_path("compact-invalid-index");
        let mut snapshot = sample();
        snapshot.pairs[0].accepted_inlier_indices[0] = 99;
        write(&path, &snapshot).unwrap();

        let error = read_mapper_compact(&path).unwrap_err();
        assert!(error.contains("accepted match"));
        let capped_error = read_mapper_compact_capped(&path, 0).unwrap_err();
        assert!(capped_error.contains("accepted match"));
        std::fs::remove_file(path).unwrap();
    }

    #[test]
    fn grouped_unordered_edge_hash_matches_flat_reference() {
        let base = sample().pairs.remove(0);
        let mut pairs = Vec::new();
        for (image_i, image_j, matches) in [
            (3, 1, vec![(9, 2), (4, 7), (4, 1)]),
            (0, 2, vec![(8, 8), (1, 5)]),
            (1, 3, vec![(6, 6), (0, 3)]),
        ] {
            let mut pair = base.clone();
            pair.image_i = image_i;
            pair.image_j = image_j;
            pair.matches = matches;
            pairs.push(pair);
        }
        let mut edges = Vec::new();
        for pair in &pairs {
            let (image_i, image_j, swapped) = if pair.image_i <= pair.image_j {
                (pair.image_i, pair.image_j, false)
            } else {
                (pair.image_j, pair.image_i, true)
            };
            for &(left, right) in &pair.matches {
                let (left, right) = if swapped {
                    (right, left)
                } else {
                    (left, right)
                };
                edges.push((image_i, image_j, left, right));
            }
        }
        edges.sort_unstable();
        let reference = edges.into_iter().fold(
            0xcbf29ce484222325u64,
            |mut hash, (image_i, image_j, left, right)| {
                for value in [image_i, image_j, left, right] {
                    hash = super::hash_u64(hash, value);
                }
                hash
            },
        );
        assert_eq!(super::unordered_edge_hash(&pairs), reference);
    }

    #[test]
    fn checksum_and_version_rejection_are_explicit() {
        let path = temp_path("reject");
        write(&path, &sample()).unwrap();
        let mut bytes = std::fs::read(&path).unwrap();
        let last = bytes.len() - 1;
        bytes[last] ^= 1;
        std::fs::write(&path, &bytes).unwrap();
        assert!(read(&path).unwrap_err().contains("checksum"));

        write(&path, &sample()).unwrap();
        let mut bytes = std::fs::read(&path).unwrap();
        // The header version starts immediately after MAGIC.
        let version_offset = b"VISLOC-VERIFIED-PAIR-SNAPSHOT\0".len();
        bytes[version_offset] = 2;
        std::fs::write(&path, &bytes).unwrap();
        assert!(read(&path).unwrap_err().contains("schema"));
        std::fs::remove_file(path).unwrap();
    }

    #[test]
    fn merge_preserves_shard_order_recomputes_integrity_and_rejects_overlap() {
        let mut first = sample();
        first.pairs[0].image_i = 0;
        first.pairs[0].image_j = 1;
        first.pair_order_hash = super::ordered_pair_hash(&first.pairs);
        first.unordered_edge_hash = super::unordered_edge_hash(&first.pairs);

        let mut second = first.clone();
        second.pairs[0].image_i = 0;
        second.pairs[0].image_j = 0;
        // Use a distinct valid pair with a third image in a small synthetic
        // envelope.  The source sample has only two names, so extend the
        // image manifest consistently for this merge-only test.
        first.image_names.push("c.png".into());
        first.feature_counts.push(5);
        second.image_names = first.image_names.clone();
        second.feature_counts = first.feature_counts.clone();
        second.pairs[0].image_i = 1;
        second.pairs[0].image_j = 2;
        second.pair_order_hash = super::ordered_pair_hash(&second.pairs);
        second.unordered_edge_hash = super::unordered_edge_hash(&second.pairs);

        let merged = merge(&[first.clone(), second.clone()]).unwrap();
        assert_eq!(merged.pairs.len(), 2);
        assert_eq!((merged.pairs[0].image_i, merged.pairs[0].image_j), (0, 1));
        assert_eq!((merged.pairs[1].image_i, merged.pairs[1].image_j), (1, 2));
        assert_eq!(merged.accepted_match_count, 4);
        assert_eq!(
            merged.effective_config,
            format!("verified-pair-export-v1;{}", first.verifier_config)
        );
        assert_eq!(
            merged.effective_config_hash,
            super::fnv1a64(merged.effective_config.as_bytes())
        );
        assert_eq!(
            merged.pair_order_hash,
            super::ordered_pair_hash(&merged.pairs)
        );
        assert_eq!(
            merged.unordered_edge_hash,
            super::unordered_edge_hash(&merged.pairs)
        );

        let overlap = merge(&[first, second.clone(), second]).unwrap_err();
        assert!(overlap.contains("overlap"));
    }

    #[test]
    fn merge_accepts_empty_shards() {
        let populated = sample();
        let mut empty = populated.clone();
        empty.pairs.clear();
        empty.accepted_match_count = 0;
        empty.pair_order_hash = super::ordered_pair_hash(&empty.pairs);
        empty.unordered_edge_hash = super::unordered_edge_hash(&empty.pairs);

        let merged = merge(&[empty.clone(), populated.clone(), empty]).unwrap();
        assert_eq!(merged.pairs, populated.pairs);
        assert_eq!(merged.accepted_match_count, populated.accepted_match_count);
        assert_eq!(
            merged.pair_order_hash,
            super::ordered_pair_hash(&populated.pairs)
        );
        assert_eq!(
            merged.unordered_edge_hash,
            super::unordered_edge_hash(&populated.pairs)
        );
    }

    #[test]
    fn merge_rejects_configuration_mismatch() {
        let first = sample();
        let mut second = first.clone();
        second.verifier_config = "different".into();
        let error = merge(&[first, second]).unwrap_err();
        assert!(error.contains("configuration"));
    }

    #[test]
    fn streamed_file_merge_is_byte_identical_to_owned_merge() {
        let first_path = temp_path("file-merge-first");
        let second_path = temp_path("file-merge-second");
        let expected_path = temp_path("file-merge-expected");
        let output_path = temp_path("file-merge-output");

        let mut first = sample();
        first.image_names.push("c.png".into());
        first.feature_counts.push(5);
        first.pairs[0].image_i = 2;
        first.pairs[0].image_j = 0;
        let mut second = first.clone();
        second.pairs[0].image_i = 1;
        second.pairs[0].image_j = 2;

        write(&first_path, &first).unwrap();
        write(&second_path, &second).unwrap();
        let expected = merge(&[first.clone(), second.clone()]).unwrap();
        write(&expected_path, &expected).unwrap();

        merge_files_atomic(&output_path, &[first_path.clone(), second_path.clone()]).unwrap();
        assert_eq!(
            std::fs::read(&output_path).unwrap(),
            std::fs::read(&expected_path).unwrap()
        );
        assert_eq!(read(&output_path).unwrap(), expected);

        for path in [first_path, second_path, expected_path, output_path] {
            std::fs::remove_file(path).unwrap();
        }
    }

    #[test]
    fn streamed_file_merge_rejects_overlap_without_replacing_output() {
        let first_path = temp_path("file-merge-overlap-first");
        let second_path = temp_path("file-merge-overlap-second");
        let output_path = temp_path("file-merge-overlap-output");
        let first = sample();
        let second = first.clone();
        write(&first_path, &first).unwrap();
        write(&second_path, &second).unwrap();
        std::fs::write(&output_path, b"previous-output").unwrap();

        let error = merge_files_atomic(&output_path, &[first_path.clone(), second_path.clone()])
            .unwrap_err();
        assert!(error.contains("overlap"));
        assert_eq!(std::fs::read(&output_path).unwrap(), b"previous-output");

        for path in [first_path, second_path, output_path] {
            std::fs::remove_file(path).unwrap();
        }
    }

    #[test]
    fn streamed_file_merge_rejects_checksum_without_replacing_output() {
        let first_path = temp_path("file-merge-checksum-first");
        let second_path = temp_path("file-merge-checksum-second");
        let output_path = temp_path("file-merge-checksum-output");
        write(&first_path, &sample()).unwrap();
        write(&second_path, &sample()).unwrap();
        let mut corrupted = std::fs::read(&second_path).unwrap();
        let last = corrupted.len() - 1;
        corrupted[last] ^= 1;
        std::fs::write(&second_path, corrupted).unwrap();
        std::fs::write(&output_path, b"previous-output").unwrap();

        let error = merge_files_atomic(&output_path, &[first_path.clone(), second_path.clone()])
            .unwrap_err();
        assert!(error.contains("checksum"));
        assert_eq!(std::fs::read(&output_path).unwrap(), b"previous-output");

        for path in [first_path, second_path, output_path] {
            std::fs::remove_file(path).unwrap();
        }
    }

    #[test]
    fn streamed_file_merge_rejects_raw_index_without_replacing_output() {
        let first_path = temp_path("file-merge-raw-index-first");
        let second_path = temp_path("file-merge-raw-index-second");
        let output_path = temp_path("file-merge-raw-index-output");
        write(&first_path, &sample()).unwrap();
        let mut invalid = sample();
        invalid.pairs[0].accepted_inlier_indices[0] = 99;
        write(&second_path, &invalid).unwrap();
        std::fs::write(&output_path, b"previous-output").unwrap();

        let error = merge_files_atomic(&output_path, &[first_path.clone(), second_path.clone()])
            .unwrap_err();
        assert!(error.contains("accepted match"));
        assert_eq!(std::fs::read(&output_path).unwrap(), b"previous-output");

        for path in [first_path, second_path, output_path] {
            std::fs::remove_file(path).unwrap();
        }
    }
}